Initial commit v0.1.0 early alpha
AniCraft 0.1.0 (early alpha): milestones M0 and M1. Contributors are credited in AUTHORS.md.
No files matched your search
@@ -0,0 +1,9 @@
|
||||
# Normalise line endings in the repository; check out with the platform's native endings.
|
||||
* text=auto
|
||||
*.rs text diff=rust
|
||||
*.toml text
|
||||
*.md text
|
||||
*.json text
|
||||
*.png binary
|
||||
# shell hooks must keep LF endings or /bin/sh rejects them
|
||||
scripts/git-hooks/* text eol=lf
|
||||
@@ -0,0 +1,14 @@
|
||||
# build output
|
||||
/target/
|
||||
|
||||
# generated screenshots and exports (regenerate with --screenshot / anicraft-cli)
|
||||
/shots/
|
||||
/frames/
|
||||
*.anicraft.tmp
|
||||
|
||||
# editors and OS
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,111 @@
|
||||
# AGENTS.md: guide for AI agents and contributors
|
||||
|
||||
AniCraft is an open-source, native, clean-room 2D animation studio (Adobe Animate class), written
|
||||
in **Rust only**. There is no Tauri, Electron or webview. The UI is egui/eframe. The product name
|
||||
is written **AniCraft**; machine names are lowercase (`anicraft-*`). Read `docs/` first.
|
||||
|
||||
## Workspace map
|
||||
|
||||
```text
|
||||
crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing
|
||||
crates/doc L1 Document model, easing, timeline evaluation, sample scene
|
||||
crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, PNG)
|
||||
crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009)
|
||||
crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format
|
||||
crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve
|
||||
src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
|
||||
```
|
||||
|
||||
A crate depends only on lower layers. Nothing below `src/` may use egui, eframe or winit.
|
||||
|
||||
## Standing rules (read `docs/product-principles.md`)
|
||||
|
||||
* **Principal-engineer check.** For every proposal ask: "Is this how a principal engineer
|
||||
would do it?" If not, use the better method or ask the project lead. Record hard-to-reverse
|
||||
decisions as ADRs in `docs/adr/`.
|
||||
* **Users are artists and creatives** (many coming from Adobe Animate). The product must be
|
||||
professional, fast, reliable and easy, with smooth, predictable flow: common actions one
|
||||
click or key away, shortcuts for power users, no modal interruptions for routine edits.
|
||||
* **UI guidelines** (`docs/ui-guidelines.md`, ADR 0005): text goes through `theme::Type`
|
||||
roles. Data (numbers, timecode, rulers, values, shortcuts, paths) is monospace; prose
|
||||
(labels, menus, buttons, names, dialog text) is proportional. No raw font sizes or colours
|
||||
outside `theme.rs` (enforced by `guidelines_tests`). Typefaces: Inter + JetBrains Mono via
|
||||
`CRAFT_FONTS_DIR`, with egui defaults as fallback.
|
||||
* **Cross-platform** (ADR 0006): macOS, Windows and Linux are first-class. OS-specific
|
||||
behaviour lives only in `src/platform.rs` (shortcut labels with ⌘ on macOS, app menu,
|
||||
window chrome, settings folder, native dialogs, GPU backend fallback). Shortcut text always
|
||||
goes through `platform::shortcut_label`.
|
||||
* **Edits are live**: anything that changes the document must show in the same frame (Auto
|
||||
render mode). Never leave an edit waiting for the next input event.
|
||||
* **Destructive actions** follow the tiers in ADR 0004: irreversible loss always confirms
|
||||
(engine-enforced `"confirm": true`); large undoable deletions confirm by default; routine
|
||||
edits rely on undo with a visible hint.
|
||||
|
||||
## Golden rules
|
||||
|
||||
1. **Never crash.** Non-test code never panics: no `unwrap`/`expect`/`panic!`/indexing on
|
||||
input-derived values. Crates carry `#![deny(clippy::unwrap_used, …)]`. Commands validate params
|
||||
and return `Err`. The `panic_hunt_every_command` test fuzzes every command and must stay green.
|
||||
2. **Everything is a command.** New behaviour means a `CommandSpec` in `crates/engine/src/cmds_*.rs`
|
||||
with id, label, menu path, shortcut, params doc and tests. Menus and shortcuts are generated
|
||||
from the registry. Only view state (zoom, pan, tool, onion skin, playback) lives in the shell.
|
||||
3. **Time is a function.** Never animate by mutating the document. Add behaviour to
|
||||
`doc::evaluate` and keep it pure.
|
||||
4. **The CPU renderer is the oracle.** Renderer changes come with analytic or golden tests. Any
|
||||
future GPU renderer is tested against it.
|
||||
5. **No unsafe** (`unsafe_code = "forbid"`).
|
||||
6. **Clean room.** Learn behaviour from public docs and observation only. Never copy proprietary
|
||||
code, presets, shaders or assets.
|
||||
7. **Verify UI changes visually**: `cargo run -- --screenshot shots/now.png`, then look at the PNG.
|
||||
|
||||
## Licensing and legal compliance (read `docs/legal/compliance.md`)
|
||||
|
||||
* AniCraft is **MIT OR Apache-2.0**, like PhotoCraft (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`).
|
||||
* **Dependencies**: permissive only, from crates.io only. `deny.toml` is the policy, and
|
||||
`cargo deny check licenses bans sources` must pass. Adding a crate with a new licence needs
|
||||
a deliberate `deny.toml` change and a note in `compliance.md`. No copyleft, "non-commercial"
|
||||
or source-available terms.
|
||||
* **Assets**: every font, icon, image, sound or sample file gets a row in `ATTRIBUTION.md`
|
||||
in the same change, with its licence text under `licenses/`. Never commit font files
|
||||
(use the shared craft-fonts input). Never commit Adobe or other proprietary material.
|
||||
* **Patents**: implement only from public papers, open specifications and permissively
|
||||
licensed references; credit them in `ATTRIBUTION.md`. Never bundle encoders for
|
||||
patent-pool codecs (H.264/HEVC/AAC); use royalty-free formats or a user-installed ffmpeg.
|
||||
* **Trademarks**: Adobe, Animate and Flash only nominatively (docs, and the non-affiliation
|
||||
disclaimer in legal notices), never in the product name, branding, feature UI or marketing.
|
||||
|
||||
## Version control
|
||||
|
||||
* Git. Remote `origin` = `https://github.com/storytold/AniCraft` (public). `main` is the
|
||||
development branch; it begins with "Initial commit v0.1.0 early alpha", and contributors are
|
||||
credited in `AUTHORS.md`.
|
||||
* **Every change reaches `main` through a pull request** from a topic branch (`feat/…`, `fix/…`,
|
||||
`docs/…`), with one roadmap step per PR, green on build, tests, clippy and `cargo deny`.
|
||||
Never commit or push to `main` directly. `core.hooksPath` points at `scripts/git-hooks`:
|
||||
`pre-commit` refuses commits on `main`, and `pre-push` refuses pushes to the remote `main`.
|
||||
Run `git config core.hooksPath scripts/git-hooks` once per clone.
|
||||
* Branches marked hidden in your local git config (`git config --add anicraft.hidden <branch>`)
|
||||
never leave the machine: `pre-push` refuses them and anything built on them.
|
||||
* Commit in small, green steps (build + tests pass), with conventional messages:
|
||||
`feat(render): …`, `fix(engine): …`, `docs: …`, `perf: …`, `test: …`. Record measured
|
||||
numbers in `perf:` commit bodies.
|
||||
* Never commit `target/`, screenshots (`shots/`), exports or `.anicraft` user files.
|
||||
|
||||
## Build hygiene (disk first, then time; `docs/development.md` › Build footprint)
|
||||
|
||||
* Use the **single shared `target/`**. No per-agent `CARGO_TARGET_DIR` copies (each is a
|
||||
full build).
|
||||
* Don't turn incremental compilation or full debug info back on in `Cargo.toml`. Do that
|
||||
locally if you need a debugger.
|
||||
* After profile or feature changes, run `cargo clean` once (with the app closed).
|
||||
|
||||
## Before you finish
|
||||
|
||||
```sh
|
||||
cargo test
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
cargo deny check licenses bans sources
|
||||
cargo run -- --screenshot shots/now.png
|
||||
```
|
||||
|
||||
Update `docs/roadmap.md` › Honest status when you move a capability.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Attribution
|
||||
|
||||
Every non-code asset AniCraft ships or embeds, and every published work our code follows
|
||||
closely, with author, source and licence. AniCraft's own code and original assets are
|
||||
MIT OR Apache-2.0 (see [`LICENSE-MIT`](LICENSE-MIT), [`LICENSE-APACHE`](LICENSE-APACHE) and
|
||||
[`NOTICE`](NOTICE)).
|
||||
|
||||
**Rule:** when you add an asset (font, icon, image, sound, sample file, data table) or base code
|
||||
on a specific published implementation, add a row here *in the same change*. Third-party assets
|
||||
must be permissively licensed and keep their licence file under [`licenses/`](licenses/).
|
||||
Never commit proprietary material (Adobe or other vendors' icons, presets, sample files, fonts,
|
||||
shaders or SDK code).
|
||||
|
||||
## Bundled in the app
|
||||
|
||||
| Item | Use | Author | Source | Licence |
|
||||
|---|---|---|---|---|
|
||||
| Ubuntu Light (via `epaint_default_fonts`) | UI proportional font | Canonical Ltd. / Dalton Maag | <https://design.ubuntu.com/font> | Ubuntu Font Licence 1.0, [`licenses/fonts/UFL-1.0-Ubuntu-font.txt`](licenses/fonts/UFL-1.0-Ubuntu-font.txt) |
|
||||
| Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | <https://github.com/source-foundry/Hack> | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) |
|
||||
| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | <https://github.com/googlefonts/noto-emoji> | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) |
|
||||
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
|
||||
| `assets/icons/anicraft-*.svg` (10 files: align, distribute, mask and masked layer) | Align panel and layer-type icons | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style | MIT OR Apache-2.0 |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (25 files: tools, transport, layer toggles, section chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
| Library symbol-kind marks, selection handles, timeline marks | UI | AniCraft contributors | Original work, drawn in code (`src/panels.rs`, `src/timeline.rs`, `src/stage.rs`) | MIT OR Apache-2.0 |
|
||||
| Sample animation (ball, star, sun, hills, sky) | First launch, tests, CLI `--sample` | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`) | MIT OR Apache-2.0 |
|
||||
| Colour theme | UI | AniCraft contributors | Original work (`src/theme.rs`) | MIT OR Apache-2.0 |
|
||||
|
||||
### Optional build input: craft-fonts (not files in this repo)
|
||||
|
||||
Builds made with `CRAFT_FONTS_DIR` (all official releases; ADR 0005) embed these from the shared
|
||||
[storytold/craft-fonts](https://github.com/storytold/craft-fonts). No font file is committed
|
||||
here.
|
||||
|
||||
| Font (embedded at build time) | Use | Author | Licence |
|
||||
|---|---|---|---|
|
||||
| Inter Regular | UI prose (primary) | The Inter Project Authors (Rasmus Andersson) | SIL OFL 1.1, shipped as `OFL-Inter.txt` |
|
||||
| JetBrains Mono Regular | UI data: timeline, readouts, values, shortcuts (primary) | The JetBrains Mono Project Authors | SIL OFL 1.1, shipped as `OFL-JetBrainsMono.txt` |
|
||||
|
||||
No image, icon, sound or font *files* are committed. Everything above is either embedded by a
|
||||
dependency crate or generated by our code.
|
||||
|
||||
## Algorithms and published techniques
|
||||
|
||||
Our implementations are written from the public descriptions below. No third-party code was
|
||||
copied. Code ported from the sibling project PhotoCraft (same project family and licence, MIT
|
||||
OR Apache-2.0) is noted in the table.
|
||||
|
||||
| Technique | Where | Reference | Notes |
|
||||
|---|---|---|---|
|
||||
| Signed-area coverage accumulation rasterizer | `crates/render/src/raster.rs` | Raph Levien, *font-rs* (2016), <https://github.com/raphlinus/font-rs>, Apache-2.0; also stb_truetype v2 (public domain) | Our implementation follows the published accumulate-and-prefix-sum approach. Credited here; Apache-2.0 includes a patent licence. |
|
||||
| Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | |
|
||||
| Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. |
|
||||
| Cubic-Bézier easing (CSS model) | `crates/doc/src/easing.rs` | W3C CSS Easing Functions Level 1 | W3C Royalty-Free Patent Policy. |
|
||||
| SVG path data syntax (file format v2) | `crates/geom/src/path.rs` | W3C SVG 1.1 / 2 | W3C Royalty-Free Patent Policy. |
|
||||
| Marching-squares contour tracing (Paint Bucket regions) | `crates/geom/src/trace.rs` | Lorensen & Cline (1987); public algorithm | Ported from PhotoCraft's mask tracer (same project family and licence) and reviewed. |
|
||||
| Chamfer distance transform (3-4) and flood fill | `crates/engine/src/cmds_paint.rs` | G. Borgefors, *Distance transformations in digital images* (1986); public algorithms | Gap closing, and growing fills under their outlines. |
|
||||
| ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs` | PKWARE APPNOTE.TXT (published ZIP specification); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries; no ZIP64 or encryption. |
|
||||
| XFL document structure and shape edges | `crates/xfl/src/` | The publicly documented XFL package structure (`DOMDocument.xml`, `LIBRARY/*.xml`, edge strings) | Clean room: no Animate or third-party converter code (ADR 0009). |
|
||||
| Full SVG path data and elliptical-arc to Bézier conversion | `crates/geom/src/svg.rs` | W3C SVG 1.1 §8.3 and Appendix F.6 (implementation notes) | W3C Royalty-Free Patent Policy. |
|
||||
| Affine QR decomposition for tweening | `crates/geom/src/affine.rs` | Standard linear algebra | |
|
||||
| Least-squares cubic Bézier curve fitting (Pencil "Smooth") | `crates/geom/src/fit.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. |
|
||||
| De Casteljau subdivision, Ramer–Douglas–Peucker simplification | `crates/geom/src/edit.rs` | Public mathematical results (de Casteljau 1959; Ramer 1972; Douglas & Peucker 1973) | |
|
||||
|
||||
## Rust dependencies
|
||||
|
||||
About 420 crates across all target platforms, all permissively licensed. Policy, audit command,
|
||||
results and elected licences are in [`docs/legal/compliance.md`](docs/legal/compliance.md). The
|
||||
generated inventory is [`docs/legal/third-party-inventory.txt`](docs/legal/third-party-inventory.txt).
|
||||
@@ -0,0 +1,6 @@
|
||||
# Authors
|
||||
|
||||
People who have contributed to AniCraft. The repository starts from one initial commit
|
||||
(`docs/release.md`), so the work before it is credited here.
|
||||
|
||||
* Tanish Manku: project lead, product direction and design.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.0 (2026-11-05): early alpha
|
||||
|
||||
The first version: milestones M0 (foundations) and M1 (authoring core) are complete. The
|
||||
repository starts here with one commit; earlier work is credited in `AUTHORS.md`.
|
||||
|
||||
* **Drawing**: Selection, Subselection, Free Transform, Pen, Pencil (smooth, straighten, ink),
|
||||
Rectangle, Oval, PolyStar, Line, Paint Bucket (with gap closing), Ink Bottle, Hand and Zoom.
|
||||
Also cut, copy and paste (in centre, in place), duplicate, arrange, rotate and flip, align
|
||||
and distribute, convert to symbol and break apart.
|
||||
* **Timeline**: layers (show, lock, outline), keyframes, blank keyframes, frame spans, classic
|
||||
tweens with easing presets, labels, onion skin, looping playback. Frames can be selected
|
||||
across layers; cut, copy and paste frames; drag keyframes and span ends. Timeline zoom and
|
||||
scrolling.
|
||||
* **Mask layers**: a mask reveals only its fill area of the layers under it, on the stage and in
|
||||
every export.
|
||||
* **Files**: `.anicraft` documents, PNG frames and sequences, animated GIF. Opens Animate
|
||||
documents (`.fla`, `.xfl`), with a report of anything not yet supported.
|
||||
* **Ease of use**: an editable keyboard shortcut map (F1), with the familiar animation
|
||||
defaults. Also the command palette (Ctrl+K), right-click menus everywhere, confirmations only
|
||||
before real loss, an unsaved-changes guard, Preferences, and macOS, Windows and Linux
|
||||
conventions.
|
||||
* **Engine**: every action is a command, scriptable headless through `anicraft-cli`. Undo is
|
||||
cheap even on large files. The stage renders in tiles in the background, on a deterministic
|
||||
CPU renderer.
|
||||
|
||||
Not in this version: scenes, layer folders, motion and shape tweens, text, bitmaps, sound,
|
||||
SVG/Lottie/video export, plug-ins and installers (milestones M2 to M8 in `docs/roadmap.md`).
|
||||
@@ -0,0 +1,100 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = [".", "crates/*"]
|
||||
default-members = [".", "crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
# 0.1.0 is the early alpha (release stage in src/app.rs, RELEASE_STAGE); see CHANGELOG.md
|
||||
# and docs/release.md.
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
# An application, not a library: not published to crates.io.
|
||||
publish = false
|
||||
repository = "https://github.com/storytold/AniCraft"
|
||||
rust-version = "1.90"
|
||||
|
||||
[workspace.dependencies]
|
||||
anicraft-geom = { path = "crates/geom" }
|
||||
anicraft-doc = { path = "crates/doc" }
|
||||
anicraft-render = { path = "crates/render" }
|
||||
anicraft-engine = { path = "crates/engine" }
|
||||
anicraft-xfl = { path = "crates/xfl" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
rayon = "1"
|
||||
png = "0.17"
|
||||
gif = "0.14"
|
||||
# wgpu is the primary renderer; glow (OpenGL) is the fallback for GPUs/VMs where wgpu fails.
|
||||
# Default features off: we skip `links` (opening web links pulls in url/idna/ICU Unicode
|
||||
# tables we don't use) and the web-only screen-reader shim. Same set as PhotoCraft, plus glow.
|
||||
eframe = { version = "0.36", default-features = false, features = ["accesskit", "default_fonts", "wgpu", "glow", "wayland", "x11"] }
|
||||
# Native file dialogs: Windows common dialogs, macOS NSOpenPanel, Linux XDG desktop portal.
|
||||
rfd = "0.17"
|
||||
# Lists and loads the OS's installed fonts for Preferences › Appearance (MIT).
|
||||
# Without the `fontconfig` feature, Linux scans the standard font folders directly
|
||||
# (/usr/share/fonts, /usr/local/share/fonts, ~/.local/share/fonts, ~/.fonts).
|
||||
fontdb = { version = "0.23", default-features = false, features = ["std", "fs", "memmap"] }
|
||||
egui = "0.36"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
dbg_macro = "warn"
|
||||
todo = "warn"
|
||||
|
||||
[package]
|
||||
name = "anicraft"
|
||||
description = "AniCraft desktop app: egui shell over the AniCraft engine"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
default-run = "anicraft"
|
||||
|
||||
[[bin]]
|
||||
name = "anicraft"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anicraft-geom.workspace = true
|
||||
anicraft-doc.workspace = true
|
||||
anicraft-render.workspace = true
|
||||
anicraft-engine.workspace = true
|
||||
eframe.workspace = true
|
||||
egui.workspace = true
|
||||
rfd.workspace = true
|
||||
serde.workspace = true
|
||||
fontdb.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
# ----- build profiles: biased for disk space, then time (docs/development.md › Build footprint) --
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
# File:line in backtraces and panics, without full variable debug info (a fraction of the size;
|
||||
# also keeps Windows PDBs under the LNK1140 limit).
|
||||
debug = "line-tables-only"
|
||||
# The incremental cache was ~3 GB for our crates; they rebuild from scratch in seconds.
|
||||
incremental = false
|
||||
|
||||
[profile.dev.package."*"]
|
||||
# Dependencies: optimized once (fast app in debug builds), no debug info at all.
|
||||
opt-level = 2
|
||||
debug = false
|
||||
|
||||
[profile.dev.build-override]
|
||||
# Build scripts and proc-macros: compile fast, no debug info.
|
||||
opt-level = 0
|
||||
debug = false
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
strip = "debuginfo"
|
||||
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ArtCraft Team and the AniCraft contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,33 @@
|
||||
AniCraft
|
||||
Copyright (c) 2026 ArtCraft Team and the AniCraft contributors.
|
||||
Licensed under the MIT License or the Apache License, Version 2.0, at your option
|
||||
(LICENSE-MIT, LICENSE-APACHE). Contributions are accepted under the same terms; the Apache
|
||||
License 2.0 includes an express patent licence from contributors (section 3).
|
||||
|
||||
Trademarks
|
||||
|
||||
Adobe, Adobe Animate and Flash are trademarks of Adobe Inc. AniCraft is an independent,
|
||||
clean-room project. It is not affiliated with, endorsed by or derived from Adobe. Those names
|
||||
appear only in documentation, to describe compatibility. The ArtCraft name and marks belong to
|
||||
the ArtCraft Team and are not covered by the licences above.
|
||||
|
||||
Third-party material
|
||||
|
||||
This product bundles third-party material under its own licences. The per-item list (author,
|
||||
source, licence) is in ATTRIBUTION.md, the dependency policy and audit are in
|
||||
docs/legal/compliance.md, and the licence texts that must ship with the fonts are in licenses/.
|
||||
|
||||
UI fonts, embedded through the egui crate `epaint_default_fonts`:
|
||||
Ubuntu Light: Ubuntu Font Licence 1.0. See licenses/fonts/UFL-1.0-Ubuntu-font.txt.
|
||||
Hack Regular: MIT, with Bitstream Vera licence portions. See licenses/fonts/LICENSE-Hack.txt.
|
||||
Noto Emoji: SIL Open Font License 1.1. See licenses/fonts/OFL-1.1-NotoEmoji.txt.
|
||||
emoji-icon-font: MIT. See licenses/fonts/LICENSE-emoji-icon-font.txt.
|
||||
|
||||
Official builds also embed, from the shared craft-fonts build input (CRAFT_FONTS_DIR):
|
||||
Inter Regular and JetBrains Mono Regular: SIL Open Font License 1.1. Their licence texts ship
|
||||
with the package as OFL-Inter.txt and OFL-JetBrainsMono.txt.
|
||||
|
||||
Rust crates (about 420 across all platforms) are permissively licensed (MIT, Apache-2.0, BSD,
|
||||
ISC, Zlib, BSL-1.0, Unicode-3.0, Unlicense, 0BSD). Where a crate offers a copyleft alternative,
|
||||
AniCraft uses it under its permissive licence. Binary releases ship the full licence texts of
|
||||
all crates (see docs/legal/compliance.md, "Release checklist").
|
||||
@@ -0,0 +1,56 @@
|
||||
# AniCraft
|
||||
|
||||
An open-source, native 2D vector animation studio in the class of Adobe Animate, written in
|
||||
Rust. It's a clean-room implementation, part of the `{Function}Craft` family (PhotoCraft,
|
||||
LightCraft, WordCraft, …).
|
||||
|
||||
* **Solid architecture**: layered crates (geom → doc → render → engine → cli → shell). The
|
||||
document is plain data, and the picture at a frame is a pure function `evaluate(doc, frame)`.
|
||||
* **Own renderer**: a deterministic CPU oracle with analytic anti-aliasing (signed-area coverage
|
||||
accumulation), non-zero/even-odd fills, gradients, round-join strokes and rayon row parallelism.
|
||||
* **Headless first**: every action is an engine command. The UI, the CLI and the JSON-lines
|
||||
agent channel all dispatch the same ids.
|
||||
* **egui shell**: stage, tools, timeline (layers, keyframes, classic tweens with easing, onion
|
||||
skin), properties and library.
|
||||
|
||||
## Build and run
|
||||
|
||||
```sh
|
||||
cargo build # whole workspace
|
||||
cargo run # desktop app with the sample animation
|
||||
cargo run -- --screenshot shots/now.png # draw ~120 frames, save the window, exit
|
||||
cargo test # all crates
|
||||
```
|
||||
|
||||
## Headless / agents
|
||||
|
||||
```sh
|
||||
cargo run -p anicraft-cli -- info --sample
|
||||
cargo run -p anicraft-cli -- render --sample --frame 12 --out frame12.png
|
||||
cargo run -p anicraft-cli -- render-seq --sample --out-dir frames --scale 0.5
|
||||
cargo run -p anicraft-cli -- commands # the registry as JSON
|
||||
cargo run -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft
|
||||
cargo run -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout
|
||||
```
|
||||
|
||||
The `serve` protocol takes one request per line,
|
||||
`{"id":1,"cmd":"timeline.insert_keyframe","params":{"frame":10}}`, and answers
|
||||
`{"id":1,"ok":true,"result":{…},"revision":7,"frame":0}`. Send `{"cmd":"quit"}` to stop.
|
||||
|
||||
## Documents
|
||||
|
||||
* [`docs/requirements.md`](docs/requirements.md): scope, functional and non-functional requirements, technology choices
|
||||
* [`docs/architecture.md`](docs/architecture.md): philosophy, crate map, document model, renderer, engine, testing
|
||||
* [`docs/roadmap.md`](docs/roadmap.md): honest status and milestones M0–M8
|
||||
* [`AGENTS.md`](AGENTS.md): rules for contributors and AI agents
|
||||
|
||||
## License
|
||||
|
||||
Licensed under either of [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE) at your option,
|
||||
like the sibling app PhotoCraft. Third-party notices are in [`NOTICE`](NOTICE) and
|
||||
[`ATTRIBUTION.md`](ATTRIBUTION.md). The dependency and asset compliance policy and audit
|
||||
(`cargo deny`) are in [`docs/legal/compliance.md`](docs/legal/compliance.md). The sample
|
||||
animation and all UI icons are original and generated in code.
|
||||
|
||||
AniCraft is an independent clean-room project. It is not affiliated with or endorsed by Adobe.
|
||||
Adobe, Animate and Flash are trademarks of Adobe Inc.
|
||||
@@ -0,0 +1,43 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
The following Lucide icons are derived from the Feather project:
|
||||
|
||||
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
||||
|
||||
The MIT License (MIT) (for the icons listed above)
|
||||
|
||||
Copyright (c) 2013-present Cole Bemis
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="3" y1="20" x2="21" y2="20" />
|
||||
<rect x="6" y="4" width="4" height="12" rx="1" />
|
||||
<rect x="14" y="9" width="4" height="7" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 335 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="12" y1="3" x2="12" y2="21" />
|
||||
<rect x="5" y="6" width="14" height="4" rx="1" />
|
||||
<rect x="8" y="14" width="8" height="4" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 335 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="4" y1="3" x2="4" y2="21" />
|
||||
<rect x="8" y="6" width="12" height="4" rx="1" />
|
||||
<rect x="8" y="14" width="7" height="4" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 333 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="20" y1="3" x2="20" y2="21" />
|
||||
<rect x="4" y="6" width="12" height="4" rx="1" />
|
||||
<rect x="9" y="14" width="7" height="4" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 335 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="3" y1="4" x2="21" y2="4" />
|
||||
<rect x="6" y="8" width="4" height="12" rx="1" />
|
||||
<rect x="14" y="8" width="4" height="7" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 333 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<rect x="6" y="5" width="4" height="14" rx="1" />
|
||||
<rect x="14" y="8" width="4" height="8" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 335 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="3" y1="4" x2="3" y2="20" />
|
||||
<line x1="21" y1="4" x2="21" y2="20" />
|
||||
<rect x="7" y="7" width="3" height="10" rx="1" />
|
||||
<rect x="14" y="7" width="3" height="10" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 376 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="4" y1="3" x2="20" y2="3" />
|
||||
<line x1="4" y1="21" x2="20" y2="21" />
|
||||
<rect x="7" y="7" width="10" height="3" rx="1" />
|
||||
<rect x="7" y="14" width="10" height="3" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 376 B |
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" />
|
||||
<circle cx="12" cy="12" r="5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 277 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M3 8V5a2 2 0 0 1 2-2h3" />
|
||||
<path d="M16 3h3a2 2 0 0 1 2 2v3" />
|
||||
<path d="M21 16v3a2 2 0 0 1-2 2h-3" />
|
||||
<path d="M8 21H5a2 2 0 0 1-2-2v-3" />
|
||||
<circle cx="12" cy="12" r="5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 382 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 236 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="m9 18 6-6-6-6" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 237 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="m11 17-5-5 5-5" />
|
||||
<path d="m18 17-5-5 5-5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 268 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="m6 17 5-5-5-5" />
|
||||
<path d="m13 17 5-5-5-5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 267 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 244 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 325 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49" />
|
||||
<path d="M14.084 14.158a3 3 0 0 1-4.242-4.242" />
|
||||
<path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143" />
|
||||
<path d="m2 2 20 20" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 504 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 360 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2" />
|
||||
<path d="M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2" />
|
||||
<path d="M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8" />
|
||||
<path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 483 B |
@@ -0,0 +1,15 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z" />
|
||||
<path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12" />
|
||||
<path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 510 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<rect width="18" height="11" x="3" y="11" rx="2" ry="2" />
|
||||
<path d="M7 11V7a5 5 0 0 1 9.9-1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 308 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<rect width="18" height="11" x="3" y="11" rx="2" ry="2" />
|
||||
<path d="M7 11V7a5 5 0 0 1 10 0v4" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 309 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 356 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<polygon points="3 11 22 2 13 21 11 13 3 11" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 258 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M11 7 6 2" />
|
||||
<path d="M18.992 12H2.041" />
|
||||
<path d="M21.145 18.38A3.34 3.34 0 0 1 20 16.5a3.3 3.3 0 0 1-1.145 1.88c-.575.46-.855 1.02-.855 1.595A2 2 0 0 0 20 22a2 2 0 0 0 2-2.025c0-.58-.285-1.13-.855-1.595" />
|
||||
<path d="m8.5 4.5 2.148-2.148a1.205 1.205 0 0 1 1.704 0l7.296 7.296a1.205 1.205 0 0 1 0 1.704l-7.592 7.592a3.615 3.615 0 0 1-5.112 0l-3.888-3.888a3.615 3.615 0 0 1 0-5.112L5.67 7.33" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 622 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<rect x="14" y="4" width="4" height="16" rx="1" />
|
||||
<rect x="6" y="4" width="4" height="16" rx="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 313 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
|
||||
<path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
|
||||
<path d="m2.3 2.3 7.286 7.286" />
|
||||
<circle cx="11" cy="11" r="2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 544 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" />
|
||||
<path d="m15 5 4 4" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 377 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M10.83 2.38a2 2 0 0 1 2.34 0l8 5.74a2 2 0 0 1 .73 2.25l-3.04 9.26a2 2 0 0 1-1.9 1.37H7.04a2 2 0 0 1-1.9-1.37L2.1 10.37a2 2 0 0 1 .73-2.25z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 362 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 306 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<rect width="20" height="12" x="2" y="6" rx="2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 261 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" />
|
||||
<path d="M21 3v5h-5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 299 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
|
||||
<path d="M14 15H9v-5" />
|
||||
<path d="M16 3h5v5" />
|
||||
<path d="M21 3 9 15" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 360 B |
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M22 2 2 22" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 234 B |
@@ -0,0 +1,16 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="11" cy="11" r="8" />
|
||||
<line x1="21" x2="16.65" y1="21" y2="16.65" />
|
||||
<line x1="11" x2="11" y1="8" y2="14" />
|
||||
<line x1="8" x2="14" y1="11" y2="11" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 376 B |
@@ -0,0 +1,83 @@
|
||||
//! Optional font build input (the Craft family convention, as in PhotoCraft).
|
||||
//!
|
||||
//! `CRAFT_FONTS_DIR=<craft-fonts checkout> cargo build` embeds the UI typefaces chosen in
|
||||
//! ADR 0005: Inter (prose) and JetBrains Mono (data), both SIL OFL 1.1. Font files are never
|
||||
//! committed to this repository. Without the variable the app uses egui's bundled defaults, and
|
||||
//! everything still works.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Files we look for, and the generated constant each fills.
|
||||
const FONTS: [(&str, &str); 2] = [("Inter-Regular.ttf", "UI_FONT"), ("JetBrainsMono-Regular.ttf", "MONO_FONT")];
|
||||
|
||||
fn find(dir: &Path, name: &str, depth: u32) -> Option<PathBuf> {
|
||||
let entries = std::fs::read_dir(dir).ok()?;
|
||||
let mut subdirs = Vec::new();
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
subdirs.push(p);
|
||||
} else if p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(name)) {
|
||||
return Some(p);
|
||||
}
|
||||
}
|
||||
if depth == 0 {
|
||||
return None;
|
||||
}
|
||||
subdirs.iter().find_map(|d| find(d, name, depth - 1))
|
||||
}
|
||||
|
||||
/// Where to look for the fonts when `CRAFT_FONTS_DIR` is not set: a `craft-fonts` checkout next
|
||||
/// to this repository (or up to three folders above it), then a sibling Craft app that vendors
|
||||
/// the same OFL files (PhotoCraft's `assets/fonts`). This makes ordinary local builds look like
|
||||
/// releases without committing font files here.
|
||||
fn discover() -> Option<PathBuf> {
|
||||
if let Some(d) = std::env::var_os("CRAFT_FONTS_DIR") {
|
||||
return Some(PathBuf::from(d));
|
||||
}
|
||||
let manifest = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR")?);
|
||||
let mut dir = manifest.parent().map(Path::to_path_buf);
|
||||
for _ in 0..4 {
|
||||
let Some(d) = dir else { break };
|
||||
for candidate in [d.join("craft-fonts"), d.join("photocraft").join("assets").join("fonts")] {
|
||||
if candidate.is_dir() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
dir = d.parent().map(Path::to_path_buf);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR");
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
let dir = discover();
|
||||
match &dir {
|
||||
Some(d) => println!("cargo:rerun-if-changed={}", d.display()),
|
||||
None => println!("cargo:warning=UI fonts: no craft-fonts found (set CRAFT_FONTS_DIR or clone storytold/craft-fonts next to the repo); using the built-in fallback fonts"),
|
||||
}
|
||||
let mut code = String::from("// Generated by build.rs (CRAFT_FONTS_DIR font input).\n");
|
||||
let mut total = 0u64;
|
||||
for (file, constant) in FONTS {
|
||||
let found = dir.as_deref().and_then(|d| find(d, file, 3));
|
||||
match found {
|
||||
Some(p) => {
|
||||
println!("cargo:rerun-if-changed={}", p.display());
|
||||
total += std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0);
|
||||
code.push_str(&format!("pub const {constant}: Option<&[u8]> = Some(include_bytes!({:?}));\n", p.display().to_string()));
|
||||
}
|
||||
None => {
|
||||
if dir.is_some() {
|
||||
println!("cargo:warning=CRAFT_FONTS_DIR is set but {file} was not found; using the bundled default");
|
||||
}
|
||||
code.push_str(&format!("pub const {constant}: Option<&[u8]> = None;\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
code.push_str(&format!("pub const CRAFT_FONT_BYTES: u64 = {total};\n"));
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("fonts.rs");
|
||||
if let Err(e) = std::fs::write(&out, code) {
|
||||
println!("cargo:warning=could not write {}: {e}", out.display());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "anicraft-cli"
|
||||
description = "AniCraft L4: headless CLI and JSON-lines control channel for agents and pipelines"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "anicraft-cli"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
anicraft-doc.workspace = true
|
||||
anicraft-engine.workspace = true
|
||||
anicraft-render.workspace = true
|
||||
anicraft-geom.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,373 @@
|
||||
//! AniCraft headless front end: argument parsing and the JSON-lines `serve` loop.
|
||||
//! Every operation goes through the engine's command registry.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use anicraft_engine::{Session, commands, format};
|
||||
use serde_json::{Value, json};
|
||||
use std::io::{BufRead, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Instant;
|
||||
|
||||
pub const USAGE: &str = "\
|
||||
AniCraft CLI — headless animation engine
|
||||
|
||||
USAGE:
|
||||
anicraft-cli info <file|--sample>
|
||||
anicraft-cli render <file|--sample> --out <frame.png> [--frame N] [--scale S]
|
||||
anicraft-cli render-seq <file|--sample> --out-dir <dir> [--from A] [--to B] [--scale S]
|
||||
anicraft-cli gif <file|--sample> --out <anim.gif> [--from A] [--to B] [--scale S] [--overwrite yes]
|
||||
anicraft-cli commands
|
||||
anicraft-cli run <file|--sample> <script.json> [--save <out.anicraft>]
|
||||
anicraft-cli exec <file|--sample> <command.id> [<json-params>] [--save <out.anicraft>]
|
||||
anicraft-cli new --out <file.anicraft> [--width W] [--height H] [--fps F]
|
||||
anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release)
|
||||
anicraft-cli serve [file|--sample] JSON-lines on stdin/stdout:
|
||||
{\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}}
|
||||
|
||||
Frames on the command line are 1-based, as in the timeline.";
|
||||
|
||||
/// Parsed flags: positional args plus `--key value` pairs.
|
||||
pub struct Args {
|
||||
pub positional: Vec<String>,
|
||||
pub flags: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
pub fn parse(args: &[String]) -> Result<Args, String> {
|
||||
let mut positional = Vec::new();
|
||||
let mut flags = Vec::new();
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
if a == "--sample" {
|
||||
positional.push(a.clone());
|
||||
} else if let Some(k) = a.strip_prefix("--") {
|
||||
let v = it.next().ok_or_else(|| format!("flag --{k} needs a value"))?;
|
||||
flags.push((k.to_string(), v.clone()));
|
||||
} else {
|
||||
positional.push(a.clone());
|
||||
}
|
||||
}
|
||||
Ok(Args { positional, flags })
|
||||
}
|
||||
pub fn flag(&self, k: &str) -> Option<&str> {
|
||||
self.flags.iter().rev().find(|(key, _)| key == k).map(|(_, v)| v.as_str())
|
||||
}
|
||||
pub fn num<T: std::str::FromStr>(&self, k: &str) -> Result<Option<T>, String> {
|
||||
self.flag(k).map(|v| v.parse::<T>().map_err(|_| format!("--{k} expects a number, got '{v}'"))).transpose()
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a session from a path or `--sample`.
|
||||
pub fn open_session(src: Option<&str>) -> Result<Session, String> {
|
||||
match src {
|
||||
None => Ok(Session::default()),
|
||||
Some("--sample") => Ok(Session::new(anicraft_doc::sample::demo())),
|
||||
Some(p) => {
|
||||
let doc = format::load(std::path::Path::new(p)).map_err(|e| format!("{p}: {e}"))?;
|
||||
let mut s = Session::new(doc);
|
||||
s.path = Some(PathBuf::from(p));
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, id: &str, params: &Value) -> Result<Value, String> {
|
||||
s.execute(id, params).map_err(|e| format!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn one_based(a: &Args, k: &str) -> Result<Option<u32>, String> {
|
||||
match a.num::<u32>(k)? {
|
||||
Some(0) => Err(format!("--{k} is 1-based; the first frame is 1")),
|
||||
Some(n) => Ok(Some(n - 1)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the CLI; returns the text to print on success.
|
||||
pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
let Some((cmd, rest)) = argv.split_first() else { return Ok(USAGE.to_string()) };
|
||||
let a = Args::parse(rest)?;
|
||||
let src = a.positional.first().map(String::as_str);
|
||||
match cmd.as_str() {
|
||||
"help" | "--help" | "-h" => Ok(USAGE.to_string()),
|
||||
"commands" => {
|
||||
let list: Vec<Value> = commands().iter().map(|c| c.to_json()).collect();
|
||||
serde_json::to_string_pretty(&list).map_err(|e| e.to_string())
|
||||
}
|
||||
"info" => {
|
||||
let s = open_session(Some(src.ok_or("info needs a file or --sample")?))?;
|
||||
serde_json::to_string_pretty(&s.info()).map_err(|e| e.to_string())
|
||||
}
|
||||
"render" => {
|
||||
let mut s = open_session(Some(src.ok_or("render needs a file or --sample")?))?;
|
||||
let out = a.flag("out").ok_or("render needs --out <file.png>")?;
|
||||
let mut p = json!({"path": out, "frame": one_based(&a, "frame")?.unwrap_or(0)});
|
||||
if let Some(sc) = a.num::<f32>("scale")? {
|
||||
p["scale"] = json!(sc);
|
||||
}
|
||||
exec(&mut s, "file.export_png", &p).map(|v| v.to_string())
|
||||
}
|
||||
"render-seq" => {
|
||||
let mut s = open_session(Some(src.ok_or("render-seq needs a file or --sample")?))?;
|
||||
let dir = a.flag("out-dir").ok_or("render-seq needs --out-dir <dir>")?;
|
||||
let mut p = json!({"dir": dir});
|
||||
if let Some(f) = one_based(&a, "from")? {
|
||||
p["from"] = json!(f);
|
||||
}
|
||||
if let Some(t) = one_based(&a, "to")? {
|
||||
p["to"] = json!(t);
|
||||
}
|
||||
if let Some(sc) = a.num::<f32>("scale")? {
|
||||
p["scale"] = json!(sc);
|
||||
}
|
||||
exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string())
|
||||
}
|
||||
"gif" => {
|
||||
let mut s = open_session(Some(src.ok_or("gif needs a file or --sample")?))?;
|
||||
let out = a.flag("out").ok_or("gif needs --out <anim.gif>")?;
|
||||
let mut p = json!({"path": out});
|
||||
if let Some(f) = one_based(&a, "from")? {
|
||||
p["from"] = json!(f);
|
||||
}
|
||||
if let Some(t) = one_based(&a, "to")? {
|
||||
p["to"] = json!(t);
|
||||
}
|
||||
if let Some(sc) = a.num::<f32>("scale")? {
|
||||
p["scale"] = json!(sc);
|
||||
}
|
||||
if a.flag("overwrite").is_some_and(|v| v == "yes" || v == "true") {
|
||||
p["confirm"] = json!(true);
|
||||
}
|
||||
exec(&mut s, "file.export_gif", &p).map(|v| v.to_string())
|
||||
}
|
||||
"new" => {
|
||||
let mut s = Session::default();
|
||||
let out = a.flag("out").ok_or("new needs --out <file.anicraft>")?;
|
||||
let mut p = json!({});
|
||||
for k in ["width", "height"] {
|
||||
if let Some(v) = a.num::<u32>(k)? {
|
||||
p[k] = json!(v);
|
||||
}
|
||||
}
|
||||
if let Some(v) = a.num::<f32>("fps")? {
|
||||
p["fps"] = json!(v);
|
||||
}
|
||||
exec(&mut s, "file.new", &p)?;
|
||||
exec(&mut s, "file.save", &json!({"path": out})).map(|v| v.to_string())
|
||||
}
|
||||
"exec" => {
|
||||
let mut s = open_session(Some(src.ok_or("exec needs a file or --sample")?))?;
|
||||
let id = a.positional.get(1).ok_or("exec needs a command id")?;
|
||||
let params: Value = match a.positional.get(2) {
|
||||
Some(t) => serde_json::from_str(t).map_err(|e| format!("params are not JSON: {e}"))?,
|
||||
None => json!({}),
|
||||
};
|
||||
let v = exec(&mut s, id, ¶ms)?;
|
||||
if let Some(out) = a.flag("save") {
|
||||
exec(&mut s, "file.save", &json!({"path": out}))?;
|
||||
}
|
||||
Ok(v.to_string())
|
||||
}
|
||||
"run" => {
|
||||
let mut s = open_session(Some(src.ok_or("run needs a file or --sample")?))?;
|
||||
let script = a.positional.get(1).ok_or("run needs a script.json")?;
|
||||
let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?;
|
||||
// Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it.
|
||||
let steps: Vec<Value> = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}}: {e}"))?;
|
||||
let mut results = Vec::new();
|
||||
for (i, step) in steps.iter().enumerate() {
|
||||
let id = step.get("cmd").and_then(Value::as_str).ok_or_else(|| format!("step {}: missing \"cmd\"", i + 1))?;
|
||||
let params = step.get("params").cloned().unwrap_or_else(|| json!({}));
|
||||
results.push(exec(&mut s, id, ¶ms).map_err(|e| format!("step {}: {e}", i + 1))?);
|
||||
}
|
||||
if let Some(out) = a.flag("save") {
|
||||
exec(&mut s, "file.save", &json!({"path": out}))?;
|
||||
}
|
||||
serde_json::to_string_pretty(&results).map_err(|e| e.to_string())
|
||||
}
|
||||
"bench" => bench(&a),
|
||||
"serve" => {
|
||||
let mut s = open_session(src)?;
|
||||
let stdin = std::io::stdin();
|
||||
let mut stdout = std::io::stdout();
|
||||
serve(&mut s, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?;
|
||||
Ok(String::new())
|
||||
}
|
||||
other => Err(format!("unknown subcommand '{other}'\n\n{USAGE}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn avg_ms(n: u32, mut f: impl FnMut(u32)) -> f64 {
|
||||
let t = Instant::now();
|
||||
for i in 0..n {
|
||||
f(i);
|
||||
}
|
||||
t.elapsed().as_secs_f64() * 1000.0 / f64::from(n.max(1))
|
||||
}
|
||||
|
||||
fn round(v: f64) -> f64 {
|
||||
(v * 1000.0).round() / 1000.0
|
||||
}
|
||||
|
||||
/// Performance probe on a generated stress document. Run in release for meaningful numbers:
|
||||
/// `cargo run --release -p anicraft-cli -- bench`.
|
||||
pub fn bench(a: &Args) -> Result<String, String> {
|
||||
use anicraft_doc::{evaluate, sample};
|
||||
use anicraft_engine::history::document_bytes;
|
||||
use anicraft_render::{View, render};
|
||||
|
||||
let layers = a.num::<u32>("layers")?.unwrap_or(50);
|
||||
let shapes = a.num::<u32>("shapes")?.unwrap_or(200);
|
||||
let frames = a.num::<u32>("frames")?.unwrap_or(240);
|
||||
let t = Instant::now();
|
||||
let doc = sample::stress(layers, shapes, frames);
|
||||
let build_ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
let instances: usize = doc.timeline.layers.iter().flat_map(|l| l.keyframes.iter()).map(|k| k.elements.len()).sum();
|
||||
|
||||
let mut json_text = String::new();
|
||||
let save_ms = avg_ms(1, |_| json_text = format::to_json(&doc).unwrap_or_default());
|
||||
let load_ms = avg_ms(1, |_| {
|
||||
let _ = format::from_json(&json_text);
|
||||
});
|
||||
|
||||
let eval_ms = avg_ms(48, |i| {
|
||||
let _ = evaluate(&doc, (i * 5) % frames.max(1));
|
||||
});
|
||||
let view = View::stage(&doc, 1.0);
|
||||
let mut drawn = 0;
|
||||
let render_ms = avg_ms(12, |i| {
|
||||
if let Ok((_, st)) = render(&evaluate(&doc, (i * 20) % frames.max(1)), &view) {
|
||||
drawn = st.drawn;
|
||||
}
|
||||
});
|
||||
// 400% zoom on the stage centre: most shapes are off-screen and culled.
|
||||
let zoomed = View { transform: anicraft_geom::Affine::translate(-2880.0, -1620.0).mul(&anicraft_geom::Affine::scale(4.0, 4.0)), ..view };
|
||||
let mut culled = 0;
|
||||
let zoom_ms = avg_ms(12, |i| {
|
||||
if let Ok((_, st)) = render(&evaluate(&doc, (i * 20) % frames.max(1)), &zoomed) {
|
||||
culled = st.culled;
|
||||
}
|
||||
});
|
||||
let clone_us = avg_ms(1000, |_| {
|
||||
let _ = doc.clone();
|
||||
}) * 1000.0;
|
||||
|
||||
let mut s = Session::new(doc);
|
||||
let _ = s.execute("layer.select", &json!({"index": 0}));
|
||||
s.set_frame(7);
|
||||
let first = s.visible_elements().first().map(|e| e.id.0);
|
||||
if let Some(id) = first {
|
||||
let _ = s.execute("element.select", &json!({"ids": [id]}));
|
||||
}
|
||||
let edit_ms = avg_ms(100, |_| {
|
||||
let _ = s.execute("element.translate", &json!({"dx": 1, "dy": 0}));
|
||||
});
|
||||
let steps = s.history().undo_len().max(1);
|
||||
let per_step = s.history().bytes() / steps;
|
||||
let undo_ms = avg_ms(50, |_| {
|
||||
let _ = s.undo();
|
||||
});
|
||||
let hit_us = avg_ms(500, |i| {
|
||||
let _ = s.hit_test(anicraft_geom::Vec2::new((i * 37 % 1920) as f32, (i * 53 % 1080) as f32), 2.0);
|
||||
}) * 1000.0;
|
||||
|
||||
let out = json!({
|
||||
"document": {"layers": layers, "shapes_per_layer": shapes, "frames": frames, "element_instances": instances,
|
||||
"estimated_mb": round(document_bytes(&s.doc) as f64 / 1048576.0), "build_ms": round(build_ms)},
|
||||
"file": {"json_mb": round(json_text.len() as f64 / 1048576.0), "save_ms": round(save_ms), "load_ms": round(load_ms)},
|
||||
"evaluate_ms_per_frame": round(eval_ms),
|
||||
"render_1080p_ms_per_frame": round(render_ms), "render_shapes_drawn": drawn,
|
||||
"render_zoom400_ms_per_frame": round(zoom_ms), "render_zoom400_culled": culled,
|
||||
"snapshot_clone_us": round(clone_us),
|
||||
"edit_command_ms": round(edit_ms), "undo_bytes_per_step": per_step, "undo_ms": round(undo_ms),
|
||||
"hit_test_us": round(hit_us),
|
||||
"threads": std::thread::available_parallelism().map_or(1, |n| n.get()),
|
||||
"build": if cfg!(debug_assertions) { "debug (use --release for real numbers)" } else { "release" },
|
||||
});
|
||||
serde_json::to_string_pretty(&out).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Answers one JSON request.
|
||||
pub fn handle_request(s: &mut Session, line: &str) -> Value {
|
||||
// Windows shells often prefix piped UTF-8 with a byte-order mark.
|
||||
let line = line.trim_start_matches('\u{feff}');
|
||||
let req: Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return json!({"id": null, "ok": false, "error": format!("invalid JSON: {e}")}),
|
||||
};
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
let Some(cmd) = req.get("cmd").and_then(Value::as_str) else {
|
||||
return json!({"id": id, "ok": false, "error": "missing \"cmd\""});
|
||||
};
|
||||
let params = req.get("params").cloned().unwrap_or_else(|| json!({}));
|
||||
let result = match cmd {
|
||||
"commands" => Ok(Value::Array(commands().iter().map(|c| c.to_json()).collect())),
|
||||
_ => s.execute(cmd, ¶ms).map_err(|e| e.to_string()),
|
||||
};
|
||||
match result {
|
||||
Ok(v) => json!({"id": id, "ok": true, "result": v, "revision": s.revision, "frame": s.frame}),
|
||||
Err(e) => json!({"id": id, "ok": false, "error": e}),
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON-lines loop: one request per line, one response per line. Ends on EOF or `{"cmd":"quit"}`.
|
||||
pub fn serve<R: BufRead, W: Write>(s: &mut Session, input: R, out: &mut W) -> std::io::Result<()> {
|
||||
writeln!(out, "{}", json!({"ready": true, "app": "AniCraft", "version": env!("CARGO_PKG_VERSION")}))?;
|
||||
out.flush()?;
|
||||
for line in input.lines() {
|
||||
let line = line?;
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
if line.contains("\"quit\"") && serde_json::from_str::<Value>(&line).ok().and_then(|v| v.get("cmd").cloned()) == Some(json!("quit")) {
|
||||
writeln!(out, "{}", json!({"ok": true, "bye": true}))?;
|
||||
break;
|
||||
}
|
||||
let resp = handle_request(s, &line);
|
||||
writeln!(out, "{resp}")?;
|
||||
out.flush()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serve_round_trip() {
|
||||
let mut s = Session::default();
|
||||
let input = b"\xef\xbb\xbf{\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":1,\"y\":1,\"w\":5,\"h\":5}}\nnot json\n{\"id\":3,\"cmd\":\"nope\"}\n{\"cmd\":\"quit\"}\n{\"id\":4,\"cmd\":\"edit.undo\"}\n";
|
||||
let mut out = Vec::new();
|
||||
serve(&mut s, &input[..], &mut out).unwrap();
|
||||
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines[0]["ready"], true);
|
||||
assert_eq!(lines[1]["ok"], true);
|
||||
assert_eq!(lines[2]["ok"], false);
|
||||
assert_eq!(lines[3]["ok"], false);
|
||||
assert_eq!(lines[4]["bye"], true);
|
||||
assert_eq!(lines.len(), 5, "nothing runs after quit");
|
||||
assert_eq!(s.visible_elements().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_sample_to_png() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-cli-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let out = dir.join("f.png");
|
||||
let argv: Vec<String> = ["render", "--sample", "--frame", "12", "--scale", "0.25", "--out", out.to_str().unwrap()].iter().map(|s| s.to_string()).collect();
|
||||
run(&argv).unwrap();
|
||||
let bytes = std::fs::read(&out).unwrap();
|
||||
assert_eq!(&bytes[1..4], b"PNG");
|
||||
assert!(run(&["render".into(), "--sample".into(), "--frame".into(), "0".into(), "--out".into(), "x.png".into()]).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_and_errors() {
|
||||
assert!(run(&[]).unwrap().contains("USAGE"));
|
||||
assert!(run(&["bogus".into()]).is_err());
|
||||
assert!(run(&["info".into()]).is_err());
|
||||
assert!(run(&["commands".into()]).unwrap().contains("timeline.insert_keyframe"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
fn main() {
|
||||
let argv: Vec<String> = std::env::args().skip(1).collect();
|
||||
// `--screenshot` is a desktop-app feature: hand over to the `anicraft` binary next to us.
|
||||
if argv.iter().any(|a| a == "--screenshot") {
|
||||
std::process::exit(delegate_to_desktop(&argv));
|
||||
}
|
||||
match anicraft_cli::run(&argv) {
|
||||
Ok(out) => {
|
||||
if !out.is_empty() {
|
||||
println!("{out}");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn delegate_to_desktop(argv: &[String]) -> i32 {
|
||||
let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.join(format!("anicraft{}", std::env::consts::EXE_SUFFIX))));
|
||||
let Some(exe) = exe.filter(|p| p.exists()) else {
|
||||
eprintln!("error: --screenshot needs the AniCraft desktop app (`anicraft`) next to anicraft-cli; build it with `cargo build`");
|
||||
return 1;
|
||||
};
|
||||
match std::process::Command::new(&exe).args(argv).status() {
|
||||
Ok(s) => s.code().unwrap_or(1),
|
||||
Err(e) => {
|
||||
eprintln!("error: could not start {}: {e}", exe.display());
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "anicraft-doc"
|
||||
description = "AniCraft L1: document model (stage, timeline, layers, keyframes, symbols) and timeline evaluation"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anicraft-geom.workspace = true
|
||||
serde = { workspace = true, features = ["rc"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Easing curves for tweens.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Maps linear tween progress `t ∈ [0, 1]` to eased progress.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Easing {
|
||||
#[default]
|
||||
Linear,
|
||||
QuadIn,
|
||||
QuadOut,
|
||||
QuadInOut,
|
||||
CubicIn,
|
||||
CubicOut,
|
||||
CubicInOut,
|
||||
/// The traditional single-slider ease: −100 (ease in) … 0 (linear) … +100 (ease out).
|
||||
Classic(f32),
|
||||
/// CSS-style cubic Bézier through (0,0), (x1,y1), (x2,y2), (1,1).
|
||||
CubicBezier(f32, f32, f32, f32),
|
||||
}
|
||||
|
||||
impl Easing {
|
||||
/// Presets shown in the UI, in menu order.
|
||||
pub const PRESETS: [(&'static str, Easing); 8] = [
|
||||
("Linear", Easing::Linear),
|
||||
("Ease in (quad)", Easing::QuadIn),
|
||||
("Ease out (quad)", Easing::QuadOut),
|
||||
("Ease in-out (quad)", Easing::QuadInOut),
|
||||
("Ease in (cubic)", Easing::CubicIn),
|
||||
("Ease out (cubic)", Easing::CubicOut),
|
||||
("Ease in-out (cubic)", Easing::CubicInOut),
|
||||
("Smooth (bezier)", Easing::CubicBezier(0.25, 0.1, 0.25, 1.0)),
|
||||
];
|
||||
|
||||
pub fn label(&self) -> String {
|
||||
match self {
|
||||
Easing::Classic(s) => format!("Classic {s:+.0}"),
|
||||
Easing::CubicBezier(a, b, c, d) => {
|
||||
Easing::PRESETS.iter().find(|(_, e)| e == self).map_or_else(|| format!("Bezier({a:.2}, {b:.2}, {c:.2}, {d:.2})"), |(n, _)| (*n).to_string())
|
||||
}
|
||||
other => Easing::PRESETS.iter().find(|(_, e)| e == other).map_or("Custom", |(n, _)| n).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply(&self, t: f32) -> f32 {
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
match *self {
|
||||
Easing::Linear => t,
|
||||
Easing::QuadIn => t * t,
|
||||
Easing::QuadOut => t * (2.0 - t),
|
||||
Easing::QuadInOut => {
|
||||
if t < 0.5 {
|
||||
2.0 * t * t
|
||||
} else {
|
||||
-1.0 + (4.0 - 2.0 * t) * t
|
||||
}
|
||||
}
|
||||
Easing::CubicIn => t * t * t,
|
||||
Easing::CubicOut => {
|
||||
let u = t - 1.0;
|
||||
u * u * u + 1.0
|
||||
}
|
||||
Easing::CubicInOut => {
|
||||
if t < 0.5 {
|
||||
4.0 * t * t * t
|
||||
} else {
|
||||
let u = 2.0 * t - 2.0;
|
||||
0.5 * u * u * u + 1.0
|
||||
}
|
||||
}
|
||||
Easing::Classic(strength) => {
|
||||
// Quadratic Bézier with the middle control point moved by `strength`.
|
||||
let s = if strength.is_finite() { strength.clamp(-100.0, 100.0) / 100.0 } else { 0.0 };
|
||||
let c = 0.5 + 0.5 * s; // y of control point at x = 0.5
|
||||
2.0 * (1.0 - t) * t * c + t * t
|
||||
}
|
||||
Easing::CubicBezier(x1, y1, x2, y2) => cubic_bezier(t, x1, y1, x2, y2),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cubic_bezier(x: f32, x1: f32, y1: f32, x2: f32, y2: f32) -> f32 {
|
||||
if ![x1, y1, x2, y2].iter().all(|v| v.is_finite()) {
|
||||
return x;
|
||||
}
|
||||
// x control points must stay in [0, 1] so x(t) is monotonic.
|
||||
let (x1, x2) = (x1.clamp(0.0, 1.0), x2.clamp(0.0, 1.0));
|
||||
let bez = |t: f32, p1: f32, p2: f32| {
|
||||
let mt = 1.0 - t;
|
||||
3.0 * mt * mt * t * p1 + 3.0 * mt * t * t * p2 + t * t * t
|
||||
};
|
||||
let dbez = |t: f32, p1: f32, p2: f32| {
|
||||
let mt = 1.0 - t;
|
||||
3.0 * mt * mt * p1 + 6.0 * mt * t * (p2 - p1) + 3.0 * t * t * (1.0 - p2)
|
||||
};
|
||||
// Newton, then bisection as a fallback.
|
||||
let mut t = x;
|
||||
for _ in 0..8 {
|
||||
let err = bez(t, x1, x2) - x;
|
||||
if err.abs() < 1e-6 {
|
||||
return bez(t, y1, y2);
|
||||
}
|
||||
let d = dbez(t, x1, x2);
|
||||
if d.abs() < 1e-6 {
|
||||
break;
|
||||
}
|
||||
t = (t - err / d).clamp(0.0, 1.0);
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0f32, 1.0f32);
|
||||
t = x;
|
||||
for _ in 0..40 {
|
||||
let v = bez(t, x1, x2);
|
||||
if (v - x).abs() < 1e-6 {
|
||||
break;
|
||||
}
|
||||
if v < x {
|
||||
lo = t;
|
||||
} else {
|
||||
hi = t;
|
||||
}
|
||||
t = 0.5 * (lo + hi);
|
||||
}
|
||||
bez(t, y1, y2)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ALL: [Easing; 10] = [
|
||||
Easing::Linear,
|
||||
Easing::QuadIn,
|
||||
Easing::QuadOut,
|
||||
Easing::QuadInOut,
|
||||
Easing::CubicIn,
|
||||
Easing::CubicOut,
|
||||
Easing::CubicInOut,
|
||||
Easing::Classic(-60.0),
|
||||
Easing::Classic(100.0),
|
||||
Easing::CubicBezier(0.25, 0.1, 0.25, 1.0),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn endpoints_fixed() {
|
||||
for e in ALL {
|
||||
assert!(e.apply(0.0).abs() < 1e-4, "{e:?}");
|
||||
assert!((e.apply(1.0) - 1.0).abs() < 1e-4, "{e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monotonic() {
|
||||
for e in ALL {
|
||||
let mut prev = -1e-6;
|
||||
for i in 0..=100 {
|
||||
let v = e.apply(i as f32 / 100.0);
|
||||
assert!(v >= prev - 1e-4, "{e:?} at {i}");
|
||||
prev = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_is_clamped() {
|
||||
assert_eq!(Easing::Linear.apply(f32::NAN), 0.0);
|
||||
assert_eq!(Easing::QuadIn.apply(5.0), 1.0);
|
||||
assert!(Easing::CubicBezier(f32::NAN, 0.0, 1.0, 1.0).apply(0.5).is_finite());
|
||||
assert!(Easing::Classic(f32::INFINITY).apply(0.5).is_finite());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ease_in_is_slow_at_start() {
|
||||
assert!(Easing::QuadIn.apply(0.25) < 0.25);
|
||||
assert!(Easing::QuadOut.apply(0.25) > 0.25);
|
||||
assert!(Easing::Classic(-100.0).apply(0.25) < 0.25);
|
||||
assert!(Easing::Classic(100.0).apply(0.25) > 0.25);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Timeline evaluation: `(document, frame) -> DisplayList`. Pure, deterministic, no caching.
|
||||
|
||||
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, Timeline};
|
||||
use anicraft_geom::{Affine, FillRule, Path};
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Symbols nested deeper than this are not drawn (guards cyclic libraries).
|
||||
pub const MAX_SYMBOL_DEPTH: usize = 32;
|
||||
|
||||
/// One shape to draw, fully resolved to stage space.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DisplayItem {
|
||||
pub path: Arc<Path>,
|
||||
/// Local → stage transform.
|
||||
pub transform: Affine,
|
||||
pub fill: Option<Paint>,
|
||||
pub stroke: Option<Stroke>,
|
||||
pub fill_rule: FillRule,
|
||||
pub color: ColorEffect,
|
||||
/// The top-level layer and element this item came from (for picking).
|
||||
pub layer: LayerId,
|
||||
pub element: ElementId,
|
||||
/// Outline-only display (layer outline mode).
|
||||
pub outline: Option<Rgba>,
|
||||
/// Drawn only inside this clip (an index into [`DisplayList::clip_parents`]).
|
||||
pub clip: Option<u32>,
|
||||
/// Mask artwork: not drawn; its fill area (strokes and opacity ignored) forms this clip.
|
||||
pub masks: Option<u32>,
|
||||
}
|
||||
|
||||
/// Back-to-front list of shapes.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DisplayList {
|
||||
pub items: Vec<DisplayItem>,
|
||||
/// One entry per clip: the enclosing clip it is intersected with. A parent always has a
|
||||
/// lower index than its children. A clip with no mask artwork hides everything in it.
|
||||
pub clip_parents: Vec<Option<u32>>,
|
||||
}
|
||||
|
||||
impl DisplayList {
|
||||
/// Whether stage point `p` lies inside clip `clip` (and every clip enclosing it): the test
|
||||
/// that keeps masked-away parts of a shape from being picked.
|
||||
pub fn clip_contains(&self, clip: u32, p: anicraft_geom::Vec2) -> bool {
|
||||
let mut c = Some(clip);
|
||||
for _ in 0..self.clip_parents.len() {
|
||||
let Some(id) = c else { return true };
|
||||
if !self.items.iter().any(|i| i.masks == Some(id) && i.fill.is_some() && i.path.contains(p, &i.transform, i.fill_rule)) {
|
||||
return false;
|
||||
}
|
||||
c = self.clip_parents.get(id as usize).copied().flatten().filter(|&q| q < id);
|
||||
}
|
||||
c.is_none()
|
||||
}
|
||||
|
||||
/// Appends `other`'s items (drawn on top), renumbering its clips.
|
||||
pub fn append(&mut self, other: DisplayList) {
|
||||
let base = self.clip_parents.len() as u32;
|
||||
let shift = |c: Option<u32>| c.map(|c| c + base);
|
||||
self.clip_parents.extend(other.clip_parents.into_iter().map(shift));
|
||||
self.items.extend(other.items.into_iter().map(|mut i| {
|
||||
i.clip = shift(i.clip);
|
||||
i.masks = shift(i.masks);
|
||||
i
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates the main timeline at `frame` (0-based).
|
||||
pub fn evaluate(doc: &Document, frame: u32) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
let cx = Ctx { xf: Affine::IDENTITY, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None };
|
||||
eval_timeline(doc, &doc.timeline, frame, &cx, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Elements of `layer` as they appear at `frame`, with tweens applied, plus the start frame of
|
||||
/// the covering keyframe. `None` when the frame is empty on this layer.
|
||||
pub fn evaluate_layer_elements(layer: &Layer, frame: u32) -> Option<(u32, Cow<'_, [Arc<Element>]>)> {
|
||||
let idx = layer.keyframe_index_at(frame)?;
|
||||
let kf = layer.keyframes.get(idx)?;
|
||||
let Some(tween) = kf.tween else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
||||
let Some(next) = layer.keyframes.get(idx + 1) else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
||||
if next.start != kf.end() || frame == kf.start {
|
||||
return Some((kf.start, Cow::Borrowed(&kf.elements)));
|
||||
}
|
||||
let t = tween.easing.apply((frame - kf.start) as f32 / kf.duration.max(1) as f32);
|
||||
let els = kf.elements.iter().enumerate().map(|(i, a)| next.elements.get(i).and_then(|b| interpolate(a, b, t)).map_or_else(|| a.clone(), Arc::new)).collect();
|
||||
Some((kf.start, Cow::Owned(els)))
|
||||
}
|
||||
|
||||
/// Interpolates two compatible elements; `None` when they cannot tween.
|
||||
fn interpolate(a: &Element, b: &Element, t: f32) -> Option<Element> {
|
||||
let kind = match (&a.kind, &b.kind) {
|
||||
(ElementKind::Shape(sa), ElementKind::Shape(sb)) => {
|
||||
let path = if Arc::ptr_eq(&sa.path, &sb.path) { sa.path.clone() } else { sa.path.lerp(&sb.path, t).map(Arc::new).unwrap_or_else(|| sa.path.clone()) };
|
||||
let fill = match (&sa.fill, &sb.fill) {
|
||||
(Some(x), Some(y)) => Some(x.lerp(y, t)),
|
||||
(x, _) => x.clone(),
|
||||
};
|
||||
let stroke = match (sa.stroke, sb.stroke) {
|
||||
(Some(x), Some(y)) => Some(Stroke { color: x.color.lerp(y.color, t), width: anicraft_geom::lerp(x.width, y.width, t) }),
|
||||
(x, _) => x,
|
||||
};
|
||||
ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule })
|
||||
}
|
||||
(ElementKind::Symbol { symbol: s1, .. }, ElementKind::Symbol { symbol: s2, .. }) if s1 == s2 => a.kind.clone(),
|
||||
_ => return None,
|
||||
};
|
||||
let transform = a.transform.decompose().lerp(&b.transform.decompose(), t).compose();
|
||||
Some(Element { id: a.id, name: a.name.clone(), transform, color: a.color.lerp(&b.color, t), kind })
|
||||
}
|
||||
|
||||
/// What a timeline is evaluated inside of.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Ctx {
|
||||
/// Local → stage transform and colour effect of the enclosing instance.
|
||||
xf: Affine,
|
||||
color: ColorEffect,
|
||||
depth: usize,
|
||||
/// The top-level layer and element everything inside belongs to (for picking).
|
||||
root: Option<(LayerId, ElementId)>,
|
||||
outline: Option<Rgba>,
|
||||
/// The clip everything inside is drawn within.
|
||||
clip: Option<u32>,
|
||||
/// Set while evaluating mask artwork: everything inside forms this clip.
|
||||
masks: Option<u32>,
|
||||
}
|
||||
|
||||
fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut DisplayList) {
|
||||
if cx.depth > MAX_SYMBOL_DEPTH {
|
||||
return;
|
||||
}
|
||||
// One clip per visible mask layer, nested in the enclosing clip. Inside mask artwork every
|
||||
// layer is artwork, so masks there do not mask again. A hidden mask layer masks nothing.
|
||||
let mut clips: Vec<(LayerId, u32)> = Vec::new();
|
||||
if cx.masks.is_none() {
|
||||
for layer in tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible) {
|
||||
clips.push((layer.id, out.clip_parents.len() as u32));
|
||||
out.clip_parents.push(cx.clip);
|
||||
}
|
||||
}
|
||||
let clip_of = |id: LayerId| clips.iter().find(|(l, _)| *l == id).map(|(_, c)| *c);
|
||||
for layer in tl.layers.iter().rev() {
|
||||
if !layer.visible || layer.kind == LayerKind::Guide {
|
||||
continue;
|
||||
}
|
||||
let (clip, masks) = match (cx.masks, layer.kind) {
|
||||
(Some(_), _) => (cx.clip, cx.masks),
|
||||
(None, LayerKind::Mask) => (cx.clip, clip_of(layer.id)),
|
||||
(None, _) => (layer.parent.and_then(clip_of).or(cx.clip), None),
|
||||
};
|
||||
let Some((kf_start, elements)) = evaluate_layer_elements(layer, frame) else { continue };
|
||||
let layer_outline = cx.outline.or(if layer.outline { Some(layer.color) } else { None });
|
||||
for el in elements.iter() {
|
||||
let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id));
|
||||
let xf = cx.xf.mul(&el.transform);
|
||||
let color = cx.color.concat(&el.color);
|
||||
match &el.kind {
|
||||
ElementKind::Shape(s) => out.items.push(DisplayItem {
|
||||
path: s.path.clone(),
|
||||
transform: xf,
|
||||
fill: s.fill.clone(),
|
||||
stroke: s.stroke,
|
||||
fill_rule: s.fill_rule,
|
||||
color,
|
||||
layer: root_layer,
|
||||
element: root_el,
|
||||
outline: layer_outline,
|
||||
clip,
|
||||
masks,
|
||||
}),
|
||||
ElementKind::Symbol { symbol, loop_mode, first_frame } => {
|
||||
let Some(sym) = doc.symbol(*symbol) else { continue };
|
||||
let local = loop_mode.local_frame(frame.saturating_sub(kf_start), *first_frame, sym.timeline.frame_count());
|
||||
let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, clip, masks };
|
||||
eval_timeline(doc, &sym.timeline, local, &inner, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "eval_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,200 @@
|
||||
use super::*;
|
||||
use crate::{Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween};
|
||||
|
||||
fn shape_el(id: u64, x: f32) -> Element {
|
||||
Element {
|
||||
id: ElementId(id),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(x, 0.0),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK))),
|
||||
}
|
||||
}
|
||||
|
||||
fn layer0(d: &mut Document) -> &mut Layer {
|
||||
Arc::make_mut(&mut d.timeline.layers[0])
|
||||
}
|
||||
|
||||
fn push(layer: &mut Layer, kf: usize, e: Element) {
|
||||
layer.keyframe_mut(kf).unwrap().elements.push(Arc::new(e));
|
||||
}
|
||||
|
||||
fn tween_doc(easing: Easing) -> Document {
|
||||
let mut d = Document::default();
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements.push(Arc::new(shape_el(10, 0.0)));
|
||||
k0.tween = Some(Tween { easing });
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements.push(Arc::new(shape_el(10, 100.0)));
|
||||
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_tween_interpolates_translation() {
|
||||
let d = tween_doc(Easing::Linear);
|
||||
let x = |f| evaluate(&d, f).items[0].transform.translation().x;
|
||||
assert_eq!(x(0), 0.0);
|
||||
assert!((x(5) - 50.0).abs() < 1e-3);
|
||||
assert_eq!(x(10), 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eased_tween_differs_from_linear() {
|
||||
let d = tween_doc(Easing::QuadIn);
|
||||
let x5 = evaluate(&d, 5).items[0].transform.translation().x;
|
||||
assert!((x5 - 25.0).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_frames_share_elements_with_the_document() {
|
||||
let d = tween_doc(Easing::Linear);
|
||||
let (_, els) = evaluate_layer_elements(&d.timeline.layers[0], 10).unwrap();
|
||||
assert!(matches!(els, Cow::Borrowed(_)), "a non-tweened frame must not copy elements");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_and_guide_layers_are_skipped() {
|
||||
let mut d = tween_doc(Easing::Linear);
|
||||
layer0(&mut d).visible = false;
|
||||
assert!(evaluate(&d, 0).items.is_empty());
|
||||
layer0(&mut d).visible = true;
|
||||
layer0(&mut d).kind = LayerKind::Guide;
|
||||
assert!(evaluate(&d, 0).items.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_symbols_compose_transforms_and_cycles_terminate() {
|
||||
let mut d = Document::default();
|
||||
let sid = SymbolId(99);
|
||||
// A symbol that contains a shape and an instance of itself: a cycle.
|
||||
let mut tl = Timeline::default();
|
||||
let mut layer = Layer::new(LayerId(50), "s");
|
||||
push(&mut layer, 0, shape_el(51, 0.0));
|
||||
push(
|
||||
&mut layer,
|
||||
0,
|
||||
Element {
|
||||
id: ElementId(52),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(1.0, 0.0),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0 },
|
||||
},
|
||||
);
|
||||
tl.layers.push(Arc::new(layer));
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, timeline: tl }));
|
||||
push(
|
||||
layer0(&mut d),
|
||||
0,
|
||||
Element {
|
||||
id: ElementId(60),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(100.0, 0.0),
|
||||
color: ColorEffect { alpha: 0.5, ..Default::default() },
|
||||
kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0 },
|
||||
},
|
||||
);
|
||||
let dl = evaluate(&d, 0);
|
||||
assert_eq!(dl.items.len(), MAX_SYMBOL_DEPTH);
|
||||
assert_eq!(dl.items[0].transform.translation().x, 100.0);
|
||||
assert_eq!(dl.items[0].color.alpha, 0.5);
|
||||
assert!(dl.items.iter().all(|i| i.element == ElementId(60)));
|
||||
}
|
||||
|
||||
/// Layers top to bottom: mask (id 1), masked (2), masked (3), plain (4).
|
||||
fn mask_doc() -> Document {
|
||||
let mut d = Document { timeline: Timeline::default(), ..Document::default() };
|
||||
for (id, kind, parent) in [(1, LayerKind::Mask, None), (2, LayerKind::Normal, Some(1)), (3, LayerKind::Normal, Some(1)), (4, LayerKind::Normal, None)] {
|
||||
let mut l = Layer::new(LayerId(id), format!("L{id}"));
|
||||
l.kind = kind;
|
||||
l.parent = parent.map(LayerId);
|
||||
push(&mut l, 0, shape_el(10 + id, 0.0));
|
||||
d.timeline.layers.push(Arc::new(l));
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_layers_clip_the_layers_they_mask() {
|
||||
let d = mask_doc();
|
||||
let dl = evaluate(&d, 0);
|
||||
assert_eq!(dl.clip_parents, vec![None]);
|
||||
let by = |e: u64| dl.items.iter().find(|i| i.element == ElementId(e)).unwrap();
|
||||
assert_eq!((by(14).clip, by(14).masks), (None, None), "unmasked layer");
|
||||
assert_eq!((by(13).clip, by(12).clip), (Some(0), Some(0)), "masked layers");
|
||||
assert_eq!(by(11).masks, Some(0), "the mask layer's artwork forms the clip");
|
||||
// A hidden mask masks nothing; its layers draw normally.
|
||||
let mut h = d.clone();
|
||||
Arc::make_mut(&mut h.timeline.layers[0]).visible = false;
|
||||
let dl = evaluate(&h, 0);
|
||||
assert!(dl.items.iter().all(|i| i.clip.is_none() && i.masks.is_none()) && dl.items.len() == 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_inside_symbols_nest_in_the_instance_clip() {
|
||||
// The main timeline's masked layer holds an instance of a symbol that has its own mask.
|
||||
let mut d = mask_doc();
|
||||
let sid = SymbolId(99);
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, timeline: mask_doc().timeline }));
|
||||
let inst = Element {
|
||||
id: ElementId(60),
|
||||
name: String::new(),
|
||||
transform: Affine::IDENTITY,
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0 },
|
||||
};
|
||||
push(Arc::make_mut(&mut d.timeline.layers[1]), 0, inst);
|
||||
let dl = evaluate(&d, 0);
|
||||
assert_eq!(dl.clip_parents, vec![None, Some(0)]);
|
||||
let inner: Vec<_> = dl.items.iter().filter(|i| i.element == ElementId(60)).map(|i| (i.clip, i.masks)).collect();
|
||||
// inside: unmasked layer keeps the outer clip; masked layers use the nested clip.
|
||||
assert_eq!(inner, vec![(Some(0), None), (Some(1), None), (Some(1), None), (Some(0), Some(1))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appending_lists_renumbers_clips() {
|
||||
let d = mask_doc();
|
||||
let mut a = evaluate(&d, 0);
|
||||
a.append(evaluate(&d, 0));
|
||||
assert_eq!(a.clip_parents, vec![None, None]);
|
||||
let second = &a.items[4..];
|
||||
assert!(second.iter().all(|i| i.clip.is_none_or(|c| c == 1) && i.masks.is_none_or(|c| c == 1)));
|
||||
assert!(second.iter().any(|i| i.masks == Some(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_links_must_stay_directly_under_their_mask() {
|
||||
let mut d = mask_doc();
|
||||
d.timeline.repair_masks();
|
||||
assert_eq!(d.timeline.layers.iter().map(|l| l.parent).collect::<Vec<_>>(), vec![None, Some(LayerId(1)), Some(LayerId(1)), None]);
|
||||
assert_eq!(d.timeline.group_range(0), 0..3);
|
||||
assert_eq!(d.timeline.mask_above(3), Some(LayerId(1)), "a layer under the group would join it");
|
||||
// The plain layer moved between the masked ones breaks the run: the lower one lets go.
|
||||
d.timeline.layers.swap(2, 3);
|
||||
d.timeline.repair_masks();
|
||||
assert_eq!(d.timeline.layers[3].parent, None);
|
||||
assert_eq!(d.timeline.layers[1].parent, Some(LayerId(1)));
|
||||
// A masked layer above its mask, or a mask that is no longer a mask, lets go too.
|
||||
let mut e = mask_doc();
|
||||
e.timeline.layers.swap(0, 1);
|
||||
e.timeline.repair_masks();
|
||||
assert_eq!(e.timeline.layers[0].parent, None);
|
||||
assert_eq!(e.timeline.layers[2].parent, Some(LayerId(1)), "still directly under the mask");
|
||||
let mut f = mask_doc();
|
||||
Arc::make_mut(&mut f.timeline.layers[0]).kind = LayerKind::Normal;
|
||||
f.sanitize();
|
||||
assert!(f.timeline.layers.iter().all(|l| l.parent.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_order_is_back_to_front() {
|
||||
let mut d = Document::default();
|
||||
push(layer0(&mut d), 0, shape_el(1, 0.0));
|
||||
let mut bottom = Layer::new(LayerId(7), "bottom");
|
||||
push(&mut bottom, 0, shape_el(2, 0.0));
|
||||
d.timeline.layers.push(Arc::new(bottom));
|
||||
let dl = evaluate(&d, 0);
|
||||
assert_eq!(dl.items[0].element, ElementId(2));
|
||||
assert_eq!(dl.items[1].element, ElementId(1));
|
||||
}
|
||||
@@ -0,0 +1,725 @@
|
||||
//! AniCraft document model (layer L1).
|
||||
//!
|
||||
//! A document is plain data. Time is a function: [`evaluate`] turns a document and a frame into
|
||||
//! a flat [`DisplayList`], which renderers draw. Nothing here mutates during playback.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod easing;
|
||||
mod eval;
|
||||
pub mod path_table;
|
||||
pub mod sample;
|
||||
|
||||
pub use easing::Easing;
|
||||
pub use eval::{DisplayItem, DisplayList, MAX_SYMBOL_DEPTH, evaluate, evaluate_layer_elements};
|
||||
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Straight-alpha sRGB colour, components in `0..=1`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Rgba {
|
||||
pub r: f32,
|
||||
pub g: f32,
|
||||
pub b: f32,
|
||||
pub a: f32,
|
||||
}
|
||||
|
||||
impl Rgba {
|
||||
pub const BLACK: Rgba = Rgba::new(0.0, 0.0, 0.0, 1.0);
|
||||
pub const WHITE: Rgba = Rgba::new(1.0, 1.0, 1.0, 1.0);
|
||||
pub const TRANSPARENT: Rgba = Rgba::new(0.0, 0.0, 0.0, 0.0);
|
||||
|
||||
pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
|
||||
Rgba { r, g, b, a }
|
||||
}
|
||||
/// From `0xRRGGBB`.
|
||||
pub fn hex(rgb: u32) -> Self {
|
||||
Rgba::new(((rgb >> 16) & 0xff) as f32 / 255.0, ((rgb >> 8) & 0xff) as f32 / 255.0, (rgb & 0xff) as f32 / 255.0, 1.0)
|
||||
}
|
||||
pub fn with_alpha(self, a: f32) -> Self {
|
||||
Rgba { a, ..self }
|
||||
}
|
||||
pub fn lerp(self, o: Rgba, t: f32) -> Rgba {
|
||||
use anicraft_geom::lerp;
|
||||
Rgba::new(lerp(self.r, o.r, t), lerp(self.g, o.g, t), lerp(self.b, o.b, t), lerp(self.a, o.a, t))
|
||||
}
|
||||
/// Clamped to `0..=1`, NaN mapped to 0.
|
||||
pub fn sanitized(self) -> Rgba {
|
||||
let c = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
Rgba::new(c(self.r), c(self.g), c(self.b), c(self.a))
|
||||
}
|
||||
pub fn to_hex(self) -> String {
|
||||
let s = self.sanitized();
|
||||
let b = |v: f32| (v * 255.0).round() as u8;
|
||||
format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b))
|
||||
}
|
||||
/// Parses `#rrggbb`, `rrggbb` or `#rrggbbaa`.
|
||||
pub fn parse_hex(s: &str) -> Option<Rgba> {
|
||||
let h = s.trim().trim_start_matches('#');
|
||||
if !h.is_ascii() || (h.len() != 6 && h.len() != 8) {
|
||||
return None;
|
||||
}
|
||||
let byte = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| v as f32 / 255.0);
|
||||
let a = if h.len() == 8 { byte(6)? } else { 1.0 };
|
||||
Some(Rgba::new(byte(0)?, byte(2)?, byte(4)?, a))
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient colour stop.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GradientStop {
|
||||
pub offset: f32,
|
||||
pub color: Rgba,
|
||||
}
|
||||
|
||||
/// How a region is painted. Gradient geometry is in the element's local space.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Paint {
|
||||
Solid(Rgba),
|
||||
Linear { start: Vec2, end: Vec2, stops: Vec<GradientStop> },
|
||||
Radial { center: Vec2, radius: f32, stops: Vec<GradientStop> },
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
/// A representative colour (first stop for gradients) for swatches and the properties panel.
|
||||
pub fn primary_color(&self) -> Rgba {
|
||||
match self {
|
||||
Paint::Solid(c) => *c,
|
||||
Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => stops.first().map_or(Rgba::BLACK, |s| s.color),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lerp(&self, o: &Paint, t: f32) -> Paint {
|
||||
let lerp_stops = |a: &[GradientStop], b: &[GradientStop]| -> Option<Vec<GradientStop>> {
|
||||
(a.len() == b.len()).then(|| {
|
||||
a.iter().zip(b).map(|(x, y)| GradientStop { offset: anicraft_geom::lerp(x.offset, y.offset, t), color: x.color.lerp(y.color, t) }).collect()
|
||||
})
|
||||
};
|
||||
match (self, o) {
|
||||
(Paint::Solid(a), Paint::Solid(b)) => Paint::Solid(a.lerp(*b, t)),
|
||||
(Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => match lerp_stops(a, b) {
|
||||
Some(stops) => Paint::Linear { start: s0.lerp(*s1, t), end: e0.lerp(*e1, t), stops },
|
||||
None => self.clone(),
|
||||
},
|
||||
(Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => match lerp_stops(a, b) {
|
||||
Some(stops) => Paint::Radial { center: c0.lerp(*c1, t), radius: anicraft_geom::lerp(*r0, *r1, t), stops },
|
||||
None => self.clone(),
|
||||
},
|
||||
_ => self.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stroke style. M0: round joins and caps.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Stroke {
|
||||
pub color: Rgba,
|
||||
pub width: f32,
|
||||
}
|
||||
|
||||
/// `Arc` equality that short-circuits on shared pointers. Unchanged subtrees of two document
|
||||
/// versions share their `Arc`s, so comparing versions costs O(changed), not O(document).
|
||||
pub fn arc_eq<T: PartialEq>(a: &Arc<T>, b: &Arc<T>) -> bool {
|
||||
Arc::ptr_eq(a, b) || **a == **b
|
||||
}
|
||||
|
||||
/// [`arc_eq`] over slices.
|
||||
pub fn arcs_eq<T: PartialEq>(a: &[Arc<T>], b: &[Arc<T>]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| arc_eq(x, y))
|
||||
}
|
||||
|
||||
/// Vector shape content.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Shape {
|
||||
#[serde(with = "path_table")]
|
||||
pub path: Arc<Path>,
|
||||
#[serde(default)]
|
||||
pub fill: Option<Paint>,
|
||||
#[serde(default)]
|
||||
pub stroke: Option<Stroke>,
|
||||
#[serde(default)]
|
||||
pub fill_rule: FillRule,
|
||||
}
|
||||
|
||||
impl PartialEq for Shape {
|
||||
fn eq(&self, o: &Shape) -> bool {
|
||||
arc_eq(&self.path, &o.path) && self.fill == o.fill && self.stroke == o.stroke && self.fill_rule == o.fill_rule
|
||||
}
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
pub fn filled(path: Path, fill: Paint) -> Shape {
|
||||
Shape { path: Arc::new(path), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero }
|
||||
}
|
||||
pub fn with_stroke(mut self, color: Rgba, width: f32) -> Shape {
|
||||
self.stroke = Some(Stroke { color, width });
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// How a graphic symbol instance picks its internal frame.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum LoopMode {
|
||||
#[default]
|
||||
Loop,
|
||||
PlayOnce,
|
||||
SingleFrame,
|
||||
}
|
||||
|
||||
impl LoopMode {
|
||||
/// Local frame for `offset` frames into the instance's span.
|
||||
pub fn local_frame(&self, offset: u32, first: u32, len: u32) -> u32 {
|
||||
let len = len.max(1);
|
||||
match self {
|
||||
LoopMode::Loop => first.saturating_add(offset) % len,
|
||||
LoopMode::PlayOnce => first.saturating_add(offset).min(len - 1),
|
||||
LoopMode::SingleFrame => first.min(len - 1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unique id of a symbol in the library.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct SymbolId(pub u64);
|
||||
|
||||
/// Unique id of an element instance within a document.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct ElementId(pub u64);
|
||||
|
||||
/// Unique id of a layer within a document.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct LayerId(pub u64);
|
||||
|
||||
/// What an element draws.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum ElementKind {
|
||||
Shape(Shape),
|
||||
Symbol {
|
||||
symbol: SymbolId,
|
||||
#[serde(default)]
|
||||
loop_mode: LoopMode,
|
||||
#[serde(default)]
|
||||
first_frame: u32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Colour effect applied to an element and everything inside it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ColorEffect {
|
||||
/// Alpha multiplier `0..=1`.
|
||||
pub alpha: f32,
|
||||
/// Tint colour mixed in by `tint_amount`.
|
||||
pub tint: Rgba,
|
||||
pub tint_amount: f32,
|
||||
}
|
||||
|
||||
impl Default for ColorEffect {
|
||||
fn default() -> Self {
|
||||
ColorEffect { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorEffect {
|
||||
/// Effect of `inner` nested inside `self`.
|
||||
pub fn concat(&self, inner: &ColorEffect) -> ColorEffect {
|
||||
// Tints compose by keeping the stronger one; alpha multiplies.
|
||||
let (tint, amount) = if inner.tint_amount >= self.tint_amount { (inner.tint, inner.tint_amount) } else { (self.tint, self.tint_amount) };
|
||||
ColorEffect { alpha: self.alpha * inner.alpha, tint, tint_amount: amount }
|
||||
}
|
||||
pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect {
|
||||
ColorEffect {
|
||||
alpha: anicraft_geom::lerp(self.alpha, o.alpha, t),
|
||||
tint: self.tint.lerp(o.tint, t),
|
||||
tint_amount: anicraft_geom::lerp(self.tint_amount, o.tint_amount, t),
|
||||
}
|
||||
}
|
||||
pub fn apply(&self, c: Rgba) -> Rgba {
|
||||
let k = self.tint_amount.clamp(0.0, 1.0);
|
||||
let mut out = c.lerp(self.tint.with_alpha(c.a), k);
|
||||
out.a = c.a * self.alpha.clamp(0.0, 1.0);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance on a keyframe.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Element {
|
||||
pub id: ElementId,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub transform: Affine,
|
||||
#[serde(default)]
|
||||
pub color: ColorEffect,
|
||||
pub kind: ElementKind,
|
||||
}
|
||||
|
||||
impl Element {
|
||||
/// Local-space bounds (control-point bounds for shapes, `None` for symbols).
|
||||
pub fn local_bounds(&self, doc: &Document) -> Rect {
|
||||
element_bounds(doc, self, &Affine::IDENTITY, 0)
|
||||
}
|
||||
/// Bounds in the parent's space.
|
||||
pub fn bounds(&self, doc: &Document) -> Rect {
|
||||
element_bounds(doc, self, &self.transform, 0)
|
||||
}
|
||||
}
|
||||
|
||||
fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize) -> Rect {
|
||||
if depth > MAX_SYMBOL_DEPTH {
|
||||
return Rect::EMPTY;
|
||||
}
|
||||
match &el.kind {
|
||||
ElementKind::Shape(s) => {
|
||||
let pad = s.stroke.map_or(0.0, |st| st.width * 0.5);
|
||||
s.path.bounds().inflate(pad).transformed(xf)
|
||||
}
|
||||
ElementKind::Symbol { symbol, .. } => {
|
||||
let Some(sym) = doc.symbol(*symbol) else { return Rect::EMPTY };
|
||||
let mut r = Rect::EMPTY;
|
||||
for layer in &sym.timeline.layers {
|
||||
if let Some(kf) = layer.keyframes.first() {
|
||||
for child in &kf.elements {
|
||||
let m = xf.mul(&child.transform);
|
||||
r = r.union(&element_bounds(doc, child, &m, depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tween from a keyframe to the next one.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Tween {
|
||||
#[serde(default)]
|
||||
pub easing: Easing,
|
||||
}
|
||||
|
||||
/// A keyframe and the span of frames it covers.
|
||||
///
|
||||
/// Elements are `Arc`-shared: copying a keyframe (F6), taking an undo snapshot or handing the
|
||||
/// document to the render thread shares them, and editing one element clones only that element
|
||||
/// (`Arc::make_mut`), never its siblings.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Keyframe {
|
||||
/// First frame (0-based).
|
||||
pub start: u32,
|
||||
/// Number of frames covered, at least 1.
|
||||
pub duration: u32,
|
||||
#[serde(default)]
|
||||
pub elements: Vec<Arc<Element>>,
|
||||
#[serde(default)]
|
||||
pub tween: Option<Tween>,
|
||||
#[serde(default)]
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
impl PartialEq for Keyframe {
|
||||
fn eq(&self, o: &Keyframe) -> bool {
|
||||
self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.label == o.label && arcs_eq(&self.elements, &o.elements)
|
||||
}
|
||||
}
|
||||
|
||||
impl Keyframe {
|
||||
pub fn new(start: u32, duration: u32) -> Self {
|
||||
Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, label: String::new() }
|
||||
}
|
||||
/// Mutable access to the elements whose ids satisfy `pick`, cloning only those.
|
||||
pub fn elements_mut_where(&mut self, mut pick: impl FnMut(ElementId) -> bool) -> Vec<&mut Element> {
|
||||
self.elements.iter_mut().filter(|e| pick(e.id)).map(Arc::make_mut).collect()
|
||||
}
|
||||
pub fn end(&self) -> u32 {
|
||||
self.start.saturating_add(self.duration.max(1))
|
||||
}
|
||||
pub fn covers(&self, frame: u32) -> bool {
|
||||
frame >= self.start && frame < self.end()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum LayerKind {
|
||||
#[default]
|
||||
Normal,
|
||||
/// Authoring aid; never rendered in output.
|
||||
Guide,
|
||||
/// Its fills are not drawn: they reveal the layers masked by it (see [`Layer::parent`]).
|
||||
Mask,
|
||||
}
|
||||
|
||||
/// A timeline layer. Keyframes are `Arc`-shared (see [`Keyframe`]).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Layer {
|
||||
pub id: LayerId,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub kind: LayerKind,
|
||||
/// The mask layer this layer is masked by. Masked layers sit directly under their mask, in
|
||||
/// one unbroken run ([`Timeline::repair_masks`] keeps it so); any other link is dropped.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<LayerId>,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
#[serde(default)]
|
||||
pub locked: bool,
|
||||
#[serde(default)]
|
||||
pub outline: bool,
|
||||
#[serde(default = "default_layer_color")]
|
||||
pub color: Rgba,
|
||||
#[serde(default)]
|
||||
pub keyframes: Vec<Arc<Keyframe>>,
|
||||
}
|
||||
|
||||
impl PartialEq for Layer {
|
||||
fn eq(&self, o: &Layer) -> bool {
|
||||
self.id == o.id
|
||||
&& self.name == o.name
|
||||
&& self.kind == o.kind
|
||||
&& self.parent == o.parent
|
||||
&& self.visible == o.visible
|
||||
&& self.locked == o.locked
|
||||
&& self.outline == o.outline
|
||||
&& self.color == o.color
|
||||
&& arcs_eq(&self.keyframes, &o.keyframes)
|
||||
}
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn default_layer_color() -> Rgba {
|
||||
Rgba::hex(0x4fa3ff)
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
pub fn new(id: LayerId, name: impl Into<String>) -> Self {
|
||||
Layer {
|
||||
id,
|
||||
name: name.into(),
|
||||
kind: LayerKind::Normal,
|
||||
parent: None,
|
||||
visible: true,
|
||||
locked: false,
|
||||
outline: false,
|
||||
color: default_layer_color(),
|
||||
keyframes: vec![Arc::new(Keyframe::new(0, 1))],
|
||||
}
|
||||
}
|
||||
/// Mutable keyframe `i` (copy-on-write: clones it only if it is shared).
|
||||
pub fn keyframe_mut(&mut self, i: usize) -> Option<&mut Keyframe> {
|
||||
self.keyframes.get_mut(i).map(Arc::make_mut)
|
||||
}
|
||||
/// Index of the keyframe whose span covers `frame`.
|
||||
pub fn keyframe_index_at(&self, frame: u32) -> Option<usize> {
|
||||
// keyframes are sorted by start: binary search on start, then check the span.
|
||||
let idx = self.keyframes.partition_point(|k| k.start <= frame);
|
||||
let i = idx.checked_sub(1)?;
|
||||
self.keyframes.get(i).filter(|k| k.covers(frame)).map(|_| i)
|
||||
}
|
||||
pub fn keyframe_at(&self, frame: u32) -> Option<&Keyframe> {
|
||||
self.keyframe_index_at(frame).and_then(|i| self.keyframes.get(i)).map(|k| &**k)
|
||||
}
|
||||
/// Index of the keyframe starting exactly at `frame`.
|
||||
pub fn keyframe_starting_at(&self, frame: u32) -> Option<usize> {
|
||||
self.keyframes.iter().position(|k| k.start == frame)
|
||||
}
|
||||
/// One past the last frame with content.
|
||||
pub fn end_frame(&self) -> u32 {
|
||||
self.keyframes.last().map_or(0, |k| k.end())
|
||||
}
|
||||
/// Restores invariants after edits: sorted, durations ≥ 1, no overlaps. Touches (and so
|
||||
/// un-shares) only keyframes whose duration actually changes.
|
||||
pub fn normalize(&mut self) {
|
||||
if !self.keyframes.is_sorted_by_key(|k| k.start) {
|
||||
self.keyframes.sort_by_key(|k| k.start);
|
||||
}
|
||||
self.keyframes.dedup_by_key(|k| k.start);
|
||||
let n = self.keyframes.len();
|
||||
for i in 0..n {
|
||||
let next_start = self.keyframes.get(i + 1).map(|k| k.start);
|
||||
let Some(k) = self.keyframes.get(i) else { continue };
|
||||
let mut want = k.duration.max(1);
|
||||
if let Some(ns) = next_start {
|
||||
want = want.min(ns.saturating_sub(k.start)).max(1);
|
||||
}
|
||||
if want != k.duration
|
||||
&& let Some(k) = self.keyframe_mut(i)
|
||||
{
|
||||
k.duration = want;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An ordered stack of layers. Index 0 is the top layer. Layers are `Arc`-shared.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Timeline {
|
||||
pub layers: Vec<Arc<Layer>>,
|
||||
}
|
||||
|
||||
impl PartialEq for Timeline {
|
||||
fn eq(&self, o: &Timeline) -> bool {
|
||||
arcs_eq(&self.layers, &o.layers)
|
||||
}
|
||||
}
|
||||
|
||||
impl Timeline {
|
||||
/// Number of frames (at least 1).
|
||||
pub fn frame_count(&self) -> u32 {
|
||||
self.layers.iter().map(|l| l.end_frame()).max().unwrap_or(1).max(1)
|
||||
}
|
||||
pub fn layer(&self, id: LayerId) -> Option<&Layer> {
|
||||
self.layers.iter().find(|l| l.id == id).map(|l| &**l)
|
||||
}
|
||||
/// Mutable layer (copy-on-write).
|
||||
pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> {
|
||||
self.layers.iter_mut().find(|l| l.id == id).map(Arc::make_mut)
|
||||
}
|
||||
|
||||
/// The mask that a layer placed at `index` would join: the mask directly above it, or the
|
||||
/// mask of the masked layer directly above it.
|
||||
pub fn mask_above(&self, index: usize) -> Option<LayerId> {
|
||||
let above = self.layers.get(index.checked_sub(1)?)?;
|
||||
match above.kind {
|
||||
LayerKind::Mask => Some(above.id),
|
||||
_ => above.parent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Indices `i..j` of the layer at `i` plus, for a mask layer, the masked layers under it.
|
||||
pub fn group_range(&self, i: usize) -> std::ops::Range<usize> {
|
||||
let Some(l) = self.layers.get(i) else { return i..i };
|
||||
let mut j = i + 1;
|
||||
if l.kind == LayerKind::Mask {
|
||||
while self.layers.get(j).is_some_and(|m| m.parent == Some(l.id)) {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
i..j
|
||||
}
|
||||
|
||||
/// Drops mask links that no longer hold: a masked layer must be a normal layer directly
|
||||
/// under its mask layer or under another layer masked by it. Touches only layers that change.
|
||||
pub fn repair_masks(&mut self) {
|
||||
for i in 0..self.layers.len() {
|
||||
let Some(l) = self.layers.get(i) else { continue };
|
||||
let Some(p) = l.parent else { continue };
|
||||
// (Layers above are already repaired, so `mask_above` sees valid links.)
|
||||
let holds = l.kind == LayerKind::Normal && self.mask_above(i) == Some(p);
|
||||
if !holds && let Some(l) = self.layers.get_mut(i)
|
||||
{
|
||||
Arc::make_mut(l).parent = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum SymbolKind {
|
||||
#[default]
|
||||
Graphic,
|
||||
MovieClip,
|
||||
Button,
|
||||
}
|
||||
|
||||
/// A reusable symbol in the library.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Symbol {
|
||||
// (PartialEq is fast: `Timeline` compares its layers by pointer first.)
|
||||
pub id: SymbolId,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub kind: SymbolKind,
|
||||
pub timeline: Timeline,
|
||||
}
|
||||
|
||||
/// Stage settings.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Stage {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: f32,
|
||||
pub background: Rgba,
|
||||
}
|
||||
|
||||
impl Default for Stage {
|
||||
fn default() -> Self {
|
||||
Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }
|
||||
}
|
||||
}
|
||||
|
||||
/// Largest stage edge accepted from files and commands.
|
||||
pub const MAX_STAGE_EDGE: u32 = 16_384;
|
||||
|
||||
/// A whole AniCraft document: a persistent (structurally shared) tree.
|
||||
///
|
||||
/// `clone()` is O(layers + symbols) pointer copies, which makes undo snapshots and render-thread
|
||||
/// hand-off cheap, and `==` costs O(changed) because shared subtrees compare by pointer.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
#[serde(default)]
|
||||
pub stage: Stage,
|
||||
#[serde(default)]
|
||||
pub timeline: Timeline,
|
||||
#[serde(default)]
|
||||
pub library: Vec<Arc<Symbol>>,
|
||||
/// Next free id for layers, elements and symbols.
|
||||
#[serde(default = "first_id")]
|
||||
pub next_id: u64,
|
||||
}
|
||||
|
||||
fn first_id() -> u64 {
|
||||
1
|
||||
}
|
||||
|
||||
impl PartialEq for Document {
|
||||
fn eq(&self, o: &Document) -> bool {
|
||||
self.stage == o.stage && self.next_id == o.next_id && self.timeline == o.timeline && arcs_eq(&self.library, &o.library)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Document {
|
||||
fn default() -> Self {
|
||||
let mut d = Document { stage: Stage::default(), timeline: Timeline::default(), library: Vec::new(), next_id: 1 };
|
||||
let id = LayerId(d.alloc_id());
|
||||
d.timeline.layers.push(Arc::new(Layer::new(id, "Layer 1")));
|
||||
d
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// A fresh id, unique within this document.
|
||||
pub fn alloc_id(&mut self) -> u64 {
|
||||
let id = self.next_id.max(1);
|
||||
self.next_id = id.saturating_add(1);
|
||||
id
|
||||
}
|
||||
pub fn symbol(&self, id: SymbolId) -> Option<&Symbol> {
|
||||
self.library.iter().find(|s| s.id == id).map(|s| &**s)
|
||||
}
|
||||
pub fn frame_count(&self) -> u32 {
|
||||
self.timeline.frame_count()
|
||||
}
|
||||
/// Repairs a loaded document: ids, sizes and keyframe order.
|
||||
pub fn sanitize(&mut self) {
|
||||
let s = &mut self.stage;
|
||||
s.width = s.width.clamp(1, MAX_STAGE_EDGE);
|
||||
s.height = s.height.clamp(1, MAX_STAGE_EDGE);
|
||||
if !s.fps.is_finite() || s.fps <= 0.0 {
|
||||
s.fps = 24.0;
|
||||
}
|
||||
s.fps = s.fps.clamp(1.0, 240.0);
|
||||
s.background = s.background.sanitized();
|
||||
let mut max_id = 0u64;
|
||||
let scan = |l: &Layer, max_id: &mut u64| {
|
||||
*max_id = (*max_id).max(l.id.0);
|
||||
for k in &l.keyframes {
|
||||
for e in &k.elements {
|
||||
*max_id = (*max_id).max(e.id.0);
|
||||
}
|
||||
}
|
||||
};
|
||||
for l in &mut self.timeline.layers {
|
||||
Arc::make_mut(l).normalize();
|
||||
scan(l, &mut max_id);
|
||||
}
|
||||
self.timeline.repair_masks();
|
||||
for sym in &mut self.library {
|
||||
max_id = max_id.max(sym.id.0);
|
||||
let tl = &mut Arc::make_mut(sym).timeline;
|
||||
for l in &mut tl.layers {
|
||||
Arc::make_mut(l).normalize();
|
||||
scan(l, &mut max_id);
|
||||
}
|
||||
tl.repair_masks();
|
||||
}
|
||||
self.next_id = self.next_id.max(max_id.saturating_add(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keyframe_lookup() {
|
||||
let mut l = Layer::new(LayerId(1), "a");
|
||||
l.keyframes = [Keyframe::new(0, 5), Keyframe::new(5, 3), Keyframe::new(10, 2)].map(Arc::new).to_vec();
|
||||
assert_eq!(l.keyframe_index_at(0), Some(0));
|
||||
assert_eq!(l.keyframe_index_at(4), Some(0));
|
||||
assert_eq!(l.keyframe_index_at(7), Some(1));
|
||||
assert_eq!(l.keyframe_index_at(8), None); // gap
|
||||
assert_eq!(l.keyframe_index_at(11), Some(2));
|
||||
assert_eq!(l.keyframe_index_at(12), None);
|
||||
assert_eq!(l.end_frame(), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_removes_overlap() {
|
||||
let mut l = Layer::new(LayerId(1), "a");
|
||||
l.keyframes = [Keyframe::new(4, 10), Keyframe::new(0, 100)].map(Arc::new).to_vec();
|
||||
l.normalize();
|
||||
assert_eq!(l.keyframes[0].start, 0);
|
||||
assert_eq!(l.keyframes[0].duration, 4);
|
||||
assert_eq!(l.keyframes[1].duration, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_modes() {
|
||||
assert_eq!(LoopMode::Loop.local_frame(7, 0, 5), 2);
|
||||
assert_eq!(LoopMode::PlayOnce.local_frame(7, 0, 5), 4);
|
||||
assert_eq!(LoopMode::SingleFrame.local_frame(7, 3, 5), 3);
|
||||
assert_eq!(LoopMode::Loop.local_frame(u32::MAX, u32::MAX, 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_roundtrip() {
|
||||
let c = Rgba::parse_hex("#ff8000").unwrap();
|
||||
assert_eq!(c.to_hex(), "#ff8000");
|
||||
assert!(Rgba::parse_hex("zz").is_none());
|
||||
assert!(Rgba::parse_hex("ééé").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clones_share_structure_and_edits_copy_only_their_path() {
|
||||
let a = sample::demo();
|
||||
let mut b = a.clone();
|
||||
assert!(a.timeline.layers.iter().zip(&b.timeline.layers).all(|(x, y)| Arc::ptr_eq(x, y)));
|
||||
// Edit one element on the top layer.
|
||||
let layer = Arc::make_mut(&mut b.timeline.layers[0]);
|
||||
let kf = layer.keyframe_mut(1).unwrap();
|
||||
Arc::make_mut(&mut kf.elements[0]).name = "edited".into();
|
||||
assert!(!Arc::ptr_eq(&a.timeline.layers[0], &b.timeline.layers[0]));
|
||||
// siblings stay shared
|
||||
assert!(Arc::ptr_eq(&a.timeline.layers[0].keyframes[0], &b.timeline.layers[0].keyframes[0]));
|
||||
assert!(a.timeline.layers[1..].iter().zip(&b.timeline.layers[1..]).all(|(x, y)| Arc::ptr_eq(x, y)));
|
||||
assert!(a.library.iter().zip(&b.library).all(|(x, y)| Arc::ptr_eq(x, y)));
|
||||
assert_ne!(a, b);
|
||||
// Equal content in fresh allocations still compares equal.
|
||||
let c: Document = serde_json::from_str(&serde_json::to_string(&a).unwrap()).unwrap();
|
||||
assert_eq!(a, c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_does_not_unshare_valid_keyframes() {
|
||||
let a = sample::demo();
|
||||
let mut b = a.clone();
|
||||
let layer = Arc::make_mut(&mut b.timeline.layers[0]);
|
||||
layer.normalize();
|
||||
assert!(a.timeline.layers[0].keyframes.iter().zip(&layer.keyframes).all(|(x, y)| Arc::ptr_eq(x, y)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_repairs_hostile_document() {
|
||||
let mut d = Document::default();
|
||||
d.stage.width = 0;
|
||||
d.stage.fps = f32::NAN;
|
||||
d.next_id = 0;
|
||||
d.sanitize();
|
||||
assert_eq!(d.stage.width, 1);
|
||||
assert_eq!(d.stage.fps, 24.0);
|
||||
assert!(d.next_id > d.timeline.layers[0].id.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Path de-duplication for serialization.
|
||||
//!
|
||||
//! In memory, a shape tweened across many keyframes shares one `Arc<Path>`. Serialized naively,
|
||||
//! every keyframe would repeat the path. Inside [`write_with_paths`], each shared path is written
|
||||
//! once to a table (built by [`build_table`]) and shapes refer to it by index. Inside a
|
||||
//! [`begin_read`] scope the references resolve back to shared `Arc`s, so loading restores the
|
||||
//! sharing (and its memory savings) too.
|
||||
//! Outside those scopes, paths serialize inline, so documents embedded in other JSON still work.
|
||||
|
||||
use crate::{Document, ElementKind};
|
||||
use anicraft_geom::Path;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
enum Ctx {
|
||||
Write { index: HashMap<usize, u32>, paths: Vec<Arc<Path>> },
|
||||
Read { paths: Vec<Arc<Path>> },
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static CTX: RefCell<Option<Ctx>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Clears the context even if serialization unwinds.
|
||||
struct Guard;
|
||||
impl Drop for Guard {
|
||||
fn drop(&mut self) {
|
||||
CTX.with(|c| c.replace(None));
|
||||
}
|
||||
}
|
||||
|
||||
/// Every distinct path of `doc` (main timeline and library), in first-use order. Walking the
|
||||
/// tree up front lets a writer emit the table *before* the document, so readers can stream.
|
||||
pub fn build_table(doc: &Document) -> Vec<Arc<Path>> {
|
||||
let mut seen: HashMap<usize, ()> = HashMap::new();
|
||||
let mut out = Vec::new();
|
||||
let timelines = std::iter::once(&doc.timeline).chain(doc.library.iter().map(|s| &s.timeline));
|
||||
for tl in timelines {
|
||||
for layer in &tl.layers {
|
||||
for k in &layer.keyframes {
|
||||
for e in &k.elements {
|
||||
if let ElementKind::Shape(s) = &e.kind
|
||||
&& seen.insert(Arc::as_ptr(&s.path) as usize, ()).is_none()
|
||||
{
|
||||
out.push(s.path.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs `f` (which serializes a document) with shapes referring to `paths` by index.
|
||||
pub fn write_with_paths<R>(paths: &[Arc<Path>], f: impl FnOnce() -> R) -> R {
|
||||
let index = paths.iter().enumerate().map(|(i, p)| (Arc::as_ptr(p) as usize, i as u32)).collect();
|
||||
CTX.with(|c| c.replace(Some(Ctx::Write { index, paths: paths.to_vec() })));
|
||||
let _guard = Guard;
|
||||
f()
|
||||
}
|
||||
|
||||
/// Scope in which deserialized path references resolve against a table. Clears on drop.
|
||||
pub struct ReadScope(Guard);
|
||||
|
||||
/// Makes `paths` available to path references until the returned scope is dropped.
|
||||
pub fn begin_read(paths: Vec<Arc<Path>>) -> ReadScope {
|
||||
CTX.with(|c| c.replace(Some(Ctx::Read { paths })));
|
||||
ReadScope(Guard)
|
||||
}
|
||||
|
||||
pub fn serialize<S: Serializer>(p: &Arc<Path>, s: S) -> Result<S::Ok, S::Error> {
|
||||
let idx = CTX.with(|c| match &mut *c.borrow_mut() {
|
||||
Some(Ctx::Write { index, paths }) => {
|
||||
let key = Arc::as_ptr(p) as usize;
|
||||
Some(*index.entry(key).or_insert_with(|| {
|
||||
paths.push(p.clone());
|
||||
(paths.len() - 1) as u32
|
||||
}))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
match idx {
|
||||
Some(i) => s.serialize_u32(i),
|
||||
None => p.serialize(s),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Arc<Path>, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Repr {
|
||||
Ref(u32),
|
||||
Inline(Path),
|
||||
}
|
||||
match Repr::deserialize(d)? {
|
||||
Repr::Inline(p) => Ok(Arc::new(p)),
|
||||
Repr::Ref(i) => CTX.with(|c| match &*c.borrow() {
|
||||
Some(Ctx::Read { paths }) => paths.get(i as usize).cloned().ok_or_else(|| serde::de::Error::custom(format!("path reference {i} is out of range"))),
|
||||
_ => Err(serde::de::Error::custom("path reference outside a path table")),
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
//! Generated documents: the demo scene (first launch, tests, `anicraft-cli --sample`) and a
|
||||
//! deterministic stress document for benchmarks. All artwork is simple generated geometry
|
||||
//! (no third-party assets).
|
||||
|
||||
use crate::{
|
||||
ColorEffect, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LoopMode, Paint, Rgba, Shape, Stage, Symbol,
|
||||
SymbolId, SymbolKind, Timeline, Tween,
|
||||
};
|
||||
use anicraft_geom::{Affine, Decomposed, Path, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn stops(cs: &[(f32, u32)]) -> Vec<GradientStop> {
|
||||
cs.iter().map(|&(offset, c)| GradientStop { offset, color: Rgba::hex(c) }).collect()
|
||||
}
|
||||
|
||||
fn el(doc: &mut Document, name: &str, transform: Affine, kind: ElementKind) -> Arc<Element> {
|
||||
Arc::new(Element { id: ElementId(doc.alloc_id()), name: name.into(), transform, color: ColorEffect::default(), kind })
|
||||
}
|
||||
|
||||
fn instance(symbol: SymbolId) -> ElementKind {
|
||||
ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0 }
|
||||
}
|
||||
|
||||
fn pose(tx: f32, ty: f32, sx: f32, sy: f32, rotation_deg: f32) -> Affine {
|
||||
Decomposed { tx, ty, sx, sy, rotation: rotation_deg.to_radians(), skew: 0.0 }.compose()
|
||||
}
|
||||
|
||||
fn layer(id: u64, name: &str, color: u32, keyframes: Vec<Keyframe>) -> Arc<Layer> {
|
||||
let mut l = Layer::new(LayerId(id), name);
|
||||
l.color = Rgba::hex(color);
|
||||
l.keyframes = keyframes.into_iter().map(Arc::new).collect();
|
||||
Arc::new(l)
|
||||
}
|
||||
|
||||
fn key(start: u32, duration: u32, elements: Vec<Arc<Element>>, tween: Option<Easing>) -> Keyframe {
|
||||
let mut k = Keyframe::new(start, duration);
|
||||
k.elements = elements;
|
||||
k.tween = tween.map(|easing| Tween { easing });
|
||||
k
|
||||
}
|
||||
|
||||
/// Builds the demo document: a bouncing ball, a spinning star, a pulsing sun over hills.
|
||||
pub fn demo() -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, timeline: Timeline::default(), library: Vec::new(), next_id: 1 };
|
||||
let (w, h) = (1280.0, 720.0);
|
||||
|
||||
// --- library -------------------------------------------------------------------------
|
||||
let ball_id = SymbolId(d.alloc_id());
|
||||
let ball_shape = Shape::filled(
|
||||
Path::ellipse(0.0, 0.0, 48.0, 48.0),
|
||||
Paint::Radial { center: Vec2::new(-16.0, -18.0), radius: 70.0, stops: stops(&[(0.0, 0xfff1c4), (0.35, 0xff8a3d), (1.0, 0xb3261e)]) },
|
||||
)
|
||||
.with_stroke(Rgba::hex(0x5a1410), 3.0);
|
||||
let ball_el = el(&mut d, "ball body", Affine::IDENTITY, ElementKind::Shape(ball_shape));
|
||||
let ball_layer = layer(d.alloc_id(), "body", 0x4fa3ff, vec![key(0, 1, vec![ball_el], None)]);
|
||||
d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![ball_layer] } }));
|
||||
|
||||
let star_id = SymbolId(d.alloc_id());
|
||||
let star_shape = Shape::filled(Path::star(0.0, 0.0, 60.0, 26.0, 5), Paint::Solid(Rgba::hex(0xfff6a8))).with_stroke(Rgba::hex(0xe0a400), 2.5);
|
||||
let star_el_id = ElementId(d.alloc_id()); // same id across keyframes: one instance over time
|
||||
let star_keys = [0.0f32, 120.0, 240.0, 360.0]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, deg)| {
|
||||
let e = Element { id: star_el_id, name: "star".into(), transform: pose(0.0, 0.0, 1.0, 1.0, deg), color: ColorEffect::default(), kind: ElementKind::Shape(star_shape.clone()) };
|
||||
key(i as u32 * 8, if i == 3 { 1 } else { 8 }, vec![Arc::new(e)], (i < 3).then_some(Easing::Linear))
|
||||
})
|
||||
.collect();
|
||||
let star_layer = layer(d.alloc_id(), "spin", 0x4fa3ff, star_keys);
|
||||
d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![star_layer] } }));
|
||||
|
||||
// --- main timeline (index 0 = top) ---------------------------------------------------
|
||||
const LEN: u32 = 48;
|
||||
|
||||
// Ball: bounces across the stage with squash at each impact.
|
||||
let ball_layer_id = d.alloc_id();
|
||||
let ball_inst = ElementId(d.alloc_id());
|
||||
let poses = [
|
||||
(0u32, (200.0, 260.0, 1.0, 1.0), Easing::QuadIn),
|
||||
(12, (480.0, 572.0, 1.25, 0.78), Easing::QuadOut),
|
||||
(24, (760.0, 270.0, 0.95, 1.05), Easing::QuadIn),
|
||||
(36, (1010.0, 572.0, 1.25, 0.78), Easing::QuadOut),
|
||||
(47, (1160.0, 330.0, 1.0, 1.0), Easing::Linear),
|
||||
];
|
||||
let ball_keys = poses
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &(start, (x, y, sx, sy), easing))| {
|
||||
let next = poses.get(i + 1).map_or(LEN, |p| p.0);
|
||||
let e = Element { id: ball_inst, name: "ball".into(), transform: pose(x, y, sx, sy, 0.0), color: ColorEffect::default(), kind: instance(ball_id) };
|
||||
key(start, next - start, vec![Arc::new(e)], (i + 1 < poses.len()).then_some(easing))
|
||||
})
|
||||
.collect();
|
||||
let ball = layer(ball_layer_id, "Ball", 0xff6b4a, ball_keys);
|
||||
|
||||
// Star: a nested, self-animating graphic symbol.
|
||||
let star_layer_id = d.alloc_id();
|
||||
let star_el = el(&mut d, "star", pose(640.0, 110.0, 0.7, 0.7, 0.0), instance(star_id));
|
||||
let star = layer(star_layer_id, "Star", 0xffd54a, vec![key(0, LEN, vec![star_el], None)]);
|
||||
|
||||
// Sun: pulses with an ease in-out.
|
||||
let sun_layer_id = d.alloc_id();
|
||||
let sun_inst = ElementId(d.alloc_id());
|
||||
let sun_shape = Shape::filled(Path::ellipse(0.0, 0.0, 90.0, 90.0), Paint::Radial { center: Vec2::ZERO, radius: 90.0, stops: stops(&[(0.0, 0xfffbe0), (0.6, 0xffd36b), (1.0, 0xffa94d)]) });
|
||||
let sun_keys = [(0u32, 24u32, 1.0f32), (24, 23, 1.15), (47, 1, 1.0)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (start, dur, s))| {
|
||||
let e = Element { id: sun_inst, name: "sun".into(), transform: pose(1040.0, 150.0, s, s, 0.0), color: ColorEffect::default(), kind: ElementKind::Shape(sun_shape.clone()) };
|
||||
key(start, dur, vec![Arc::new(e)], (i < 2).then_some(Easing::QuadInOut))
|
||||
})
|
||||
.collect();
|
||||
let sun = layer(sun_layer_id, "Sun", 0xffa726, sun_keys);
|
||||
|
||||
// Hills and ground.
|
||||
let hills_id = d.alloc_id();
|
||||
let mut hill_els = Vec::new();
|
||||
for (name, path, c) in [
|
||||
("far hill", Path::ellipse(330.0, 700.0, 520.0, 220.0), 0x4f8f6a),
|
||||
("near hill", Path::ellipse(1010.0, 730.0, 560.0, 230.0), 0x3d7a58),
|
||||
("ground", Path::rect(0.0, 620.0, w, h - 620.0), 0x2f6247),
|
||||
] {
|
||||
hill_els.push(el(&mut d, name, Affine::IDENTITY, ElementKind::Shape(Shape::filled(path, Paint::Solid(Rgba::hex(c))))));
|
||||
}
|
||||
let hills = layer(hills_id, "Hills", 0x66bb6a, vec![key(0, LEN, hill_els, None)]);
|
||||
|
||||
// Sky.
|
||||
let sky_id = d.alloc_id();
|
||||
let sky_el = el(
|
||||
&mut d,
|
||||
"sky",
|
||||
Affine::IDENTITY,
|
||||
ElementKind::Shape(Shape::filled(
|
||||
Path::rect(0.0, 0.0, w, h),
|
||||
Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(0.0, h), stops: stops(&[(0.0, 0x27407a), (0.55, 0x8a79c9), (1.0, 0xf7b98b)]) },
|
||||
)),
|
||||
);
|
||||
let mut sky = layer(sky_id, "Sky", 0x7e57c2, vec![key(0, LEN, vec![sky_el], None)]);
|
||||
Arc::make_mut(&mut sky).locked = true;
|
||||
|
||||
d.timeline.layers = vec![ball, star, sun, hills, sky];
|
||||
d
|
||||
}
|
||||
|
||||
/// Deterministic stress document for benchmarks and scaling tests: `layers` layers with
|
||||
/// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens.
|
||||
/// Every element keeps one `Arc<Path>` across its keyframes, as a real tweened shape does.
|
||||
pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, timeline: Timeline::default(), library: Vec::new(), next_id: 1 };
|
||||
let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000));
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let mut rnd = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
(seed as f32) / (u32::MAX as f32)
|
||||
};
|
||||
for li in 0..layers {
|
||||
let lid = d.alloc_id();
|
||||
let els: Vec<(ElementId, Arc<Path>, Paint, f32, f32)> = (0..shapes)
|
||||
.map(|si| {
|
||||
let r = 6.0 + rnd() * 40.0;
|
||||
let path = match si % 3 {
|
||||
0 => Path::ellipse(0.0, 0.0, r, r * (0.5 + rnd())),
|
||||
1 => Path::star(0.0, 0.0, r, r * 0.45, 5),
|
||||
_ => Path::rounded_rect(-r, -r * 0.6, r * 2.0, r * 1.2, r * 0.2),
|
||||
};
|
||||
let c = Rgba::new(rnd(), rnd(), rnd(), 0.6 + 0.4 * rnd());
|
||||
(ElementId(d.alloc_id()), Arc::new(path), Paint::Solid(c), rnd() * 1920.0, rnd() * 1080.0)
|
||||
})
|
||||
.collect();
|
||||
let mut keys = Vec::new();
|
||||
let mut start = 0;
|
||||
while start < frames {
|
||||
let dur = 12.min(frames - start);
|
||||
let phase = start as f32 * 0.05;
|
||||
let elements = els
|
||||
.iter()
|
||||
.map(|(id, path, fill, x, y)| {
|
||||
let dx = (phase + x * 0.01).sin() * 60.0;
|
||||
let dy = (phase + y * 0.01).cos() * 40.0;
|
||||
Arc::new(Element {
|
||||
id: *id,
|
||||
name: String::new(),
|
||||
transform: pose(x + dx, y + dy, 1.0, 1.0, phase * 20.0),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape { path: path.clone(), fill: Some(fill.clone()), stroke: None, fill_rule: Default::default() }),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
keys.push(key(start, dur, elements, (start + dur < frames).then_some(Easing::QuadInOut)));
|
||||
start += dur;
|
||||
}
|
||||
d.timeline.layers.push(layer(lid, &format!("Layer {}", li + 1), 0x4fa3ff, keys));
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn demo_is_consistent() {
|
||||
let mut d = demo();
|
||||
assert_eq!(d.frame_count(), 48);
|
||||
let before = d.clone();
|
||||
d.sanitize();
|
||||
assert_eq!(d.timeline, before.timeline, "demo must already satisfy invariants");
|
||||
let items = crate::evaluate(&d, 10).items.len();
|
||||
assert!(items >= 7, "{items}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stress_shape() {
|
||||
let d = stress(3, 50, 30);
|
||||
assert_eq!(d.timeline.layers.len(), 3);
|
||||
assert_eq!(d.frame_count(), 30);
|
||||
assert_eq!(crate::evaluate(&d, 7).items.len(), 150);
|
||||
// paths are shared across keyframes
|
||||
let l = &d.timeline.layers[0];
|
||||
let (ElementKind::Shape(a), ElementKind::Shape(b)) = (&l.keyframes[0].elements[0].kind, &l.keyframes[1].elements[0].kind) else { panic!() };
|
||||
assert!(Arc::ptr_eq(&a.path, &b.path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "anicraft-engine"
|
||||
description = "AniCraft L3: session, undo history, command registry and the .anicraft file format"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anicraft-geom.workspace = true
|
||||
anicraft-doc.workspace = true
|
||||
anicraft-render.workspace = true
|
||||
anicraft-xfl.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
rayon.workspace = true
|
||||
gif.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,492 @@
|
||||
//! Drawing, selection, element and symbol commands.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline};
|
||||
use anicraft_geom::{Affine, Decomposed, Path, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("draw.rect", "Rectangle", "", None, "{x, y, w, h, radius?, fill?, stroke?, stroke_width?}", true, draw_rect as crate::RunFn),
|
||||
c("draw.ellipse", "Oval", "", None, "{x, y, w, h, fill?, stroke?, stroke_width?}", true, draw_ellipse),
|
||||
c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?}", true, draw_star),
|
||||
c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?}", true, draw_line),
|
||||
c("edit.select_all", "Select All", "Edit", Some("Ctrl+A"), "{}", false, select_all),
|
||||
c("edit.deselect", "Deselect All", "Edit", Some("Ctrl+Shift+A"), "{}", false, |s, _| {
|
||||
s.selection.clear();
|
||||
Ok(json!({"selected": 0}))
|
||||
}),
|
||||
c("edit.delete", "Clear", "Edit", Some("Delete"), "{}", true, delete),
|
||||
c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?}", true, duplicate),
|
||||
c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool}", false, select),
|
||||
c("element.pick", "Select at Point", "", None, "{x, y, add?: bool}", false, pick),
|
||||
c("element.translate", "Move", "", None, "{dx, dy}", true, translate),
|
||||
c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, set_transform),
|
||||
c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, set_fill),
|
||||
c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?}", true, set_stroke),
|
||||
c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, set_alpha),
|
||||
c("element.rename", "Instance Name", "", None, "{name}", true, rename),
|
||||
c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{}", true, |s, _| arrange(s, true)),
|
||||
c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{}", true, |s, _| arrange_step(s, true)),
|
||||
c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{}", true, |s, _| arrange_step(s, false)),
|
||||
c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{}", true, |s, _| arrange(s, false)),
|
||||
c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?}", true, convert_to_symbol),
|
||||
c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, break_apart),
|
||||
c("library.place", "Place Instance", "", None, "{symbol, x?, y?}", true, place),
|
||||
]
|
||||
}
|
||||
|
||||
// ----- drawing ----------------------------------------------------------------------------
|
||||
|
||||
/// Max path size accepted from params (extent in stage units).
|
||||
pub(crate) const MAX_EXTENT: f32 = 1_000_000.0;
|
||||
|
||||
pub(crate) fn style(s: &Session, p: &Value, closed: bool) -> Result<(Option<Paint>, Option<Stroke>)> {
|
||||
let fill = if !closed || p.get("fill").is_some_and(Value::is_null) {
|
||||
None
|
||||
} else {
|
||||
match opt_color(p, "fill")? {
|
||||
Some(c) => Some(Paint::Solid(c)),
|
||||
None => s.style.use_fill.then_some(Paint::Solid(s.style.fill)),
|
||||
}
|
||||
};
|
||||
let width = match opt_f32(p, "stroke_width")? {
|
||||
Some(w) if (0.0..=1000.0).contains(&w) => w,
|
||||
Some(_) => return Err(EngineError::Param("param 'stroke_width' must be in 0..=1000".into())),
|
||||
None => s.style.stroke_width,
|
||||
};
|
||||
let stroke = if p.get("stroke").is_some_and(Value::is_null) || width <= 0.0 {
|
||||
None
|
||||
} else {
|
||||
match opt_color(p, "stroke")? {
|
||||
Some(c) => Some(Stroke { color: c, width }),
|
||||
None => (s.style.use_stroke || !closed).then_some(Stroke { color: s.style.stroke, width }),
|
||||
}
|
||||
};
|
||||
if fill.is_none() && stroke.is_none() {
|
||||
return Err(EngineError::Param("shape would be invisible: give it a fill or a stroke".into()));
|
||||
}
|
||||
Ok((fill, stroke))
|
||||
}
|
||||
|
||||
fn rect_params(p: &Value) -> Result<(f32, f32, f32, f32)> {
|
||||
let (x, y, w, h) = (f32_req(p, "x")?, f32_req(p, "y")?, f32_req(p, "w")?, f32_req(p, "h")?);
|
||||
if w.abs() < 0.5 || h.abs() < 0.5 {
|
||||
return Err(EngineError::Param("shape is too small (width and height must be at least 0.5)".into()));
|
||||
}
|
||||
if w.abs() > MAX_EXTENT || h.abs() > MAX_EXTENT {
|
||||
return Err(EngineError::Param("shape is too large".into()));
|
||||
}
|
||||
// normalise negative sizes (dragging up/left)
|
||||
Ok((x.min(x + w), y.min(y + h), w.abs(), h.abs()))
|
||||
}
|
||||
|
||||
/// Adds a shape whose local origin is its centre, placed with a translation.
|
||||
pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, fill: Option<Paint>, stroke: Option<Stroke>) -> Result<Value> {
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: Affine::translate(origin.x, origin.y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default() }),
|
||||
};
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() >= 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
}
|
||||
kf.elements.push(Arc::new(el));
|
||||
s.selection = vec![id];
|
||||
Ok(json!({"element": id.0, "kind": name}))
|
||||
}
|
||||
|
||||
fn draw_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (x, y, w, h) = rect_params(p)?;
|
||||
let r = opt_f32(p, "radius")?.unwrap_or(0.0).max(0.0);
|
||||
let (fill, stroke) = style(s, p, true)?;
|
||||
add_shape(s, "rect", Path::rounded_rect(-w / 2.0, -h / 2.0, w, h, r), Vec2::new(x + w / 2.0, y + h / 2.0), fill, stroke)
|
||||
}
|
||||
|
||||
fn draw_ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (x, y, w, h) = rect_params(p)?;
|
||||
let (fill, stroke) = style(s, p, true)?;
|
||||
add_shape(s, "ellipse", Path::ellipse(0.0, 0.0, w / 2.0, h / 2.0), Vec2::new(x + w / 2.0, y + h / 2.0), fill, stroke)
|
||||
}
|
||||
|
||||
fn draw_star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cx, cy, outer) = (f32_req(p, "cx")?, f32_req(p, "cy")?, f32_req(p, "outer")?);
|
||||
if !(0.5..=MAX_EXTENT).contains(&outer) {
|
||||
return Err(EngineError::Param("param 'outer' must be between 0.5 and 1,000,000".into()));
|
||||
}
|
||||
let inner = opt_f32(p, "inner")?.unwrap_or(outer * 0.5).clamp(0.0, MAX_EXTENT);
|
||||
let points = opt_u32(p, "points")?.unwrap_or(5);
|
||||
if !(3..=64).contains(&points) {
|
||||
return Err(EngineError::Param("param 'points' must be between 3 and 64".into()));
|
||||
}
|
||||
let (fill, stroke) = style(s, p, true)?;
|
||||
add_shape(s, "star", Path::star(0.0, 0.0, outer, inner, points), Vec2::new(cx, cy), fill, stroke)
|
||||
}
|
||||
|
||||
fn draw_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Vec2::new(f32_req(p, "x0")?, f32_req(p, "y0")?);
|
||||
let b = Vec2::new(f32_req(p, "x1")?, f32_req(p, "y1")?);
|
||||
if a.distance(b) < 0.5 {
|
||||
return Err(EngineError::Param("line is too short".into()));
|
||||
}
|
||||
let (_, stroke) = style(s, p, false)?;
|
||||
let c = (a + b) * 0.5;
|
||||
add_shape(s, "line", Path::line(a - c, b - c), c, None, stroke)
|
||||
}
|
||||
|
||||
// ----- selection --------------------------------------------------------------------------
|
||||
|
||||
fn select_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.selection = s.visible_elements().iter().map(|e| e.id).collect();
|
||||
Ok(json!({"selected": s.selection.len()}))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = opt_u64_list(p, "ids")?.ok_or_else(|| EngineError::Param("param 'ids' is required".into()))?;
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
let present: Vec<ElementId> = s.visible_elements().iter().map(|e| e.id).collect();
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
for id in ids.into_iter().map(ElementId) {
|
||||
if !present.contains(&id) {
|
||||
return Err(EngineError::State(format!("element {} is not on the active layer at this frame", id.0)));
|
||||
}
|
||||
if !s.selection.contains(&id) {
|
||||
s.selection.push(id);
|
||||
}
|
||||
}
|
||||
Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pt = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
match s.hit_test(pt, 2.0) {
|
||||
Some((layer, el)) => {
|
||||
if layer != s.layer {
|
||||
s.layer = layer;
|
||||
s.selection.clear();
|
||||
}
|
||||
if add {
|
||||
if let Some(i) = s.selection.iter().position(|e| *e == el) {
|
||||
s.selection.remove(i);
|
||||
} else {
|
||||
s.selection.push(el);
|
||||
}
|
||||
} else if !s.selection.contains(&el) {
|
||||
s.selection = vec![el];
|
||||
}
|
||||
Ok(json!({"layer": layer.0, "element": el.0}))
|
||||
}
|
||||
None => {
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
Ok(json!({"element": null}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----- element edits ----------------------------------------------------------------------
|
||||
|
||||
fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (dx, dy) = (f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
let els = s.selected_elements_mut()?;
|
||||
let n = els.len();
|
||||
for e in els {
|
||||
e.transform = Affine::translate(dx, dy).mul(&e.transform);
|
||||
}
|
||||
Ok(json!({"moved": n}))
|
||||
}
|
||||
|
||||
fn set_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let x = opt_f32(p, "x")?;
|
||||
let y = opt_f32(p, "y")?;
|
||||
let sx = opt_f32(p, "sx")?;
|
||||
let sy = opt_f32(p, "sy")?;
|
||||
let rot = opt_f32(p, "rotation")?;
|
||||
for v in [sx, sy].into_iter().flatten() {
|
||||
if v.abs() < 1e-3 || v.abs() > 1000.0 {
|
||||
return Err(EngineError::Param("scale must be between 0.001 and 1000 in magnitude".into()));
|
||||
}
|
||||
}
|
||||
let els = s.selected_elements_mut()?;
|
||||
for e in els {
|
||||
let mut d: Decomposed = e.transform.decompose();
|
||||
if let Some(v) = x {
|
||||
d.tx = v;
|
||||
}
|
||||
if let Some(v) = y {
|
||||
d.ty = v;
|
||||
}
|
||||
if let Some(v) = sx {
|
||||
d.sx = v;
|
||||
}
|
||||
if let Some(v) = sy {
|
||||
d.sy = v;
|
||||
}
|
||||
if let Some(v) = rot {
|
||||
d.rotation = v.to_radians();
|
||||
}
|
||||
e.transform = d.compose();
|
||||
}
|
||||
Ok(json!({"ok": true}))
|
||||
}
|
||||
|
||||
fn shapes_mut(s: &mut Session) -> Result<Vec<&mut Shape>> {
|
||||
let shapes: Vec<&mut Shape> = s
|
||||
.selected_elements_mut()?
|
||||
.into_iter()
|
||||
.filter_map(|e| match &mut e.kind {
|
||||
ElementKind::Shape(sh) => Some(sh),
|
||||
ElementKind::Symbol { .. } => None,
|
||||
})
|
||||
.collect();
|
||||
if shapes.is_empty() {
|
||||
return Err(EngineError::State("the selection has no shapes (symbol instances use alpha/tint)".into()));
|
||||
}
|
||||
Ok(shapes)
|
||||
}
|
||||
|
||||
fn set_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fill = if p.get("color").is_some_and(Value::is_null) {
|
||||
None
|
||||
} else {
|
||||
Some(Paint::Solid(opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' is required".into()))?))
|
||||
};
|
||||
for sh in shapes_mut(s)? {
|
||||
sh.fill = fill.clone();
|
||||
}
|
||||
Ok(json!({"ok": true}))
|
||||
}
|
||||
|
||||
fn set_stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let remove = p.get("color").is_some_and(Value::is_null);
|
||||
let color = opt_color(p, "color")?;
|
||||
let width = opt_f32(p, "width")?;
|
||||
if width.is_some_and(|w| !(0.0..=1000.0).contains(&w)) {
|
||||
return Err(EngineError::Param("param 'width' must be in 0..=1000".into()));
|
||||
}
|
||||
let default = s.style;
|
||||
for sh in shapes_mut(s)? {
|
||||
if remove {
|
||||
sh.stroke = None;
|
||||
continue;
|
||||
}
|
||||
let mut st = sh.stroke.unwrap_or(Stroke { color: default.stroke, width: default.stroke_width });
|
||||
if let Some(c) = color {
|
||||
st.color = c;
|
||||
}
|
||||
if let Some(w) = width {
|
||||
st.width = w;
|
||||
}
|
||||
sh.stroke = (st.width > 0.0).then_some(st);
|
||||
}
|
||||
Ok(json!({"ok": true}))
|
||||
}
|
||||
|
||||
fn set_alpha(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = f32_req(p, "alpha")?;
|
||||
if !(0.0..=1.0).contains(&a) {
|
||||
return Err(EngineError::Param("param 'alpha' must be between 0 and 1".into()));
|
||||
}
|
||||
for e in s.selected_elements_mut()? {
|
||||
e.color.alpha = a;
|
||||
}
|
||||
Ok(json!({"alpha": a}))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name: String = str_req(p, "name")?.chars().take(128).collect();
|
||||
for e in s.selected_elements_mut()? {
|
||||
e.name = name.clone();
|
||||
}
|
||||
Ok(json!({"name": name}))
|
||||
}
|
||||
|
||||
pub(crate) fn delete(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
let before = kf.elements.len();
|
||||
kf.elements.retain(|e| !sel.contains(&e.id));
|
||||
let n = before - kf.elements.len();
|
||||
s.selection.clear();
|
||||
Ok(json!({"deleted": n}))
|
||||
}
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dx = opt_f32(p, "dx")?.unwrap_or(10.0);
|
||||
let dy = opt_f32(p, "dy")?.unwrap_or(10.0);
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
let copies: Vec<Element> = s.editable_keyframe()?.elements.iter().filter(|e| sel.contains(&e.id)).map(|e| (**e).clone()).collect();
|
||||
let mut new_ids = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for mut e in copies {
|
||||
e.id = ElementId(s.doc.alloc_id());
|
||||
e.transform = Affine::translate(dx, dy).mul(&e.transform);
|
||||
new_ids.push(e.id);
|
||||
out.push(Arc::new(e));
|
||||
}
|
||||
s.editable_keyframe()?.elements.extend(out);
|
||||
s.selection = new_ids.clone();
|
||||
Ok(json!({"created": new_ids.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn arrange(s: &mut Session, front: bool) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
let (picked, rest): (Vec<Arc<Element>>, Vec<Arc<Element>>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id));
|
||||
kf.elements = if front { rest.into_iter().chain(picked).collect() } else { picked.into_iter().chain(rest).collect() };
|
||||
Ok(json!({"ok": true}))
|
||||
}
|
||||
|
||||
/// Bring Forward / Send Backward: each selected element swaps with the unselected neighbour
|
||||
/// above (or below) it; a selected block moves as one, keeping its order.
|
||||
fn arrange_step(s: &mut Session, forward: bool) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
let n = kf.elements.len();
|
||||
let picked = |els: &Vec<Arc<Element>>, i: usize| els.get(i).is_some_and(|e| sel.contains(&e.id));
|
||||
if forward {
|
||||
// From the top down, so a selected element never jumps over another selected one.
|
||||
for i in (0..n.saturating_sub(1)).rev() {
|
||||
if picked(&kf.elements, i) && !picked(&kf.elements, i + 1) {
|
||||
kf.elements.swap(i, i + 1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i in 1..n {
|
||||
if picked(&kf.elements, i) && !picked(&kf.elements, i - 1) {
|
||||
kf.elements.swap(i, i - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"ok": true}))
|
||||
}
|
||||
|
||||
// ----- symbols ----------------------------------------------------------------------------
|
||||
|
||||
fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("select something to convert".into()));
|
||||
}
|
||||
let n = s.doc.library.len() + 1;
|
||||
let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}"));
|
||||
let bounds = s.selection_bounds();
|
||||
let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() };
|
||||
let sym_id = SymbolId(s.doc.alloc_id());
|
||||
let layer_id = LayerId(s.doc.alloc_id());
|
||||
let inst_id = ElementId(s.doc.alloc_id());
|
||||
let kf = s.editable_keyframe()?;
|
||||
let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len());
|
||||
let (picked, rest): (Vec<Arc<Element>>, Vec<Arc<Element>>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id));
|
||||
// Children are stored relative to the registration point (the selection centre).
|
||||
let to_local = Affine::translate(-center.x, -center.y);
|
||||
let children: Vec<Arc<Element>> = picked
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let mut e = Arc::unwrap_or_clone(e);
|
||||
e.transform = to_local.mul(&e.transform);
|
||||
Arc::new(e)
|
||||
})
|
||||
.collect();
|
||||
let instance = Element {
|
||||
id: inst_id,
|
||||
name: String::new(),
|
||||
transform: Affine::translate(center.x, center.y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::Loop, first_frame: 0 },
|
||||
};
|
||||
let mut elements = rest;
|
||||
elements.insert(first_pos.min(elements.len()), Arc::new(instance));
|
||||
kf.elements = elements;
|
||||
let mut layer = Layer::new(layer_id, "Layer 1");
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.elements = children;
|
||||
}
|
||||
s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(layer)] } }));
|
||||
s.selection = vec![inst_id];
|
||||
Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name}))
|
||||
}
|
||||
|
||||
fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
let library = s.doc.library.clone();
|
||||
let mut fresh_ids = Vec::new();
|
||||
let kf_elements: Vec<Arc<Element>> = s.editable_keyframe()?.elements.clone();
|
||||
let mut out = Vec::new();
|
||||
for e in kf_elements {
|
||||
let ElementKind::Symbol { symbol, .. } = &e.kind else {
|
||||
out.push(e);
|
||||
continue;
|
||||
};
|
||||
if !sel.contains(&e.id) {
|
||||
out.push(e);
|
||||
continue;
|
||||
}
|
||||
let Some(sym) = library.iter().find(|x| x.id == *symbol) else {
|
||||
out.push(e);
|
||||
continue;
|
||||
};
|
||||
for layer in sym.timeline.layers.iter().rev() {
|
||||
for child in layer.keyframes.first().map(|k| k.elements.as_slice()).unwrap_or(&[]) {
|
||||
let mut c = (**child).clone();
|
||||
c.id = ElementId(s.doc.alloc_id());
|
||||
c.transform = e.transform.mul(&child.transform);
|
||||
c.color = e.color.concat(&child.color);
|
||||
fresh_ids.push(c.id);
|
||||
out.push(Arc::new(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
if fresh_ids.is_empty() {
|
||||
return Err(EngineError::State("the selection has no symbol instances to break apart".into()));
|
||||
}
|
||||
s.editable_keyframe()?.elements = out;
|
||||
s.selection = fresh_ids.clone();
|
||||
Ok(json!({"created": fresh_ids.len()}))
|
||||
}
|
||||
|
||||
fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sym = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?);
|
||||
if s.doc.symbol(sym).is_none() {
|
||||
return Err(EngineError::State(format!("no symbol with id {}", sym.0)));
|
||||
}
|
||||
let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0);
|
||||
let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0);
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: Affine::translate(x, y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Symbol { symbol: sym, loop_mode: LoopMode::Loop, first_frame: 0 },
|
||||
};
|
||||
s.editable_keyframe()?.elements.push(Arc::new(el));
|
||||
s.selection = vec![id];
|
||||
Ok(json!({"element": id.0}))
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! File, edit-history and document commands.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session, format};
|
||||
use anicraft_doc::{Document, MAX_STAGE_EDGE, Stage, sample};
|
||||
use anicraft_render::{View, render};
|
||||
use rayon::prelude::*;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec { id: "file.new", label: "New", menu: "File", shortcut: Some("Ctrl+N"), params: "{width?, height?, fps?}", mutates: false, run: new_doc },
|
||||
CommandSpec { id: "file.new_sample", label: "New from Sample", menu: "File", shortcut: None, params: "{}", mutates: false, run: new_sample },
|
||||
CommandSpec { id: "file.open", label: "Open…", menu: "File", shortcut: Some("Ctrl+O"), params: "{path}", mutates: false, run: open },
|
||||
CommandSpec { id: "file.save", label: "Save", menu: "File", shortcut: Some("Ctrl+S"), params: "{path?, confirm?}", mutates: false, run: save },
|
||||
CommandSpec {
|
||||
id: "file.save_as",
|
||||
label: "Save As…",
|
||||
menu: "File",
|
||||
shortcut: Some("Ctrl+Shift+S"),
|
||||
params: "{path, confirm?}",
|
||||
mutates: false,
|
||||
run: |s, p| {
|
||||
str_req(p, "path")?;
|
||||
save(s, p)
|
||||
},
|
||||
},
|
||||
CommandSpec { id: "file.export_png", label: "Export Frame as PNG…", menu: "File/Export", shortcut: None, params: "{path, frame?, scale?}", mutates: false, run: export_png },
|
||||
CommandSpec {
|
||||
id: "file.export_png_sequence",
|
||||
label: "Export PNG Sequence…",
|
||||
menu: "File/Export",
|
||||
shortcut: None,
|
||||
params: "{dir, from?, to?, scale?}",
|
||||
mutates: false,
|
||||
run: export_sequence,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "file.export_gif",
|
||||
label: "Export Animated GIF…",
|
||||
menu: "File/Export",
|
||||
shortcut: None,
|
||||
params: "{path, from?, to?, scale?, loop?, confirm?}",
|
||||
mutates: false,
|
||||
run: export_gif,
|
||||
},
|
||||
CommandSpec { id: "edit.undo", label: "Undo", menu: "Edit", shortcut: Some("Ctrl+Z"), params: "{}", mutates: false, run: |s, _| s.undo() },
|
||||
CommandSpec { id: "edit.redo", label: "Redo", menu: "Edit", shortcut: Some("Ctrl+Y"), params: "{}", mutates: false, run: |s, _| s.redo() },
|
||||
CommandSpec {
|
||||
id: "doc.set_stage",
|
||||
label: "Document Settings",
|
||||
menu: "Modify",
|
||||
shortcut: None,
|
||||
params: "{width?, height?, fps?, background?: \"#rrggbb\"}",
|
||||
mutates: true,
|
||||
run: set_stage,
|
||||
},
|
||||
CommandSpec { id: "doc.info", label: "Document Info", menu: "", shortcut: None, params: "{}", mutates: false, run: |s, _| Ok(s.info()) },
|
||||
]
|
||||
}
|
||||
|
||||
fn stage_edge(p: &Value, key: &str, default: u32) -> Result<u32> {
|
||||
match opt_u32(p, key)? {
|
||||
None => Ok(default),
|
||||
Some(v) if (1..=MAX_STAGE_EDGE).contains(&v) => Ok(v),
|
||||
Some(_) => Err(EngineError::Param(format!("param '{key}' must be between 1 and {MAX_STAGE_EDGE}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn fps(p: &Value, default: f32) -> Result<f32> {
|
||||
match opt_f32(p, "fps")? {
|
||||
None => Ok(default),
|
||||
Some(f) if (1.0..=240.0).contains(&f) => Ok(f),
|
||||
Some(_) => Err(EngineError::Param("param 'fps' must be between 1 and 240".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_doc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = Stage::default();
|
||||
let mut doc = Document::default();
|
||||
doc.stage.width = stage_edge(p, "width", d.width)?;
|
||||
doc.stage.height = stage_edge(p, "height", d.height)?;
|
||||
doc.stage.fps = fps(p, d.fps)?;
|
||||
s.replace_document(doc, None);
|
||||
Ok(s.info())
|
||||
}
|
||||
|
||||
fn new_sample(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.replace_document(sample::demo(), None);
|
||||
Ok(json!({"frames": s.frame_count()}))
|
||||
}
|
||||
|
||||
/// Whether `path` is an Animate document: a `.fla` archive, an `.xfl` file or an XFL folder.
|
||||
pub fn is_animate(path: &std::path::Path) -> bool {
|
||||
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
matches!(ext.as_deref(), Some("fla" | "xfl")) || (path.is_dir() && path.join("DOMDocument.xml").is_file())
|
||||
}
|
||||
|
||||
fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
if is_animate(&path) {
|
||||
// Imported, not adopted: the document is untitled, so Save asks for a new .anicraft
|
||||
// name and never writes over the Animate file.
|
||||
let (doc, report) = anicraft_xfl::import_path(&path).map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?;
|
||||
s.replace_document(doc, None);
|
||||
let mut info = s.info();
|
||||
info["imported"] = json!(path.display().to_string());
|
||||
info["report"] = json!(report.summary());
|
||||
info["skipped"] = json!(report.skipped);
|
||||
return Ok(info);
|
||||
}
|
||||
let doc = format::load(&path)?;
|
||||
s.replace_document(doc, Some(path));
|
||||
Ok(s.info())
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = match opt_str(p, "path")? {
|
||||
Some(x) => PathBuf::from(x),
|
||||
None => s.path.clone().ok_or_else(|| EngineError::Param("no file name yet: pass {\"path\": …}".into()))?,
|
||||
};
|
||||
format::save(&s.doc, &path)?;
|
||||
s.path = Some(path.clone());
|
||||
s.mark_saved();
|
||||
Ok(json!({"saved": path.display().to_string()}))
|
||||
}
|
||||
|
||||
fn scale_param(p: &Value) -> Result<f32> {
|
||||
match opt_f32(p, "scale")? {
|
||||
None => Ok(1.0),
|
||||
Some(v) if v > 0.0 && v <= 8.0 => Ok(v),
|
||||
Some(_) => Err(EngineError::Param("param 'scale' must be in (0, 8]".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders a frame of the session's document to PNG bytes.
|
||||
pub fn render_png(doc: &Document, frame: u32, scale: f32) -> Result<Vec<u8>> {
|
||||
let dl = anicraft_doc::evaluate(doc, frame);
|
||||
let (pm, _) = render(&dl, &View::stage(doc, scale))?;
|
||||
Ok(pm.encode_png()?)
|
||||
}
|
||||
|
||||
fn export_png(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
|
||||
let bytes = render_png(&s.doc, frame, scale_param(p)?)?;
|
||||
std::fs::write(&path, &bytes)?;
|
||||
Ok(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame}))
|
||||
}
|
||||
|
||||
fn export_sequence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dir = PathBuf::from(str_req(p, "dir")?);
|
||||
let last = s.frame_count().saturating_sub(1);
|
||||
let from = opt_u32(p, "from")?.unwrap_or(0).min(last);
|
||||
let to = opt_u32(p, "to")?.unwrap_or(last).min(last);
|
||||
if to < from {
|
||||
return Err(EngineError::Param("'to' must not be before 'from'".into()));
|
||||
}
|
||||
let scale = scale_param(p)?;
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
// Frames are independent: render and encode them in parallel (each render is itself
|
||||
// row-parallel; rayon balances both levels). Output is identical to a serial export.
|
||||
let doc = &s.doc;
|
||||
let files: Vec<String> = (from..=to)
|
||||
.into_par_iter()
|
||||
.map(|f| {
|
||||
let path = dir.join(format!("frame_{:05}.png", f + 1));
|
||||
std::fs::write(&path, render_png(doc, f, scale)?)?;
|
||||
Ok(path.display().to_string())
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(json!({"frames": files.len(), "dir": dir.display().to_string()}))
|
||||
}
|
||||
|
||||
/// Largest GIF we produce (frames × pixels), keeping memory and time bounded.
|
||||
const MAX_GIF_PIXELS: u64 = 600 * 1280 * 720;
|
||||
|
||||
/// Per-frame delays in 1/100 s that add up to the exact running time (error carried forward),
|
||||
/// never below 2 cs (browsers slow down shorter delays).
|
||||
pub fn gif_delays(frames: usize, fps: f32) -> Vec<u16> {
|
||||
let fps = if fps.is_finite() && fps > 0.0 { fps } else { 24.0 };
|
||||
(0..frames)
|
||||
.map(|i| {
|
||||
let t0 = (i as f64 * 100.0 / f64::from(fps)).round();
|
||||
let t1 = ((i + 1) as f64 * 100.0 / f64::from(fps)).round();
|
||||
((t1 - t0) as u16).max(2)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn export_gif(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
let last = s.frame_count().saturating_sub(1);
|
||||
let from = opt_u32(p, "from")?.unwrap_or(0).min(last);
|
||||
let to = opt_u32(p, "to")?.unwrap_or(last).min(last);
|
||||
if to < from {
|
||||
return Err(EngineError::Param("'to' must not be before 'from'".into()));
|
||||
}
|
||||
let scale = scale_param(p)?;
|
||||
let looping = opt_bool(p, "loop")?.unwrap_or(true);
|
||||
let view = View::stage(&s.doc, scale);
|
||||
let (w, h) = (u16::try_from(view.width), u16::try_from(view.height));
|
||||
let (Ok(w), Ok(h)) = (w, h) else { return Err(EngineError::Param("GIF frames are limited to 65535 px per side".into())) };
|
||||
let n = (to - from + 1) as u64;
|
||||
if n * u64::from(w) * u64::from(h) > MAX_GIF_PIXELS {
|
||||
return Err(EngineError::Param(format!("that GIF would be too large ({n} frames at {w}×{h}); lower 'scale' or the frame range")));
|
||||
}
|
||||
// Render and colour-quantize frames in parallel; encode in order.
|
||||
let doc = &s.doc;
|
||||
let delays = gif_delays(n as usize, doc.stage.fps);
|
||||
let frames: Vec<gif::Frame<'static>> = (from..to.saturating_add(1))
|
||||
.into_par_iter()
|
||||
.zip(delays.into_par_iter())
|
||||
.map(|(f, delay)| {
|
||||
let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?;
|
||||
let mut rgba = pm.to_rgba8();
|
||||
let mut frame = gif::Frame::from_rgba_speed(w, h, &mut rgba, 10);
|
||||
frame.delay = delay;
|
||||
Ok(frame)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let mut bytes = Vec::new();
|
||||
{
|
||||
let mut enc = gif::Encoder::new(&mut bytes, w, h, &[]).map_err(|e| EngineError::Format(e.to_string()))?;
|
||||
if looping {
|
||||
enc.set_repeat(gif::Repeat::Infinite).map_err(|e| EngineError::Format(e.to_string()))?;
|
||||
}
|
||||
for fr in &frames {
|
||||
enc.write_frame(fr).map_err(|e| EngineError::Format(e.to_string()))?;
|
||||
}
|
||||
}
|
||||
std::fs::write(&path, &bytes)?;
|
||||
Ok(json!({"written": path.display().to_string(), "frames": n, "bytes": bytes.len(), "width": w, "height": h}))
|
||||
}
|
||||
|
||||
fn set_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cur = s.doc.stage;
|
||||
s.doc.stage.width = stage_edge(p, "width", cur.width)?;
|
||||
s.doc.stage.height = stage_edge(p, "height", cur.height)?;
|
||||
s.doc.stage.fps = fps(p, cur.fps)?;
|
||||
if let Some(c) = opt_color(p, "background")? {
|
||||
s.doc.stage.background = c;
|
||||
}
|
||||
Ok(json!({"width": s.doc.stage.width, "height": s.doc.stage.height, "fps": s.doc.stage.fps, "background": s.doc.stage.background.to_hex()}))
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Copy, cut and paste frames (Edit › Timeline).
|
||||
//!
|
||||
//! Design notes (principal engineer / senior designer review):
|
||||
//! * Frames have their own clipboard, separate from copied artwork, as in Animate: copying
|
||||
//! frames never replaces copied shapes, and the reverse.
|
||||
//! * A copy is cut exactly at the selection edges by splitting a scratch copy of the layer with
|
||||
//! the same keyframe logic as F6, so a span that starts before the selection, or is
|
||||
//! mid-tween, comes out as it looks there.
|
||||
//! * Paste inserts (later frames move right), which is what Animate's Paste Frames does and so
|
||||
//! what its users expect. Several copied layers land on the target layer and the ones below
|
||||
//! it; missing layers are created. Pasted elements get fresh ids, mapped consistently within
|
||||
//! one paste so tweens between pasted keys still pair up, and symbols they need come along
|
||||
//! (also from another document).
|
||||
|
||||
use crate::cmds_modify::{collect_symbols, import_symbols};
|
||||
use crate::cmds_timeline::{count_param, insert_keyframe_at, remove_frame, shift_after, target, target_layers};
|
||||
use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, Keyframe, Layer, LayerId, Symbol};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("timeline.cut_frames", "Cut Frames", "Edit/Timeline", Some("Ctrl+Alt+X"), "{layer? | layers?: [..], frame?, count?}", true, cut_frames as crate::RunFn),
|
||||
c("timeline.copy_frames", "Copy Frames", "Edit/Timeline", Some("Ctrl+Alt+C"), "{layer? | layers?: [..], frame?, count?}", false, copy_frames),
|
||||
c("timeline.paste_frames", "Paste Frames", "Edit/Timeline", Some("Ctrl+Alt+V"), "{layer?, frame?} (top layer and first frame; default: active layer, playhead)", true, paste_frames),
|
||||
]
|
||||
}
|
||||
|
||||
/// One copied layer's frames; keyframe starts are relative to the first copied frame.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FrameSlice {
|
||||
pub name: String,
|
||||
pub keys: Vec<Arc<Keyframe>>,
|
||||
}
|
||||
|
||||
/// Copied frames: one slice per layer (top to bottom), `count` frames wide.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FrameClipboard {
|
||||
pub layers: Vec<FrameSlice>,
|
||||
pub count: u32,
|
||||
pub symbols: Vec<Arc<Symbol>>,
|
||||
}
|
||||
|
||||
impl FrameClipboard {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.layers.iter().all(|l| l.keys.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyframes covering `frame..frame + count` of `layer`, cut at both edges.
|
||||
fn slice(layer: &Layer, frame: u32, count: u32) -> Result<Vec<Arc<Keyframe>>> {
|
||||
let end = layer.end_frame();
|
||||
if frame >= end {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let stop = frame.saturating_add(count).min(end);
|
||||
let mut l = layer.clone();
|
||||
if l.keyframe_index_at(frame).is_some() {
|
||||
insert_keyframe_at(&mut l, frame, true)?;
|
||||
}
|
||||
if stop < end && l.keyframe_index_at(stop).is_some() {
|
||||
insert_keyframe_at(&mut l, stop, true)?;
|
||||
}
|
||||
Ok(l.keyframes
|
||||
.iter()
|
||||
.filter(|k| k.start >= frame && k.start < stop)
|
||||
.map(|k| {
|
||||
let mut k = (**k).clone();
|
||||
k.duration = k.duration.min(stop - k.start);
|
||||
k.start -= frame;
|
||||
Arc::new(k)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn copy_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (_, frame) = target(s, p)?;
|
||||
let count = count_param(p)?;
|
||||
let mut ids = target_layers(s, p)?;
|
||||
// Top to bottom, whatever order the params gave.
|
||||
let order: Vec<LayerId> = s.doc.timeline.layers.iter().map(|l| l.id).collect();
|
||||
ids.sort_by_key(|id| order.iter().position(|o| o == id));
|
||||
let mut layers = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
let l = s.doc.timeline.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
layers.push(FrameSlice { name: l.name.clone(), keys: slice(l, frame, count)? });
|
||||
}
|
||||
let clip = FrameClipboard { layers, count, symbols: Vec::new() };
|
||||
if clip.is_empty() {
|
||||
return Err(EngineError::State("no frames there to copy".into()));
|
||||
}
|
||||
let elements: Vec<Element> = clip.layers.iter().flat_map(|l| l.keys.iter().flat_map(|k| k.elements.iter().map(|e| (**e).clone()))).collect();
|
||||
let symbols = collect_symbols(s, &elements);
|
||||
let n = clip.layers.len();
|
||||
s.frame_clipboard = FrameClipboard { symbols, ..clip };
|
||||
Ok(json!({"copied": count, "layers": n}))
|
||||
}
|
||||
|
||||
fn cut_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
copy_frames(s, p)?;
|
||||
remove_frame(s, p)?;
|
||||
Ok(json!({"cut": s.frame_clipboard.count, "layers": s.frame_clipboard.layers.len()}))
|
||||
}
|
||||
|
||||
fn paste_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.frame_clipboard.is_empty() {
|
||||
return Err(EngineError::State("no frames have been copied".into()));
|
||||
}
|
||||
let (top, frame) = target(s, p)?;
|
||||
let top = top.unwrap_or(s.layer);
|
||||
let clip = s.frame_clipboard.clone();
|
||||
if frame.saturating_add(clip.count) > MAX_FRAME || s.doc.frame_count().saturating_add(clip.count) > MAX_FRAME {
|
||||
return Err(EngineError::State("the timeline would grow past its maximum length".into()));
|
||||
}
|
||||
let mut row = s.doc.timeline.layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?;
|
||||
import_symbols(s, &clip.symbols);
|
||||
let mut remap: HashMap<ElementId, ElementId> = HashMap::new();
|
||||
let mut pasted = Vec::new();
|
||||
for sl in &clip.layers {
|
||||
// Missing layers below are created, named after the copied ones.
|
||||
if s.doc.timeline.layers.get(row).is_none() {
|
||||
if s.doc.timeline.layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let id = LayerId(s.doc.alloc_id());
|
||||
let mut l = Layer::new(id, sl.name.clone());
|
||||
if !sl.keys.is_empty() {
|
||||
// The pasted keys are its frames (no stray blank frame at 1).
|
||||
l.keyframes.clear();
|
||||
}
|
||||
s.doc.timeline.layers.push(Arc::new(l));
|
||||
}
|
||||
let mut keys = Vec::with_capacity(sl.keys.len());
|
||||
for k in &sl.keys {
|
||||
let mut k = (**k).clone();
|
||||
k.start += frame;
|
||||
for e in &mut k.elements {
|
||||
let old = e.id;
|
||||
let new = *remap.entry(old).or_insert_with(|| ElementId(s.doc.alloc_id()));
|
||||
Arc::make_mut(e).id = new;
|
||||
}
|
||||
keys.push(Arc::new(k));
|
||||
}
|
||||
let Some(layer) = s.doc.timeline.layers.get_mut(row).map(Arc::make_mut) else { continue };
|
||||
if layer.keyframe_index_at(frame).is_some() {
|
||||
insert_keyframe_at(layer, frame, true)?;
|
||||
}
|
||||
shift_after(layer, frame, i64::from(clip.count));
|
||||
layer.keyframes.extend(keys);
|
||||
layer.normalize();
|
||||
pasted.push(layer.id.0);
|
||||
row += 1;
|
||||
}
|
||||
s.selection.clear();
|
||||
Ok(json!({"pasted": clip.count, "layers": pasted}))
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! Clipboard (cut/copy/paste), transforms (free transform, rotate 90°, flip) and alignment.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, Symbol, SymbolId};
|
||||
use anicraft_geom::{Affine, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("edit.cut", "Cut", "Edit", Some("Ctrl+X"), "{}", true, cut as crate::RunFn),
|
||||
c("edit.copy", "Copy", "Edit", Some("Ctrl+C"), "{}", false, copy),
|
||||
c("edit.paste", "Paste in Center", "Edit", Some("Ctrl+V"), "{x?, y?} (centre of the pasted artwork; default: offset 10 px)", true, paste),
|
||||
c("edit.paste_in_place", "Paste in Place", "Edit", Some("Ctrl+Shift+V"), "{}", true, paste_in_place),
|
||||
c("modify.transform", "Transform", "", None, "{a, b, c, d, e, f} affine applied in stage space (free transform)", true, transform),
|
||||
c("modify.rotate_cw", "Rotate 90° CW", "Modify/Transform", Some("Ctrl+Shift+9"), "{}", true, |s, _| about_center(s, Affine::rotate(std::f32::consts::FRAC_PI_2))),
|
||||
c("modify.rotate_ccw", "Rotate 90° CCW", "Modify/Transform", Some("Ctrl+Shift+7"), "{}", true, |s, _| about_center(s, Affine::rotate(-std::f32::consts::FRAC_PI_2))),
|
||||
c("modify.flip_h", "Flip Horizontal", "Modify/Transform", None, "{}", true, |s, _| about_center(s, Affine::scale(-1.0, 1.0))),
|
||||
c("modify.flip_v", "Flip Vertical", "Modify/Transform", None, "{}", true, |s, _| about_center(s, Affine::scale(1.0, -1.0))),
|
||||
c("modify.remove_transform", "Remove Transform", "Modify/Transform", Some("Ctrl+Shift+Z"), "{}", true, remove_transform),
|
||||
c("align.left", "Left", "Modify/Align", Some("Ctrl+Alt+1"), "{to_stage?}", true, |s, p| align(s, p, Edge::Left)),
|
||||
c("align.hcenter", "Horizontal Center", "Modify/Align", Some("Ctrl+Alt+2"), "{to_stage?}", true, |s, p| align(s, p, Edge::HCenter)),
|
||||
c("align.right", "Right", "Modify/Align", Some("Ctrl+Alt+3"), "{to_stage?}", true, |s, p| align(s, p, Edge::Right)),
|
||||
c("align.top", "Top", "Modify/Align", Some("Ctrl+Alt+4"), "{to_stage?}", true, |s, p| align(s, p, Edge::Top)),
|
||||
c("align.vcenter", "Vertical Center", "Modify/Align", Some("Ctrl+Alt+5"), "{to_stage?}", true, |s, p| align(s, p, Edge::VCenter)),
|
||||
c("align.bottom", "Bottom", "Modify/Align", Some("Ctrl+Alt+6"), "{to_stage?}", true, |s, p| align(s, p, Edge::Bottom)),
|
||||
c("align.distribute_h", "Distribute Horizontal Centers", "Modify/Align", None, "{}", true, |s, _| distribute(s, true)),
|
||||
c("align.distribute_v", "Distribute Vertical Centers", "Modify/Align", None, "{}", true, |s, _| distribute(s, false)),
|
||||
]
|
||||
}
|
||||
|
||||
// ----- clipboard --------------------------------------------------------------------------------
|
||||
|
||||
/// Copied artwork: elements as they look at the playhead, plus every symbol they need, so a
|
||||
/// paste into another document is complete.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Clipboard {
|
||||
pub elements: Vec<Element>,
|
||||
pub symbols: Vec<Arc<Symbol>>,
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.elements.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn symbol_refs(e: &Element) -> Option<SymbolId> {
|
||||
match &e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => Some(*symbol),
|
||||
ElementKind::Shape(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbols reachable from `roots` (bounded walk; libraries may be cyclic).
|
||||
pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec<Arc<Symbol>> {
|
||||
let mut seen: HashSet<SymbolId> = HashSet::new();
|
||||
let mut stack: Vec<SymbolId> = roots.iter().filter_map(symbol_refs).collect();
|
||||
let mut out = Vec::new();
|
||||
while let Some(id) = stack.pop() {
|
||||
if !seen.insert(id) || seen.len() > 10_000 {
|
||||
continue;
|
||||
}
|
||||
let Some(sym) = s.doc.library.iter().find(|x| x.id == id) else { continue };
|
||||
for l in &sym.timeline.layers {
|
||||
for k in &l.keyframes {
|
||||
stack.extend(k.elements.iter().filter_map(|e| symbol_refs(e)));
|
||||
}
|
||||
}
|
||||
out.push(sym.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let sel = s.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
// What you see is what you copy: the evaluated state at the playhead (tweens applied).
|
||||
let elements: Vec<Element> = s.visible_elements().iter().filter(|e| sel.contains(&e.id)).map(|e| (**e).clone()).collect();
|
||||
let symbols = collect_symbols(s, &elements);
|
||||
let n = elements.len();
|
||||
s.clipboard = Clipboard { elements, symbols };
|
||||
Ok(json!({"copied": n}))
|
||||
}
|
||||
|
||||
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
copy(s, p)?;
|
||||
crate::cmds_draw::delete(s, p)?;
|
||||
Ok(json!({"cut": s.clipboard.elements.len()}))
|
||||
}
|
||||
|
||||
fn clipboard_bounds(s: &Session) -> Rect {
|
||||
s.clipboard.elements.iter().fold(Rect::EMPTY, |r, e| r.union(&clip_element_bounds(s, e)))
|
||||
}
|
||||
|
||||
fn clip_element_bounds(s: &Session, e: &Element) -> Rect {
|
||||
// Symbols may come from another document: look them up in the clipboard first.
|
||||
let mut doc = s.doc.clone();
|
||||
for sym in &s.clipboard.symbols {
|
||||
if doc.symbol(sym.id).is_none() {
|
||||
doc.library.push(sym.clone());
|
||||
}
|
||||
}
|
||||
e.bounds(&doc)
|
||||
}
|
||||
|
||||
fn paste_with(s: &mut Session, offset: Vec2) -> Result<Value> {
|
||||
if s.clipboard.is_empty() {
|
||||
return Err(EngineError::State("the clipboard is empty".into()));
|
||||
}
|
||||
import_symbols(s, &s.clipboard.symbols.clone());
|
||||
let mut fresh = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for e in s.clipboard.elements.clone() {
|
||||
let mut e = e;
|
||||
e.id = ElementId(s.doc.alloc_id());
|
||||
e.transform = Affine::translate(offset.x, offset.y).mul(&e.transform);
|
||||
fresh.push(e.id);
|
||||
out.push(Arc::new(e));
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() + out.len() > 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
}
|
||||
kf.elements.extend(out);
|
||||
s.selection = fresh.clone();
|
||||
Ok(json!({"pasted": fresh.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Adds the symbols this document lacks (from a clipboard, maybe another document's) and
|
||||
/// moves the id counter past every id they use, so new ids stay unique.
|
||||
pub(crate) fn import_symbols(s: &mut Session, symbols: &[Arc<Symbol>]) {
|
||||
let mut max_id = 0u64;
|
||||
for sym in symbols.iter().cloned() {
|
||||
if s.doc.symbol(sym.id).is_none() {
|
||||
max_id = max_id.max(sym.id.0);
|
||||
for l in &sym.timeline.layers {
|
||||
max_id = max_id.max(l.id.0);
|
||||
for k in &l.keyframes {
|
||||
for e in &k.elements {
|
||||
max_id = max_id.max(e.id.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.doc.library.push(sym);
|
||||
}
|
||||
}
|
||||
s.doc.next_id = s.doc.next_id.max(max_id.saturating_add(1));
|
||||
}
|
||||
|
||||
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let offset = match (opt_f32(p, "x")?, opt_f32(p, "y")?) {
|
||||
(Some(x), Some(y)) => {
|
||||
let b = clipboard_bounds(s);
|
||||
if b.is_empty() { Vec2::new(10.0, 10.0) } else { Vec2::new(x, y) - b.center() }
|
||||
}
|
||||
_ => Vec2::new(10.0, 10.0),
|
||||
};
|
||||
paste_with(s, offset)
|
||||
}
|
||||
|
||||
fn paste_in_place(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
paste_with(s, Vec2::ZERO)
|
||||
}
|
||||
|
||||
// ----- transforms -------------------------------------------------------------------------------
|
||||
|
||||
/// Applies `m` (stage space) to every selected element: `t' = m · t`.
|
||||
pub(crate) fn apply(s: &mut Session, m: &Affine) -> Result<usize> {
|
||||
if !m.is_finite() || m.determinant().abs() < 1e-8 {
|
||||
return Err(EngineError::Param("the transform is degenerate (it would collapse the artwork)".into()));
|
||||
}
|
||||
let els = s.selected_elements_mut()?;
|
||||
let n = els.len();
|
||||
for e in els {
|
||||
let t = m.mul(&e.transform);
|
||||
let d = t.decompose();
|
||||
if !t.is_finite() || d.sx.abs() > 10_000.0 || d.sy.abs() > 10_000.0 || d.sx.abs() < 1e-4 || d.sy.abs() < 1e-4 {
|
||||
return Err(EngineError::Param("the transform would make an element too large or too small".into()));
|
||||
}
|
||||
e.transform = t;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let m = Affine { m: [f32_req(p, "a")?, f32_req(p, "b")?, f32_req(p, "c")?, f32_req(p, "d")?, f32_req(p, "e")?, f32_req(p, "f")?] };
|
||||
let n = apply(s, &m)?;
|
||||
Ok(json!({"transformed": n}))
|
||||
}
|
||||
|
||||
/// `m` applied about the centre of the selection's bounds.
|
||||
/// Remove Transform: scale, rotation and skew go back to none; each element keeps its
|
||||
/// position (registration point).
|
||||
fn remove_transform(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let els = s.selected_elements_mut()?;
|
||||
let n = els.len();
|
||||
for e in els {
|
||||
let t = e.transform.translation();
|
||||
e.transform = Affine::translate(t.x, t.y);
|
||||
}
|
||||
Ok(json!({"reset": n}))
|
||||
}
|
||||
|
||||
fn about_center(s: &mut Session, m: Affine) -> Result<Value> {
|
||||
let b = s.selection_bounds();
|
||||
if b.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
let c = b.center();
|
||||
let full = Affine::translate(c.x, c.y).mul(&m).mul(&Affine::translate(-c.x, -c.y));
|
||||
let n = apply(s, &full)?;
|
||||
Ok(json!({"transformed": n}))
|
||||
}
|
||||
|
||||
// ----- align ------------------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Edge {
|
||||
Left,
|
||||
HCenter,
|
||||
Right,
|
||||
Top,
|
||||
VCenter,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
fn moves_for(bounds: &[(ElementId, Rect)], target: Rect, edge: Edge) -> Vec<(ElementId, Vec2)> {
|
||||
bounds
|
||||
.iter()
|
||||
.map(|(id, b)| {
|
||||
let d = match edge {
|
||||
Edge::Left => Vec2::new(target.min.x - b.min.x, 0.0),
|
||||
Edge::HCenter => Vec2::new(target.center().x - b.center().x, 0.0),
|
||||
Edge::Right => Vec2::new(target.max.x - b.max.x, 0.0),
|
||||
Edge::Top => Vec2::new(0.0, target.min.y - b.min.y),
|
||||
Edge::VCenter => Vec2::new(0.0, target.center().y - b.center().y),
|
||||
Edge::Bottom => Vec2::new(0.0, target.max.y - b.max.y),
|
||||
};
|
||||
(*id, d)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn translate_each(s: &mut Session, moves: &[(ElementId, Vec2)]) -> Result<usize> {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let mut n = 0;
|
||||
for (id, d) in moves {
|
||||
if d.x == 0.0 && d.y == 0.0 {
|
||||
continue; // untouched elements stay shared with the undo snapshot
|
||||
}
|
||||
for e in kf.elements_mut_where(|e| e == *id) {
|
||||
e.transform = Affine::translate(d.x, d.y).mul(&e.transform);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn selected_bounds(s: &Session) -> Vec<(ElementId, Rect)> {
|
||||
s.selection.iter().map(|id| (*id, s.element_bounds(*id))).filter(|(_, b)| !b.is_empty()).collect()
|
||||
}
|
||||
|
||||
fn align(s: &mut Session, p: &Value, edge: Edge) -> Result<Value> {
|
||||
let bounds = selected_bounds(s);
|
||||
if bounds.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
// One element aligns to the stage (there is nothing else to align it with).
|
||||
let to_stage = opt_bool(p, "to_stage")?.unwrap_or(bounds.len() == 1);
|
||||
let target = if to_stage {
|
||||
Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32)
|
||||
} else {
|
||||
bounds.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b))
|
||||
};
|
||||
let moves = moves_for(&bounds, target, edge);
|
||||
let n = translate_each(s, &moves)?;
|
||||
Ok(json!({"moved": n, "to_stage": to_stage}))
|
||||
}
|
||||
|
||||
fn distribute(s: &mut Session, horizontal: bool) -> Result<Value> {
|
||||
let mut bounds = selected_bounds(s);
|
||||
if bounds.len() < 3 {
|
||||
return Err(EngineError::State("select at least three elements to distribute".into()));
|
||||
}
|
||||
let key = |b: &Rect| if horizontal { b.center().x } else { b.center().y };
|
||||
bounds.sort_by(|a, b| key(&a.1).total_cmp(&key(&b.1)));
|
||||
let (Some(first), Some(last)) = (bounds.first(), bounds.last()) else { return Ok(json!({"moved": 0})) };
|
||||
let (a, z) = (key(&first.1), key(&last.1));
|
||||
let step = (z - a) / (bounds.len() - 1) as f32;
|
||||
let moves: Vec<(ElementId, Vec2)> = bounds
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (id, b))| {
|
||||
let d = a + step * i as f32 - key(b);
|
||||
(*id, if horizontal { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) })
|
||||
})
|
||||
.collect();
|
||||
let n = translate_each(s, &moves)?;
|
||||
Ok(json!({"moved": n}))
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
//! Paint Bucket and Ink Bottle.
|
||||
//!
|
||||
//! AniCraft shapes are independent objects (like object drawing), so a fill for an area
|
||||
//! enclosed by several shapes has to be found, not looked up:
|
||||
//!
|
||||
//! 1. Click on a filled shape: it is recoloured.
|
||||
//! 2. Otherwise the active layer at the playhead is rasterized into a "wall" mask with the
|
||||
//! renderer's own coverage rasterizer (fills and stroke outlines), walls are thickened by the
|
||||
//! gap size so small openings close, and the area is flood-filled from the click.
|
||||
//! 3. An area that reaches the edge of the artwork is not enclosed: nothing is added and the
|
||||
//! message suggests a larger gap.
|
||||
//! 4. The region is grown back under the walls (so no hairline shows between fill and line),
|
||||
//! traced into closed contours (`geom::trace`), fitted with curves (`geom::fit_curve`) and
|
||||
//! added as a fill-only shape at the bottom of the layer, below the lines that bound it.
|
||||
//!
|
||||
//! The grid is at most `MAX_GRID` cells on its long side (cell size grows for big artwork), so
|
||||
//! the cost is bounded whatever the document.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, DisplayItem, Element, ElementId, ElementKind, Paint, Shape, Stroke};
|
||||
use anicraft_geom::trace::contours;
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2, fit_curve};
|
||||
use anicraft_render::raster::{Coverage, IRect};
|
||||
use anicraft_render::stroke::stroke_polygons;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("paint.bucket", "Paint Bucket", "", None, "{x, y, color?, gap? (stage units: how wide an opening still counts as closed)}", true, bucket as crate::RunFn),
|
||||
c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?}", true, ink),
|
||||
]
|
||||
}
|
||||
|
||||
/// Longest side of the flood-fill grid, in cells.
|
||||
const MAX_GRID: f32 = 1400.0;
|
||||
|
||||
/// Items of the active layer at the playhead, back to front.
|
||||
fn layer_items(s: &Session) -> Vec<DisplayItem> {
|
||||
s.display_list().items.iter().filter(|i| i.layer == s.layer && i.outline.is_none()).cloned().collect()
|
||||
}
|
||||
|
||||
/// Topmost item of the active layer under `p`: `(element, inside its fill)`.
|
||||
fn pick(items: &[DisplayItem], p: Vec2, slop: f32) -> Option<(ElementId, bool)> {
|
||||
items.iter().rev().find_map(|it| {
|
||||
let hw = it.stroke.map_or(0.0, |s| s.width * 0.5 * it.transform.mean_scale());
|
||||
if !it.path.bounds().transformed(&it.transform).inflate(hw + slop).contains(p) {
|
||||
return None;
|
||||
}
|
||||
let inside = it.fill.is_some() && it.path.contains(p, &it.transform, it.fill_rule);
|
||||
(inside || it.path.distance_to_edge(p, &it.transform) <= hw + slop).then_some((it.element, inside))
|
||||
})
|
||||
}
|
||||
|
||||
fn element_shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let el = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State("that shape is not on the active layer at this frame".into()))?;
|
||||
match &mut el.kind {
|
||||
ElementKind::Shape(sh) => Ok(sh),
|
||||
ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances keep their own colours; break it apart (Ctrl+B) or edit the symbol to paint it".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let color = opt_color(p, "color")?.unwrap_or(s.style.fill);
|
||||
let gap = opt_f32(p, "gap")?.unwrap_or(0.0);
|
||||
if !(0.0..=1000.0).contains(&gap) {
|
||||
return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into()));
|
||||
}
|
||||
let items = layer_items(s);
|
||||
// 1. On a fill: recolour it.
|
||||
if let Some((id, true)) = pick(&items, at, 0.0) {
|
||||
element_shape_mut(s, id)?.fill = Some(Paint::Solid(color));
|
||||
return Ok(json!({"recolored": id.0}));
|
||||
}
|
||||
// 2. Find the enclosed area.
|
||||
let Some(path) = enclosed_region(&items, at, gap)? else {
|
||||
return Err(EngineError::State("this area isn't closed. Close the outline, or choose a larger gap size".into()));
|
||||
};
|
||||
let c = path.bounds().center();
|
||||
let local = path.transformed(&Affine::translate(-c.x, -c.y));
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: Affine::translate(c.x, c.y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(Paint::Solid(color)), stroke: None, fill_rule: FillRule::EvenOdd }),
|
||||
};
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() >= 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
}
|
||||
// Under everything on the layer, so the lines that bound it stay on top.
|
||||
kf.elements.insert(0, Arc::new(el));
|
||||
Ok(json!({"element": id.0}))
|
||||
}
|
||||
|
||||
/// Grid over stage space: origin and cell size.
|
||||
struct Grid {
|
||||
origin: Vec2,
|
||||
cell: f32,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
fn to_px(&self) -> Affine {
|
||||
Affine::scale(1.0 / self.cell, 1.0 / self.cell).mul(&Affine::translate(-self.origin.x, -self.origin.y))
|
||||
}
|
||||
}
|
||||
|
||||
/// The area around `at` enclosed by the layer's artwork, as a stage-space path; `None` when it
|
||||
/// is not enclosed (or there is no artwork around it).
|
||||
fn enclosed_region(items: &[DisplayItem], at: Vec2, gap: f32) -> Result<Option<Path>> {
|
||||
let mut bounds = Rect::EMPTY;
|
||||
for it in items {
|
||||
let pad = it.stroke.map_or(0.0, |s| s.width * 0.5 * it.transform.mean_scale());
|
||||
bounds = bounds.union(&it.path.bounds().inflate(pad).transformed(&it.transform));
|
||||
}
|
||||
if bounds.is_empty() || !bounds.contains(at) || !(bounds.min.is_finite() && bounds.max.is_finite()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let extent = bounds.width().max(bounds.height());
|
||||
let cell = (extent / MAX_GRID).max(0.5);
|
||||
// One free cell of margin all round: anything that reaches it is outside.
|
||||
let origin = bounds.min - Vec2::new(cell, cell);
|
||||
let w = (bounds.width() / cell).ceil() as usize + 3;
|
||||
let h = (bounds.height() / cell).ceil() as usize + 3;
|
||||
let g = Grid { origin, cell };
|
||||
let m = g.to_px();
|
||||
let mut wall = vec![0.0f32; w * h];
|
||||
let mut row = Vec::new();
|
||||
for it in items {
|
||||
let to_px = m.mul(&it.transform);
|
||||
let mut polys: Vec<(Vec<Vec<Vec2>>, FillRule)> = Vec::new();
|
||||
let lines = it.path.flatten(&to_px, 0.2);
|
||||
if it.fill.is_some() {
|
||||
polys.push((lines.iter().map(|l| l.points.clone()).collect(), it.fill_rule));
|
||||
}
|
||||
if let Some(st) = it.stroke {
|
||||
let hw = (st.width * 0.5 * it.transform.mean_scale() / cell).max(0.5);
|
||||
polys.push((stroke_polygons(&lines, hw), FillRule::NonZero));
|
||||
}
|
||||
for (pp, rule) in polys {
|
||||
let mut bb = Rect::EMPTY;
|
||||
for q in pp.iter().flatten() {
|
||||
bb.include(*q);
|
||||
}
|
||||
if bb.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let ir = IRect { x0: (bb.min.x.floor() as i32).max(0), y0: (bb.min.y.floor() as i32).max(0), x1: (bb.max.x.ceil() as i32 + 1).min(w as i32), y1: (bb.max.y.ceil() as i32 + 1).min(h as i32) };
|
||||
if ir.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut cov = Coverage::new(ir);
|
||||
for poly in &pp {
|
||||
cov.add_polygon(poly);
|
||||
}
|
||||
row.resize(ir.width(), 0.0);
|
||||
for y in 0..ir.height() {
|
||||
cov.resolve_row(y, rule, &mut row);
|
||||
let base = (ir.y0 as usize + y) * w + ir.x0 as usize;
|
||||
for (x, v) in row.iter().enumerate() {
|
||||
if let Some(cellv) = wall.get_mut(base + x) {
|
||||
*cellv = cellv.max(*v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Any coverage is a wall, so hairlines cannot leak; then close gaps.
|
||||
let mut blocked: Vec<bool> = wall.iter().map(|v| *v > 0.02).collect();
|
||||
let gap_cells = gap / cell * 0.5;
|
||||
if gap_cells > 0.0 {
|
||||
let d = distance(&blocked, w, h);
|
||||
for (b, dv) in blocked.iter_mut().zip(&d) {
|
||||
*b = *dv <= gap_cells;
|
||||
}
|
||||
}
|
||||
// Flood fill from the click.
|
||||
let cx = ((at.x - origin.x) / cell) as usize;
|
||||
let cy = ((at.y - origin.y) / cell) as usize;
|
||||
let start = cy * w + cx;
|
||||
if blocked.get(start).copied().unwrap_or(true) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut region = vec![false; w * h];
|
||||
let mut q = VecDeque::from([start]);
|
||||
if let Some(r) = region.get_mut(start) {
|
||||
*r = true;
|
||||
}
|
||||
while let Some(i) = q.pop_front() {
|
||||
let (x, y) = (i % w, i / w);
|
||||
if x == 0 || y == 0 || x + 1 >= w || y + 1 >= h {
|
||||
// Reached the margin: open to the outside.
|
||||
return Ok(None);
|
||||
}
|
||||
for n in [i - 1, i + 1, i - w, i + w] {
|
||||
if !blocked.get(n).copied().unwrap_or(true) && !region.get(n).copied().unwrap_or(true) {
|
||||
if let Some(r) = region.get_mut(n) {
|
||||
*r = true;
|
||||
}
|
||||
q.push_back(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Grow back: free cells up to the closed gap (the wall thickening took them), and cells
|
||||
// under a line a little further, so the fill tucks under its outline. Never into open space
|
||||
// beyond a line.
|
||||
let d = distance(®ion, w, h);
|
||||
let mask: Vec<f32> = d
|
||||
.iter()
|
||||
.zip(&wall)
|
||||
.map(|(dv, wv)| {
|
||||
let under_line = *wv > 0.02;
|
||||
let keep = *dv == 0.0 || (!under_line && *dv <= gap_cells) || (under_line && *dv <= gap_cells + 1.5);
|
||||
if keep { 1.0 } else { 0.0 }
|
||||
})
|
||||
.collect();
|
||||
let loops = contours(&mask, w, h);
|
||||
if loops.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut path = Path::new();
|
||||
for lp in loops {
|
||||
let pts: Vec<Vec2> = lp.iter().map(|q| origin + *q * cell).collect();
|
||||
let part = fit_curve(&pts, (cell * 0.6).max(0.25), cell * 3.0, true);
|
||||
path.cmds.extend(part.cmds);
|
||||
}
|
||||
Ok((!path.is_empty()).then_some(path))
|
||||
}
|
||||
|
||||
/// Distance in cells from each cell to the nearest `true` cell (two-pass 3-4 chamfer, ≈ 2 %
|
||||
/// from Euclidean).
|
||||
fn distance(src: &[bool], w: usize, h: usize) -> Vec<f32> {
|
||||
const FAR: f32 = 1e9;
|
||||
let mut d: Vec<f32> = src.iter().map(|b| if *b { 0.0 } else { FAR }).collect();
|
||||
let (a, b) = (1.0f32, 4.0f32 / 3.0);
|
||||
let at = |d: &Vec<f32>, x: isize, y: isize| -> f32 {
|
||||
if x < 0 || y < 0 || x as usize >= w || y as usize >= h { FAR } else { d.get(y as usize * w + x as usize).copied().unwrap_or(FAR) }
|
||||
};
|
||||
for y in 0..h as isize {
|
||||
for x in 0..w as isize {
|
||||
let i = y as usize * w + x as usize;
|
||||
let v = d.get(i).copied().unwrap_or(FAR).min(at(&d, x - 1, y) + a).min(at(&d, x, y - 1) + a).min(at(&d, x - 1, y - 1) + b).min(at(&d, x + 1, y - 1) + b);
|
||||
if let Some(c) = d.get_mut(i) {
|
||||
*c = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in (0..h as isize).rev() {
|
||||
for x in (0..w as isize).rev() {
|
||||
let i = y as usize * w + x as usize;
|
||||
let v = d.get(i).copied().unwrap_or(FAR).min(at(&d, x + 1, y) + a).min(at(&d, x, y + 1) + a).min(at(&d, x + 1, y + 1) + b).min(at(&d, x - 1, y + 1) + b);
|
||||
if let Some(c) = d.get_mut(i) {
|
||||
*c = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
fn ink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let color = opt_color(p, "color")?.unwrap_or(s.style.stroke);
|
||||
let width = opt_f32(p, "width")?.unwrap_or(s.style.stroke_width.max(1.0));
|
||||
if !(0.1..=1000.0).contains(&width) {
|
||||
return Err(EngineError::Param("param 'width' must be between 0.1 and 1000".into()));
|
||||
}
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(3.0).clamp(0.0, 100.0);
|
||||
let items = layer_items(s);
|
||||
let (id, _) = pick(&items, at, slop).ok_or_else(|| EngineError::State("click a shape to give it this stroke".into()))?;
|
||||
element_shape_mut(s, id)?.stroke = Some(Stroke { color, width });
|
||||
Ok(json!({"element": id.0}))
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! Path drawing (Pen, Pencil) and point editing (Subselection).
|
||||
//!
|
||||
//! Points are addressed as `(cmd, slot)` on the shape's path in its local space: slot 0 is the
|
||||
//! anchor a command ends on, 1 and 2 its control points (`anicraft_geom::edit`). A closed
|
||||
//! subpath's start is one anchor even though the path stores it twice; commands accept either
|
||||
//! copy. Deltas and positions in params are in stage space.
|
||||
|
||||
use crate::cmds_draw::{MAX_EXTENT, add_shape, style};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, Shape};
|
||||
use anicraft_geom::edit::{ANCHOR, polyline_path, simplify};
|
||||
use anicraft_geom::{Affine, Path, PathCmd, Vec2, fit_curve};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("draw.path", "Pen Path", "", None, "{d: SVG path data (stage space), fill?, stroke?, stroke_width?}", true, draw_path as crate::RunFn),
|
||||
c(
|
||||
"draw.freehand",
|
||||
"Pencil Stroke",
|
||||
"",
|
||||
None,
|
||||
"{points: [[x, y], ..], mode?: \"smooth\"|\"straighten\"|\"ink\", tolerance? (stage units), closed?, stroke?, stroke_width?}",
|
||||
true,
|
||||
draw_freehand,
|
||||
),
|
||||
c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy}", true, move_points),
|
||||
c("path.add_point", "Add Anchor Point", "", None, "{id, x, y, slop?}", true, add_point),
|
||||
c("path.delete_points", "Delete Anchor Points", "", None, "{id, cmds: [..]}", true, delete_points),
|
||||
c("path.convert_point", "Convert Anchor Point", "", None, "{id, cmd, smooth: bool}", true, convert_point),
|
||||
]
|
||||
}
|
||||
|
||||
/// Most commands one path may have (keeps one edit's cost bounded).
|
||||
const MAX_CMDS: usize = 100_000;
|
||||
|
||||
fn check_path(path: &Path) -> Result<()> {
|
||||
if path.cmds.len() > MAX_CMDS {
|
||||
return Err(EngineError::Param(format!("path has more than {MAX_CMDS} commands")));
|
||||
}
|
||||
if path.anchors().len() < 2 {
|
||||
return Err(EngineError::Param("a path needs at least two points".into()));
|
||||
}
|
||||
let b = path.bounds();
|
||||
if !(b.min.is_finite() && b.max.is_finite()) || b.width() > MAX_EXTENT || b.height() > MAX_EXTENT {
|
||||
return Err(EngineError::Param("path is too large".into()));
|
||||
}
|
||||
if b.width().max(b.height()) < 0.5 {
|
||||
return Err(EngineError::Param("path is too small".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds a stage-space path as a shape whose local origin is its bounds centre.
|
||||
fn add_path(s: &mut Session, kind: &str, mut path: Path, p: &Value) -> Result<Value> {
|
||||
check_path(&path)?;
|
||||
path.close_explicitly();
|
||||
let closed = path.cmds.iter().any(|c| matches!(c, PathCmd::Close));
|
||||
let (fill, stroke) = style(s, p, closed)?;
|
||||
let c = path.bounds().center();
|
||||
let local = path.transformed(&Affine::translate(-c.x, -c.y));
|
||||
add_shape(s, kind, local, c, fill, stroke)
|
||||
}
|
||||
|
||||
fn draw_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = str_req(p, "d")?;
|
||||
if d.len() > 4_000_000 {
|
||||
return Err(EngineError::Param("param 'd' is too long".into()));
|
||||
}
|
||||
let path = Path::from_svg(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?;
|
||||
add_path(s, "path", path, p)
|
||||
}
|
||||
|
||||
fn points_param(p: &Value, key: &str) -> Result<Vec<Vec2>> {
|
||||
let bad = || EngineError::Param(format!("param '{key}' must be a list of [x, y] pairs"));
|
||||
let list = p.get(key).and_then(Value::as_array).ok_or_else(bad)?;
|
||||
if list.len() > MAX_CMDS {
|
||||
return Err(EngineError::Param(format!("param '{key}' has more than {MAX_CMDS} points")));
|
||||
}
|
||||
list.iter()
|
||||
.map(|v| {
|
||||
let xy = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?;
|
||||
let n = |i: usize| xy.get(i).and_then(Value::as_f64).map(|f| f as f32).filter(|f| f.is_finite()).ok_or_else(bad);
|
||||
Ok(Vec2::new(n(0)?, n(1)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Pencil: "smooth" fits curves, "straighten" keeps the stroke's main straight runs, "ink"
|
||||
/// follows the hand closely with short straight segments.
|
||||
fn draw_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = points_param(p, "points")?;
|
||||
let tol = opt_f32(p, "tolerance")?.unwrap_or(1.5);
|
||||
if !(0.01..=1000.0).contains(&tol) {
|
||||
return Err(EngineError::Param("param 'tolerance' must be between 0.01 and 1000".into()));
|
||||
}
|
||||
let closed = opt_bool(p, "closed")?.unwrap_or(false);
|
||||
let path = match opt_str(p, "mode")?.unwrap_or("smooth") {
|
||||
"smooth" => fit_curve(&pts, tol, tol * 2.0, closed),
|
||||
"straighten" => polyline_path(&simplify(&pts, tol * 4.0), closed),
|
||||
"ink" => polyline_path(&simplify(&pts, tol * 0.35), closed),
|
||||
other => return Err(EngineError::Param(format!("unknown pencil mode '{other}' (smooth, straighten or ink)"))),
|
||||
};
|
||||
// A pencil stroke is a line: no fill unless it was closed and a fill was asked for.
|
||||
let mut style_params = p.clone();
|
||||
if !(closed && p.get("fill").is_some()) {
|
||||
style_params["fill"] = Value::Null;
|
||||
}
|
||||
add_path(s, "pencil", path, &style_params)
|
||||
}
|
||||
|
||||
// ----- point editing ----------------------------------------------------------------------
|
||||
|
||||
/// The shape element `id` in the editable keyframe (copy-on-write), with its transform.
|
||||
fn shape_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Shape, Affine)> {
|
||||
let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?);
|
||||
if !s.visible_elements().iter().any(|e| e.id == id) {
|
||||
return Err(EngineError::State(format!("element {} is not on the active layer at this frame", id.0)));
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
let el: &mut Element = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?;
|
||||
let m = el.transform;
|
||||
match &mut el.kind {
|
||||
ElementKind::Shape(sh) => Ok((sh, m)),
|
||||
ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances have no points to edit (double-click to edit the symbol)".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn index_list(p: &Value, key: &str) -> Result<Vec<usize>> {
|
||||
let v = opt_u64_list(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required")))?;
|
||||
Ok(v.into_iter().map(|i| usize::try_from(i).unwrap_or(usize::MAX)).collect())
|
||||
}
|
||||
|
||||
fn move_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
let bad = || EngineError::Param("param 'points' must be a list of [cmd, slot] pairs".into());
|
||||
let list = p.get("points").and_then(Value::as_array).ok_or_else(bad)?;
|
||||
let mut wanted = Vec::with_capacity(list.len().min(MAX_CMDS));
|
||||
for v in list.iter().take(MAX_CMDS) {
|
||||
let pair = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?;
|
||||
let cmd = pair.first().and_then(Value::as_u64).ok_or_else(bad)?;
|
||||
let slot = pair.get(1).and_then(Value::as_u64).filter(|s| *s <= 2).ok_or_else(bad)?;
|
||||
wanted.push((usize::try_from(cmd).unwrap_or(usize::MAX), slot as u8));
|
||||
}
|
||||
let (sh, m) = shape_mut(s, p)?;
|
||||
let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?;
|
||||
let local = inv.apply_vector(d);
|
||||
if !local.is_finite() {
|
||||
return Err(EngineError::Param("the move is too large".into()));
|
||||
}
|
||||
let path = Arc::make_mut(&mut sh.path);
|
||||
// Anchors bring their handles and their twin at a closed start; each point moves once.
|
||||
let mut set = BTreeSet::new();
|
||||
for (cmd, slot) in wanted {
|
||||
if path.point(cmd, slot).is_none() {
|
||||
return Err(EngineError::Param(format!("no point ({cmd}, {slot}) on this path")));
|
||||
}
|
||||
if slot == ANCHOR {
|
||||
set.extend(path.anchor_group(cmd));
|
||||
} else {
|
||||
set.insert((cmd, slot));
|
||||
}
|
||||
}
|
||||
for &(cmd, slot) in &set {
|
||||
if let Some(q) = path.point(cmd, slot) {
|
||||
path.set_point(cmd, slot, q + local);
|
||||
}
|
||||
}
|
||||
check_path(path)?;
|
||||
Ok(json!({"moved": set.len()}))
|
||||
}
|
||||
|
||||
fn add_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 1000.0);
|
||||
let (sh, m) = shape_mut(s, p)?;
|
||||
let path = Arc::make_mut(&mut sh.path);
|
||||
path.close_explicitly();
|
||||
let (cmd, t, dist) = path.nearest_segment(at, &m).ok_or_else(|| EngineError::State("the path has no segments".into()))?;
|
||||
if dist > slop {
|
||||
return Err(EngineError::State("no segment there".into()));
|
||||
}
|
||||
if path.cmds.len() >= MAX_CMDS || !path.split_segment(cmd, t) {
|
||||
return Err(EngineError::State("cannot add a point there".into()));
|
||||
}
|
||||
Ok(json!({"cmd": cmd}))
|
||||
}
|
||||
|
||||
fn delete_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmds = index_list(p, "cmds")?;
|
||||
let (sh, _) = shape_mut(s, p)?;
|
||||
let path = Arc::make_mut(&mut sh.path);
|
||||
// Highest first, so earlier indices stay valid; twins collapse onto one anchor.
|
||||
let order: BTreeSet<usize> = cmds.iter().map(|&c| path.canonical_anchor(c)).collect();
|
||||
let mut removed = 0;
|
||||
for cmd in order.into_iter().rev() {
|
||||
if path.remove_anchor(cmd) {
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
if removed == 0 {
|
||||
return Err(EngineError::State("a path keeps at least two points (delete the shape instead)".into()));
|
||||
}
|
||||
Ok(json!({"deleted": removed}))
|
||||
}
|
||||
|
||||
fn convert_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?;
|
||||
let cmd = usize::try_from(cmd).unwrap_or(usize::MAX);
|
||||
let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required".into()))?;
|
||||
let (sh, _) = shape_mut(s, p)?;
|
||||
let path = Arc::make_mut(&mut sh.path);
|
||||
if path.point(cmd, ANCHOR).is_none() {
|
||||
return Err(EngineError::Param(format!("no anchor {cmd} on this path")));
|
||||
}
|
||||
let changed = if smooth { path.make_smooth(cmd) } else { path.make_corner(cmd) };
|
||||
Ok(json!({"changed": changed}))
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
//! Timeline and layer commands.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session};
|
||||
use anicraft_doc::{Keyframe, Layer, LayerId, LayerKind, Tween, evaluate_layer_elements};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("timeline.insert_frame", "Frame", "Insert/Timeline", Some("F5"), "{layer? | layers?: [..], frame?, count?}", true, insert_frame as crate::RunFn),
|
||||
c("timeline.remove_frame", "Remove Frame", "Insert/Timeline", Some("Shift+F5"), "{layer? | layers?: [..], frame?, count?}", true, remove_frame),
|
||||
c("timeline.insert_keyframe", "Keyframe", "Insert/Timeline", Some("F6"), "{layer? | layers?: [..], frame?}", true, insert_keyframe),
|
||||
c("timeline.insert_blank_keyframe", "Blank Keyframe", "Insert/Timeline", Some("F7"), "{layer? | layers?: [..], frame?}", true, insert_blank_keyframe),
|
||||
c("timeline.clear_keyframe", "Clear Keyframe", "Insert/Timeline", Some("Shift+F6"), "{layer? | layers?: [..], frame?, count?}", true, clear_keyframe),
|
||||
c("timeline.move_keyframes", "Move Keyframes", "", None, "{layer? | layers?: [..], from, to?, by, layer_by? (rows down; negative = up)}", true, move_keyframes),
|
||||
c("timeline.create_tween", "Create Classic Tween", "Insert", None, "{layer?, frame?, easing?}", true, create_tween),
|
||||
c("timeline.remove_tween", "Remove Tween", "Insert", None, "{layer?, frame?}", true, remove_tween),
|
||||
c("timeline.set_easing", "Set Tween Easing", "", None, "{easing, layer?, frame?}", true, set_easing),
|
||||
c("timeline.set_label", "Frame Label", "", None, "{label, layer?, frame?}", true, set_label),
|
||||
c("timeline.goto", "Go to Frame", "", None, "{frame}", false, goto),
|
||||
c("timeline.next_frame", "Next Frame", "Control", Some("."), "{}", false, |s, _| step(s, 1)),
|
||||
c("timeline.prev_frame", "Previous Frame", "Control", Some(","), "{}", false, |s, _| step(s, -1)),
|
||||
c("timeline.first_frame", "Go to First Frame", "Control", Some("Home"), "{}", false, |s, _| {
|
||||
s.set_frame(0);
|
||||
Ok(json!({"frame": 0}))
|
||||
}),
|
||||
c("timeline.last_frame", "Go to Last Frame", "Control", Some("End"), "{}", false, |s, _| {
|
||||
let f = s.frame_count().saturating_sub(1);
|
||||
s.set_frame(f);
|
||||
Ok(json!({"frame": f}))
|
||||
}),
|
||||
c("layer.new", "New Layer", "Insert/Timeline", None, "{name?}", true, new_layer),
|
||||
c("layer.delete", "Delete Layer", "Modify/Timeline", None, "{layer?}", true, delete_layer),
|
||||
c("layer.rename", "Rename Layer", "", None, "{name, layer?}", true, rename_layer),
|
||||
c("layer.toggle_visible", "Show/Hide Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.visible = !l.visible)),
|
||||
c("layer.toggle_lock", "Lock/Unlock Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.locked = !l.locked)),
|
||||
c("layer.toggle_outline", "Outline Layer", "", None, "{layer?}", true, |s, p| toggle(s, p, |l| l.outline = !l.outline)),
|
||||
c("layer.select", "Select Layer", "", None, "{layer: id} or {index}", false, select_layer),
|
||||
c("layer.move_up", "Move Layer Up", "Modify/Timeline", None, "{layer?}", true, |s, p| move_layer(s, p, -1)),
|
||||
c("layer.move_down", "Move Layer Down", "Modify/Timeline", None, "{layer?}", true, |s, p| move_layer(s, p, 1)),
|
||||
c("layer.toggle_mask", "Mask", "Modify/Timeline", None, "{layer?}", true, toggle_mask),
|
||||
c("layer.set_type", "Layer Type", "", None, "{type: normal|mask|masked|guide, layer?}", true, set_layer_type),
|
||||
]
|
||||
}
|
||||
|
||||
/// The mask command: turns a layer into a mask over the normal layer directly under it, or a
|
||||
/// mask back into a normal layer (its masked layers become normal too).
|
||||
fn toggle_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
let is_mask = s.doc.timeline.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask;
|
||||
let ty = if is_mask { "normal" } else { "mask" };
|
||||
set_type(s, id, ty)?;
|
||||
if !is_mask {
|
||||
let tl = &mut s.doc.timeline;
|
||||
if let Some(i) = tl.layers.iter().position(|l| l.id == id)
|
||||
&& let Some(below) = tl.layers.get_mut(i + 1)
|
||||
&& below.kind == LayerKind::Normal
|
||||
&& below.parent.is_none()
|
||||
{
|
||||
Arc::make_mut(below).parent = Some(id);
|
||||
}
|
||||
}
|
||||
Ok(layer_type_json(s, id))
|
||||
}
|
||||
|
||||
fn set_layer_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
set_type(s, id, str_req(p, "type")?)?;
|
||||
Ok(layer_type_json(s, id))
|
||||
}
|
||||
|
||||
fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> {
|
||||
let tl = &mut s.doc.timeline;
|
||||
let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
let (kind, parent) = match ty {
|
||||
"normal" => (LayerKind::Normal, None),
|
||||
"mask" => (LayerKind::Mask, None),
|
||||
"guide" => (LayerKind::Guide, None),
|
||||
"masked" => {
|
||||
let m = tl.mask_above(i).ok_or_else(|| EngineError::State("only a layer directly under a mask layer (or its masked layers) can be masked".into()))?;
|
||||
(LayerKind::Normal, Some(m))
|
||||
}
|
||||
other => return Err(EngineError::Param(format!("unknown layer type '{other}' (normal, mask, masked or guide)"))),
|
||||
};
|
||||
let l = tl.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
l.kind = kind;
|
||||
l.parent = parent;
|
||||
tl.repair_masks();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn layer_type_json(s: &Session, id: LayerId) -> Value {
|
||||
let Some(l) = s.doc.timeline.layer(id) else { return json!({}) };
|
||||
let ty = match (l.kind, l.parent) {
|
||||
(LayerKind::Mask, _) => "mask",
|
||||
(LayerKind::Guide, _) => "guide",
|
||||
(LayerKind::Normal, Some(_)) => "masked",
|
||||
(LayerKind::Normal, None) => "normal",
|
||||
};
|
||||
json!({"layer": id.0, "type": ty, "masked_by": l.parent.map(|p| p.0)})
|
||||
}
|
||||
|
||||
pub(crate) fn target(s: &Session, p: &Value) -> Result<(Option<LayerId>, u32)> {
|
||||
let layer = opt_u64(p, "layer")?.map(LayerId);
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
|
||||
if frame > MAX_FRAME {
|
||||
return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}")));
|
||||
}
|
||||
Ok((layer, frame))
|
||||
}
|
||||
|
||||
/// Layers a range command acts on: `layers: [ids]`, else `layer`, else the active layer.
|
||||
pub(crate) fn target_layers(s: &Session, p: &Value) -> Result<Vec<LayerId>> {
|
||||
let ids = match opt_u64_list(p, "layers")? {
|
||||
Some(v) if !v.is_empty() => v.into_iter().map(LayerId).collect(),
|
||||
Some(_) => return Err(EngineError::Param("param 'layers' must not be empty".into())),
|
||||
None => vec![opt_u64(p, "layer")?.map_or(s.layer, LayerId)],
|
||||
};
|
||||
let mut out: Vec<LayerId> = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
if s.doc.timeline.layer(id).is_none() {
|
||||
return Err(EngineError::State(format!("no layer with id {}", id.0)));
|
||||
}
|
||||
if !out.contains(&id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Frames a range command spans (`count`, default 1).
|
||||
pub(crate) fn count_param(p: &Value) -> Result<u32> {
|
||||
let n = opt_u32(p, "count")?.unwrap_or(1);
|
||||
if !(1..=10_000).contains(&n) {
|
||||
return Err(EngineError::Param("param 'count' must be between 1 and 10,000".into()));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Shifts keyframes starting at or after `from` by `delta` frames.
|
||||
pub(crate) fn shift_after(layer: &mut Layer, from: u32, delta: i64) {
|
||||
for k in layer.keyframes.iter_mut().filter(|k| k.start >= from).map(Arc::make_mut) {
|
||||
k.start = (i64::from(k.start) + delta).clamp(0, i64::from(MAX_FRAME)) as u32;
|
||||
}
|
||||
}
|
||||
|
||||
/// F5 over a range: `count` frames on each target layer.
|
||||
fn insert_frame(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (_, frame) = target(s, p)?;
|
||||
let count = count_param(p)?;
|
||||
let mut frames = 0;
|
||||
for id in target_layers(s, p)? {
|
||||
let layer = s.layer_mut(Some(id))?;
|
||||
for _ in 0..count {
|
||||
insert_frame_at(layer, frame)?;
|
||||
}
|
||||
frames = frames.max(layer.end_frame());
|
||||
}
|
||||
Ok(json!({"frames": frames}))
|
||||
}
|
||||
|
||||
fn insert_frame_at(layer: &mut Layer, frame: u32) -> Result<()> {
|
||||
if layer.end_frame() >= MAX_FRAME {
|
||||
return Err(EngineError::State("the timeline is at its maximum length".into()));
|
||||
}
|
||||
match layer.keyframe_index_at(frame) {
|
||||
Some(i) => {
|
||||
if let Some(k) = layer.keyframe_mut(i) {
|
||||
k.duration += 1;
|
||||
}
|
||||
shift_after(layer, frame + 1, 1);
|
||||
}
|
||||
None => match layer.keyframes.iter().rposition(|k| k.start <= frame) {
|
||||
// extend the previous keyframe up to and including `frame`
|
||||
Some(i) => {
|
||||
let next_start = layer.keyframes.get(i + 1).map(|k| k.start);
|
||||
if let Some(k) = layer.keyframe_mut(i) {
|
||||
let want = frame + 1 - k.start;
|
||||
k.duration = next_start.map_or(want, |n| want.min(n - k.start));
|
||||
}
|
||||
}
|
||||
None => layer.keyframes.insert(0, Arc::new(Keyframe::new(frame, 1))),
|
||||
},
|
||||
}
|
||||
layer.normalize();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shift+F5 over a range: removes up to `count` frames on each target layer. Layers that run
|
||||
/// out of frames stop early; it fails only when nothing could be removed.
|
||||
pub(crate) fn remove_frame(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (_, frame) = target(s, p)?;
|
||||
let count = count_param(p)?;
|
||||
let mut removed = 0u32;
|
||||
let mut first_err = None;
|
||||
for id in target_layers(s, p)? {
|
||||
let layer = s.layer_mut(Some(id))?;
|
||||
for _ in 0..count {
|
||||
match remove_frame_at(layer, frame) {
|
||||
Ok(()) => removed += 1,
|
||||
Err(e) => {
|
||||
first_err.get_or_insert(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match (removed, first_err) {
|
||||
(0, Some(e)) => Err(e),
|
||||
_ => Ok(json!({"removed": removed, "frames": s.doc.frame_count()})),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_frame_at(layer: &mut Layer, frame: u32) -> Result<()> {
|
||||
let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?;
|
||||
let dur = layer.keyframes.get(i).map_or(1, |k| k.duration);
|
||||
if dur > 1 {
|
||||
if let Some(k) = layer.keyframe_mut(i) {
|
||||
k.duration -= 1;
|
||||
}
|
||||
} else {
|
||||
if layer.keyframes.len() == 1 {
|
||||
return Err(EngineError::State("cannot remove the layer's only frame".into()));
|
||||
}
|
||||
layer.keyframes.remove(i);
|
||||
}
|
||||
shift_after(layer, frame + 1, -1);
|
||||
layer.normalize();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Inserts a keyframe at `frame` (F6 when `copy`, F7 otherwise). Inside a tween the new key
|
||||
/// captures the tweened state, so the motion is unchanged.
|
||||
pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> Result<()> {
|
||||
if frame > MAX_FRAME {
|
||||
return Err(EngineError::Param(format!("frame must be at most {MAX_FRAME}")));
|
||||
}
|
||||
if layer.keyframe_starting_at(frame).is_some() {
|
||||
if !copy {
|
||||
// F7 on a keyframe clears it
|
||||
if let Some(k) = layer.keyframe_starting_at(frame).and_then(|i| layer.keyframe_mut(i)) {
|
||||
k.elements.clear();
|
||||
k.tween = None;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let elements = if copy { evaluate_layer_elements(layer, frame).map(|(_, e)| e.into_owned()) } else { None };
|
||||
match layer.keyframe_index_at(frame) {
|
||||
Some(i) => {
|
||||
let Some(k) = layer.keyframe_mut(i) else { return Ok(()) };
|
||||
let end = k.end();
|
||||
let tween = if copy { k.tween } else { None };
|
||||
k.duration = frame - k.start;
|
||||
let mut nk = Keyframe::new(frame, end - frame);
|
||||
nk.elements = elements.unwrap_or_default();
|
||||
nk.tween = tween;
|
||||
layer.keyframes.insert(i + 1, Arc::new(nk));
|
||||
}
|
||||
None => {
|
||||
// Past the end or in a gap: extend the previous key and copy its last state.
|
||||
let prev = layer.keyframes.iter().rposition(|k| k.start < frame);
|
||||
let mut nk = Keyframe::new(frame, 1);
|
||||
if let Some(i) = prev {
|
||||
let next_start = layer.keyframes.get(i + 1).map(|k| k.start);
|
||||
if let Some(k) = layer.keyframe_mut(i) {
|
||||
if copy {
|
||||
nk.elements = k.elements.clone();
|
||||
}
|
||||
k.duration = frame - k.start;
|
||||
}
|
||||
if let Some(n) = next_start {
|
||||
nk.duration = n - frame;
|
||||
}
|
||||
}
|
||||
let pos = layer.keyframes.partition_point(|k| k.start < frame);
|
||||
layer.keyframes.insert(pos, Arc::new(nk));
|
||||
}
|
||||
}
|
||||
layer.normalize();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_keyframe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (_, frame) = target(s, p)?;
|
||||
for id in target_layers(s, p)? {
|
||||
insert_keyframe_at(s.layer_mut(Some(id))?, frame, true)?;
|
||||
}
|
||||
Ok(json!({"keyframe": frame}))
|
||||
}
|
||||
|
||||
fn insert_blank_keyframe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (_, frame) = target(s, p)?;
|
||||
for id in target_layers(s, p)? {
|
||||
insert_keyframe_at(s.layer_mut(Some(id))?, frame, false)?;
|
||||
}
|
||||
Ok(json!({"keyframe": frame}))
|
||||
}
|
||||
|
||||
/// Shift+F6 over a range: clears every keyframe starting in `frame..frame + count` on each
|
||||
/// target layer.
|
||||
fn clear_keyframe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (_, frame) = target(s, p)?;
|
||||
let count = count_param(p)?;
|
||||
let mut cleared = 0;
|
||||
for id in target_layers(s, p)? {
|
||||
let layer = s.layer_mut(Some(id))?;
|
||||
let starts: Vec<u32> = layer.keyframes.iter().map(|k| k.start).filter(|&f| f >= frame && f - frame < count).collect();
|
||||
// Last first, so each removal merges into a span that is still there.
|
||||
for f in starts.into_iter().rev() {
|
||||
clear_keyframe_at(layer, f)?;
|
||||
cleared += 1;
|
||||
}
|
||||
}
|
||||
if cleared == 0 {
|
||||
return Err(EngineError::State(if count == 1 { format!("frame {} is not a keyframe", frame + 1) } else { "no keyframes in the selected frames".into() }));
|
||||
}
|
||||
Ok(json!({"cleared": cleared}))
|
||||
}
|
||||
|
||||
/// Moves the keyframes starting in `from..=to` by `by` frames (dragging a frame selection).
|
||||
/// Keyframes they land on are replaced; the span before a key moved right grows to fill the
|
||||
/// frames it left, and the layer keeps its length (no frames are lost by moving left).
|
||||
fn move_keyframes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let from = opt_u32(p, "from")?.ok_or_else(|| EngineError::Param("param 'from' is required".into()))?;
|
||||
let to = opt_u32(p, "to")?.unwrap_or(from);
|
||||
let by = p.get("by").and_then(Value::as_i64).ok_or_else(|| EngineError::Param("param 'by' must be a whole number of frames".into()))?;
|
||||
if to < from || to > MAX_FRAME || by.unsigned_abs() > u64::from(MAX_FRAME) {
|
||||
return Err(EngineError::Param(format!("frames must be in order and within {MAX_FRAME}")));
|
||||
}
|
||||
let layer_by = match p.get("layer_by") {
|
||||
None | Some(Value::Null) => 0,
|
||||
Some(v) => v.as_i64().ok_or_else(|| EngineError::Param("param 'layer_by' must be a whole number of layers".into()))?,
|
||||
};
|
||||
if layer_by != 0 {
|
||||
return move_across_layers(s, p, from, to, by, layer_by);
|
||||
}
|
||||
let mut moved = 0;
|
||||
for id in target_layers(s, p)? {
|
||||
moved += move_keys(s.layer_mut(Some(id))?, from, to, by)?;
|
||||
}
|
||||
Ok(json!({"moved": moved}))
|
||||
}
|
||||
|
||||
/// Dragging keyframes onto other layers (`layer_by` rows down, negative = up): the frames are
|
||||
/// lifted out of every source layer first (leaving blank keyframes, as in Animate), then
|
||||
/// placed on the target layers, replacing what was there; frames after the landing range
|
||||
/// keep their content. Lifting everything before placing anything makes overlapping row
|
||||
/// ranges (dragging two rows down by one) come out right.
|
||||
fn move_across_layers(s: &mut Session, p: &Value, from: u32, to: u32, by: i64, layer_by: i64) -> Result<Value> {
|
||||
let order: Vec<LayerId> = s.doc.timeline.layers.iter().map(|l| l.id).collect();
|
||||
let mut rows: Vec<usize> = target_layers(s, p)?.iter().filter_map(|id| order.iter().position(|o| o == id)).collect();
|
||||
rows.sort_unstable();
|
||||
let mut plan = Vec::with_capacity(rows.len());
|
||||
for &r in &rows {
|
||||
let t = i64::try_from(r).unwrap_or(i64::MAX).checked_add(layer_by).filter(|t| *t >= 0 && (*t as usize) < order.len());
|
||||
let Some(t) = t else { return Err(EngineError::State("there is no layer there to move the frames to".into())) };
|
||||
let (Some(&src), Some(&dst)) = (order.get(r), order.get(t as usize)) else { continue };
|
||||
plan.push((src, dst));
|
||||
}
|
||||
// 1. Lift.
|
||||
let mut lifted: Vec<(LayerId, Vec<Keyframe>)> = Vec::new();
|
||||
for &(src, dst) in &plan {
|
||||
let layer = s.layer_mut(Some(src))?;
|
||||
let keys: Vec<Keyframe> = layer.keyframes.iter().filter(|k| k.start >= from && k.start <= to).map(|k| (**k).clone()).collect();
|
||||
if let (Some(first), Some(last)) = (keys.first().map(|k| k.start), keys.last().map(Keyframe::end)) {
|
||||
layer.keyframes.retain(|k| !(k.start >= from && k.start <= to));
|
||||
// The frames stay; their content leaves.
|
||||
layer.keyframes.push(Arc::new(Keyframe::new(first, last - first)));
|
||||
layer.normalize();
|
||||
}
|
||||
lifted.push((dst, keys));
|
||||
}
|
||||
// 2. Place.
|
||||
let mut moved = 0;
|
||||
for (dst, keys) in lifted {
|
||||
let (Some(first), Some(last)) = (keys.first().map(|k| k.start), keys.last().map(Keyframe::end)) else { continue };
|
||||
let (a, b) = (i64::from(first) + by, i64::from(last) + by);
|
||||
if a < 0 || b > i64::from(MAX_FRAME) + 1 {
|
||||
return Err(EngineError::State(if a < 0 { "keyframes cannot move before frame 1".into() } else { "keyframes would move past the end of the timeline".into() }));
|
||||
}
|
||||
let (a, b) = (a as u32, b as u32);
|
||||
let layer = s.layer_mut(Some(dst))?;
|
||||
// Cut the target at both ends of the landing range so what lies outside it stays.
|
||||
if layer.keyframe_index_at(a).is_some_and(|i| layer.keyframes.get(i).is_some_and(|k| k.start < a)) {
|
||||
insert_keyframe_at(layer, a, true)?;
|
||||
}
|
||||
if b < layer.end_frame() && layer.keyframe_index_at(b).is_some() {
|
||||
insert_keyframe_at(layer, b, true)?;
|
||||
}
|
||||
layer.keyframes.retain(|k| !(k.start >= a && k.start < b));
|
||||
for mut k in keys {
|
||||
k.start = (i64::from(k.start) + by) as u32;
|
||||
layer.keyframes.push(Arc::new(k));
|
||||
moved += 1;
|
||||
}
|
||||
layer.normalize();
|
||||
}
|
||||
Ok(json!({"moved": moved}))
|
||||
}
|
||||
|
||||
fn move_keys(layer: &mut Layer, from: u32, to: u32, by: i64) -> Result<usize> {
|
||||
if by == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let end = layer.end_frame();
|
||||
let (mut moving, mut staying): (Vec<Arc<Keyframe>>, Vec<Arc<Keyframe>>) = std::mem::take(&mut layer.keyframes).into_iter().partition(|k| k.start >= from && k.start <= to);
|
||||
if moving.is_empty() {
|
||||
layer.keyframes = staying;
|
||||
return Ok(0);
|
||||
}
|
||||
let first = moving.first().map_or(0, |k| i64::from(k.start));
|
||||
let last_end = moving.last().map_or(0, |k| i64::from(k.end()));
|
||||
if first + by < 0 || last_end + by > i64::from(MAX_FRAME) + 1 {
|
||||
layer.keyframes = moving.into_iter().chain(staying).collect();
|
||||
layer.normalize();
|
||||
return Err(EngineError::State(if first + by < 0 { "keyframes cannot move before frame 1".into() } else { "keyframes would move past the end of the timeline".into() }));
|
||||
}
|
||||
for k in moving.iter_mut().map(Arc::make_mut) {
|
||||
k.start = (i64::from(k.start) + by) as u32;
|
||||
}
|
||||
let landed: Vec<u32> = moving.iter().map(|k| k.start).collect();
|
||||
staying.retain(|k| !landed.contains(&k.start));
|
||||
let n = moving.len();
|
||||
let new_end = end.max((last_end + by) as u32);
|
||||
let mut keys: Vec<Arc<Keyframe>> = staying.into_iter().chain(moving).collect();
|
||||
keys.sort_by_key(|k| k.start);
|
||||
// Each span runs to the next key; the last runs to the layer's end.
|
||||
let starts: Vec<u32> = keys.iter().map(|k| k.start).collect();
|
||||
for (i, k) in keys.iter_mut().enumerate() {
|
||||
let stop = starts.get(i + 1).copied().unwrap_or(new_end);
|
||||
let want = stop.saturating_sub(k.start).max(1);
|
||||
if k.duration != want {
|
||||
Arc::make_mut(k).duration = want;
|
||||
}
|
||||
}
|
||||
layer.keyframes = keys;
|
||||
layer.normalize();
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn clear_keyframe_at(layer: &mut Layer, frame: u32) -> Result<()> {
|
||||
let i = layer.keyframe_starting_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is not a keyframe", frame + 1)))?;
|
||||
if i == 0 {
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.elements.clear();
|
||||
k.tween = None;
|
||||
}
|
||||
} else {
|
||||
let removed = layer.keyframes.remove(i);
|
||||
if let Some(prev) = layer.keyframe_mut(i - 1) {
|
||||
prev.duration = removed.end() - prev.start;
|
||||
}
|
||||
}
|
||||
layer.normalize();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn keyframe_mut<'a>(s: &'a mut Session, p: &Value) -> Result<&'a mut Keyframe> {
|
||||
let (lid, frame) = target(s, p)?;
|
||||
let layer = s.layer_mut(lid)?;
|
||||
let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?;
|
||||
layer.keyframe_mut(i).ok_or_else(|| EngineError::State("keyframe vanished".into()))
|
||||
}
|
||||
|
||||
fn create_tween(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let easing = opt_easing(p, "easing")?.unwrap_or_default();
|
||||
let k = keyframe_mut(s, p)?;
|
||||
k.tween = Some(Tween { easing });
|
||||
Ok(json!({"tween": k.start, "easing": easing.label()}))
|
||||
}
|
||||
|
||||
fn remove_tween(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let k = keyframe_mut(s, p)?;
|
||||
k.tween = None;
|
||||
Ok(json!({"removed": k.start}))
|
||||
}
|
||||
|
||||
fn set_easing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let easing = opt_easing(p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?;
|
||||
let k = keyframe_mut(s, p)?;
|
||||
let t = k.tween.as_mut().ok_or_else(|| EngineError::State("this span has no tween; create one first".into()))?;
|
||||
t.easing = easing;
|
||||
Ok(json!({"easing": easing.label()}))
|
||||
}
|
||||
|
||||
fn set_label(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let label = str_req(p, "label")?.chars().take(256).collect::<String>();
|
||||
let k = keyframe_mut(s, p)?;
|
||||
k.label = label;
|
||||
Ok(json!({"label": k.label}))
|
||||
}
|
||||
|
||||
fn goto(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = opt_u32(p, "frame")?.ok_or_else(|| EngineError::Param("param 'frame' is required".into()))?;
|
||||
s.set_frame(f);
|
||||
Ok(json!({"frame": s.frame}))
|
||||
}
|
||||
|
||||
fn step(s: &mut Session, d: i64) -> Result<Value> {
|
||||
let n = i64::from(s.frame_count().max(1));
|
||||
let f = (i64::from(s.frame) + d).rem_euclid(n);
|
||||
s.set_frame(f as u32);
|
||||
Ok(json!({"frame": s.frame}))
|
||||
}
|
||||
|
||||
fn new_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = s.doc.timeline.layers.len() + 1;
|
||||
let name = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Layer {n}"));
|
||||
if s.doc.timeline.layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let id = LayerId(s.doc.alloc_id());
|
||||
let mut layer = Layer::new(id, name);
|
||||
// Match the timeline length so the new layer spans the existing frames.
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.duration = s.doc.frame_count().max(1);
|
||||
}
|
||||
let palette = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65];
|
||||
layer.color = anicraft_doc::Rgba::hex(palette[n % palette.len()]);
|
||||
let at = s.active_layer_index().unwrap_or(0);
|
||||
// Added above a masked layer, it lands inside the mask's group, so it is masked too.
|
||||
layer.parent = s.doc.timeline.layers.get(at).and_then(|l| l.parent);
|
||||
s.doc.timeline.layers.insert(at, Arc::new(layer));
|
||||
s.layer = id;
|
||||
s.selection.clear();
|
||||
Ok(json!({"layer": id.0}))
|
||||
}
|
||||
|
||||
fn delete_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
if s.doc.timeline.layers.len() <= 1 {
|
||||
return Err(EngineError::State("a document needs at least one layer".into()));
|
||||
}
|
||||
let i = s.doc.timeline.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
s.doc.timeline.layers.remove(i);
|
||||
// Layers masked by a deleted mask become normal layers.
|
||||
s.doc.timeline.repair_masks();
|
||||
if s.layer == id {
|
||||
let j = i.min(s.doc.timeline.layers.len() - 1);
|
||||
s.layer = s.doc.timeline.layers.get(j).map_or(LayerId(0), |l| l.id);
|
||||
s.selection.clear();
|
||||
}
|
||||
Ok(json!({"deleted": id.0}))
|
||||
}
|
||||
|
||||
fn rename_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name: String = str_req(p, "name")?.chars().take(128).collect();
|
||||
if name.trim().is_empty() {
|
||||
return Err(EngineError::Param("layer name must not be empty".into()));
|
||||
}
|
||||
let lid = opt_u64(p, "layer")?.map(LayerId);
|
||||
let layer = s.layer_mut(lid)?;
|
||||
layer.name = name;
|
||||
Ok(json!({"name": layer.name}))
|
||||
}
|
||||
|
||||
fn toggle(s: &mut Session, p: &Value, f: fn(&mut Layer)) -> Result<Value> {
|
||||
let lid = opt_u64(p, "layer")?.map(LayerId);
|
||||
let layer = s.layer_mut(lid)?;
|
||||
f(layer);
|
||||
Ok(json!({"visible": layer.visible, "locked": layer.locked, "outline": layer.outline}))
|
||||
}
|
||||
|
||||
fn select_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = if let Some(id) = opt_u64(p, "layer")? {
|
||||
LayerId(id)
|
||||
} else if let Some(i) = opt_u64(p, "index")? {
|
||||
usize::try_from(i).ok().and_then(|i| s.doc.timeline.layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))?
|
||||
} else {
|
||||
return Err(EngineError::Param("pass {\"layer\": id} or {\"index\": n}".into()));
|
||||
};
|
||||
if s.doc.timeline.layer(id).is_none() {
|
||||
return Err(EngineError::State(format!("no layer with id {}", id.0)));
|
||||
}
|
||||
if s.layer != id {
|
||||
s.layer = id;
|
||||
s.selection.clear();
|
||||
}
|
||||
Ok(json!({"layer": id.0}))
|
||||
}
|
||||
|
||||
/// Moves a layer one step. A mask layer moves with its masked layers and steps over a whole
|
||||
/// neighbouring mask group. Any other layer swaps with its neighbour and then belongs to the
|
||||
/// mask group it landed in, if any: moving a layer in under a mask masks it, moving it out
|
||||
/// frees it.
|
||||
fn move_layer(s: &mut Session, p: &Value, d: i64) -> Result<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
let tl = &mut s.doc.timeline;
|
||||
let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
let n = tl.layers.len();
|
||||
if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Mask) {
|
||||
let block = tl.group_range(i);
|
||||
// The neighbouring unit: a layer, or a whole mask group.
|
||||
let unit = if d < 0 {
|
||||
let Some(a) = i.checked_sub(1) else { return Ok(json!({"index": i})) };
|
||||
let top = match tl.layers.get(a).and_then(|l| l.parent) {
|
||||
Some(m) => tl.layers.iter().position(|l| l.id == m).unwrap_or(a),
|
||||
None => a,
|
||||
};
|
||||
top..i
|
||||
} else {
|
||||
if block.end >= n {
|
||||
return Ok(json!({"index": i}));
|
||||
}
|
||||
tl.group_range(block.end)
|
||||
};
|
||||
let (lo, hi) = (unit.start.min(block.start), unit.end.max(block.end));
|
||||
let Some(span) = tl.layers.get_mut(lo..hi) else { return Ok(json!({"index": i})) };
|
||||
// Rotate so the block and the unit trade places.
|
||||
if d < 0 { span.rotate_left(unit.len()) } else { span.rotate_right(unit.len()) }
|
||||
let at = if d < 0 { unit.start } else { block.start + unit.len() };
|
||||
tl.repair_masks();
|
||||
return Ok(json!({"index": at}));
|
||||
}
|
||||
let j = i as i64 + d;
|
||||
if j < 0 || j as usize >= n {
|
||||
return Ok(json!({"index": i}));
|
||||
}
|
||||
let j = j as usize;
|
||||
tl.layers.swap(i, j);
|
||||
let join = tl.mask_above(j).filter(|_| tl.layers.get(j).is_some_and(|l| l.kind == LayerKind::Normal));
|
||||
if let Some(l) = tl.layers.get_mut(j)
|
||||
&& l.parent != join
|
||||
{
|
||||
Arc::make_mut(l).parent = join;
|
||||
}
|
||||
tl.repair_masks();
|
||||
Ok(json!({"index": j}))
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Which commands need the user's confirmation, and why (ADR 0004).
|
||||
//!
|
||||
//! The rules live in the engine so every front end (desktop, CLI, agents) is equally safe:
|
||||
//! irreversible actions are refused unless the params carry `"confirm": true`.
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{Keyframe, Layer, LayerId};
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
/// A confirmation the user must give before a command runs.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Confirmation {
|
||||
pub title: String,
|
||||
pub message: String,
|
||||
/// Label for the destructive button, e.g. "Delete Layer".
|
||||
pub action: String,
|
||||
/// True when undo cannot bring the loss back (unsaved work, files on disk).
|
||||
pub irreversible: bool,
|
||||
}
|
||||
|
||||
/// Whether the params carry an explicit confirmation.
|
||||
pub fn confirmed(p: &Value) -> bool {
|
||||
p.get("confirm").and_then(Value::as_bool) == Some(true)
|
||||
}
|
||||
|
||||
fn doc_name(s: &Session) -> String {
|
||||
s.path.as_ref().and_then(|p| p.file_name()).map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn layer_content(l: &Layer) -> (usize, usize) {
|
||||
let keys = l.keyframes.iter().filter(|k| !k.elements.is_empty()).count();
|
||||
let elements = l.keyframes.iter().map(|k| k.elements.len()).sum();
|
||||
(keys, elements)
|
||||
}
|
||||
|
||||
fn plural(n: usize, word: &str) -> String {
|
||||
if n == 1 { format!("1 {word}") } else { format!("{n} {word}s") }
|
||||
}
|
||||
|
||||
fn target_layer<'a>(s: &'a Session, p: &Value) -> Option<&'a Layer> {
|
||||
let id = p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId);
|
||||
s.doc.timeline.layer(id)
|
||||
}
|
||||
|
||||
fn target_frame(s: &Session, p: &Value) -> u32 {
|
||||
p.get("frame").and_then(Value::as_u64).and_then(|f| u32::try_from(f).ok()).unwrap_or(s.frame)
|
||||
}
|
||||
|
||||
fn target_count(p: &Value) -> u32 {
|
||||
p.get("count").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(1).max(1)
|
||||
}
|
||||
|
||||
/// Keyframes with artwork that `hit` selects on the target layers (`layers` or `layer`), as
|
||||
/// `(layer name, element count)`.
|
||||
fn lost_keys(s: &Session, p: &Value, hit: impl Fn(&Keyframe) -> bool) -> Vec<(String, usize)> {
|
||||
let ids: Vec<LayerId> = match p.get("layers").and_then(Value::as_array) {
|
||||
Some(v) => v.iter().filter_map(Value::as_u64).map(LayerId).take(1000).collect(),
|
||||
None => vec![p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId)],
|
||||
};
|
||||
ids.iter()
|
||||
.filter_map(|id| s.doc.timeline.layer(*id))
|
||||
.flat_map(|l| l.keyframes.iter().filter(|k| !k.elements.is_empty() && hit(k)).map(|k| (l.name.clone(), k.elements.len())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn overwrite(path: &Path, what: &str) -> Confirmation {
|
||||
Confirmation {
|
||||
title: "Replace existing file?".into(),
|
||||
message: format!("{} already exists. {what} will replace it; this cannot be undone.", path.display()),
|
||||
action: "Replace".into(),
|
||||
irreversible: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The confirmation `id` with `p` needs right now, if any.
|
||||
pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
match id {
|
||||
"file.new" | "file.new_sample" | "file.open" if s.is_dirty() => Some(Confirmation {
|
||||
title: "Discard unsaved changes?".into(),
|
||||
message: format!("“{}” has changes that are not saved. They will be lost, and its undo history is cleared.", doc_name(s)),
|
||||
action: "Discard Changes".into(),
|
||||
irreversible: true,
|
||||
}),
|
||||
"file.save" | "file.save_as" => {
|
||||
let path = Path::new(p.get("path").and_then(Value::as_str)?);
|
||||
let same = s.path.as_deref() == Some(path);
|
||||
(!same && path.exists()).then(|| overwrite(path, "Saving"))
|
||||
}
|
||||
"file.export_png" | "file.export_gif" => {
|
||||
let path = Path::new(p.get("path").and_then(Value::as_str)?);
|
||||
path.exists().then(|| overwrite(path, "Exporting"))
|
||||
}
|
||||
"file.export_png_sequence" => {
|
||||
let dir = Path::new(p.get("dir").and_then(Value::as_str)?);
|
||||
let has_frames = std::fs::read_dir(dir).ok()?.take(10_000).flatten().any(|e| {
|
||||
let n = e.file_name();
|
||||
let n = n.to_string_lossy();
|
||||
n.starts_with("frame_") && n.ends_with(".png")
|
||||
});
|
||||
has_frames.then(|| Confirmation {
|
||||
title: "Replace exported frames?".into(),
|
||||
message: format!("{} already contains exported frames. Matching files will be replaced; this cannot be undone.", dir.display()),
|
||||
action: "Replace".into(),
|
||||
irreversible: true,
|
||||
})
|
||||
}
|
||||
"layer.delete" => {
|
||||
let l = target_layer(s, p)?;
|
||||
let (keys, elements) = layer_content(l);
|
||||
(elements > 0).then(|| Confirmation {
|
||||
title: "Delete layer?".into(),
|
||||
message: format!("Layer “{}” has {} with {}. You can undo this.", l.name, plural(keys, "keyframe"), plural(elements, "element")),
|
||||
action: "Delete Layer".into(),
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"timeline.clear_keyframe" => {
|
||||
let (f, n) = (target_frame(s, p), target_count(p));
|
||||
let lost = lost_keys(s, p, |k| k.start >= f && k.start - f < n);
|
||||
let (keys, elements) = (lost.len(), lost.iter().map(|(_, e)| e).sum::<usize>());
|
||||
(elements > 0).then(|| Confirmation {
|
||||
title: if keys == 1 { "Clear keyframe?".into() } else { "Clear keyframes?".into() },
|
||||
message: match lost.as_slice() {
|
||||
[(name, e)] if n == 1 => format!("The keyframe at frame {} on “{name}” holds {}. You can undo this.", f + 1, plural(*e, "element")),
|
||||
_ => format!("The selected frames hold {} with {}. You can undo this.", plural(keys, "keyframe"), plural(elements, "element")),
|
||||
},
|
||||
action: if keys == 1 { "Clear Keyframe".into() } else { "Clear Keyframes".into() },
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"timeline.remove_frame" => {
|
||||
// A keyframe whose whole span is removed takes its artwork with it.
|
||||
let (f, n) = (target_frame(s, p), target_count(p));
|
||||
let lost = lost_keys(s, p, |k| k.start >= f && k.end() <= f.saturating_add(n));
|
||||
let (keys, elements) = (lost.len(), lost.iter().map(|(_, e)| e).sum::<usize>());
|
||||
(elements > 0).then(|| Confirmation {
|
||||
title: if n == 1 { "Remove frame?".into() } else { "Remove frames?".into() },
|
||||
message: match lost.as_slice() {
|
||||
[(name, e)] if n == 1 => format!("Frame {} is a one-frame keyframe on “{name}” with {}; removing it deletes that artwork. You can undo this.", f + 1, plural(*e, "element")),
|
||||
_ => format!("Removing these frames deletes {} with {}. You can undo this.", plural(keys, "keyframe"), plural(elements, "element")),
|
||||
},
|
||||
action: if n == 1 { "Remove Frame".into() } else { "Remove Frames".into() },
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! The `.anicraft` native format: a versioned JSON envelope around the document.
|
||||
|
||||
use crate::EngineError;
|
||||
use anicraft_doc::{Document, path_table};
|
||||
use anicraft_geom::Path;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub const FORMAT_NAME: &str = "anicraft";
|
||||
/// v1: inline tagged paths. v2: SVG path strings, shared paths stored once in `paths`.
|
||||
pub const FORMAT_VERSION: u32 = 2;
|
||||
/// Largest file we will parse.
|
||||
pub const MAX_FILE_BYTES: u64 = 1024 * 1024 * 1024;
|
||||
/// Files smaller than this (compact) are pretty-printed for humans and diffs.
|
||||
const PRETTY_LIMIT: usize = 1024 * 1024;
|
||||
|
||||
/// Written in this field order: the path table precedes the document, so a reader can stream
|
||||
/// the file in one pass with references already resolvable.
|
||||
#[derive(Serialize)]
|
||||
struct EnvelopeOut<'a> {
|
||||
format: &'a str,
|
||||
version: u32,
|
||||
generator: String,
|
||||
paths: &'a [Arc<Path>],
|
||||
document: &'a Document,
|
||||
}
|
||||
|
||||
/// Streaming reader: when `paths` arrives it opens a path-table scope for `document`.
|
||||
struct EnvelopeIn {
|
||||
format: String,
|
||||
version: u32,
|
||||
document: Option<Document>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for EnvelopeIn {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct V;
|
||||
impl<'de> serde::de::Visitor<'de> for V {
|
||||
type Value = EnvelopeIn;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("an .anicraft envelope object")
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<EnvelopeIn, A::Error> {
|
||||
let (mut format, mut version, mut document) = (None, None, None);
|
||||
let mut _scope = None;
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
match key.as_str() {
|
||||
"format" => format = Some(map.next_value::<String>()?),
|
||||
"version" => version = Some(map.next_value::<u32>()?),
|
||||
"paths" => {
|
||||
let paths: Vec<Path> = map.next_value()?;
|
||||
_scope = Some(path_table::begin_read(paths.into_iter().map(Arc::new).collect()));
|
||||
}
|
||||
"document" => document = Some(map.next_value::<Document>()?),
|
||||
_ => {
|
||||
map.next_value::<serde::de::IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(EnvelopeIn {
|
||||
format: format.ok_or_else(|| serde::de::Error::missing_field("format"))?,
|
||||
version: version.ok_or_else(|| serde::de::Error::missing_field("version"))?,
|
||||
document,
|
||||
})
|
||||
}
|
||||
}
|
||||
d.deserialize_map(V)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_json(doc: &Document) -> Result<String, EngineError> {
|
||||
let paths = path_table::build_table(doc);
|
||||
let env = EnvelopeOut { format: FORMAT_NAME, version: FORMAT_VERSION, generator: format!("AniCraft {}", env!("CARGO_PKG_VERSION")), paths: &paths, document: doc };
|
||||
let compact = path_table::write_with_paths(&paths, || serde_json::to_string(&env)).map_err(|e| EngineError::Format(e.to_string()))?;
|
||||
if compact.len() < PRETTY_LIMIT {
|
||||
return path_table::write_with_paths(&paths, || serde_json::to_string_pretty(&env)).map_err(|e| EngineError::Format(e.to_string()));
|
||||
}
|
||||
Ok(compact)
|
||||
}
|
||||
|
||||
pub fn from_json(text: &str) -> Result<Document, EngineError> {
|
||||
let env: EnvelopeIn = serde_json::from_str(text).map_err(|e| EngineError::Format(format!("not a valid .anicraft file: {e}")))?;
|
||||
if env.format != FORMAT_NAME {
|
||||
return Err(EngineError::Format(format!("unexpected format '{}'", env.format)));
|
||||
}
|
||||
if env.version > FORMAT_VERSION {
|
||||
return Err(EngineError::Format(format!("file version {} is newer than this AniCraft (supports {FORMAT_VERSION})", env.version)));
|
||||
}
|
||||
let mut doc = env.document.ok_or_else(|| EngineError::Format("the file has no document".into()))?;
|
||||
doc.sanitize();
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
pub fn load(path: &std::path::Path) -> Result<Document, EngineError> {
|
||||
let meta = std::fs::metadata(path)?;
|
||||
if meta.len() > MAX_FILE_BYTES {
|
||||
return Err(EngineError::Format(format!("file is {} bytes; the limit is {MAX_FILE_BYTES}", meta.len())));
|
||||
}
|
||||
from_json(&std::fs::read_to_string(path)?)
|
||||
}
|
||||
|
||||
pub fn save(doc: &Document, path: &std::path::Path) -> Result<(), EngineError> {
|
||||
let json = to_json(doc)?;
|
||||
// Write next to the target, then rename: a crash mid-write never corrupts the old file.
|
||||
let tmp = path.with_extension("anicraft.tmp");
|
||||
std::fs::write(&tmp, json)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_doc::sample;
|
||||
|
||||
#[test]
|
||||
fn round_trip_is_lossless() {
|
||||
let d = sample::demo();
|
||||
let back = from_json(&to_json(&d).unwrap()).unwrap();
|
||||
assert_eq!(d, back);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_paths_are_written_once_and_shared_again_on_load() {
|
||||
let d = anicraft_doc::sample::stress(2, 40, 48); // 4 keyframes per element share a path
|
||||
let json = to_json(&d).unwrap();
|
||||
let env: serde_json::Value = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(env["version"], 2);
|
||||
assert_eq!(env["paths"].as_array().unwrap().len(), 80, "one entry per distinct path");
|
||||
let back = from_json(&json).unwrap();
|
||||
assert_eq!(d, back);
|
||||
let l = &back.timeline.layers[0];
|
||||
let (anicraft_doc::ElementKind::Shape(a), anicraft_doc::ElementKind::Shape(b)) = (&l.keyframes[0].elements[0].kind, &l.keyframes[3].elements[0].kind) else { panic!() };
|
||||
assert!(Arc::ptr_eq(&a.path, &b.path), "sharing restored on load");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_1_files_still_load() {
|
||||
let v1 = r#"{"format":"anicraft","version":1,"document":{"timeline":{"layers":[{"id":1,"name":"L","keyframes":[{"start":0,"duration":2,"elements":[
|
||||
{"id":2,"kind":{"Shape":{"path":{"cmds":[{"MoveTo":{"x":0.0,"y":0.0}},{"LineTo":{"x":10.0,"y":0.0}},{"LineTo":{"x":10.0,"y":10.0}},"Close"]},"fill":{"Solid":{"r":1.0,"g":0.0,"b":0.0,"a":1.0}}}}}]}]}]},"next_id":3}}"#;
|
||||
let d = from_json(v1).unwrap();
|
||||
assert_eq!(d.frame_count(), 2);
|
||||
assert_eq!(anicraft_doc::evaluate(&d, 1).items.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_path_references_are_errors() {
|
||||
let bad = r#"{"format":"anicraft","version":2,"paths":["M0 0L1 1Z"],"document":{"timeline":{"layers":[{"id":1,"name":"L","keyframes":[{"start":0,"duration":1,"elements":[
|
||||
{"id":2,"kind":{"Shape":{"path":7}}}]}]}]}}}"#;
|
||||
assert!(from_json(bad).is_err());
|
||||
assert!(from_json(r#"{"format":"anicraft","version":2,"paths":["M0 0 Q"],"document":{}}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_garbage_and_future_versions() {
|
||||
assert!(from_json("{").is_err());
|
||||
assert!(from_json(r#"{"format":"other","version":1,"document":{}}"#).is_err());
|
||||
assert!(from_json(r#"{"format":"anicraft","version":99,"document":{}}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_fields_default() {
|
||||
let d = from_json(r#"{"format":"anicraft","version":1,"document":{"stage":{"width":0,"height":50,"fps":-3,"background":{"r":2,"g":0,"b":0,"a":1}}}}"#).unwrap();
|
||||
assert_eq!(d.stage.width, 1);
|
||||
assert_eq!(d.stage.fps, 24.0);
|
||||
assert_eq!(d.stage.background.r, 1.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Undo/redo history over persistent document snapshots.
|
||||
//!
|
||||
//! Design (see `docs/adr/0001-undo-persistent-snapshots.md`): every undo step is a snapshot of
|
||||
//! the structurally-shared [`Document`], so a step costs memory only for the nodes the edit
|
||||
//! actually copied. History is bounded by an estimate of that unique memory, not by step count,
|
||||
//! so a thousand small nudges are cheap while one huge import is still evictable.
|
||||
|
||||
use anicraft_doc::{Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Symbol};
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::mem::size_of;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Globally unique id of a document *state*. Equal ids mean identical content, so render caches
|
||||
/// can key on it and an undo back to a cached state is a cache hit.
|
||||
pub type StateId = u64;
|
||||
|
||||
static NEXT_STATE: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
pub fn fresh_state() -> StateId {
|
||||
NEXT_STATE.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Everything restored by undo/redo.
|
||||
#[derive(Clone)]
|
||||
pub struct Snapshot {
|
||||
pub label: String,
|
||||
pub doc: Document,
|
||||
pub state: StateId,
|
||||
pub frame: u32,
|
||||
pub layer: LayerId,
|
||||
pub selection: Vec<ElementId>,
|
||||
/// Estimated bytes this snapshot keeps alive that the neighbouring state does not share.
|
||||
pub bytes: usize,
|
||||
}
|
||||
|
||||
/// Default memory budget for undo history.
|
||||
pub const DEFAULT_BUDGET_BYTES: usize = 512 * 1024 * 1024;
|
||||
/// Hard cap on steps, whatever their size.
|
||||
pub const MAX_STEPS: usize = 10_000;
|
||||
|
||||
pub struct History {
|
||||
undo: VecDeque<Snapshot>,
|
||||
redo: Vec<Snapshot>,
|
||||
pub budget_bytes: usize,
|
||||
pub max_steps: usize,
|
||||
undo_bytes: usize,
|
||||
redo_bytes: usize,
|
||||
/// Steps dropped from the old end because of the budget.
|
||||
pub evicted: usize,
|
||||
}
|
||||
|
||||
impl Default for History {
|
||||
fn default() -> Self {
|
||||
History { undo: VecDeque::new(), redo: Vec::new(), budget_bytes: DEFAULT_BUDGET_BYTES, max_steps: MAX_STEPS, undo_bytes: 0, redo_bytes: 0, evicted: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl History {
|
||||
/// Records `before` as an undo step leading to `current`, and clears redo.
|
||||
pub fn record(&mut self, mut before: Snapshot, current: &Document) {
|
||||
before.bytes = unique_bytes(&before.doc, current);
|
||||
self.undo_bytes += before.bytes;
|
||||
self.undo.push_back(before);
|
||||
self.redo.clear();
|
||||
self.redo_bytes = 0;
|
||||
self.enforce_budget();
|
||||
}
|
||||
|
||||
fn enforce_budget(&mut self) {
|
||||
while self.undo.len() > 1 && (self.undo_bytes + self.redo_bytes > self.budget_bytes || self.undo.len() > self.max_steps) {
|
||||
if let Some(old) = self.undo.pop_front() {
|
||||
self.undo_bytes = self.undo_bytes.saturating_sub(old.bytes);
|
||||
self.evicted += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pops the newest undo step and pushes `current` onto the redo stack.
|
||||
pub fn undo(&mut self, mut current: Snapshot) -> Option<Snapshot> {
|
||||
let s = self.undo.pop_back()?;
|
||||
self.undo_bytes = self.undo_bytes.saturating_sub(s.bytes);
|
||||
current.bytes = unique_bytes(¤t.doc, &s.doc);
|
||||
current.label = s.label.clone();
|
||||
self.redo_bytes += current.bytes;
|
||||
self.redo.push(current);
|
||||
Some(s)
|
||||
}
|
||||
|
||||
/// Pops the newest redo step and pushes `current` back onto the undo stack.
|
||||
pub fn redo(&mut self, mut current: Snapshot) -> Option<Snapshot> {
|
||||
let s = self.redo.pop()?;
|
||||
self.redo_bytes = self.redo_bytes.saturating_sub(s.bytes);
|
||||
current.bytes = unique_bytes(¤t.doc, &s.doc);
|
||||
current.label = s.label.clone();
|
||||
self.undo_bytes += current.bytes;
|
||||
self.undo.push_back(current);
|
||||
self.enforce_budget();
|
||||
Some(s)
|
||||
}
|
||||
|
||||
pub fn can_undo(&self) -> bool {
|
||||
!self.undo.is_empty()
|
||||
}
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.redo.is_empty()
|
||||
}
|
||||
pub fn undo_len(&self) -> usize {
|
||||
self.undo.len()
|
||||
}
|
||||
pub fn redo_len(&self) -> usize {
|
||||
self.redo.len()
|
||||
}
|
||||
pub fn undo_label(&self) -> Option<&str> {
|
||||
self.undo.back().map(|s| s.label.as_str())
|
||||
}
|
||||
pub fn redo_label(&self) -> Option<&str> {
|
||||
self.redo.last().map(|s| s.label.as_str())
|
||||
}
|
||||
/// Labels, oldest first.
|
||||
pub fn undo_labels(&self) -> impl Iterator<Item = &str> {
|
||||
self.undo.iter().map(|s| s.label.as_str())
|
||||
}
|
||||
/// Labels of redoable steps, next-to-redo first.
|
||||
pub fn redo_labels(&self) -> impl Iterator<Item = &str> {
|
||||
self.redo.iter().rev().map(|s| s.label.as_str())
|
||||
}
|
||||
/// Estimated memory held by history.
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.undo_bytes + self.redo_bytes
|
||||
}
|
||||
}
|
||||
|
||||
// ----- unique-memory estimate ------------------------------------------------------------------
|
||||
|
||||
fn ptr<T>(a: &Arc<T>) -> usize {
|
||||
Arc::as_ptr(a) as *const u8 as usize
|
||||
}
|
||||
|
||||
fn path_bytes(e: &Element) -> usize {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(s) => size_of::<anicraft_geom::Path>() + s.path.cmds.len() * size_of::<anicraft_geom::PathCmd>(),
|
||||
ElementKind::Symbol { .. } => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn element_bytes(e: &Element, shared_paths: &HashSet<usize>) -> usize {
|
||||
let mut b = size_of::<Element>() + e.name.len();
|
||||
if let ElementKind::Shape(s) = &e.kind {
|
||||
if !shared_paths.contains(&ptr(&s.path)) {
|
||||
b += path_bytes(e);
|
||||
}
|
||||
if let Some(anicraft_doc::Paint::Linear { stops, .. } | anicraft_doc::Paint::Radial { stops, .. }) = &s.fill {
|
||||
b += stops.len() * size_of::<anicraft_doc::GradientStop>();
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn keyframe_bytes(k: &Keyframe, other: Option<&Keyframe>) -> usize {
|
||||
let shared_els: HashSet<usize> = other.map(|o| o.elements.iter().map(ptr).collect()).unwrap_or_default();
|
||||
let shared_paths: HashSet<usize> = other
|
||||
.map(|o| {
|
||||
o.elements
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
ElementKind::Shape(s) => Some(ptr(&s.path)),
|
||||
ElementKind::Symbol { .. } => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut b = size_of::<Keyframe>() + k.label.len() + k.elements.len() * size_of::<usize>();
|
||||
for e in &k.elements {
|
||||
if !shared_els.contains(&ptr(e)) {
|
||||
b += element_bytes(e, &shared_paths);
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn layer_bytes(l: &Layer, other: Option<&Layer>) -> usize {
|
||||
let shared: HashSet<usize> = other.map(|o| o.keyframes.iter().map(ptr).collect()).unwrap_or_default();
|
||||
let mut b = size_of::<Layer>() + l.name.len() + l.keyframes.len() * size_of::<usize>();
|
||||
for k in &l.keyframes {
|
||||
if shared.contains(&ptr(k)) {
|
||||
continue;
|
||||
}
|
||||
let peer = other.and_then(|o| o.keyframes.iter().find(|p| p.start == k.start)).map(|p| &**p);
|
||||
b += keyframe_bytes(k, peer);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn symbol_bytes(s: &Symbol, other: Option<&Symbol>) -> usize {
|
||||
let shared: HashSet<usize> = other.map(|o| o.timeline.layers.iter().map(ptr).collect()).unwrap_or_default();
|
||||
let mut b = size_of::<Symbol>() + s.name.len();
|
||||
for l in &s.timeline.layers {
|
||||
if !shared.contains(&ptr(l)) {
|
||||
let peer = other.and_then(|o| o.timeline.layers.iter().find(|p| p.id == l.id)).map(|p| &**p);
|
||||
b += layer_bytes(l, peer);
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Estimated bytes reachable from `old` that are not shared with `new`. Costs O(changed) after
|
||||
/// an O(layers + symbols) pointer scan.
|
||||
pub fn unique_bytes(old: &Document, new: &Document) -> usize {
|
||||
let mut b = size_of::<Snapshot>() + (old.timeline.layers.len() + old.library.len()) * size_of::<usize>();
|
||||
let shared_layers: HashSet<usize> = new.timeline.layers.iter().map(ptr).collect();
|
||||
for l in &old.timeline.layers {
|
||||
if !shared_layers.contains(&ptr(l)) {
|
||||
let peer = new.timeline.layers.iter().find(|p| p.id == l.id).map(|p| &**p);
|
||||
b += layer_bytes(l, peer);
|
||||
}
|
||||
}
|
||||
let shared_syms: HashSet<usize> = new.library.iter().map(ptr).collect();
|
||||
for s in &old.library {
|
||||
if !shared_syms.contains(&ptr(s)) {
|
||||
let peer = new.library.iter().find(|p| p.id == s.id).map(|p| &**p);
|
||||
b += symbol_bytes(s, peer);
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Estimated total bytes of a document (as if nothing were shared). Used for reporting.
|
||||
pub fn document_bytes(doc: &Document) -> usize {
|
||||
let empty = Document { stage: doc.stage, timeline: Default::default(), library: Vec::new(), next_id: doc.next_id };
|
||||
unique_bytes(doc, &empty)
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
//! AniCraft engine (layer L3): the session, undo history and the command registry.
|
||||
//!
|
||||
//! Every user-visible action is a [`CommandSpec`]. The egui shell, the CLI, the JSON-lines
|
||||
//! control channel and future MCP server all call [`Session::execute`] with a command id and
|
||||
//! JSON params, so headless and interactive behaviour cannot drift apart.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod cmds_draw;
|
||||
mod cmds_file;
|
||||
mod cmds_frames;
|
||||
mod cmds_modify;
|
||||
mod cmds_paint;
|
||||
mod cmds_path;
|
||||
mod cmds_timeline;
|
||||
pub mod confirm;
|
||||
pub mod format;
|
||||
pub mod history;
|
||||
pub mod render_service;
|
||||
pub mod params;
|
||||
|
||||
use anicraft_doc::{DisplayList, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, evaluate, evaluate_layer_elements};
|
||||
use anicraft_geom::{Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use history::History;
|
||||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use anicraft_doc as doc;
|
||||
pub use anicraft_geom as geom;
|
||||
pub use anicraft_render as render;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
#[error("unknown command '{0}'")]
|
||||
UnknownCommand(String),
|
||||
#[error("{0}")]
|
||||
Param(String),
|
||||
#[error("{0}")]
|
||||
State(String),
|
||||
#[error("file format: {0}")]
|
||||
Format(String),
|
||||
#[error("I/O: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("render: {0}")]
|
||||
Render(#[from] anicraft_render::RenderError),
|
||||
#[error("{0}")]
|
||||
NeedsConfirmation(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, EngineError>;
|
||||
|
||||
/// Signature of a command implementation.
|
||||
pub type RunFn = fn(&mut Session, &Value) -> Result<Value>;
|
||||
|
||||
/// Description of one command.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CommandSpec {
|
||||
/// Stable id, e.g. `timeline.insert_keyframe`.
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
/// Menu path, e.g. `Insert/Timeline`. Empty = not in a menu.
|
||||
pub menu: &'static str,
|
||||
pub shortcut: Option<&'static str>,
|
||||
/// Human-readable params description.
|
||||
pub params: &'static str,
|
||||
/// Whether it changes the document (and therefore records an undo step).
|
||||
pub mutates: bool,
|
||||
pub run: RunFn,
|
||||
}
|
||||
|
||||
impl CommandSpec {
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({ "id": self.id, "label": self.label, "menu": self.menu, "shortcut": self.shortcut, "params": self.params, "mutates": self.mutates })
|
||||
}
|
||||
}
|
||||
|
||||
/// All commands, in menu order.
|
||||
pub fn commands() -> Vec<CommandSpec> {
|
||||
let mut v = Vec::new();
|
||||
v.extend(cmds_file::specs());
|
||||
v.extend(cmds_timeline::specs());
|
||||
v.extend(cmds_frames::specs());
|
||||
v.extend(cmds_draw::specs());
|
||||
v.extend(cmds_modify::specs());
|
||||
v.extend(cmds_path::specs());
|
||||
v.extend(cmds_paint::specs());
|
||||
v
|
||||
}
|
||||
|
||||
/// Second keys for commands, `(keys, command id)`: Animate's where the primary key is the
|
||||
/// platform's, and keys that differ by keyboard (a Mac's Delete key sends Backspace).
|
||||
pub const SHORTCUT_ALIASES: &[(&str, &str)] = &[
|
||||
("Backspace", "edit.delete"),
|
||||
("Shift+,", "timeline.first_frame"),
|
||||
("Shift+.", "timeline.last_frame"),
|
||||
];
|
||||
|
||||
pub fn find_command(id: &str) -> Option<CommandSpec> {
|
||||
commands().into_iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
pub use history::{Snapshot, StateId};
|
||||
|
||||
/// Last addressable frame (0-based); about 70 minutes at 24 fps.
|
||||
pub const MAX_FRAME: u32 = 100_000;
|
||||
|
||||
/// Drawing defaults used by the drawing commands when params omit colours.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ToolStyle {
|
||||
pub fill: anicraft_doc::Rgba,
|
||||
pub stroke: anicraft_doc::Rgba,
|
||||
pub stroke_width: f32,
|
||||
pub use_fill: bool,
|
||||
pub use_stroke: bool,
|
||||
}
|
||||
|
||||
impl Default for ToolStyle {
|
||||
fn default() -> Self {
|
||||
ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// An open document plus everything the editor tracks about it.
|
||||
pub struct Session {
|
||||
/// The document: a persistent tree, so cloning it (undo, render thread) is cheap.
|
||||
pub doc: Document,
|
||||
/// Playhead (0-based).
|
||||
pub frame: u32,
|
||||
/// Active layer.
|
||||
pub layer: LayerId,
|
||||
/// Selected elements on the active layer.
|
||||
pub selection: Vec<ElementId>,
|
||||
/// Bumped on every document change, undo and redo (UI invalidation).
|
||||
pub revision: u64,
|
||||
/// Identity of the current document content (equal ids ⇒ identical content).
|
||||
pub state: StateId,
|
||||
saved_state: Option<StateId>,
|
||||
pub path: Option<PathBuf>,
|
||||
pub style: ToolStyle,
|
||||
history: History,
|
||||
/// Open gesture (e.g. a drag): commands inside it coalesce into one undo step.
|
||||
gesture: Option<Snapshot>,
|
||||
/// Display list of `(state, frame)`, shared by hit testing, bounds and overlays.
|
||||
dl_cache: RefCell<Option<(StateId, u32, Arc<DisplayList>)>>,
|
||||
/// Copied elements (and the symbols they use), outside the document so undo leaves it alone.
|
||||
pub clipboard: cmds_modify::Clipboard,
|
||||
/// Copied frames (Copy Frames), separate from copied artwork as in Animate.
|
||||
pub frame_clipboard: cmds_frames::FrameClipboard,
|
||||
}
|
||||
|
||||
impl Default for Session {
|
||||
fn default() -> Self {
|
||||
Session::new(Document::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn new(mut doc: Document) -> Session {
|
||||
doc.sanitize();
|
||||
if doc.timeline.layers.is_empty() {
|
||||
let id = LayerId(doc.alloc_id());
|
||||
doc.timeline.layers.push(Arc::new(Layer::new(id, "Layer 1")));
|
||||
}
|
||||
let layer = doc.timeline.layers.first().map_or(LayerId(0), |l| l.id);
|
||||
let state = history::fresh_state();
|
||||
Session {
|
||||
doc,
|
||||
frame: 0,
|
||||
layer,
|
||||
selection: Vec::new(),
|
||||
revision: 1,
|
||||
state,
|
||||
saved_state: Some(state),
|
||||
path: None,
|
||||
style: ToolStyle::default(),
|
||||
history: History::default(),
|
||||
gesture: None,
|
||||
dl_cache: RefCell::new(None),
|
||||
clipboard: cmds_modify::Clipboard::default(),
|
||||
frame_clipboard: cmds_frames::FrameClipboard::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the document differs from the last saved (or opened) state. Undoing back to
|
||||
/// the saved state makes it clean again.
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
self.saved_state != Some(self.state)
|
||||
}
|
||||
|
||||
/// Marks the current state as saved.
|
||||
pub fn mark_saved(&mut self) {
|
||||
self.saved_state = Some(self.state);
|
||||
}
|
||||
|
||||
/// The confirmation running `id` with `params` needs right now (ADR 0004).
|
||||
pub fn confirmation(&self, id: &str, params: &Value) -> Option<confirm::Confirmation> {
|
||||
confirm::confirmation(self, id, params)
|
||||
}
|
||||
|
||||
pub fn history(&self) -> &History {
|
||||
&self.history
|
||||
}
|
||||
|
||||
/// Sets the undo memory budget (bytes); older steps are evicted beyond it.
|
||||
pub fn set_history_budget(&mut self, bytes: usize) {
|
||||
self.history.budget_bytes = bytes;
|
||||
}
|
||||
|
||||
/// Starts coalescing: every mutating command until [`Session::end_gesture`] becomes a single
|
||||
/// undo step labelled `label` (used for drags, so a move is one step, not sixty).
|
||||
pub fn begin_gesture(&mut self, label: &str) {
|
||||
if self.gesture.is_none() {
|
||||
self.gesture = Some(self.snapshot(label));
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the open gesture, recording one undo step if the document changed.
|
||||
pub fn end_gesture(&mut self) {
|
||||
if let Some(before) = self.gesture.take()
|
||||
&& self.doc != before.doc
|
||||
{
|
||||
self.history.record(before, &self.doc);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn in_gesture(&self) -> bool {
|
||||
self.gesture.is_some()
|
||||
}
|
||||
|
||||
/// Replaces the document (new/open), clearing history.
|
||||
pub fn replace_document(&mut self, doc: Document, path: Option<PathBuf>) {
|
||||
let style = self.style;
|
||||
let rev = self.revision;
|
||||
let budget = self.history.budget_bytes;
|
||||
let clipboard = std::mem::take(&mut self.clipboard);
|
||||
*self = Session::new(doc);
|
||||
// The clipboard survives New/Open, so artwork can move between documents.
|
||||
self.clipboard = clipboard;
|
||||
self.style = style;
|
||||
self.revision = rev + 1;
|
||||
self.path = path;
|
||||
self.history.budget_bytes = budget;
|
||||
}
|
||||
|
||||
/// Runs a command by id. Mutating commands are atomic: on error the document is restored.
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
// Irreversible loss (unsaved work, files on disk) needs explicit consent, whoever asks.
|
||||
if let Some(c) = self.confirmation(id, params)
|
||||
&& c.irreversible
|
||||
&& !confirm::confirmed(params)
|
||||
{
|
||||
return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message)));
|
||||
}
|
||||
if !spec.mutates {
|
||||
return (spec.run)(self, params);
|
||||
}
|
||||
let before = self.snapshot(spec.label);
|
||||
// A command must never observe a display list of the state it is changing.
|
||||
self.dl_cache.replace(None);
|
||||
let result = (spec.run)(self, params);
|
||||
self.dl_cache.replace(None);
|
||||
match result {
|
||||
Ok(v) => {
|
||||
// O(changed): unchanged subtrees compare by pointer.
|
||||
if self.doc != before.doc {
|
||||
self.state = history::fresh_state();
|
||||
self.revision += 1;
|
||||
if self.gesture.is_none() {
|
||||
self.history.record(before, &self.doc);
|
||||
}
|
||||
}
|
||||
self.fix_selection();
|
||||
Ok(v)
|
||||
}
|
||||
Err(e) => {
|
||||
self.restore(before);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, label: &str) -> Snapshot {
|
||||
Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 }
|
||||
}
|
||||
|
||||
fn restore(&mut self, s: Snapshot) {
|
||||
self.doc = s.doc;
|
||||
self.state = s.state;
|
||||
self.frame = s.frame;
|
||||
self.layer = s.layer;
|
||||
self.selection = s.selection;
|
||||
self.dl_cache.replace(None);
|
||||
}
|
||||
|
||||
pub fn can_undo(&self) -> bool {
|
||||
self.history.can_undo() || self.gesture.as_ref().is_some_and(|g| g.doc != self.doc)
|
||||
}
|
||||
pub fn can_redo(&self) -> bool {
|
||||
self.history.can_redo()
|
||||
}
|
||||
pub fn undo_label(&self) -> Option<&str> {
|
||||
self.history.undo_label()
|
||||
}
|
||||
pub fn history_len(&self) -> usize {
|
||||
self.history.undo_len()
|
||||
}
|
||||
|
||||
pub fn undo(&mut self) -> Result<Value> {
|
||||
self.end_gesture();
|
||||
let cur = self.snapshot("");
|
||||
let s = self.history.undo(cur).ok_or_else(|| EngineError::State("nothing to undo".into()))?;
|
||||
let label = s.label.clone();
|
||||
self.restore(s);
|
||||
self.revision += 1;
|
||||
self.fix_selection();
|
||||
Ok(json!({ "undone": label }))
|
||||
}
|
||||
|
||||
pub fn redo(&mut self) -> Result<Value> {
|
||||
self.end_gesture();
|
||||
let cur = self.snapshot("");
|
||||
let s = self.history.redo(cur).ok_or_else(|| EngineError::State("nothing to redo".into()))?;
|
||||
let label = s.label.clone();
|
||||
self.restore(s);
|
||||
self.revision += 1;
|
||||
self.fix_selection();
|
||||
Ok(json!({ "redone": label }))
|
||||
}
|
||||
|
||||
/// Moves through history until `undo_len()` equals `target` (for a History panel click).
|
||||
pub fn travel_to(&mut self, target: usize) -> Result<Value> {
|
||||
let mut moved = 0usize;
|
||||
while self.history.undo_len() > target && self.history.can_undo() {
|
||||
self.undo()?;
|
||||
moved += 1;
|
||||
}
|
||||
while self.history.undo_len() < target && self.history.can_redo() {
|
||||
self.redo()?;
|
||||
moved += 1;
|
||||
}
|
||||
Ok(json!({ "steps": moved, "position": self.history.undo_len() }))
|
||||
}
|
||||
|
||||
// ----- queries ---------------------------------------------------------------------------
|
||||
|
||||
pub fn frame_count(&self) -> u32 {
|
||||
self.doc.frame_count()
|
||||
}
|
||||
|
||||
pub fn active_layer(&self) -> Option<&Layer> {
|
||||
self.doc.timeline.layer(self.layer)
|
||||
}
|
||||
|
||||
pub fn active_layer_index(&self) -> Option<usize> {
|
||||
self.doc.timeline.layers.iter().position(|l| l.id == self.layer)
|
||||
}
|
||||
|
||||
/// The evaluated frame at the playhead, cached per `(state, frame)`.
|
||||
pub fn display_list(&self) -> Arc<DisplayList> {
|
||||
if let Some((s, f, dl)) = &*self.dl_cache.borrow()
|
||||
&& *s == self.state
|
||||
&& *f == self.frame
|
||||
{
|
||||
return dl.clone();
|
||||
}
|
||||
let dl = Arc::new(evaluate(&self.doc, self.frame));
|
||||
self.dl_cache.replace(Some((self.state, self.frame, dl.clone())));
|
||||
dl
|
||||
}
|
||||
|
||||
/// Elements on the active layer at the playhead (tweens applied). Shares the document's
|
||||
/// element `Arc`s on non-tweened frames.
|
||||
pub fn visible_elements(&self) -> Vec<Arc<Element>> {
|
||||
self.active_layer().and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Topmost element under `p` (stage space) on a visible, unlocked layer. A bounding-box
|
||||
/// test rejects almost every item before any curve is flattened.
|
||||
pub fn hit_test(&self, p: Vec2, slop: f32) -> Option<(LayerId, ElementId)> {
|
||||
let dl = self.display_list();
|
||||
for item in dl.items.iter().rev() {
|
||||
let hw = item.stroke.map_or(0.0, |s| s.width * 0.5 * item.transform.mean_scale());
|
||||
let bounds = item.path.bounds().transformed(&item.transform).inflate(hw + slop);
|
||||
if !bounds.contains(p) {
|
||||
continue;
|
||||
}
|
||||
let Some(layer) = self.doc.timeline.layer(item.layer) else { continue };
|
||||
if layer.locked {
|
||||
continue;
|
||||
}
|
||||
// Masked-away parts cannot be picked.
|
||||
if item.clip.is_some_and(|c| !dl.clip_contains(c, p)) {
|
||||
continue;
|
||||
}
|
||||
let inside = item.fill.is_some() && item.path.contains(p, &item.transform, item.fill_rule);
|
||||
if inside || item.path.distance_to_edge(p, &item.transform) <= hw + slop {
|
||||
return Some((item.layer, item.element));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Stage-space bounds of a top-level element at the playhead.
|
||||
pub fn element_bounds(&self, id: ElementId) -> Rect {
|
||||
let mut r = Rect::EMPTY;
|
||||
for item in self.display_list().items.iter().filter(|i| i.element == id) {
|
||||
let pad = item.stroke.map_or(0.0, |s| s.width * 0.5);
|
||||
r = r.union(&item.path.bounds().inflate(pad).transformed(&item.transform));
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Bounds of the whole selection.
|
||||
pub fn selection_bounds(&self) -> Rect {
|
||||
self.selection.iter().fold(Rect::EMPTY, |r, id| r.union(&self.element_bounds(*id)))
|
||||
}
|
||||
|
||||
/// Drops selected ids that no longer exist on the active layer at the playhead.
|
||||
pub fn fix_selection(&mut self) {
|
||||
if self.doc.timeline.layer(self.layer).is_none() {
|
||||
self.layer = self.doc.timeline.layers.first().map_or(LayerId(0), |l| l.id);
|
||||
}
|
||||
if self.selection.is_empty() {
|
||||
return;
|
||||
}
|
||||
let ids: Vec<ElementId> = self.visible_elements().iter().map(|e| e.id).collect();
|
||||
self.selection.retain(|s| ids.contains(s));
|
||||
}
|
||||
|
||||
pub fn set_frame(&mut self, frame: u32) {
|
||||
self.frame = frame.min(MAX_FRAME);
|
||||
self.fix_selection();
|
||||
}
|
||||
|
||||
// ----- mutation helpers used by commands ------------------------------------------------
|
||||
|
||||
pub(crate) fn layer_mut(&mut self, id: Option<LayerId>) -> Result<&mut Layer> {
|
||||
let id = id.unwrap_or(self.layer);
|
||||
self.doc.timeline.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))
|
||||
}
|
||||
|
||||
/// The keyframe on the active layer that edits at the playhead should change. Creates a
|
||||
/// keyframe when the playhead is inside a tween (auto-key) or past the layer's end.
|
||||
pub(crate) fn editable_keyframe(&mut self) -> Result<&mut Keyframe> {
|
||||
let frame = self.frame;
|
||||
let layer = self.layer_mut(None)?;
|
||||
if layer.locked {
|
||||
return Err(EngineError::State(format!("layer '{}' is locked", layer.name)));
|
||||
}
|
||||
let needs_key = match layer.keyframe_at(frame) {
|
||||
None => true,
|
||||
Some(k) => k.tween.is_some() && k.start != frame,
|
||||
};
|
||||
if needs_key {
|
||||
// Inside a tween: capture the tweened state. On an empty frame: start blank.
|
||||
let copy = layer.keyframe_at(frame).is_some();
|
||||
cmds_timeline::insert_keyframe_at(layer, frame, copy)?;
|
||||
}
|
||||
let idx = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State("no keyframe at the playhead".into()))?;
|
||||
layer.keyframe_mut(idx).ok_or_else(|| EngineError::State("no keyframe at the playhead".into()))
|
||||
}
|
||||
|
||||
/// Selected elements in the editable keyframe (copy-on-write: only these are cloned).
|
||||
pub(crate) fn selected_elements_mut(&mut self) -> Result<Vec<&mut Element>> {
|
||||
let sel = self.selection.clone();
|
||||
if sel.is_empty() {
|
||||
return Err(EngineError::State("nothing is selected".into()));
|
||||
}
|
||||
let kf = self.editable_keyframe()?;
|
||||
Ok(kf.elements_mut_where(|id| sel.contains(&id)))
|
||||
}
|
||||
|
||||
/// JSON summary used by `doc.info` and the CLI.
|
||||
pub fn info(&self) -> Value {
|
||||
let layers: Vec<Value> = self
|
||||
.doc
|
||||
.timeline
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
json!({
|
||||
"id": l.id.0, "name": l.name, "visible": l.visible, "locked": l.locked,
|
||||
"keyframes": l.keyframes.iter().map(|k| json!({"start": k.start, "duration": k.duration, "elements": k.elements.len(), "tween": k.tween.map(|t| t.easing.label())})).collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let symbols: Vec<Value> = self.doc.library.iter().map(|s| json!({"id": s.id.0, "name": s.name, "kind": format!("{:?}", s.kind), "frames": s.timeline.frame_count()})).collect();
|
||||
json!({
|
||||
"stage": {"width": self.doc.stage.width, "height": self.doc.stage.height, "fps": self.doc.stage.fps, "background": self.doc.stage.background.to_hex()},
|
||||
"frames": self.frame_count(),
|
||||
"frame": self.frame,
|
||||
"layer": self.layer.0,
|
||||
"selection": self.selection.iter().map(|e| e.0).collect::<Vec<_>>(),
|
||||
"layers": layers,
|
||||
"library": symbols,
|
||||
"revision": self.revision,
|
||||
"dirty": self.is_dirty(),
|
||||
"history": {"undo": self.history.undo_len(), "redo": self.history.redo_len(), "bytes": self.history.bytes(), "evicted": self.history.evicted},
|
||||
"state": self.state,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Short human label for an element (properties panel, library, CLI).
|
||||
pub fn element_label(doc: &Document, e: &Element) -> String {
|
||||
let kind = match &e.kind {
|
||||
ElementKind::Shape(_) => "Shape".to_string(),
|
||||
ElementKind::Symbol { symbol, .. } => format!("Graphic: {}", doc.symbol(*symbol).map_or("missing", |s| s.name.as_str())),
|
||||
};
|
||||
if e.name.is_empty() { kind } else { format!("{} ({kind})", e.name) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Typed, validating access to JSON command params. Every getter returns an error the caller
|
||||
//! can show, never panics, and rejects non-finite numbers.
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
use anicraft_doc::{Easing, Rgba};
|
||||
use serde_json::Value;
|
||||
|
||||
fn bad(key: &str, want: &str) -> EngineError {
|
||||
EngineError::Param(format!("param '{key}' must be {want}"))
|
||||
}
|
||||
|
||||
pub fn opt_f32(p: &Value, key: &str) -> Result<Option<f32>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => {
|
||||
let f = v.as_f64().ok_or_else(|| bad(key, "a number"))?;
|
||||
if !f.is_finite() || f.abs() > 1e7 {
|
||||
return Err(bad(key, "a finite number within ±10,000,000"));
|
||||
}
|
||||
Ok(Some(f as f32))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn f32_req(p: &Value, key: &str) -> Result<f32> {
|
||||
opt_f32(p, key)?.ok_or_else(|| bad(key, "given (a number)"))
|
||||
}
|
||||
|
||||
pub fn opt_u32(p: &Value, key: &str) -> Result<Option<u32>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => {
|
||||
let n = v.as_u64().ok_or_else(|| bad(key, "a non-negative integer"))?;
|
||||
u32::try_from(n).map(Some).map_err(|_| bad(key, "an integer below 4,294,967,296"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn opt_u64(p: &Value, key: &str) -> Result<Option<u64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(key, "a non-negative integer")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn opt_str<'a>(p: &'a Value, key: &str) -> Result<Option<&'a str>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_str().map(Some).ok_or_else(|| bad(key, "a string")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn str_req<'a>(p: &'a Value, key: &str) -> Result<&'a str> {
|
||||
opt_str(p, key)?.ok_or_else(|| bad(key, "given (a string)"))
|
||||
}
|
||||
|
||||
pub fn opt_bool(p: &Value, key: &str) -> Result<Option<bool>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(key, "true or false")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn opt_color(p: &Value, key: &str) -> Result<Option<Rgba>> {
|
||||
match opt_str(p, key)? {
|
||||
None => Ok(None),
|
||||
Some(s) => Rgba::parse_hex(s).map(Some).ok_or_else(|| bad(key, "a colour like \"#ff8800\"")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn opt_u64_list(p: &Value, key: &str) -> Result<Option<Vec<u64>>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Array(a)) => {
|
||||
if a.len() > 100_000 {
|
||||
return Err(bad(key, "a list of at most 100,000 ids"));
|
||||
}
|
||||
a.iter().map(|v| v.as_u64().ok_or_else(|| bad(key, "a list of integer ids"))).collect::<Result<Vec<_>>>().map(Some)
|
||||
}
|
||||
Some(_) => Err(bad(key, "a list of integer ids")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Easing from a preset name (`"Linear"`, `"QuadIn"`…), `{"classic": n}` or `{"bezier": [x1,y1,x2,y2]}`.
|
||||
pub fn opt_easing(p: &Value, key: &str) -> Result<Option<Easing>> {
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
if v.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(s) = v.as_str() {
|
||||
let e = match s.to_ascii_lowercase().replace(['-', '_', ' '], "").as_str() {
|
||||
"linear" | "none" => Easing::Linear,
|
||||
"quadin" | "easein" => Easing::QuadIn,
|
||||
"quadout" | "easeout" => Easing::QuadOut,
|
||||
"quadinout" | "easeinout" => Easing::QuadInOut,
|
||||
"cubicin" => Easing::CubicIn,
|
||||
"cubicout" => Easing::CubicOut,
|
||||
"cubicinout" => Easing::CubicInOut,
|
||||
"smooth" => Easing::CubicBezier(0.25, 0.1, 0.25, 1.0),
|
||||
_ => return Err(bad(key, "one of Linear, QuadIn, QuadOut, QuadInOut, CubicIn, CubicOut, CubicInOut, Smooth")),
|
||||
};
|
||||
return Ok(Some(e));
|
||||
}
|
||||
if let Some(c) = v.get("classic") {
|
||||
let s = c.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(key, "{\"classic\": -100..100}"))?;
|
||||
return Ok(Some(Easing::Classic((s as f32).clamp(-100.0, 100.0))));
|
||||
}
|
||||
if let Some(Value::Array(b)) = v.get("bezier") {
|
||||
let n: Vec<f32> = b.iter().filter_map(Value::as_f64).filter(|f| f.is_finite()).map(|f| f as f32).collect();
|
||||
if let [x1, y1, x2, y2] = n[..] {
|
||||
return Ok(Some(Easing::CubicBezier(x1.clamp(0.0, 1.0), y1.clamp(-5.0, 5.0), x2.clamp(0.0, 1.0), y2.clamp(-5.0, 5.0))));
|
||||
}
|
||||
}
|
||||
Err(bad(key, "an easing name, {\"classic\": n} or {\"bezier\": [x1, y1, x2, y2]}"))
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
//! Background rendering of stage tiles and frames, with a memory-bounded cache.
|
||||
//!
|
||||
//! The stage is drawn from **tiles** (ADR 0007): fixed-size pieces of the stage at a zoom level,
|
||||
//! each a [`FrameJob`]. The UI asks for the tiles it needs as one **batch**. The worker takes the
|
||||
//! whole batch, evaluates the scene **once per (state, frame, onion)** (the job's `scene`), and
|
||||
//! renders the tiles in parallel. Newer batches replace older pending ones (latest wins), so a
|
||||
//! drag or a fast pan never builds a backlog. Jobs carry a `Document` clone, which is O(layers)
|
||||
//! thanks to structural sharing. Keys hash the document *state id*, so undoing back to a state
|
||||
//! already rendered is a cache hit.
|
||||
|
||||
use crate::history::StateId;
|
||||
use anicraft_doc::{ColorEffect, DisplayList, Document, Rgba, evaluate};
|
||||
use anicraft_render::{RenderStats, View, render};
|
||||
use rayon::prelude::*;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Instant;
|
||||
|
||||
/// One image to render: a whole frame or one stage tile.
|
||||
#[derive(Clone)]
|
||||
pub struct FrameJob {
|
||||
pub key: u64,
|
||||
/// Identity of the evaluated scene (`scene_key`): tiles of one frame share it.
|
||||
pub scene: u64,
|
||||
pub doc: Document,
|
||||
pub frame: u32,
|
||||
pub view: View,
|
||||
pub onion: bool,
|
||||
}
|
||||
|
||||
/// A finished image: premultiplied RGBA8, ready for a texture upload.
|
||||
pub struct FrameImage {
|
||||
pub key: u64,
|
||||
pub frame: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba_premul: Vec<u8>,
|
||||
pub ms: f32,
|
||||
pub stats: RenderStats,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Identity of an evaluated scene: the display list depends on these and nothing else.
|
||||
pub fn scene_key(state: StateId, frame: u32, onion: bool) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
(state, frame, onion).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Cache key for a scene seen through a view (a frame or a tile).
|
||||
pub fn frame_key(state: StateId, frame: u32, view: &View, onion: bool) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
state.hash(&mut h);
|
||||
frame.hash(&mut h);
|
||||
for v in view.transform.m {
|
||||
v.to_bits().hash(&mut h);
|
||||
}
|
||||
view.width.hash(&mut h);
|
||||
view.height.hash(&mut h);
|
||||
if let Some(bg) = view.background {
|
||||
[bg.r, bg.g, bg.b, bg.a].map(f32::to_bits).hash(&mut h);
|
||||
}
|
||||
onion.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// A job whose `scene` is derived from the same inputs as its key.
|
||||
pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
|
||||
FrameJob { key: frame_key(state, frame, &view, onion), scene: scene_key(state, frame, onion), doc: doc.clone(), frame, view, onion }
|
||||
}
|
||||
|
||||
/// The frame's display list, with ±2 onion-skin frames (tinted red before, green after) underneath.
|
||||
pub fn display_list_with_onion(doc: &Document, frame: u32, onion: bool) -> DisplayList {
|
||||
let mut dl = DisplayList::default();
|
||||
if onion {
|
||||
let n = i64::from(doc.frame_count());
|
||||
for (off, tint, alpha) in [(-2i64, 0xff5a5a, 0.12f32), (2, 0x4cd07d, 0.12), (-1, 0xff5a5a, 0.25), (1, 0x4cd07d, 0.25)] {
|
||||
let f = i64::from(frame) + off;
|
||||
if f < 0 || f >= n {
|
||||
continue;
|
||||
}
|
||||
let mut ghost = evaluate(doc, f as u32);
|
||||
for item in &mut ghost.items {
|
||||
item.color = item.color.concat(&ColorEffect { alpha, tint: Rgba::hex(tint), tint_amount: 1.0 });
|
||||
}
|
||||
dl.append(ghost);
|
||||
}
|
||||
}
|
||||
dl.append(evaluate(doc, frame));
|
||||
dl
|
||||
}
|
||||
|
||||
/// Renders a job against an already evaluated scene.
|
||||
pub fn render_job_with(job: &FrameJob, dl: &DisplayList) -> FrameImage {
|
||||
let t0 = Instant::now();
|
||||
// Last-resort guard: a renderer bug must not take the editor down with it.
|
||||
let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render(dl, &job.view)));
|
||||
let (rgba, stats, error) = match out {
|
||||
Ok(Ok((pm, stats))) => (pm.to_premul_rgba8(), stats, None),
|
||||
Ok(Err(e)) => (Vec::new(), RenderStats::default(), Some(e.to_string())),
|
||||
Err(_) => (Vec::new(), RenderStats::default(), Some("the renderer failed on this frame".into())),
|
||||
};
|
||||
let (width, height) = if error.is_none() { (job.view.width, job.view.height) } else { (0, 0) };
|
||||
FrameImage { key: job.key, frame: job.frame, width, height, rgba_premul: rgba, ms: t0.elapsed().as_secs_f32() * 1000.0, stats, error }
|
||||
}
|
||||
|
||||
/// Renders a job synchronously, evaluating its scene.
|
||||
pub fn render_job(job: &FrameJob) -> FrameImage {
|
||||
render_job_with(job, &display_list_with_onion(&job.doc, job.frame, job.onion))
|
||||
}
|
||||
|
||||
/// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel.
|
||||
pub fn render_batch(jobs: &[FrameJob]) -> Vec<FrameImage> {
|
||||
let mut scenes: HashMap<u64, Arc<DisplayList>> = HashMap::new();
|
||||
for j in jobs {
|
||||
scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_with_onion(&j.doc, j.frame, j.onion)));
|
||||
}
|
||||
jobs.par_iter()
|
||||
.map(|j| match scenes.get(&j.scene) {
|
||||
Some(dl) => render_job_with(j, dl),
|
||||
None => render_job(j),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// LRU cache of finished images, bounded by bytes.
|
||||
pub struct FrameCache {
|
||||
map: HashMap<u64, (Arc<FrameImage>, u64)>,
|
||||
tick: u64,
|
||||
bytes: usize,
|
||||
pub budget_bytes: usize,
|
||||
pub hits: u64,
|
||||
pub misses: u64,
|
||||
}
|
||||
|
||||
impl FrameCache {
|
||||
pub fn new(budget_bytes: usize) -> Self {
|
||||
FrameCache { map: HashMap::new(), tick: 0, bytes: 0, budget_bytes, hits: 0, misses: 0 }
|
||||
}
|
||||
pub fn get(&mut self, key: u64) -> Option<Arc<FrameImage>> {
|
||||
self.tick += 1;
|
||||
let tick = self.tick;
|
||||
match self.map.get_mut(&key) {
|
||||
Some((img, t)) => {
|
||||
*t = tick;
|
||||
self.hits += 1;
|
||||
Some(img.clone())
|
||||
}
|
||||
None => {
|
||||
self.misses += 1;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn contains(&self, key: u64) -> bool {
|
||||
self.map.contains_key(&key)
|
||||
}
|
||||
pub fn insert(&mut self, img: Arc<FrameImage>) {
|
||||
self.tick += 1;
|
||||
let size = img.rgba_premul.len() + std::mem::size_of::<FrameImage>();
|
||||
if let Some((old, _)) = self.map.insert(img.key, (img, self.tick)) {
|
||||
self.bytes = self.bytes.saturating_sub(old.rgba_premul.len() + std::mem::size_of::<FrameImage>());
|
||||
}
|
||||
self.bytes += size;
|
||||
while self.bytes > self.budget_bytes && self.map.len() > 1 {
|
||||
let Some((&victim, _)) = self.map.iter().min_by_key(|(_, (_, t))| *t) else { break };
|
||||
if let Some((old, _)) = self.map.remove(&victim) {
|
||||
self.bytes = self.bytes.saturating_sub(old.rgba_premul.len() + std::mem::size_of::<FrameImage>());
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.map.is_empty()
|
||||
}
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Queue {
|
||||
/// What the screen needs now (replaced by each new batch).
|
||||
urgent: VecDeque<FrameJob>,
|
||||
/// Look-ahead: margin tiles and upcoming playback frames (replaced wholesale).
|
||||
prefetch: VecDeque<FrameJob>,
|
||||
busy: HashSet<u64>,
|
||||
shutdown: bool,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
queue: Mutex<Queue>,
|
||||
wake: Condvar,
|
||||
cache: Mutex<FrameCache>,
|
||||
notify: Option<Box<dyn Fn() + Send + Sync>>,
|
||||
}
|
||||
|
||||
/// Default image-cache budget.
|
||||
pub const DEFAULT_CACHE_BYTES: usize = 768 * 1024 * 1024;
|
||||
/// Most jobs the worker renders in one parallel pass.
|
||||
const BATCH: usize = 32;
|
||||
|
||||
/// A render thread plus its cache.
|
||||
pub struct RenderService {
|
||||
shared: Arc<Shared>,
|
||||
worker: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl RenderService {
|
||||
/// Starts the worker. `notify` runs on the worker after each finished batch (the UI passes
|
||||
/// "request a repaint"). If no thread can be spawned, requests render synchronously.
|
||||
pub fn new(cache_bytes: usize, notify: Option<Box<dyn Fn() + Send + Sync>>) -> RenderService {
|
||||
let shared = Arc::new(Shared { queue: Mutex::new(Queue::default()), wake: Condvar::new(), cache: Mutex::new(FrameCache::new(cache_bytes)), notify });
|
||||
let s = shared.clone();
|
||||
let worker = std::thread::Builder::new().name("anicraft-render".into()).spawn(move || worker_loop(&s)).ok();
|
||||
RenderService { shared, worker }
|
||||
}
|
||||
|
||||
fn cache(&self) -> std::sync::MutexGuard<'_, FrameCache> {
|
||||
self.shared.cache.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn queue(&self) -> std::sync::MutexGuard<'_, Queue> {
|
||||
self.shared.queue.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Images that are ready, in order; the missing ones become the new urgent batch
|
||||
/// (replacing any older pending batch).
|
||||
pub fn request_batch(&self, jobs: Vec<FrameJob>) -> Vec<Option<Arc<FrameImage>>> {
|
||||
let mut out = Vec::with_capacity(jobs.len());
|
||||
let mut missing = Vec::new();
|
||||
{
|
||||
let mut cache = self.cache();
|
||||
for j in jobs {
|
||||
match cache.get(j.key) {
|
||||
Some(img) => out.push(Some(img)),
|
||||
None => {
|
||||
out.push(None);
|
||||
missing.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if missing.is_empty() {
|
||||
return out;
|
||||
}
|
||||
if self.worker.is_none() {
|
||||
// No thread available: render here, so the caller still gets pictures.
|
||||
let imgs: Vec<Arc<FrameImage>> = render_batch(&missing).into_iter().map(Arc::new).collect();
|
||||
let mut cache = self.cache();
|
||||
for img in &imgs {
|
||||
cache.insert(img.clone());
|
||||
}
|
||||
let mut it = imgs.into_iter();
|
||||
for slot in out.iter_mut().filter(|s| s.is_none()) {
|
||||
*slot = it.next();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
let mut q = self.queue();
|
||||
let busy = q.busy.clone();
|
||||
q.urgent = missing.into_iter().filter(|j| !busy.contains(&j.key)).collect();
|
||||
if !q.urgent.is_empty() {
|
||||
self.shared.wake.notify_one();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Single-image form of [`RenderService::request_batch`].
|
||||
pub fn request(&self, job: FrameJob) -> Option<Arc<FrameImage>> {
|
||||
self.request_batch(vec![job]).into_iter().next().flatten()
|
||||
}
|
||||
|
||||
/// Renders on the calling thread (one scene evaluation, tiles in parallel) and caches the
|
||||
/// results: for edits, where showing the change in this frame matters most.
|
||||
pub fn render_now_batch(&self, jobs: Vec<FrameJob>) -> Vec<Arc<FrameImage>> {
|
||||
let (mut out, missing): (Vec<Option<Arc<FrameImage>>>, Vec<FrameJob>) = {
|
||||
let mut cache = self.cache();
|
||||
let mut missing = Vec::new();
|
||||
let out = jobs
|
||||
.into_iter()
|
||||
.map(|j| {
|
||||
let hit = cache.get(j.key);
|
||||
if hit.is_none() {
|
||||
missing.push(j);
|
||||
}
|
||||
hit
|
||||
})
|
||||
.collect();
|
||||
(out, missing)
|
||||
};
|
||||
let fresh: Vec<Arc<FrameImage>> = render_batch(&missing).into_iter().map(Arc::new).collect();
|
||||
{
|
||||
let mut cache = self.cache();
|
||||
for img in &fresh {
|
||||
cache.insert(img.clone());
|
||||
}
|
||||
}
|
||||
let mut it = fresh.into_iter();
|
||||
for slot in out.iter_mut().filter(|s| s.is_none()) {
|
||||
*slot = it.next();
|
||||
}
|
||||
out.into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
/// Single-image form of [`RenderService::render_now_batch`].
|
||||
pub fn render_now(&self, job: FrameJob) -> Arc<FrameImage> {
|
||||
let key = job.key;
|
||||
let frame = job.frame;
|
||||
self.render_now_batch(vec![job]).into_iter().next().unwrap_or_else(|| {
|
||||
Arc::new(FrameImage { key, frame, width: 0, height: 0, rgba_premul: Vec::new(), ms: 0.0, stats: RenderStats::default(), error: Some("render failed".into()) })
|
||||
})
|
||||
}
|
||||
|
||||
/// Replaces the look-ahead queue (images already cached are skipped).
|
||||
pub fn prefetch(&self, jobs: Vec<FrameJob>) {
|
||||
if self.worker.is_none() {
|
||||
return;
|
||||
}
|
||||
let jobs: VecDeque<FrameJob> = {
|
||||
let cache = self.cache();
|
||||
jobs.into_iter().filter(|j| !cache.contains(j.key)).collect()
|
||||
};
|
||||
let mut q = self.queue();
|
||||
q.prefetch = jobs;
|
||||
if !q.prefetch.is_empty() {
|
||||
self.shared.wake.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the worker has queued or in-flight work.
|
||||
pub fn busy(&self) -> bool {
|
||||
let q = self.queue();
|
||||
!q.busy.is_empty() || !q.urgent.is_empty() || !q.prefetch.is_empty()
|
||||
}
|
||||
|
||||
/// `(images, bytes, hits, misses)`.
|
||||
pub fn cache_stats(&self) -> (usize, usize, u64, u64) {
|
||||
let c = self.cache();
|
||||
(c.len(), c.bytes(), c.hits, c.misses)
|
||||
}
|
||||
|
||||
/// Blocks until `key` is rendered (tests, headless tools). Times out after `ms`.
|
||||
pub fn wait_for(&self, key: u64, ms: u64) -> Option<Arc<FrameImage>> {
|
||||
let deadline = Instant::now() + std::time::Duration::from_millis(ms);
|
||||
while Instant::now() < deadline {
|
||||
if let Some(img) = self.cache().get(key) {
|
||||
return Some(img);
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RenderService {
|
||||
fn drop(&mut self) {
|
||||
{
|
||||
let mut q = self.queue();
|
||||
q.shutdown = true;
|
||||
q.urgent.clear();
|
||||
q.prefetch.clear();
|
||||
}
|
||||
self.shared.wake.notify_all();
|
||||
if let Some(w) = self.worker.take() {
|
||||
let _ = w.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn worker_loop(s: &Shared) {
|
||||
loop {
|
||||
// Take a whole batch: urgent first, topped up with prefetch work.
|
||||
let jobs: Vec<FrameJob> = {
|
||||
let mut q = s.queue.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
loop {
|
||||
if q.shutdown {
|
||||
return;
|
||||
}
|
||||
if !q.urgent.is_empty() || !q.prefetch.is_empty() {
|
||||
let mut batch = Vec::new();
|
||||
while batch.len() < BATCH {
|
||||
let Some(j) = q.urgent.pop_front().or_else(|| q.prefetch.pop_front()) else { break };
|
||||
batch.push(j);
|
||||
}
|
||||
for j in &batch {
|
||||
q.busy.insert(j.key);
|
||||
}
|
||||
break batch;
|
||||
}
|
||||
q = s.wake.wait(q).unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
};
|
||||
let todo: Vec<FrameJob> = {
|
||||
let cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
jobs.iter().filter(|j| !cache.contains(j.key)).cloned().collect()
|
||||
};
|
||||
let imgs = render_batch(&todo);
|
||||
{
|
||||
let mut cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for img in imgs {
|
||||
cache.insert(Arc::new(img));
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut q = s.queue.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for j in &jobs {
|
||||
q.busy.remove(&j.key);
|
||||
}
|
||||
}
|
||||
if let Some(n) = &s.notify {
|
||||
n();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_doc::sample;
|
||||
use anicraft_geom::Affine;
|
||||
|
||||
fn job(doc: &Document, state: u64, frame: u32) -> FrameJob {
|
||||
let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) };
|
||||
make_job(state, doc, frame, view, false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_matches_synchronous_render() {
|
||||
let doc = sample::demo();
|
||||
let svc = RenderService::new(64 << 20, None);
|
||||
let j = job(&doc, 1, 9);
|
||||
let direct = render_job(&j);
|
||||
assert!(svc.request(j.clone()).is_none(), "first request is queued");
|
||||
let img = svc.wait_for(j.key, 10_000).unwrap();
|
||||
assert_eq!(img.rgba_premul, direct.rgba_premul);
|
||||
// second request is a cache hit
|
||||
assert!(svc.request(j).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_now_is_synchronous_and_cached() {
|
||||
let doc = sample::demo();
|
||||
let svc = RenderService::new(64 << 20, None);
|
||||
let j = job(&doc, 3, 4);
|
||||
let img = svc.render_now(j.clone());
|
||||
assert_eq!(img.rgba_premul, render_job(&j).rgba_premul);
|
||||
assert!(svc.request(j).is_some(), "available to later requests without re-rendering");
|
||||
}
|
||||
|
||||
/// Tiles rendered separately and stitched match one full render to within 1/255 per
|
||||
/// channel (float rounding differs at anti-aliased edges when coordinates are offset), with
|
||||
/// differences rare: no visible seams. Each tile itself is deterministic.
|
||||
#[test]
|
||||
fn stitched_tiles_match_a_full_render() {
|
||||
let doc = sample::demo();
|
||||
let z = 0.37f32; // deliberately odd zoom
|
||||
let (w, h) = ((1280.0 * z).ceil() as u32, (720.0 * z).ceil() as u32);
|
||||
let bg = Some(doc.stage.background);
|
||||
let full = render_job(&make_job(1, &doc, 13, View { transform: Affine::scale(z, z), width: w, height: h, background: bg }, false));
|
||||
let t = 128u32;
|
||||
let mut jobs = Vec::new();
|
||||
for ty in 0..h.div_ceil(t) {
|
||||
for tx in 0..w.div_ceil(t) {
|
||||
let view = View {
|
||||
transform: Affine::translate(-((tx * t) as f32), -((ty * t) as f32)).mul(&Affine::scale(z, z)),
|
||||
width: t.min(w - tx * t),
|
||||
height: t.min(h - ty * t),
|
||||
background: bg,
|
||||
};
|
||||
jobs.push((tx, ty, make_job(1, &doc, 13, view, false)));
|
||||
}
|
||||
}
|
||||
let batch: Vec<FrameJob> = jobs.iter().map(|(_, _, j)| j.clone()).collect();
|
||||
let imgs = render_batch(&batch);
|
||||
assert!(jobs.windows(2).all(|p| p[0].2.scene == p[1].2.scene), "one scene for all tiles");
|
||||
let (mut differing, mut total) = (0usize, 0usize);
|
||||
for ((tx, ty, _), img) in jobs.iter().zip(&imgs) {
|
||||
for y in 0..img.height {
|
||||
for x in 0..img.width {
|
||||
let (gx, gy) = (tx * t + x, ty * t + y);
|
||||
let a = ((y * img.width + x) * 4) as usize;
|
||||
let b = ((gy * w + gx) * 4) as usize;
|
||||
let (p, q) = (&img.rgba_premul[a..a + 4], &full.rgba_premul[b..b + 4]);
|
||||
let d = p.iter().zip(q).map(|(u, v)| u.abs_diff(*v)).max().unwrap_or(0);
|
||||
assert!(d <= 1, "tile ({tx},{ty}) px ({x},{y}): {p:?} vs {q:?}");
|
||||
differing += usize::from(d > 0);
|
||||
total += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(differing * 200 < total, "{differing} of {total} pixels differ (by 1/255)");
|
||||
// determinism: the same tile twice gives the same bytes
|
||||
assert_eq!(render_batch(&batch[..1])[0].rgba_premul, imgs[0].rgba_premul);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batches_replace_pending_work_and_complete() {
|
||||
let doc = sample::demo();
|
||||
let svc = RenderService::new(64 << 20, None);
|
||||
let first: Vec<FrameJob> = (0..8).map(|f| job(&doc, 7, f)).collect();
|
||||
let second: Vec<FrameJob> = (20..24).map(|f| job(&doc, 7, f)).collect();
|
||||
let keys: Vec<u64> = second.iter().map(|j| j.key).collect();
|
||||
let _ = svc.request_batch(first);
|
||||
let r = svc.request_batch(second);
|
||||
assert!(r.iter().all(Option::is_none));
|
||||
for k in keys {
|
||||
assert!(svc.wait_for(k, 10_000).is_some(), "the latest batch is always rendered");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefetch_fills_cache() {
|
||||
let doc = sample::demo();
|
||||
let svc = RenderService::new(64 << 20, None);
|
||||
let jobs: Vec<FrameJob> = (0..6).map(|f| job(&doc, 2, f)).collect();
|
||||
let keys: Vec<u64> = jobs.iter().map(|j| j.key).collect();
|
||||
svc.prefetch(jobs);
|
||||
for k in keys {
|
||||
assert!(svc.wait_for(k, 10_000).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_respects_budget_lru() {
|
||||
let mut c = FrameCache::new(3 * 1000);
|
||||
for k in 0..10u64 {
|
||||
c.insert(Arc::new(FrameImage { key: k, frame: 0, width: 0, height: 0, rgba_premul: vec![0; 800], ms: 0.0, stats: RenderStats::default(), error: None }));
|
||||
}
|
||||
assert!(c.bytes() <= 3000);
|
||||
assert!(c.contains(9) && !c.contains(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_distinguish_state_frame_and_view() {
|
||||
let doc = sample::demo();
|
||||
let a = job(&doc, 1, 0).key;
|
||||
assert_ne!(a, job(&doc, 2, 0).key);
|
||||
assert_ne!(a, job(&doc, 1, 1).key);
|
||||
assert_eq!(a, job(&doc, 1, 0).key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn onion_adds_neighbour_frames() {
|
||||
let doc = sample::demo();
|
||||
let plain = display_list_with_onion(&doc, 10, false).items.len();
|
||||
let onion = display_list_with_onion(&doc, 10, true).items.len();
|
||||
assert_eq!(onion, plain * 5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "anicraft-geom"
|
||||
description = "AniCraft L0: points, affine transforms, Bezier paths, flattening and hit testing"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,205 @@
|
||||
//! 2D affine transforms and their decomposition for tweening.
|
||||
|
||||
use crate::Vec2;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Affine transform `[a b c d e f]` mapping `(x, y)` to `(a x + c y + e, b x + d y + f)`
|
||||
/// (the column convention used by SVG, PDF and most animation formats).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Affine {
|
||||
pub m: [f32; 6],
|
||||
}
|
||||
|
||||
impl Default for Affine {
|
||||
fn default() -> Self {
|
||||
Affine::IDENTITY
|
||||
}
|
||||
}
|
||||
|
||||
impl Affine {
|
||||
pub const IDENTITY: Affine = Affine { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] };
|
||||
|
||||
pub fn translate(tx: f32, ty: f32) -> Affine {
|
||||
Affine { m: [1.0, 0.0, 0.0, 1.0, tx, ty] }
|
||||
}
|
||||
pub fn scale(sx: f32, sy: f32) -> Affine {
|
||||
Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }
|
||||
}
|
||||
/// Rotation by `radians` (clockwise on a y-down screen).
|
||||
pub fn rotate(radians: f32) -> Affine {
|
||||
let (s, c) = radians.sin_cos();
|
||||
Affine { m: [c, s, -s, c, 0.0, 0.0] }
|
||||
}
|
||||
|
||||
/// `self ∘ other`: apply `other` first, then `self`.
|
||||
pub fn then_apply_to(&self, other: &Affine) -> Affine {
|
||||
let [a, b, c, d, e, f] = self.m;
|
||||
let [a2, b2, c2, d2, e2, f2] = other.m;
|
||||
Affine {
|
||||
m: [
|
||||
a * a2 + c * b2,
|
||||
b * a2 + d * b2,
|
||||
a * c2 + c * d2,
|
||||
b * c2 + d * d2,
|
||||
a * e2 + c * f2 + e,
|
||||
b * e2 + d * f2 + f,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Composition in reading order: `a.mul(b)` applies `b` first, then `a`.
|
||||
pub fn mul(&self, other: &Affine) -> Affine {
|
||||
self.then_apply_to(other)
|
||||
}
|
||||
|
||||
pub fn apply(&self, p: Vec2) -> Vec2 {
|
||||
let [a, b, c, d, e, f] = self.m;
|
||||
Vec2::new(a * p.x + c * p.y + e, b * p.x + d * p.y + f)
|
||||
}
|
||||
|
||||
/// Applies only the linear part (for vectors).
|
||||
pub fn apply_vector(&self, v: Vec2) -> Vec2 {
|
||||
let [a, b, c, d, _, _] = self.m;
|
||||
Vec2::new(a * v.x + c * v.y, b * v.x + d * v.y)
|
||||
}
|
||||
|
||||
pub fn determinant(&self) -> f32 {
|
||||
self.m[0] * self.m[3] - self.m[1] * self.m[2]
|
||||
}
|
||||
|
||||
/// Inverse, or `None` for a singular (or non-finite) matrix.
|
||||
pub fn inverse(&self) -> Option<Affine> {
|
||||
let det = self.determinant();
|
||||
if !det.is_finite() || det.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let [a, b, c, d, e, f] = self.m;
|
||||
let inv = 1.0 / det;
|
||||
let ia = d * inv;
|
||||
let ib = -b * inv;
|
||||
let ic = -c * inv;
|
||||
let id = a * inv;
|
||||
Some(Affine { m: [ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)] })
|
||||
}
|
||||
|
||||
pub fn translation(&self) -> Vec2 {
|
||||
Vec2::new(self.m[4], self.m[5])
|
||||
}
|
||||
|
||||
pub fn is_finite(&self) -> bool {
|
||||
self.m.iter().all(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Approximate uniform scale factor (sqrt of |det|), used for stroke widths and tolerances.
|
||||
pub fn mean_scale(&self) -> f32 {
|
||||
self.determinant().abs().sqrt()
|
||||
}
|
||||
|
||||
/// Decompose into translation, rotation, scale and skew (QR-style).
|
||||
pub fn decompose(&self) -> Decomposed {
|
||||
let [a, b, c, d, e, f] = self.m;
|
||||
let sx = (a * a + b * b).sqrt();
|
||||
let rotation = b.atan2(a);
|
||||
let det = a * d - b * c;
|
||||
let (sy, skew) = if sx > 1e-12 {
|
||||
let sy = det / sx;
|
||||
// col1 · col2 = sx · sy · skew
|
||||
let skew = if det.abs() > 1e-12 { (a * c + b * d) / det } else { 0.0 };
|
||||
(sy, skew)
|
||||
} else {
|
||||
((c * c + d * d).sqrt(), 0.0)
|
||||
};
|
||||
Decomposed { tx: e, ty: f, sx, sy, rotation, skew }
|
||||
}
|
||||
}
|
||||
|
||||
/// Transform components that interpolate well over time.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Decomposed {
|
||||
pub tx: f32,
|
||||
pub ty: f32,
|
||||
pub sx: f32,
|
||||
pub sy: f32,
|
||||
/// Radians.
|
||||
pub rotation: f32,
|
||||
/// Shear factor (x += skew * y before scaling).
|
||||
pub skew: f32,
|
||||
}
|
||||
|
||||
impl Default for Decomposed {
|
||||
fn default() -> Self {
|
||||
Decomposed { tx: 0.0, ty: 0.0, sx: 1.0, sy: 1.0, rotation: 0.0, skew: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Decomposed {
|
||||
/// `T · R · Shear · S` — the inverse of [`Affine::decompose`].
|
||||
pub fn compose(&self) -> Affine {
|
||||
let t = Affine::translate(self.tx, self.ty);
|
||||
let r = Affine::rotate(self.rotation);
|
||||
let k = Affine { m: [1.0, 0.0, self.skew, 1.0, 0.0, 0.0] };
|
||||
let s = Affine::scale(self.sx, self.sy);
|
||||
t.mul(&r).mul(&k).mul(&s)
|
||||
}
|
||||
|
||||
/// Component-wise interpolation; rotation takes the shortest arc.
|
||||
pub fn lerp(&self, o: &Decomposed, t: f32) -> Decomposed {
|
||||
let mut dr = o.rotation - self.rotation;
|
||||
let tau = std::f32::consts::TAU;
|
||||
while dr > std::f32::consts::PI {
|
||||
dr -= tau;
|
||||
}
|
||||
while dr < -std::f32::consts::PI {
|
||||
dr += tau;
|
||||
}
|
||||
Decomposed {
|
||||
tx: crate::lerp(self.tx, o.tx, t),
|
||||
ty: crate::lerp(self.ty, o.ty, t),
|
||||
sx: crate::lerp(self.sx, o.sx, t),
|
||||
sy: crate::lerp(self.sy, o.sy, t),
|
||||
rotation: self.rotation + dr * t,
|
||||
skew: crate::lerp(self.skew, o.skew, t),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn close(a: &Affine, b: &Affine) -> bool {
|
||||
a.m.iter().zip(b.m.iter()).all(|(x, y)| (x - y).abs() < 1e-4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_roundtrip() {
|
||||
let m = Affine::translate(10.0, -4.0).mul(&Affine::rotate(0.7)).mul(&Affine::scale(2.0, 0.5));
|
||||
let inv = m.inverse().unwrap();
|
||||
assert!(close(&m.mul(&inv), &Affine::IDENTITY));
|
||||
assert!(Affine::scale(0.0, 1.0).inverse().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompose_compose_identity() {
|
||||
for (rot, sx, sy, skew) in [(0.3, 2.0, 1.5, 0.0), (-2.5, 0.5, 3.0, 0.2), (1.0, 1.0, -1.0, 0.0)] {
|
||||
let d = Decomposed { tx: 5.0, ty: 7.0, sx, sy, rotation: rot, skew };
|
||||
let m = d.compose();
|
||||
let back = m.decompose().compose();
|
||||
assert!(close(&m, &back), "{m:?} vs {back:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_lerp_takes_short_arc() {
|
||||
let a = Decomposed { rotation: 3.0, ..Default::default() };
|
||||
let b = Decomposed { rotation: -3.0, ..Default::default() };
|
||||
let mid = a.lerp(&b, 0.5);
|
||||
assert!((mid.rotation.abs() - std::f32::consts::PI).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_order() {
|
||||
let m = Affine::translate(10.0, 0.0).mul(&Affine::scale(2.0, 2.0));
|
||||
assert_eq!(m.apply(Vec2::new(1.0, 1.0)), Vec2::new(12.0, 2.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
//! Point editing on Bézier paths: addressing anchors and handles, splitting and removing
|
||||
//! segments, smooth/corner conversion and nearest-segment search.
|
||||
//!
|
||||
//! Addressing: command `i` of a path owns its *end point* (the anchor, slot 0) and its control
|
||||
//! points: slot 1 is the first control point (`QuadTo`'s or `CubicTo`'s `c1`, the out-handle of
|
||||
//! the previous anchor) and slot 2 is `CubicTo`'s `c2` (the in-handle of anchor `i`).
|
||||
|
||||
use crate::{Affine, Path, PathCmd, Vec2};
|
||||
|
||||
/// Slot numbers.
|
||||
pub const ANCHOR: u8 = 0;
|
||||
pub const C1: u8 = 1;
|
||||
pub const C2: u8 = 2;
|
||||
|
||||
/// Points closer than this (stage units) are the same anchor.
|
||||
const LINK_EPS: f32 = 1e-3;
|
||||
|
||||
impl Path {
|
||||
/// The point at `(cmd, slot)`.
|
||||
pub fn point(&self, cmd: usize, slot: u8) -> Option<Vec2> {
|
||||
match (self.cmds.get(cmd)?, slot) {
|
||||
(PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p), ANCHOR) => Some(*p),
|
||||
(PathCmd::QuadTo(c, _) | PathCmd::CubicTo(c, _, _), C1) => Some(*c),
|
||||
(PathCmd::CubicTo(_, c, _), C2) => Some(*c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the point at `(cmd, slot)`; false when it does not exist or `p` is not finite.
|
||||
pub fn set_point(&mut self, cmd: usize, slot: u8, p: Vec2) -> bool {
|
||||
if !p.is_finite() {
|
||||
return false;
|
||||
}
|
||||
let Some(c) = self.cmds.get_mut(cmd) else { return false };
|
||||
let target = match (c, slot) {
|
||||
(PathCmd::MoveTo(a) | PathCmd::LineTo(a) | PathCmd::QuadTo(_, a) | PathCmd::CubicTo(_, _, a), ANCHOR) => a,
|
||||
(PathCmd::QuadTo(c1, _) | PathCmd::CubicTo(c1, _, _), C1) => c1,
|
||||
(PathCmd::CubicTo(_, c2, _), C2) => c2,
|
||||
_ => return false,
|
||||
};
|
||||
*target = p;
|
||||
true
|
||||
}
|
||||
|
||||
/// Commands that own an anchor, with the anchor position.
|
||||
pub fn anchors(&self) -> Vec<(usize, Vec2)> {
|
||||
(0..self.cmds.len()).filter_map(|i| self.point(i, ANCHOR).map(|p| (i, p))).collect()
|
||||
}
|
||||
|
||||
/// The point a segment command starts from (previous anchor, or the subpath start after a
|
||||
/// `Close`). `None` for `MoveTo`/`Close` or out of range.
|
||||
pub fn segment_start(&self, cmd: usize) -> Option<Vec2> {
|
||||
if !matches!(self.cmds.get(cmd)?, PathCmd::LineTo(_) | PathCmd::QuadTo(..) | PathCmd::CubicTo(..)) {
|
||||
return None;
|
||||
}
|
||||
let (mut cur, mut start) = (Vec2::ZERO, Vec2::ZERO);
|
||||
for c in self.cmds.get(..cmd)? {
|
||||
match *c {
|
||||
PathCmd::MoveTo(p) => {
|
||||
cur = p;
|
||||
start = p;
|
||||
}
|
||||
PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => cur = p,
|
||||
PathCmd::Close => cur = start,
|
||||
}
|
||||
}
|
||||
Some(cur)
|
||||
}
|
||||
|
||||
/// Point on segment `cmd` at parameter `t ∈ [0, 1]`.
|
||||
pub fn segment_point(&self, cmd: usize, t: f32) -> Option<Vec2> {
|
||||
let s = self.segment_start(cmd)?;
|
||||
let mt = 1.0 - t;
|
||||
Some(match *self.cmds.get(cmd)? {
|
||||
PathCmd::LineTo(p) => s.lerp(p, t),
|
||||
PathCmd::QuadTo(c, p) => s * (mt * mt) + c * (2.0 * mt * t) + p * (t * t),
|
||||
PathCmd::CubicTo(c1, c2, p) => s * (mt * mt * mt) + c1 * (3.0 * mt * mt * t) + c2 * (3.0 * mt * t * t) + p * (t * t * t),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Splits segment `cmd` at `t` (de Casteljau), adding an anchor without changing the shape.
|
||||
pub fn split_segment(&mut self, cmd: usize, t: f32) -> bool {
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { return false };
|
||||
let Some(s) = self.segment_start(cmd) else { return false };
|
||||
let Some(&c) = self.cmds.get(cmd) else { return false };
|
||||
let (first, second) = match c {
|
||||
PathCmd::LineTo(p) => (PathCmd::LineTo(s.lerp(p, t)), PathCmd::LineTo(p)),
|
||||
PathCmd::QuadTo(c1, p) => {
|
||||
let (a, b) = (s.lerp(c1, t), c1.lerp(p, t));
|
||||
let m = a.lerp(b, t);
|
||||
(PathCmd::QuadTo(a, m), PathCmd::QuadTo(b, p))
|
||||
}
|
||||
PathCmd::CubicTo(c1, c2, p) => {
|
||||
let (a, b, c3) = (s.lerp(c1, t), c1.lerp(c2, t), c2.lerp(p, t));
|
||||
let (d, e) = (a.lerp(b, t), b.lerp(c3, t));
|
||||
let m = d.lerp(e, t);
|
||||
(PathCmd::CubicTo(a, d, m), PathCmd::CubicTo(e, c3, p))
|
||||
}
|
||||
_ => return false,
|
||||
};
|
||||
if let Some(slot) = self.cmds.get_mut(cmd) {
|
||||
*slot = first;
|
||||
}
|
||||
self.cmds.insert(cmd + 1, second);
|
||||
true
|
||||
}
|
||||
|
||||
fn is_segment(&self, cmd: usize) -> bool {
|
||||
matches!(self.cmds.get(cmd), Some(PathCmd::LineTo(_) | PathCmd::QuadTo(..) | PathCmd::CubicTo(..)))
|
||||
}
|
||||
|
||||
/// The `MoveTo` that starts the subpath containing `cmd`.
|
||||
fn subpath_start(&self, cmd: usize) -> Option<usize> {
|
||||
self.cmds.get(..=cmd)?.iter().rposition(|x| matches!(x, PathCmd::MoveTo(_)))
|
||||
}
|
||||
|
||||
/// Writes every `Close` that would draw an implicit edge as an explicit line back to the
|
||||
/// subpath start, so each edge of the outline is a command that can be split and curved.
|
||||
/// The shape does not change.
|
||||
pub fn close_explicitly(&mut self) {
|
||||
let mut out = Vec::with_capacity(self.cmds.len() + 4);
|
||||
let (mut cur, mut start) = (Vec2::ZERO, Vec2::ZERO);
|
||||
for &c in &self.cmds {
|
||||
match c {
|
||||
PathCmd::MoveTo(p) => {
|
||||
cur = p;
|
||||
start = p;
|
||||
}
|
||||
PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => cur = p,
|
||||
PathCmd::Close => {
|
||||
if cur.distance(start) > LINK_EPS {
|
||||
out.push(PathCmd::LineTo(start));
|
||||
}
|
||||
cur = start;
|
||||
}
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
self.cmds = out;
|
||||
}
|
||||
|
||||
/// In a closed subpath whose last segment returns to the start, the start `MoveTo` and that
|
||||
/// segment's end are one anchor stored twice. Returns the other copy.
|
||||
pub fn linked_anchor(&self, cmd: usize) -> Option<usize> {
|
||||
match self.cmds.get(cmd)? {
|
||||
PathCmd::MoveTo(p) => {
|
||||
let end = (cmd + 1..self.cmds.len()).find(|&j| !self.is_segment(j))?;
|
||||
let last = end.checked_sub(1).filter(|&l| l > cmd)?;
|
||||
(matches!(self.cmds.get(end), Some(PathCmd::Close)) && self.point(last, ANCHOR)?.distance(*p) <= LINK_EPS).then_some(last)
|
||||
}
|
||||
_ if self.is_segment(cmd) && matches!(self.cmds.get(cmd + 1), Some(PathCmd::Close)) => {
|
||||
let m = self.subpath_start(cmd)?;
|
||||
(self.linked_anchor(m) == Some(cmd)).then_some(m)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The command that names an anchor: the `MoveTo` for a closed subpath's start, else `cmd`.
|
||||
/// Overlays list only canonical anchors, so the start is not drawn twice.
|
||||
pub fn canonical_anchor(&self, cmd: usize) -> usize {
|
||||
match self.cmds.get(cmd) {
|
||||
Some(PathCmd::MoveTo(_)) | None => cmd,
|
||||
_ => self.linked_anchor(cmd).unwrap_or(cmd),
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors as the user sees them: one per position, start of a closed subpath once.
|
||||
pub fn editable_anchors(&self) -> Vec<(usize, Vec2)> {
|
||||
self.anchors().into_iter().filter(|(i, _)| self.canonical_anchor(*i) == *i).collect()
|
||||
}
|
||||
|
||||
/// The segments that arrive at and leave anchor `cmd`: `(in, out)`. The in-segment's `C2`
|
||||
/// and the out-segment's `C1` are the anchor's handles.
|
||||
pub fn anchor_segments(&self, cmd: usize) -> (Option<usize>, Option<usize>) {
|
||||
let cmd = self.canonical_anchor(cmd);
|
||||
let out = |i: usize| (self.is_segment(i + 1)).then_some(i + 1);
|
||||
match self.cmds.get(cmd) {
|
||||
Some(PathCmd::MoveTo(_)) => (self.linked_anchor(cmd), out(cmd)),
|
||||
Some(_) if self.is_segment(cmd) => (Some(cmd), out(cmd)),
|
||||
_ => (None, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every stored point that moves when anchor `cmd` moves: both copies of the anchor and its
|
||||
/// two handles.
|
||||
pub fn anchor_group(&self, cmd: usize) -> Vec<(usize, u8)> {
|
||||
let cmd = self.canonical_anchor(cmd);
|
||||
let mut v = vec![(cmd, ANCHOR)];
|
||||
if let Some(k) = self.linked_anchor(cmd) {
|
||||
v.push((k, ANCHOR));
|
||||
}
|
||||
let (i, o) = self.anchor_segments(cmd);
|
||||
if let Some(i) = i.filter(|&i| matches!(self.cmds.get(i), Some(PathCmd::CubicTo(..)))) {
|
||||
v.push((i, C2));
|
||||
}
|
||||
if let Some(o) = o.filter(|&o| matches!(self.cmds.get(o), Some(PathCmd::CubicTo(..)))) {
|
||||
v.push((o, C1));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Removes anchor `cmd`. A segment anchor is dropped (the next segment then starts from the
|
||||
/// previous anchor); a subpath start passes to the next anchor. Refuses when the subpath
|
||||
/// would be left with fewer than two anchors.
|
||||
pub fn remove_anchor(&mut self, cmd: usize) -> bool {
|
||||
let cmd = self.canonical_anchor(cmd);
|
||||
let Some(&c) = self.cmds.get(cmd) else { return false };
|
||||
let Some(m) = self.subpath_start(cmd) else { return false };
|
||||
let segs = (m + 1..self.cmds.len()).take_while(|&j| self.is_segment(j)).count();
|
||||
let linked = self.linked_anchor(m);
|
||||
let distinct = 1 + segs - usize::from(linked.is_some());
|
||||
if distinct <= 2 {
|
||||
return false;
|
||||
}
|
||||
match c {
|
||||
PathCmd::MoveTo(_) => {
|
||||
let Some(next_end) = self.point(cmd + 1, ANCHOR) else { return false };
|
||||
if let Some(k) = linked {
|
||||
self.set_point(k, ANCHOR, next_end);
|
||||
}
|
||||
if let Some(slot) = self.cmds.get_mut(cmd) {
|
||||
*slot = PathCmd::MoveTo(next_end);
|
||||
}
|
||||
self.cmds.remove(cmd + 1);
|
||||
true
|
||||
}
|
||||
PathCmd::LineTo(_) | PathCmd::QuadTo(..) | PathCmd::CubicTo(..) => {
|
||||
self.cmds.remove(cmd);
|
||||
true
|
||||
}
|
||||
PathCmd::Close => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes anchor `cmd` a corner: its handles collapse onto it (segments stay curves).
|
||||
pub fn make_corner(&mut self, cmd: usize) -> bool {
|
||||
let Some(a) = self.point(cmd, ANCHOR) else { return false };
|
||||
let (i, o) = self.anchor_segments(cmd);
|
||||
let mut changed = false;
|
||||
if let Some(i) = i.filter(|&i| matches!(self.cmds.get(i), Some(PathCmd::CubicTo(..)))) {
|
||||
changed |= self.set_point(i, C2, a);
|
||||
}
|
||||
if let Some(o) = o.filter(|&o| matches!(self.cmds.get(o), Some(PathCmd::CubicTo(..)))) {
|
||||
changed |= self.set_point(o, C1, a);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Makes anchor `cmd` smooth: neighbouring segments become cubics whose handles at this
|
||||
/// anchor are collinear, along the direction from the previous to the next anchor.
|
||||
pub fn make_smooth(&mut self, cmd: usize) -> bool {
|
||||
let Some(a) = self.point(cmd, ANCHOR) else { return false };
|
||||
let (i, o) = self.anchor_segments(cmd);
|
||||
let prev = i.and_then(|i| self.segment_start(i));
|
||||
let next = o.and_then(|o| self.point(o, ANCHOR));
|
||||
let dir = match (prev, next) {
|
||||
(Some(p), Some(n)) => (n - p).normalized(),
|
||||
(Some(p), None) => (a - p).normalized(),
|
||||
(None, Some(n)) => (n - a).normalized(),
|
||||
(None, None) => return false,
|
||||
};
|
||||
if dir == Vec2::ZERO {
|
||||
return false;
|
||||
}
|
||||
if let (Some(i), Some(p)) = (i, prev) {
|
||||
self.to_cubic(i);
|
||||
self.set_point(i, C2, a - dir * (a.distance(p) / 3.0));
|
||||
}
|
||||
if let (Some(o), Some(n)) = (o, next) {
|
||||
self.to_cubic(o);
|
||||
self.set_point(o, C1, a + dir * (a.distance(n) / 3.0));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Converts segment `cmd` to an equivalent cubic (no-op for cubics and non-segments).
|
||||
pub fn to_cubic(&mut self, cmd: usize) {
|
||||
let Some(s) = self.segment_start(cmd) else { return };
|
||||
let Some(c) = self.cmds.get_mut(cmd) else { return };
|
||||
*c = match *c {
|
||||
PathCmd::LineTo(p) => PathCmd::CubicTo(s.lerp(p, 1.0 / 3.0), s.lerp(p, 2.0 / 3.0), p),
|
||||
PathCmd::QuadTo(q, p) => PathCmd::CubicTo(s + (q - s) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p),
|
||||
other => other,
|
||||
};
|
||||
}
|
||||
|
||||
/// The segment nearest to `p` (in the space `m` maps to): `(cmd, t, distance)`.
|
||||
pub fn nearest_segment(&self, p: Vec2, m: &Affine) -> Option<(usize, f32, f32)> {
|
||||
let mut best: Option<(usize, f32, f32)> = None;
|
||||
for cmd in 0..self.cmds.len().min(100_000) {
|
||||
if self.segment_start(cmd).is_none() {
|
||||
continue;
|
||||
}
|
||||
let steps = 32;
|
||||
for i in 0..=steps {
|
||||
let t = i as f32 / steps as f32;
|
||||
let Some(q) = self.segment_point(cmd, t) else { continue };
|
||||
let d = m.apply(q).distance(p);
|
||||
if best.is_none_or(|b| d < b.2) {
|
||||
best = Some((cmd, t, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
// refine t around the best sample
|
||||
let (cmd, mut t, mut d) = best?;
|
||||
let mut step = 1.0 / 64.0;
|
||||
for _ in 0..12 {
|
||||
for cand in [t - step, t + step] {
|
||||
let c = cand.clamp(0.0, 1.0);
|
||||
if let Some(q) = self.segment_point(cmd, c) {
|
||||
let dc = m.apply(q).distance(p);
|
||||
if dc < d {
|
||||
d = dc;
|
||||
t = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
step *= 0.5;
|
||||
}
|
||||
Some((cmd, t, d))
|
||||
}
|
||||
}
|
||||
|
||||
/// Ramer–Douglas–Peucker simplification (iterative; bounded memory).
|
||||
pub fn simplify(points: &[Vec2], tolerance: f32) -> Vec<Vec2> {
|
||||
let n = points.len();
|
||||
if n < 3 {
|
||||
return points.to_vec();
|
||||
}
|
||||
let tol = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.5 };
|
||||
let mut keep = vec![false; n];
|
||||
keep[0] = true;
|
||||
keep[n - 1] = true;
|
||||
let mut stack = vec![(0usize, n - 1)];
|
||||
while let Some((a, b)) = stack.pop() {
|
||||
if b <= a + 1 {
|
||||
continue;
|
||||
}
|
||||
let (pa, pb) = (points[a], points[b]);
|
||||
let mut far = (a, 0.0f32);
|
||||
for (i, p) in points.iter().enumerate().take(b).skip(a + 1) {
|
||||
let d = crate::path::segment_distance(*p, pa, pb);
|
||||
if d > far.1 {
|
||||
far = (i, d);
|
||||
}
|
||||
}
|
||||
if far.1 > tol {
|
||||
keep[far.0] = true;
|
||||
stack.push((a, far.0));
|
||||
stack.push((far.0, b));
|
||||
}
|
||||
}
|
||||
points.iter().zip(keep).filter_map(|(p, k)| k.then_some(*p)).collect()
|
||||
}
|
||||
|
||||
/// A straight-segment path through `points`.
|
||||
pub fn polyline_path(points: &[Vec2], closed: bool) -> Path {
|
||||
let mut path = Path::new();
|
||||
for (i, &p) in points.iter().enumerate() {
|
||||
if i == 0 {
|
||||
path.move_to(p);
|
||||
} else {
|
||||
path.line_to(p);
|
||||
}
|
||||
}
|
||||
if closed && points.len() > 2 {
|
||||
path.close();
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn cubic_path() -> Path {
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(10.0, 20.0), Vec2::new(30.0, 20.0), Vec2::new(40.0, 0.0)).line_to(Vec2::new(40.0, -20.0));
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn addressing() {
|
||||
let p = cubic_path();
|
||||
assert_eq!(p.anchors().len(), 3);
|
||||
assert_eq!(p.point(1, C2), Some(Vec2::new(30.0, 20.0)));
|
||||
assert_eq!(p.point(2, C1), None);
|
||||
assert_eq!(p.segment_start(2), Some(Vec2::new(40.0, 0.0)));
|
||||
let mut q = p.clone();
|
||||
assert!(q.set_point(1, C1, Vec2::new(5.0, 5.0)));
|
||||
assert!(!q.set_point(0, C1, Vec2::new(5.0, 5.0)));
|
||||
assert!(!q.set_point(1, ANCHOR, Vec2::new(f32::NAN, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_keeps_the_curve() {
|
||||
let p = cubic_path();
|
||||
let mut q = p.clone();
|
||||
assert!(q.split_segment(1, 0.3));
|
||||
assert_eq!(q.anchors().len(), 4);
|
||||
// the new anchor lies on the original curve
|
||||
let on = p.segment_point(1, 0.3).unwrap();
|
||||
assert!(q.point(1, ANCHOR).unwrap().distance(on) < 1e-4);
|
||||
// and the flattened shapes agree
|
||||
let a = p.flatten(&Affine::IDENTITY, 0.01)[0].points.clone();
|
||||
let b = q.flatten(&Affine::IDENTITY, 0.01)[0].points.clone();
|
||||
let near = |pt: &Vec2, set: &[Vec2]| set.windows(2).map(|w| crate::path::segment_distance(*pt, w[0], w[1])).fold(f32::INFINITY, f32::min);
|
||||
assert!(b.iter().all(|pt| near(pt, &a) < 0.2));
|
||||
assert!(!q.split_segment(0, 0.5), "MoveTo is not a segment");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_keeps_at_least_two_anchors() {
|
||||
let mut p = cubic_path();
|
||||
assert!(p.remove_anchor(1));
|
||||
assert_eq!(p.anchors().len(), 2);
|
||||
assert!(!p.remove_anchor(1), "a subpath needs two anchors");
|
||||
let mut r = Path::rect(0.0, 0.0, 10.0, 10.0);
|
||||
assert!(r.remove_anchor(0), "MoveTo takes over the next anchor");
|
||||
assert_eq!(r.point(0, ANCHOR), Some(Vec2::new(10.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_subpaths_have_one_start_anchor() {
|
||||
let mut r = Path::rect(0.0, 0.0, 10.0, 10.0);
|
||||
let before = r.flatten(&Affine::IDENTITY, 0.1);
|
||||
r.close_explicitly();
|
||||
assert_eq!(r.flatten(&Affine::IDENTITY, 0.1)[0].points.len(), before[0].points.len() + 1, "only a duplicate end point added");
|
||||
assert_eq!(r.linked_anchor(0), Some(4));
|
||||
assert_eq!(r.linked_anchor(4), Some(0));
|
||||
assert_eq!(r.canonical_anchor(4), 0);
|
||||
assert_eq!(r.editable_anchors().len(), 4);
|
||||
assert_eq!(r.anchor_segments(0), (Some(4), Some(1)));
|
||||
r.close_explicitly();
|
||||
assert_eq!(r.cmds.len(), 6, "idempotent");
|
||||
// The start anchor is smooth across the seam and removable.
|
||||
assert!(r.make_smooth(0));
|
||||
assert!(matches!(r.cmds[4], PathCmd::CubicTo(..)) && matches!(r.cmds[1], PathCmd::CubicTo(..)));
|
||||
let mut q = r.clone();
|
||||
assert!(q.remove_anchor(4), "the duplicate names the start");
|
||||
assert_eq!(q.editable_anchors().len(), 3);
|
||||
assert_eq!(q.point(0, ANCHOR), Some(Vec2::new(10.0, 0.0)));
|
||||
assert_eq!(q.linked_anchor(0), Some(3), "still closed on the new start");
|
||||
assert!(q.remove_anchor(0));
|
||||
assert!(!q.remove_anchor(0), "two anchors stay");
|
||||
// Moving the start moves both copies and both handles.
|
||||
let g = r.anchor_group(0);
|
||||
assert!(g.contains(&(0, ANCHOR)) && g.contains(&(4, ANCHOR)) && g.contains(&(4, C2)) && g.contains(&(1, C1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_and_corner() {
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(10.0, 10.0)).line_to(Vec2::new(20.0, 0.0));
|
||||
assert!(p.make_smooth(1));
|
||||
let (a, i, o) = (p.point(1, ANCHOR).unwrap(), p.point(1, C2).unwrap(), p.point(2, C1).unwrap());
|
||||
assert!((i - a).cross(o - a).abs() < 1e-3, "handles collinear");
|
||||
assert!((i - a).dot(o - a) < 0.0, "on opposite sides");
|
||||
assert!(p.make_corner(1));
|
||||
assert_eq!(p.point(1, C2), Some(a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_segment_finds_the_curve() {
|
||||
let p = cubic_path();
|
||||
let target = p.segment_point(1, 0.62).unwrap();
|
||||
let (cmd, t, d) = p.nearest_segment(target + Vec2::new(0.0, 0.5), &Affine::IDENTITY).unwrap();
|
||||
assert_eq!(cmd, 1);
|
||||
assert!((t - 0.62).abs() < 0.05, "{t}");
|
||||
assert!(d < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simplify_and_fit() {
|
||||
let pts: Vec<Vec2> = (0..=100).map(|i| Vec2::new(i as f32, (i as f32 * 0.1).sin() * 0.05)).collect();
|
||||
assert_eq!(simplify(&pts, 0.5).len(), 2, "a nearly straight stroke collapses to its ends");
|
||||
let wave: Vec<Vec2> = (0..=200).map(|i| Vec2::new(i as f32, (i as f32 * 0.05).sin() * 30.0)).collect();
|
||||
let s = simplify(&wave, 1.0);
|
||||
assert!(s.len() > 4 && s.len() < 60, "{}", s.len());
|
||||
let path = polyline_path(&s, false);
|
||||
assert_eq!(path.anchors().len(), s.len());
|
||||
assert!(path.anchors().iter().zip(&s).all(|((_, a), b)| a.distance(*b) < 1e-4), "passes through the points");
|
||||
assert!(simplify(&[], 1.0).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! Fitting cubic Béziers to freehand strokes (Pencil "Smooth" mode).
|
||||
//!
|
||||
//! 1. Consecutive duplicate points are dropped (a held mouse reports the same position).
|
||||
//! 2. Corners are where the stroke direction, measured over `corner_window` of arc length on
|
||||
//! each side, turns by more than 60°; only the sharpest point of each turn counts.
|
||||
//! 3. Each run between corners is fitted by least squares with fixed end tangents and Newton
|
||||
//! reparameterisation, splitting at the worst point until within `tolerance` (P. J. Schneider,
|
||||
//! "An Algorithm for Automatically Fitting Digitized Curves", Graphics Gems, 1990).
|
||||
//!
|
||||
//! Ported from PhotoCraft's mask tracer (`vector::trace`, same project family, MIT OR
|
||||
//! Apache-2.0) and adapted for strokes: open paths, a caller-chosen corner window (so it can
|
||||
//! follow the zoom), end tangents measured over that window instead of from one noisy
|
||||
//! neighbour, and no indexing that input can push out of range. Maths runs in `f64`.
|
||||
|
||||
use crate::{Path, Vec2};
|
||||
|
||||
type P = (f64, f64);
|
||||
|
||||
fn sub(a: P, b: P) -> P {
|
||||
(a.0 - b.0, a.1 - b.1)
|
||||
}
|
||||
fn add(a: P, b: P) -> P {
|
||||
(a.0 + b.0, a.1 + b.1)
|
||||
}
|
||||
fn mul(a: P, k: f64) -> P {
|
||||
(a.0 * k, a.1 * k)
|
||||
}
|
||||
fn dot(a: P, b: P) -> f64 {
|
||||
a.0 * b.0 + a.1 * b.1
|
||||
}
|
||||
fn len(a: P) -> f64 {
|
||||
a.0.hypot(a.1)
|
||||
}
|
||||
fn norm(a: P) -> P {
|
||||
let l = len(a);
|
||||
if l > 1e-12 { (a.0 / l, a.1 / l) } else { (0.0, 0.0) }
|
||||
}
|
||||
|
||||
/// A smooth path through a freehand stroke: cubic segments within `tolerance` of the points,
|
||||
/// with corners kept sharp. Fewer than two distinct points give a path with at most a `MoveTo`.
|
||||
pub fn fit_curve(points: &[Vec2], tolerance: f32, corner_window: f32, closed: bool) -> Path {
|
||||
let tol = if tolerance.is_finite() && tolerance > 0.0 { f64::from(tolerance) } else { 1.0 };
|
||||
let window = if corner_window.is_finite() && corner_window > 0.0 { f64::from(corner_window) } else { 3.0 };
|
||||
let mut lp: Vec<P> = Vec::with_capacity(points.len());
|
||||
for p in points.iter().filter(|p| p.is_finite()) {
|
||||
let q = (f64::from(p.x), f64::from(p.y));
|
||||
if lp.last().is_none_or(|&l| len(sub(q, l)) > 1e-4) {
|
||||
lp.push(q);
|
||||
}
|
||||
}
|
||||
if closed && lp.len() > 2 && lp.first().zip(lp.last()).is_some_and(|(a, b)| len(sub(*a, *b)) <= 1e-4) {
|
||||
lp.pop();
|
||||
}
|
||||
let mut path = Path::new();
|
||||
let v = |p: P| Vec2::new(p.0 as f32, p.1 as f32);
|
||||
let Some(&first) = lp.first() else { return path };
|
||||
path.move_to(v(first));
|
||||
if lp.len() < 3 {
|
||||
for &p in lp.iter().skip(1) {
|
||||
path.line_to(v(p));
|
||||
}
|
||||
return path;
|
||||
}
|
||||
let segs = if closed { fit_closed(&lp, tol, window) } else { fit_open(&lp, tol, window) };
|
||||
for s in segs {
|
||||
path.cubic_to(v(s[1]), v(s[2]), v(s[3]));
|
||||
}
|
||||
if closed {
|
||||
path.close();
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// The point `window` of arc length away from `i`, forwards or backwards. Open strokes stop at
|
||||
/// their ends; closed ones wrap.
|
||||
fn walk(lp: &[P], i: usize, window: f64, fwd: bool, closed: bool) -> P {
|
||||
let n = lp.len();
|
||||
let mut acc = 0.0;
|
||||
let mut cur = i.min(n - 1);
|
||||
for _ in 0..n {
|
||||
let nx = match (fwd, closed) {
|
||||
(true, true) => (cur + 1) % n,
|
||||
(false, true) => (cur + n - 1) % n,
|
||||
(true, false) if cur + 1 < n => cur + 1,
|
||||
(false, false) if cur > 0 => cur - 1,
|
||||
_ => break,
|
||||
};
|
||||
let d = len(sub(lp[nx], lp[cur]));
|
||||
if acc + d >= window {
|
||||
let t = (window - acc) / d.max(1e-12);
|
||||
return add(lp[cur], mul(sub(lp[nx], lp[cur]), t));
|
||||
}
|
||||
acc += d;
|
||||
cur = nx;
|
||||
}
|
||||
lp[cur]
|
||||
}
|
||||
|
||||
/// Indices of corner points (never an open stroke's ends).
|
||||
fn corners(lp: &[P], window: f64, closed: bool) -> Vec<usize> {
|
||||
let n = lp.len();
|
||||
let cos_thresh = 60f64.to_radians().cos();
|
||||
let interior = |i: usize| closed || (i > 0 && i + 1 < n);
|
||||
let turn: Vec<f64> = (0..n)
|
||||
.map(|i| {
|
||||
if !interior(i) {
|
||||
return 1.0;
|
||||
}
|
||||
let a = norm(sub(lp[i], walk(lp, i, window, false, closed)));
|
||||
let b = norm(sub(walk(lp, i, window, true, closed), lp[i]));
|
||||
dot(a, b)
|
||||
})
|
||||
.collect();
|
||||
let step = |j: usize, fwd: bool| -> Option<usize> {
|
||||
match (fwd, closed) {
|
||||
(true, true) => Some((j + 1) % n),
|
||||
(false, true) => Some((j + n - 1) % n),
|
||||
(true, false) => (j + 1 < n).then_some(j + 1),
|
||||
(false, false) => j.checked_sub(1),
|
||||
}
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for i in 0..n {
|
||||
if turn[i] >= cos_thresh {
|
||||
continue;
|
||||
}
|
||||
// The sharpest point within ±window (ties go to the first index).
|
||||
let mut is_min = true;
|
||||
for fwd in [true, false] {
|
||||
let (mut acc, mut j) = (0.0, i);
|
||||
while is_min && acc < window {
|
||||
let Some(nx) = step(j, fwd) else { break };
|
||||
acc += len(sub(lp[nx], lp[j]));
|
||||
j = nx;
|
||||
if j == i {
|
||||
break;
|
||||
}
|
||||
if if fwd { turn[j] < turn[i] } else { turn[j] <= turn[i] } {
|
||||
is_min = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if is_min {
|
||||
out.push(i);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn fit_open(lp: &[P], tol: f64, window: f64) -> Vec<[P; 4]> {
|
||||
let n = lp.len();
|
||||
let mut cuts = vec![0];
|
||||
cuts.extend(corners(lp, window, false));
|
||||
cuts.push(n - 1);
|
||||
let mut segs = Vec::new();
|
||||
for w in cuts.windows(2) {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
let run = &lp[a..=b];
|
||||
let t1 = norm(sub(walk(run, 0, window, true, false), run[0]));
|
||||
let t2 = norm(sub(walk(run, run.len() - 1, window, false, false), run[run.len() - 1]));
|
||||
fit_cubic(run, t1, t2, tol * tol, &mut segs, 0);
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
fn fit_closed(lp: &[P], tol: f64, window: f64) -> Vec<[P; 4]> {
|
||||
let n = lp.len();
|
||||
let cs = corners(lp, window, true);
|
||||
let mut segs = Vec::new();
|
||||
if cs.is_empty() {
|
||||
// A smooth loop: start at 0 with one tangent across the seam.
|
||||
let mut pts = lp.to_vec();
|
||||
pts.push(lp[0]);
|
||||
let t = norm(sub(walk(lp, 0, window, true, true), walk(lp, 0, window, false, true)));
|
||||
fit_cubic(&pts, t, mul(t, -1.0), tol * tol, &mut segs, 0);
|
||||
return segs;
|
||||
}
|
||||
for (k, &c) in cs.iter().enumerate() {
|
||||
let end = cs[(k + 1) % cs.len()];
|
||||
let mut pts = vec![lp[c]];
|
||||
let mut j = c;
|
||||
loop {
|
||||
j = (j + 1) % n;
|
||||
pts.push(lp[j]);
|
||||
if j == end {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let m = pts.len();
|
||||
let t1 = norm(sub(walk(&pts, 0, window, true, false), pts[0]));
|
||||
let t2 = norm(sub(walk(&pts, m - 1, window, false, false), pts[m - 1]));
|
||||
fit_cubic(&pts, t1, t2, tol * tol, &mut segs, 0);
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
fn bezier(b: &[P; 4], t: f64) -> P {
|
||||
let mt = 1.0 - t;
|
||||
let (a, bb, c, d) = (mt * mt * mt, 3.0 * mt * mt * t, 3.0 * mt * t * t, t * t * t);
|
||||
(a * b[0].0 + bb * b[1].0 + c * b[2].0 + d * b[3].0, a * b[0].1 + bb * b[1].1 + c * b[2].1 + d * b[3].1)
|
||||
}
|
||||
|
||||
fn bezier_d1(b: &[P; 4], t: f64) -> P {
|
||||
let mt = 1.0 - t;
|
||||
let q0 = mul(sub(b[1], b[0]), 3.0);
|
||||
let q1 = mul(sub(b[2], b[1]), 3.0);
|
||||
let q2 = mul(sub(b[3], b[2]), 3.0);
|
||||
add(add(mul(q0, mt * mt), mul(q1, 2.0 * mt * t)), mul(q2, t * t))
|
||||
}
|
||||
|
||||
fn bezier_d2(b: &[P; 4], t: f64) -> P {
|
||||
let r0 = mul(add(sub(b[2], mul(b[1], 2.0)), b[0]), 6.0);
|
||||
let r1 = mul(add(sub(b[3], mul(b[2], 2.0)), b[1]), 6.0);
|
||||
add(mul(r0, 1.0 - t), mul(r1, t))
|
||||
}
|
||||
|
||||
fn chord_params(pts: &[P]) -> Vec<f64> {
|
||||
let mut u = vec![0.0; pts.len()];
|
||||
for i in 1..pts.len() {
|
||||
u[i] = u[i - 1] + len(sub(pts[i], pts[i - 1]));
|
||||
}
|
||||
let total = u[pts.len() - 1];
|
||||
if total > 0.0 {
|
||||
for v in &mut u {
|
||||
*v /= total;
|
||||
}
|
||||
}
|
||||
u
|
||||
}
|
||||
|
||||
/// Least-squares control points with fixed end tangents (`pts.len() >= 2`).
|
||||
fn generate(pts: &[P], u: &[f64], t1: P, t2: P) -> [P; 4] {
|
||||
let (p0, p3) = (pts[0], pts[pts.len() - 1]);
|
||||
let mut c = [[0.0f64; 2]; 2];
|
||||
let mut x = [0.0f64; 2];
|
||||
for (i, &t) in u.iter().enumerate() {
|
||||
let mt = 1.0 - t;
|
||||
let b1 = 3.0 * mt * mt * t;
|
||||
let b2 = 3.0 * mt * t * t;
|
||||
let a1 = mul(t1, b1);
|
||||
let a2 = mul(t2, b2);
|
||||
c[0][0] += dot(a1, a1);
|
||||
c[0][1] += dot(a1, a2);
|
||||
c[1][1] += dot(a2, a2);
|
||||
let tmp = sub(pts[i], add(mul(p0, mt * mt * mt + b1), mul(p3, b2 + t * t * t)));
|
||||
x[0] += dot(a1, tmp);
|
||||
x[1] += dot(a2, tmp);
|
||||
}
|
||||
c[1][0] = c[0][1];
|
||||
let det = c[0][0] * c[1][1] - c[1][0] * c[0][1];
|
||||
let det0 = c[0][0] * x[1] - c[1][0] * x[0];
|
||||
let det1 = x[0] * c[1][1] - x[1] * c[0][1];
|
||||
let (mut al, mut ar) = if det.abs() > 1e-12 { (det1 / det, det0 / det) } else { (0.0, 0.0) };
|
||||
let seg = len(sub(p3, p0));
|
||||
// Schneider's fallback when the solve is degenerate or flips a handle.
|
||||
if al < 1e-6 * seg || ar < 1e-6 * seg {
|
||||
al = seg / 3.0;
|
||||
ar = seg / 3.0;
|
||||
}
|
||||
[p0, add(p0, mul(t1, al)), add(p3, mul(t2, ar)), p3]
|
||||
}
|
||||
|
||||
/// Largest squared distance between the points and the curve, and where (`pts.len() >= 3`).
|
||||
fn max_error(pts: &[P], b: &[P; 4], u: &[f64]) -> (f64, usize) {
|
||||
let mut best = (0.0, pts.len() / 2);
|
||||
for i in 1..pts.len() - 1 {
|
||||
let d = sub(bezier(b, u[i]), pts[i]);
|
||||
let e = dot(d, d);
|
||||
if e >= best.0 {
|
||||
best = (e, i);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// One Newton step towards each point's nearest parameter on the curve.
|
||||
fn reparam(pts: &[P], u: &[f64], b: &[P; 4]) -> Vec<f64> {
|
||||
pts.iter()
|
||||
.zip(u)
|
||||
.map(|(p, &t)| {
|
||||
let q = bezier(b, t);
|
||||
let d1 = bezier_d1(b, t);
|
||||
let d2 = bezier_d2(b, t);
|
||||
let num = dot(sub(q, *p), d1);
|
||||
let den = dot(d1, d1) + dot(sub(q, *p), d2);
|
||||
if den.abs() < 1e-12 { t } else { (t - num / den).clamp(0.0, 1.0) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fits `pts` (at least two) and appends the segments to `out`. Each split shortens both
|
||||
/// halves, so recursion ends; `depth` caps it anyway.
|
||||
fn fit_cubic(pts: &[P], t1: P, t2: P, err2: f64, out: &mut Vec<[P; 4]>, depth: u32) {
|
||||
let n = pts.len();
|
||||
if n < 2 {
|
||||
return;
|
||||
}
|
||||
if n == 2 || depth > 40 {
|
||||
let d = len(sub(pts[n - 1], pts[0])) / 3.0;
|
||||
out.push([pts[0], add(pts[0], mul(t1, d)), add(pts[n - 1], mul(t2, d)), pts[n - 1]]);
|
||||
return;
|
||||
}
|
||||
let mut u = chord_params(pts);
|
||||
let mut b = generate(pts, &u, t1, t2);
|
||||
let (mut e, mut split) = max_error(pts, &b, &u);
|
||||
if e < err2 {
|
||||
out.push(b);
|
||||
return;
|
||||
}
|
||||
if e < err2 * 16.0 {
|
||||
for _ in 0..6 {
|
||||
u = reparam(pts, &u, &b);
|
||||
b = generate(pts, &u, t1, t2);
|
||||
(e, split) = max_error(pts, &b, &u);
|
||||
if e < err2 {
|
||||
out.push(b);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let split = split.clamp(1, n - 2);
|
||||
let tc = norm(sub(pts[split - 1], pts[split + 1]));
|
||||
let tc = if len(tc) < 0.5 { norm(sub(pts[split - 1], pts[split])) } else { tc };
|
||||
fit_cubic(&pts[..=split], t1, tc, err2, out, depth + 1);
|
||||
fit_cubic(&pts[split..], mul(tc, -1.0), t2, err2, out, depth + 1);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Affine, PathCmd};
|
||||
|
||||
fn max_dist(path: &Path, pts: &[Vec2]) -> f32 {
|
||||
let lines = path.flatten(&Affine::IDENTITY, 0.05);
|
||||
pts.iter()
|
||||
.map(|p| {
|
||||
lines
|
||||
.iter()
|
||||
.flat_map(|l| l.points.windows(2).map(|w| crate::path::segment_distance(*p, w[0], w[1])))
|
||||
.fold(f32::INFINITY, f32::min)
|
||||
})
|
||||
.fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_wave_fits_within_tolerance_with_few_segments() {
|
||||
let wave: Vec<Vec2> = (0..=300).map(|i| Vec2::new(i as f32, (i as f32 * 0.04).sin() * 40.0)).collect();
|
||||
let path = fit_curve(&wave, 1.0, 3.0, false);
|
||||
let segs = path.cmds.iter().filter(|c| matches!(c, PathCmd::CubicTo(..))).count();
|
||||
assert!((1..=12).contains(&segs), "{segs} segments");
|
||||
assert!(max_dist(&path, &wave) <= 1.05, "{}", max_dist(&path, &wave));
|
||||
assert_eq!(path.point(0, crate::edit::ANCHOR), Some(wave[0]), "starts where the stroke starts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corners_stay_sharp() {
|
||||
// An "L": down then right, sampled every pixel.
|
||||
let mut pts: Vec<Vec2> = (0..=50).map(|i| Vec2::new(0.0, i as f32)).collect();
|
||||
pts.extend((1..=50).map(|i| Vec2::new(i as f32, 50.0)));
|
||||
let path = fit_curve(&pts, 0.5, 3.0, false);
|
||||
assert!(path.anchors().iter().any(|(_, a)| a.distance(Vec2::new(0.0, 50.0)) < 1e-3), "an anchor at the corner");
|
||||
assert!(max_dist(&path, &pts) <= 0.55);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_loop_and_degenerate_input() {
|
||||
let circle: Vec<Vec2> = (0..120).map(|i| {
|
||||
let a = i as f32 / 120.0 * std::f32::consts::TAU;
|
||||
Vec2::new(50.0 + 30.0 * a.cos(), 50.0 + 30.0 * a.sin())
|
||||
}).collect();
|
||||
let path = fit_curve(&circle, 0.5, 3.0, true);
|
||||
assert!(matches!(path.cmds.last(), Some(PathCmd::Close)));
|
||||
assert!(max_dist(&path, &circle) <= 0.55);
|
||||
// Repeated, non-finite and tiny inputs never panic.
|
||||
let same = vec![Vec2::new(1.0, 1.0); 20];
|
||||
assert_eq!(fit_curve(&same, 1.0, 3.0, false).cmds.len(), 1);
|
||||
assert!(fit_curve(&[], 1.0, 3.0, true).is_empty());
|
||||
let odd = [Vec2::new(0.0, 0.0), Vec2::new(f32::NAN, 1.0), Vec2::new(5.0, 0.0), Vec2::new(5.0, 0.0)];
|
||||
assert_eq!(fit_curve(&odd, f32::NAN, -1.0, false).cmds.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! AniCraft geometry (layer L0): points, affine transforms, rectangles and Bézier paths.
|
||||
//!
|
||||
//! Everything here is pure math with no allocation beyond the path buffers, deterministic
|
||||
//! across platforms (plain `f32`, no fused ops that depend on the target).
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod affine;
|
||||
pub mod edit;
|
||||
mod fit;
|
||||
mod path;
|
||||
pub mod svg;
|
||||
pub mod trace;
|
||||
|
||||
pub use affine::{Affine, Decomposed};
|
||||
pub use fit::fit_curve;
|
||||
pub use path::{FillRule, Path, PathCmd, Polyline};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::{Add, Mul, Neg, Sub};
|
||||
|
||||
/// A 2D point or vector.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Vec2 {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
}
|
||||
|
||||
impl Vec2 {
|
||||
pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
|
||||
|
||||
pub const fn new(x: f32, y: f32) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
pub fn dot(self, o: Vec2) -> f32 {
|
||||
self.x * o.x + self.y * o.y
|
||||
}
|
||||
pub fn cross(self, o: Vec2) -> f32 {
|
||||
self.x * o.y - self.y * o.x
|
||||
}
|
||||
pub fn length(self) -> f32 {
|
||||
self.dot(self).sqrt()
|
||||
}
|
||||
pub fn normalized(self) -> Vec2 {
|
||||
let l = self.length();
|
||||
if l > 1e-12 { self * (1.0 / l) } else { Vec2::ZERO }
|
||||
}
|
||||
/// Perpendicular (rotated +90° in y-down screen space).
|
||||
pub fn perp(self) -> Vec2 {
|
||||
Vec2::new(-self.y, self.x)
|
||||
}
|
||||
pub fn lerp(self, o: Vec2, t: f32) -> Vec2 {
|
||||
self + (o - self) * t
|
||||
}
|
||||
pub fn distance(self, o: Vec2) -> f32 {
|
||||
(o - self).length()
|
||||
}
|
||||
pub fn is_finite(self) -> bool {
|
||||
self.x.is_finite() && self.y.is_finite()
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Vec2 {
|
||||
type Output = Vec2;
|
||||
fn add(self, o: Vec2) -> Vec2 {
|
||||
Vec2::new(self.x + o.x, self.y + o.y)
|
||||
}
|
||||
}
|
||||
impl Sub for Vec2 {
|
||||
type Output = Vec2;
|
||||
fn sub(self, o: Vec2) -> Vec2 {
|
||||
Vec2::new(self.x - o.x, self.y - o.y)
|
||||
}
|
||||
}
|
||||
impl Mul<f32> for Vec2 {
|
||||
type Output = Vec2;
|
||||
fn mul(self, s: f32) -> Vec2 {
|
||||
Vec2::new(self.x * s, self.y * s)
|
||||
}
|
||||
}
|
||||
impl Neg for Vec2 {
|
||||
type Output = Vec2;
|
||||
fn neg(self) -> Vec2 {
|
||||
Vec2::new(-self.x, -self.y)
|
||||
}
|
||||
}
|
||||
|
||||
/// Axis-aligned rectangle (min inclusive, max exclusive in raster use).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Rect {
|
||||
pub min: Vec2,
|
||||
pub max: Vec2,
|
||||
}
|
||||
|
||||
impl Rect {
|
||||
/// The empty rectangle: union identity.
|
||||
pub const EMPTY: Rect = Rect {
|
||||
min: Vec2 { x: f32::INFINITY, y: f32::INFINITY },
|
||||
max: Vec2 { x: f32::NEG_INFINITY, y: f32::NEG_INFINITY },
|
||||
};
|
||||
|
||||
pub fn new(x0: f32, y0: f32, x1: f32, y1: f32) -> Self {
|
||||
Rect { min: Vec2::new(x0.min(x1), y0.min(y1)), max: Vec2::new(x0.max(x1), y0.max(y1)) }
|
||||
}
|
||||
pub fn from_points(a: Vec2, b: Vec2) -> Self {
|
||||
Rect::new(a.x, a.y, b.x, b.y)
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
!(self.max.x > self.min.x && self.max.y > self.min.y)
|
||||
}
|
||||
pub fn width(&self) -> f32 {
|
||||
(self.max.x - self.min.x).max(0.0)
|
||||
}
|
||||
pub fn height(&self) -> f32 {
|
||||
(self.max.y - self.min.y).max(0.0)
|
||||
}
|
||||
pub fn center(&self) -> Vec2 {
|
||||
(self.min + self.max) * 0.5
|
||||
}
|
||||
pub fn include(&mut self, p: Vec2) {
|
||||
self.min.x = self.min.x.min(p.x);
|
||||
self.min.y = self.min.y.min(p.y);
|
||||
self.max.x = self.max.x.max(p.x);
|
||||
self.max.y = self.max.y.max(p.y);
|
||||
}
|
||||
pub fn union(&self, o: &Rect) -> Rect {
|
||||
Rect {
|
||||
min: Vec2::new(self.min.x.min(o.min.x), self.min.y.min(o.min.y)),
|
||||
max: Vec2::new(self.max.x.max(o.max.x), self.max.y.max(o.max.y)),
|
||||
}
|
||||
}
|
||||
pub fn intersect(&self, o: &Rect) -> Rect {
|
||||
Rect {
|
||||
min: Vec2::new(self.min.x.max(o.min.x), self.min.y.max(o.min.y)),
|
||||
max: Vec2::new(self.max.x.min(o.max.x), self.max.y.min(o.max.y)),
|
||||
}
|
||||
}
|
||||
pub fn inflate(&self, d: f32) -> Rect {
|
||||
Rect { min: self.min - Vec2::new(d, d), max: self.max + Vec2::new(d, d) }
|
||||
}
|
||||
pub fn contains(&self, p: Vec2) -> bool {
|
||||
p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y
|
||||
}
|
||||
/// Bounds of this rectangle after a transform.
|
||||
pub fn transformed(&self, m: &Affine) -> Rect {
|
||||
if self.is_empty() {
|
||||
return *self;
|
||||
}
|
||||
let mut r = Rect::EMPTY;
|
||||
for p in [self.min, Vec2::new(self.max.x, self.min.y), self.max, Vec2::new(self.min.x, self.max.y)] {
|
||||
r.include(m.apply(p));
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear interpolation of scalars.
|
||||
pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rect_union_and_intersect() {
|
||||
let a = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
let b = Rect::new(5.0, 5.0, 20.0, 20.0);
|
||||
assert_eq!(a.union(&b), Rect::new(0.0, 0.0, 20.0, 20.0));
|
||||
assert_eq!(a.intersect(&b), Rect::new(5.0, 5.0, 10.0, 10.0));
|
||||
assert!(Rect::EMPTY.is_empty());
|
||||
assert_eq!(Rect::EMPTY.union(&a), a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec_ops() {
|
||||
let v = Vec2::new(3.0, 4.0);
|
||||
assert_eq!(v.length(), 5.0);
|
||||
assert_eq!(v.perp().dot(v), 0.0);
|
||||
assert_eq!(Vec2::ZERO.normalized(), Vec2::ZERO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
//! Bézier paths, adaptive flattening (Wang's formula) and winding-number hit testing.
|
||||
|
||||
use crate::{Affine, Rect, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Fill rule for closed regions.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum FillRule {
|
||||
#[default]
|
||||
NonZero,
|
||||
EvenOdd,
|
||||
}
|
||||
|
||||
/// One path command. Coordinates are in the element's local space.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum PathCmd {
|
||||
MoveTo(Vec2),
|
||||
LineTo(Vec2),
|
||||
QuadTo(Vec2, Vec2),
|
||||
CubicTo(Vec2, Vec2, Vec2),
|
||||
Close,
|
||||
}
|
||||
|
||||
/// A sequence of subpaths.
|
||||
///
|
||||
/// Serialized as compact SVG path data (`"M0 0L10 0Q5 5 0 10Z"`, absolute commands only), which
|
||||
/// is about four times smaller than a tagged JSON list and readable by people and tools. The
|
||||
/// legacy `{"cmds": [...]}` form is still accepted when reading.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Path {
|
||||
pub cmds: Vec<PathCmd>,
|
||||
}
|
||||
|
||||
/// Largest path accepted from a file.
|
||||
pub const MAX_PATH_CMDS: usize = 4_000_000;
|
||||
|
||||
impl Path {
|
||||
/// SVG path data with shortest round-trip number formatting.
|
||||
pub fn to_svg(&self) -> String {
|
||||
use std::fmt::Write;
|
||||
let mut s = String::with_capacity(self.cmds.len() * 16);
|
||||
let pt = |s: &mut String, p: Vec2| {
|
||||
let _ = write!(s, "{} {}", p.x, p.y);
|
||||
};
|
||||
for c in &self.cmds {
|
||||
match *c {
|
||||
PathCmd::MoveTo(p) => {
|
||||
s.push('M');
|
||||
pt(&mut s, p);
|
||||
}
|
||||
PathCmd::LineTo(p) => {
|
||||
s.push('L');
|
||||
pt(&mut s, p);
|
||||
}
|
||||
PathCmd::QuadTo(a, p) => {
|
||||
s.push('Q');
|
||||
pt(&mut s, a);
|
||||
s.push(' ');
|
||||
pt(&mut s, p);
|
||||
}
|
||||
PathCmd::CubicTo(a, b, p) => {
|
||||
s.push('C');
|
||||
pt(&mut s, a);
|
||||
s.push(' ');
|
||||
pt(&mut s, b);
|
||||
s.push(' ');
|
||||
pt(&mut s, p);
|
||||
}
|
||||
PathCmd::Close => s.push('Z'),
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Parses the absolute-command subset written by [`Path::to_svg`] (M, L, Q, C, Z; numbers
|
||||
/// separated by spaces or commas). Never panics; rejects non-finite numbers.
|
||||
pub fn from_svg(src: &str) -> Result<Path, String> {
|
||||
let mut cmds = Vec::new();
|
||||
let mut it = src.char_indices().peekable();
|
||||
let mut nums: Vec<f32> = Vec::with_capacity(6);
|
||||
let mut cur: Option<char> = None;
|
||||
let flush = |cur: Option<char>, nums: &mut Vec<f32>, cmds: &mut Vec<PathCmd>| -> Result<(), String> {
|
||||
let Some(c) = cur else {
|
||||
return if nums.is_empty() { Ok(()) } else { Err("number before the first command".into()) };
|
||||
};
|
||||
let need = match c {
|
||||
'M' | 'L' => 2,
|
||||
'Q' => 4,
|
||||
'C' => 6,
|
||||
_ => 0,
|
||||
};
|
||||
if c == 'Z' {
|
||||
if !nums.is_empty() {
|
||||
return Err("Z takes no numbers".into());
|
||||
}
|
||||
cmds.push(PathCmd::Close);
|
||||
return Ok(());
|
||||
}
|
||||
if nums.is_empty() || !nums.len().is_multiple_of(need) {
|
||||
return Err(format!("{c} needs a multiple of {need} numbers, got {}", nums.len()));
|
||||
}
|
||||
for g in nums.chunks(need) {
|
||||
let v = |i: usize| Vec2::new(g[i], g[i + 1]);
|
||||
cmds.push(match c {
|
||||
'M' => PathCmd::MoveTo(v(0)),
|
||||
'L' => PathCmd::LineTo(v(0)),
|
||||
'Q' => PathCmd::QuadTo(v(0), v(2)),
|
||||
_ => PathCmd::CubicTo(v(0), v(2), v(4)),
|
||||
});
|
||||
}
|
||||
nums.clear();
|
||||
if cmds.len() > MAX_PATH_CMDS {
|
||||
return Err(format!("path has more than {MAX_PATH_CMDS} commands"));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
while let Some(&(i, ch)) = it.peek() {
|
||||
match ch {
|
||||
'M' | 'L' | 'Q' | 'C' | 'Z' | 'z' => {
|
||||
flush(cur, &mut nums, &mut cmds)?;
|
||||
cur = Some(ch.to_ascii_uppercase());
|
||||
it.next();
|
||||
}
|
||||
' ' | ',' | '\n' | '\t' | '\r' => {
|
||||
it.next();
|
||||
}
|
||||
'-' | '+' | '.' | '0'..='9' => {
|
||||
let start = i;
|
||||
let mut end = i + ch.len_utf8();
|
||||
it.next();
|
||||
while let Some(&(j, c2)) = it.peek() {
|
||||
let exp_sign = (c2 == '-' || c2 == '+') && matches!(src.get(..j).and_then(|s| s.chars().last()), Some('e' | 'E'));
|
||||
if c2.is_ascii_digit() || c2 == '.' || c2 == 'e' || c2 == 'E' || exp_sign {
|
||||
end = j + c2.len_utf8();
|
||||
it.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let tok = src.get(start..end).unwrap_or("");
|
||||
let v: f32 = tok.parse().map_err(|_| format!("bad number '{tok}'"))?;
|
||||
if !v.is_finite() {
|
||||
return Err(format!("number '{tok}' is not finite"));
|
||||
}
|
||||
nums.push(v);
|
||||
if nums.len() > 6 {
|
||||
// repeated implicit commands: emit as we go to bound memory
|
||||
let c = cur.ok_or("number before the first command")?;
|
||||
let need = match c {
|
||||
'M' | 'L' => 2,
|
||||
'Q' => 4,
|
||||
'C' => 6,
|
||||
_ => return Err("Z takes no numbers".into()),
|
||||
};
|
||||
if nums.len().is_multiple_of(need) {
|
||||
flush(cur, &mut nums, &mut cmds)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
other => return Err(format!("unexpected character '{other}' in path data")),
|
||||
}
|
||||
}
|
||||
flush(cur, &mut nums, &mut cmds)?;
|
||||
Ok(Path { cmds })
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Path {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&self.to_svg())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Path {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Path, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Repr {
|
||||
Svg(String),
|
||||
Legacy { cmds: Vec<PathCmd> },
|
||||
}
|
||||
match Repr::deserialize(d)? {
|
||||
Repr::Svg(s) => Path::from_svg(&s).map_err(serde::de::Error::custom),
|
||||
Repr::Legacy { cmds } => {
|
||||
if cmds.len() > MAX_PATH_CMDS {
|
||||
return Err(serde::de::Error::custom("path is too long"));
|
||||
}
|
||||
Ok(Path { cmds })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A flattened subpath.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Polyline {
|
||||
pub points: Vec<Vec2>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
/// Hard cap on segments per curve, so a hostile curve cannot allocate unboundedly.
|
||||
const MAX_SEGMENTS_PER_CURVE: usize = 1024;
|
||||
/// Bézier circle constant.
|
||||
const KAPPA: f32 = 0.552_284_8;
|
||||
|
||||
impl Path {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
pub fn move_to(&mut self, p: Vec2) -> &mut Self {
|
||||
self.cmds.push(PathCmd::MoveTo(p));
|
||||
self
|
||||
}
|
||||
pub fn line_to(&mut self, p: Vec2) -> &mut Self {
|
||||
self.cmds.push(PathCmd::LineTo(p));
|
||||
self
|
||||
}
|
||||
pub fn quad_to(&mut self, c: Vec2, p: Vec2) -> &mut Self {
|
||||
self.cmds.push(PathCmd::QuadTo(c, p));
|
||||
self
|
||||
}
|
||||
pub fn cubic_to(&mut self, c1: Vec2, c2: Vec2, p: Vec2) -> &mut Self {
|
||||
self.cmds.push(PathCmd::CubicTo(c1, c2, p));
|
||||
self
|
||||
}
|
||||
pub fn close(&mut self) -> &mut Self {
|
||||
self.cmds.push(PathCmd::Close);
|
||||
self
|
||||
}
|
||||
|
||||
/// Axis-aligned rectangle, clockwise on a y-down screen.
|
||||
pub fn rect(x: f32, y: f32, w: f32, h: f32) -> Path {
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(x, y))
|
||||
.line_to(Vec2::new(x + w, y))
|
||||
.line_to(Vec2::new(x + w, y + h))
|
||||
.line_to(Vec2::new(x, y + h))
|
||||
.close();
|
||||
p
|
||||
}
|
||||
|
||||
/// Rectangle with rounded corners (radius clamped to half the shorter side).
|
||||
pub fn rounded_rect(x: f32, y: f32, w: f32, h: f32, r: f32) -> Path {
|
||||
let r = r.max(0.0).min(w.abs() * 0.5).min(h.abs() * 0.5);
|
||||
if r <= 0.0 {
|
||||
return Path::rect(x, y, w, h);
|
||||
}
|
||||
let k = r * (1.0 - KAPPA);
|
||||
let (x1, y1) = (x + w, y + h);
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(x + r, y))
|
||||
.line_to(Vec2::new(x1 - r, y))
|
||||
.cubic_to(Vec2::new(x1 - k, y), Vec2::new(x1, y + k), Vec2::new(x1, y + r))
|
||||
.line_to(Vec2::new(x1, y1 - r))
|
||||
.cubic_to(Vec2::new(x1, y1 - k), Vec2::new(x1 - k, y1), Vec2::new(x1 - r, y1))
|
||||
.line_to(Vec2::new(x + r, y1))
|
||||
.cubic_to(Vec2::new(x + k, y1), Vec2::new(x, y1 - k), Vec2::new(x, y1 - r))
|
||||
.line_to(Vec2::new(x, y + r))
|
||||
.cubic_to(Vec2::new(x, y + k), Vec2::new(x + k, y), Vec2::new(x + r, y))
|
||||
.close();
|
||||
p
|
||||
}
|
||||
|
||||
/// Ellipse centred at `(cx, cy)` built from four cubic arcs.
|
||||
pub fn ellipse(cx: f32, cy: f32, rx: f32, ry: f32) -> Path {
|
||||
let (kx, ky) = (rx * KAPPA, ry * KAPPA);
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(cx + rx, cy))
|
||||
.cubic_to(Vec2::new(cx + rx, cy + ky), Vec2::new(cx + kx, cy + ry), Vec2::new(cx, cy + ry))
|
||||
.cubic_to(Vec2::new(cx - kx, cy + ry), Vec2::new(cx - rx, cy + ky), Vec2::new(cx - rx, cy))
|
||||
.cubic_to(Vec2::new(cx - rx, cy - ky), Vec2::new(cx - kx, cy - ry), Vec2::new(cx, cy - ry))
|
||||
.cubic_to(Vec2::new(cx + kx, cy - ry), Vec2::new(cx + rx, cy - ky), Vec2::new(cx + rx, cy))
|
||||
.close();
|
||||
p
|
||||
}
|
||||
|
||||
/// Star (or polygon when `inner == outer`) with `points` tips, first tip pointing up.
|
||||
pub fn star(cx: f32, cy: f32, outer: f32, inner: f32, points: u32) -> Path {
|
||||
let n = points.clamp(3, 256) as usize;
|
||||
let mut p = Path::new();
|
||||
for i in 0..n * 2 {
|
||||
let r = if i % 2 == 0 { outer } else { inner };
|
||||
let a = -std::f32::consts::FRAC_PI_2 + i as f32 * std::f32::consts::PI / n as f32;
|
||||
let v = Vec2::new(cx + r * a.cos(), cy + r * a.sin());
|
||||
if i == 0 {
|
||||
p.move_to(v);
|
||||
} else {
|
||||
p.line_to(v);
|
||||
}
|
||||
}
|
||||
p.close();
|
||||
p
|
||||
}
|
||||
|
||||
/// Open two-point line.
|
||||
pub fn line(a: Vec2, b: Vec2) -> Path {
|
||||
let mut p = Path::new();
|
||||
p.move_to(a).line_to(b);
|
||||
p
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.cmds.is_empty()
|
||||
}
|
||||
|
||||
/// Control-point bounds (a superset of the exact curve bounds).
|
||||
pub fn bounds(&self) -> Rect {
|
||||
let mut r = Rect::EMPTY;
|
||||
for c in &self.cmds {
|
||||
match *c {
|
||||
PathCmd::MoveTo(p) | PathCmd::LineTo(p) => r.include(p),
|
||||
PathCmd::QuadTo(a, p) => {
|
||||
r.include(a);
|
||||
r.include(p);
|
||||
}
|
||||
PathCmd::CubicTo(a, b, p) => {
|
||||
r.include(a);
|
||||
r.include(b);
|
||||
r.include(p);
|
||||
}
|
||||
PathCmd::Close => {}
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Path with every point transformed.
|
||||
pub fn transformed(&self, m: &Affine) -> Path {
|
||||
let t = |p: Vec2| m.apply(p);
|
||||
Path {
|
||||
cmds: self
|
||||
.cmds
|
||||
.iter()
|
||||
.map(|c| match *c {
|
||||
PathCmd::MoveTo(p) => PathCmd::MoveTo(t(p)),
|
||||
PathCmd::LineTo(p) => PathCmd::LineTo(t(p)),
|
||||
PathCmd::QuadTo(a, p) => PathCmd::QuadTo(t(a), t(p)),
|
||||
PathCmd::CubicTo(a, b, p) => PathCmd::CubicTo(t(a), t(b), t(p)),
|
||||
PathCmd::Close => PathCmd::Close,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Point-wise interpolation for shape tweens. `None` when the command structures differ.
|
||||
pub fn lerp(&self, o: &Path, t: f32) -> Option<Path> {
|
||||
if self.cmds.len() != o.cmds.len() {
|
||||
return None;
|
||||
}
|
||||
let l = |a: Vec2, b: Vec2| a.lerp(b, t);
|
||||
let mut cmds = Vec::with_capacity(self.cmds.len());
|
||||
for (a, b) in self.cmds.iter().zip(&o.cmds) {
|
||||
cmds.push(match (*a, *b) {
|
||||
(PathCmd::MoveTo(p), PathCmd::MoveTo(q)) => PathCmd::MoveTo(l(p, q)),
|
||||
(PathCmd::LineTo(p), PathCmd::LineTo(q)) => PathCmd::LineTo(l(p, q)),
|
||||
(PathCmd::QuadTo(p1, p), PathCmd::QuadTo(q1, q)) => PathCmd::QuadTo(l(p1, q1), l(p, q)),
|
||||
(PathCmd::CubicTo(p1, p2, p), PathCmd::CubicTo(q1, q2, q)) => PathCmd::CubicTo(l(p1, q1), l(p2, q2), l(p, q)),
|
||||
(PathCmd::Close, PathCmd::Close) => PathCmd::Close,
|
||||
_ => return None,
|
||||
});
|
||||
}
|
||||
Some(Path { cmds })
|
||||
}
|
||||
|
||||
/// Flattens under `m` into polylines whose deviation from the true curve is at most
|
||||
/// `tolerance` (in output units). Non-finite points are dropped.
|
||||
pub fn flatten(&self, m: &Affine, tolerance: f32) -> Vec<Polyline> {
|
||||
let tol = if tolerance.is_finite() && tolerance > 1e-4 { tolerance } else { 0.1 };
|
||||
let mut out: Vec<Polyline> = Vec::new();
|
||||
let mut cur = Polyline::default();
|
||||
let mut start = Vec2::ZERO;
|
||||
let mut last = Vec2::ZERO;
|
||||
let flush = |cur: &mut Polyline, out: &mut Vec<Polyline>| {
|
||||
if cur.points.len() >= 2 {
|
||||
out.push(std::mem::take(cur));
|
||||
} else {
|
||||
cur.points.clear();
|
||||
cur.closed = false;
|
||||
}
|
||||
};
|
||||
for c in &self.cmds {
|
||||
match *c {
|
||||
PathCmd::MoveTo(p) => {
|
||||
flush(&mut cur, &mut out);
|
||||
let p = m.apply(p);
|
||||
start = p;
|
||||
last = p;
|
||||
push_finite(&mut cur.points, p);
|
||||
}
|
||||
PathCmd::LineTo(p) => {
|
||||
let p = m.apply(p);
|
||||
if cur.points.is_empty() {
|
||||
push_finite(&mut cur.points, last);
|
||||
}
|
||||
push_finite(&mut cur.points, p);
|
||||
last = p;
|
||||
}
|
||||
PathCmd::QuadTo(c1, p) => {
|
||||
let (c1, p) = (m.apply(c1), m.apply(p));
|
||||
if cur.points.is_empty() {
|
||||
push_finite(&mut cur.points, last);
|
||||
}
|
||||
let dd = (last - c1 * 2.0 + p).length();
|
||||
let n = segments(0.25 * dd, tol);
|
||||
for i in 1..=n {
|
||||
let t = i as f32 / n as f32;
|
||||
let mt = 1.0 - t;
|
||||
let q = last * (mt * mt) + c1 * (2.0 * mt * t) + p * (t * t);
|
||||
push_finite(&mut cur.points, q);
|
||||
}
|
||||
last = p;
|
||||
}
|
||||
PathCmd::CubicTo(c1, c2, p) => {
|
||||
let (c1, c2, p) = (m.apply(c1), m.apply(c2), m.apply(p));
|
||||
if cur.points.is_empty() {
|
||||
push_finite(&mut cur.points, last);
|
||||
}
|
||||
let dd = (last - c1 * 2.0 + c2).length().max((c1 - c2 * 2.0 + p).length());
|
||||
let n = segments(0.75 * dd, tol);
|
||||
for i in 1..=n {
|
||||
let t = i as f32 / n as f32;
|
||||
let mt = 1.0 - t;
|
||||
let q = last * (mt * mt * mt) + c1 * (3.0 * mt * mt * t) + c2 * (3.0 * mt * t * t) + p * (t * t * t);
|
||||
push_finite(&mut cur.points, q);
|
||||
}
|
||||
last = p;
|
||||
}
|
||||
PathCmd::Close => {
|
||||
cur.closed = true;
|
||||
flush(&mut cur, &mut out);
|
||||
last = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut cur, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `p` (in the same space as `m`'s output) is inside the filled path.
|
||||
pub fn contains(&self, p: Vec2, m: &Affine, rule: FillRule) -> bool {
|
||||
let mut winding = 0i32;
|
||||
for pl in self.flatten(m, 0.25) {
|
||||
let pts = &pl.points;
|
||||
let n = pts.len();
|
||||
for i in 0..n {
|
||||
let a = pts[i];
|
||||
let b = pts[(i + 1) % n];
|
||||
if a.y <= p.y {
|
||||
if b.y > p.y && (b - a).cross(p - a) > 0.0 {
|
||||
winding += 1;
|
||||
}
|
||||
} else if b.y <= p.y && (b - a).cross(p - a) < 0.0 {
|
||||
winding -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
match rule {
|
||||
FillRule::NonZero => winding != 0,
|
||||
FillRule::EvenOdd => winding % 2 != 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Distance from `p` to the nearest flattened edge (for stroke hit testing).
|
||||
pub fn distance_to_edge(&self, p: Vec2, m: &Affine) -> f32 {
|
||||
let mut best = f32::INFINITY;
|
||||
for pl in self.flatten(m, 0.25) {
|
||||
let n = pl.points.len();
|
||||
let segs = if pl.closed { n } else { n.saturating_sub(1) };
|
||||
for i in 0..segs {
|
||||
let a = pl.points[i];
|
||||
let b = pl.points[(i + 1) % n];
|
||||
best = best.min(segment_distance(p, a, b));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
}
|
||||
|
||||
fn push_finite(v: &mut Vec<Vec2>, p: Vec2) {
|
||||
if p.is_finite() {
|
||||
v.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
fn segments(scaled_dd: f32, tol: f32) -> usize {
|
||||
let n = (scaled_dd / tol).sqrt().ceil();
|
||||
if n.is_finite() && n >= 1.0 { (n as usize).min(MAX_SEGMENTS_PER_CURVE) } else { 1 }
|
||||
}
|
||||
|
||||
/// Distance from point `p` to segment `ab`.
|
||||
pub fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 {
|
||||
let ab = b - a;
|
||||
let len2 = ab.dot(ab);
|
||||
let t = if len2 > 1e-12 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
p.distance(a + ab * t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn flatten_rect_is_closed_polygon() {
|
||||
let pls = Path::rect(0.0, 0.0, 10.0, 5.0).flatten(&Affine::IDENTITY, 0.1);
|
||||
assert_eq!(pls.len(), 1);
|
||||
assert!(pls[0].closed);
|
||||
assert_eq!(pls[0].points.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_flatten_within_tolerance() {
|
||||
let r = 100.0;
|
||||
let pls = Path::ellipse(0.0, 0.0, r, r).flatten(&Affine::IDENTITY, 0.1);
|
||||
for p in &pls[0].points {
|
||||
assert!((p.length() - r).abs() < 0.2, "{}", p.length());
|
||||
}
|
||||
// tighter tolerance yields more points
|
||||
let fine = Path::ellipse(0.0, 0.0, r, r).flatten(&Affine::IDENTITY, 0.01);
|
||||
assert!(fine[0].points.len() > pls[0].points.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contains_respects_fill_rule() {
|
||||
let mut p = Path::rect(0.0, 0.0, 10.0, 10.0);
|
||||
p.cmds.extend(Path::rect(2.0, 2.0, 6.0, 6.0).cmds); // same winding → hole only with even-odd
|
||||
let c = Vec2::new(5.0, 5.0);
|
||||
assert!(p.contains(c, &Affine::IDENTITY, FillRule::NonZero));
|
||||
assert!(!p.contains(c, &Affine::IDENTITY, FillRule::EvenOdd));
|
||||
assert!(!p.contains(Vec2::new(11.0, 5.0), &Affine::IDENTITY, FillRule::NonZero));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_curves_are_bounded() {
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::ZERO).cubic_to(Vec2::new(1e30, 0.0), Vec2::new(f32::NAN, 1.0), Vec2::new(1.0, 1.0));
|
||||
let pls = p.flatten(&Affine::IDENTITY, 0.1);
|
||||
assert!(pls.iter().all(|pl| pl.points.len() <= MAX_SEGMENTS_PER_CURVE + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_round_trip_is_exact() {
|
||||
let mut p = Path::rounded_rect(-1.5, 2.25, 100.0, 33.333, 7.0);
|
||||
p.cmds.extend(Path::star(1e-7, -3e5, 12.0, 5.0, 7).cmds);
|
||||
p.quad_to(Vec2::new(0.1, 0.2), Vec2::new(1.0 / 3.0, -0.0));
|
||||
let s = p.to_svg();
|
||||
assert_eq!(Path::from_svg(&s).unwrap(), p);
|
||||
assert!(s.starts_with('M'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_parser_rejects_garbage_without_panicking() {
|
||||
for bad in ["L", "M 1", "Z 3", "12 M", "M1 2 x", "M nan 1", "M 1e99 1", "M1 2L", "C1 2 3 4 5"] {
|
||||
assert!(Path::from_svg(bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(Path::from_svg("").unwrap(), Path::new());
|
||||
assert_eq!(Path::from_svg("M1,2 L3,4 5,6 z").unwrap().cmds.len(), 4);
|
||||
assert_eq!(Path::from_svg("M1e-3 2E+2").unwrap().cmds[0], PathCmd::MoveTo(Vec2::new(1e-3, 200.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_json_paths_still_load() {
|
||||
let legacy = r#"{"cmds":[{"MoveTo":{"x":1.0,"y":2.0}},{"LineTo":{"x":3.0,"y":4.0}},"Close"]}"#;
|
||||
let p: Path = serde_json::from_str(legacy).unwrap();
|
||||
assert_eq!(p.cmds.len(), 3);
|
||||
let s = serde_json::to_string(&p).unwrap();
|
||||
assert_eq!(s, "\"M1 2L3 4Z\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lerp_requires_matching_structure() {
|
||||
let a = Path::rect(0.0, 0.0, 10.0, 10.0);
|
||||
let b = Path::rect(10.0, 10.0, 20.0, 20.0);
|
||||
let m = a.lerp(&b, 0.5).unwrap();
|
||||
assert_eq!(m.bounds(), Rect::new(5.0, 5.0, 20.0, 20.0));
|
||||
assert!(a.lerp(&Path::ellipse(0.0, 0.0, 1.0, 1.0), 0.5).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Full SVG path data (SVG 1.1 §8.3 / SVG 2 "paths"): every command in absolute and relative
|
||||
//! form (M L H V C S Q T A Z), implicit repeats, packed numbers and arc flags.
|
||||
//!
|
||||
//! [`crate::Path::from_svg`] stays the strict parser for AniCraft's own file format; this one
|
||||
//! reads SVG written by other tools (icon sets now, SVG import later). Elliptical arcs become
|
||||
//! cubic Béziers using the endpoint-to-centre conversion of the SVG implementation notes
|
||||
//! (W3C SVG 1.1 Appendix F.6, Royalty-Free Patent Policy), at most a quarter turn per cubic.
|
||||
//! Never panics; non-finite numbers and oversized paths are errors.
|
||||
|
||||
use crate::path::MAX_PATH_CMDS;
|
||||
use crate::{Path, Vec2};
|
||||
|
||||
struct Cursor<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Cursor<'_> {
|
||||
fn skip(&mut self) {
|
||||
while self.s.get(self.i).is_some_and(|c| c.is_ascii_whitespace() || *c == b',') {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
fn letter(&mut self) -> Option<u8> {
|
||||
self.skip();
|
||||
self.s.get(self.i).copied().filter(u8::is_ascii_alphabetic).filter(|c| !matches!(c, b'e' | b'E'))
|
||||
}
|
||||
fn number(&mut self) -> Result<f64, String> {
|
||||
self.skip();
|
||||
let start = self.i;
|
||||
let at = |i: usize| self.s.get(i).copied();
|
||||
let mut i = self.i;
|
||||
if matches!(at(i), Some(b'+' | b'-')) {
|
||||
i += 1;
|
||||
}
|
||||
let mut digits = false;
|
||||
while at(i).is_some_and(|c| c.is_ascii_digit()) {
|
||||
i += 1;
|
||||
digits = true;
|
||||
}
|
||||
if at(i) == Some(b'.') {
|
||||
i += 1;
|
||||
while at(i).is_some_and(|c| c.is_ascii_digit()) {
|
||||
i += 1;
|
||||
digits = true;
|
||||
}
|
||||
}
|
||||
if !digits {
|
||||
return Err(format!("expected a number at byte {start}"));
|
||||
}
|
||||
if matches!(at(i), Some(b'e' | b'E')) {
|
||||
let mut j = i + 1;
|
||||
if matches!(at(j), Some(b'+' | b'-')) {
|
||||
j += 1;
|
||||
}
|
||||
if at(j).is_some_and(|c| c.is_ascii_digit()) {
|
||||
while at(j).is_some_and(|c| c.is_ascii_digit()) {
|
||||
j += 1;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
let tok = std::str::from_utf8(self.s.get(start..i).unwrap_or_default()).unwrap_or("");
|
||||
let v: f64 = tok.parse().map_err(|_| format!("bad number '{tok}'"))?;
|
||||
if !v.is_finite() {
|
||||
return Err(format!("number '{tok}' is not finite"));
|
||||
}
|
||||
self.i = i;
|
||||
Ok(v)
|
||||
}
|
||||
/// An arc flag: a single `0` or `1`, which may be packed against the next number.
|
||||
fn flag(&mut self) -> Result<bool, String> {
|
||||
self.skip();
|
||||
match self.s.get(self.i) {
|
||||
Some(b'0') => {
|
||||
self.i += 1;
|
||||
Ok(false)
|
||||
}
|
||||
Some(b'1') => {
|
||||
self.i += 1;
|
||||
Ok(true)
|
||||
}
|
||||
_ => Err(format!("expected an arc flag (0 or 1) at byte {}", self.i)),
|
||||
}
|
||||
}
|
||||
fn done(&mut self) -> bool {
|
||||
self.skip();
|
||||
self.i >= self.s.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct P(f64, f64);
|
||||
|
||||
impl P {
|
||||
fn v(self) -> Vec2 {
|
||||
Vec2::new(self.0 as f32, self.1 as f32)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses SVG path data (`d` attribute) into a [`Path`].
|
||||
pub fn parse_path_data(d: &str) -> Result<Path, String> {
|
||||
let mut c = Cursor { s: d.as_bytes(), i: 0 };
|
||||
let mut path = Path::new();
|
||||
let (mut cur, mut start) = (P(0.0, 0.0), P(0.0, 0.0));
|
||||
// The last control point of a C/S (for S) or Q/T (for T), for reflection.
|
||||
let (mut last_cubic, mut last_quad): (Option<P>, Option<P>) = (None, None);
|
||||
let mut cmd: Option<u8> = None;
|
||||
while !c.done() {
|
||||
if let Some(l) = c.letter() {
|
||||
c.i += 1;
|
||||
cmd = Some(l);
|
||||
}
|
||||
let Some(k) = cmd else { return Err("path data must start with a command".into()) };
|
||||
let rel = k.is_ascii_lowercase();
|
||||
let off = |p: P, cur: P| if rel { P(p.0 + cur.0, p.1 + cur.1) } else { p };
|
||||
let pt = |c: &mut Cursor| -> Result<P, String> { Ok(P(c.number()?, c.number()?)) };
|
||||
let (mut nc, mut nq) = (None, None);
|
||||
match k.to_ascii_uppercase() {
|
||||
b'M' => {
|
||||
let p = off(pt(&mut c)?, cur);
|
||||
path.move_to(p.v());
|
||||
cur = p;
|
||||
start = p;
|
||||
// Further pairs after a moveto are linetos.
|
||||
cmd = Some(if rel { b'l' } else { b'L' });
|
||||
}
|
||||
b'L' => {
|
||||
cur = off(pt(&mut c)?, cur);
|
||||
path.line_to(cur.v());
|
||||
}
|
||||
b'H' => {
|
||||
let x = c.number()?;
|
||||
cur = P(if rel { cur.0 + x } else { x }, cur.1);
|
||||
path.line_to(cur.v());
|
||||
}
|
||||
b'V' => {
|
||||
let y = c.number()?;
|
||||
cur = P(cur.0, if rel { cur.1 + y } else { y });
|
||||
path.line_to(cur.v());
|
||||
}
|
||||
b'C' => {
|
||||
let (c1, c2, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur), off(pt(&mut c)?, cur));
|
||||
path.cubic_to(c1.v(), c2.v(), p.v());
|
||||
nc = Some(c2);
|
||||
cur = p;
|
||||
}
|
||||
b'S' => {
|
||||
let c1 = last_cubic.map_or(cur, |l| P(2.0 * cur.0 - l.0, 2.0 * cur.1 - l.1));
|
||||
let (c2, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur));
|
||||
path.cubic_to(c1.v(), c2.v(), p.v());
|
||||
nc = Some(c2);
|
||||
cur = p;
|
||||
}
|
||||
b'Q' => {
|
||||
let (q, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur));
|
||||
path.quad_to(q.v(), p.v());
|
||||
nq = Some(q);
|
||||
cur = p;
|
||||
}
|
||||
b'T' => {
|
||||
let q = last_quad.map_or(cur, |l| P(2.0 * cur.0 - l.0, 2.0 * cur.1 - l.1));
|
||||
let p = off(pt(&mut c)?, cur);
|
||||
path.quad_to(q.v(), p.v());
|
||||
nq = Some(q);
|
||||
cur = p;
|
||||
}
|
||||
b'A' => {
|
||||
let (rx, ry, rot) = (c.number()?, c.number()?, c.number()?);
|
||||
let (large, sweep) = (c.flag()?, c.flag()?);
|
||||
let p = off(pt(&mut c)?, cur);
|
||||
arc_to(&mut path, cur, rx, ry, rot, large, sweep, p);
|
||||
cur = p;
|
||||
}
|
||||
b'Z' => {
|
||||
path.close();
|
||||
cur = start;
|
||||
// Numbers may not follow Z without a new command.
|
||||
cmd = None;
|
||||
}
|
||||
other => return Err(format!("unknown path command '{}'", other as char)),
|
||||
}
|
||||
last_cubic = nc;
|
||||
last_quad = nq;
|
||||
if path.cmds.len() > MAX_PATH_CMDS {
|
||||
return Err(format!("path has more than {MAX_PATH_CMDS} commands"));
|
||||
}
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Appends the SVG elliptical arc from `p0` to `p1` as cubics (F.6.5 / F.6.6).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn arc_to(path: &mut Path, p0: P, rx: f64, ry: f64, rot_deg: f64, large: bool, sweep: bool, p1: P) {
|
||||
if (p0.0 - p1.0).abs() < 1e-12 && (p0.1 - p1.1).abs() < 1e-12 {
|
||||
return;
|
||||
}
|
||||
let (mut rx, mut ry) = (rx.abs(), ry.abs());
|
||||
if rx < 1e-12 || ry < 1e-12 {
|
||||
path.line_to(p1.v());
|
||||
return;
|
||||
}
|
||||
let (sin, cos) = rot_deg.to_radians().sin_cos();
|
||||
let (dx, dy) = ((p0.0 - p1.0) * 0.5, (p0.1 - p1.1) * 0.5);
|
||||
let (x1, y1) = (cos * dx + sin * dy, -sin * dx + cos * dy);
|
||||
// Radii too small to reach: scale them up (F.6.6).
|
||||
let lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry);
|
||||
if lambda > 1.0 {
|
||||
let s = lambda.sqrt();
|
||||
rx *= s;
|
||||
ry *= s;
|
||||
}
|
||||
let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
|
||||
let den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
|
||||
let mut coef = if den > 0.0 { (num / den).max(0.0).sqrt() } else { 0.0 };
|
||||
if large == sweep {
|
||||
coef = -coef;
|
||||
}
|
||||
let (cxp, cyp) = (coef * rx * y1 / ry, -coef * ry * x1 / rx);
|
||||
let (cx, cy) = (cos * cxp - sin * cyp + (p0.0 + p1.0) * 0.5, sin * cxp + cos * cyp + (p0.1 + p1.1) * 0.5);
|
||||
let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
|
||||
let (ux, uy) = ((x1 - cxp) / rx, (y1 - cyp) / ry);
|
||||
let (vx, vy) = ((-x1 - cxp) / rx, (-y1 - cyp) / ry);
|
||||
let theta1 = angle(1.0, 0.0, ux, uy);
|
||||
let mut delta = angle(ux, uy, vx, vy);
|
||||
let tau = std::f64::consts::TAU;
|
||||
if !sweep && delta > 0.0 {
|
||||
delta -= tau;
|
||||
} else if sweep && delta < 0.0 {
|
||||
delta += tau;
|
||||
}
|
||||
let n = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().clamp(1.0, 4.0) as usize;
|
||||
let step = delta / n as f64;
|
||||
let k = 4.0 / 3.0 * (step / 4.0).tan();
|
||||
// A point / tangent on the unit circle, mapped onto the rotated ellipse.
|
||||
let map = |x: f64, y: f64| P(cx + rx * cos * x - ry * sin * y, cy + rx * sin * x + ry * cos * y);
|
||||
let mut t = theta1;
|
||||
for i in 0..n {
|
||||
let (s0, c0) = t.sin_cos();
|
||||
let t1 = t + step;
|
||||
let (s1, c1) = t1.sin_cos();
|
||||
let a = map(c0 - k * s0, s0 + k * c0);
|
||||
let b = map(c1 + k * s1, s1 - k * c1);
|
||||
// Land exactly on the requested end point.
|
||||
let e = if i + 1 == n { p1 } else { map(c1, s1) };
|
||||
path.cubic_to(a.v(), b.v(), e.v());
|
||||
t = t1;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::PathCmd;
|
||||
|
||||
fn ends(p: &Path) -> Vec<Vec2> {
|
||||
p.anchors().into_iter().map(|(_, a)| a).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_and_shorthand_commands() {
|
||||
let p = parse_path_data("m10 10 h5 v5 H10 z m 1,1 l2-2").unwrap();
|
||||
assert_eq!(ends(&p), vec![Vec2::new(10.0, 10.0), Vec2::new(15.0, 10.0), Vec2::new(15.0, 15.0), Vec2::new(10.0, 15.0), Vec2::new(11.0, 11.0), Vec2::new(13.0, 9.0)]);
|
||||
assert!(matches!(p.cmds[4], PathCmd::Close));
|
||||
// Implicit lineto after moveto, packed negative numbers.
|
||||
let q = parse_path_data("M0 0 10 0-5.5.5").unwrap();
|
||||
assert_eq!(ends(&q), vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(-5.5, 0.5)]);
|
||||
// S reflects the previous control point.
|
||||
let s = parse_path_data("M0 0 C 0 10 10 10 10 0 S 20 -10 20 0").unwrap();
|
||||
assert!(matches!(s.cmds[2], PathCmd::CubicTo(c1, _, _) if (c1 - Vec2::new(10.0, -10.0)).length() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arcs_land_on_the_ellipse() {
|
||||
// A half circle of radius 5 from (0,0) to (10,0), sweeping through (5,-5) or (5,5).
|
||||
for (sweep, mid_y) in [("1", -5.0), ("0", 5.0)] {
|
||||
let p = parse_path_data(&format!("M0 0 A5 5 0 0 {sweep} 10 0")).unwrap();
|
||||
let lines = p.flatten(&crate::Affine::IDENTITY, 0.01);
|
||||
let pts = &lines[0].points;
|
||||
assert!(pts.iter().all(|q| (q.distance(Vec2::new(5.0, 0.0)) - 5.0).abs() < 0.05), "on the circle");
|
||||
assert!(pts.iter().any(|q| (q.y - mid_y).abs() < 0.05), "through the right side ({sweep})");
|
||||
assert_eq!(pts.last().copied(), Some(Vec2::new(10.0, 0.0)));
|
||||
}
|
||||
// Packed flags as icon sets write them, and radii too small get scaled up.
|
||||
let p = parse_path_data("M2 2a1 1 0 011 1a.1.1 0 0 0 4 0").unwrap();
|
||||
assert_eq!(ends(&p).last().copied(), Some(Vec2::new(7.0, 3.0)));
|
||||
// A real icon outline (rounded square corner arcs).
|
||||
let lock = parse_path_data("M7 11V7a5 5 0 0 1 10 0v4").unwrap();
|
||||
assert_eq!(ends(&lock).last().copied(), Some(Vec2::new(17.0, 11.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_input_is_an_error() {
|
||||
for bad in ["", "10 10", "M", "M 1", "M0 0 A1 1 0 2 0 3 3", "M0 0 Z 4 4", "M0 0 L1e999 0", "M0 0 X1 1"] {
|
||||
if bad.is_empty() {
|
||||
assert!(parse_path_data(bad).unwrap().is_empty());
|
||||
continue;
|
||||
}
|
||||
assert!(parse_path_data(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Mask → outlines: closed iso-contours of a grid of values (Paint Bucket regions).
|
||||
//!
|
||||
//! Marching squares at level 0.5 over cell centres, with linear interpolation along cell edges
|
||||
//! and saddles resolved by the cell average, gives closed, non-intersecting loops: outer
|
||||
//! boundaries and holes, which fill correctly with the even-odd rule whatever their direction.
|
||||
//!
|
||||
//! Ported from PhotoCraft's mask tracer (`vector::trace::contours`, same project family, MIT OR
|
||||
//! Apache-2.0) and reviewed: values are read through a bounds-checked accessor (no indexing that
|
||||
//! a bad size could push out of range), the grid size is validated, and points come back in
|
||||
//! cell units for the caller to map. Curve fitting is `crate::fit_curve`.
|
||||
|
||||
use crate::Vec2;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Largest grid traced (cells).
|
||||
pub const MAX_CELLS: usize = 16_000_000;
|
||||
|
||||
/// Closed contours at level 0.5 of `values` (row-major, `w × h`); cell `(x, y)` has its centre
|
||||
/// at `(x + 0.5, y + 0.5)`. Values outside the grid count as 0. Empty when the sizes disagree.
|
||||
pub fn contours(values: &[f32], w: usize, h: usize) -> Vec<Vec<Vec2>> {
|
||||
if w == 0 || h == 0 || w.saturating_mul(h) != values.len() || values.len() > MAX_CELLS {
|
||||
return Vec::new();
|
||||
}
|
||||
let (wi, hi) = (w as i64, h as i64);
|
||||
let get = |x: i64, y: i64| -> f32 {
|
||||
if x < 0 || y < 0 || x >= wi || y >= hi {
|
||||
return 0.0;
|
||||
}
|
||||
values.get((y * wi + x) as usize).copied().unwrap_or(0.0)
|
||||
};
|
||||
let lvl = 0.5f32;
|
||||
let point = |a: (i64, i64), b: (i64, i64)| -> Vec2 {
|
||||
let (va, vb) = (get(a.0, a.1), get(b.0, b.1));
|
||||
let t = if (vb - va).abs() > 1e-9 { ((lvl - va) / (vb - va)).clamp(0.0, 1.0) } else { 0.5 };
|
||||
let (ax, ay) = (a.0 as f32 + 0.5, a.1 as f32 + 0.5);
|
||||
let (bx, by) = (b.0 as f32 + 0.5, b.1 as f32 + 0.5);
|
||||
Vec2::new(ax + (bx - ax) * t, ay + (by - ay) * t)
|
||||
};
|
||||
// Edge ids: horizontal edge between (x,y)-(x+1,y) = (x, y, 0); vertical (x,y)-(x,y+1) = (x, y, 1).
|
||||
// Segments go edge → edge with the inside on the left (y down).
|
||||
let mut next: HashMap<(i64, i64, u8), (i64, i64, u8)> = HashMap::new();
|
||||
for cy in -1..hi {
|
||||
for cx in -1..wi {
|
||||
let tl = get(cx, cy) >= lvl;
|
||||
let tr = get(cx + 1, cy) >= lvl;
|
||||
let br = get(cx + 1, cy + 1) >= lvl;
|
||||
let bl = get(cx, cy + 1) >= lvl;
|
||||
let idx = u8::from(tl) | (u8::from(tr) << 1) | (u8::from(br) << 2) | (u8::from(bl) << 3);
|
||||
if idx == 0 || idx == 15 {
|
||||
continue;
|
||||
}
|
||||
let top = (cx, cy, 0u8);
|
||||
let bottom = (cx, cy + 1, 0u8);
|
||||
let left = (cx, cy, 1u8);
|
||||
let right = (cx + 1, cy, 1u8);
|
||||
let centre = || (get(cx, cy) + get(cx + 1, cy) + get(cx + 1, cy + 1) + get(cx, cy + 1)) / 4.0 >= lvl;
|
||||
let mut seg = |a, b| {
|
||||
next.insert(a, b);
|
||||
};
|
||||
match idx {
|
||||
1 => seg(left, top),
|
||||
2 => seg(top, right),
|
||||
3 => seg(left, right),
|
||||
4 => seg(right, bottom),
|
||||
5 => {
|
||||
if centre() {
|
||||
seg(left, bottom);
|
||||
seg(right, top);
|
||||
} else {
|
||||
seg(left, top);
|
||||
seg(right, bottom);
|
||||
}
|
||||
}
|
||||
6 => seg(top, bottom),
|
||||
7 => seg(left, bottom),
|
||||
8 => seg(bottom, left),
|
||||
9 => seg(bottom, top),
|
||||
10 => {
|
||||
if centre() {
|
||||
seg(top, left);
|
||||
seg(bottom, right);
|
||||
} else {
|
||||
seg(top, right);
|
||||
seg(bottom, left);
|
||||
}
|
||||
}
|
||||
11 => seg(bottom, right),
|
||||
12 => seg(right, left),
|
||||
13 => seg(right, top),
|
||||
14 => seg(top, left),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let edge_point = |e: (i64, i64, u8)| if e.2 == 0 { point((e.0, e.1), (e.0 + 1, e.1)) } else { point((e.0, e.1), (e.0, e.1 + 1)) };
|
||||
let mut keys: Vec<(i64, i64, u8)> = next.keys().copied().collect();
|
||||
keys.sort_unstable_by_key(|k| (k.1, k.0, k.2));
|
||||
let mut out = Vec::new();
|
||||
for start in keys {
|
||||
if !next.contains_key(&start) {
|
||||
continue;
|
||||
}
|
||||
let mut lp = Vec::new();
|
||||
let mut cur = start;
|
||||
while let Some(n) = next.remove(&cur) {
|
||||
lp.push(edge_point(cur));
|
||||
cur = n;
|
||||
if cur == start {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Drop consecutive duplicates (interpolation can land on a corner).
|
||||
lp.dedup_by(|a, b| a.distance(*b) < 1e-6);
|
||||
if lp.len() >= 3 {
|
||||
out.push(lp);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn grid(w: usize, h: usize, inside: impl Fn(usize, usize) -> bool) -> Vec<f32> {
|
||||
(0..w * h).map(|i| if inside(i % w, i / w) { 1.0 } else { 0.0 }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_square_and_a_ring() {
|
||||
let sq = grid(10, 10, |x, y| (2..8).contains(&x) && (2..8).contains(&y));
|
||||
let loops = contours(&sq, 10, 10);
|
||||
assert_eq!(loops.len(), 1);
|
||||
let xs: Vec<f32> = loops[0].iter().map(|p| p.x).collect();
|
||||
let (lo, hi) = (xs.iter().copied().fold(f32::INFINITY, f32::min), xs.iter().copied().fold(0.0, f32::max));
|
||||
assert!((lo - 2.0).abs() < 0.01 && (hi - 8.0).abs() < 0.01, "{lo}..{hi}: edges halfway between cells");
|
||||
// A ring has an outer boundary and a hole.
|
||||
let ring = grid(20, 20, |x, y| (2..18).contains(&x) && (2..18).contains(&y) && !((7..13).contains(&x) && (7..13).contains(&y)));
|
||||
assert_eq!(contours(&ring, 20, 20).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_sizes_are_empty_not_a_panic() {
|
||||
assert!(contours(&[1.0; 10], 3, 3).is_empty());
|
||||
assert!(contours(&[], 0, 0).is_empty());
|
||||
assert_eq!(contours(&[1.0], 1, 1).len(), 1, "a single cell touching the border");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "anicraft-render"
|
||||
description = "AniCraft L2: deterministic CPU oracle renderer (analytic coverage rasterizer, paints, compositor, PNG)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anicraft-geom.workspace = true
|
||||
anicraft-doc.workspace = true
|
||||
rayon.workspace = true
|
||||
png.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,610 @@
|
||||
//! AniCraft CPU oracle renderer (layer L2).
|
||||
//!
|
||||
//! Deterministic: the same display list and view always produce the same bytes, whatever the
|
||||
//! thread count. Each output row is written by exactly one task and shapes composite in order.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod paint;
|
||||
pub mod raster;
|
||||
pub mod stroke;
|
||||
|
||||
use anicraft_doc::{ColorEffect, DisplayItem, DisplayList, Document, Paint, Rgba, evaluate};
|
||||
use anicraft_geom::{Affine, FillRule, Rect, Vec2};
|
||||
use paint::{Premul, Shader, premultiply};
|
||||
use raster::{Coverage, IRect};
|
||||
use rayon::prelude::*;
|
||||
|
||||
/// Largest surface we allocate (pixels): 4096 × 4096.
|
||||
pub const MAX_PIXELS: u64 = 4096 * 4096;
|
||||
/// Flattening tolerance in output pixels.
|
||||
pub const TOLERANCE: f32 = 0.1;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RenderError {
|
||||
#[error("image {0}×{1} is too large (limit {MAX_PIXELS} pixels)")]
|
||||
TooLarge(u32, u32),
|
||||
#[error("PNG encoding failed: {0}")]
|
||||
Png(String),
|
||||
#[error("I/O error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
/// Premultiplied f32 RGBA surface.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Pixmap {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub data: Vec<Premul>,
|
||||
}
|
||||
|
||||
impl Pixmap {
|
||||
pub fn new(width: u32, height: u32) -> Result<Pixmap, RenderError> {
|
||||
let n = u64::from(width) * u64::from(height);
|
||||
if n > MAX_PIXELS {
|
||||
return Err(RenderError::TooLarge(width, height));
|
||||
}
|
||||
Ok(Pixmap { width, height, data: vec![[0.0; 4]; n as usize] })
|
||||
}
|
||||
|
||||
pub fn fill(&mut self, c: Rgba) {
|
||||
let p = premultiply(c);
|
||||
self.data.fill(p);
|
||||
}
|
||||
|
||||
/// Straight-alpha 8-bit RGBA bytes.
|
||||
pub fn to_rgba8(&self) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(self.data.len() * 4);
|
||||
for p in &self.data {
|
||||
let a = p[3].clamp(0.0, 1.0);
|
||||
let un = |v: f32| if a > 1e-6 { (v / a).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let q = |v: f32| (v * 255.0 + 0.5) as u8;
|
||||
out.extend_from_slice(&[q(un(p[0])), q(un(p[1])), q(un(p[2])), q(a)]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Premultiplied 8-bit RGBA (what GPU textures with premultiplied alpha expect).
|
||||
pub fn to_premul_rgba8(&self) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(self.data.len() * 4);
|
||||
for p in &self.data {
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
out.extend_from_slice(&[q(p[0]), q(p[1]), q(p[2]), q(p[3])]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn encode_png(&self) -> Result<Vec<u8>, RenderError> {
|
||||
encode_png(self.width, self.height, &self.to_rgba8())
|
||||
}
|
||||
|
||||
pub fn pixel(&self, x: u32, y: u32) -> Option<Premul> {
|
||||
if x >= self.width || y >= self.height {
|
||||
return None;
|
||||
}
|
||||
self.data.get(y as usize * self.width as usize + x as usize).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes straight-alpha RGBA8 as PNG.
|
||||
pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, RenderError> {
|
||||
let mut buf = Vec::new();
|
||||
{
|
||||
let mut enc = png::Encoder::new(&mut buf, width, height);
|
||||
enc.set_color(png::ColorType::Rgba);
|
||||
enc.set_depth(png::BitDepth::Eight);
|
||||
let mut w = enc.write_header().map_err(|e| RenderError::Png(e.to_string()))?;
|
||||
w.write_image_data(rgba).map_err(|e| RenderError::Png(e.to_string()))?;
|
||||
}
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Where and how to draw.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct View {
|
||||
/// Stage → pixel transform.
|
||||
pub transform: Affine,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Fill colour before drawing (`None` = transparent).
|
||||
pub background: Option<Rgba>,
|
||||
}
|
||||
|
||||
impl View {
|
||||
/// The whole stage at `scale`.
|
||||
pub fn stage(doc: &Document, scale: f32) -> View {
|
||||
let s = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
|
||||
View {
|
||||
transform: Affine::scale(s, s),
|
||||
width: ((doc.stage.width as f32 * s).round() as u32).max(1),
|
||||
height: ((doc.stage.height as f32 * s).round() as u32).max(1),
|
||||
background: Some(doc.stage.background),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Statistics from one render (for the status bar and perf logs).
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct RenderStats {
|
||||
pub items: usize,
|
||||
pub drawn: usize,
|
||||
/// Items skipped because they lie outside the view.
|
||||
pub culled: usize,
|
||||
pub edges: usize,
|
||||
pub pixels_touched: u64,
|
||||
}
|
||||
|
||||
/// Renders frame `frame` of `doc` at `scale` with the stage background.
|
||||
pub fn render_frame(doc: &Document, frame: u32, scale: f32) -> Result<Pixmap, RenderError> {
|
||||
let dl = evaluate(doc, frame);
|
||||
render(&dl, &View::stage(doc, scale)).map(|(p, _)| p)
|
||||
}
|
||||
|
||||
/// Renders a display list.
|
||||
pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), RenderError> {
|
||||
let mut pm = Pixmap::new(view.width, view.height)?;
|
||||
if let Some(bg) = view.background {
|
||||
pm.fill(bg);
|
||||
}
|
||||
let surface = IRect { x0: 0, y0: 0, x1: view.width as i32, y1: view.height as i32 };
|
||||
|
||||
// Phase 1 (parallel over items): cull, flatten, stroke and build shaders. Output keeps
|
||||
// display-list order.
|
||||
let prepared: Vec<Vec<Prepared>> = dl.items.par_iter().map(|item| prepare(item, &view.transform, surface)).collect();
|
||||
let mut stats = RenderStats { items: dl.items.len(), ..Default::default() };
|
||||
let mut ops: Vec<Prepared> = Vec::with_capacity(prepared.len());
|
||||
let mut mask_ops: Vec<Prepared> = Vec::new();
|
||||
for p in prepared {
|
||||
if p.is_empty() {
|
||||
stats.culled += 1;
|
||||
}
|
||||
for op in p {
|
||||
if op.masks.is_some() { mask_ops.push(op) } else { ops.push(op) }
|
||||
}
|
||||
}
|
||||
let clips = Clips::new(&dl.clip_parents, mask_ops);
|
||||
// A clipped op can only touch its clip's area; an op whose clip is empty draws nothing.
|
||||
ops.retain_mut(|op| {
|
||||
let Some(c) = op.clip else { return true };
|
||||
op.bounds = op.bounds.intersect(&clips.bounds(c));
|
||||
!op.bounds.is_empty()
|
||||
});
|
||||
stats.drawn = ops.len();
|
||||
for op in &ops {
|
||||
stats.edges += op.polys.iter().map(Vec::len).sum::<usize>();
|
||||
stats.pixels_touched += (op.bounds.width() * op.bounds.height()) as u64;
|
||||
}
|
||||
|
||||
// Phase 2 (parallel over horizontal bands): each band rasterizes every op that touches
|
||||
// it, in order, into its own rows. A row is owned by exactly one band, so the result is
|
||||
// identical to a serial render whatever the thread count.
|
||||
let w = view.width as usize;
|
||||
pm.data.par_chunks_mut(BAND_ROWS * w.max(1)).enumerate().for_each(|(bi, rows)| {
|
||||
let y0 = (bi * BAND_ROWS) as i32;
|
||||
let band = IRect { x0: 0, y0, x1: surface.x1, y1: (y0 + BAND_ROWS as i32).min(surface.y1) };
|
||||
let mut cov = Coverage::new(IRect { x0: 0, y0: 0, x1: 0, y1: 0 });
|
||||
let mut row = Vec::new();
|
||||
let mut band_clips = BandClips::default();
|
||||
for op in &ops {
|
||||
let b = IRect { x0: op.bounds.x0, y0: op.bounds.y0.max(band.y0), x1: op.bounds.x1, y1: op.bounds.y1.min(band.y1) };
|
||||
if b.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mask = op.clip.map(|c| band_clips.get(&clips, c, band, w, &mut cov, &mut row));
|
||||
cov.reset(b);
|
||||
for poly in &op.polys {
|
||||
cov.add_polygon(poly);
|
||||
}
|
||||
composite(&cov, op, b, band.y0, w, rows, &mut row, mask.as_deref().map(Vec::as_slice));
|
||||
}
|
||||
});
|
||||
Ok((pm, stats))
|
||||
}
|
||||
|
||||
/// Rows per parallel band.
|
||||
const BAND_ROWS: usize = 32;
|
||||
|
||||
/// One fill operation, ready to rasterize: polygons in pixel space, its paint and bounds.
|
||||
struct Prepared {
|
||||
polys: Vec<Vec<Vec2>>,
|
||||
rule: FillRule,
|
||||
shader: Shader,
|
||||
bounds: IRect,
|
||||
/// Drawn only inside this clip.
|
||||
clip: Option<u32>,
|
||||
/// Mask artwork for this clip (not drawn).
|
||||
masks: Option<u32>,
|
||||
}
|
||||
|
||||
/// The clips of a display list: their mask artwork and where each can be non-zero.
|
||||
struct Clips {
|
||||
parents: Vec<Option<u32>>,
|
||||
/// Mask artwork, grouped by clip.
|
||||
art: Vec<Vec<Prepared>>,
|
||||
bounds: Vec<IRect>,
|
||||
}
|
||||
|
||||
const NO_PIXELS: IRect = IRect { x0: 0, y0: 0, x1: 0, y1: 0 };
|
||||
|
||||
impl Clips {
|
||||
fn new(parents: &[Option<u32>], mask_ops: Vec<Prepared>) -> Clips {
|
||||
let n = parents.len();
|
||||
let mut art: Vec<Vec<Prepared>> = (0..n).map(|_| Vec::new()).collect();
|
||||
for op in mask_ops {
|
||||
if let Some(a) = op.masks.and_then(|c| art.get_mut(c as usize)) {
|
||||
a.push(op);
|
||||
}
|
||||
}
|
||||
// A parent always precedes its children, so one pass in order intersects the chain.
|
||||
// A malformed parent link (not earlier in the list) masks everything out.
|
||||
let mut bounds: Vec<IRect> = Vec::with_capacity(n);
|
||||
let mut clean: Vec<Option<u32>> = Vec::with_capacity(n);
|
||||
for (i, a) in art.iter().enumerate() {
|
||||
let own = a.iter().fold(NO_PIXELS, |r, op| r.union(&op.bounds));
|
||||
let parent = parents.get(i).copied().flatten();
|
||||
let b = match parent {
|
||||
None => own,
|
||||
Some(p) => bounds.get(p as usize).filter(|_| (p as usize) < i).map_or(NO_PIXELS, |pb| own.intersect(pb)),
|
||||
};
|
||||
bounds.push(b);
|
||||
clean.push(parent.filter(|&p| (p as usize) < i));
|
||||
}
|
||||
Clips { parents: clean, art, bounds }
|
||||
}
|
||||
|
||||
fn bounds(&self, c: u32) -> IRect {
|
||||
self.bounds.get(c as usize).copied().unwrap_or(NO_PIXELS)
|
||||
}
|
||||
}
|
||||
|
||||
/// Clip coverage for one band, computed on first use: `w × band height` values in `0..=1`.
|
||||
#[derive(Default)]
|
||||
struct BandClips {
|
||||
cov: Vec<Option<std::rc::Rc<Vec<f32>>>>,
|
||||
}
|
||||
|
||||
impl BandClips {
|
||||
fn get(&mut self, clips: &Clips, c: u32, band: IRect, w: usize, cov: &mut Coverage, row: &mut Vec<f32>) -> std::rc::Rc<Vec<f32>> {
|
||||
let i = c as usize;
|
||||
if self.cov.len() < clips.parents.len() {
|
||||
self.cov.resize(clips.parents.len(), None);
|
||||
}
|
||||
if let Some(Some(done)) = self.cov.get(i) {
|
||||
return done.clone();
|
||||
}
|
||||
let parent = clips.parents.get(i).copied().flatten().map(|p| self.get(clips, p, band, w, cov, row));
|
||||
let mut buf = vec![0.0f32; w * band.height()];
|
||||
// Union of the artwork's coverage (a ∪ b = a + b − ab), anti-aliased like any fill.
|
||||
for op in clips.art.get(i).into_iter().flatten() {
|
||||
let b = op.bounds.intersect(&band);
|
||||
if b.is_empty() {
|
||||
continue;
|
||||
}
|
||||
cov.reset(b);
|
||||
for poly in &op.polys {
|
||||
cov.add_polygon(poly);
|
||||
}
|
||||
row.clear();
|
||||
row.resize(b.width(), 0.0);
|
||||
for ry in 0..b.height() {
|
||||
cov.resolve_row(ry, op.rule, row);
|
||||
let start = (b.y0 + ry as i32 - band.y0) as usize * w + b.x0 as usize;
|
||||
let Some(dst) = buf.get_mut(start..start + b.width()) else { continue };
|
||||
for (d, &k) in dst.iter_mut().zip(row.iter()) {
|
||||
let k = k.clamp(0.0, 1.0);
|
||||
*d = *d + k - *d * k;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(p) = parent {
|
||||
for (d, m) in buf.iter_mut().zip(p.iter()) {
|
||||
*d *= m;
|
||||
}
|
||||
}
|
||||
let buf = std::rc::Rc::new(buf);
|
||||
if let Some(slot) = self.cov.get_mut(i) {
|
||||
*slot = Some(buf.clone());
|
||||
}
|
||||
buf
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns a display item into fill operations (fill, then stroke), or none when culled.
|
||||
fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
|
||||
let mut out = Vec::new();
|
||||
let m = view.mul(&item.transform);
|
||||
if !m.is_finite() {
|
||||
return out;
|
||||
}
|
||||
// Mask artwork is its fill area only: no strokes, no opacity (as animators expect).
|
||||
let is_mask = item.masks.is_some();
|
||||
if is_mask && item.fill.is_none() {
|
||||
return out;
|
||||
}
|
||||
// Cull before flattening: control-point bounds are a cheap, conservative superset.
|
||||
let pad = if is_mask { 1.0 } else { item.stroke.map_or(0.0, |s| s.width * 0.5) + 1.0 };
|
||||
let bounds = item.path.bounds().inflate(pad).transformed(&m);
|
||||
let surface_rect = Rect::new(0.0, 0.0, surface.x1 as f32, surface.y1 as f32);
|
||||
if bounds.is_empty() || bounds.intersect(&surface_rect).is_empty() {
|
||||
return out;
|
||||
}
|
||||
let lines = item.path.flatten(&m, TOLERANCE);
|
||||
if lines.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let (clip, masks) = (item.clip, item.masks);
|
||||
let mut push = |polys: Vec<Vec<Vec2>>, rule, shader: Shader| {
|
||||
if shader.is_solid().is_some_and(|c| c[3] <= 0.0) {
|
||||
return;
|
||||
}
|
||||
if let Some(b) = pixel_bounds(&polys, surface) {
|
||||
out.push(Prepared { polys, rule, shader, bounds: b, clip, masks });
|
||||
}
|
||||
};
|
||||
|
||||
if is_mask {
|
||||
push(lines.iter().map(|l| l.points.clone()).collect(), item.fill_rule, Shader::Solid([1.0; 4]));
|
||||
return out;
|
||||
}
|
||||
if let Some(color) = item.outline {
|
||||
// Outline mode: hairline in the layer colour, no fill.
|
||||
push(stroke::stroke_polygons(&lines, 0.5), FillRule::NonZero, Shader::Solid(premultiply(color)));
|
||||
return out;
|
||||
}
|
||||
if let Some(fill) = &item.fill {
|
||||
let polys: Vec<Vec<Vec2>> = lines.iter().map(|l| l.points.clone()).collect();
|
||||
push(polys, item.fill_rule, Shader::new(fill, &m, &item.color));
|
||||
}
|
||||
if let Some(st) = item.stroke {
|
||||
let mut fx: ColorEffect = item.color;
|
||||
let mut pw = st.width * m.mean_scale();
|
||||
if pw.is_finite() && pw > 0.0 {
|
||||
if pw < 1.0 {
|
||||
// Thin strokes: keep a 1 px footprint and fade by width (avoids dropouts).
|
||||
fx.alpha *= pw;
|
||||
pw = 1.0;
|
||||
}
|
||||
push(stroke::stroke_polygons(&lines, pw * 0.5), FillRule::NonZero, Shader::new(&Paint::Solid(st.color), &m, &fx));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn pixel_bounds(polys: &[Vec<Vec2>], surface: IRect) -> Option<IRect> {
|
||||
let mut r = Rect::EMPTY;
|
||||
for p in polys.iter().flatten() {
|
||||
r.include(*p);
|
||||
}
|
||||
if !(r.max.x >= r.min.x && r.max.y >= r.min.y) {
|
||||
return None; // no points
|
||||
}
|
||||
let b = IRect {
|
||||
x0: (r.min.x.floor().max(surface.x0 as f32)) as i32,
|
||||
y0: (r.min.y.floor().max(surface.y0 as f32)) as i32,
|
||||
x1: (r.max.x.ceil().min(surface.x1 as f32)) as i32,
|
||||
y1: (r.max.y.ceil().min(surface.y1 as f32)) as i32,
|
||||
};
|
||||
(!b.is_empty()).then_some(b)
|
||||
}
|
||||
|
||||
/// Composites coverage `cov` (over `b`) of `op` into the band whose first row is `band_y0`,
|
||||
/// scaled by the band's clip coverage `mask` when the op is clipped.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn composite(cov: &Coverage, op: &Prepared, b: IRect, band_y0: i32, w: usize, rows: &mut [Premul], c: &mut Vec<f32>, mask: Option<&[f32]>) {
|
||||
let bw = b.width();
|
||||
c.clear();
|
||||
c.resize(bw, 0.0);
|
||||
let solid = op.shader.is_solid();
|
||||
for ry in 0..b.height() {
|
||||
cov.resolve_row(ry, op.rule, c);
|
||||
let py = b.y0 + ry as i32;
|
||||
let start = (py - band_y0) as usize * w + b.x0 as usize;
|
||||
if let Some(mask) = mask {
|
||||
let Some(m) = mask.get(start..start + bw) else { continue };
|
||||
for (k, m) in c.iter_mut().zip(m) {
|
||||
*k *= m;
|
||||
}
|
||||
}
|
||||
let Some(dst) = rows.get_mut(start..start + bw) else { continue };
|
||||
for (i, (d, &k)) in dst.iter_mut().zip(c.iter()).enumerate() {
|
||||
if k <= 1e-4 {
|
||||
continue;
|
||||
}
|
||||
let s = match solid {
|
||||
Some(s) => s,
|
||||
None => op.shader.at(b.x0 + i as i32, py),
|
||||
};
|
||||
let sa = s[3] * k;
|
||||
let inv = 1.0 - sa;
|
||||
d[0] = s[0] * k + d[0] * inv;
|
||||
d[1] = s[1] * k + d[1] * inv;
|
||||
d[2] = s[2] * k + d[2] * inv;
|
||||
d[3] = sa + d[3] * inv;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_doc::{ElementId, LayerId, sample};
|
||||
use anicraft_geom::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn item(path: Path, fill: Paint) -> DisplayItem {
|
||||
DisplayItem {
|
||||
path: Arc::new(path),
|
||||
transform: Affine::IDENTITY,
|
||||
fill: Some(fill),
|
||||
stroke: None,
|
||||
fill_rule: FillRule::NonZero,
|
||||
color: ColorEffect::default(),
|
||||
layer: LayerId(0),
|
||||
element: ElementId(0),
|
||||
outline: None,
|
||||
clip: None,
|
||||
masks: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn list(items: Vec<DisplayItem>) -> DisplayList {
|
||||
DisplayList { items, clip_parents: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_reveals_only_its_fill_area() {
|
||||
// A 40 × 40 square masked by a circle of radius 10: only the circle's area shows, in
|
||||
// the square's colour; the mask's own colour, stroke and opacity play no part.
|
||||
let mut square = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
square.clip = Some(0);
|
||||
let mut mask = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.2)));
|
||||
mask.masks = Some(0);
|
||||
mask.stroke = Some(anicraft_doc::Stroke { color: Rgba::BLACK, width: 8.0 });
|
||||
let dl = DisplayList { items: vec![square, mask], clip_parents: vec![None] };
|
||||
let (pm, _) = render(&dl, &view(40, 40)).unwrap();
|
||||
// Pixel for pixel, the same as the circle drawn in the square's colour.
|
||||
let circle = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
let (plain, _) = render(&list(vec![circle]), &view(40, 40)).unwrap();
|
||||
assert!(pm.data.iter().zip(&plain.data).all(|(a, b)| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5)));
|
||||
let area = alpha_sum(&plain);
|
||||
assert_eq!(pm.pixel(20, 20).unwrap(), [0.0, 0.0, 1.0, 1.0]);
|
||||
assert_eq!(pm.pixel(2, 2).unwrap()[3], 0.0);
|
||||
// Two overlapping mask shapes reveal their union, not a cancelled overlap.
|
||||
let mut dl2 = dl.clone();
|
||||
let mut m2 = item(Path::rect(20.0, 0.0, 20.0, 40.0), Paint::Solid(Rgba::WHITE));
|
||||
m2.masks = Some(0);
|
||||
dl2.items.push(m2);
|
||||
let (pm2, _) = render(&dl2, &view(40, 40)).unwrap();
|
||||
assert_eq!(pm2.pixel(25, 20).unwrap()[3], 1.0);
|
||||
assert_eq!(pm2.pixel(35, 2).unwrap()[3], 1.0);
|
||||
assert!((alpha_sum(&pm2) - (800.0 + area / 2.0)).abs() < 8.0, "{}", alpha_sum(&pm2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_mask_hides_everything_and_unclipped_items_are_untouched() {
|
||||
let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
|
||||
clipped.clip = Some(0);
|
||||
let free = item(Path::rect(0.0, 0.0, 2.0, 2.0), Paint::Solid(Rgba::BLACK));
|
||||
let (pm, st) = render(&DisplayList { items: vec![clipped, free.clone()], clip_parents: vec![None] }, &view(8, 8)).unwrap();
|
||||
assert_eq!(st.drawn, 1);
|
||||
assert_eq!(pm, render(&list(vec![free]), &view(8, 8)).unwrap().0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_clips_intersect_and_bad_links_draw_nothing() {
|
||||
let mut fill = item(Path::rect(0.0, 0.0, 64.0, 64.0), Paint::Solid(Rgba::BLACK));
|
||||
fill.clip = Some(1);
|
||||
let mut outer = item(Path::rect(0.0, 0.0, 32.0, 64.0), Paint::Solid(Rgba::BLACK));
|
||||
outer.masks = Some(0);
|
||||
let mut inner = item(Path::rect(0.0, 16.0, 64.0, 32.0), Paint::Solid(Rgba::BLACK));
|
||||
inner.masks = Some(1);
|
||||
let items = vec![fill, outer, inner];
|
||||
// Clip 1 lies inside clip 0: a 32 × 32 square across two render bands survives.
|
||||
let (pm, _) = render(&DisplayList { items: items.clone(), clip_parents: vec![None, Some(0)] }, &view(64, 64)).unwrap();
|
||||
assert!((alpha_sum(&pm) - 32.0 * 32.0).abs() < 1e-2, "{}", alpha_sum(&pm));
|
||||
// A parent link pointing forward (malformed) or out of range masks everything out.
|
||||
for parents in [vec![Some(1), Some(1)], vec![None, Some(9)]] {
|
||||
let (pm, _) = render(&DisplayList { items: items.clone(), clip_parents: parents }, &view(64, 64)).unwrap();
|
||||
assert_eq!(alpha_sum(&pm), 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn view(w: u32, h: u32) -> View {
|
||||
View { transform: Affine::IDENTITY, width: w, height: h, background: None }
|
||||
}
|
||||
|
||||
fn alpha_sum(p: &Pixmap) -> f32 {
|
||||
p.data.iter().map(|c| c[3]).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circle_area_matches_pi_r2() {
|
||||
let r = 40.0;
|
||||
let dl = list(vec![item(Path::ellipse(50.0, 50.0, r, r), Paint::Solid(Rgba::BLACK))]);
|
||||
let (pm, _) = render(&dl, &view(100, 100)).unwrap();
|
||||
let area = std::f32::consts::PI * r * r;
|
||||
let err = (alpha_sum(&pm) - area).abs() / area;
|
||||
assert!(err < 0.005, "relative error {err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_is_pixel_exact_and_clipped() {
|
||||
let dl = list(vec![item(Path::rect(-10.0, 2.0, 15.0, 3.0), Paint::Solid(Rgba::WHITE))]);
|
||||
let (pm, _) = render(&dl, &view(8, 8)).unwrap();
|
||||
assert_eq!(pm.pixel(0, 2).unwrap(), [1.0, 1.0, 1.0, 1.0]);
|
||||
assert_eq!(pm.pixel(4, 4).unwrap(), [1.0, 1.0, 1.0, 1.0]);
|
||||
assert_eq!(pm.pixel(5, 3).unwrap()[3], 0.0);
|
||||
assert_eq!(pm.pixel(0, 1).unwrap()[3], 0.0);
|
||||
assert!((alpha_sum(&pm) - 15.0).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_covers_expected_area() {
|
||||
let mut it = item(Path::line(Vec2::new(10.0, 20.0), Vec2::new(90.0, 20.0)), Paint::Solid(Rgba::BLACK));
|
||||
it.fill = None;
|
||||
it.stroke = Some(anicraft_doc::Stroke { color: Rgba::BLACK, width: 4.0 });
|
||||
let (pm, _) = render(&list(vec![it]),&view(100, 40)).unwrap();
|
||||
// 80 × 4 body plus two round caps (π · 2²)
|
||||
let expected = 80.0 * 4.0 + std::f32::consts::PI * 4.0;
|
||||
assert!((alpha_sum(&pm) - expected).abs() / expected < 0.01, "{}", alpha_sum(&pm));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn src_over_order() {
|
||||
let a = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0)));
|
||||
let b = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 0.5)));
|
||||
let (pm, _) = render(&list(vec![a, b]),&view(4, 4)).unwrap();
|
||||
let p = pm.pixel(1, 1).unwrap();
|
||||
assert!((p[0] - 0.5).abs() < 1e-5 && (p[2] - 0.5).abs() < 1e-5 && (p[3] - 1.0).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn demo_renders_deterministically() {
|
||||
let d = sample::demo();
|
||||
let a = render_frame(&d, 7, 0.5).unwrap();
|
||||
let b = render_frame(&d, 7, 0.5).unwrap();
|
||||
assert_eq!(a.to_rgba8(), b.to_rgba8());
|
||||
assert_eq!((a.width, a.height), (640, 360));
|
||||
// Frames differ because things move.
|
||||
let c = render_frame(&d, 20, 0.5).unwrap();
|
||||
assert_ne!(a.to_rgba8(), c.to_rgba8());
|
||||
let png = a.encode_png().unwrap();
|
||||
assert_eq!(&png[1..4], b"PNG");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offscreen_items_are_culled_without_changing_pixels() {
|
||||
let on = item(Path::rect(2.0, 2.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK));
|
||||
let off = item(Path::ellipse(500.0, 500.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK));
|
||||
let (a, sa) = render(&list(vec![on.clone(), off]),&view(16, 16)).unwrap();
|
||||
let (b, _) = render(&list(vec![on]),&view(16, 16)).unwrap();
|
||||
assert_eq!(sa.culled, 1);
|
||||
assert_eq!(sa.drawn, 1);
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn band_boundaries_do_not_change_coverage() {
|
||||
// A rectangle with fractional edges spanning three 32-row bands keeps its exact area.
|
||||
let dl = list(vec![item(Path::rect(3.25, 20.5, 40.0, 61.75), Paint::Solid(Rgba::BLACK))]);
|
||||
let (pm, _) = render(&dl, &view(64, 100)).unwrap();
|
||||
assert!((alpha_sum(&pm) - 40.0 * 61.75).abs() < 1e-2, "{}", alpha_sum(&pm));
|
||||
// and a full row inside the shape is fully covered on both sides of a band edge
|
||||
for y in [31, 32] {
|
||||
assert_eq!(pm.pixel(10, y).unwrap()[3], 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_shapes_render_identically_across_runs() {
|
||||
let d = sample::stress(4, 300, 24);
|
||||
let a = render_frame(&d, 5, 0.5).unwrap();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(render_frame(&d, 5, 0.5).unwrap(), a);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_surface_is_refused() {
|
||||
assert!(matches!(Pixmap::new(100_000, 100_000), Err(RenderError::TooLarge(..))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Paint shaders: solid colours and gradients evaluated per pixel through a 256-entry LUT.
|
||||
|
||||
use anicraft_doc::{ColorEffect, GradientStop, Paint, Rgba};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
|
||||
/// Premultiplied RGBA.
|
||||
pub type Premul = [f32; 4];
|
||||
|
||||
pub fn premultiply(c: Rgba) -> Premul {
|
||||
let c = c.sanitized();
|
||||
[c.r * c.a, c.g * c.a, c.b * c.a, c.a]
|
||||
}
|
||||
|
||||
const LUT: usize = 256;
|
||||
|
||||
pub enum Shader {
|
||||
Solid(Premul),
|
||||
Linear { inv: Affine, start: Vec2, dir: Vec2, lut: Box<[Premul; LUT]> },
|
||||
Radial { inv: Affine, center: Vec2, inv_radius: f32, lut: Box<[Premul; LUT]> },
|
||||
}
|
||||
|
||||
fn sample_stops(stops: &[GradientStop], t: f32) -> Rgba {
|
||||
let Some(first) = stops.first() else { return Rgba::TRANSPARENT };
|
||||
if t <= first.offset {
|
||||
return first.color;
|
||||
}
|
||||
for w in stops.windows(2) {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
if t <= b.offset {
|
||||
let span = b.offset - a.offset;
|
||||
let k = if span > 1e-6 { (t - a.offset) / span } else { 1.0 };
|
||||
return a.color.lerp(b.color, k);
|
||||
}
|
||||
}
|
||||
stops.last().map_or(first.color, |s| s.color)
|
||||
}
|
||||
|
||||
fn build_lut(stops: &[GradientStop], fx: &ColorEffect) -> Box<[Premul; LUT]> {
|
||||
let mut sorted: Vec<GradientStop> = stops.iter().copied().filter(|s| s.offset.is_finite()).collect();
|
||||
sorted.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
let mut lut = Box::new([[0.0; 4]; LUT]);
|
||||
for (i, slot) in lut.iter_mut().enumerate() {
|
||||
let t = i as f32 / (LUT - 1) as f32;
|
||||
*slot = premultiply(fx.apply(sample_stops(&sorted, t)));
|
||||
}
|
||||
lut
|
||||
}
|
||||
|
||||
impl Shader {
|
||||
/// `to_pixel` maps the paint's local space to pixels.
|
||||
pub fn new(paint: &Paint, to_pixel: &Affine, fx: &ColorEffect) -> Shader {
|
||||
let inv = to_pixel.inverse();
|
||||
match (paint, inv) {
|
||||
(Paint::Solid(c), _) => Shader::Solid(premultiply(fx.apply(*c))),
|
||||
(Paint::Linear { start, end, stops }, Some(inv)) => {
|
||||
let d = *end - *start;
|
||||
let len2 = d.dot(d);
|
||||
if len2 < 1e-12 {
|
||||
return Shader::Solid(premultiply(fx.apply(stops.last().map_or(Rgba::TRANSPARENT, |s| s.color))));
|
||||
}
|
||||
Shader::Linear { inv, start: *start, dir: d * (1.0 / len2), lut: build_lut(stops, fx) }
|
||||
}
|
||||
(Paint::Radial { center, radius, stops }, Some(inv)) => {
|
||||
if !(radius.is_finite() && *radius > 1e-6) {
|
||||
return Shader::Solid(premultiply(fx.apply(stops.last().map_or(Rgba::TRANSPARENT, |s| s.color))));
|
||||
}
|
||||
Shader::Radial { inv, center: *center, inv_radius: 1.0 / radius, lut: build_lut(stops, fx) }
|
||||
}
|
||||
(p, None) => Shader::Solid(premultiply(fx.apply(p.primary_color()))),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_solid(&self) -> Option<Premul> {
|
||||
match self {
|
||||
Shader::Solid(c) => Some(*c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Colour at pixel centre `(x + 0.5, y + 0.5)`.
|
||||
#[inline]
|
||||
pub fn at(&self, x: i32, y: i32) -> Premul {
|
||||
let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let lookup = |lut: &[Premul; LUT], t: f32| {
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
lut[(t * (LUT - 1) as f32 + 0.5) as usize & (LUT - 1)]
|
||||
};
|
||||
match self {
|
||||
Shader::Solid(c) => *c,
|
||||
Shader::Linear { inv, start, dir, lut } => lookup(lut, (inv.apply(p) - *start).dot(*dir)),
|
||||
Shader::Radial { inv, center, inv_radius, lut } => lookup(lut, (inv.apply(p) - *center).length() * inv_radius),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn linear_gradient_endpoints() {
|
||||
let paint = Paint::Linear {
|
||||
start: Vec2::new(0.0, 0.0),
|
||||
end: Vec2::new(100.0, 0.0),
|
||||
stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }],
|
||||
};
|
||||
let s = Shader::new(&paint, &Affine::IDENTITY, &ColorEffect::default());
|
||||
assert!(s.at(0, 0)[0] < 0.02);
|
||||
assert!(s.at(99, 0)[0] > 0.98);
|
||||
assert!((s.at(49, 0)[0] - 0.5).abs() < 0.02);
|
||||
// gradient follows the transform
|
||||
let s2 = Shader::new(&paint, &Affine::scale(2.0, 1.0), &ColorEffect::default());
|
||||
assert!((s2.at(99, 0)[0] - 0.5).abs() < 0.02);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alpha_effect_premultiplies() {
|
||||
let s = Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorEffect { alpha: 0.5, ..Default::default() });
|
||||
assert_eq!(s.at(0, 0), [0.5, 0.5, 0.5, 0.5]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Signed-area coverage accumulation rasterizer.
|
||||
//!
|
||||
//! Each edge deposits the signed area it sweeps into a per-pixel accumulation buffer; a running
|
||||
//! sum along a row then yields exact analytic coverage (no supersampling). The buffer covers only
|
||||
//! the shape's pixel bounding box. Edges left of the box collapse onto its left edge, which keeps
|
||||
//! the winding of every pixel to their right correct.
|
||||
|
||||
use anicraft_geom::{FillRule, Vec2};
|
||||
|
||||
/// Integer pixel rectangle `[x0, x1) × [y0, y1)`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct IRect {
|
||||
pub x0: i32,
|
||||
pub y0: i32,
|
||||
pub x1: i32,
|
||||
pub y1: i32,
|
||||
}
|
||||
|
||||
impl IRect {
|
||||
pub fn width(&self) -> usize {
|
||||
(self.x1 - self.x0).max(0) as usize
|
||||
}
|
||||
pub fn height(&self) -> usize {
|
||||
(self.y1 - self.y0).max(0) as usize
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.x1 <= self.x0 || self.y1 <= self.y0
|
||||
}
|
||||
pub fn intersect(&self, o: &IRect) -> IRect {
|
||||
IRect { x0: self.x0.max(o.x0), y0: self.y0.max(o.y0), x1: self.x1.min(o.x1), y1: self.y1.min(o.y1) }
|
||||
}
|
||||
/// Smallest rectangle holding both (an empty side is ignored).
|
||||
pub fn union(&self, o: &IRect) -> IRect {
|
||||
if self.is_empty() {
|
||||
return *o;
|
||||
}
|
||||
if o.is_empty() {
|
||||
return *self;
|
||||
}
|
||||
IRect { x0: self.x0.min(o.x0), y0: self.y0.min(o.y0), x1: self.x1.max(o.x1), y1: self.y1.max(o.y1) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Coverage accumulation buffer over a pixel rectangle.
|
||||
pub struct Coverage {
|
||||
pub bounds: IRect,
|
||||
stride: usize,
|
||||
acc: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
pub fn new(bounds: IRect) -> Coverage {
|
||||
let stride = bounds.width() + 2;
|
||||
Coverage { bounds, stride, acc: vec![0.0; stride * bounds.height()] }
|
||||
}
|
||||
|
||||
/// Re-targets the buffer at `bounds`, reusing its allocation (one buffer per render band).
|
||||
pub fn reset(&mut self, bounds: IRect) {
|
||||
self.bounds = bounds;
|
||||
self.stride = bounds.width() + 2;
|
||||
self.acc.clear();
|
||||
self.acc.resize(self.stride * bounds.height(), 0.0);
|
||||
}
|
||||
|
||||
/// Adds one edge, in pixel coordinates of the target surface.
|
||||
pub fn add_line(&mut self, a: Vec2, b: Vec2) {
|
||||
if !(a.is_finite() && b.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let o = Vec2::new(self.bounds.x0 as f32, self.bounds.y0 as f32);
|
||||
let (a, b) = (a - o, b - o);
|
||||
if a.y == b.y {
|
||||
return;
|
||||
}
|
||||
let w = self.bounds.width() as f32;
|
||||
// Split at x = 0 and x = w so every piece lies fully inside or outside [0, w].
|
||||
let mut ts = [0.0f32, 1.0, 1.0, 1.0];
|
||||
let mut n = 1;
|
||||
let dx = b.x - a.x;
|
||||
if dx != 0.0 {
|
||||
for edge in [0.0, w] {
|
||||
let t = (edge - a.x) / dx;
|
||||
if t > 0.0 && t < 1.0 {
|
||||
ts[n] = t;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
ts[n] = 1.0;
|
||||
let (head, _) = ts.split_at_mut(n + 1);
|
||||
head.sort_by(f32::total_cmp);
|
||||
let clamp = |p: Vec2| Vec2::new(p.x.clamp(0.0, w), p.y);
|
||||
for win in head.windows(2) {
|
||||
let (t0, t1) = (win[0], win[1]);
|
||||
if t1 <= t0 {
|
||||
continue;
|
||||
}
|
||||
self.raw_line(clamp(a.lerp(b, t0)), clamp(a.lerp(b, t1)));
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn deposit(&mut self, row: usize, xi: i64, v: f32) {
|
||||
if xi >= 0
|
||||
&& (xi as usize) < self.stride
|
||||
&& let Some(cell) = self.acc.get_mut(row + xi as usize)
|
||||
{
|
||||
*cell += v;
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_line(&mut self, p0: Vec2, p1: Vec2) {
|
||||
if (p0.y - p1.y).abs() < 1e-9 {
|
||||
return;
|
||||
}
|
||||
let (dir, p0, p1) = if p0.y < p1.y { (1.0f32, p0, p1) } else { (-1.0f32, p1, p0) };
|
||||
let h = self.bounds.height();
|
||||
let hf = h as f32;
|
||||
if p1.y <= 0.0 || p0.y >= hf {
|
||||
return;
|
||||
}
|
||||
let dxdy = (p1.x - p0.x) / (p1.y - p0.y);
|
||||
let mut x = p0.x;
|
||||
let ystart = if p0.y < 0.0 {
|
||||
x -= p0.y * dxdy;
|
||||
0
|
||||
} else {
|
||||
p0.y as usize
|
||||
};
|
||||
let yend = (p1.y.ceil() as usize).min(h);
|
||||
for y in ystart..yend {
|
||||
let row = y * self.stride;
|
||||
let dy = ((y + 1) as f32).min(p1.y) - (y as f32).max(p0.y);
|
||||
let xnext = x + dxdy * dy;
|
||||
let d = dy * dir;
|
||||
let (x0, x1) = if x < xnext { (x, xnext) } else { (xnext, x) };
|
||||
let x0floor = x0.floor();
|
||||
let x0i = x0floor as i64;
|
||||
let x1ceil = x1.ceil();
|
||||
let x1i = x1ceil as i64;
|
||||
if x1i <= x0i + 1 {
|
||||
let xmf = 0.5 * (x + xnext) - x0floor;
|
||||
self.deposit(row, x0i, d - d * xmf);
|
||||
self.deposit(row, x0i + 1, d * xmf);
|
||||
} else {
|
||||
let s = 1.0 / (x1 - x0);
|
||||
let x0f = x0 - x0floor;
|
||||
let a0 = 0.5 * s * (1.0 - x0f) * (1.0 - x0f);
|
||||
let x1f = x1 - x1ceil + 1.0;
|
||||
let am = 0.5 * s * x1f * x1f;
|
||||
self.deposit(row, x0i, d * a0);
|
||||
if x1i == x0i + 2 {
|
||||
self.deposit(row, x0i + 1, d * (1.0 - a0 - am));
|
||||
} else {
|
||||
let a1 = s * (1.5 - x0f);
|
||||
self.deposit(row, x0i + 1, d * (a1 - a0));
|
||||
for xi in x0i + 2..x1i - 1 {
|
||||
self.deposit(row, xi, d * s);
|
||||
}
|
||||
let a2 = a1 + (x1i - x0i - 3) as f32 * s;
|
||||
self.deposit(row, x1i - 1, d * (1.0 - a2 - am));
|
||||
}
|
||||
self.deposit(row, x1i, d * am);
|
||||
}
|
||||
x = xnext;
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a closed polygon (the closing edge is implicit).
|
||||
pub fn add_polygon(&mut self, pts: &[Vec2]) {
|
||||
let n = pts.len();
|
||||
if n < 2 {
|
||||
return;
|
||||
}
|
||||
for i in 0..n {
|
||||
let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % n)) else { continue };
|
||||
self.add_line(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves row `y` (relative to the bounds) into coverage values in `out` (len = width).
|
||||
pub fn resolve_row(&self, y: usize, rule: FillRule, out: &mut [f32]) {
|
||||
let start = y * self.stride;
|
||||
let Some(row) = self.acc.get(start..start + self.stride) else {
|
||||
out.fill(0.0);
|
||||
return;
|
||||
};
|
||||
let mut sum = 0.0f32;
|
||||
for (o, a) in out.iter_mut().zip(row) {
|
||||
sum += a;
|
||||
*o = fold(sum, rule);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn fold(winding: f32, rule: FillRule) -> f32 {
|
||||
match rule {
|
||||
FillRule::NonZero => winding.abs().min(1.0),
|
||||
FillRule::EvenOdd => {
|
||||
let t = winding.abs() % 2.0;
|
||||
if t > 1.0 { 2.0 - t } else { t }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn total(c: &Coverage, rule: FillRule) -> f32 {
|
||||
let mut row = vec![0.0; c.bounds.width()];
|
||||
let mut s = 0.0;
|
||||
for y in 0..c.bounds.height() {
|
||||
c.resolve_row(y, rule, &mut row);
|
||||
s += row.iter().sum::<f32>();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(x0: f32, y0: f32, x1: f32, y1: f32) -> Vec<Vec2> {
|
||||
vec![Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_coverage_is_exact() {
|
||||
let mut c = Coverage::new(IRect { x0: 0, y0: 0, x1: 20, y1: 20 });
|
||||
c.add_polygon(&rect(2.25, 3.5, 12.75, 9.0));
|
||||
let area = 10.5 * 5.5;
|
||||
assert!((total(&c, FillRule::NonZero) - area).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_pixel_is_fractional() {
|
||||
let mut c = Coverage::new(IRect { x0: 0, y0: 0, x1: 4, y1: 1 });
|
||||
c.add_polygon(&rect(1.0, 0.0, 2.5, 1.0));
|
||||
let mut row = vec![0.0; 4];
|
||||
c.resolve_row(0, FillRule::NonZero, &mut row);
|
||||
assert!((row[0]).abs() < 1e-5);
|
||||
assert!((row[1] - 1.0).abs() < 1e-5);
|
||||
assert!((row[2] - 0.5).abs() < 1e-5);
|
||||
assert!((row[3]).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_left_of_bounds_keep_winding() {
|
||||
// Rectangle starting far left of the buffer: pixels inside must be fully covered.
|
||||
let mut c = Coverage::new(IRect { x0: 10, y0: 0, x1: 20, y1: 2 });
|
||||
c.add_polygon(&rect(-100.0, 0.0, 15.0, 2.0));
|
||||
let mut row = vec![0.0; 10];
|
||||
c.resolve_row(0, FillRule::NonZero, &mut row);
|
||||
assert!(row[..5].iter().all(|v| (v - 1.0).abs() < 1e-4), "{row:?}");
|
||||
assert!(row[5..].iter().all(|v| v.abs() < 1e-4), "{row:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_hole() {
|
||||
let mut c = Coverage::new(IRect { x0: 0, y0: 0, x1: 10, y1: 10 });
|
||||
c.add_polygon(&rect(0.0, 0.0, 10.0, 10.0));
|
||||
c.add_polygon(&rect(2.0, 2.0, 8.0, 8.0));
|
||||
assert!((total(&c, FillRule::EvenOdd) - 64.0).abs() < 1e-2);
|
||||
assert!((total(&c, FillRule::NonZero) - 100.0).abs() < 1e-2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_edges_ignored() {
|
||||
let mut c = Coverage::new(IRect { x0: 0, y0: 0, x1: 4, y1: 4 });
|
||||
c.add_line(Vec2::new(f32::NAN, 0.0), Vec2::new(1.0, 3.0));
|
||||
c.add_line(Vec2::new(0.0, -1e30), Vec2::new(1e30, 1e30));
|
||||
assert!(total(&c, FillRule::NonZero).is_finite());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Stroker: polylines → positively-wound polygons (segment quads plus round joins and caps).
|
||||
//!
|
||||
//! Every emitted polygon has the same orientation, so overlaps only add winding and the
|
||||
//! non-zero rule gives a seamless union without computing an outline offset.
|
||||
|
||||
use anicraft_geom::{Polyline, Vec2};
|
||||
|
||||
fn signed_area(p: &[Vec2]) -> f32 {
|
||||
let n = p.len();
|
||||
let mut a = 0.0;
|
||||
for i in 0..n {
|
||||
let (Some(u), Some(v)) = (p.get(i), p.get((i + 1) % n)) else { continue };
|
||||
a += u.cross(*v);
|
||||
}
|
||||
a * 0.5
|
||||
}
|
||||
|
||||
fn oriented(mut poly: Vec<Vec2>) -> Vec<Vec2> {
|
||||
if signed_area(&poly) < 0.0 {
|
||||
poly.reverse();
|
||||
}
|
||||
poly
|
||||
}
|
||||
|
||||
/// Polygon approximating a circle within ~0.1 px.
|
||||
fn disc(c: Vec2, r: f32) -> Vec<Vec2> {
|
||||
let tol = 0.1f32;
|
||||
let n = if r > tol { (std::f32::consts::PI / (1.0 - tol / r).clamp(-1.0, 1.0).acos()).ceil() as usize } else { 6 };
|
||||
let n = n.clamp(6, 96);
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let a = i as f32 * std::f32::consts::TAU / n as f32;
|
||||
Vec2::new(c.x + r * a.cos(), c.y + r * a.sin())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Polygons covering the stroke of `lines` with half-width `hw` (pixels).
|
||||
pub fn stroke_polygons(lines: &[Polyline], hw: f32) -> Vec<Vec<Vec2>> {
|
||||
let mut out = Vec::new();
|
||||
if !(hw.is_finite() && hw > 0.0) {
|
||||
return out;
|
||||
}
|
||||
for pl in lines {
|
||||
let pts = &pl.points;
|
||||
let n = pts.len();
|
||||
if n < 2 {
|
||||
continue;
|
||||
}
|
||||
let segs = if pl.closed { n } else { n - 1 };
|
||||
for i in 0..segs {
|
||||
let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % n)) else { continue };
|
||||
let d = b - a;
|
||||
if d.length() < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let nrm = d.normalized().perp() * hw;
|
||||
out.push(oriented(vec![a + nrm, b + nrm, b - nrm, a - nrm]));
|
||||
}
|
||||
// Round joins at interior vertices (all vertices when closed) and round caps at ends.
|
||||
for (i, &p) in pts.iter().enumerate() {
|
||||
let interior = pl.closed || (i > 0 && i + 1 < n);
|
||||
let is_end = !pl.closed && (i == 0 || i + 1 == n);
|
||||
if interior {
|
||||
// Skip joins on nearly straight runs (common on flattened curves): the quads
|
||||
// already overlap seamlessly there.
|
||||
let prev = pts.get(if i == 0 { n - 1 } else { i - 1 });
|
||||
let next = pts.get((i + 1) % n);
|
||||
if let (Some(&a), Some(&b)) = (prev, next) {
|
||||
let (u, v) = ((p - a).normalized(), (b - p).normalized());
|
||||
// the uncovered outer wedge is about hw · sin(turn) wide
|
||||
if u.dot(v) > 0.0 && u.cross(v).abs() * hw < 0.05 {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if interior || is_end {
|
||||
out.push(oriented(disc(p, hw)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn all_polygons_positive() {
|
||||
let pl = Polyline { points: vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0)], closed: false };
|
||||
let polys = stroke_polygons(&[pl], 2.0);
|
||||
assert!(polys.len() >= 4);
|
||||
assert!(polys.iter().all(|p| signed_area(p) > 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_inputs() {
|
||||
assert!(stroke_polygons(&[], 1.0).is_empty());
|
||||
let pl = Polyline { points: vec![Vec2::ZERO, Vec2::ZERO], closed: false };
|
||||
assert!(stroke_polygons(std::slice::from_ref(&pl), f32::NAN).is_empty());
|
||||
// zero-length segment still yields caps, no NaN
|
||||
let polys = stroke_polygons(&[pl], 1.0);
|
||||
assert!(polys.iter().flatten().all(|p| p.is_finite()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "anicraft-xfl"
|
||||
description = "AniCraft XFL/FLA import: Animate documents (DOMDocument.xml, library symbols, shape edges) into the AniCraft document model"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anicraft-geom.workspace = true
|
||||
anicraft-doc.workspace = true
|
||||
# Inflate for .fla (zip) archives; already in the tree through png (MIT OR Zlib OR Apache-2.0).
|
||||
miniz_oxide = "0.8"
|
||||
thiserror.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,231 @@
|
||||
//! XFL shape edges → AniCraft paths.
|
||||
//!
|
||||
//! A `DOMShape` stores its outline as `<Edge>` elements. Each carries an `edges` string of
|
||||
//! drawing commands in twips (1/20 px): `!x y` moves, `|x y` or `/x y` draws a line, `[cx cy x y`
|
||||
//! or `]cx cy x y` draws a quadratic curve; `Sn` marks selection state and is skipped. Numbers
|
||||
//! are decimal, or `#` hex fixed point (signed 24.8). An edge names the fill style on its
|
||||
//! left (`fillStyle0`) and right (`fillStyle1`) and an optional stroke style.
|
||||
//!
|
||||
//! Fill regions are rebuilt per fill style: its right-side edges as drawn, its left-side edges
|
||||
//! reversed, then chained end to start into closed loops. Strokes are the stroked edges in
|
||||
//! drawing order. Written from the public description of the format; no Animate code involved.
|
||||
|
||||
use anicraft_geom::{Path, Vec2};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// One segment in pixels: a line (`ctrl` = None) or a quadratic curve.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Seg {
|
||||
pub from: Vec2,
|
||||
pub ctrl: Option<Vec2>,
|
||||
pub to: Vec2,
|
||||
}
|
||||
|
||||
impl Seg {
|
||||
fn reversed(self) -> Seg {
|
||||
Seg { from: self.to, ctrl: self.ctrl, to: self.from }
|
||||
}
|
||||
}
|
||||
|
||||
/// An `<Edge>`: its fill styles (left, right), stroke style and segments.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Edge {
|
||||
pub fill_left: u32,
|
||||
pub fill_right: u32,
|
||||
pub stroke: u32,
|
||||
pub segs: Vec<Seg>,
|
||||
}
|
||||
|
||||
const TWIPS: f32 = 20.0;
|
||||
const MAX_SEGS: usize = 2_000_000;
|
||||
|
||||
fn number(s: &[u8], i: &mut usize) -> Option<f32> {
|
||||
while s.get(*i).is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
*i += 1;
|
||||
}
|
||||
let start = *i;
|
||||
if s.get(*i) == Some(&b'#') {
|
||||
*i += 1;
|
||||
let h0 = *i;
|
||||
while s.get(*i).is_some_and(u8::is_ascii_hexdigit) {
|
||||
*i += 1;
|
||||
}
|
||||
let int = std::str::from_utf8(s.get(h0..*i)?).ok()?;
|
||||
let mut frac = 0u32;
|
||||
if s.get(*i) == Some(&b'.') {
|
||||
*i += 1;
|
||||
let f0 = *i;
|
||||
while s.get(*i).is_some_and(u8::is_ascii_hexdigit) && *i - f0 < 2 {
|
||||
*i += 1;
|
||||
}
|
||||
let f = std::str::from_utf8(s.get(f0..*i)?).ok()?;
|
||||
// One digit means sixteenths of 256ths: "#A.8" = 10.5.
|
||||
frac = u32::from_str_radix(f, 16).ok()? << (if f.len() == 1 { 4 } else { 0 });
|
||||
}
|
||||
let v = u32::from_str_radix(if int.is_empty() { "0" } else { int }, 16).ok()?;
|
||||
let fixed = (v.wrapping_shl(8) | frac) as i32;
|
||||
return Some(fixed as f32 / 256.0);
|
||||
}
|
||||
if matches!(s.get(*i), Some(b'-' | b'+')) {
|
||||
*i += 1;
|
||||
}
|
||||
while s.get(*i).is_some_and(|c| c.is_ascii_digit() || *c == b'.' || *c == b'e' || *c == b'E') {
|
||||
*i += 1;
|
||||
}
|
||||
std::str::from_utf8(s.get(start..*i)?).ok()?.parse::<f32>().ok().filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Decodes an `edges` attribute into segments (pixels). Stops quietly at anything it can't
|
||||
/// read, keeping what came before.
|
||||
pub fn parse(s: &str) -> Vec<Seg> {
|
||||
let b = s.as_bytes();
|
||||
let mut i = 0;
|
||||
let mut cur = Vec2::ZERO;
|
||||
let mut out = Vec::new();
|
||||
let pt = |b: &[u8], i: &mut usize| -> Option<Vec2> { Some(Vec2::new(number(b, i)? / TWIPS, number(b, i)? / TWIPS)) };
|
||||
while let Some(&c) = b.get(i) {
|
||||
i += 1;
|
||||
match c {
|
||||
b'!' => match pt(b, &mut i) {
|
||||
Some(p) => cur = p,
|
||||
None => break,
|
||||
},
|
||||
b'|' | b'/' => match pt(b, &mut i) {
|
||||
Some(p) => {
|
||||
out.push(Seg { from: cur, ctrl: None, to: p });
|
||||
cur = p;
|
||||
}
|
||||
None => break,
|
||||
},
|
||||
b'[' | b']' => match (pt(b, &mut i), pt(b, &mut i)) {
|
||||
(Some(q), Some(p)) => {
|
||||
out.push(Seg { from: cur, ctrl: Some(q), to: p });
|
||||
cur = p;
|
||||
}
|
||||
_ => break,
|
||||
},
|
||||
b'S' => {
|
||||
while b.get(i).is_some_and(u8::is_ascii_digit) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
c if c.is_ascii_whitespace() => {}
|
||||
_ => break,
|
||||
}
|
||||
if out.len() >= MAX_SEGS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Hash key for an end point (to 1/100 px, which absorbs the format's rounding).
|
||||
fn key(p: Vec2) -> (i64, i64) {
|
||||
((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64)
|
||||
}
|
||||
|
||||
fn push_seg(path: &mut Path, s: &Seg) {
|
||||
match s.ctrl {
|
||||
Some(q) => path.quad_to(q, s.to),
|
||||
None => path.line_to(s.to),
|
||||
};
|
||||
}
|
||||
|
||||
/// The region of fill style `style`, as closed loops.
|
||||
pub fn fill_path(edges: &[Edge], style: u32) -> Path {
|
||||
let mut segs: Vec<Seg> = Vec::new();
|
||||
for e in edges {
|
||||
if e.fill_right == style {
|
||||
segs.extend(e.segs.iter().copied());
|
||||
}
|
||||
if e.fill_left == style {
|
||||
segs.extend(e.segs.iter().rev().map(|s| s.reversed()));
|
||||
}
|
||||
}
|
||||
let mut by_start: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
// Zero-length segments carry no area and would confuse the chaining.
|
||||
if key(s.from) != key(s.to) {
|
||||
by_start.entry(key(s.from)).or_default().push(i);
|
||||
}
|
||||
}
|
||||
let mut used = vec![false; segs.len()];
|
||||
let mut path = Path::new();
|
||||
for first in 0..segs.len() {
|
||||
if used.get(first).copied().unwrap_or(true) || segs.get(first).is_some_and(|s| key(s.from) == key(s.to)) {
|
||||
continue;
|
||||
}
|
||||
let Some(&start) = segs.get(first) else { continue };
|
||||
path.move_to(start.from);
|
||||
let mut at = first;
|
||||
while let Some(s) = segs.get(at).copied() {
|
||||
if let Some(u) = used.get_mut(at) {
|
||||
*u = true;
|
||||
}
|
||||
push_seg(&mut path, &s);
|
||||
if key(s.to) == key(start.from) {
|
||||
break;
|
||||
}
|
||||
let next = by_start.get(&key(s.to)).and_then(|v| v.iter().copied().find(|&j| !used.get(j).copied().unwrap_or(true)));
|
||||
match next {
|
||||
Some(j) => at = j,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
path.close();
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// The stroked edges of stroke style `style`, in drawing order.
|
||||
pub fn stroke_path(edges: &[Edge], style: u32) -> Path {
|
||||
let mut path = Path::new();
|
||||
let mut last: Option<Vec2> = None;
|
||||
for e in edges.iter().filter(|e| e.stroke == style) {
|
||||
for s in &e.segs {
|
||||
if last.is_none_or(|l| key(l) != key(s.from)) {
|
||||
path.move_to(s.from);
|
||||
}
|
||||
push_seg(&mut path, s);
|
||||
last = Some(s.to);
|
||||
}
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn decodes_commands_and_numbers() {
|
||||
let s = parse("!0 0|200 0[400 0 400 200S2/0 200!#A.8 -20");
|
||||
assert_eq!(s.len(), 3);
|
||||
assert_eq!(s[0].to, Vec2::new(10.0, 0.0), "twips to pixels");
|
||||
assert_eq!(s[1].ctrl, Some(Vec2::new(20.0, 0.0)));
|
||||
assert_eq!(s[2], Seg { from: Vec2::new(20.0, 10.0), ctrl: None, to: Vec2::new(0.0, 10.0) });
|
||||
// Hex fixed point: #A.8 = 10.5 twips; a negative two's-complement value.
|
||||
let mut i = 0;
|
||||
assert_eq!(number(b"#A.8", &mut i), Some(10.5));
|
||||
let mut i = 0;
|
||||
assert_eq!(number(b"#FFFFFF.80", &mut i), Some(-0.5));
|
||||
assert!(parse("!1 2|x").is_empty(), "stops at garbage, never panics");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_square_split_into_edges_with_fills_on_either_side() {
|
||||
// Top and right drawn clockwise with the fill on the right; bottom and left drawn the
|
||||
// other way with the fill on the left. Both describe the same square.
|
||||
let e = |l, r, d: &str| Edge { fill_left: l, fill_right: r, stroke: 1, segs: parse(d) };
|
||||
let edges = vec![e(0, 1, "!0 0|200 0|200 200"), e(1, 0, "!0 0|0 200|200 200")];
|
||||
let p = fill_path(&edges, 1);
|
||||
let lines = p.flatten(&anicraft_geom::Affine::IDENTITY, 0.1);
|
||||
assert_eq!(lines.len(), 1, "one closed loop");
|
||||
assert!(lines[0].closed);
|
||||
assert!(p.contains(Vec2::new(5.0, 5.0), &anicraft_geom::Affine::IDENTITY, anicraft_geom::FillRule::EvenOdd));
|
||||
assert!(!p.contains(Vec2::new(15.0, 5.0), &anicraft_geom::Affine::IDENTITY, anicraft_geom::FillRule::EvenOdd));
|
||||
let st = stroke_path(&edges, 1);
|
||||
assert_eq!(st.anchors().len(), 6, "two runs of two segments each, plus their starts");
|
||||
assert!(fill_path(&edges, 7).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
//! XFL document → AniCraft document.
|
||||
//!
|
||||
//! What maps (first slice of M4): stage size, frame rate and colour; the first scene's
|
||||
//! layers (name, colour, visibility, lock, outline; guide layers; folders flattened); frames
|
||||
//! and keyframes with durations, labels and classic tweens with their ease; shapes (solid,
|
||||
//! linear and radial fills, solid strokes), groups (flattened), rectangle and oval
|
||||
//! primitives; symbol instances with their matrix, alpha and tint, loop mode and first frame;
|
||||
//! library symbols (graphic, movie clip, button) with their own timelines, nested to any
|
||||
//! depth. Everything else (bitmaps, text, sound, masks, motion tweens with property curves,
|
||||
//! filters) is counted in the report instead of guessed at.
|
||||
|
||||
use crate::edges::{self, Edge};
|
||||
use crate::xml::{self, Element as X};
|
||||
use anicraft_doc::{
|
||||
ColorEffect, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId,
|
||||
SymbolKind, Timeline, Tween,
|
||||
};
|
||||
use anicraft_geom::{Affine, FillRule, Path, Vec2};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum XflError {
|
||||
#[error("{0}")]
|
||||
Xml(#[from] xml::XmlError),
|
||||
#[error("{0}")]
|
||||
Zip(#[from] crate::zip::ZipError),
|
||||
#[error("I/O: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("this isn't an Animate document: {0}")]
|
||||
NotXfl(String),
|
||||
}
|
||||
|
||||
/// What the import couldn't bring across, by kind ("3 bitmaps").
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Report {
|
||||
pub skipped: BTreeMap<String, usize>,
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
fn skip(&mut self, what: &str) {
|
||||
*self.skipped.entry(what.to_string()).or_default() += 1;
|
||||
}
|
||||
/// One line for a status bar: "Imported. Not yet supported: 2 bitmaps, 1 text field."
|
||||
pub fn summary(&self) -> String {
|
||||
if self.skipped.is_empty() && self.notes.is_empty() {
|
||||
return "Imported everything in the file.".into();
|
||||
}
|
||||
let mut parts: Vec<String> = self.skipped.iter().map(|(k, n)| format!("{n} {k}")).collect();
|
||||
parts.extend(self.notes.iter().cloned());
|
||||
format!("Imported. Not yet supported: {}.", parts.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads files of the XFL package by their path inside it (`DOMDocument.xml`, `LIBRARY/x.xml`).
|
||||
pub type Reader<'a> = dyn Fn(&str) -> Result<Option<Vec<u8>>, XflError> + 'a;
|
||||
|
||||
const MAX_SYMBOLS: usize = 20_000;
|
||||
const MAX_LAYERS: usize = 5_000;
|
||||
const MAX_FRAME: u32 = 100_000;
|
||||
|
||||
struct Builder<'a> {
|
||||
doc: Document,
|
||||
read: &'a Reader<'a>,
|
||||
/// Library item name → symbol id (allocated before timelines are built, so instances can
|
||||
/// refer to any symbol).
|
||||
ids: HashMap<String, SymbolId>,
|
||||
/// Parsed symbol files waiting to be built.
|
||||
pending: Vec<(SymbolId, String, SymbolKind, X)>,
|
||||
report: Report,
|
||||
}
|
||||
|
||||
fn color(el: &X, key: &str, alpha_key: &str) -> Rgba {
|
||||
let rgb = el.attr(key).and_then(|c| u32::from_str_radix(c.trim().trim_start_matches('#'), 16).ok()).unwrap_or(0);
|
||||
Rgba::hex(rgb).with_alpha(el.f32(alpha_key).unwrap_or(1.0).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
fn matrix(el: &X) -> Affine {
|
||||
let Some(m) = el.child("matrix").and_then(|m| m.child("Matrix")) else { return Affine::IDENTITY };
|
||||
let a = Affine { m: [m.f32("a").unwrap_or(1.0), m.f32("b").unwrap_or(0.0), m.f32("c").unwrap_or(0.0), m.f32("d").unwrap_or(1.0), m.f32("tx").unwrap_or(0.0), m.f32("ty").unwrap_or(0.0)] };
|
||||
if a.is_finite() { a } else { Affine::IDENTITY }
|
||||
}
|
||||
|
||||
/// Half the side of the square XFL gradients are defined on, in pixels (16384 twips / 20).
|
||||
const GRADIENT_HALF: f32 = 819.2;
|
||||
|
||||
/// A fill definition (`SolidColor`, `LinearGradient`, `RadialGradient`) as a paint.
|
||||
fn paint(def: &X, report: &mut Report) -> Option<Paint> {
|
||||
match def.name.as_str() {
|
||||
"SolidColor" => Some(Paint::Solid(color(def, "color", "alpha"))),
|
||||
"LinearGradient" | "RadialGradient" => {
|
||||
let m = matrix(def);
|
||||
let stops: Vec<GradientStop> = def.children.iter().filter(|c| c.name == "GradientEntry").map(|g| GradientStop { offset: g.f32("ratio").unwrap_or(0.0).clamp(0.0, 1.0), color: color(g, "color", "alpha") }).collect();
|
||||
if stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(if def.name == "LinearGradient" {
|
||||
Paint::Linear { start: m.apply(Vec2::new(-GRADIENT_HALF, 0.0)), end: m.apply(Vec2::new(GRADIENT_HALF, 0.0)), stops }
|
||||
} else {
|
||||
let c = m.apply(Vec2::ZERO);
|
||||
let r = (m.apply_vector(Vec2::new(GRADIENT_HALF, 0.0)).length() + m.apply_vector(Vec2::new(0.0, GRADIENT_HALF)).length()) * 0.5;
|
||||
Paint::Radial { center: c, radius: r, stops }
|
||||
})
|
||||
}
|
||||
"BitmapFill" => {
|
||||
report.skip("bitmap fills");
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke definition (`SolidStroke` and friends) as a stroke: weight and its fill colour.
|
||||
fn stroke(def: &X, report: &mut Report) -> Option<Stroke> {
|
||||
if !matches!(def.name.as_str(), "SolidStroke" | "DashedStroke" | "DottedStroke" | "RaggedStroke" | "StippleStroke" | "HatchedStroke") {
|
||||
return None;
|
||||
}
|
||||
if def.name != "SolidStroke" {
|
||||
report.skip("stroke styles drawn as solid");
|
||||
}
|
||||
let width = def.f32("weight").unwrap_or(1.0).clamp(0.05, 1000.0);
|
||||
let fill = def.child("fill").and_then(|f| f.children.first());
|
||||
let c = fill.map_or(Rgba::BLACK, |f| if f.name == "SolidColor" { color(f, "color", "alpha") } else { paint(f, report).map_or(Rgba::BLACK, |p| p.primary_color()) });
|
||||
Some(Stroke { color: c, width })
|
||||
}
|
||||
|
||||
impl<'a> Builder<'a> {
|
||||
fn element(&mut self, kind: ElementKind, transform: Affine, color: ColorEffect) -> Arc<Element> {
|
||||
Arc::new(Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform, color, kind })
|
||||
}
|
||||
|
||||
/// Shapes for one `DOMShape`: a fill-only shape per fill style (bottom), then a stroke-only
|
||||
/// shape per stroke style, as Animate draws them.
|
||||
fn shape(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
|
||||
let m = parent.mul(&matrix(el));
|
||||
let fills: Vec<(u32, Option<Paint>)> = el.list("fills").iter().map(|f| (f.u32("index").unwrap_or(0), f.children.first().and_then(|d| paint(d, &mut self.report)))).collect();
|
||||
let strokes: Vec<(u32, Option<Stroke>)> = el.list("strokes").iter().map(|s| (s.u32("index").unwrap_or(0), s.children.first().and_then(|d| stroke(d, &mut self.report)))).collect();
|
||||
let edges: Vec<Edge> = el
|
||||
.list("edges")
|
||||
.iter()
|
||||
.filter(|e| e.name == "Edge")
|
||||
.map(|e| Edge { fill_left: e.u32("fillStyle0").unwrap_or(0), fill_right: e.u32("fillStyle1").unwrap_or(0), stroke: e.u32("strokeStyle").unwrap_or(0), segs: e.attr("edges").map(edges::parse).unwrap_or_default() })
|
||||
.collect();
|
||||
for (index, p) in fills {
|
||||
let (Some(p), true) = (p, index > 0) else { continue };
|
||||
let path = edges::fill_path(&edges, index);
|
||||
if !path.is_empty() {
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd }), m, ColorEffect::default()));
|
||||
}
|
||||
}
|
||||
for (index, s) in strokes {
|
||||
let (Some(s), true) = (s, index > 0) else { continue };
|
||||
let path = edges::stroke_path(&edges, index);
|
||||
if !path.is_empty() {
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero }), m, ColorEffect::default()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rectangle and oval primitives.
|
||||
fn primitive(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
|
||||
let (x, y) = (el.f32("x").unwrap_or(0.0), el.f32("y").unwrap_or(0.0));
|
||||
let (w, h) = (el.f32("objectWidth").unwrap_or(0.0), el.f32("objectHeight").unwrap_or(0.0));
|
||||
if !(w > 0.0 && h > 0.0) {
|
||||
return;
|
||||
}
|
||||
let path = if el.name == "DOMOvalObject" { Path::ellipse(x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0) } else { Path::rounded_rect(x, y, w, h, el.f32("topLeftRadius").unwrap_or(0.0).max(0.0)) };
|
||||
let fill = el.child("fill").and_then(|f| f.children.first()).and_then(|d| paint(d, &mut self.report));
|
||||
let stroke = el.child("stroke").and_then(|s| s.children.first()).and_then(|d| stroke(d, &mut self.report));
|
||||
if fill.is_some() || stroke.is_some() {
|
||||
let m = parent.mul(&matrix(el));
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill, stroke, fill_rule: FillRule::NonZero }), m, ColorEffect::default()));
|
||||
}
|
||||
}
|
||||
|
||||
fn instance(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
|
||||
let Some(&symbol) = el.attr("libraryItemName").and_then(|n| self.ids.get(n)) else {
|
||||
self.report.skip("instances of missing symbols");
|
||||
return;
|
||||
};
|
||||
let loop_mode = match el.attr("loop") {
|
||||
Some("play once") => LoopMode::PlayOnce,
|
||||
Some("single frame") => LoopMode::SingleFrame,
|
||||
_ => LoopMode::Loop,
|
||||
};
|
||||
let first_frame = el.u32("firstFrame").unwrap_or(0).min(MAX_FRAME);
|
||||
let mut fx = ColorEffect::default();
|
||||
if let Some(c) = el.child("color").and_then(|c| c.child("Color")) {
|
||||
fx.alpha = c.f32("alphaMultiplier").unwrap_or(1.0).clamp(0.0, 1.0);
|
||||
if let Some(t) = c.f32("tintMultiplier") {
|
||||
fx.tint = color(c, "tintColor", "__none");
|
||||
fx.tint_amount = t.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
let m = parent.mul(&matrix(el));
|
||||
out.push(self.element(ElementKind::Symbol { symbol, loop_mode, first_frame }, m, fx));
|
||||
}
|
||||
|
||||
fn elements(&mut self, list: &[X], parent: &Affine, out: &mut Vec<Arc<Element>>, depth: usize) {
|
||||
if depth > 64 {
|
||||
return;
|
||||
}
|
||||
for el in list {
|
||||
match el.name.as_str() {
|
||||
"DOMShape" => self.shape(el, parent, out),
|
||||
"DOMGroup" => {
|
||||
let m = parent.mul(&matrix(el));
|
||||
self.elements(el.list("members"), &m, out, depth + 1);
|
||||
}
|
||||
"DOMSymbolInstance" => self.instance(el, parent, out),
|
||||
"DOMRectangleObject" | "DOMOvalObject" => self.primitive(el, parent, out),
|
||||
"DOMBitmapInstance" => self.report.skip("bitmaps"),
|
||||
"DOMStaticText" | "DOMDynamicText" | "DOMInputText" => self.report.skip("text fields"),
|
||||
"DOMVideoInstance" => self.report.skip("videos"),
|
||||
_ => self.report.skip("other elements"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn timeline(&mut self, tl: &X) -> Timeline {
|
||||
let mut layers = Vec::new();
|
||||
// Mask layers by their position in the file's layer list (`parentLayerIndex` points at
|
||||
// a layer's folder or mask; folders are flattened away).
|
||||
let mut masks: Vec<Option<LayerId>> = Vec::new();
|
||||
for l in tl.list("layers").iter().filter(|l| l.name == "DOMLayer").take(MAX_LAYERS) {
|
||||
masks.push(None);
|
||||
let kind = match l.attr("layerType") {
|
||||
Some("folder") => continue,
|
||||
Some("guide") => LayerKind::Guide,
|
||||
Some("mask") => LayerKind::Mask,
|
||||
_ => LayerKind::Normal,
|
||||
};
|
||||
let id = LayerId(self.doc.alloc_id());
|
||||
let mut layer = Layer::new(id, l.attr("name").unwrap_or("Layer"));
|
||||
layer.kind = kind;
|
||||
if kind == LayerKind::Mask
|
||||
&& let Some(slot) = masks.last_mut()
|
||||
{
|
||||
*slot = Some(id);
|
||||
}
|
||||
if kind == LayerKind::Normal {
|
||||
layer.parent = l.u32("parentLayerIndex").and_then(|i| masks.get(i as usize).copied().flatten());
|
||||
}
|
||||
layer.visible = l.bool("visible").unwrap_or(true);
|
||||
layer.locked = l.bool("locked").unwrap_or(false);
|
||||
layer.outline = l.bool("outline").unwrap_or(false);
|
||||
layer.color = color(l, "color", "__none");
|
||||
let mut keys = Vec::new();
|
||||
for f in l.list("frames").iter().filter(|f| f.name == "DOMFrame") {
|
||||
let start = f.u32("index").unwrap_or(0).min(MAX_FRAME);
|
||||
let duration = f.u32("duration").unwrap_or(1).clamp(1, MAX_FRAME);
|
||||
let mut k = Keyframe::new(start, duration);
|
||||
k.label = f.attr("name").unwrap_or("").chars().take(256).collect();
|
||||
match f.attr("tweenType") {
|
||||
Some("motion") => {
|
||||
let acc = f.f32("acceleration").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
k.tween = Some(Tween { easing: if acc == 0.0 { Easing::Linear } else { Easing::Classic(acc) } });
|
||||
}
|
||||
Some("motion object") => self.report.skip("motion tweens (kept as keyframes)"),
|
||||
Some("shape") => self.report.skip("shape tweens (kept as keyframes)"),
|
||||
_ => {}
|
||||
}
|
||||
let mut els = Vec::new();
|
||||
self.elements(f.list("elements"), &Affine::IDENTITY, &mut els, 0);
|
||||
k.elements = els;
|
||||
keys.push(Arc::new(k));
|
||||
}
|
||||
if !keys.is_empty() {
|
||||
layer.keyframes = keys;
|
||||
}
|
||||
layer.normalize();
|
||||
layers.push(Arc::new(layer));
|
||||
}
|
||||
if layers.is_empty() {
|
||||
layers.push(Arc::new(Layer::new(LayerId(self.doc.alloc_id()), "Layer 1")));
|
||||
}
|
||||
let mut tl = Timeline { layers };
|
||||
// Links that do not form an unbroken run under their mask are dropped.
|
||||
tl.repair_masks();
|
||||
tl
|
||||
}
|
||||
|
||||
/// Allocates ids for every symbol the document lists, parsing their files.
|
||||
fn register_symbols(&mut self, root: &X) -> Result<(), XflError> {
|
||||
let mut seen = HashSet::new();
|
||||
for inc in root.list("symbols").iter().filter(|i| i.name == "Include").take(MAX_SYMBOLS) {
|
||||
let Some(href) = inc.attr("href") else { continue };
|
||||
if !seen.insert(href.to_string()) {
|
||||
continue;
|
||||
}
|
||||
let Some(bytes) = (self.read)(&format!("LIBRARY/{href}"))? else {
|
||||
self.report.skip("missing library files");
|
||||
continue;
|
||||
};
|
||||
let item = xml::parse(&bytes)?;
|
||||
if item.name != "DOMSymbolItem" {
|
||||
continue;
|
||||
}
|
||||
let name = item.attr("name").map(str::to_string).unwrap_or_else(|| href.trim_end_matches(".xml").to_string());
|
||||
let kind = match item.attr("symbolType") {
|
||||
Some("movie clip") => SymbolKind::MovieClip,
|
||||
Some("button") => SymbolKind::Button,
|
||||
_ => SymbolKind::Graphic,
|
||||
};
|
||||
let id = SymbolId(self.doc.alloc_id());
|
||||
self.ids.insert(name.clone(), id);
|
||||
self.pending.push((id, name, kind, item));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_symbols(&mut self) {
|
||||
for (id, name, kind, item) in std::mem::take(&mut self.pending) {
|
||||
let timeline = match item.child("timeline").and_then(|t| t.child("DOMTimeline")) {
|
||||
Some(tl) => self.timeline(tl),
|
||||
None => Timeline { layers: vec![Arc::new(Layer::new(LayerId(self.doc.alloc_id()), "Layer 1"))] },
|
||||
};
|
||||
let short = name.rsplit('/').next().unwrap_or(&name).to_string();
|
||||
self.doc.library.push(Arc::new(Symbol { id, name: short, kind, timeline }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Imports an XFL package through `read` (paths inside the package).
|
||||
pub fn import_with(read: &Reader<'_>) -> Result<(Document, Report), XflError> {
|
||||
let bytes = read("DOMDocument.xml")?.ok_or_else(|| XflError::NotXfl("no DOMDocument.xml".into()))?;
|
||||
let root = xml::parse(&bytes)?;
|
||||
if root.name != "DOMDocument" {
|
||||
return Err(XflError::NotXfl(format!("the root element is <{}>", root.name)));
|
||||
}
|
||||
let mut b = Builder { doc: Document::default(), read, ids: HashMap::new(), pending: Vec::new(), report: Report::default() };
|
||||
b.doc.library.clear();
|
||||
b.doc.timeline.layers.clear();
|
||||
b.doc.stage = Stage {
|
||||
width: root.f32("width").unwrap_or(550.0).clamp(1.0, 8192.0) as u32,
|
||||
height: root.f32("height").unwrap_or(400.0).clamp(1.0, 8192.0) as u32,
|
||||
fps: root.f32("frameRate").unwrap_or(24.0).clamp(1.0, 120.0),
|
||||
background: color(&root, "backgroundColor", "__none"),
|
||||
};
|
||||
b.register_symbols(&root)?;
|
||||
b.build_symbols();
|
||||
let scenes: Vec<&X> = root.list("timelines").iter().filter(|t| t.name == "DOMTimeline").collect();
|
||||
if scenes.len() > 1 {
|
||||
b.report.notes.push(format!("scenes after the first ({} more)", scenes.len() - 1));
|
||||
}
|
||||
match scenes.first() {
|
||||
Some(tl) => b.doc.timeline = b.timeline(tl),
|
||||
None => b.doc.timeline = Timeline { layers: vec![Arc::new(Layer::new(LayerId(b.doc.alloc_id()), "Layer 1"))] },
|
||||
}
|
||||
Ok((b.doc, b.report))
|
||||
}
|
||||
|
||||
/// Imports from disk: an XFL folder, its `.xfl` file, or a `.fla` archive.
|
||||
pub fn import_path(path: &std::path::Path) -> Result<(Document, Report), XflError> {
|
||||
let meta = std::fs::metadata(path)?;
|
||||
let is_fla = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("fla"));
|
||||
if meta.is_file() && is_fla {
|
||||
if meta.len() as usize > crate::zip::MAX_ENTRY * 4 {
|
||||
return Err(XflError::NotXfl("the file is too large".into()));
|
||||
}
|
||||
let data = std::fs::read(path)?;
|
||||
let archive = crate::zip::Archive::open(&data)?;
|
||||
let read = |p: &str| -> Result<Option<Vec<u8>>, XflError> { Ok(archive.read(p)?) };
|
||||
return import_with(&read);
|
||||
}
|
||||
let dir = if meta.is_dir() { path.to_path_buf() } else { path.parent().map(std::path::Path::to_path_buf).unwrap_or_default() };
|
||||
let read = |p: &str| -> Result<Option<Vec<u8>>, XflError> {
|
||||
// Only plain relative paths inside the package.
|
||||
if p.split('/').any(|c| c == ".." || c.is_empty()) || p.contains(':') {
|
||||
return Ok(None);
|
||||
}
|
||||
let full = dir.join(p);
|
||||
match std::fs::read(&full) {
|
||||
Ok(b) if b.len() <= xml::MAX_INPUT => Ok(Some(b)),
|
||||
Ok(_) => Err(XflError::NotXfl(format!("{p} is too large"))),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
};
|
||||
import_with(&read)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! AniCraft XFL import (between `doc` and `engine`): opens Animate documents, as an XFL folder
|
||||
//! or a `.fla` archive, into the AniCraft document model.
|
||||
//!
|
||||
//! Clean room: written from the publicly documented structure of XFL (an XML package:
|
||||
//! `DOMDocument.xml`, `LIBRARY/*.xml`) and the published ZIP format. No Animate code, and no
|
||||
//! third-party converter code. The test corpus is self-authored.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod edges;
|
||||
pub mod import;
|
||||
pub mod xml;
|
||||
pub mod zip;
|
||||
|
||||
pub use import::{Report, XflError, import_path, import_with};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Import tests on a small, self-authored XFL package.
|
||||
|
||||
use crate::import::{XflError, import_with};
|
||||
use anicraft_doc::{ElementKind, LayerKind, LoopMode, Paint, Rgba, SymbolKind, evaluate};
|
||||
use std::collections::HashMap;
|
||||
|
||||
const DOC: &str = r##"<DOMDocument xmlns="http://ns.adobe.com/xfl/2008/" width="640" height="360" frameRate="30" backgroundColor="#336699">
|
||||
<symbols><Include href="Characters/Ball.xml"/><Include href="Missing.xml"/></symbols>
|
||||
<timelines>
|
||||
<DOMTimeline name="Scene 1">
|
||||
<layers>
|
||||
<DOMLayer name="Ball" color="#FF4FFF">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="10" tweenType="motion" acceleration="-50" name="start">
|
||||
<elements>
|
||||
<DOMSymbolInstance libraryItemName="Characters/Ball" loop="play once" firstFrame="2">
|
||||
<matrix><Matrix a="2" d="2" tx="100" ty="50"/></matrix>
|
||||
<color><Color alphaMultiplier="0.5"/></color>
|
||||
</DOMSymbolInstance>
|
||||
</elements>
|
||||
</DOMFrame>
|
||||
<DOMFrame index="10" duration="5">
|
||||
<elements>
|
||||
<DOMSymbolInstance libraryItemName="Characters/Ball"><matrix><Matrix a="2" d="2" tx="300" ty="50"/></matrix></DOMSymbolInstance>
|
||||
</elements>
|
||||
</DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
<DOMLayer name="Ground" locked="true">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="15">
|
||||
<elements>
|
||||
<DOMShape>
|
||||
<fills><FillStyle index="1"><SolidColor color="#00AA00"/></FillStyle>
|
||||
<FillStyle index="2"><LinearGradient><matrix><Matrix a="0.1" d="0.1" tx="320"/></matrix>
|
||||
<GradientEntry color="#000000" ratio="0"/><GradientEntry color="#FFFFFF" ratio="1"/></LinearGradient></FillStyle></fills>
|
||||
<strokes><StrokeStyle index="1"><SolidStroke weight="3"><fill><SolidColor color="#112233"/></fill></SolidStroke></StrokeStyle></strokes>
|
||||
<edges>
|
||||
<Edge fillStyle1="1" strokeStyle="1" edges="!0 6000|12800 6000|12800 7200"/>
|
||||
<Edge fillStyle0="1" edges="!0 6000|0 7200|12800 7200"/>
|
||||
</edges>
|
||||
</DOMShape>
|
||||
<DOMStaticText/>
|
||||
<DOMBitmapInstance libraryItemName="photo.png"/>
|
||||
</elements>
|
||||
</DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
<DOMLayer name="Notes" layerType="guide"><frames><DOMFrame index="0"><elements/></DOMFrame></frames></DOMLayer>
|
||||
<DOMLayer name="Folder" layerType="folder"/>
|
||||
</layers>
|
||||
</DOMTimeline>
|
||||
<DOMTimeline name="Scene 2"/>
|
||||
</timelines>
|
||||
</DOMDocument>"##;
|
||||
|
||||
const BALL: &str = r##"<DOMSymbolItem name="Characters/Ball" symbolType="movie clip">
|
||||
<timeline><DOMTimeline name="Ball"><layers><DOMLayer name="Layer 1"><frames><DOMFrame index="0" duration="4"><elements>
|
||||
<DOMOvalObject x="-10" y="-10" objectWidth="20" objectHeight="20"><fill><SolidColor color="#FF0000"/></fill></DOMOvalObject>
|
||||
</elements></DOMFrame></frames></DOMLayer></layers></DOMTimeline></timeline>
|
||||
</DOMSymbolItem>"##;
|
||||
|
||||
fn package() -> HashMap<&'static str, &'static str> {
|
||||
HashMap::from([("DOMDocument.xml", DOC), ("LIBRARY/Characters/Ball.xml", BALL)])
|
||||
}
|
||||
|
||||
fn import(files: &HashMap<&'static str, &'static str>) -> Result<(anicraft_doc::Document, crate::Report), XflError> {
|
||||
let read = |p: &str| -> Result<Option<Vec<u8>>, XflError> { Ok(files.get(p).map(|s| s.as_bytes().to_vec())) };
|
||||
import_with(&read)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_layers_frames_and_tweens() {
|
||||
let (doc, report) = import(&package()).unwrap();
|
||||
assert_eq!((doc.stage.width, doc.stage.height, doc.stage.fps), (640, 360, 30.0));
|
||||
assert_eq!(doc.stage.background, Rgba::hex(0x336699));
|
||||
let names: Vec<&str> = doc.timeline.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["Ball", "Ground", "Notes"], "folders are flattened away, order kept (top first)");
|
||||
let ball = &doc.timeline.layers[0];
|
||||
assert_eq!(ball.keyframes.len(), 2);
|
||||
assert_eq!((ball.keyframes[0].start, ball.keyframes[0].duration), (0, 10));
|
||||
assert_eq!(ball.keyframes[0].label, "start");
|
||||
assert!(matches!(ball.keyframes[0].tween.map(|t| t.easing), Some(anicraft_doc::Easing::Classic(e)) if e == -50.0));
|
||||
assert!(doc.timeline.layers[1].locked);
|
||||
assert_eq!(doc.timeline.layers[2].kind, LayerKind::Guide);
|
||||
assert_eq!(doc.frame_count(), 15);
|
||||
// What couldn't come across is reported, not guessed.
|
||||
assert_eq!(report.skipped.get("text fields"), Some(&1));
|
||||
assert_eq!(report.skipped.get("bitmaps"), Some(&1));
|
||||
assert_eq!(report.skipped.get("missing library files"), Some(&1));
|
||||
assert!(report.summary().contains("scenes after the first (1 more)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_layers_mask_the_layers_that_point_at_them() {
|
||||
// A mask inside a folder: `parentLayerIndex` counts every layer in the file, folders too.
|
||||
let shape = r##"<DOMShape><fills><FillStyle index="1"><SolidColor color="#FF0000"/></FillStyle></fills>
|
||||
<edges><Edge fillStyle1="1" edges="!0 0|2000 0|2000 2000|0 2000|0 0"/></edges></DOMShape>"##;
|
||||
let layer = |attrs: &str| format!(r#"<DOMLayer {attrs}><frames><DOMFrame index="0"><elements>{shape}</elements></DOMFrame></frames></DOMLayer>"#);
|
||||
let doc = format!(
|
||||
r#"<DOMDocument width="100" height="100"><timelines><DOMTimeline name="Scene 1"><layers>
|
||||
<DOMLayer name="Group" layerType="folder"/>{}{}{}{}</layers></DOMTimeline></timelines></DOMDocument>"#,
|
||||
layer(r#"name="Spot" layerType="mask" parentLayerIndex="0""#),
|
||||
layer(r#"name="Ball" layerType="masked" parentLayerIndex="1""#),
|
||||
layer(r#"name="Ring" parentLayerIndex="1""#),
|
||||
layer(r#"name="Sky" parentLayerIndex="0""#),
|
||||
);
|
||||
let doc: &'static str = Box::leak(doc.into_boxed_str());
|
||||
let (d, report) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap();
|
||||
let l = &d.timeline.layers;
|
||||
assert_eq!(l.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["Spot", "Ball", "Ring", "Sky"]);
|
||||
assert_eq!(l[0].kind, LayerKind::Mask);
|
||||
assert_eq!((l[1].parent, l[2].parent, l[3].parent), (Some(l[0].id), Some(l[0].id), None), "in the folder, not masked");
|
||||
assert!(report.skipped.keys().all(|k| !k.contains("mask")));
|
||||
let dl = evaluate(&d, 0);
|
||||
assert_eq!(dl.clip_parents.len(), 1);
|
||||
assert_eq!(dl.items.iter().filter(|i| i.clip == Some(0)).count(), 2);
|
||||
assert_eq!(dl.items.iter().filter(|i| i.masks == Some(0)).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_instances_and_the_tween_between_them() {
|
||||
let (doc, _) = import(&package()).unwrap();
|
||||
assert_eq!(doc.library.len(), 1);
|
||||
let sym = &doc.library[0];
|
||||
assert_eq!((sym.name.as_str(), sym.kind), ("Ball", SymbolKind::MovieClip));
|
||||
let inst = &doc.timeline.layers[0].keyframes[0].elements[0];
|
||||
let ElementKind::Symbol { symbol, loop_mode, first_frame } = &inst.kind else { panic!("an instance") };
|
||||
assert_eq!((*symbol, *loop_mode, *first_frame), (sym.id, LoopMode::PlayOnce, 2));
|
||||
assert_eq!(inst.transform.m, [2.0, 0.0, 0.0, 2.0, 100.0, 50.0]);
|
||||
assert_eq!(inst.color.alpha, 0.5);
|
||||
// Half-way through the tween (eased), the ball is between its two positions.
|
||||
let dl = evaluate(&doc, 5);
|
||||
let ball = dl.items.iter().find(|i| matches!(i.fill, Some(Paint::Solid(c)) if c == Rgba::hex(0xff0000))).expect("the ball renders");
|
||||
let x = ball.transform.translation().x;
|
||||
assert!(x > 100.0 && x < 300.0, "{x}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_become_fills_and_strokes() {
|
||||
let (doc, _) = import(&package()).unwrap();
|
||||
let els = &doc.timeline.layers[1].keyframes[0].elements;
|
||||
assert_eq!(els.len(), 2, "one fill (style 2 has no edges), one stroke");
|
||||
let ElementKind::Shape(fill) = &els[0].kind else { panic!() };
|
||||
assert_eq!(fill.fill, Some(Paint::Solid(Rgba::hex(0x00aa00))));
|
||||
let b = fill.path.bounds();
|
||||
assert!((b.min.y - 300.0).abs() < 0.01 && (b.max.x - 640.0).abs() < 0.01 && (b.max.y - 360.0).abs() < 0.01, "{b:?}: twips to pixels");
|
||||
let ElementKind::Shape(st) = &els[1].kind else { panic!() };
|
||||
assert_eq!(st.stroke.map(|s| (s.color, s.width)), Some((Rgba::hex(0x112233), 3.0)));
|
||||
assert!(st.fill.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fla_archive_imports_the_same() {
|
||||
let z = crate::zip::tests::make_zip(&[("DOMDocument.xml", DOC.as_bytes(), true), ("LIBRARY/Characters/Ball.xml", BALL.as_bytes(), true)]);
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-xfl-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let fla = dir.join("scene.fla");
|
||||
std::fs::write(&fla, &z).unwrap();
|
||||
let (doc, _) = crate::import_path(&fla).unwrap();
|
||||
assert_eq!(doc.timeline.layers.len(), 3);
|
||||
assert_eq!(doc.library.len(), 1);
|
||||
std::fs::remove_file(&fla).ok();
|
||||
std::fs::remove_dir(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_packages_fail_cleanly() {
|
||||
let mut files = package();
|
||||
files.insert("DOMDocument.xml", "<DOMDocument><timelines><DOMTimeline><layers><DOMLayer><frames><DOMFrame index=\"99999999999\" duration=\"-4\"><elements><DOMShape><edges><Edge fillStyle1=\"1\" edges=\"!#FFFFFFFF.FF 1e30|nan 0[\"/></edges></DOMShape></elements></DOMFrame></frames></DOMLayer></layers></DOMTimeline></timelines></DOMDocument>");
|
||||
let (doc, _) = import(&files).unwrap();
|
||||
assert!(doc.frame_count() <= 100_001);
|
||||
files.insert("DOMDocument.xml", "<NotAnimate/>");
|
||||
assert!(matches!(import(&files), Err(XflError::NotXfl(_))));
|
||||
files.insert("DOMDocument.xml", "<DOMDocument><unclosed>");
|
||||
assert!(matches!(import(&files), Err(XflError::Xml(_))));
|
||||
assert!(import(&HashMap::new()).is_err(), "no DOMDocument.xml");
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
//! A small, strict-enough XML reader for XFL documents.
|
||||
//!
|
||||
//! XFL stores everything that matters in elements and attributes (even shape geometry is an
|
||||
//! attribute), so the reader builds a tree of elements with attributes and ignores text.
|
||||
//! It handles the prolog, comments, CDATA, doctype, processing instructions, the five
|
||||
//! standard entities and numeric character references. Limits on input size, depth and
|
||||
//! element count keep a hostile file from exhausting memory or the stack. Never panics.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Largest document read (bytes).
|
||||
pub const MAX_INPUT: usize = 256 * 1024 * 1024;
|
||||
const MAX_DEPTH: usize = 256;
|
||||
const MAX_ELEMENTS: usize = 4_000_000;
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Element {
|
||||
pub name: String,
|
||||
pub attrs: HashMap<String, String>,
|
||||
pub children: Vec<Element>,
|
||||
}
|
||||
|
||||
impl Element {
|
||||
pub fn attr(&self, name: &str) -> Option<&str> {
|
||||
self.attrs.get(name).map(String::as_str)
|
||||
}
|
||||
pub fn f32(&self, name: &str) -> Option<f32> {
|
||||
self.attr(name).and_then(|v| v.trim().parse::<f32>().ok()).filter(|v| v.is_finite())
|
||||
}
|
||||
pub fn u32(&self, name: &str) -> Option<u32> {
|
||||
self.attr(name).and_then(|v| v.trim().parse::<u32>().ok())
|
||||
}
|
||||
pub fn bool(&self, name: &str) -> Option<bool> {
|
||||
self.attr(name).map(|v| v.trim() == "true")
|
||||
}
|
||||
/// The first child named `name`.
|
||||
pub fn child(&self, name: &str) -> Option<&Element> {
|
||||
self.children.iter().find(|c| c.name == name)
|
||||
}
|
||||
/// Children of the first child named `name` (XFL wraps lists: `<layers><DOMLayer/>…`).
|
||||
pub fn list(&self, name: &str) -> &[Element] {
|
||||
self.child(name).map_or(&[], |c| c.children.as_slice())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
pub enum XmlError {
|
||||
#[error("the XML is too large")]
|
||||
TooLarge,
|
||||
#[error("the XML is nested too deeply")]
|
||||
TooDeep,
|
||||
#[error("the XML has too many elements")]
|
||||
TooMany,
|
||||
#[error("malformed XML at byte {0}: {1}")]
|
||||
Syntax(usize, &'static str),
|
||||
}
|
||||
|
||||
struct P<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
impl P<'_> {
|
||||
fn err<T>(&self, what: &'static str) -> Result<T, XmlError> {
|
||||
Err(XmlError::Syntax(self.i, what))
|
||||
}
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.s.get(self.i).copied()
|
||||
}
|
||||
fn starts(&self, pat: &[u8]) -> bool {
|
||||
self.s.get(self.i..).is_some_and(|r| r.starts_with(pat))
|
||||
}
|
||||
fn skip_ws(&mut self) {
|
||||
while self.peek().is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
/// Skips past `end` (used for comments, CDATA, PIs, doctype).
|
||||
fn skip_until(&mut self, end: &[u8]) -> Result<(), XmlError> {
|
||||
let rest = self.s.get(self.i..).unwrap_or_default();
|
||||
match rest.windows(end.len()).position(|w| w == end) {
|
||||
Some(p) => {
|
||||
self.i += p + end.len();
|
||||
Ok(())
|
||||
}
|
||||
None => self.err("unterminated construct"),
|
||||
}
|
||||
}
|
||||
fn name(&mut self) -> Result<String, XmlError> {
|
||||
let start = self.i;
|
||||
while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.' | b':') || c >= 0x80) {
|
||||
self.i += 1;
|
||||
}
|
||||
if self.i == start {
|
||||
return self.err("expected a name");
|
||||
}
|
||||
Ok(String::from_utf8_lossy(self.s.get(start..self.i).unwrap_or_default()).into_owned())
|
||||
}
|
||||
/// Skips text, comments and other non-element content up to the next tag.
|
||||
fn skip_misc(&mut self) -> Result<(), XmlError> {
|
||||
loop {
|
||||
while self.peek().is_some_and(|c| c != b'<') {
|
||||
self.i += 1;
|
||||
}
|
||||
if self.starts(b"<!--") {
|
||||
self.skip_until(b"-->")?;
|
||||
} else if self.starts(b"<![CDATA[") {
|
||||
self.skip_until(b"]]>")?;
|
||||
} else if self.starts(b"<?") {
|
||||
self.skip_until(b"?>")?;
|
||||
} else if self.starts(b"<!") {
|
||||
self.skip_until(b">")?;
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
fn element(&mut self, depth: usize) -> Result<Element, XmlError> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(XmlError::TooDeep);
|
||||
}
|
||||
self.count += 1;
|
||||
if self.count > MAX_ELEMENTS {
|
||||
return Err(XmlError::TooMany);
|
||||
}
|
||||
if self.peek() != Some(b'<') {
|
||||
return self.err("expected '<'");
|
||||
}
|
||||
self.i += 1;
|
||||
let mut el = Element { name: self.name()?, ..Element::default() };
|
||||
loop {
|
||||
self.skip_ws();
|
||||
match self.peek() {
|
||||
Some(b'/') => {
|
||||
self.i += 1;
|
||||
if self.peek() != Some(b'>') {
|
||||
return self.err("expected '>' after '/'");
|
||||
}
|
||||
self.i += 1;
|
||||
return Ok(el);
|
||||
}
|
||||
Some(b'>') => {
|
||||
self.i += 1;
|
||||
break;
|
||||
}
|
||||
Some(_) => {
|
||||
let k = self.name()?;
|
||||
self.skip_ws();
|
||||
if self.peek() != Some(b'=') {
|
||||
return self.err("expected '=' in an attribute");
|
||||
}
|
||||
self.i += 1;
|
||||
self.skip_ws();
|
||||
let q = match self.peek() {
|
||||
Some(q @ (b'"' | b'\'')) => q,
|
||||
_ => return self.err("expected a quoted attribute value"),
|
||||
};
|
||||
self.i += 1;
|
||||
let start = self.i;
|
||||
while self.peek().is_some_and(|c| c != q) {
|
||||
self.i += 1;
|
||||
}
|
||||
if self.peek().is_none() {
|
||||
return self.err("unterminated attribute value");
|
||||
}
|
||||
let raw = String::from_utf8_lossy(self.s.get(start..self.i).unwrap_or_default()).into_owned();
|
||||
self.i += 1;
|
||||
el.attrs.insert(k, unescape(&raw));
|
||||
}
|
||||
None => return self.err("unexpected end inside a tag"),
|
||||
}
|
||||
}
|
||||
// Content: children until the matching end tag.
|
||||
loop {
|
||||
self.skip_misc()?;
|
||||
if self.peek().is_none() {
|
||||
return self.err("missing end tag");
|
||||
}
|
||||
if self.starts(b"</") {
|
||||
self.i += 2;
|
||||
let n = self.name()?;
|
||||
self.skip_ws();
|
||||
if self.peek() != Some(b'>') || n != el.name {
|
||||
return self.err("mismatched end tag");
|
||||
}
|
||||
self.i += 1;
|
||||
return Ok(el);
|
||||
}
|
||||
el.children.push(self.element(depth + 1)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unescape(s: &str) -> String {
|
||||
if !s.contains('&') {
|
||||
return s.to_string();
|
||||
}
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut rest = s;
|
||||
while let Some(i) = rest.find('&') {
|
||||
out.push_str(rest.get(..i).unwrap_or(""));
|
||||
let tail = rest.get(i..).unwrap_or("");
|
||||
let Some(end) = tail.find(';').filter(|e| *e <= 12) else {
|
||||
out.push('&');
|
||||
rest = tail.get(1..).unwrap_or("");
|
||||
continue;
|
||||
};
|
||||
let ent = tail.get(1..end).unwrap_or("");
|
||||
let ch = match ent {
|
||||
"lt" => Some('<'),
|
||||
"gt" => Some('>'),
|
||||
"amp" => Some('&'),
|
||||
"quot" => Some('"'),
|
||||
"apos" => Some('\''),
|
||||
_ => ent
|
||||
.strip_prefix("#x")
|
||||
.or_else(|| ent.strip_prefix("#X"))
|
||||
.and_then(|h| u32::from_str_radix(h, 16).ok())
|
||||
.or_else(|| ent.strip_prefix('#').and_then(|d| d.parse::<u32>().ok()))
|
||||
.and_then(char::from_u32),
|
||||
};
|
||||
match ch {
|
||||
Some(c) => {
|
||||
out.push(c);
|
||||
rest = tail.get(end + 1..).unwrap_or("");
|
||||
}
|
||||
None => {
|
||||
out.push('&');
|
||||
rest = tail.get(1..).unwrap_or("");
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Parses a document and returns its root element.
|
||||
pub fn parse(src: &[u8]) -> Result<Element, XmlError> {
|
||||
if src.len() > MAX_INPUT {
|
||||
return Err(XmlError::TooLarge);
|
||||
}
|
||||
// A UTF-8 byte-order mark is allowed.
|
||||
let src = src.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(src);
|
||||
let mut p = P { s: src, i: 0, count: 0 };
|
||||
p.skip_misc()?;
|
||||
if p.peek().is_none() {
|
||||
return p.err("no root element");
|
||||
}
|
||||
p.element(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn elements_attributes_and_entities() {
|
||||
let x = br#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- a comment -->
|
||||
<DOMDocument xmlns="http://ns.adobe.com/xfl/2008/" width="640" frameRate='30'>
|
||||
<timelines><DOMTimeline name="Scene & "1" AB"><layers/></DOMTimeline></timelines>
|
||||
<![CDATA[ <ignored/> ]]>
|
||||
text is ignored
|
||||
</DOMDocument>"#;
|
||||
let root = parse(x).unwrap();
|
||||
assert_eq!(root.name, "DOMDocument");
|
||||
assert_eq!(root.f32("width"), Some(640.0));
|
||||
assert_eq!(root.u32("frameRate"), Some(30));
|
||||
let tl = &root.list("timelines")[0];
|
||||
assert_eq!(tl.attr("name"), Some("Scene & \"1\" AB"));
|
||||
assert!(tl.list("layers").is_empty());
|
||||
assert_eq!(root.children.len(), 1, "CDATA and text are skipped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_input_is_an_error_not_a_panic() {
|
||||
for bad in [&b""[..], b"<", b"<a", b"<a b>", b"<a b='1>", b"<a></b>", b"<a><b></a>", b"<!-- open", b"<a>\xff\xfe"] {
|
||||
assert!(parse(bad).is_err(), "{:?}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
let deep = "<a>".repeat(400) + &"</a>".repeat(400);
|
||||
assert_eq!(parse(deep.as_bytes()).unwrap_err(), XmlError::TooDeep);
|
||||
assert_eq!(unescape("a &unknown; b & c"), "a &unknown; b & c");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! Reading files out of a `.fla` (a zip archive of an XFL folder).
|
||||
//!
|
||||
//! Implements the parts of the published ZIP format (PKWARE APPNOTE) that `.fla` files use:
|
||||
//! the end-of-central-directory record, central directory entries and local headers, with
|
||||
//! "stored" and "deflate" entries (inflated by `miniz_oxide`). ZIP64 and encryption are refused
|
||||
//! with a clear error. Every offset and size is checked; sizes are capped so a zip bomb can't
|
||||
//! exhaust memory. Never panics.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Largest single entry inflated (bytes).
|
||||
pub const MAX_ENTRY: usize = 256 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
pub enum ZipError {
|
||||
#[error("not a zip archive (no end-of-directory record)")]
|
||||
NotZip,
|
||||
#[error("the archive is damaged: {0}")]
|
||||
Damaged(&'static str),
|
||||
#[error("'{0}' uses an unsupported zip feature ({1})")]
|
||||
Unsupported(String, &'static str),
|
||||
#[error("'{0}' is too large to read")]
|
||||
TooLarge(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Entry {
|
||||
method: u16,
|
||||
flags: u16,
|
||||
comp: usize,
|
||||
size: usize,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
pub struct Archive<'a> {
|
||||
data: &'a [u8],
|
||||
entries: HashMap<String, Entry>,
|
||||
}
|
||||
|
||||
fn u16_at(d: &[u8], i: usize) -> Option<u16> {
|
||||
Some(u16::from_le_bytes(d.get(i..i + 2)?.try_into().ok()?))
|
||||
}
|
||||
fn u32_at(d: &[u8], i: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(d.get(i..i + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
impl<'a> Archive<'a> {
|
||||
pub fn open(data: &'a [u8]) -> Result<Archive<'a>, ZipError> {
|
||||
// The end record is in the last 22 + 65535 bytes (it may carry a comment).
|
||||
let lo = data.len().saturating_sub(22 + 65_535);
|
||||
let eocd = (lo..data.len().saturating_sub(21)).rev().find(|&i| u32_at(data, i) == Some(0x0605_4b50)).ok_or(ZipError::NotZip)?;
|
||||
let count = u16_at(data, eocd + 10).ok_or(ZipError::Damaged("end record"))? as usize;
|
||||
let dir = u32_at(data, eocd + 16).ok_or(ZipError::Damaged("end record"))? as usize;
|
||||
if count == 0xffff || dir == 0xffff_ffff {
|
||||
return Err(ZipError::Unsupported("archive".into(), "ZIP64"));
|
||||
}
|
||||
let mut entries = HashMap::with_capacity(count.min(100_000));
|
||||
let mut i = dir;
|
||||
for _ in 0..count {
|
||||
if u32_at(data, i) != Some(0x0201_4b50) {
|
||||
return Err(ZipError::Damaged("central directory"));
|
||||
}
|
||||
let field = |o: usize| u32_at(data, i + o).ok_or(ZipError::Damaged("central directory"));
|
||||
let short = |o: usize| u16_at(data, i + o).ok_or(ZipError::Damaged("central directory"));
|
||||
let (flags, method) = (short(8)?, short(10)?);
|
||||
let (comp, size) = (field(20)? as usize, field(24)? as usize);
|
||||
let (nlen, xlen, clen) = (short(28)? as usize, short(30)? as usize, short(32)? as usize);
|
||||
let offset = field(42)? as usize;
|
||||
let name = data.get(i + 46..i + 46 + nlen).ok_or(ZipError::Damaged("entry name"))?;
|
||||
let name = String::from_utf8_lossy(name).replace('\\', "/");
|
||||
entries.insert(name, Entry { method, flags, comp, size, offset });
|
||||
i += 46 + nlen + xlen + clen;
|
||||
}
|
||||
Ok(Archive { data, entries })
|
||||
}
|
||||
|
||||
pub fn names(&self) -> impl Iterator<Item = &str> {
|
||||
self.entries.keys().map(String::as_str)
|
||||
}
|
||||
|
||||
/// The bytes of entry `name` (path inside the archive, `/`-separated).
|
||||
pub fn read(&self, name: &str) -> Result<Option<Vec<u8>>, ZipError> {
|
||||
let Some(e) = self.entries.get(name) else { return Ok(None) };
|
||||
if e.flags & 1 != 0 {
|
||||
return Err(ZipError::Unsupported(name.into(), "encryption"));
|
||||
}
|
||||
if e.size > MAX_ENTRY || e.comp > MAX_ENTRY {
|
||||
return Err(ZipError::TooLarge(name.into()));
|
||||
}
|
||||
let d = self.data;
|
||||
if u32_at(d, e.offset) != Some(0x0403_4b50) {
|
||||
return Err(ZipError::Damaged("local header"));
|
||||
}
|
||||
let nlen = u16_at(d, e.offset + 26).ok_or(ZipError::Damaged("local header"))? as usize;
|
||||
let xlen = u16_at(d, e.offset + 28).ok_or(ZipError::Damaged("local header"))? as usize;
|
||||
let start = e.offset + 30 + nlen + xlen;
|
||||
let raw = d.get(start..start + e.comp).ok_or(ZipError::Damaged("entry data"))?;
|
||||
match e.method {
|
||||
0 => Ok(Some(raw.to_vec())),
|
||||
8 => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.clamp(1, MAX_ENTRY)).map(Some).map_err(|_| ZipError::Damaged("deflate data")),
|
||||
_ => Err(ZipError::Unsupported(name.into(), "compression method")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Builds a zip with stored and deflated entries (for tests).
|
||||
pub fn make_zip(files: &[(&str, &[u8], bool)]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut dir = Vec::new();
|
||||
for (name, body, deflate) in files {
|
||||
let data = if *deflate { miniz_oxide::deflate::compress_to_vec(body, 6) } else { body.to_vec() };
|
||||
let offset = out.len() as u32;
|
||||
let method: u16 = if *deflate { 8 } else { 0 };
|
||||
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&[20, 0, 0, 0]);
|
||||
out.extend_from_slice(&method.to_le_bytes());
|
||||
out.extend_from_slice(&[0; 8]); // time, date, crc (not checked)
|
||||
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.extend_from_slice(&data);
|
||||
dir.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
|
||||
dir.extend_from_slice(&[20, 0, 20, 0, 0, 0]);
|
||||
dir.extend_from_slice(&method.to_le_bytes());
|
||||
dir.extend_from_slice(&[0; 8]);
|
||||
dir.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
dir.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
dir.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
dir.extend_from_slice(&[0; 12]);
|
||||
dir.extend_from_slice(&offset.to_le_bytes());
|
||||
dir.extend_from_slice(name.as_bytes());
|
||||
}
|
||||
let dir_at = out.len() as u32;
|
||||
out.extend_from_slice(&dir);
|
||||
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
out.extend_from_slice(&(files.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&(files.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&(dir.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&dir_at.to_le_bytes());
|
||||
out.extend_from_slice(&[0, 0]);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_stored_and_deflated_entries() {
|
||||
let z = make_zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("LIBRARY\\Ball.xml", b"<DOMSymbolItem/>", false)]);
|
||||
let a = Archive::open(&z).unwrap();
|
||||
assert_eq!(a.read("DOMDocument.xml").unwrap().unwrap(), b"<DOMDocument/>");
|
||||
assert_eq!(a.read("LIBRARY/Ball.xml").unwrap().unwrap(), b"<DOMSymbolItem/>", "backslashes normalised");
|
||||
assert_eq!(a.read("missing").unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_archives_are_errors() {
|
||||
assert_eq!(Archive::open(b"not a zip").err(), Some(ZipError::NotZip));
|
||||
let mut z = make_zip(&[("a", b"hello", true)]);
|
||||
let n = z.len();
|
||||
// Point the directory past the end.
|
||||
z[n - 6] = 0xff;
|
||||
assert!(Archive::open(&z).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# cargo-deny policy: every dependency must be permissively licensed, come from crates.io and
|
||||
# carry no copyleft obligation on AniCraft. Run: cargo deny check licenses bans sources
|
||||
# (and `cargo deny check advisories` when online). See docs/legal/compliance.md.
|
||||
|
||||
[graph]
|
||||
# Check every platform we ship (Windows, macOS, Linux, wasm), not just the host.
|
||||
all-features = false
|
||||
|
||||
[licenses]
|
||||
# Permissive licenses only. Where a crate offers a choice ("MIT OR GPL"), cargo-deny picks the
|
||||
# permissive one; nothing in our tree is accepted under a copyleft term.
|
||||
allow = [
|
||||
"MIT",
|
||||
"Apache-2.0",
|
||||
"Apache-2.0 WITH LLVM-exception",
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"ISC",
|
||||
"Zlib",
|
||||
"0BSD",
|
||||
"BSL-1.0",
|
||||
"Unicode-3.0",
|
||||
"Unlicense",
|
||||
]
|
||||
confidence-threshold = 0.93
|
||||
|
||||
# Font licenses are allowed only for the crate that embeds egui's default UI fonts.
|
||||
[[licenses.exceptions]]
|
||||
crate = "epaint_default_fonts"
|
||||
allow = ["OFL-1.1", "Ubuntu-font-1.0"]
|
||||
|
||||
[licenses.private]
|
||||
# Our own workspace crates are MIT OR Apache-2.0 (checked by `cargo deny` like any other crate).
|
||||
ignore = false
|
||||
|
||||
[bans]
|
||||
multiple-versions = "allow"
|
||||
# Path dependencies inside the workspace have no version; that is fine for unpublished crates.
|
||||
wildcards = "deny"
|
||||
allow-wildcard-paths = true
|
||||
|
||||
[sources]
|
||||
unknown-registry = "deny"
|
||||
unknown-git = "deny"
|
||||
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
|
||||
|
||||
[advisories]
|
||||
# Fetched from the RustSec database when online.
|
||||
yanked = "warn"
|
||||
@@ -0,0 +1,51 @@
|
||||
# ADR 0001: Undo/redo on persistent (structurally shared) document snapshots
|
||||
|
||||
* Status: accepted (2026-10-28)
|
||||
* Supersedes: the M0 full-document-clone history
|
||||
|
||||
## Context
|
||||
|
||||
AniCraft must handle large files: Animate projects with hundreds of layers, thousands of
|
||||
keyframes and hundreds of thousands of element instances once XFL import lands. Undo has to be
|
||||
exact (it is the user's safety net), memory-bounded, cheap per edit, and it must not slow down
|
||||
interactive gestures such as dragging.
|
||||
|
||||
## Options considered
|
||||
|
||||
| Option | Exactness | Per-edit cost | Engineering risk |
|
||||
|---|---|---|---|
|
||||
| A. Full-document clone per step (M0) | exact by construction | O(document) time and memory | none, but unusable at scale |
|
||||
| B. Command pattern (each command records its inverse) | only as good as every hand-written inverse | O(change) | high: dozens of commands, each needing a correct inverse, and every new command adds risk |
|
||||
| C. Diff/patch of serialized states | exact | O(document) to diff | medium; slow on big files |
|
||||
| **D. Persistent document + snapshot per step** | exact by construction | O(path to the change) | low: one rule (mutate through `Arc::make_mut`) |
|
||||
|
||||
## Decision
|
||||
|
||||
**D.** The document is a persistent tree: `Timeline.layers: Vec<Arc<Layer>>`,
|
||||
`Layer.keyframes: Vec<Arc<Keyframe>>`, `Keyframe.elements: Vec<Arc<Element>>`,
|
||||
`Shape.path: Arc<Path>`, `library: Vec<Arc<Symbol>>`. Mutation goes through `Arc::make_mut`,
|
||||
which copies only the nodes on the path to the change (copy-on-write).
|
||||
|
||||
* **Snapshot** = `Document::clone()` = O(layers + symbols) pointer copies (0.4 µs measured on
|
||||
a 200k-instance document).
|
||||
* **Change detection** = `PartialEq` that compares `Arc`s by pointer first (`arc_eq`), so it is
|
||||
O(changed), not O(document).
|
||||
* **History** (`engine/src/history.rs`) stores snapshots and an *estimate of unique bytes* per
|
||||
step (memory not shared with the neighbouring state). It is bounded by a byte budget
|
||||
(default 512 MB) plus a step cap, evicting the oldest steps first.
|
||||
* **State ids**: every committed change gets a process-unique `StateId`. Undo returns to the
|
||||
earlier id. The save point is a state id, so undoing back to the saved state makes the
|
||||
document clean again. Render caches key on state ids, so undo is a cache hit.
|
||||
* **Gestures** coalesce a drag (or a slider scrub) into one undo step.
|
||||
* **Atomic commands**: a failing command restores the pre-command snapshot. That is free with D.
|
||||
|
||||
## Consequences
|
||||
|
||||
* A rule every contributor must follow: never get `&mut` into the document except through
|
||||
`Arc::make_mut` (`Timeline::layer_mut`, `Layer::keyframe_mut`,
|
||||
`Keyframe::elements_mut_where`). Touch only what changes. For example, `Layer::normalize`
|
||||
only un-shares keyframes whose duration actually changes.
|
||||
* The same sharing makes render-thread hand-off O(1)-ish (ADR 0002) and lets F6 keyframe
|
||||
copies share elements.
|
||||
* Measured (release, 50 layers × 200 shapes × 240 frames = 200k instances): edit 0.011 ms,
|
||||
undo 0.009 ms, about 2.7 KB of history per nudge.
|
||||
@@ -0,0 +1,45 @@
|
||||
# ADR 0002: Render pipeline: background worker, frame cache, band parallelism, culling
|
||||
|
||||
* Status: accepted (2026-10-28)
|
||||
|
||||
## Context
|
||||
|
||||
In M0 the stage rasterized on the UI thread, one shape at a time, with row parallelism only for
|
||||
big shapes. A synthetic 10k-visible-shape frame took 92 ms at 1080p on 32 threads, and the UI
|
||||
would freeze for that long on every edit.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **The UI thread never rasterizes.** `engine::render_service::RenderService` owns a worker
|
||||
thread. The stage asks for a frame by key and keeps showing the newest finished picture,
|
||||
placed by the stage area it covers so pan and zoom stay smooth, until the new one arrives.
|
||||
Policy: one *urgent* slot (latest wins, so a drag never builds a backlog) plus a *prefetch*
|
||||
queue, replaced wholesale. During playback the stage prefetches the next 12 frames.
|
||||
2. **Frame cache keyed by content.** `frame_key(state id, frame, view, onion)`, LRU-bounded by
|
||||
bytes (default 768 MB). Undo/redo and looping playback are cache hits.
|
||||
3. **Two-phase, band-parallel rasterization** (`render::render`):
|
||||
* Phase 1, parallel over items: cull by control-point bounds, flatten, stroke and build the
|
||||
shader. Display-list order is preserved.
|
||||
* Phase 2, parallel over 32-row bands: each band rasterizes every op touching it, in order,
|
||||
with one reused coverage buffer. Each row belongs to exactly one band, so output is
|
||||
**bit-identical** to a serial render (this keeps the oracle deterministic).
|
||||
4. **Culling before flattening**, using conservative control-point bounds.
|
||||
5. **Cheap hit testing**: a bounding-box test rejects items before any curve is flattened. The
|
||||
session caches the display list per `(state, frame)`.
|
||||
6. **Parallel PNG-sequence export** across frames (same bytes as serial export).
|
||||
|
||||
## Measured (release, 32 threads, 50 layers × 200 shapes, ≈9.9k visible shapes)
|
||||
|
||||
| Metric | Before | After |
|
||||
|---|---|---|
|
||||
| 1080p frame | 92.5 ms | 16.5 ms |
|
||||
| 400% zoom frame (9.2k culled) | 58.1 ms | 10.9 ms |
|
||||
| Hit test | n/a | 51 µs |
|
||||
|
||||
## Consequences / next
|
||||
|
||||
* GPU renderer (M3) plugs in behind the same `FrameJob → FrameImage` contract and is checked
|
||||
against this CPU oracle.
|
||||
* Further CPU wins, measured before adopting: a flatten cache keyed by `(Arc<Path>, transform)`
|
||||
for static shapes during playback; sparse-strip coverage for very large shapes; SIMD
|
||||
compositing.
|
||||
@@ -0,0 +1,34 @@
|
||||
# ADR 0003: `.anicraft` v2: SVG path strings, shared path table, streaming read
|
||||
|
||||
* Status: accepted (2026-10-28)
|
||||
|
||||
## Context
|
||||
|
||||
Measuring before optimizing paid off here. The v1 writer turned an 86 MB in-memory stress
|
||||
document into **782 MB** of JSON (925 ms to save, 633 ms to load). Two causes: paths shared in
|
||||
memory across keyframes were repeated in every keyframe, and paths were written as verbose
|
||||
tagged JSON.
|
||||
|
||||
## Decision
|
||||
|
||||
* `Path` serializes as compact SVG path data (`"M0 0L10 0C…Z"`) with shortest round-trip
|
||||
floats. The parser is strict, bounded and never panics.
|
||||
* Shared paths are written once in a top-level `paths` table; shapes store an index.
|
||||
`path_table::build_table` walks the document first, so the table precedes the document in the
|
||||
file. The reader streams in one pass and resolves references to shared `Arc`s, which
|
||||
**restores in-memory sharing on load**.
|
||||
* Small files (< 1 MB) are pretty-printed for humans and diffs; large files are compact.
|
||||
* v1 files (inline legacy paths) still load; newer-than-supported versions are refused.
|
||||
|
||||
## Measured (same stress document)
|
||||
|
||||
| | v1 | v2 |
|
||||
|---|---|---|
|
||||
| File size | 782 MB | 65 MB |
|
||||
| Save | 925 ms | 118 ms |
|
||||
| Load | 633 ms | 142 ms |
|
||||
|
||||
## Next
|
||||
|
||||
A zip container for embedded media (M2); optional binary encoding if profiling shows JSON
|
||||
parsing dominates on real XFL-imported files.
|
||||
@@ -0,0 +1,35 @@
|
||||
# ADR 0004: Destructive actions: tiered confirmation, enforced in the engine
|
||||
|
||||
* Status: accepted (2026-10-28)
|
||||
|
||||
## Context
|
||||
|
||||
Requirement from the project lead: destructive actions must always have a confirmation and
|
||||
must never be a single action away. The users are artists in a flow state, often driving the
|
||||
app from the keyboard.
|
||||
|
||||
## Options considered
|
||||
|
||||
| Option | Safety | Flow |
|
||||
|---|---|---|
|
||||
| A. Confirm every destructive command (including deleting a shape) | high on paper; in practice users learn to click through constant dialogs ("dialog blindness"), which erodes it | poor: a modal on the most frequent edits |
|
||||
| B. No confirmations, rely on undo | fine for undoable edits; **fails** for irreversible loss (discarding unsaved work, overwriting files) | best |
|
||||
| **C. Tiered** (see `product-principles.md`) | irreversible loss always guarded; large undoable deletions guarded by default; routine edits protected by undo with a visible hint | good |
|
||||
|
||||
## Decision
|
||||
|
||||
**C.** Confirmation rules live in the engine (`engine/src/confirm.rs`, `Session::confirmation`),
|
||||
not the UI, so every front end gets the same safety:
|
||||
|
||||
* The desktop app shows a dialog for both guarded tiers. For irreversible actions the
|
||||
destructive button must be clicked; Enter does nothing, Esc cancels.
|
||||
* Irreversible commands are **refused by the engine** unless the params include
|
||||
`"confirm": true`. This protects agents and scripts too.
|
||||
* Closing the window with unsaved changes asks Save / Don't Save / Cancel.
|
||||
* Routine deletions report "Ctrl+Z to undo" in the status bar.
|
||||
|
||||
## Consequences
|
||||
|
||||
* New commands that can discard content must add a rule to `confirm.rs` and a test.
|
||||
* "Don't ask again" covers only the undoable tier and lasts for the session; it becomes a
|
||||
preference when the settings system lands.
|
||||