Merge remote-tracking branch 'origin/main' into HEAD

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
Dylan M. Taylor committed 2026-11-16 22:15:37 -05:00
commit 1de34736d8
527 files changed
+103621 -6441

No files matched your search

+4
View File
@@ -16,3 +16,7 @@ scripts/git-hooks/* text eol=lf
*.tiff binary
*.DS_Store binary
*.ico binary
# XFL corpus media (ADR 0086)
*.flv binary
*.aif binary
*.dat binary
+16
View File
@@ -0,0 +1,16 @@
version: 2
updates:
# Maintain GitHub Actions workflows
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
groups:
actions:
patterns:
- "*"
commit-message:
prefix: "ci(deps)"
+25
View File
@@ -22,11 +22,36 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
# Store readiness (ADR 0094): the metadata Flathub, AppStream consumers and winget/MSIX read.
# Checks only; nothing is submitted (submissions are the team's job, docs/release.md).
store-readiness:
timeout-minutes: 10
name: Store readiness (Flatpak, AppStream, winget/MSIX)
runs-on: ubuntu-24.04
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install the validators
run: |
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends appstream desktop-file-utils python3-yaml
- name: Check store metadata
run: packaging/check-store-readiness.sh
windows-install-policy:
timeout-minutes: 15
name: Windows installation policy (no app build)
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+62
View File
@@ -0,0 +1,62 @@
# The gate on macOS and Windows (ADR 0067): build, test and clippy the whole workspace on the
# latest macOS (arm64) and Windows (x64) runners, so `cfg(target_os = "macos")` and
# `cfg(windows)` code (the platform layer, Apple Events, Increase Contrast, contrast themes,
# the Windows resource build) is compiled and linted on every pull request that changes code.
# The Linux gate is ci.yml; this file only calls the suite's shared gate with other runners.
name: CI (macOS, Windows)
# A change that touches only documentation or other workflows skips both legs. Later patterns
# win: everything, then not docs, Markdown or .github, then this file again. Kept in step in
# both lists (no YAML anchors: not every workflow tool reads them).
on:
push:
branches: [main]
paths:
- "**"
- "!docs/**"
- "!**/*.md"
- "!.github/**"
- ".github/workflows/platforms.yml"
pull_request:
paths:
- "**"
- "!docs/**"
- "!**/*.md"
- "!.github/**"
- ".github/workflows/platforms.yml"
workflow_dispatch:
permissions:
contents: read
# Its own group, so these legs never cancel the Linux gate. A newer push to a PR branch cancels
# its older run (macOS runners are scarce); every push to main runs to the end.
concurrency:
group: ci-platforms-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
gate:
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. The
# shared gate pins every action by SHA, runs Harden-Runner first in each leg, and keys
# rust-cache per OS and architecture (written by pushes to main, read by pull requests).
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["macos-latest", "windows-latest"]'
# Same craft-fonts commit as ci.yml, release.yml and freebsd.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# Nothing extra: the wasm build is web.yml's, and plain cargo test needs no nextest.
targets: ""
tools: ""
# Cargo.toml's dev profile already keeps line tables only (and Windows PDBs small).
dev-debug: ""
timeout-minutes: 90
gate-timeout-minutes: 85
# All three steps run, so one run reports every failure; GPU tests skip themselves when
# the runner has no usable adapter (crates/gpu/src/tests.rs).
command: |
status=0
cargo build --workspace --locked || status=1
cargo test --workspace --locked --no-fail-fast || status=1
cargo clippy --workspace --all-targets --locked -- -D warnings || status=1
exit "$status"
+7 -1
View File
@@ -8,6 +8,10 @@
name: Release
on:
# A nightly dry run on main: every release build except macOS, nothing signed or released
# (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
schedule:
- cron: "0 1 * * *"
push:
branches: [release]
workflow_dispatch:
@@ -26,10 +30,12 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: anicraft
app-title: AniCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# No WebAssembly build of the editor yet (roadmap M8).
# The web editor builds (ADR 0036) and packaging/web/package.sh makes its zip (#210), but
# releases don't carry it until the team decides where it is hosted: off for now.
has-web: false
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+26 -32
View File
@@ -1,7 +1,7 @@
# The web build (ADR 0036, docs/web.md), so it never regresses: every crate of the workspace
# builds for wasm32-unknown-unknown, the engine's tests/wasm.rs runs inside WebAssembly in Node
# (what a build can't catch: clock, thread and file calls that compile but trap), and
# scripts/build-web.sh produces the web/ bundle. Nothing is deployed.
# packaging/web/package.sh produces the web/ bundle and its release zip. Nothing is deployed.
name: Web
on:
@@ -21,34 +21,28 @@ concurrency:
jobs:
wasm:
name: Web build (wasm32)
runs-on: ubuntu-latest
timeout-minutes: 60
env:
CARGO_TERM_COLOR: always
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Rust with the wasm32 target
run: |
rustup toolchain install stable --profile minimal --target wasm32-unknown-unknown
rustup default stable
- name: Every crate builds for wasm32
run: cargo build --workspace --target wasm32-unknown-unknown --locked
- name: wasm-bindgen CLI at the version Cargo.lock pins
run: |
version="$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' Cargo.lock)"
cargo install wasm-bindgen-cli --version "$version" --locked
- name: The engine inside WebAssembly (Node)
env:
CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner
run: cargo test -p anicraft-engine --target wasm32-unknown-unknown --test wasm --locked
- name: The web editor bundle
run: |
scripts/build-web.sh
ls -l web
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
timeout-minutes: 60
# As before: no craft-fonts, apt packages or nextest; the gate adds the wasm32 target.
craft-fonts-ref: ""
tools: ""
# Its own cache, apart from ci.yml's gate.
cache-version: v1-web
command: |
# Every crate builds for wasm32.
cargo build --workspace --target wasm32-unknown-unknown --locked
# The sample plug-ins (examples/plugins; ADR 0017, 0088): built to WebAssembly, their own
# tests, and the engine running the built modules.
examples/plugins/build.sh
(cd examples/plugins && cargo test --locked)
ANICRAFT_EXAMPLE_PLUGINS="$PWD/examples/plugins/dist" cargo test -p anicraft-engine --test example_plugins --locked
# wasm-bindgen CLI at the version Cargo.lock pins.
version="$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' Cargo.lock)"
cargo install wasm-bindgen-cli --version "$version" --locked
# The engine inside WebAssembly (Node).
CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER=wasm-bindgen-test-runner cargo test -p anicraft-engine --target wasm32-unknown-unknown --test wasm --locked
# The web editor bundle and its release zip (#210): what the release workflow's web job runs.
packaging/web/package.sh
ls -l web dist/release
+15 -2
View File
@@ -12,6 +12,7 @@ crates/xml L0 Bounded XML element reader shared by the importers (XFL, SVG
crates/plugins L0 Sandboxed WebAssembly plug-ins: wasmi host, ABI v1, limits, registry (ADR 0017)
crates/audio L0 Sound decoding (WAV, Ogg Vorbis, MP3), pure mixing and resampling, WAV, peaks (ADR 0020)
crates/actions L0 Timeline action IR: stop/play/goto, targets, button events, frame scripts (ADR 0024)
crates/guide L0 The user guide (docs/guide) as a bundled static HTML book, with its link checks (ADR 0069)
crates/doc L1 Document model, easing, timeline evaluation, the interactive player, sample scene
crates/text L1 Fonts on this computer, shaping and line layout into outlines (ADR 0012)
crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, PNG)
@@ -19,7 +20,7 @@ crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR
crates/svg L2 SVG import: shapes, groups, use, styles, gradients, clips/masks → mask layers, text
crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format
crates/gpu L3 wgpu stage renderer (the default stage): tile binning, compute coverage, bitmaps, filters (ADR 0019, 0029, 0032)
crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve/mcp
crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/guide/serve/mcp
src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
```
@@ -76,7 +77,9 @@ a new crate needs a row here and in its `LAYERS` table.
## 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
* **Dependencies**: permissive only, from crates.io or the explicitly allowlisted
`storytold/craft-libs` Git source, pinned to a reviewed `rev` in `Cargo.toml`.
`deny.toml` is the policy; unknown registries and Git sources remain denied, 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.
@@ -142,3 +145,13 @@ cargo run -- --screenshot shots/now.png
```
Update `docs/roadmap.md` › Honest status when you move a capability.
## Shared Craft libraries
Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage.
ADR 0040 Decision 2 remains a deliberate, scoped exception for the existing app-local
craft-i18n catalog parser until a separately reviewed parity-preserving cutover updates
that ADR and its implementation together. Its historical crates.io-only rationale does
not override the reviewed/pinned craft-libs source exception above. This guidance alone
does not migrate that parser or supersede its runtime behavior.
+30 -6
View File
@@ -19,15 +19,18 @@ shaders or SDK code).
| 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` (19 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
| `assets/icons/anicraft-*.svg` (35 files: align, distribute, layer, mask and masked layer, width tool, gradient transform tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, asset warp, edit multiple frames, insert frame, keyframe and blank keyframe, clip to the stage, and seven panel icons: properties, swatches, library, explorer, history, output, actions) | Align panel, layer-type, Width tool, Gradient Transform tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone, Bind and Asset Warp tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames, the timeline's Insert Frame / Keyframe / Blank Keyframe buttons, Clip Content Outside the Stage, panel icons in docks collapsed to icons (ADR 0087) | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
| `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, 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 (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
| `crates/svg/fixtures/soft-masks-text-paths.svg` | SVG import test drawing (an alpha and a luminance mask, text on a path) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/*.svg` except `anicraft-*` (37 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons, plus, trash, copy, ellipsis) | 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 (`volume-2.svg` from Lucide 0.512.0; `plus.svg`, `trash.svg`, `copy.svg` and `ellipsis.svg` from Lucide's `main` branch, 2026-11) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
| `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) |
| `packaging/macos/dmg/` (`background.tiff`, `dmg-layout.DS_Store`) | macOS DMG window background and Finder layout | AniCraft contributors | Original work drawn by `packaging/macos/dmg/generate.py` in the app icon's colours; layout approach as in the PhotoCraft sibling project | MIT OR Apache-2.0 |
| `docs/guide/images/` (8 screenshots) | User guide (Help › User Guide) | AniCraft contributors | Original work: AniCraft's own screenshots, taken by `scripts/guide-shots.sh` | MIT OR Apache-2.0 |
| `docs/images/` (screenshots and `sample-animation.gif`) | README | AniCraft contributors | Original work: AniCraft's own screenshots (`--screenshot`) and sample animation (`anicraft-cli gif`) | MIT OR Apache-2.0 |
| 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 |
| Interactive sample (menu, Play button, spinner) | File › New from Sample (`which: interactive`), Test Movie tests and screenshots | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`, `interactive`) | MIT OR Apache-2.0 |
| Built-in templates (Leaderboard and Rectangle banners, Social square, Storyboard 16:9, Character turnaround, Lip-sync mouth chart: guides, layers, labels and placeholder mouth shapes) | File › New from Template and the start screen (ADR 0065) | AniCraft contributors | Original work, generated in code (`crates/doc/src/templates.rs`); sizes and safe areas follow public conventions (the IAB's 728 × 90 and 300 × 250 ad units, EBU R 95's 93 % action-safe and 90 % title-safe areas), the mouth set the common phoneme groups animators use | MIT OR Apache-2.0 |
| Colour theme | UI | AniCraft contributors | Original work (`src/theme.rs`) | MIT OR Apache-2.0 |
| `docs/brand/artcraft-logo-white.png` | ArtCraft brand mark (wordmark, light ink for dark backgrounds) | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`), not open source |
| `docs/brand/artcraft-logo-white.svg` | ArtCraft brand mark (wordmark, light ink for dark backgrounds) | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`), not open source |
@@ -44,6 +47,7 @@ shaders or SDK code).
| File | Use | Author | Source | Licence |
|---|---|---|---|---|
| `crates/xfl/tests/corpus/` (12 XFL packages: XML, `.xfl` proxies, a publish-settings file in `scripts/`, `bitmaps/LIBRARY/art/checker.png` and `sunset.jpg`) | XFL import corpus (never shipped in the app) | AniCraft contributors | Original work, written by hand from the public description of the XFL format; the two images made for it (a 16×16 checker drawn in a script, and a 32×16 ramp encoded to JPEG with ffmpeg) | MIT OR Apache-2.0 |
| `crates/xfl/tests/corpus/sounds/` and `video/` media (`beep.wav`, `theme.aif`, `voice.wav`, `bin/M 3 1.dat`, `screen.flv`, `bin/M 4 2.dat`; `tone.mp3` is a copy of the audio crate's fixture below) | XFL sound and video import corpus (never shipped in the app) | AniCraft contributors | Original work, made by a script for these tests: an 880 Hz beep, an AIFF header, one block of silent IMA ADPCM, bytes in no known format, a 64×48 four-colour Screen Video key frame, an FLV header naming On2 VP6 (ADR 0086) | MIT OR Apache-2.0 |
| `crates/xfl/tests/corpus/*/golden/*.png` (20 frames, 160×90) | Golden renders of the corpus | AniCraft contributors | Original work: AniCraft's own CPU renders of the corpus (`UPDATE_GOLDENS=1`) | MIT OR Apache-2.0 |
| `crates/audio/tests/data/tone.ogg`, `tone.mp3` | Decoder tests (never shipped in the app) | AniCraft contributors | Generated for these tests: half a second of a 440 Hz sine made by ffmpeg's `sine` source, encoded with libvorbis and libmp3lame | MIT OR Apache-2.0 |
@@ -78,45 +82,65 @@ 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. |
| Tile binning with per-row backdrops; per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (<https://github.com/linebender/vello>, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019). |
| Tile binning with integer backdrops and left-edge steps ("y-edges"); per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (<https://github.com/linebender/vello>, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019, ADR 0048). |
| Tile binning on the GPU: count, prefix sum, scatter, per-tile lists | `crates/gpu/src/gpu_binning.rs`, `crates/gpu/src/bin.wgsl`, `crates/gpu/src/scan.wgsl` | The binning stages described for *Vello* (above) and Patrick Walton's *Pathfinder* (<https://github.com/servo/pathfinder>, Apache-2.0 OR MIT) design posts; the work-efficient scan of G. E. Blelloch, *Prefix Sums and Their Applications* (CMU-CS-90-190, 1990) | Our own arrangement (one invocation per row of a fill's tiles, no atomics) written from the public descriptions; no code or shaders copied (ADR 0048). |
| Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). |
| Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), <https://cldr.unicode.org>, Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. |
| Stage elements as a multi-select list box; menu bar keyboard model (Alt/F10, arrows, access keys) | `src/stage_a11y.rs`, `src/menus.rs` | W3C *WAI-ARIA Authoring Practices Guide*, Listbox and Menubar patterns, <https://www.w3.org/WAI/ARIA/apg/> (W3C Software and Document License) | Keyboard behaviour learned from the published patterns; no code or text copied. |
| Desktop integration of an AppImage: desktop entry `Exec` quoting and string escapes, MIME packages, hicolor icons, the user's data folder | `crates/engine/src/cmds_desktop.rs`, `src/platform.rs` | freedesktop.org *Desktop Entry Specification* 1.5, *Shared MIME-info Database*, *Icon Theme Specification*, *XDG Base Directory Specification*, <https://specifications.freedesktop.org/>; AppImage documentation on `$APPIMAGE` (public docs) | Written from the specifications (ADR 0094); no code copied. |
| Reading the desktop's contrast setting | `src/platform.rs` | *XDG Desktop Portal*, Settings interface, `org.freedesktop.appearance` `contrast` key, <https://flatpak.github.io/xdg-desktop-portal/> (LGPL documentation, read only; nothing bundled or linked) | One value read through the `gdbus` tool. |
| Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). |
| 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. |
| Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs`, `crates/gpu/src/fine.wgsl` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. |
| Adjust Color filter (brightness, contrast, saturation and hue as colour matrices) | `crates/render/src/filters.rs` | Paul Haeberli, *Matrix Operations for Image Processing* (Silicon Graphics, 1993) | Public description; standard matrix operations. |
| Colour effects (per-channel multiply and offset; brightness and tint as such transforms) | `crates/doc/src/color_effect.rs`, `crates/gpu/src/fine.wgsl`, `crates/render/src/svg.rs` | Adobe, *ActionScript 3.0 Reference: flash.geom.ColorTransform* (public documentation); W3C *Filter Effects Module Level 1*, `feColorMatrix` | Behaviour learned from the public descriptions; no code or assets used (ADR 0056). |
| Blur, drop shadow and glow by repeated box blurs | `crates/render/src/filters.rs` | Standard image processing (repeated box filters approach a Gaussian, central limit theorem) | Public; no specific implementation followed. |
| Bevel and Gradient Bevel by offset differences of the blurred opacity; Gradient Glow and Gradient Bevel through a colour ramp | `crates/render/src/filters.rs` | Standard image processing: embossing as the difference of an image offset along the light direction (a directional derivative; e.g. R. C. Gonzalez & R. E. Woods, *Digital Image Processing*); parameters and behaviour from Adobe's public Animate user guide and ActionScript 3.0 reference (`BevelFilter`, `GradientGlowFilter`, `GradientBevelFilter`) | Public descriptions only; no Adobe code or assets (ADR 0025). |
| Bevel and gradient filters in SVG export (`feComposite` arithmetic, `feComponentTransfer` tables) | `crates/render/src/svg.rs` | W3C Filter Effects Module Level 1 / SVG 1.1 filters | W3C Royalty-Free Patent Policy. |
| Timeline playback semantics for actions (stop, play, go to frame or label, next/previous frame and scene; button Up/Over/Down/Hit states; mouse events) | `crates/actions`, `crates/doc/src/player.rs` | Behaviour learned from Adobe's public *ActionScript 3.0 Reference* (`MovieClip`, `SimpleButton`, `MouseEvent`) and the public Animate user guide on buttons, plus observation (ADR 0013, ADR 0024) | Clean room: no Adobe code, SDKs or players; names used nominatively. |
| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the action IR | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `EventDispatcher.addEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. |
| Seeded `Math.random()` for the player (xorshift128) | `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | G. Marsaglia, "Xorshift RNGs", *Journal of Statistical Software* 8(14), 2003 (public paper); 53-bit doubles from two 32-bit outputs as the common construction | Our own implementation of a published algorithm. |
| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the script IR, the evaluator (types, coercions, operators, `Math`, listeners for enter-frame and keys) | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `Event`, `KeyboardEvent`, `flash.ui.Keyboard`, `Math`, `EventDispatcher.addEventListener` and `removeEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. |
| 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. |
| Ease presets: In/Out/In Out of Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic | `crates/doc/src/easing.rs` | The classic public easing equations (R. Penner, *Programming Macromedia Flash MX*, 2002, ch. 7, "Motion, Tweening, and Easing"; widely republished); Animate's set of eases from its public user guide | Our own implementation of the formulas (ADR 0081); Circ's curve drawn as circular arcs by the standard cubic arc approximation (handle length 4/3·tan(θ/4)). |
| Marching-squares contour tracing (Paint Bucket regions, Brush outlines) | `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. |
| ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs`, `crates/xfl/tests/support/fla.rs` | PKWARE APPNOTE.TXT 6.3 (published ZIP specification), the Info-ZIP Unicode path extra field (0x7075, Info-ZIP `proginfo/extrafld.txt`); CRC-32 by slicing by 8 (M. Kounavis and F. Berry, "A Systematic Approach to Building High Performance Software-based CRC Generators", IEEE ISCC 2005); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries, ZIP64, data descriptors, CP437 and UTF-8 names; no encryption (ADR 0054). |
| ZIP archive writing (web Publish) | `crates/engine/src/publish.rs` (`zip`) | PKWARE APPNOTE.TXT 6.3; the CRC-32 above | Stored entries with UTF-8 names, read back by the reader above in the tests (ADR 0060). |
| JPEG decoding (imported images) | `crates/engine/src/cmds_file.rs` | `zune-jpeg` (MIT OR Apache-2.0 OR Zlib), already in the dependency tree | Decoded to RGBA, kept as PNG. |
| 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). |
| Sound effects, envelopes and embedded video in XFL (`soundEffect`, `SoundEnvelope`, Screen Video stills, FLV) | `crates/xfl/src/import.rs`, `crates/xfl/src/video.rs` | Adobe, *SWF File Format Specification* (version 19), `SOUNDENVELOPE` and `SCREENVIDEOPACKET`, and *Video File Format Specification* (version 10), FLV header and tags (published open specifications); zlib inflate by `miniz_oxide` | Only the layouts are taken; no code or data. Other video codecs are named, not decoded (ADR 0086). |
| Button sounds by state transition (Up→Over, Over→Up, Over→Down, Down→Over) | `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | Adobe, *SWF File Format Specification* (version 19), `DefineButtonSound` (published open specification) | Only the mapping of transitions to the four state frames is taken; no code or data (ADR 0057). |
| 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. |
| SVG document import: shapes, styling and inheritance, transforms, viewBox and preserveAspectRatio, paint servers (gradients), `use` | `crates/svg` | W3C SVG 1.1 (§5, §6, §7, §9, §13) and SVG 2; CSS Color Module Level 3 (colour syntax and names) | W3C Royalty-Free Patent Policy. |
| SVG clip paths, masks and text: `clipPath`, `mask`, `text`/`tspan` positioning and text chunks, white-space handling | `crates/svg/src/clip.rs`, `crates/svg/src/text.rs` | W3C SVG 1.1 (§10, §14) and SVG 2 (§11 Text); W3C CSS Masking Module Level 1; CSS Fonts Level 3 (`font-family`, `font-weight`, `font-size` keywords) | W3C Royalty-Free Patent Policy. |
| Exact clipping of filled paths by a convex polygon | `crates/geom/src/clip.rs` | I. E. Sutherland and G. W. Hodgman, "Reentrant Polygon Clipping", CACM 17(1), 1974, extended to Bézier segments (de Casteljau subdivision, roots bracketed by critical points) | Published algorithm; no code taken. |
| Shape morphing (cubic normalization, subdivision to equal segment counts, winding and start-point alignment) | `crates/geom/src/morph.rs` | Standard curve-blending techniques from the public computer-graphics literature (de Casteljau subdivision, exact degree elevation) | |
| Affine QR decomposition for tweening | `crates/geom/src/affine.rs` | Standard linear algebra | |
| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.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. |
| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`; deleting a raw drawing's point joins its edges, `raw::join`, ADR 0045) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs`, `crates/geom/src/raw.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. |
| Monotone cubic interpolation of stroke widths (width profiles) | `crates/doc/src/width.rs` | F. N. Fritsch and R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 17(2), 1980 | Published algorithm (harmonic-mean tangents). |
| Stroke caps, joins, miter limit and dash patterns (`butt`/`square` caps, miter length and limit, dash arrays restarting per subpath, zero-length round-capped dashes as dots) | `crates/doc/src/stroke_style.rs`, `crates/render/src/stroke.rs`, SVG/HTML/Lottie export, `crates/svg` | W3C SVG 1.1 §11.4 and SVG 2 / CSS Fill and Stroke Module Level 3 (stroke properties); WHATWG HTML canvas line styles; the public Lottie JSON schema (`lc`, `lj`, `ml`, `d`); public descriptions of XFL `SolidStroke`/`DashedStroke`/`DottedStroke` attributes | W3C Royalty-Free Patent Policy; open specifications. |
| Soft masks (alpha and luminance masks, `luminanceToAlpha` coefficients, `mask-type`) and text on a path (`textPath`, `startOffset`, `side`, glyph midpoints on the path, per-character `x`/`y`/`dx`/`dy`/`rotate`) | `crates/render`, `crates/gpu`, `crates/text`, `crates/svg` | W3C CSS Masking Module Level 1 (§7 mask types); W3C SVG 1.1 §10.13 and §14.4, SVG 2 §11.8 (text on a path); W3C Filter Effects (`luminanceToAlpha`); the public Lottie JSON schema (track mattes `td`/`tt`); WHATWG HTML canvas compositing | W3C Royalty-Free Patent Policy; open specifications. Own implementation (ADR 0070). |
| Lottie keyframes and eases (hold keys, cubic Bézier eases with `o`/`i` handles, split position, shape keyframes, group transform order T · R · Skew · S · T(−anchor)); subdividing a cubic at its midpoint (de Casteljau) | `crates/render/src/lottie.rs`, `crates/render/src/lottie_keys.rs`, `crates/engine/tests/lottie_player` | The public Lottie JSON format description (Lottie Animation Community); W3C CSS Easing Functions Level 1 (`cubic-bezier`); de Casteljau's algorithm (public domain mathematics) | Open specifications. Own implementation (ADR 0089). |
| Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. |
| Brush outlines (the swept tip as a signed distance field: exact distance to the convex hull of two tips, L2 for round and L∞ for square tips, minimised in closed form; traced at level zero) | `crates/geom/src/brush.rs` | Standard sweep and distance-field constructions from the public computer-graphics literature; behaviour of Animate's Brush tool learned from Adobe's public help and observation | Own implementation (ADR 0033); no Adobe code or presets. |
| Pen tilt (altitude and azimuth as the brush's angle and width), the paper-grain texture and scattered dabs, width profiles carried through the merge by arc length | `crates/geom/src/brush.rs`, `crates/geom/src/planar.rs`, `crates/doc/src/width.rs` | W3C *Pointer Events* (Level 3: `altitudeAngle`, `azimuthAngle`); value noise from the public graphics literature; SplitMix64's finaliser (S. Vigna, public domain); Gauss–Legendre quadrature (public numerical analysis); tilt behaviour learned from Adobe's public help and observation | Own implementation (ADR 0093); no Adobe code, presets or textures. |
| Pressure curves (monotone cubic through the curve's points: Fritsch–Butland tangents with the Fritsch–Carlson limits), Paint Brush width profiles simplified by Ramer–Douglas–Peucker, the Chalk brush's worn edge (two-octave value noise from SplitMix64's finaliser, subtracted from the brush's distance field) | `crates/geom/src/pressure.rs`, `crates/geom/src/brush.rs`, `crates/engine/src/cmds_brush.rs` | F. N. Fritsch & R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. (1980); F. N. Fritsch & J. Butland (1984); Ramer (1972) and Douglas & Peucker (1973); S. Vigna's SplitMix64 (public domain); value noise from the public graphics literature; brush library behaviour learned from Adobe's public help and observation | Own implementation (ADR 0068); the built-in brushes are AniCraft's own parameter sets, no Adobe presets. |
| Eraser (the swept tip as a fill in the planar merge whose regions are dropped; exact fill areas by Green's theorem with five-point Gauss–Legendre quadrature) and Eyedropper | `crates/engine/src/cmds_erase.rs`, `crates/engine/src/cmds_paint.rs` | Green's theorem and Gauss–Legendre quadrature (public mathematical results); behaviour of Animate's Eraser and Eyedropper learned from Adobe's public help and observation | Own implementation (ADR 0034); no Adobe code or presets. |
| WebAssembly plug-in host (module validation, limits, fuel, resumable host calls) | `crates/plugins` | W3C WebAssembly Core Specification 1.0 / 2.0 (W3C Royalty-Free Patent Policy); the `wasmi` interpreter (MIT OR Apache-2.0) | Host model ported from PhotoCraft's filter plug-ins (same project family and licence) and extended with the AniCraft request ABI (ADR 0017). |
| Selection tool on raw shapes: bending an edge (least-squares control-point move), following a bent edge in every shape that shares it, snapping, a marquee that cuts | `crates/geom/src/raw.rs`, `crates/geom/src/planar.rs`, `crates/engine/src/cmds_raw.rs` | Bernstein polynomials and least squares (public mathematical results); behaviour of Animate's Selection tool learned from issue #42, Adobe's public help and observation | Own implementation (ADR 0041); no Adobe code. |
| Inverse kinematics by cyclic coordinate descent (bone drags, `bone.solve`), with joint limits as a clamp per step | `crates/doc/src/armature.rs` | L.-C. T. Wang and C. C. Chen, *A combined optimization method for solving the inverse kinematics problem of mechanical manipulators*, IEEE Trans. Robotics and Automation 7(4), 1991; C. Welman, *Inverse Kinematics and Geometric Constraints for Articulated Figure Manipulation*, MSc thesis, Simon Fraser University, 1993 | Published algorithm; own implementation (ADR 0043). |
| Bone springs: a damped oscillator on each joint driven by the inertia of a pendulum on an accelerating pivot, integrated by backward (implicit) Euler | `crates/doc/src/spring.rs` | L. D. Landau and E. M. Lifshitz, *Mechanics*, §5 and §25 (pendulum with a moving point of support; damped oscillations); E. Hairer and G. Wanner, *Solving Ordinary Differential Equations II: Stiff and Differential-Algebraic Problems*, Springer, 1996 (the implicit Euler method) | Textbook mathematics; own implementation (ADR 0084). |
| Asset Warp: rigid moving-least-squares deformation of a warp mesh's vertices by pins (weights `1 / d²`, the best rotation from the weighted dot and cross of the centred pins), piecewise affine between them | `crates/doc/src/warp.rs`, `crates/render/src/warp.rs` | S. Schaefer, T. McPhail and J. Warren, *Image deformation using moving least squares*, SIGGRAPH 2006, §2.3 | Published method; own implementation (ADR 0079). |
| Linear blend skinning of a shape's outline by its bones (shape armatures: anchors blended by bone weights, handles with their anchors), with weights from the inverse fourth power of the distance to each bone | `crates/doc/src/skin.rs` | N. Magnenat-Thalmann, R. Laperrière and D. Thalmann, *Joint-dependent local deformations for hand animation and object grasping*, Graphics Interface 1988; J. P. Lewis, M. Cordner and N. Fong, *Pose space deformation*, SIGGRAPH 2000, §2 | Published method; own implementation (ADR 0071). |
| Envelope: bicubic Bézier patch warp, inner points from a bicubic Coons patch (ADR 0080) | `crates/geom/src/envelope.rs` | S. A. Coons, *Surfaces for Computer-Aided Design of Space Forms*, MIT Project MAC TR-41, 1967; G. Farin, *Curves and Surfaces for CAGD*, 5th ed., Morgan Kaufmann, 2002 (tensor-product Bézier patches) | Published mathematics; own implementation. |
| De Casteljau subdivision, Ramer–Douglas–Peucker simplification | `crates/geom/src/edit.rs` | Public mathematical results (de Casteljau 1959; Ramer 1972; Douglas & Peucker 1973) | |
| WAV (RIFF WAVE) reading and writing: PCM 8/16/24/32-bit, IEEE float, `WAVE_FORMAT_EXTENSIBLE` | `crates/audio/src/wav.rs` | Microsoft/IBM, *Multimedia Programming Interface and Data Specifications 1.0* (1991), and Microsoft's public `WAVE_FORMAT_EXTENSIBLE` description | Public file format descriptions. |
| Resampling by cubic Hermite (Catmull-Rom) interpolation | `crates/audio/src/mix.rs` | E. Catmull and R. Rom, *A class of local interpolating splines* (1974); R. Keys, *Cubic convolution interpolation for digital image processing* (1981) | Public mathematical results. |
| Ogg Vorbis decoding | `crates/audio/src/vorbis.rs` | `lewton` (MIT OR Apache-2.0) with `ogg` (BSD-3-Clause); Xiph.Org's open, royalty-free Vorbis I specification | Used as a library, not copied. |
| MP3 (MPEG-1/2 audio layers I–III) decoding | `crates/audio/src/mp3.rs` | `nanomp3` (MIT OR Apache-2.0), a port of minimp3 (CC0) | Used as a library. The MP3 patents have expired; decoding only, no encoder. |
| Animated PNG and animated WebP files: APNG chunks (`acTL`, `fcTL`, `fdAT`), frame regions, blend and dispose ops; the WebP RIFF container (`VP8X`, `ANIM`, `ANMF`) | `crates/engine/src/anim.rs` | The APNG specification (Mozilla; part of W3C *Portable Network Graphics (PNG) Specification*, Third Edition); Google's public *WebP Container Specification* and *WebP Lossless Bitstream Specification*; PNG frame data by the `png` crate (MIT OR Apache-2.0), lossless WebP frames by `image-webp` (MIT OR Apache-2.0) | Open, royalty-free specifications; the chunks are written by our own code (ADR 0063). |
## Rust dependencies
+884 -4
View File
@@ -3,6 +3,886 @@
## Unreleased
* **Security: safer reads and temp files.** Import to Library checks an image's size (256 MiB) before reading it, and saves, audio exports and the video soundtrack write their temporary files under unguessable names, created exclusively.
* **Saved commands (command macros)** (ADR 0097, M6).
* In the **History** panel, **Ctrl+click** steps (Shift+click a range) and choose **Save As
Command…**: the steps come back at the end of the **Commands** menu, to run on whatever is
selected as **one undo step**. Steps that name a layer or object of this document act on the
active layer or the selection instead; a step that can't be kept (the clipboard, particular
path points or Library items) is named with the reason.
* A run that fails at a step changes nothing and says which step stopped it.
* **Commands › Manage Saved Commands…**: run, reorder, rename, delete, give a **shortcut** (the
Keyboard Shortcuts editor, under Commands) and add one from a file. **Commands › Run
Command…** runs a saved command file.
* Saved commands are small JSON files in the settings folder's `Commands`, easy to share. They
may do only what a plug-in may (no files, clipboard or preferences), and plug-ins can't run
them. `anicraft-cli run` takes them; `macro.*` commands work headless and over MCP.
* **Search the user guide, and help for what you are working on** (ADR 0096, M8).
* **Search** in every page of the bundled guide, offline: results as you type with the
chapter, heading and a passage with your words marked; `/` goes to the field, arrows move
through results, Enter opens one. `anicraft-cli guide search <words>` prints the same results.
* **F1** opens the guide at the section for the dialog in front, the panel or tool under the
pointer, the focused panel or the tool in hand (F1 on the Bone tool: building an armature).
Also **Help › Help for This**, **Help › Search the User Guide**, **? Help for…** in every
panel menu, and F1 on a command in the command palette.
* The keyboard shortcut editor moves from F1 to **Ctrl+Alt+Shift+K**, as in Animate.
* A new chapter, **Using this guide**.
* **Sound output polish** (ADR 0095, M5).
* The playhead follows the sound being **heard**: the device's latency is taken off and slow
frames are dropped rather than drifting (within a frame over an hour of play in tests).
* **Event sounds play to their end** when Loop Playback goes round and after the playhead stops
on the last frame; pressing Enter stops all sound.
* **Volume and mute** in the timeline header (also **Control › Mute Sounds** and **Preferences ›
Sound**): for listening only, kept in your preferences, never in exports.
* **Control › Audio Scrubbing** turns scrubbing off or on; a scrub plays at least 1/20 s.
* No sound device, or one unplugged mid-play, never crashes: playback carries on silently with a
notice and a log line, and the next play opens the device again.
* The **web version plays sound** through Web Audio.
* **Portable copies and AppImage desktop integration** (ADR 0094, M8).
* **The Windows zip and the Linux tar.gz are portable**: preferences, autosaved work, logs,
plug-ins, templates, brushes, filter presets, workspaces and recent files stay in a `data`
folder beside AniCraft. A file named `anicraft-portable` next to the program (or next to
`AniCraft.app` or an `.AppImage`) is what makes a copy portable; delete it to use your user
folder. A portable folder that can't be written falls back to your user folder and says so.
* **Preferences › About** shows the version, whether this copy is installed or portable, and
every folder AniCraft keeps things in, each with an Open button.
* **AppImage: Add to Menu.** The first start from an AppImage offers once, in a card that
nothing waits on, to add AniCraft to your applications menu and open `.anicraft`, `.fla` and
`.xfl` files with it. Only `~/.local/share` changes; Preferences › About removes it again,
and the entry follows the AppImage when you move or update it. Headless:
`desktop.integrate`, `desktop.remove`, `desktop.status`.
* **Store readiness:** a Packaging lint job validates the Flatpak manifests, the AppStream
metainfo (`appstreamcli validate`), the desktop entry and any winget or MSIX manifests.
Nothing is submitted.
* **Brushes and erasing, second slice: tilt, textured brushes, erasing inside symbols, profiles
in the merge** (ADR 0093, M7).
* **Pen tilt** shapes the Brush: it turns the tip with the way the pen leans and paints up
to twice as wide as it lies down (the Paint Brush too). A mouse is never affected. Desktop
systems don't pass tilt on to AniCraft yet, so the Tilt options stay hidden in Properties
until a pen reports it; scripts and MCP send it in `draw.brush` points as
`[x, y, pressure, altitude, azimuth]`.
* **Textured brushes**, still vector: **Texture** lets a fixed paper grain show through the
paint, **Scatter** throws dabs either side of the stroke. New built-in brushes **Charcoal**
and **Spatter**.
* **Variable-width lines are merged drawing**: a line across one, or the Eraser, cuts it, and
each piece keeps the widths it had there. Pressured Paint Brush lines are raw now.
* **Erased gradients** keep their gradient in place in every piece.
* **Erasing inside symbols**: open a symbol or drawing object (double-click) and the Eraser
erases its lines and fills; on the stage it keeps them and the status bar says how.
* Fix: the curve fitter could send a handle far off on a tiny, nearly closed stretch.
* **Surviving graphics card failures, and filters in the Motion Editor** (ADR 0092, M3).
* **The stage keeps drawing when the graphics card fails mid-session**: the CPU takes it over
at once, the status bar says so, and the graphics card is tried again after 3, 15, 60 and
300 seconds (sooner when the window is resized). Preferences › Stage says why.
* **A graphics driver error no longer closes AniCraft** (#255: `Surface::configure` "Failed to
wait for GPU to come idle"): the error goes to the log, unsaved work is autosaved at once,
and a surface that fails is reconfigured, then made anew. If the window loses its graphics
device, AniCraft saves the work, reopens the window a safer way and offers the work back;
the next three starts try that safer way first (#207).
* **Filters animate in the Motion Editor**: each filter of a movie clip in a motion tween lists
its numbers (Blur X/Y, Strength, Angle, Distance, Adjust Color's four) under its name, with
curves, keys, eases and retiming like the other properties. Changing a filter in Properties
with the playhead inside the tween keys it; reordering or removing filters takes their keys
along. Headless: `motion.set_key {"property": "filter.0.blur_x", …}`; files keep the tracks
under `filter_tracks`, so older builds still open them.
* **Shape armatures, second slice: painted weights and reshaping** (ADR 0090, M7).
* The **Bind** tool's **Paint Weights** (Properties › Bone) brushes a bone's influence onto
the points of its shape: **Add**, **Subtract** or **Smooth**, with a size (`[` and `]`)
and a strength, fading to the brush's rim. The bone's share shows live as a heat map on the
outline and its points, blue (none) to red (all). Each point's weights always add up to
100 %, painted points stay as painted when bones are added, and a stroke is one undo step.
* **Weights as numbers**: Properties › Bone shows a point's share of the bone as a field to
type in, and every bone the point follows. Click a point or type its number.
* **Reshaping a shape with bones**: at the rest pose, Subselection moves, adds, deletes and
converts its points. The bones keep their binding: new points blend their neighbours'
weights, deleted ones drop theirs, and every pose bends the new outline.
* Headless: `bone.paint_weights`, `bone.set_weight`; the `path.*` point commands reshape a
bound shape at rest.
* **Filters, second slice: order, on/off, copy and paste, presets** (ADR 0091, M5).
* **Reorder filters** in Properties › Filters: drag a filter by its grip, or focus the grip
and press Alt+Up/Alt+Down, or right-click for Move Up/Down. The order changes the picture
(filters apply from the top down).
* **Switch a filter off** with its eye: it keeps its settings and draws nothing, on the
stage and in every export (SVG, HTML canvas, Lottie, video, images). Enable All and
Disable All in the **…** menu. Animate files' switched-off filters now come in switched
off instead of being dropped.
* **Copy and paste filters** between movie clips and buttons (Copy All Filters, Copy Filter,
Paste Filters).
* **Filter presets**: Save as Preset…, apply by name (replaces the filters, undoable),
rename, delete (asks), and export or import them as a small JSON file. Presets are kept in
your preferences, for any document.
* Classic tweens keep tweening filter values when a filter is switched off; tests cover a
blur and a glow at a tween's midpoint.
* Headless: `filter.move`, `filter.enable`, `filter.remove`, `filter.copy`,
`filter.paste`, `filter.preset_list/save/apply/rename/delete/export/import`, and
`enabled` in `element.set_filters`.
* **Lottie export with real keyframes and eases** (ADR 0089, M4).
* Tweens become **Lottie keyframes with Lottie's own Bézier eases** instead of a key at every
frame: No Ease, Classic Ease, Bézier handles, Quad, Cubic, Back and Bounce, and custom
curves (a key per piece) come across exactly, and the motion is smooth on any screen.
* Objects that move, turn or scale keep their outline and move as a whole (an animated group
transform: position, rotation, skew, scale); shape tweens between outlines of one
structure are shape keys; colours, gradients, strokes, opacity and masks are keyed the
same way.
* Every frame still shows exactly what AniCraft shows: each eased span is checked at every
frame, and what no Lottie ease draws (Elastic, Sine, curved motion guides, tweens inside
tweening symbols) stays frame by frame and is reported once.
* Files are much smaller: the demo 46.7 → 10.4 kB, a 240-frame stress movie 14.5 → 1.45 MB
(and it exports in 360 ms instead of 931 ms).
* A playback parity test plays the exported file with a Lottie player written from the
public format description through the CPU oracle at every frame, for the sample scenes, a
movie of every tween and ease, and the XFL corpus.
* **Plug-ins, second slice: export formats and eases** (ADR 0088, M6).
* **Export-format plug-ins** appear in **File › Export** below the built-in formats. Their
**Export** window has the plug-in's options, the frames and the file, then a progress bar
and **Cancel** while the export runs in the background. The plug-in gets the movie's
evaluated frames, never the document, and AniCraft writes the file it returns (at most
64 MB). Replacing a file asks first.
* **Ease plug-ins** add eases to every ease menu, under **Plug-in eases**. AniCraft samples
each ease once when the plug-in loads, and a tween keeps the curve, so the movie plays the
same without the plug-in.
* Hostile plug-ins stop with a clear message: endless loops, huge or misplaced output, eases
that give NaN, leave −10..10 or miss 0 and 1 at their ends.
* Samples: **Plain Text Frames** (an exporter) and **Stepped Eases** (Stepped 2, 4, 8, Smooth
Steps 4), built and run in CI; the guest SDK gains `exporter!`, `ease!`, `movie()` and
`frame()`.
* Headless: `file.export_plugin`, `file.export_formats`, `{"plugin", "ease"}` and
`{"sampled"}` easing params, plug-in eases in `ease.list`; `anicraft-cli export --format
<id>` (built-in formats too) and `anicraft-cli formats`.
* **Dockable panels, second slice** (ADR 0087, M8).
* **The tools move like any panel**: drag the grip at the top of the tools (or use its
menu) to put them in a slim bar on any side, as a tab in a dock (laid out in as many
columns as fit), or floating. Older preferences keep them on the left.
* **Floating windows hold several tabs**: drop a tab on a floating window, or use the panel
menu's **Stack With**. **Drag a floating window back into a dock** by its grip (or its
title bar inside the editor), with the same drop targets as a tab; **Dock** puts each
panel back where it came from.
* **Docks collapse to icons**: the » button (or the panel menu) shrinks a dock to a strip
of panel icons, names as tooltips; a click opens the panel over the stage, Esc or a click
outside closes it. Ctrl+F6 and the Window menu reach panels there.
* **Manage Workspaces…**: rename and delete your own workspaces (delete asks with a second
click); built-in ones can be reset but not deleted.
* **Panels fit narrow docks**: at the narrowest side dock (now 200 pt) form rows put their
value under the label and fields shrink, so nothing runs off the edge (Properties' "Snap
to objects", the stage size, the Align buttons and "To stage" did); a test checks every
panel at that width in English and the pseudo-locale. Long section titles end in "…".
* Fixed: clicking a tab above or below the stage could start a drag instead of showing it.
* **Animate files: sounds, videos and more archive layouts** (ADR 0086, M4).
* Frame sounds keep their **effect**: Left or Right Channel, the fades, or a custom envelope.
* Sounds and videos that don't come across are **named in the report** with the reason
("theme.aif: AIFF", "voice.wav: WAV in IMA ADPCM", "intro.flv: FLV, On2 VP6, 4.5 s");
`file.open` returns them as `named`.
* A **Screen Video** comes in as a still of its first frame, in the Library and where the
video was placed; other videos are named with their format and length.
* A **zipped XFL folder** (one top folder, `__MACOSX` ignored) and a **self-extracting
archive** renamed to `.fla` open like any `.fla`.
* The corpus gains `sounds` and `video` packages and six archive layouts.
* **Motion Editor and timeline retiming** (ADR 0083, M2).
* **Moving keys in time** in the Motion Editor: drag a key sideways. It snaps to frames and
stops next to its neighbours, and the value and ease go with it. Shift-click picks keys
across properties, the new **All** lane picks every property's keys on a frame, and with
the curve focused Left and Right (Shift: ten frames) move the picked keys. One undo step
per drag.
* **Stretching tweens**: dragging a span's end stretches a motion tween's property keys in
proportion, as in Animate (Shift keeps them in place). Classic and shape tween spans
stretch too.
* **Moving and copying tween spans**: a click picks a whole motion tween span, and dragging
it (or a selection of whole tween spans) moves it at its length. **Alt-drag** copies it.
* **Split Motion** and **Join Motion** in the span's context menu and in Modify ›
Timeline. Splitting and then joining gives the original tween back.
* **Dock tabs** never run under a panel's menu button: they shrink with an ellipsis (the
full name is in the tooltip), and at the narrowest the strip scrolls.
* Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`,
`motion.split`, `motion.join`.
* **Bones, second slice: springs, joint translation and editing members** (ADR 0084, M7).
* **Joint translation**: Properties › Bone › X/Y translation lets a joint slide along the
axes of what the bone starts on, freely or within limits (pixels). Slides are part of each
pose and tween with it; the Selection tool's IK turns joints first and slides them only to
reach where turning can't.
* **Springs**: per-bone Spring (strength) and Damping, 0 to 100. A sprung bone lags behind
and swings past its pose as the bones it hangs from move, then settles, chaining down a
tail. Evaluated as a pure function of the motion up to the frame (no stored state, bounded
replay of at most six seconds), so seeking equals playing bit for bit, and the stage, Test
Movie and every export show it. Springs: Enable turns an armature's springs off for posing.
* **Members edited in place**: picking a bone selects the instance it moves; its colour
effect, blending and filters change on every pose, one undo step, the armature intact.
* Headless: `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`, `slide_x` /
`slide_y` on `bone.pose`; `bone.info` reports slides, springs and each bone's swing.
* **Ease presets, custom eases and saved eases** (ADR 0081, M7).
* One ease menu in the timeline header, Properties › Frame and the Motion Editor: No Ease,
**Classic Ease** with a strength, and **Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce
and Elastic**, each In, Out and In Out, drawn as curves; then your saved eases.
* **Custom Ease** window: click the curve to add a point, drag points and handles (one undo
step per drag), double-click for smooth or corner, right-click to delete, type a point's
time and value, or use the keyboard (`[` `]`, arrows, `S`, `+`, Delete). Overshoot is
allowed; time never runs backwards.
* **Saved eases** live in the document and are offered to every classic tween and Motion
Editor property; **Copy Ease** / **Paste Ease** carry an ease between tweens.
* Classic tweens can **ease each property separately** (position, rotation, scale, colour,
filters), and instance filters now tween.
* Animate files: custom eases of several segments and per-property eases import exactly.
* Headless: `ease.info`, `ease.set`, `ease.add_point`, `ease.move_point`, `ease.move_handle`,
`ease.delete_point`, `ease.convert_point`, `ease.separate`, `ease.save`, `ease.delete`,
`ease.rename`, `ease.list`, `ease.copy`, `ease.paste`; `timeline.set_easing` takes `group`
and every ease (`{"saved": name}`, `{"custom": …}`).
* **Camera, second slice: layer depth, attaching layers and colour** (ADR 0082, M7).
* **Layer depth in perspective**: through the camera, a pinhole with a fixed focal length
(1,000 px), a deeper layer moves less when the camera pans and grows less when it zooms;
deeper layers draw behind nearer ones (ties in timeline order). The camera at rest shows
every layer as drawn, and depth 0 is bit-for-bit what it was. A layer the camera has passed
isn't drawn.
* **Depth over time**: key a layer's depth on any frame; it tweens linearly between keys.
* **Window › Layer Depth**: the layers by depth, nearest first, each with a track to drag
nearer or farther, its value, a key diamond and Attach.
* **Attach Layer to Camera**: a camera toggle on each layer's timeline row; an attached layer
stays where it is on screen while the camera moves (titles, HUDs).
* **Camera colour effects**: Brightness, Tint and Advanced (no alpha), in Properties and
`camera.set`, tweened, in every export.
* **Editing while previewing**: with View › Preview Through Camera the Selection tool picks
and moves artwork where the movie shows it, mapped back through the camera and the layer's
depth.
* Every export (PNG, sequences, GIF, video, SVG, Lottie, HTML canvas), Test Movie and the GPU
stage see the same picture. Headless: `layer.set_depth {key, frame}`,
`layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view:
camera}`; `camera.info` reports `color_effect`.
* Changed: depth now also scales under the camera's zoom (it was pan-only); files with a
depth and a zoomed camera look different.
* **Drawing parity leftovers** (ADR 0080, M1).
* **PolyStar options**: Shape (**Polygon** or **Star**), **Sides**/**Points** (3 to 32) and
**Point size** (0 to 1; at 1 a star is the polygon through its tips) in the tool's options.
It merges or draws objects like the other shape tools.
* **Paint Selection** and **Paint Inside** brush modes: the paint is clipped exactly to the
selected fills, or to the fill (or the empty area closed off) where the stroke starts, and
never covers lines. Paint Selection keeps the selection for the next stroke.
* **Double-click a drawing object** (or Ctrl+E) to edit it in place, as groups and symbols
open: inside, its raw shapes merge only with each other. It closes as one drawing object
again; opening and closing it without an edit changes nothing.
* **Modify › Transform › Envelope**: corner and tangent handles bend the selected shapes and
drawing objects through a Bézier patch, one undo step per drag. Like Animate, the bend is
baked into the shapes, so there is no Delete Envelope.
* Headless: `shape`, `sides`, `point_size` on `draw.star`; `selection` and `inside` modes on
`draw.brush`; drawing objects on `symbol.edit`; `modify.envelope`,
`modify.envelope_move`, `modify.envelope_close`.
* **Asset Warp** (M7, ADR 0079; refs #213).
* **Added**: the **Asset Warp** tool (**Shift+Q**). Click a shape or a bitmap to pin it (the
first pin covers it with a warp mesh), drag a pin to bend the artwork around the others,
live, one undo step per drag; Delete removes the picked pin. Bending is rigid moving least
squares, so the artwork stays as rigid as it can near the pins.
* **Added**: pin poses per keyframe, tweened with classic tweens and their easing; a pin added
later lands on every keyframe of the artwork. Properties › Asset Warp sets the mesh's
resolution and removes pins or the whole warp (also in Modify › Asset Warp).
* **Added**: bitmaps bend in the renderer and on the GPU stage (the same prepared image, so
they match exactly) and in every raster export; SVG writes a bent bitmap as an image; HTML
and Lottie report it. Warped shapes are bent outlines everywhere.
* **Added**: commands `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`,
`warp.remove` and `warp.info`, for scripts, plug-ins, the CLI and MCP.
* **Swatches panel** (M1, ADR 0078).
* **Added**: **Window › Swatches**, the document's saved colours and gradients, saved in the
document (new documents and older files start with a default set). Click a swatch to apply
it to the selection and the tool colour, to the stroke or the fill, whichever is active
(the Tools panel's and Colour panel's squares choose, or the panel's own toggle); gradients
go to the fill. Add the current colour or gradient, Duplicate, Delete, drag to reorder
(Alt+arrows from the keyboard), names on hover, Clear and Load Default Swatches. Every
change is one undo step.
* **Added**: Import and Export Swatches as a small JSON swatch file, and import of GIMP `.gpl`
palettes. Adobe's `.aco`, `.ase` and `.clr` are proprietary and not read.
* **Added**: the colour picker shows the document's swatches, and the fill picker its gradient
swatches.
* **Added**: commands `swatch.list`, `swatch.add`, `swatch.remove`, `swatch.move`,
`swatch.duplicate`, `swatch.rename`, `swatch.apply`, `swatch.clear`, `swatch.reset`,
`swatch.import` and `swatch.export`, for scripts, the CLI and MCP (plug-ins may edit swatches
but not read or write swatch files).
* **Fixed**: the timeline's layer footer cut **Delete** to "Del…" at the default window size
since docking. Its buttons are now icon buttons (New Layer, Delete, New Folder, Up, Down),
named for screen readers, that fit at any size and in any language.
* **Rulers, grid and guides** (ADR 0076, M1).
* **View › Rulers** (**Ctrl+Alt+Shift+R**): rulers along the top and left of the stage, in
pixels from its corner, following zoom and pan and marking the pointer.
* **Guides**: drag one out of a ruler; drag it with the Selection tool to move it, or back
onto a ruler to delete it. Each scene keeps its guides in the document. **View › Guides**:
Show (**Ctrl+;**), Lock (**Ctrl+Alt+;**), Snap to Guides (**Ctrl+Shift+;**), Edit Guides
(**Ctrl+Alt+Shift+G**: colour, accuracy, and every guide by position, so the keyboard can
add, move and delete them), Add Guide and Clear Guides.
* **Grid**: **View › Grid** › Show Grid (**Ctrl+'**), Snap to Grid (**Ctrl+Shift+'**), Edit
Grid (**Ctrl+Alt+G**: spacing, colour, show over objects, accuracy up to Always snap).
* **Snap to Pixels** in View › Snapping, next to Snap to Objects, Grid and Guides.
* One snap engine for every drawing tool, the Selection tool's moves (symbols, text and
bitmaps now snap by their box's corners and centre) and Free Transform's handles, in a
fixed order: point, guide, line, grid, pixel.
* Shown on the stage only, never in Test Movie or exports.
* Headless: `view.*` commands (`view.guide_add`, `view.grid_set`, `view.guides_clear`, …)
and `view.aids`.
* **A light theme** (ADR 0077, M8). Fixes #227.
* **Preferences › Appearance › Theme** offers **Light** beside **Dark (Graphite)** and **High
contrast**: light grey panels, near-black text, hairline-edged buttons and fields, soft
shadows, and the timeline's mint, violet, amber and sky blocks in deeper tones made for a light
background. Applied as you click, no restart.
* **Follow system** now follows your system's light or dark mode as well as its
contrast setting: Windows' app mode, macOS' Appearance, the Linux desktop's colour scheme and
the browser's `prefers-color-scheme`. The window's title bar follows too.
* `anicraft --theme light` (also `dark`, `high-contrast`) previews a theme for one run.
* Every palette is checked by the contrast test (WCAG AA text, 3:1 controls and focus).
* **Gradient editor, the Gradient Transform tool and Lock Fill** (M1, ADR 0074; #208, #203).
* **Added**: gradients in the colour picker. The fill's picker (the Tools panel's Fill square,
and every Fill swatch in Properties) starts with the fill's type: None, Solid, Linear,
Radial or Bitmap. A gradient shows a bar of colour stops (click to add, drag to move, drag
off to remove; arrow keys and Delete on a focused stop), overflow (Extend, Reflect, Repeat),
Linear RGB and a radial gradient's focal point, above the same swatches, mixer and hex
field, which then set the picked stop's colour and opacity. A gradient's swatch in
Properties shows its ramp. One picker, as Animate has one Color panel; the fill's No Colour
is its type None.
* **Added**: the **Gradient Transform** tool (**F**): move, turn, stretch and resize a gradient,
move a radial gradient's focal point, and scale, turn and skew a bitmap fill. Each drag is
one undo step.
* **Added**: **Lock Fill** for the Paint Bucket and the Brush. Without it, gradients and bitmaps
are fitted to each shape, as in Animate; the Eyedropper turns it on for what it picks.
* **Added**: commands `paint.set_fill`, `paint.transform_fill` and `paint.lock_fill`, for
scripts, the CLI and MCP.
* **Improved**: gradients keep their overflow, Linear RGB, focal point and elliptical shape
from Animate files and SVG drawings, on the GPU stage and in SVG export (HTML canvas draws
them as near as canvas can). Radial gradients on skewed shapes are now drawn exactly.
* **Dockable panels and workspaces** (M8, ADR 0075, fixes #249).
* Drag any panel's tab to dock it on any side of the stage (the timeline above the stage, for
example), stack it with other panels as a tab, or float it in a window of its own (inside
the editor where a system can't open one). Docks and the lines between panel groups resize,
groups fold, and every panel has a menu (☰, or right-click its tab) to dock, float or close
it from the keyboard.
* **Window** lists every panel; choosing one brings it forward, reopening it where it was.
* **Window › Workspace**: Essentials (the layout so far), Animator and Designer, your own with
**Save Workspace…**, and **Reset**. Where everything is is kept in your preferences.
* New **Colour** (stroke and fill, Swap, Black and White) and **Output** (Test Movie's lines,
kept after it closes) panels. Ctrl+F6 visits every docked panel in the order they are docked.
* **Groups and Combine Objects** (ADR 0073, M1; issues #206, #229).
* **Modify › Group** (**Ctrl+G**) and **Ungroup** (**Ctrl+Shift+G**): keep artwork together
without a Library symbol. Double-click a group to edit it in place (the rest dims, the edit
bar says `Scene 1 › Group`); groups nest; merged drawing inside a group only cuts and joins
the shapes in that group. Ungroup puts everything back exactly where it showed. Break Apart
on a group ungroups it.
* **Modify › Combine Objects › Union, Intersect, Punch, Crop** on two or more selected shapes,
with the exact geometry of merge drawing.
* **Selection tool**: **Alt-drag** (Option-drag) to drag a copy away; **Shift** keeps a move
horizontal, vertical or at 45°.
* **Break Apart** on a group ungroups it; its merged drawing merges with the drawing below.
* Animate files keep their groups (`DOMGroup` used to be flattened).
* Headless: `modify.group`, `modify.ungroup`, `modify.combine {op}`, `symbol.edit {id}` on a
group.
* **Fixed: start-up, files and display, from user reports** (M8).
* Fixed: Flash files that opened in 0.1 no longer opening (#226). One damaged or unreadable
part of a `.fla` (a bitmap, a sound, a library symbol) no longer stops the whole file from
opening: the rest opens and the report says what was left out. A file double-clicked or
opened with **Open With** that can't be opened now says why in the status bar instead of
quietly showing the sample, and `anicraft-cli info`, `render` and the export commands open
`.fla` and `.xfl` files too.
* Fixed: Animate documents opening on a black stage instead of white (#163).
* Fixed: AniCraft not opening at all on some laptops with two graphics chips, such as the
Surface Book 2 (#207). If a way of drawing the window fails, AniCraft now tries the next one
(on Windows: DirectX 12 on the built-in chip, then OpenGL) instead of exiting, and a start that
crashed inside a graphics driver tries that way last next time. If nothing works, a message
says so. A start-up log in the settings folder (`Logs/anicraft.log`) records what was tried,
to attach to a bug report.
* New: **Preferences › Stage › Window graphics** chooses how the window is drawn (Automatic,
DirectX 12, Vulkan, Metal or OpenGL), for windows that flicker or flash black (#255).
`--renderer dx12`, `vulkan` and `metal` now pick that interface; before, they all meant the
default.
* Fixed: the selection shading on shapes stopping part way down when zoomed in or on a big
shape (#204). The dot pattern now covers the whole shape and its outline at any zoom, and
costs the same however much of the screen it covers.
* The web version's download is now built by `packaging/web/package.sh` and checked in CI; the
README no longer suggests releases carry it yet (#210).
* **Drawing tools and colour fixes from user reports** (M1).
* **Fixed**: the Fill and Stroke colour squares in the Tools panel did nothing when clicked.
They open the colour picker now, with No Colour, and recolour selected shapes (#246).
* **Fixed**: the colour picker had no hex field. Every colour swatch's picker shows the colour
as `#rrggbb` and takes one you type (#201).
* **Fixed**: the colour picker had no web-safe palette. It opens on Animate's 216 web-safe
swatches, with greys and primaries beside them and the colours you mix or type in a row
below; **Mixer** has the full picker (#248).
* **Fixed**: the Pencil's Properties showed a Fill swatch, though the Pencil only draws lines.
The Pencil and the Line tool show only the stroke now (#252).
* **Fixed**: a squiggle drawn with Object Drawing on was trapped in its object. **Modify ›
Break Apart** (Ctrl+B) now turns a drawing object into merged drawing you can edit (#253).
* **Fixed**: the Width tool didn't thicken a line when you dragged on it, the pointer didn't
change, and the marker was a tiny dark box. A drag on the line widens it there, the pointer
is a crosshair (an add pointer over a line), and the marker is a white box with handles
(#250).
* **Fixed**: every new line segment came with a scale gizmo whose handles couldn't be dragged,
and a box appeared after every brush or pencil stroke. As in Animate, what you draw isn't
left selected, and the Selection tool's box no longer shows handles that do nothing (#205,
#243).
* **Fixed**: Ctrl-dragging a shape's edge made a smooth curve. It adds a corner point where you
pressed, with straight sides on a straight edge (#200).
* **Filters, Subtract and Invert in HTML canvas export** (ADR 0072, M6). Exported web pages now
show every filter (Drop Shadow, Blur, Glow, Bevel, Gradient Glow, Gradient Bevel and Adjust
Color, with inner, knockout, hide object and Inner/Outer/Full) and the Subtract and Invert blend
modes as AniCraft draws them, in every browser: the page runs a port of AniCraft's own filters
over the symbol's pixels instead of the browser's effects, and shadows and glows reach onto the
stage from symbols beside it. A filtered symbol that doesn't change is filtered once. Tested
against AniCraft's renderer pixel by pixel (35 filter set-ups at three view scales, within
1/1000) and checked in a browser. At 1080p the demo's filtered symbols cost 3.4 ms a frame while
they change; one covering the whole frame 50 to 150 ms. The export report no longer lists them.
* **Timeline, bones, menus and stage fixes from user reports** (M1).
* **Fixed**: F5 with no frames selected only extended the active layer. It now extends every
layer that has frames at or after the playhead, as in Animate, and leaves the layers that end
before it alone (#242).
* **Fixed**: after F5, F6 or F7 you had to select the next frame by hand. F5 now moves onto the
frame it adds, and F6 or F7 on a keyframe makes the new keyframe on the next frame and moves
there, so draw, F6, draw keeps going (#254). F7 on a keyframe no longer clears its drawing.
* **Fixed**: the timeline's Frame, Keyframe and Blank buttons took a lot of room. They are icons
now (a frame, a filled dot and a hollow dot, each with a plus), named in their tooltips (#240).
* **Fixed**: bone chains looked broken and jumped while posing. A bone started anywhere on an
instance now starts at the end of the bone before it, so the chain stays joined, and dragging
a bone along its length moves it from where you grabbed it instead of snapping its end to the
pointer (#239).
* **Fixed**: on macOS there were no menus (no File, no Save). The title bar covered the menu
row; it is see-through now, as designed (#247).
* **Fixed**: you couldn't draw outside the stage; anything past its edge was hidden. The
pasteboard now shows your artwork, as in Animate, and **Clip content outside the stage**
(beside the zoom menu, and in the View menu) hides it again when you want (#245, #251).
* **Soft masks and text on a path** (ADR 0070, M4).
* **Soft masks**: Layer Properties › **Mask type** on a mask layer: *Shape* (as in Animate),
*Alpha* (the mask's opacity reveals: a gradient to transparent fades the artwork out) or
*Luminance* (the mask's brightness reveals: white shows, black hides). On the stage, on the
GPU stage, in Test Movie and in every export: SVG writes a `mask`, Lottie a track matte, the
HTML canvas composites it. `layer.set_mask` does it headless.
* **Text on a path**: Properties › Path › **Attach to Path**, then click a shape: static text
follows its outline (a copy of it; the shape stays). Move it along with **Offset**, put it on
the other side with **Flip**, and **Release** it back to lines of text. The alignment says
whether the text starts, is centred or ends at the offset. Editing the words, the font or
the size keeps it on its path. Also Modify › Text › Attach Text to Path.
* **SVG import**: soft masks come in as soft mask layers (luminance, or alpha with
`mask-type: alpha`) instead of being drawn unmasked; `textPath` comes in as text on a path;
per-character `x`, `y`, `dx`, `dy` and `rotate` are kept where they are simple.
* **Bones inside shapes** (ADR 0071, M7).
* The **Bone** tool now also draws bones inside a shape, so the shape itself bends like a tail
or a tentacle. Its points follow the nearest bones, and the bend stays smooth through the
joints. Lines keep their width, and the shape as drawn comes back exactly at rest.
* Pose by dragging bones with the Selection tool. Poses key per frame and tween with easing,
as symbol armatures do, and every export, Test Movie and the stage show the bend.
* The new **Bind** tool (**Shift+M**) shows which points follow which bone, and changes it by
click, Shift-click, Ctrl-click or a box. **Properties › Bone** counts the bone's points and
has **Rebind All**.
* Headless: `bone.add_in_shape`, `bone.bind`, and `bone.info` with `points`.
* **CI on macOS and Windows** (ADR 0067, M8). Every pull request that changes code now builds,
tests and lints the workspace on macOS (arm64) and Windows (x64) runners as well as Linux, so
macOS-only and Windows-only code is checked before it merges. Documentation-only changes skip
them, and a newer push cancels the older run. Their first run
found one macOS-only failure: the screen-reader translation tests treated the macOS app
menu's title, the product name, as untranslated.
* **The user guide** (ADR 0069, M8).
* **Help › User Guide** opens AniCraft's guide in your browser. It comes with the app, so it
works offline; the web editor serves it beside the editor. It is also in the command palette.
* Eighteen chapters written for artists, from getting started, drawing, symbols, the timeline and
tweens to masks, the camera and bones, text, images and sound, interactivity, exporting and
Publish, opening Animate files, preferences and accessibility, plug-ins, working headless, and
troubleshooting, plus **Coming from Animate**, which maps Animate's panels, tools and shortcuts
to AniCraft's.
* A **command reference** and a **shortcut reference** (with the macOS keys beside the others),
generated from AniCraft itself, so they always match the version you have.
* `anicraft-cli guide --out <folder>` writes the guide as HTML pages.
* On macOS, the fixed keys that hold a key while dragging ("Space+Drag") keep that key in their
label.
* **Brush library, pressure curves and the Paint Brush** (ADR 0068, M7).
* **Window › Brush Library**: seven built-in brushes, each with a stroke preview drawn by the
renderer: Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk (a ragged edge that
is the same every time) and Dotted. They are all made of parameters, with no bitmaps. A click
sets the brush in hand.
* **Your own brushes**: Save Brush keeps the brush in hand under a name, in your preferences.
Right-click to rename or delete one (deleting asks first). Import… and Export… move a brush
set between computers as a small JSON file.
* **Pressure curves**: an editor in Properties maps pen pressure to the size and, optionally,
to the stroke's opacity. It has Linear, Soft and Firm presets, or your own points.
* **Shaping**: tapers at the start and end, dab spacing and a rough edge, in Properties.
* **Velocity**: without a pen, drawing faster draws thinner (off by default).
* **Paint Brush (Y)**: draws a line in the stroke colour whose width follows the pressure and
tapers, as a width profile you can reshape with the Width tool.
* Headless: `brush.preset_list`, `brush.preset_save`, `brush.preset_rename`,
`brush.preset_delete`, `brush.preset_export`, `brush.preset_import`; `preset`, `curve`,
`pressure_size`, `pressure_opacity`, `taper_start`, `taper_end`, `spacing`, `jitter` and
`as_stroke` on `draw.brush`.
* Pen tilt isn't read yet: egui doesn't report it.
* **Dynamic and input text fields** (ADR 0066, M5).
* **Properties › Text type**: Static, Dynamic or Input text, as in Animate. Dynamic and input
fields have an **instance name**, a **line type** (single line, multiline, multiline no wrap,
password), a fixed **box**, **Show border**, **Selectable** and **Max characters**.
* **Scripts** set and read fields: `score_txt.text = "Score: " + n`, `appendText`, `.length`.
* **Test Movie**: click an input field and type. Caret, selection with Shift and the pointer,
Backspace, Delete, the arrows, Home, End, Enter in multiline fields, Tab to the next field,
Select All, Copy, paste and input methods. Screen readers find fields as text inputs.
* **HTML canvas export**: input fields are real text inputs over the movie (input methods, the
on-screen keyboard and the clipboard work), and text that scripts set is drawn in the
browser. Authored text is drawn exactly as in AniCraft.
* **Animate files**: dynamic and input fields come across as fields, with their names, boxes,
borders and line types (they used to become static text).
* Every other export and the stage draw fields with their authored text, box and border.
* `text.field`, `text.create {type}` and `control.test_movie` `text` and `select_all` events
for agents and the CLI.
* **Templates, SVG into the Library, and drops on the timeline** (ADR 0065, M8).
* **File › New from Template** and the start screen's new **Templates** row: Leaderboard banner
728 × 90, Rectangle banner 300 × 250, Social square 1080 × 1080 at 30 fps, Storyboard 16:9 (six
labelled panels), Character turnaround and a Lip-sync mouth chart. Each has named layers and
guides on a locked guide layer (they show while drawing and never export). They open as new,
untitled documents with a drawing layer active.
* **File › Save as Template** keeps the open document, with a picture, under a name and a
category in your settings folder. It shows under "My templates" on the start screen, with
Delete. Replacing or deleting a template asks first.
* **SVG into the Library**: dropping an SVG on the Library, or File › Import › Import to Library,
makes one graphic symbol named after the file, in the folder under the pointer.
* **Drops on the timeline**: a sound dropped on a layer's frame goes onto that keyframe. An image
or SVG goes onto that layer at that frame, in a new keyframe if needed. Either way it is one undo
step, and a highlight shows the cell. Locked layers, folders and the camera say why they won't
take it.
* The timeline's layer footer keeps its Move Down button in every language.
* Headless: `file.new_from_template`, `file.templates`, `file.save_as_template`,
`file.delete_template`, and `file.drop` with `to: "timeline"`.
* Exact drop positions from the desktop still wait for winit 0.31 (eframe 0.37 is still on 0.30).
* **Accessibility, second pass** (ADR 0064, M8).
* **Select on the stage from the keyboard.** With the stage focused (Ctrl+F6), Tab goes to
its elements, and a ring shows the focused one on the artwork.
* Tab, Shift+Tab and the arrows move between elements.
* Enter or Space selects one; Shift+Enter or Shift+Space adds it to the selection or
takes it out.
* Esc goes back to the stage.
* **Screen readers hear what is on the stage.** While the stage has focus, its elements are
a list ("Rectangle", "Text: Hello", "ball · Graphic: Ball"), each with its layer, place,
size, on-screen bounds and whether it is selected.
* **The active layer's frames are a list too.** Each item reads "Frames 1–24: keyframe ·
motion tween · label “walk”", and activating one moves the playhead there.
* **The timeline from the keyboard.** On the focused timeline, the arrows move the playhead
and the active layer, and each move is announced.
* **The menu bar from the keyboard** on Windows and Linux.
* Press and let go of Alt, or press F10. Then the arrows, Enter and Esc work as in other
applications.
* Alt+F, Alt+E and the rest open a menu directly. While Alt is held, each title shows its
letter underlined.
* **Follow system** is the new default theme. AniCraft switches to high contrast while
Windows uses a contrast theme, macOS has Increase Contrast on, the Linux desktop asks for
high contrast, or the browser prefers more contrast. Choosing Graphite or High contrast
keeps that palette.
* Headless: `element.select` takes `toggle`.
* **Test Movie in its own window, and opening documents on macOS** (ADR 0062, M8).
* **Control › Test Movie** (Ctrl+Enter) now opens in a **window of its own** on the desktop,
as in Animate. It is sized to the stage at 100 % (smaller if that wouldn't fit the
screen), titled with the document's name, and opens where it was last. It takes the
keyboard when it opens. **Esc** or **Ctrl+W (⌘W)** closes it, Ctrl+Enter restarts it in
place, and the editor's Ctrl and Alt shortcuts still work from it.
* In the web build, and wherever the system can't open another window, it floats inside the
editor as before and says why. **Preferences › Test Movie** keeps it inside the editor if
you prefer. On Wayland the desktop places the window, so it can't come back where it was
(Preferences says so).
* **macOS:** double-clicking a `.anicraft`, `.fla` or `.xfl` in Finder, dropping it on the
Dock icon, or choosing Open With › AniCraft opens it, whether AniCraft is running or
not. If there are unsaved changes it asks first, and the Dock's Quit asks to save too.
This uses the small `fmv-macos-events` crate (MIT OR Apache-2.0), so AniCraft's own code
stays free of `unsafe`. Still to be checked on a Mac (the list is in ADR 0062).
* Windows and Linux already open a double-clicked document from the command line; a test
now covers it.
* **Timeline polish** (ADR 0061, M1).
* A **per-layer onion skin toggle** in each layer row (Alt-click: this layer only, again:
every layer). Layers left out show only their playhead frame; Edit Multiple Frames still
edits them.
* **View as Outlines** draws a layer's artwork as hairlines in its colour **on the stage
only**. Exports, Test Movie and the player draw it as it is (before, an outlined layer
exported as outlines). The **colour chip** on the row's edge opens the layer colour.
* **Onion skin inside a symbol edited in place** now also shows the parent timeline's frames
around it, dimmed.
* **Layer Height** 100 / 200 / 300 % (right-click menu), **Layer Properties** (double-click a
layer's icon, Properties… or Modify › Timeline), and a **Frame View** menu with frame widths
Tiny to Large and **Short** rows. Frame zoom and Frame View sit at the right end of the
timeline's bottom bar, as in Animate, so the header fits at the default window size again
(the tween-kind menu was cut off).
* Headless: `layer.set_onion`, `layer.set_color`, `layer.set_height`, `layer.set_properties`,
`layer.properties`. Saved in the document with defaults left out, so older files open as
before. XFL import reads a layer's height.
* **Animated PNG and animated WebP export** (ADR 0063, M4).
* **File › Export › Export Animated PNG…** and **Export Animated WebP…** make full-colour
animations with real transparency, for the web and chat apps, where a GIF has 256 colours
and hard edges. WebP is lossless. Both are transparent by default; turn on the stage colour
as background if you want it. Loop forever, play once, or play a set number of times.
* Every frame is exactly what AniCraft renders. Frames that repeat the one before are stored
once and shown longer, and each later frame stores only the rectangle that changed, so
holds and small motions cost little.
* Timing is exact: APNG delays are fractions of the frame rate (29.97 fps stays 29.97), and
WebP's milliseconds never drift.
* Both are in **Publish Settings** (Animated PNG, Animated WebP) with frames, scale, loop and
background; in a browser they download. Headless: `file.export_apng`, `file.export_webp`
and `anicraft-cli apng` / `webp`.
* On the sample (48 frames, 1280 × 720) the APNG is 2.0 MB and the WebP 1.8 MB, against the
GIF's 1.4 MB, which has only 256 colours; both take less time to make than the GIF.
* **Publish Settings and Publish** (ADR 0060, M8).
* **File › Publish Settings** (Ctrl+Shift+F12) is a window that stays open while you work.
It lists every format AniCraft exports (HTML canvas, animated GIF, video, Lottie, sprite
sheet, PNG sequence, PNG, SVG, audio), each with a checkbox. The selected format shows
its output name and the same options its File › Export command has. The settings are
saved **in the document** and every change can be undone. Older files open with the HTML
page on.
* Output names are relative to the document's folder, and `{name}` stands for the
document's name (`web/{name}.html`). Each name is checked as you type and the full path
is shown below it. A name can't point outside the document's folder, and two formats
can't write the same file.
* **File › Publish** (Shift+F12) writes every format that is on, in the background. A
window shows each format's progress and has a Cancel button. A single report then lists
what each format wrote, skipped (video in a browser, audio with no sounds), left out
(Lottie's and the HTML page's notes) or why it failed. One failing format doesn't stop
the others.
* Publishing over files that are already there asks once. After that, the files this
session published are replaced without asking.
* **Presets**: save the settings under a name, apply them to any document, or delete them.
Presets are kept in your preferences.
* In a browser, the files go to your downloads, as one ZIP when there are several.
* Headless: `publish.settings_get`, `publish.settings_set` and `file.publish`, which returns
the report. Publishing the sample in six formats takes 0.64 s.
* **Files from the desktop, recent files and a start screen** (ADR 0059, M8).
* **Drop files onto the window**: `.anicraft`, `.fla` and `.xfl` open (asking first over
unsaved work); SVG drawings, PNG and JPEG images and WAV, Ogg and MP3 sounds dropped on the
**stage** go onto the active layer at the playhead, centred where they were dropped, and
dropped on the **Library** go into the folder under the pointer. One undo step per drop.
A highlight shows where they will land; anything AniCraft can't take gets one clear
status line. In the web editor too.
* **File › Open Recent**: the last 10 documents opened or saved, with pinned favourites on
top, missing files greyed out with Remove, and Clear Recent Files. Kept in the
preferences (browser storage on the web).
* **Start screen** when AniCraft starts without a document: New with HD, Full HD, square
and vertical presets or a custom size and frame rate, Open, the sample animation, and the
recent files with a picture of their first frame (captured on save). Esc goes back to the
document; File › Start Screen brings it back; it can be switched off.
* New commands for the CLI and MCP: `file.drop`, `file.open_recent`, `file.recent_list`,
`prefs.recent_pin`, `prefs.recent_remove`, `prefs.recent_clear`; `file.import` takes
`cx`/`cy` and `layer: "active"`.
* **Buttons, complete: sounds on button frames and hit-area editing** (ADR 0057, M5).
* A sound on a button's **Over** or **Down** frame plays when the pointer goes over or
presses the button, in Test Movie and in the HTML canvas page (Web Audio). As the SWF format
keeps them, the Up frame's plays on leaving and the Hit frame's on letting go over it. A
stream on a button frame plays as an event. Buttons stay out of the soundtrack: Export Audio
and video are unchanged.
* Editing a button in place, the timeline names its four frames **Up, Over, Down, Hit** (and
widens them to fit while the button is open), and the stage draws the **Hit area**
translucent over the other states.
* Test Movie has a **Show hit areas** checkbox.
* XFL and `.fla` import bring sounds whose file is in the package (WAV, Ogg Vorbis, MP3), with
the sounds on frames that use them, buttons' states included; sounds kept only in Animate's
own format are reported.
* Headless: `control.test_movie` lists the sounds it started.
* 9-slice guides switched off are now kept, and come back where they were when switched on.
* **Find and Replace, and the Movie Explorer** (ADR 0058, M8).
* **Edit › Find and Replace** (Ctrl+F) is a window that stays open while you work. It finds
text in text fields, frame labels, layer names, instance names and frame scripts, with
match case, whole word and regular expressions. It also finds fonts, colours (fills,
gradient stops, strokes, text), symbols, sounds and bitmaps. It searches this scene and
the symbols in it, or the whole document. Results show as you type.
* Click a result, or press **Find Next** (F3) or Find Previous (Shift+F3), to go there: the
scene, the frame and the item selected. A symbol opens in place through the instances
that lead to it.
* **Replace** replaces the current result and goes on to the next. **Replace All** is one
undo step and asks first above 100 places. Replaced text is laid out again, colours keep
their transparency, and a symbol is never put inside itself.
* **Window › Movie Explorer** (Alt+F3) is a tab next to the Library. It shows scenes ›
layers › keyframes › instances, text, sounds, bitmaps and scripts, each instance opening
into its symbol, plus the Library's symbol definitions. A Show menu filters it by kind
and a search keeps matching rows. Double-click a row to go there.
* Both lists draw only the rows in view, so movies with 100,000 rows stay smooth.
* Headless: `find.search`, `find.replace`, `find.goto` and `explorer.tree` (paged).
Patterns use a linear-time engine with size limits.
* **Colour effects, complete** (ADR 0056, M2).
* **Properties › Colour effect**: Animate's Style menu (None, Brightness, Tint, Advanced,
Alpha) with each style's controls: brightness −100..100 %, tint colour and amount,
Advanced's multiplier and offset for red, green, blue and alpha. Every row says "mixed"
when the selection differs, and a change sets only that value on all of them. Switching
style keeps the look where it can (Advanced starts as exactly the effect before).
* One exact colour transform behind every style: nested effects compose exactly (a
brightness around a tint shows both), and the CPU renderer, the GPU stage (bitmaps
included, pixel-identical), SVG (`feColorMatrix` on bitmaps), HTML canvas (bitmaps
recoloured, no longer reported) and Lottie (baked into the colours) draw the same.
* Classic tweens interpolate within a style (a brightness tween passes through 0) and across
styles in the Advanced space, as Animate does.
* Motion tweens key **Brightness**, **Tint** colour (red, green, blue) beside its amount, and
the eight **Advanced** values; the Motion Editor lists the styles in use and adds others
with **Add Colour Effect**. A tween has one colour effect style, as in Animate.
* XFL/FLA import brings every `Color` style across (Advanced no longer keeps only its
alpha); a new `colour` corpus package with goldens.
* `element.set_color_effect` for the CLI, MCP and plug-ins; `element.set_alpha` now keeps
the rest of the effect. Older files open unchanged, and None, Alpha and Tint effects are
still written exactly as before.
* **9-slice scaling for symbols** (ADR 0055, M2).
* **Enable guides for 9-slice scaling** on a symbol, in the Library's item properties or in
Properties. A scaled instance then keeps its corners unscaled, stretches its edges one way
and its centre both ways. Rounded buttons and panels resize without distorting, strokes
keep their width, and rotation and skew apply after. Nested symbols, text and bitmaps
inside scale normally, as in Animate. When there isn't room for the corners, they shrink
together in proportion.
* While the symbol is open for editing, its four guides are **dashed lines across the
stage**. Drag them with the Selection tool (one undo step per drag), or type their
positions in Properties.
* Every export draws it from the same frames. SVG and Lottie get baked outlines. HTML canvas
export scales such instances as a whole for now and says so in its report.
* XFL and `.fla` import read `scaleGridLeft/Right/Top/Bottom`. Headless:
`symbol.set_scale_grid {symbol?, on?, left?, right?, top?, bottom?}`.
* **Frame scripts in ActionScript 3.0 run small logic** (ADR 0052, M6).
* Typed variables (`var score:int = 0;` as Number, int, uint, Boolean, String or untyped),
kept per timeline instance across its frame scripts as Animate timelines keep them;
expressions (arithmetic, comparison, logic, joining text, `Math.min/max/abs/floor/ceil/
round/random`, casts); `if`/`else`, `for`, `while` and `do` loops; functions with
parameters and results, callable from any frame of the same timeline.
* Scripts read properties of instances and timelines (`x`, `y`, `alpha`, `visible`,
`rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`),
remove listeners, and listen for `Event.ENTER_FRAME` and for keys on the stage
(`KeyboardEvent.KEY_DOWN`/`KEY_UP`, `e.keyCode`); `e.target` and `e.currentTarget` work.
* Test Movie sends your keys to the movie (it says so in its bar); `Math.random()` is
seeded, so a headless `control.test_movie` with the same `seed` and events always plays the
same; key events and `seed` there too.
* An endless loop or an error stops only its script, with a line in Output, and the movie
plays on. A script that uses a name no frame of its timeline declares doesn't run, and the
Actions panel shows the name in place.
* The HTML canvas export runs the same scripts, keys included, checked against Test Movie
step by step.
* **Repeating bitmap fills on the GL backend** (M3): the GPU stage wrapped a repeating
bitmap with a signed remainder, which GLSL leaves undefined for negative values, so on
OpenGL (llvmpipe in the FreeBSD VM) the texels at the bitmap's left and top edges came out
wrong. It now wraps without one, and a test keeps every shader free of signed remainders.
* **Library and Properties polish** (ADR 0053, M2).
* **Drag Library items onto the stage**: symbols and bitmaps land at the pointer on the
active layer at the playhead, a sound goes onto that layer's keyframe; drag several at once.
One undo step, and it works inside a symbol open for editing. The stage shows where they
land and on which layer.
* **Place on Stage** (the Library's button, right-click, or **Enter** in the list) puts the
selected items at the centre of the view.
* **Swap Bitmap** in Properties › Bitmap: a placed bitmap keeps its position and transform
and takes the new bitmap's size; a shape painted with a bitmap fill keeps its outline.
* **Convert to Symbol** (F8) asks for a name, a type and a **Library folder**, and offers the
folder and type you used last.
* **"mixed" on every Properties row** when several elements differ: Symbol, Type, Filters,
Blending, Looping, First frame, Bitmap and Width now join Scale, Rotation, Alpha, Fill,
Stroke and Style. A change sets them all; Type sets the type of every selected instance's
symbol.
* Headless: `library.place {items: [..], x, y}` (and `{sound}`), `element.swap_bitmap`,
`kind` and `folder` on `modify.convert_to_symbol`; `symbol.set_kind` without `symbol` sets
every selected instance's symbol.
* **`.fla` files open reliably, and hostile ones safely** (ADR 0054, M4).
* The `.fla` reader takes the layouts zip tools write: folder entries, Windows `\`
separators, CP437 and UTF-8 names (and Info-ZIP Unicode names), data descriptors and
ZIP64. Each entry's size and checksum are checked.
* Damaged or hostile archives fail with a sentence that names the problem: entries sharing
bytes, sizes or checksums that lie, compression bombs (a 1024 : 1 ratio cap, 256 MB per
entry, 1 GiB in all), paths with `..`, absolute or drive paths, duplicate names, more than
32 nested folders, a central directory cut short. Nothing is ever extracted to disk.
* A renamed `.fla` opens (it is recognised by its contents), and a `.fla` saved by Flash CS4
or earlier says to open it in Animate and save it again.
* Every corpus package, packed nine ways, imports identically to its folder and renders the
same golden frames; a fuzz throws 9,664 hostile archives at the reader. A 54.6 MB `.fla`
imports in 311–328 ms (checksums by slicing by 8: reading every entry 53 ms, was 130 ms).
* **Edit Multiple Frames, complete; onion skin inside symbols** (ADR 0051, M1).
* With Edit Multiple Frames on, **Cut, Copy, Paste, Paste in Place and Clear** act on the
artwork selected on every keyframe between the markers. Paste in Place puts artwork copied
from several keyframes back keyframe by keyframe, and artwork copied on one frame onto every
keyframe; Paste puts it on the current frame.
* **Free Transform** shows one box around the selection on every keyframe and scales, rotates
and moves it all about one pivot, one undo step per drag. **Align** (To Stage too),
**Rotate 90°** and **Flip** work across keyframes, and so do the arrow keys.
* Merge-drawing shapes moved, transformed or pasted there **merge again** on their own
keyframe, so drawings stay connected.
* **Onion skin and Edit Multiple Frames work inside a symbol** edited in place, on the
symbol's own timeline.
* Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`,
`frames.paste`, `frames.merge`.
* **Library management** (ADR 0050, M2).
* **Folders**: New Folder (the folder icon under the list, or right-click), nested as deep as
you like (32 levels). Drag items and folders onto a folder to move them in, onto an item to
join its folder, or below the list for the top level; right-click › Move to does the same.
Deleting a folder that holds items asks first, and its items go with it.
* **Rename in place** with F2 or a double-click on the name; Enter keeps it, Esc cancels.
Names are unique within a folder (case aside), as in Animate. Convert to Symbol picks the next
free “Symbol n”.
* **Duplicate Symbol** (right-click): “Ball copy” in the same folder, ready to rename.
* **Swap Symbol** in Properties › Symbol: pick another symbol for the selected instances.
Position, colour effect, blending, filters, looping and instance name stay.
* A **use count** for every item, **Select Unused Items** and **Delete Unused Items…** (in
More). Unused means nothing in any scene reaches it, so one pass clears a whole unused
branch; symbols with a linkage class count as used. Deleting an item the movie uses asks,
and its instances go with it.
* **Sort** by name, type, use count or date added, ascending or descending, and **search**
by name; folders that hold a match open.
* A **preview** of the current item (a symbol's first frame, the bitmap, or a sound's
waveform with a play button) and its **properties**: a symbol's type and linkage class, a
bitmap's **Allow Smoothing**. Smoothing off keeps hard pixel edges on the stage, in
renders, in SVG and in the HTML page.
* Animate files keep their library folders and Allow Smoothing.
* Headless: `library.items`, `library.new_folder`, `library.rename`, `library.move`,
`library.duplicate`, `library.delete`, `library.unused`, `library.delete_unused`,
`library.set_smoothing`, `element.swap_symbol`.
* **The GPU stage sorts heavy frames into tiles on the graphics card, and outlines are cheap**
(ADR 0048, M3).
* Frames with many shapes are binned on the GPU (count, prefix sum, scatter and tile-list
compute passes) instead of on the CPU: the CPU only lays out the shapes' points, and every
buffer is sized up front, so nothing is read back. On Vulkan, a 10,000-shape 4K frame
drawn as one texture takes about 5 ms instead of 22, a 50,000-shape one about 23 ms
instead of 122, and the 50,000-shape 4K stage about 37 ms instead of 75. Frames with few
shapes, shapes inside masks or faded symbols, and Direct3D 12 (where the passes cost more
per stage tile) are still binned on the CPU, which stays the reference
(`ANICRAFT_GPU_BINNING=cpu|gpu|auto` to compare).
* **Outline mode** (an outlined layer, and onion skin's Outlines) draws true one-pixel
hairlines, one edge per segment where the old half-pixel strokes had four and a disc at
every bend, in the CPU renderer and on the GPU alike. On a 2,000-shape scene with ±5 onion
frames, outlines are now as fast as tinted onion frames: 10 ms on the GPU stage at 1080p
(was 73) and 17 ms on the CPU stage (was 34–39). Lines look the same, with smoother joins.
* Parity with the CPU renderer is unchanged (at most 1/255 on every test scene), and a test
checks that the GPU's tile lists are the CPU's, entry by entry and pixel by pixel.
* **Raw points, snapping while drawing, and symbols edited in place** (ADR 0045, issue #42, M1).
* **Add a point** on a merged drawing's line or fill edge with the Pen's Alt-click or a
Subselection double-click: every shape on that edge gets it, and the curve keeps its shape.
* **Delete points** with Delete (or the right-click menu): the shapes that share each point are
joined across it, so a fill and its outline stay together; deleting a line's last points
removes it. A point where three or more lines meet is kept, and the status bar says so.
* **Make Smooth / Make Corner** on raw points. Dragging a handle of a smooth point keeps the
other handle in line (on drawing objects too); **Alt** moves it alone.
* The **Line, Rectangle, Oval, PolyStar and Pen** tools snap their points to points, lines and
fill edges within 10 screen pixels, with a ring where they will snap. **Snap to Objects** is
now Ctrl+Shift+/, as in Animate.
* **Double-click a symbol instance** (or press Ctrl+E, or double-click the symbol in the
Library) to edit it in place: the rest of the stage dims, the timeline shows the symbol's
layers, and merge drawing, the Selection and Subselection tools and every other tool work
inside it as on the stage. The edit bar shows `Scene 1 › Symbol`; click the scene, press
Ctrl+E or double-click empty stage to go back. Undo returns to the symbol where a change was
made. Rotated instances open upright.
* Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth`
on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`; `doc.info` lists
the open symbols.
* **Motion path points pinned to frames** (ADR 0049, M2). As in Animate, a motion tween's
position keyframes are now points on its path: move the object at a frame and the path gets a
point there that the object passes exactly on that frame, whatever else you do to the path.
* Moving the object between the ends adds a pinned point where you put it; after the last
position keyframe the path carries on to the new place. The eases on X and Y time the
object between pinned points as they did between the ends.
* Pinned points are diamonds with their frame number on the stage, and Selection can drag
them. With Subselection, right-click any point to **Pin to Frame** (the playhead's frame)
or **Unpin**. Properties › Frame has **Pin Here** / **Unpin**, and F6 inside a path tween
pins where the object is.
* The Motion Editor draws a pinned frame's X and Y keys in blue; dragging one moves its
point. The timeline marks pinned frames with a larger diamond.
* Adding and deleting points keeps the pins on their points; deleting a pinned point, or
unpinning it, removes its frame's X and Y keys and the motion flows as before.
* Older files open and play exactly as they did (only the ends are pinned).
* Headless: new `motion.pin_point` and `motion.unpin_point`; `motion.info` and the path
commands report `pins`.
* **Stroke caps, joins, miter limit, and dashed and dotted lines** (ADR 0046, M7). Properties ›
Stroke has Animate's rows: **Style** (Solid, Dashed with a dash and gap editor, Dotted with
dot spacing), **Cap** (None, Round, Square), **Join** (Miter, Round, Bevel) and **Miter**
@@ -568,7 +1448,7 @@
play, go to a frame or label, button clicks) in Test Movie and HTML canvas export. Until
then, opening an Animate document now says how many frame scripts it left out instead of
dropping them silently.
* **Filters** (Properties › Filters, on movie clip and button instances as in Animate): **Drop
* **Filters** (Properties › Filters, on movie clip and button instances): **Drop
Shadow**, **Blur**, **Glow** and **Adjust Color**, in any order and combination, with blur
X/Y, quality (Low, Medium, High), strength, colour, angle and distance, and inner, knockout
and hide object. They show on the stage and in every picture export; SVG export writes
@@ -577,7 +1457,7 @@
Animate. Animate documents keep their instances' filters (bevel and gradient filters are
reported). Headless: `element.set_filters`.
* **Blend modes** (Properties › Blending, on movie clip and button instances as in Animate):
* **Blend modes** (Properties › Blending, on movie clip and button instances):
Normal, Layer, Darken, Multiply, Lighten, Screen, Overlay, Hard Light, Add, Subtract,
Difference, Invert, Alpha and Erase. The instance is composited on its own and then blended
with what is below, on the stage and in every export. SVG export writes the CSS blend modes
@@ -638,7 +1518,7 @@
(loop, play once, single frame) and **First frame** (`symbol.set_kind`, `element.set_loop`).
* **Symbols fade as one.** A symbol instance below full opacity now composites its contents
first and then fades the result, as in Animate, so overlapping parts no longer show through
first and then fades the result, so overlapping parts no longer show through
each other. This applies on the stage and in PNG, GIF, sprite sheet and SVG exports (SVG
uses `<g opacity>`). Fully opaque instances render exactly as before.
@@ -680,7 +1560,7 @@
Properties › Kind, and the easing is kept. Animate documents' shape tweens now import as
shape tweens.
* **Import to Stage** (File › Import, **Ctrl+R** as in Animate; `file.import`): SVG drawings
* **Import to Stage** (File › Import, **Ctrl+R**; `file.import`): SVG drawings
come in as editable shapes on a new layer named after the file, at the playhead, centred
and selected, as one undo step. Supported: paths and basic shapes, groups, `use` and
symbols, transforms, `viewBox`, inline and attribute styles, opacity, and linear and radial
Generated
+1264 -73
View File
File diff suppressed because it is too large. Load diff
+47 -8
View File
@@ -6,15 +6,16 @@ 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"
version = "0.3.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"
rust-version = "1.95"
[workspace.dependencies]
craft-lottie = { git = "https://github.com/storytold/craft-libs", rev = "b421e6777343cba6c017295e318624e419b95323" }
anicraft-geom = { path = "crates/geom" }
anicraft-doc = { path = "crates/doc" }
anicraft-render = { path = "crates/render" }
@@ -26,9 +27,23 @@ anicraft-text = { path = "crates/text" }
anicraft-plugins = { path = "crates/plugins" }
anicraft-audio = { path = "crates/audio" }
anicraft-gpu = { path = "crates/gpu" }
anicraft-guide = { path = "crates/guide" }
craft-anicraft-format = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
craft-html = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false }
craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["decode", "pcm-encode"] }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
# Isolate the already-merged APNG container from the existing raster-codec pin.
craft-apng-container = { package = "craft-image-codecs", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "55b1d7f3c598b600a130ae63f4a40334a230ae7b", default-features = false }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
craft-webp = { git = "https://github.com/storytold/craft-libs", rev = "0c144b7d983899d4b5b281046dd03a8b1ab35fbb" }
craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" }
# The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same
# (default) features, so the tree keeps one wgpu build.
wgpu = "30"
# The WGSL front end wgpu already builds, for checking the shaders in tests.
naga = { version = "30", features = ["wgsl-in"] }
pollster = "1"
bytemuck = "1"
anicraft-actions = { path = "crates/actions" }
@@ -36,10 +51,6 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
rayon = "1"
png = "0.17"
# JPEG decoding for imported images (already in the tree; MIT OR Apache-2.0 OR Zlib).
zune-jpeg = { version = "0.5", default-features = false }
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.
@@ -54,6 +65,9 @@ egui = "0.36"
# `Instant` and `SystemTime` that work in the browser too (std's panic on wasm32-unknown-unknown);
# on other targets a re-export of std::time (MIT OR Apache-2.0; already in the tree via winit).
web-time = "1"
# Find and Replace's pattern matching (ADR 0058): linear time, with size limits on what a
# pattern compiles to (MIT OR Apache-2.0). Unicode case folding and word boundaries only.
regex = { version = "1", default-features = false, features = ["std", "perf", "unicode-case", "unicode-perl"] }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -102,11 +116,28 @@ web-time.workspace = true
sys-locale = "0.3"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
eframe.workspace = true
# The user guide, bundled for Help › User Guide (ADR 0069). The web build serves it as pages instead.
anicraft-guide.workspace = true
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a" }
eframe = { workspace = true, features = ["links"] }
rfd.workspace = true
# Sound output (Apache-2.0): WASAPI on Windows, CoreAudio on macOS, ALSA on Linux and the BSDs.
cpal = { version = "0.18", optional = true }
# macOS hands a double-clicked document to the app as an Apple Event, which winit 0.30 doesn't
# deliver (ADR 0062). This small crate (MIT OR Apache-2.0, ~170 lines, read in full) registers the
# open-documents and quit handlers with AppKit and hands us plain paths, so our code stays free of
# `unsafe`. Pinned exactly: it is young, and a new version is read again before it comes in. Its
# objc2 / objc2-app-kit / objc2-foundation are the versions wgpu already brings on macOS.
[target.'cfg(target_os = "macos")'.dependencies]
fmv-macos-events = "=0.1.0"
# The system's high-contrast setting (ADR 0064): one registry value. MIT, already in the tree
# through craft-update.
[target.'cfg(windows)'.dependencies]
winreg = "0.55"
# The web build (ADR 0036, docs/web.md). The window draws with WebGL2 (glow): every current
# browser has it, the stage is drawn on the CPU there, and leaving wgpu out keeps the download
# smaller. The browser glue is wasm-bindgen's (MIT OR Apache-2.0), already under eframe's web
@@ -116,9 +147,17 @@ eframe = { version = "0.36", default-features = false, features = ["accesskit",
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
# Sound output in the browser (ADR 0095): cpal's Web Audio host, on the wasm-bindgen glue above
# (Apache-2.0). The AudioContext opens on the first play, which is a click, as browsers ask.
cpal = { version = "0.18", optional = true, features = ["wasm-bindgen"] }
# In the browser the page's language (navigator.languages) is the system's.
sys-locale = { version = "0.3", features = ["js"] }
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] }
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "MediaQueryList", "Navigator", "Storage", "Url", "Window", "console"] }
[dev-dependencies]
# Plug-in fixtures for the shell's plug-in tests, in WebAssembly text (Apache-2.0 WITH
# LLVM-exception; already in the tree for the engine's tests).
wat = "1.228"
[build-dependencies]
# Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets.
+7 -1
View File
@@ -164,6 +164,7 @@ cargo run --release -p anicraft-cli -- render --sample --frame 12 --out frame12.
cargo run --release -p anicraft-cli -- render-seq --sample --out-dir frames --scale 0.5
cargo run --release -p anicraft-cli -- gif --sample --out animation.gif
cargo run --release -p anicraft-cli -- commands # the command registry as JSON
cargo run --release -p anicraft-cli -- guide --out guide # the user guide as HTML pages
cargo run --release -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft
cargo run --release -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout
cargo test # all crates
@@ -215,6 +216,11 @@ src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
No code below `src/` depends on egui, eframe or windowing libraries.
**New to AniCraft?** The [**user guide**](docs/guide/index.md) is written for artists: getting started, every
workflow, a chapter for people [coming from Animate](docs/guide/coming-from-animate.md), and generated
[command](docs/guide/reference/commands.md) and [shortcut](docs/guide/reference/shortcuts.md) references. It also
opens offline from **Help › User Guide**.
Agent and contributor rules (clean room, the asset policy, no panics in shipped code) are in [`AGENTS.md`](AGENTS.md).
[`docs/requirements.md`](docs/requirements.md) has the scope, [`docs/architecture.md`](docs/architecture.md) the design,
[`docs/product-principles.md`](docs/product-principles.md) the design and user experience principles,
@@ -267,7 +273,7 @@ RISC-V (riscv64): `anicraft-<ver>-linux-riscv64.tar.gz`, a tarball only.
| Build | File | Notes |
|---|---|---|
| Static site | `anicraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
| Static site | `anicraft-web-<ver>.zip` | Not in the releases yet: build it yourself with `packaging/web/package.sh` ([docs/web.md](docs/web.md)), then host it on any static server |
## The Crafting Apps
+8
View File
@@ -0,0 +1,8 @@
<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="5" cy="5" r="2.5" />
<path d="M6.8 3.2 L13.5 13.5 L3.2 6.8" />
<path d="M14 14 L17 9" />
<path d="M14 14 L9 17" />
<rect x="16.5" y="5.5" width="4" height="4" />
<rect x="5.5" y="16.5" width="4" height="4" />
</svg>

After

Width:  |  Height:  |  Size: 422 B

+11
View File
@@ -0,0 +1,11 @@
<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="6" y="6" width="12" height="12" rx="1" />
<path d="M6 2v2" />
<path d="M2 6h2" />
<path d="M18 2v2" />
<path d="M20 6h2" />
<path d="M6 20v2" />
<path d="M2 18h2" />
<path d="M18 20v2" />
<path d="M20 18h2" />
</svg>

After

Width:  |  Height:  |  Size: 426 B

@@ -0,0 +1,8 @@
<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="7" width="14" height="14" rx="2" />
<path d="M8 7 L8 21" />
<path d="M11.5 7 L11.5 21" />
<path d="M14.3 7 L14.3 21" />
<path d="M17 7 L19.2 4.8" />
<circle cx="20.3" cy="3.7" r="1.5" />
</svg>

After

Width:  |  Height:  |  Size: 403 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">
<circle cx="9" cy="15" r="6" />
<path d="M19 3v6" />
<path d="M16 6h6" />
</svg>

After

Width:  |  Height:  |  Size: 269 B

+5
View File
@@ -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">
<rect x="3" y="8" width="11" height="13" rx="2" />
<path d="M19 3v6" />
<path d="M16 6h6" />
</svg>

After

Width:  |  Height:  |  Size: 288 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">
<circle cx="9" cy="15" r="6" fill="currentColor" />
<path d="M19 3v6" />
<path d="M16 6h6" />
</svg>

After

Width:  |  Height:  |  Size: 289 B

+5
View File
@@ -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">
<rect x="3" y="6" width="18" height="12" rx="2" />
<circle cx="8" cy="12" r="1.5" />
<path d="M12 12h5" />
</svg>

After

Width:  |  Height:  |  Size: 302 B

+6
View File
@@ -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">
<path d="M21 3 L15 9" />
<path d="M12.5 7.5 L16.5 11.5" />
<path d="M12.5 7.5 C10 8 9 10 10.5 12 C12 13.5 15 13.5 16.5 11.5" />
<path d="M3 20 C4.5 16.5 6.5 16 8 17.5 C9.5 19 11.5 18.5 13 16" />
</svg>

After

Width:  |  Height:  |  Size: 392 B

+5
View File
@@ -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">
<path d="M8 7l-5 5 5 5" />
<path d="M16 7l5 5-5 5" />
<path d="M14 4l-4 16" />
</svg>

After

Width:  |  Height:  |  Size: 274 B

+7
View File
@@ -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">
<rect x="3" y="3" width="6" height="5" rx="1" />
<path d="M6 8v9a2 2 0 0 0 2 2h5" />
<path d="M6 12h7" />
<rect x="13" y="9.5" width="8" height="5" rx="1" />
<rect x="13" y="16.5" width="8" height="5" rx="1" />
</svg>

After

Width:  |  Height:  |  Size: 410 B

+5
View File
@@ -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">
<path d="M4.5 9A8 8 0 1 1 4 13.5" />
<path d="M4 4v5h5" />
<path d="M12 8v4.5l3 1.5" />
</svg>

After

Width:  |  Height:  |  Size: 283 B

+5
View File
@@ -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">
<rect x="3" y="4" width="4" height="16" rx="1" />
<rect x="9" y="4" width="4" height="16" rx="1" />
<path d="M15 6.2 L18.6 5 L22 18.8 L18.4 20 Z" />
</svg>

After

Width:  |  Height:  |  Size: 344 B

+5
View File
@@ -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">
<rect x="3" y="4" width="18" height="16" rx="2" />
<path d="M7 9l3 3-3 3" />
<path d="M13 15h4" />
</svg>

After

Width:  |  Height:  |  Size: 294 B

@@ -0,0 +1,10 @@
<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 6h8" />
<path d="M18 6h2" />
<circle cx="15" cy="6" r="2.5" />
<path d="M4 12h2" />
<path d="M12 12h8" />
<circle cx="9" cy="12" r="2.5" />
<path d="M4 18h10" />
<circle cx="17" cy="18" r="2.5" />
</svg>

After

Width:  |  Height:  |  Size: 414 B

+6
View File
@@ -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">
<rect x="3" y="3" width="7" height="7" rx="1.5" />
<rect x="14" y="3" width="7" height="7" rx="1.5" />
<rect x="3" y="14" width="7" height="7" rx="1.5" />
<rect x="14" y="14" width="7" height="7" rx="1.5" />
</svg>

After

Width:  |  Height:  |  Size: 405 B

+9
View File
@@ -0,0 +1,9 @@
<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 5 C8 3 14 8 21 5" />
<path d="M3 19 C8 17 14 22 21 19" />
<path d="M3 5 L3 19" />
<path d="M21 5 L21 19" />
<path d="M3 12 C7 10 10 13 12 12.5" />
<path d="M12 5.4 C11 8 11.5 10 12 12.5 C12.5 15 11.5 17 12 19.6" />
<circle cx="16" cy="13" r="2.5" />
</svg>

After

Width:  |  Height:  |  Size: 465 B

+14
View File
@@ -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="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</svg>

After

Width:  |  Height:  |  Size: 339 B

+15
View File
@@ -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"
>
<circle cx="12" cy="12" r="1" />
<circle cx="19" cy="12" r="1" />
<circle cx="5" cy="12" r="1" />
</svg>

After

Width:  |  Height:  |  Size: 312 B

+14
View File
@@ -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="M5 12h14" />
<path d="M12 5v14" />
</svg>

After

Width:  |  Height:  |  Size: 256 B

+17
View File
@@ -0,0 +1,17 @@
<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 11v6" />
<path d="M14 11v6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
<path d="M3 6h18" />
<path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>

After

Width:  |  Height:  |  Size: 389 B

+6 -5
View File
@@ -84,14 +84,15 @@ fn windows_icon() {
}
}
/// The desktop-only features (ADR 0036) as cfgs: `gpu_stage` and `sound_output` are on when
/// their feature is and the target isn't the web, so `cargo build --target wasm32-unknown-unknown`
/// works with the default features and the web build draws on the CPU, silently.
/// The features as cfgs: `gpu_stage` is on when its feature is and the target isn't the web
/// (ADR 0036), so `cargo build --target wasm32-unknown-unknown` works with the default features
/// and the web build draws on the CPU; `sound_output` is on when its feature is, on the web too
/// (Web Audio, ADR 0095).
fn native_features() {
println!("cargo::rustc-check-cfg=cfg(gpu_stage, sound_output)");
let web = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
for (feature, cfg) in [("CARGO_FEATURE_GPU_STAGE", "gpu_stage"), ("CARGO_FEATURE_SOUND_OUTPUT", "sound_output")] {
if std::env::var_os(feature).is_some() && !web {
for (feature, cfg, desktop_only) in [("CARGO_FEATURE_GPU_STAGE", "gpu_stage", true), ("CARGO_FEATURE_SOUND_OUTPUT", "sound_output", false)] {
if std::env::var_os(feature).is_some() && !(web && desktop_only) {
println!("cargo::rustc-cfg={cfg}");
}
}
+829
View File
@@ -0,0 +1,829 @@
//! The script IR (ADR 0052): a small, typed form of statements and expressions that a
//! compiled script runs as, evaluated by [`super::run`]. It is data, not code: the player (and
//! the HTML canvas player, which reads the same IR as JSON) walks it with a fuel budget.
//!
//! Names are resolved when the script compiles: a function's own variables are numbered slots,
//! the timeline's variables (`var` at the top of a frame script, shared by every frame script
//! of that timeline, as ActionScript 3.0 timelines keep them per instance) are looked up by
//! name, and instances are name paths from a base (the timeline, the stage, or the event's
//! target). Calls to functions go by name to the timeline's functions, so a frame can call a
//! function another frame of the same timeline declares.
use crate::{FrameRef, Property, Target};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::sync::Arc;
/// A variable's type: what values written to it are coerced to (ECMA-262 §9, ActionScript 3.0's
/// `int` and `uint` as ToInt32 and ToUint32).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Ty {
/// Untyped (`*`, `Object`, or no annotation): keeps any value.
#[default]
Any,
Number,
Int,
Uint,
Boolean,
String,
}
impl Ty {
/// The type an annotation names, when it is one scripts can hold.
pub fn from_name(s: &str) -> Option<Ty> {
Some(match s {
"*" | "Object" => Ty::Any,
"Number" => Ty::Number,
"int" => Ty::Int,
"uint" => Ty::Uint,
"Boolean" => Ty::Boolean,
"String" => Ty::String,
_ => return None,
})
}
/// What a variable of this type holds before anything is written to it.
pub fn default_value(self) -> Value {
match self {
Ty::Any => Value::Undefined,
Ty::Number => Value::Num(f64::NAN),
Ty::Int | Ty::Uint => Value::Num(0.0),
Ty::Boolean => Value::Bool(false),
Ty::String => Value::Null,
}
}
/// `v` as this type.
pub fn coerce(self, v: Value) -> Value {
match self {
Ty::Any => v,
Ty::Number => Value::Num(v.number()),
Ty::Int => Value::Num(f64::from(to_int32(v.number()))),
Ty::Uint => Value::Num(f64::from(to_uint32(v.number()))),
Ty::Boolean => Value::Bool(v.truthy()),
Ty::String => match v {
Value::Null | Value::Undefined => Value::Null,
Value::Str(_) => v,
other => Value::Str(other.text().into()),
},
}
}
}
/// ToInt32 (ECMA-262 §9.5).
pub fn to_int32(n: f64) -> i32 {
let u = to_uint32(n);
u as i32
}
/// ToUint32 (ECMA-262 §9.6).
pub fn to_uint32(n: f64) -> u32 {
if !n.is_finite() {
return 0;
}
let m = n.trunc().rem_euclid(4_294_967_296.0);
// In 0 .. 2^32 by construction.
if (0.0..4_294_967_296.0).contains(&m) { m as u32 } else { 0 }
}
/// A value a script computes with: ActionScript's primitive values.
#[derive(Clone, Debug, Default)]
pub enum Value {
#[default]
Undefined,
Null,
Bool(bool),
Num(f64),
Str(Arc<str>),
}
impl PartialEq for Value {
/// The same value (NaN is NaN): what state comparisons need, not ActionScript's `==`.
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
(Value::Bool(a), Value::Bool(b)) => a == b,
(Value::Num(a), Value::Num(b)) => a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan()),
(Value::Str(a), Value::Str(b)) => a == b,
_ => false,
}
}
}
impl Value {
pub fn str(s: &str) -> Value {
Value::Str(s.into())
}
/// ToNumber (ECMA-262 §9.3).
pub fn number(&self) -> f64 {
match self {
Value::Num(n) => *n,
Value::Bool(b) => f64::from(u8::from(*b)),
Value::Null => 0.0,
Value::Undefined => f64::NAN,
Value::Str(s) => string_number(s),
}
}
/// ToBoolean (§9.2).
pub fn truthy(&self) -> bool {
match self {
Value::Num(n) => *n != 0.0 && !n.is_nan(),
Value::Str(s) => !s.is_empty(),
Value::Bool(b) => *b,
Value::Null | Value::Undefined => false,
}
}
/// ToString (§9.8).
pub fn text(&self) -> String {
match self {
Value::Num(n) => number_text(*n),
Value::Str(s) => s.to_string(),
Value::Bool(b) => b.to_string(),
Value::Null => "null".into(),
Value::Undefined => "undefined".into(),
}
}
pub fn is_str(&self) -> bool {
matches!(self, Value::Str(_))
}
}
/// The JSON form: `"u"`, `"null"`, `{"b": true}`, `{"n": 1.5}`, `{"s": "text"}`, `"nan"`,
/// `{"inf": false}` (JSON has no NaN or infinities).
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum ValueRepr {
U,
Null,
B(bool),
N(f64),
S(String),
Nan,
/// `true`: negative.
Inf(bool),
}
impl Serialize for Value {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Value::Undefined => ValueRepr::U,
Value::Null => ValueRepr::Null,
Value::Bool(b) => ValueRepr::B(*b),
Value::Num(n) if n.is_nan() => ValueRepr::Nan,
Value::Num(n) if n.is_infinite() => ValueRepr::Inf(*n < 0.0),
Value::Num(n) => ValueRepr::N(*n),
Value::Str(t) => ValueRepr::S(t.to_string()),
}
.serialize(s)
}
}
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Value, D::Error> {
Ok(match ValueRepr::deserialize(d)? {
ValueRepr::U => Value::Undefined,
ValueRepr::Null => Value::Null,
ValueRepr::B(b) => Value::Bool(b),
ValueRepr::N(n) => Value::Num(n),
ValueRepr::S(t) => Value::Str(t.into()),
ValueRepr::Nan => Value::Num(f64::NAN),
ValueRepr::Inf(neg) => Value::Num(if neg { f64::NEG_INFINITY } else { f64::INFINITY }),
})
}
}
/// White space and line terminators as ECMAScript trims them from numbers in text.
fn js_space(c: char) -> bool {
matches!(c, '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}')
}
/// A number written as text (StringToNumber, ECMA-262 §9.3.1 as browsers read it: decimal,
/// `Infinity`, and `0x`/`0o`/`0b` integers), or NaN.
pub fn string_number(s: &str) -> f64 {
let t = s.trim_matches(js_space);
if t.is_empty() {
return 0.0;
}
let radix = |p: &str, r: u32| -> f64 {
if p.is_empty() || !p.chars().all(|c| c.is_digit(r)) {
return f64::NAN;
}
p.chars().filter_map(|c| c.to_digit(r)).fold(0.0, |v, d| v * f64::from(r) + f64::from(d))
};
if let Some(p) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
return radix(p, 16);
}
if let Some(p) = t.strip_prefix("0o").or_else(|| t.strip_prefix("0O")) {
return radix(p, 8);
}
if let Some(p) = t.strip_prefix("0b").or_else(|| t.strip_prefix("0B")) {
return radix(p, 2);
}
let (neg, body) = match t.as_bytes().first() {
Some(b'-') => (true, t.get(1..).unwrap_or("")),
Some(b'+') => (false, t.get(1..).unwrap_or("")),
_ => (false, t),
};
if body == "Infinity" {
return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
}
// digits [. digits] [e[+-]digits], or . digits [e…]
let b = body.as_bytes();
let mut i = 0;
let digits = |i: &mut usize| {
let from = *i;
while b.get(*i).is_some_and(u8::is_ascii_digit) {
*i += 1;
}
*i - from
};
let int = digits(&mut i);
let mut frac = 0;
if b.get(i) == Some(&b'.') {
i += 1;
frac = digits(&mut i);
}
if int + frac == 0 {
return f64::NAN;
}
if matches!(b.get(i), Some(b'e' | b'E')) {
i += 1;
if matches!(b.get(i), Some(b'+' | b'-')) {
i += 1;
}
if digits(&mut i) == 0 {
return f64::NAN;
}
}
if i != b.len() {
return f64::NAN;
}
let v: f64 = body.parse().unwrap_or(f64::NAN);
if neg { -v } else { v }
}
/// A number as ActionScript writes it (`Number.toString()`, ECMA-262 §9.8.1): integers without
/// a point, exponents outside 1e-6 … 1e21.
pub fn number_text(n: f64) -> String {
if n.is_nan() {
return "NaN".into();
}
if n.is_infinite() {
return if n > 0.0 { "Infinity".into() } else { "-Infinity".into() };
}
if n == 0.0 {
return "0".into();
}
let a = n.abs();
if (1e-6..1e21).contains(&a) {
return format!("{n}");
}
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
}
/// Length in UTF-16 units, as ActionScript's `String.length` counts.
pub fn text_len(s: &str) -> usize {
s.encode_utf16().count()
}
/// Where an instance path starts.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Base {
/// The script's timeline.
#[default]
This,
/// The stage (keyboard listeners live there).
Stage,
/// The event's `target`.
Target,
/// The event's `currentTarget`: the instance (or stage) listened to.
Current,
}
impl Base {
pub fn is_this(&self) -> bool {
*self == Base::This
}
}
/// An instance a script names: a base and a name path from it (`hero_mc.arm_mc`, `parent`,
/// `root.menu`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Place {
#[serde(default, skip_serializing_if = "Base::is_this")]
pub base: Base,
#[serde(default, skip_serializing_if = "Target::is_this")]
pub path: Target,
}
impl Place {
pub fn this() -> Place {
Place::default()
}
pub fn named(path: impl Into<String>) -> Place {
Place { base: Base::This, path: Target::new(path) }
}
}
impl std::fmt::Display for Place {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base = match self.base {
Base::This => "",
Base::Stage => "stage",
Base::Target => "e.target",
Base::Current => "e.currentTarget",
};
match (base, self.path.is_this()) {
("", _) => write!(f, "{}", self.path),
(b, true) => f.write_str(b),
(b, false) => write!(f, "{b}.{}", self.path),
}
}
}
/// A property a script reads (of an instance or of the timeline).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Prop {
X,
Y,
Alpha,
Visible,
Rotation,
ScaleX,
ScaleY,
/// 1-based, as ActionScript counts frames.
CurrentFrame,
TotalFrames,
/// The label at or before the playhead, or `null`.
CurrentLabel,
/// The pointer in the instance's own space.
MouseX,
MouseY,
/// The instance name.
Name,
/// A text field's text, and its length in UTF-16 units (ADR 0066). Only as `field.text` and
/// `field.length`: a bare `text` is a variable.
Text,
Length,
}
impl Prop {
pub fn from_name(s: &str) -> Option<Prop> {
Some(match s {
"x" => Prop::X,
"y" => Prop::Y,
"alpha" => Prop::Alpha,
"visible" => Prop::Visible,
"rotation" => Prop::Rotation,
"scaleX" => Prop::ScaleX,
"scaleY" => Prop::ScaleY,
"currentFrame" => Prop::CurrentFrame,
"totalFrames" => Prop::TotalFrames,
"currentLabel" => Prop::CurrentLabel,
"mouseX" => Prop::MouseX,
"mouseY" => Prop::MouseY,
"name" => Prop::Name,
_ => return None,
})
}
/// A property read or set as `instance.m`: those [`Prop::from_name`] knows, and a text
/// field's `text` and `length`.
pub fn from_member(s: &str) -> Option<Prop> {
match s {
"text" => Some(Prop::Text),
"length" => Some(Prop::Length),
_ => Prop::from_name(s),
}
}
pub fn name(self) -> &'static str {
match self {
Prop::X => "x",
Prop::Y => "y",
Prop::Alpha => "alpha",
Prop::Visible => "visible",
Prop::Rotation => "rotation",
Prop::ScaleX => "scaleX",
Prop::ScaleY => "scaleY",
Prop::CurrentFrame => "currentFrame",
Prop::TotalFrames => "totalFrames",
Prop::CurrentLabel => "currentLabel",
Prop::MouseX => "mouseX",
Prop::MouseY => "mouseY",
Prop::Name => "name",
Prop::Text => "text",
Prop::Length => "length",
}
}
/// The instance property a script may also set.
pub fn settable(self) -> Option<Property> {
Some(match self {
Prop::X => Property::X,
Prop::Y => Property::Y,
Prop::Alpha => Property::Alpha,
Prop::Visible => Property::Visible,
Prop::Rotation => Property::Rotation,
Prop::ScaleX => Property::ScaleX,
Prop::ScaleY => Property::ScaleY,
_ => return None,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnOp {
Neg,
Plus,
Not,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Mod,
Lt,
Gt,
Le,
Ge,
Eq,
Ne,
StrictEq,
StrictNe,
}
impl BinOp {
pub fn from_token(s: &str) -> Option<BinOp> {
Some(match s {
"+" => BinOp::Add,
"-" => BinOp::Sub,
"*" => BinOp::Mul,
"/" => BinOp::Div,
"%" => BinOp::Mod,
"<" => BinOp::Lt,
">" => BinOp::Gt,
"<=" => BinOp::Le,
">=" => BinOp::Ge,
"==" => BinOp::Eq,
"!=" => BinOp::Ne,
"===" => BinOp::StrictEq,
"!==" => BinOp::StrictNe,
_ => return None,
})
}
}
/// `Math` functions scripts may call.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MathFn {
Min,
Max,
Abs,
Floor,
Ceil,
Round,
/// From the player's seeded generator: the same movie and events give the same numbers.
Random,
}
impl MathFn {
pub fn from_name(s: &str) -> Option<MathFn> {
Some(match s {
"min" => MathFn::Min,
"max" => MathFn::Max,
"abs" => MathFn::Abs,
"floor" => MathFn::Floor,
"ceil" => MathFn::Ceil,
"round" => MathFn::Round,
"random" => MathFn::Random,
_ => return None,
})
}
/// How many arguments it takes (`None`: any number).
pub fn arity(self) -> Option<usize> {
match self {
MathFn::Min | MathFn::Max => None,
MathFn::Random => Some(0),
MathFn::Abs | MathFn::Floor | MathFn::Ceil | MathFn::Round => Some(1),
}
}
}
/// What an assignment writes to.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "k", rename_all = "snake_case")]
pub enum LValue {
/// A function's own variable (or parameter).
Local { i: u16 },
/// A variable of the timeline.
Var { n: String },
/// An instance property.
Prop { at: Place, p: Property },
/// A text field's text (`field.text = …`, `field.appendText(…)` as `+=`).
Text { at: Place },
}
/// An expression.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "e", rename_all = "snake_case")]
pub enum Expr {
Lit { v: Value },
Local { i: u16 },
Var { n: String },
Get { at: Place, p: Prop },
/// The keyboard event's `keyCode`.
Key,
/// The event a listener handles, passed on to a function's event parameter.
Event,
Un { op: UnOp, x: Box<Expr> },
Bin { op: BinOp, a: Box<Expr>, b: Box<Expr> },
/// `a && b`, `a || b` (the operand's value, as ECMAScript gives it).
And { a: Box<Expr>, b: Box<Expr> },
Or { a: Box<Expr>, b: Box<Expr> },
Cond { c: Box<Expr>, a: Box<Expr>, b: Box<Expr> },
Math { f: MathFn, args: Vec<Expr> },
/// A call to a function of the timeline, by name.
Call { f: String, args: Vec<Expr> },
/// Whether two names are the same instance (`e.currentTarget == btn_a`); `ne` negates.
Same { a: Place, b: Place, ne: bool },
/// `to = v` or `to op= v`; its value is what was written.
Set { to: LValue, op: Option<BinOp>, v: Box<Expr> },
/// `++` / `--` (`d` is +1 or -1); `post`: the value before.
Step { to: LValue, d: i8, post: bool },
/// `int(x)`, `Number(x)`, `String(x)`, `Boolean(x)`, `uint(x)`.
Cast { t: Ty, x: Box<Expr> },
}
impl Expr {
pub fn lit(v: Value) -> Expr {
Expr::Lit { v }
}
}
/// A timeline method.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Method {
Stop,
Play,
GotoAndPlay,
GotoAndStop,
NextFrame,
PrevFrame,
NextScene,
PrevScene,
}
impl Method {
pub fn from_name(s: &str) -> Option<Method> {
Some(match s {
"stop" => Method::Stop,
"play" => Method::Play,
"gotoAndPlay" => Method::GotoAndPlay,
"gotoAndStop" => Method::GotoAndStop,
"nextFrame" => Method::NextFrame,
"prevFrame" => Method::PrevFrame,
"nextScene" => Method::NextScene,
"prevScene" => Method::PrevScene,
_ => return None,
})
}
pub fn name(self) -> &'static str {
match self {
Method::Stop => "stop",
Method::Play => "play",
Method::GotoAndPlay => "gotoAndPlay",
Method::GotoAndStop => "gotoAndStop",
Method::NextFrame => "nextFrame",
Method::PrevFrame => "prevFrame",
Method::NextScene => "nextScene",
Method::PrevScene => "prevScene",
}
}
/// The action it is, at a frame (go-tos) and scene.
pub fn action(self, target: Target, frame: FrameRef, scene: Option<String>) -> crate::Action {
use crate::Action as A;
match self {
Method::Stop => A::Stop { target },
Method::Play => A::Play { target },
Method::GotoAndPlay => A::GotoAndPlay { target, frame, scene },
Method::GotoAndStop => A::GotoAndStop { target, frame, scene },
Method::NextFrame => A::NextFrame { target },
Method::PrevFrame => A::PrevFrame { target },
Method::NextScene => A::NextScene,
Method::PrevScene => A::PrevScene,
}
}
}
/// An event a listener waits for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ListenEvent {
Click,
Press,
Release,
Over,
Out,
/// `Event.ENTER_FRAME`: every frame, playing or not.
EnterFrame,
/// `KeyboardEvent.KEY_DOWN` / `KEY_UP` on the stage.
KeyDown,
KeyUp,
}
impl ListenEvent {
pub fn key(self) -> &'static str {
match self {
ListenEvent::Click => "click",
ListenEvent::Press => "press",
ListenEvent::Release => "release",
ListenEvent::Over => "over",
ListenEvent::Out => "out",
ListenEvent::EnterFrame => "enter_frame",
ListenEvent::KeyDown => "key_down",
ListenEvent::KeyUp => "key_up",
}
}
/// The pointer event it is, for mouse listeners.
pub fn mouse(self) -> Option<crate::ButtonEvent> {
use crate::ButtonEvent as B;
Some(match self {
ListenEvent::Click => B::Click,
ListenEvent::Press => B::Press,
ListenEvent::Release => B::Release,
ListenEvent::Over => B::Over,
ListenEvent::Out => B::Out,
_ => return None,
})
}
pub fn from_mouse(b: crate::ButtonEvent) -> ListenEvent {
use crate::ButtonEvent as B;
match b {
B::Click => ListenEvent::Click,
B::Press => ListenEvent::Press,
B::Release => ListenEvent::Release,
B::Over => ListenEvent::Over,
B::Out => ListenEvent::Out,
}
}
pub fn is_key(self) -> bool {
matches!(self, ListenEvent::KeyDown | ListenEvent::KeyUp)
}
}
/// The function a listener runs.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FuncRef {
/// A function of the timeline, by name.
Named(String),
/// A function written in place: the index in the enclosing code's `inner` list.
Inline(u16),
}
/// A statement, with the line it starts on (for messages).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Stmt {
pub l: u32,
#[serde(flatten)]
pub s: S,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "s", rename_all = "snake_case")]
pub enum S {
/// An expression for its effect.
Do { x: Expr },
If { c: Expr, a: Vec<Stmt>, b: Vec<Stmt> },
/// `while (c)`, `for (; c; next)` (`first`: the condition is tested before the body) and
/// `do … while (c)`.
Loop {
c: Option<Expr>,
body: Vec<Stmt>,
next: Option<Expr>,
first: bool,
},
Break,
Continue,
Return { v: Option<Expr> },
/// A timeline method on an instance; `args` are the frame and the scene, when it takes them.
Act { at: Place, m: Method, args: Vec<Expr> },
Trace { args: Vec<Expr> },
/// `addEventListener` (`add`) or `removeEventListener`.
Listen { at: Place, ev: ListenEvent, f: FuncRef, add: bool },
}
/// A parameter.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Param {
pub t: Ty,
/// The value when a call leaves it out.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub d: Option<Value>,
/// It is the event (typed `…Event`): its fields read the event the listener handles.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub ev: bool,
}
/// A function: its parameters, its own variables (parameters first, each slot's type), what it
/// returns and its body.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Function {
pub name: String,
pub line: u32,
pub params: Vec<Param>,
pub locals: Vec<Ty>,
/// `None`: `void`, or no result.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ret: Option<Ty>,
pub body: Vec<Stmt>,
/// Functions written in place inside it (listeners).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inner: Vec<Arc<Function>>,
}
impl Function {
/// Whether the function's first parameter takes an event (it can be a listener).
pub fn takes_event(&self) -> bool {
let required = self.params.iter().filter(|p| p.d.is_none()).count();
required <= 1 && self.params.first().is_some_and(|p| p.ev || p.t == Ty::Any)
}
}
/// The keyboard key codes ActionScript names (`Keyboard.LEFT`, …): the public `flash.ui.Keyboard`
/// constants scripts compare `e.keyCode` with.
pub fn key_code(name: &str) -> Option<u32> {
let one = |s: &str| {
let mut c = s.chars();
match (c.next(), c.next()) {
(Some(ch), None) => Some(ch),
_ => None,
}
};
if let Some(c) = one(name).filter(char::is_ascii_uppercase) {
return Some(u32::from(c));
}
if let Some(d) = name.strip_prefix("NUMBER_").and_then(one).and_then(|c| c.to_digit(10)) {
return Some(48 + d);
}
if let Some(d) = name.strip_prefix("NUMPAD_").and_then(one).and_then(|c| c.to_digit(10)) {
return Some(96 + d);
}
if let Some(n) = name.strip_prefix('F').and_then(|n| n.parse::<u32>().ok()).filter(|n| (1..=15).contains(n)) {
return Some(111 + n);
}
Some(match name {
"BACKSPACE" => 8,
"TAB" => 9,
"ENTER" => 13,
"SHIFT" => 16,
"CONTROL" => 17,
"ALTERNATE" => 18,
"CAPS_LOCK" => 20,
"ESCAPE" => 27,
"SPACE" => 32,
"PAGE_UP" => 33,
"PAGE_DOWN" => 34,
"END" => 35,
"HOME" => 36,
"LEFT" => 37,
"UP" => 38,
"RIGHT" => 39,
"DOWN" => 40,
"INSERT" => 45,
"DELETE" => 46,
"NUMPAD_MULTIPLY" => 106,
"NUMPAD_ADD" => 107,
"NUMPAD_ENTER" => 108,
"NUMPAD_SUBTRACT" => 109,
"NUMPAD_DECIMAL" => 110,
"NUMPAD_DIVIDE" => 111,
"SEMICOLON" => 186,
"EQUAL" => 187,
"COMMA" => 188,
"MINUS" => 189,
"PERIOD" => 190,
"SLASH" => 191,
"BACKQUOTE" => 192,
"LEFTBRACKET" => 219,
"BACKSLASH" => 220,
"RIGHTBRACKET" => 221,
"QUOTE" => 222,
_ => return None,
})
}
File diff suppressed because it is too large. Load diff
+107 -56
View File
@@ -1,29 +1,40 @@
//! The ActionScript 3.0 timeline subset (ADR 0013 tier 2): a hand-written lexer and
//! recursive-descent parser, and a lowering to the action IR.
//! The ActionScript 3.0 subset (ADR 0013 tiers 2 and 2.5): a hand-written lexer and
//! recursive-descent parser, a lowering to a small typed script IR ([`ir`]), and the evaluator
//! that runs it ([`run`]) over the player.
//!
//! What runs is what most Animate frame scripts do: `stop()`, `play()`, `gotoAndPlay` and
//! `gotoAndStop` by frame number or label (and scene), `nextFrame()`, `prevFrame()`,
//! `nextScene()` and `prevScene()`, on this timeline or on instance-name paths
//! (`hero_mc.gotoAndStop("run")`, `MovieClip(this.parent).play()`); mouse listeners
//! (`btn.addEventListener(MouseEvent.CLICK, onClick)` with `function onClick(e:MouseEvent):void
//! { … }` made of those calls, or an inline function); `trace` of literals and their `+`; and
//! setting `x`, `y`, `alpha`, `visible`, `rotation`, `scaleX` and `scaleY` on named instances to
//! values. A function declared in the script and called from it runs in place.
//! What runs is what Animate frame scripts do: timeline control (`stop()`, `play()`,
//! `gotoAndPlay`/`gotoAndStop` by frame or label and scene, `nextFrame()` … on this timeline or
//! on instance-name paths); **typed variables** (`var n:int = 0;` as Number, int, uint, Boolean,
//! String or untyped), kept per timeline instance across its frame scripts as ActionScript 3.0
//! timelines keep them; **expressions** (arithmetic, comparison, logic, joining text,
//! `Math.min/max/abs/floor/ceil/round/random`, `int(…)` and the other casts); `if`/`else`,
//! `for`, `while` and `do` loops; **reading properties** of named instances and of the
//! timeline (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`,
//! `totalFrames`, `currentLabel`, `mouseX/Y`, `name`); setting the instance ones; functions
//! with parameters and results, called from any frame script of the same timeline; listeners
//! (`addEventListener` and `removeEventListener`) for mouse events on buttons and movie clips,
//! `Event.ENTER_FRAME`, and `KeyboardEvent.KEY_DOWN`/`KEY_UP` on the stage with `e.keyCode`;
//! `e.target` and `e.currentTarget`; and `trace`.
//!
//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all:
//! nothing is ever half-run. Calls that would reach outside the movie (`navigateToURL`,
//! `fscommand`, `ExternalInterface`) are ignored and listed as notes.
//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all.
//! Calls that would reach outside the movie (`navigateToURL`, `fscommand`, `ExternalInterface`)
//! are ignored and listed as notes. A compiled script names the variables and functions it
//! uses from other frames ([`Compiled::free`]); the timeline must declare them
//! ([`Decls::problems`]) or the script doesn't run either.
//!
//! Learned from the ECMAScript 3rd edition standard (ECMA-262) and Adobe's public ActionScript
//! 3.0 language reference; no Adobe code. Everything is bounded: source length, token count,
//! nesting depth, inlining depth, actions, listeners and problems.
//! nesting depth, listeners and problems here; fuel, call depth and text length when it runs.
pub mod ir;
mod lex;
mod lower;
mod parse;
pub mod run;
use crate::{Action, ButtonEvent, Target};
use ir::{Function, Ty};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Arc;
/// Longest script that runs, in bytes (far more than frame scripts written by hand).
@@ -32,8 +43,6 @@ pub const MAX_RUN_BYTES: usize = 256 * 1024;
pub const MAX_TOKENS: usize = 65_536;
/// Deepest nesting of statements and expressions.
pub const MAX_DEPTH: usize = 64;
/// Deepest chain of calls to the script's own functions.
pub const MAX_INLINE_DEPTH: usize = 16;
/// Most listeners one script adds.
pub const MAX_LISTENERS: usize = 64;
/// Most problems reported for one script.
@@ -73,53 +82,95 @@ impl std::fmt::Display for Problem {
}
}
/// A mouse listener a script adds: when `event` happens on `target` (a button or movie clip,
/// named from the script's timeline), `actions` run on the script's timeline.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Listener {
#[serde(default, skip_serializing_if = "Target::is_this")]
pub target: Target,
pub event: ButtonEvent,
/// The function's name (`function at line 7` for an inline one): adding the same function
/// for the same event again changes nothing, as in ActionScript.
pub function: String,
pub actions: Arc<Vec<Action>>,
/// A name a script uses that it doesn't declare: a variable or function of another frame
/// script of the same timeline.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Free {
pub name: String,
pub line: u32,
pub column: u32,
/// Called (a function), or read and written (a variable).
pub call: bool,
}
impl Listener {
pub fn describe(&self) -> String {
let body = if self.actions.is_empty() { "nothing".to_string() } else { self.actions.iter().map(Action::describe).collect::<Vec<_>>().join("; ") };
format!("On {} ({}): {body}", self.event.key(), self.target)
}
}
/// One step of a script, in source order.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ScriptOp {
Action(Action),
Listen(Listener),
}
impl ScriptOp {
pub fn describe(&self) -> String {
match self {
ScriptOp::Action(a) => a.describe(),
ScriptOp::Listen(l) => l.describe(),
}
}
}
/// A script that runs: its steps, and what in it is ignored.
/// A script that runs.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Compiled {
pub ops: Vec<ScriptOp>,
/// The top-level statements, in order.
pub body: Vec<ir::Stmt>,
/// Functions written in place at the top level (listeners).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inner: Vec<Arc<Function>>,
/// The functions it declares (the timeline's, callable from its other frames).
pub functions: Vec<Arc<Function>>,
/// The variables it declares (the timeline's), with their types.
pub vars: Vec<(String, Ty)>,
/// Names it uses from other frames of the timeline.
pub free: Vec<Free>,
/// Calls that are ignored (they would reach outside the movie, or do nothing here).
pub notes: Vec<Problem>,
/// Statements it holds, functions included (for "runs, N steps").
pub steps: usize,
}
/// Compiles ActionScript 3.0 source to the action IR, or says why it doesn't run (the
/// problems sorted by position, at most [`MAX_PROBLEMS`]).
/// A timeline's declarations: every function and variable its frame scripts declare (the
/// first one of a name, in frame order, top layer first), as ActionScript 3.0 makes them
/// members of the timeline.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Decls {
pub functions: BTreeMap<String, Arc<Function>>,
pub vars: BTreeMap<String, Ty>,
}
impl Decls {
/// From the timeline's compiled scripts, in frame order (top layer first within a frame).
pub fn build<'a>(scripts: impl IntoIterator<Item = &'a Compiled>) -> Decls {
let mut d = Decls::default();
for c in scripts {
for f in &c.functions {
d.functions.entry(f.name.clone()).or_insert_with(|| f.clone());
}
for (n, t) in &c.vars {
d.vars.entry(n.clone()).or_insert(*t);
}
}
d
}
/// Why `c` can't run on a timeline with these declarations: a name from another frame that
/// the timeline doesn't declare, or a declaration another frame already makes differently.
pub fn problems(&self, c: &Compiled) -> Vec<Problem> {
let mut out = Vec::new();
for f in &c.free {
let pos = Pos { line: f.line, column: f.column };
let known = if f.call { self.functions.contains_key(&f.name) } else { self.vars.contains_key(&f.name) };
if !known {
let msg = match (f.call, self.functions.contains_key(&f.name) || self.vars.contains_key(&f.name)) {
(true, true) => format!("`{}` is a variable, not a function", f.name),
(false, true) => format!("`{}` is a function; call it, as in `{}()`", f.name, f.name),
(true, false) => format!("`{}` isn't a function of this timeline (declare it in one of its frame scripts)", f.name),
(false, false) => format!("`{}` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)", f.name),
};
out.push(Problem::at(pos, msg));
}
}
for f in &c.functions {
if self.functions.get(&f.name).is_some_and(|g| !Arc::ptr_eq(f, g) && **f != **g) {
out.push(Problem::at(Pos { line: f.line, column: 1 }, format!("`{}` is also declared on another frame of this timeline", f.name)));
}
}
for (n, t) in &c.vars {
if self.vars.get(n).is_some_and(|u| u != t) {
out.push(Problem::whole(format!("`{n}` is declared with another type on another frame of this timeline")));
}
}
out.truncate(MAX_PROBLEMS);
out
}
}
/// Compiles ActionScript 3.0 source to the script IR, or says why it doesn't run (the problems
/// sorted by position, at most [`MAX_PROBLEMS`]).
pub fn compile(src: &str) -> Result<Compiled, Vec<Problem>> {
if src.len() > MAX_RUN_BYTES {
return Err(vec![Problem::whole(format!("the script is longer than {} KiB, the most that runs", MAX_RUN_BYTES / 1024))]);
+147 -41
View File
@@ -1,8 +1,8 @@
//! The parser: tokens to a syntax tree, by recursive descent (the grammar of ECMA-262 3rd
//! edition §11–14, with ActionScript 3.0's type annotations, `import`, `as`, `is`, rest
//! parameters and `for each`). It reads more of the language than AniCraft runs, so lowering
//! can say exactly which construct isn't run and where; what it reads but never runs (loop
//! headers, `switch` and `try` bodies) is skipped by balanced brackets. Bounded: nesting
//! can say exactly which construct isn't run and where; what it reads but never runs (`for in`
//! heads, `switch` and `try` bodies) is skipped by balanced brackets. Bounded: nesting
//! deeper than [`super::MAX_DEPTH`] is a problem, not a stack overflow.
use super::lex::{Tok, Token};
@@ -47,7 +47,9 @@ pub enum E {
pub struct Param {
pub name: String,
pub pos: Pos,
pub default: bool,
/// The type annotation as written (`int`, `MouseEvent`, `*`), when there is one.
pub ty: Option<(String, Pos)>,
pub default: Option<Expr>,
pub rest: bool,
}
@@ -56,9 +58,20 @@ pub struct Func {
pub name: Option<String>,
pub pos: Pos,
pub params: Vec<Param>,
/// The result type as written (`void`, `int`), when there is one.
pub ret: Option<(String, Pos)>,
pub body: Vec<Stmt>,
}
/// One name of a `var` (or `const`) statement.
#[derive(Clone, Debug, PartialEq)]
pub struct VarDecl {
pub name: String,
pub pos: Pos,
pub ty: Option<(String, Pos)>,
pub init: Option<Expr>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Stmt {
pub pos: Pos,
@@ -71,8 +84,15 @@ pub enum S {
Import,
Function(Func),
/// `var`, `const`.
Var(&'static str),
Var(&'static str, Vec<VarDecl>),
If(Expr, Vec<Stmt>, Vec<Stmt>),
/// `for (init; cond; update) body` (`init` a `var` statement or an expression).
For(Option<Box<Stmt>>, Option<Expr>, Option<Expr>, Vec<Stmt>),
While(Expr, Vec<Stmt>),
DoWhile(Vec<Stmt>, Expr),
/// `break` and `continue` (without a label).
Break,
Continue,
Return(Option<Expr>),
Block(Vec<Stmt>),
Empty,
@@ -228,12 +248,83 @@ impl<'a> Parser<'a> {
}
}
/// `: Type` (read and dropped: `*`, `void`, `a.b.C`, `Vector.<T>`).
fn annotation(&mut self) -> R<()> {
/// `: Type` (`*`, `void`, `a.b.C`, `Vector.<T>`), as written.
fn annotation(&mut self) -> R<Option<(String, Pos)>> {
if !self.eat(":") {
return Ok(());
return Ok(None);
}
self.type_name()
let pos = self.pos();
let start = self.i;
self.type_name()?;
let text: String = self
.toks
.get(start..self.i)
.unwrap_or_default()
.iter()
.map(|t| match &t.tok {
Tok::Name(n) => n.clone(),
Tok::Punct(p) => (*p).to_string(),
_ => String::new(),
})
.collect();
Ok(Some((text, pos)))
}
/// The names of a `var` statement after the keyword.
fn var_list(&mut self) -> R<Vec<VarDecl>> {
let mut out = Vec::new();
loop {
let (name, pos) = self.name("a variable name")?;
let ty = self.annotation()?;
let init = if self.eat("=") { Some(self.assign()?) } else { None };
out.push(VarDecl { name, pos, ty, init });
if !self.eat(",") {
return Ok(out);
}
}
}
/// `( init ; cond ; update )` after `for`, or `None` for `for … in` (read, not run).
#[allow(clippy::type_complexity)]
fn for_head(&mut self) -> R<Option<(Option<Box<Stmt>>, Option<Expr>, Option<Expr>)>> {
let open = self.i;
self.expect("(", "after `for`")?;
let pos = self.pos();
let init = if self.is(";") {
None
} else if self.is_word("var") || self.is_word("const") {
let w = if self.is_word("var") { "var" } else { "const" };
self.i += 1;
let list = self.var_list()?;
if self.is_word("in") || list.iter().any(|d| matches!(&d.init, Some(Expr { kind: E::Binary("in", ..), .. }))) {
self.i = open;
self.skip_group()?;
return Ok(None);
}
Some(Box::new(Stmt { pos, kind: S::Var(w, list) }))
} else {
let e = self.expr()?;
if matches!(e.kind, E::Binary("in", ..)) {
self.i = open;
self.skip_group()?;
return Ok(None);
}
Some(Box::new(Stmt { pos, kind: S::Expr(e) }))
};
self.expect(";", "after the loop's start")?;
let cond = if self.is(";") { None } else { Some(self.expr()?) };
self.expect(";", "after the loop's condition")?;
let update = if self.is(")") { None } else { Some(self.expr()?) };
self.expect(")", "to close the loop's head")?;
Ok(Some((init, cond, update)))
}
/// `( expr )`
fn paren(&mut self, what: &str) -> R<Expr> {
self.expect("(", what)?;
let e = self.expr()?;
self.expect(")", "after the condition")?;
Ok(e)
}
fn type_name(&mut self) -> R<()> {
@@ -323,18 +414,9 @@ impl<'a> Parser<'a> {
"var" | "const" => {
let w = if w == "var" { "var" } else { "const" };
self.i += 1;
loop {
self.name("a variable name")?;
self.annotation()?;
if self.eat("=") {
self.assign()?;
}
if !self.eat(",") {
break;
}
}
let list = self.var_list()?;
self.end()?;
S::Var(w)
S::Var(w, list)
}
"if" => {
self.i += 1;
@@ -353,14 +435,20 @@ impl<'a> Parser<'a> {
}
"for" => {
self.i += 1;
self.eat_word("each");
self.skip_group()?;
S::Other("for", self.body()?)
if self.eat_word("each") {
self.skip_group()?;
S::Other("for each", self.body()?)
} else {
match self.for_head()? {
Some((init, cond, update)) => S::For(init, cond, update, self.body()?),
None => S::Other("for in", self.body()?),
}
}
}
"while" => {
self.i += 1;
self.skip_group()?;
S::Other("while", self.body()?)
let c = self.paren("after `while`")?;
S::While(c, self.body()?)
}
"do" => {
self.i += 1;
@@ -368,9 +456,9 @@ impl<'a> Parser<'a> {
if !self.eat_word("while") {
return Err(self.unexpected("`while` after the `do` body"));
}
self.skip_group()?;
let c = self.paren("after `while`")?;
self.end()?;
S::Other("do", b)
S::DoWhile(b, c)
}
"with" => {
self.i += 1;
@@ -408,11 +496,17 @@ impl<'a> Parser<'a> {
_ => "throw",
};
self.i += 1;
if !(self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl()) {
let bare = self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl();
if !bare {
self.expr()?;
}
self.end()?;
S::Other(w, Vec::new())
match (w, bare) {
("break", true) => S::Break,
("continue", true) => S::Continue,
("throw", _) => S::Other("throw", Vec::new()),
_ => S::Other("labelled break", Vec::new()),
}
}
// Applications, not timeline scripts (ADR 0013 tier 3).
"package" | "class" | "interface" | "namespace" | "use" | "include" | "default" => {
@@ -454,21 +548,18 @@ impl<'a> Parser<'a> {
loop {
let rest = self.eat("...");
let (n, p) = self.name("a parameter name")?;
self.annotation()?;
let default = self.eat("=");
if default {
self.assign()?;
}
params.push(Param { name: n, pos: p, default, rest });
let ty = self.annotation()?;
let default = if self.eat("=") { Some(self.assign()?) } else { None };
params.push(Param { name: n, pos: p, ty, default, rest });
if self.eat(")") {
break;
}
self.expect(",", "or `)` after the parameter")?;
}
}
self.annotation()?;
let ret = self.annotation()?;
let body = self.block()?;
Ok(Func { name, pos, params, body })
Ok(Func { name, pos, params, ret, body })
}
/// An expression (`a, b` included).
@@ -534,29 +625,44 @@ impl<'a> Parser<'a> {
];
let Some(ops) = LEVELS.get(level) else { return self.unary() };
let mut lhs = self.binary(level + 1)?;
loop {
// Each operator in a row nests the tree one deeper: it counts toward the depth limit,
// so what runs the tree can't recurse without bound.
let mut chain = 0;
let r = loop {
let op = match self.tok() {
Tok::Punct(p) if ops.contains(p) => ops.iter().find(|o| *o == p).copied(),
Tok::Name(n) if ops.contains(&n.as_str()) => ops.iter().find(|o| **o == n.as_str()).copied(),
_ => None,
};
let Some(op) = op else { return Ok(lhs) };
let Some(op) = op else { break Ok(lhs) };
chain += 1;
self.depth += 1;
if self.depth > MAX_DEPTH {
break Err(Problem::at(self.pos(), format!("this expression has too many operators in a row (code nests at most {MAX_DEPTH} levels deep)")));
}
self.i += 1;
// The right side of `as` and `is` is a type.
let rhs = if matches!(op, "as" | "is") {
let pos = self.pos();
let start = self.i;
self.type_name()?;
if let Err(e) = self.type_name() {
break Err(e);
}
let name = match self.toks.get(start..self.i) {
Some([Token { tok: Tok::Name(n), .. }]) => n.clone(),
_ => "*".into(),
};
Expr { pos, kind: E::Name(name) }
} else {
self.binary(level + 1)?
match self.binary(level + 1) {
Ok(e) => e,
Err(e) => break Err(e),
}
};
lhs = Expr { pos: lhs.pos, kind: E::Binary(op, Box::new(lhs), Box::new(rhs)) };
}
};
self.depth -= chain;
r
}
fn unary(&mut self) -> R<Expr> {
+538
View File
@@ -0,0 +1,538 @@
//! Running the script IR (ADR 0052): a small tree-walking evaluator over a
//! [`World`] (the player, which knows the movie). It is deterministic (the only random numbers
//! come from the world's seeded generator) and bounded: every statement and expression costs
//! fuel, text has a length limit, calls a depth limit. When fuel runs out or something can't
//! be done (a name that isn't there, a value of the wrong kind), the run stops where it is,
//! as an ActionScript error stops a script, and says why; what it did before stays done.
//!
//! The HTML canvas player (`player.js`) mirrors this file step for step.
use super::ir::*;
use crate::{FrameRef, MAX_FRAME, MAX_LABEL_CHARS, MAX_TRACE_CHARS, Property};
use std::sync::Arc;
/// Fuel one frame script (or one listener call) may use.
pub const FUEL_PER_RUN: u64 = 100_000;
/// Deepest chain of calls.
pub const MAX_CALL_DEPTH: usize = 16;
/// Longest text a script makes, in UTF-16 units.
pub const MAX_TEXT: usize = 16_384;
/// Why a run stopped before its end.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Stop {
/// It used its fuel (an endless loop, most likely).
Fuel,
/// Something couldn't be done, at `line`.
Error { line: u32, message: String },
/// The world stopped everything (a per-frame budget ran out); it already said why.
Halt,
}
impl Stop {
pub fn describe(&self) -> String {
match self {
Stop::Fuel => format!("it ran more than {FUEL_PER_RUN} steps (an endless loop?)"),
Stop::Error { line, message } if *line > 0 => format!("line {line}: {message}"),
Stop::Error { message, .. } => message.clone(),
Stop::Halt => "the frame's budget ran out".into(),
}
}
}
/// What a running script talks to. Errors stop the run (`Err(message)`); actions that can't
/// find their instance write a line to Output and the script goes on, as before (tier 2).
pub trait World {
/// A timeline action, on the instance `base` starts from (`action`'s target is the name path).
fn act(&mut self, base: Base, action: &crate::Action) -> Result<(), Option<String>>;
/// Reads a property.
fn get(&mut self, at: &Place, p: Prop) -> Result<Value, String>;
/// Sets an instance property.
fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option<String>>;
/// Sets a text field's text (ADR 0066).
fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option<String>>;
fn trace(&mut self, line: String);
/// A timeline variable's value, and writing one (the world knows its type).
fn read(&mut self, name: &str) -> Result<Value, String>;
fn write(&mut self, name: &str, v: Value) -> Result<(), String>;
/// The timeline's function by that name.
fn function(&mut self, name: &str) -> Option<Arc<Function>>;
/// Adds (or removes) a listener; `name` is how it is known (adding the same again does
/// nothing).
fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc<Function>, add: bool) -> Result<(), Option<String>>;
/// The next number from the movie's seeded generator, in [0, 1).
fn random(&mut self) -> f64;
/// Whether two names are one instance.
fn same(&mut self, a: &Place, b: &Place) -> Result<bool, String>;
/// The keyboard event's key code.
fn key_code(&mut self) -> Result<f64, String>;
}
/// The error of a world call: `None` means the world halted (and said so).
fn lift(line: u32, e: Option<String>) -> Stop {
match e {
Some(message) => Stop::Error { line, message },
None => Stop::Halt,
}
}
enum Flow {
Normal,
Break,
Continue,
Return(Value),
}
struct Frame<'f> {
locals: Vec<Value>,
/// Each local's type (a write coerces to it).
types: &'f [Ty],
inner: &'f [Arc<Function>],
}
struct Vm<'w> {
w: &'w mut dyn World,
fuel: u64,
depth: usize,
line: u32,
}
type R<T> = Result<T, Stop>;
/// Runs a frame script's top-level statements; returns the fuel used and how it ended.
pub fn run_script(w: &mut dyn World, body: &[Stmt], inner: &[Arc<Function>], fuel: u64) -> (u64, Result<(), Stop>) {
let mut vm = Vm { w, fuel, depth: 0, line: 0 };
let mut frame = Frame { locals: Vec::new(), types: &[], inner };
let r = vm.block(body, &mut frame).map(|_| ());
(fuel - vm.fuel, r)
}
/// Calls a listener's function with the event (its first parameter).
pub fn run_listener(w: &mut dyn World, f: &Arc<Function>, fuel: u64) -> (u64, Result<(), Stop>) {
let mut vm = Vm { w, fuel, depth: 0, line: f.line };
let r = vm.call(f, &[Expr::Event], &mut Frame { locals: Vec::new(), types: &[], inner: &[] }).map(|_| ());
(fuel - vm.fuel, r)
}
/// JavaScript's `Math.round`: the nearest integer, halves toward +∞.
pub fn round(x: f64) -> f64 {
if !x.is_finite() {
return x;
}
let f = x.floor();
if x - f >= 0.5 { f + 1.0 } else { f }
}
/// Math.min / Math.max: NaN wins, no arguments give ±Infinity.
fn min_max(vals: &[f64], max: bool) -> f64 {
let mut out = if max { f64::NEG_INFINITY } else { f64::INFINITY };
for &v in vals {
if v.is_nan() {
return f64::NAN;
}
if (max && v > out) || (!max && v < out) {
out = v;
}
}
out
}
/// `==` (ECMA-262 §11.9.3) over primitives.
pub fn loose_eq(a: &Value, b: &Value) -> bool {
use Value as V;
match (a, b) {
(V::Undefined | V::Null, V::Undefined | V::Null) => true,
(V::Undefined | V::Null, _) | (_, V::Undefined | V::Null) => false,
(V::Num(x), V::Num(y)) => x == y,
(V::Str(x), V::Str(y)) => x == y,
(V::Bool(x), V::Bool(y)) => x == y,
(V::Num(x), V::Str(_)) => *x == b.number(),
(V::Str(_), V::Num(y)) => a.number() == *y,
(V::Bool(_), _) => loose_eq(&V::Num(a.number()), b),
(_, V::Bool(_)) => loose_eq(a, &V::Num(b.number())),
}
}
/// `===` (§11.9.6).
pub fn strict_eq(a: &Value, b: &Value) -> bool {
use Value as V;
match (a, b) {
(V::Num(x), V::Num(y)) => x == y,
(V::Undefined, V::Undefined) | (V::Null, V::Null) => true,
(V::Str(x), V::Str(y)) => x == y,
(V::Bool(x), V::Bool(y)) => x == y,
_ => false,
}
}
/// `<` (§11.8.5): text by UTF-16 units, the rest as numbers; `None` when a NaN is involved.
fn compare(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
if let (Value::Str(x), Value::Str(y)) = (a, b) {
return Some(x.encode_utf16().cmp(y.encode_utf16()));
}
a.number().partial_cmp(&b.number())
}
/// Text cut to [`MAX_TRACE_CHARS`] UTF-16 units (never through a surrogate pair), with `…`.
pub fn trace_line(s: String) -> String {
let units: Vec<u16> = s.encode_utf16().collect();
if units.len() <= MAX_TRACE_CHARS {
return s;
}
let mut n = MAX_TRACE_CHARS;
if units.get(n - 1).is_some_and(|u| (0xd800..0xdc00).contains(u)) {
n -= 1;
}
let mut out = String::from_utf16_lossy(units.get(..n).unwrap_or(&[]));
out.push('…');
out
}
impl Vm<'_> {
fn tick(&mut self, n: u64) -> R<()> {
if self.fuel < n {
self.fuel = 0;
return Err(Stop::Fuel);
}
self.fuel -= n;
Ok(())
}
fn err<T>(&self, message: impl Into<String>) -> R<T> {
Err(Stop::Error { line: self.line, message: message.into() })
}
fn block(&mut self, list: &[Stmt], fr: &mut Frame<'_>) -> R<Flow> {
for s in list {
match self.stmt(s, fr)? {
Flow::Normal => {}
other => return Ok(other),
}
}
Ok(Flow::Normal)
}
fn stmt(&mut self, st: &Stmt, fr: &mut Frame<'_>) -> R<Flow> {
self.tick(1)?;
self.line = st.l;
match &st.s {
S::Do { x } => {
self.expr(x, fr)?;
}
S::If { c, a, b } => {
let c = self.expr(c, fr)?.truthy();
return self.block(if c { a } else { b }, fr);
}
S::Loop { c, body, next, first } => {
let mut test = *first;
loop {
if test && let Some(c) = c {
self.line = st.l;
if !self.expr(c, fr)?.truthy() {
break;
}
}
test = true;
// A loop with nothing in it still costs fuel.
self.tick(1)?;
match self.block(body, fr)? {
Flow::Break => break,
Flow::Return(v) => return Ok(Flow::Return(v)),
Flow::Normal | Flow::Continue => {}
}
if let Some(n) = next {
self.line = st.l;
self.expr(n, fr)?;
}
}
}
S::Break => return Ok(Flow::Break),
S::Continue => return Ok(Flow::Continue),
S::Return { v } => {
let v = match v {
Some(v) => self.expr(v, fr)?,
None => Value::Undefined,
};
return Ok(Flow::Return(v));
}
S::Act { at, m, args } => {
let frame = match args.first() {
Some(a) => Some(self.expr(a, fr)?),
None => None,
};
let scene = match args.get(1) {
Some(a) => Some(self.expr(a, fr)?),
None => None,
};
self.line = st.l;
let frame = match frame {
None => FrameRef::default(),
Some(Value::Str(s)) if label_ok(&s) => FrameRef::Label(s.to_string()),
Some(Value::Num(n)) if n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(&n) => FrameRef::Number(n as u32 - 1),
Some(v) => return self.err(format!("`{}` needs a frame number from 1 or a label, not {}", m.name(), shown(&v))),
};
let scene = match scene {
None | Some(Value::Null | Value::Undefined) => None,
Some(Value::Str(s)) if label_ok(&s) => Some(s.to_string()),
Some(v) => return self.err(format!("the scene is its name, not {}", shown(&v))),
};
let action = m.action(at.path.clone(), frame, scene);
self.w.act(at.base, &action).map_err(|e| lift(st.l, e))?;
}
S::Trace { args } => {
let mut parts = Vec::with_capacity(args.len());
for a in args {
parts.push(self.expr(a, fr)?.text());
}
self.w.trace(trace_line(parts.join(" ")));
}
S::Listen { at, ev, f, add } => {
let func = match f {
FuncRef::Named(n) => match self.w.function(n) {
Some(f) => f,
None => return self.err(format!("there's no function `{n}` on this timeline")),
},
FuncRef::Inline(i) => match fr.inner.get(usize::from(*i)) {
Some(f) => f.clone(),
None => return self.err("the listener's function is missing"),
},
};
self.w.listen(at, *ev, &func, *add).map_err(|e| lift(st.l, e))?;
}
}
Ok(Flow::Normal)
}
fn text(&mut self, s: String) -> R<Value> {
let n = text_len(&s);
if n > MAX_TEXT {
return self.err(format!("this text would be longer than {MAX_TEXT} characters"));
}
// Making text costs fuel for its length, so a loop building text can't run long.
self.tick(n as u64 / 64)?;
Ok(Value::Str(s.into()))
}
fn binary(&mut self, op: BinOp, a: Value, b: Value) -> R<Value> {
use std::cmp::Ordering::*;
Ok(match op {
BinOp::Add if a.is_str() || b.is_str() => return self.text(a.text() + &b.text()),
BinOp::Add => Value::Num(a.number() + b.number()),
BinOp::Sub => Value::Num(a.number() - b.number()),
BinOp::Mul => Value::Num(a.number() * b.number()),
BinOp::Div => Value::Num(a.number() / b.number()),
BinOp::Mod => Value::Num(a.number() % b.number()),
BinOp::Lt => Value::Bool(compare(&a, &b) == Some(Less)),
BinOp::Gt => Value::Bool(compare(&a, &b) == Some(Greater)),
BinOp::Le => Value::Bool(matches!(compare(&a, &b), Some(Less | Equal))),
BinOp::Ge => Value::Bool(matches!(compare(&a, &b), Some(Greater | Equal))),
BinOp::Eq => Value::Bool(loose_eq(&a, &b)),
BinOp::Ne => Value::Bool(!loose_eq(&a, &b)),
BinOp::StrictEq => Value::Bool(strict_eq(&a, &b)),
BinOp::StrictNe => Value::Bool(!strict_eq(&a, &b)),
})
}
fn load(&mut self, to: &LValue, fr: &Frame<'_>) -> R<Value> {
match to {
LValue::Local { i } => Ok(fr.locals.get(usize::from(*i)).cloned().unwrap_or_default()),
LValue::Var { n } => self.w.read(n).map_err(|message| Stop::Error { line: self.line, message }),
LValue::Prop { at, p } => {
let prop = match p {
Property::X => Prop::X,
Property::Y => Prop::Y,
Property::Alpha => Prop::Alpha,
Property::Visible => Prop::Visible,
Property::Rotation => Prop::Rotation,
Property::ScaleX => Prop::ScaleX,
Property::ScaleY => Prop::ScaleY,
};
self.w.get(at, prop).map_err(|message| Stop::Error { line: self.line, message })
}
LValue::Text { at } => self.w.get(at, Prop::Text).map_err(|message| Stop::Error { line: self.line, message }),
}
}
/// Writes `v`; the value is what the place holds after (a typed variable's coercion).
fn store(&mut self, to: &LValue, v: Value, fr: &mut Frame<'_>) -> R<Value> {
match to {
LValue::Local { i } => {
let ty = fr.types.get(usize::from(*i)).copied().unwrap_or_default();
let v = ty.coerce(v);
if let Some(slot) = fr.locals.get_mut(usize::from(*i)) {
*slot = v.clone();
}
Ok(v)
}
LValue::Var { n } => {
self.w.write(n, v).map_err(|message| Stop::Error { line: self.line, message })?;
self.w.read(n).map_err(|message| Stop::Error { line: self.line, message })
}
LValue::Prop { at, p } => {
let n = v.number();
if !n.is_finite() {
return self.err(format!("`{}` is set to a number, not {}", prop_name(*p), shown(&v)));
}
self.w.set(at, *p, n).map_err(|e| lift(self.line, e))?;
Ok(v)
}
LValue::Text { at } => {
if matches!(v, Value::Null | Value::Undefined) {
return self.err(format!("`text` is set to text, not {}", v.text()));
}
self.w.set_text(at, v.text()).map_err(|e| lift(self.line, e))?;
Ok(v)
}
}
}
fn expr(&mut self, e: &Expr, fr: &mut Frame<'_>) -> R<Value> {
self.tick(1)?;
Ok(match e {
Expr::Lit { v } => v.clone(),
Expr::Local { i } => fr.locals.get(usize::from(*i)).cloned().unwrap_or_default(),
Expr::Var { n } => self.w.read(n).map_err(|message| Stop::Error { line: self.line, message })?,
Expr::Get { at, p } => self.w.get(at, *p).map_err(|message| Stop::Error { line: self.line, message })?,
Expr::Key => Value::Num(self.w.key_code().map_err(|message| Stop::Error { line: self.line, message })?),
Expr::Event => return self.err("the event can only be passed to a function's event parameter"),
Expr::Un { op, x } => {
let v = self.expr(x, fr)?;
match op {
UnOp::Neg => Value::Num(-v.number()),
UnOp::Plus => Value::Num(v.number()),
UnOp::Not => Value::Bool(!v.truthy()),
}
}
Expr::Bin { op, a, b } => {
let a = self.expr(a, fr)?;
let b = self.expr(b, fr)?;
return self.binary(*op, a, b);
}
Expr::And { a, b } => {
let a = self.expr(a, fr)?;
if a.truthy() { self.expr(b, fr)? } else { a }
}
Expr::Or { a, b } => {
let a = self.expr(a, fr)?;
if a.truthy() { a } else { self.expr(b, fr)? }
}
Expr::Cond { c, a, b } => {
if self.expr(c, fr)?.truthy() {
self.expr(a, fr)?
} else {
self.expr(b, fr)?
}
}
Expr::Math { f, args } => {
let mut v = Vec::with_capacity(args.len());
for a in args {
v.push(self.expr(a, fr)?.number());
}
let x = v.first().copied().unwrap_or(f64::NAN);
Value::Num(match f {
MathFn::Min => min_max(&v, false),
MathFn::Max => min_max(&v, true),
MathFn::Abs => x.abs(),
MathFn::Floor => x.floor(),
MathFn::Ceil => x.ceil(),
MathFn::Round => round(x),
MathFn::Random => self.w.random(),
})
}
Expr::Call { f, args } => {
let Some(func) = self.w.function(f) else { return self.err(format!("there's no function `{f}` on this timeline")) };
let line = self.line;
let v = self.call(&func, args, fr)?;
self.line = line;
v
}
Expr::Same { a, b, ne } => {
let same = self.w.same(a, b).map_err(|message| Stop::Error { line: self.line, message })?;
Value::Bool(same != *ne)
}
Expr::Set { to, op, v } => {
let new = match op {
None => self.expr(v, fr)?,
Some(op) => {
let old = self.load(to, fr)?;
let rhs = self.expr(v, fr)?;
self.binary(*op, old, rhs)?
}
};
return self.store(to, new, fr);
}
Expr::Step { to, d, post } => {
let old = Value::Num(self.load(to, fr)?.number());
let new = Value::Num(old.number() + f64::from(*d));
let stored = self.store(to, new, fr)?;
if *post { old } else { stored }
}
Expr::Cast { t, x } => {
let v = self.expr(x, fr)?;
t.coerce(v)
}
})
}
/// Calls `f` with `args` evaluated in the caller's frame.
fn call(&mut self, f: &Arc<Function>, args: &[Expr], caller: &mut Frame<'_>) -> R<Value> {
if self.depth >= MAX_CALL_DEPTH {
return self.err(format!("functions call each other more than {MAX_CALL_DEPTH} deep"));
}
let required = f.params.iter().filter(|p| p.d.is_none()).count();
if args.len() < required || args.len() > f.params.len() {
let want = if required == f.params.len() { format!("{required}") } else { format!("{required} to {}", f.params.len()) };
return self.err(format!("`{}` takes {want} argument{}, not {}", f.name, if f.params.len() == 1 { "" } else { "s" }, args.len()));
}
let mut locals: Vec<Value> = f.locals.iter().map(|t| t.default_value()).collect();
for (i, p) in f.params.iter().enumerate() {
let v = match args.get(i) {
Some(Expr::Event) if p.ev || p.t == Ty::Any => Value::Null,
Some(Expr::Event) => return self.err("the event can only be passed to a function's event parameter"),
Some(a) => self.expr(a, caller)?,
None => p.d.clone().unwrap_or_default(),
};
if let Some(slot) = locals.get_mut(i) {
*slot = p.t.coerce(v);
}
}
self.depth += 1;
self.line = f.line;
let mut fr = Frame { locals, types: &f.locals, inner: &f.inner };
let flow = self.block(&f.body, &mut fr);
self.depth -= 1;
let v = match flow? {
Flow::Return(v) => v,
_ => Value::Undefined,
};
Ok(match f.ret {
Some(t) => t.coerce(v),
None => Value::Undefined,
})
}
}
fn label_ok(s: &str) -> bool {
let n = s.chars().count();
(1..=MAX_LABEL_CHARS).contains(&n) && !s.chars().any(char::is_control) && s.chars().any(|c| !c.is_whitespace())
}
/// A value as a message names it.
fn shown(v: &Value) -> String {
match v {
Value::Str(s) => format!("\"{}\"", s.chars().take(40).collect::<String>()),
other => other.text(),
}
}
fn prop_name(p: Property) -> &'static str {
match p {
Property::X => "x",
Property::Y => "y",
Property::Alpha => "alpha",
Property::Visible => "visible",
Property::Rotation => "rotation",
Property::ScaleX => "scaleX",
Property::ScaleY => "scaleY",
}
}
+401 -141
View File
@@ -1,21 +1,13 @@
use super::ir::*;
use super::run::{self, Stop, World};
use super::*;
use crate::{Action, ButtonEvent, FrameRef, Property, Target};
use crate::{Action, FrameRef, Property};
use std::collections::BTreeMap;
fn ok(src: &str) -> Compiled {
compile(src).unwrap_or_else(|p| panic!("{src:?} didn't compile: {p:?}"))
}
fn actions(src: &str) -> Vec<Action> {
ok(src)
.ops
.into_iter()
.map(|o| match o {
ScriptOp::Action(a) => a,
ScriptOp::Listen(l) => panic!("unexpected listener {l:?}"),
})
.collect()
}
/// The first problem: (line, column, message).
fn err(src: &str) -> (u32, u32, String) {
match compile(src) {
@@ -27,99 +19,273 @@ fn err(src: &str) -> (u32, u32, String) {
}
}
fn t(s: &str) -> Target {
Target::new(s)
/// A movie in miniature: one timeline with its variables and functions, instances with
/// properties, and a log of everything the script did.
#[derive(Default)]
struct Mock {
decls: Decls,
vars: BTreeMap<String, Value>,
props: BTreeMap<(String, &'static str), f64>,
log: Vec<String>,
rng: u32,
key: Option<f64>,
frame: u32,
/// Text fields' text, by name.
texts: BTreeMap<String, String>,
}
#[test]
fn timeline_calls_lower_to_actions() {
let a = actions("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();");
assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }, Action::NextFrame { target: t("") }, Action::PrevFrame { target: t("") }, Action::NextScene, Action::PrevScene]);
// Frames are 1-based in ActionScript, 0-based in the IR; strings are labels.
let a = actions(r#"gotoAndStop(1); gotoAndPlay("run"); gotoAndPlay(12, "Scene 2"); gotoAndStop('end', null); gotoAndStop(2 + 3);"#);
assert_eq!(
a,
vec![
Action::GotoAndStop { target: t(""), frame: FrameRef::Number(0), scene: None },
Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("run".into()), scene: None },
Action::GotoAndPlay { target: t(""), frame: FrameRef::Number(11), scene: Some("Scene 2".into()) },
Action::GotoAndStop { target: t(""), frame: FrameRef::Label("end".into()), scene: None },
Action::GotoAndStop { target: t(""), frame: FrameRef::Number(4), scene: None },
]
);
}
#[test]
fn instance_paths_become_targets() {
let a = actions("hero_mc.gotoAndStop(\"run\");\nthis.hero_mc.arm_mc.play();\nMovieClip(parent).stop();\nMovieClip(this.parent.parent).nextFrame();\nMovieClip(root).menu.play();\n(root as MovieClip).stop();\nhero_mc.root.stop();\nObject(parent).door.prevFrame();");
let targets: Vec<String> = a.iter().map(|a| a.target().map(|t| t.0.clone()).unwrap_or_default()).collect();
assert_eq!(targets, ["hero_mc", "hero_mc.arm_mc", "parent", "parent.parent", "root.menu", "root", "root", "parent.door"]);
assert!(a.iter().all(|x| x.check().is_ok()));
}
#[test]
fn properties_are_set_to_values() {
let a = actions("hero_mc.x = 100;\nhero_mc.y = -20.5;\nhero_mc.alpha = .5;\nhero_mc.visible = false;\ndoor.rotation = 45;\ndoor.scaleX = 2; door.scaleY = 1.5\nalpha = 0.25;");
assert_eq!(
a,
vec![
Action::SetProperty { target: t("hero_mc"), property: Property::X, value: 100.0 },
Action::SetProperty { target: t("hero_mc"), property: Property::Y, value: -20.5 },
Action::SetProperty { target: t("hero_mc"), property: Property::Alpha, value: 0.5 },
Action::SetProperty { target: t("hero_mc"), property: Property::Visible, value: 0.0 },
Action::SetProperty { target: t("door"), property: Property::Rotation, value: 45.0 },
Action::SetProperty { target: t("door"), property: Property::ScaleX, value: 2.0 },
Action::SetProperty { target: t("door"), property: Property::ScaleY, value: 1.5 },
Action::SetProperty { target: t(""), property: Property::Alpha, value: 0.25 },
]
);
}
#[test]
fn trace_writes_literals_and_their_sums_as_actionscript_does() {
let msgs: Vec<String> = actions(r#"trace("hello"); trace('a' + 1 + 2); trace(1 + 2 + "a"); trace(0.1, true, null, undefined); trace(1e21, 1e-7, -0, 5 / 2, 7 % 4); trace(); trace("tab\there é \x41");"#)
.into_iter()
.map(|a| match a {
Action::Trace { message } => message,
other => panic!("{other:?}"),
impl World for Mock {
fn act(&mut self, base: Base, a: &Action) -> Result<(), Option<String>> {
if let Action::GotoAndStop { frame: FrameRef::Number(n), .. } = a {
self.frame = *n;
}
self.log.push(format!("{base:?} {}", a.describe()));
Ok(())
}
fn get(&mut self, at: &Place, p: Prop) -> Result<Value, String> {
if at.path.0 == "ghost" {
return Err("no instance named “ghost” here".into());
}
Ok(match p {
Prop::CurrentFrame => Value::Num(f64::from(self.frame + 1)),
Prop::Name => Value::str(&at.to_string()),
Prop::Visible => Value::Bool(true),
Prop::Text | Prop::Length => {
let t = self.texts.get(&at.path.0).ok_or_else(|| format!("“{at}” isn't a text field"))?;
if p == Prop::Text { Value::str(t) } else { Value::Num(text_len(t) as f64) }
}
p => Value::Num(self.props.get(&(at.path.0.clone(), p.name())).copied().unwrap_or(0.0)),
})
.collect();
assert_eq!(msgs, ["hello", "a12", "3a", "0.1 true null undefined", "1e+21 1e-7 0 2.5 3", "", "tab\there é A"]);
}
#[test]
fn listeners_lower_to_handlers_with_their_bodies() {
let src = "import flash.events.MouseEvent;\n\nstop();\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(e:MouseEvent):void {\n\tgotoAndPlay(\"walk\"); // on\n\ttrace(\"go\");\n}\nmenu.btn.addEventListener(MouseEvent.ROLL_OVER, function (event:MouseEvent):void { MovieClip(event.currentTarget).gotoAndStop(2); });\naddEventListener(\"mouseDown\", onPlay);";
let c = ok(src);
assert_eq!(c.ops.len(), 4);
assert_eq!(c.ops[0], ScriptOp::Action(Action::Stop { target: t("") }));
let ScriptOp::Listen(l) = &c.ops[1] else { panic!("{:?}", c.ops[1]) };
assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("play_btn", ButtonEvent::Click, "onPlay"));
assert_eq!(*l.actions, vec![Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("walk".into()), scene: None }, Action::Trace { message: "go".into() }]);
let ScriptOp::Listen(l) = &c.ops[2] else { panic!() };
// `currentTarget` is the instance listened to, named from the script's timeline.
assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("menu.btn", ButtonEvent::Over, "function at line 10"));
assert_eq!(*l.actions, vec![Action::GotoAndStop { target: t("menu.btn"), frame: FrameRef::Number(1), scene: None }]);
let ScriptOp::Listen(l) = &c.ops[3] else { panic!() };
assert_eq!((l.target.is_this(), l.event), (true, ButtonEvent::Press));
assert!(l.describe().starts_with("On press (this): Go to “walk” and play"), "{}", l.describe());
for (k, e) in [("MOUSE_UP", ButtonEvent::Release), ("ROLL_OUT", ButtonEvent::Out), ("MOUSE_OVER", ButtonEvent::Over), ("MOUSE_OUT", ButtonEvent::Out)] {
let c = ok(&format!("b.addEventListener(MouseEvent.{k}, f, false, 0, true); function f(e) {{}}"));
assert!(matches!(&c.ops[0], ScriptOp::Listen(l) if l.event == e), "{k}");
}
fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option<String>> {
let name = Prop::from_name(match p {
Property::X => "x",
Property::Y => "y",
Property::Alpha => "alpha",
Property::Visible => "visible",
Property::Rotation => "rotation",
Property::ScaleX => "scaleX",
Property::ScaleY => "scaleY",
})
.map_or("?", Prop::name);
self.props.insert((at.path.0.clone(), name), v);
Ok(())
}
fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option<String>> {
if !self.texts.contains_key(&at.path.0) {
return Err(Some(format!("“{at}” isn't a text field")));
}
self.log.push(format!("text {at} = {text}"));
self.texts.insert(at.path.0.clone(), text);
Ok(())
}
fn trace(&mut self, line: String) {
self.log.push(line);
}
fn read(&mut self, name: &str) -> Result<Value, String> {
match self.vars.get(name) {
Some(v) => Ok(v.clone()),
None => self.decls.vars.get(name).map(|t| t.default_value()).ok_or_else(|| format!("`{name}` isn't defined")),
}
}
fn write(&mut self, name: &str, v: Value) -> Result<(), String> {
let t = *self.decls.vars.get(name).ok_or_else(|| format!("`{name}` isn't defined"))?;
self.vars.insert(name.to_string(), t.coerce(v));
Ok(())
}
fn function(&mut self, name: &str) -> Option<Arc<Function>> {
self.decls.functions.get(name).cloned()
}
fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc<Function>, add: bool) -> Result<(), Option<String>> {
self.log.push(format!("{} {} {at} {}", if add { "listen" } else { "unlisten" }, ev.key(), f.name));
Ok(())
}
fn random(&mut self) -> f64 {
self.rng = self.rng.wrapping_mul(1_103_515_245).wrapping_add(12345);
f64::from(self.rng >> 8) / f64::from(1u32 << 24)
}
fn same(&mut self, a: &Place, b: &Place) -> Result<bool, String> {
Ok(a == b)
}
fn key_code(&mut self) -> Result<f64, String> {
self.key.ok_or_else(|| "there's no keyboard event here".into())
}
}
/// Compiles and runs `src` on a fresh timeline; the log and how the run ended.
fn exec(src: &str) -> (Vec<String>, Result<(), Stop>, Mock) {
let c = ok(src);
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
assert!(m.decls.problems(&c).is_empty(), "{:?}", m.decls.problems(&c));
let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
(std::mem::take(&mut m.log), r, m)
}
fn lines(src: &str) -> Vec<String> {
let (log, r, _) = exec(src);
assert_eq!(r, Ok(()), "{src}: {log:?}");
log
}
#[test]
fn own_functions_run_where_they_are_called() {
let a = actions("function go(n:int = 1):void { gotoAndStop(3); return; trace(\"never\"); }\ngo();\nfunction twice() { go(); go(); }\ntwice();");
assert_eq!(a.len(), 3, "{a:?}");
assert!(a.iter().all(|x| matches!(x, Action::GotoAndStop { frame: FrameRef::Number(2), .. })));
fn timeline_calls_run_as_actions() {
let a = lines("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();\ngotoAndStop(1); gotoAndPlay(\"run\"); gotoAndPlay(12, \"Scene 2\"); gotoAndStop('end', null); gotoAndStop(2 + 3);");
assert_eq!(a, ["This Stop", "This Play", "This Next frame", "This Previous frame", "This Next scene", "This Previous scene", "This Go to frame 1 and stop", "This Go to “run” and play", "This Go to frame 12 in “Scene 2” and play", "This Go to “end” and stop", "This Go to frame 5 and stop"]);
let a = lines("hero_mc.gotoAndStop(\"run\");\nthis.hero_mc.arm_mc.play();\nMovieClip(parent).stop();\nMovieClip(this.parent.parent).nextFrame();\nMovieClip(root).menu.play();\n(root as MovieClip).stop();\nhero_mc.root.stop();\nObject(parent).door.prevFrame();");
assert_eq!(a, ["This Go to “run” and stop (hero_mc)", "This Play (hero_mc.arm_mc)", "This Stop (parent)", "This Next frame (parent.parent)", "This Play (root.menu)", "This Stop (root)", "This Stop (root)", "This Previous frame (parent.door)"]);
}
#[test]
fn typed_variables_coerce_as_actionscript_does() {
let a = lines(
"var n:int = 7.9; var u:uint = -1; var num:Number = \"2.5\"; var b:Boolean = \"no\"; var s:String = 12; var z:String; var any = \"x\";\n\
var big:int = 2147483647; big = big + 1;\n\
var nan:Number; var none:int;\n\
trace(n, u, num, b, s, z, any, big, nan, none);\n\
n += 0.7; n++; ++n; trace(n, n++ + n, --n);",
);
assert_eq!(a, ["7 4294967295 2.5 true 12 null x -2147483648 NaN 0", "9 19 9"]);
}
#[test]
fn expressions_follow_ecmascript() {
let a = lines(
r#"trace(1 + 2 * 3 - 4 / 8, 7 % 3, -7 % 3, 1 / 0, -1 / 0, 0 / 0);
trace("a" + 1 + 2, 1 + 2 + "a", "5" * "2", "x" - 1, true + 1, null + 1, undefined + 1);
trace(1 < 2, "b" < "a", "10" < "9", 10 < "9", NaN < 1, NaN >= 1, 2 >= 2);
trace(1 == "1", 1 === "1", null == undefined, null === undefined, 0 == false, "" == 0, NaN == NaN, "a" != "b");
trace(0 || "x", 1 && "y", !0, !"", true ? "t" : "f", null || undefined);
trace(int("12px"), int(" 0x1F "), Number(""), Number("1e3"), String(null), Boolean("false"), uint(-2), Number("Infinity"), Number("infinity"));
trace(Math.min(3, 1, 2), Math.max(), Math.min(1, NaN), Math.abs(-4.5), Math.floor(-1.5), Math.ceil(1.2), Math.round(2.5), Math.round(-2.5), Math.round(-0.4), Math.PI > 3.14);"#,
);
assert_eq!(
a,
[
"6.5 1 -1 Infinity -Infinity NaN",
"a12 3a 10 NaN 2 1 NaN",
"true false true false false false true",
"true false true false true true false true",
"x y true true t undefined",
"0 31 0 1000 null true 4294967294 Infinity NaN",
"1 -Infinity NaN 4.5 -2 2 3 -2 0 true",
]
);
}
#[test]
fn if_else_and_loops_run_with_break_and_continue() {
let a = lines(
"var total:int = 0;\n\
for (var i:int = 0; i < 10; i++) { if (i == 2) continue; if (i > 5) break; total += i; }\n\
trace(total, i);\n\
var k:int = 3; while (k > 0) { k--; } trace(k);\n\
do { k++; } while (k < 2); trace(k);\n\
do { k = 100; } while (false); trace(k);\n\
if (k > 50) trace(\"big\"); else if (k > 5) trace(\"mid\"); else trace(\"small\");\n\
for (;;) { break; } trace(\"out\");",
);
assert_eq!(a, ["13 6", "0", "2", "100", "big", "out"]);
}
#[test]
fn functions_take_parameters_return_values_and_recurse() {
let a = lines(
"function add(a:int, b:int = 10):int { return a + b; }\n\
function fact(n:Number):Number { if (n <= 1) return 1; return n * fact(n - 1); }\n\
function hello(who:String):void { trace(\"hi \" + who); return; trace(\"never\"); }\n\
function untyped(x) { return x; }\n\
trace(add(1, 2), add(5), add(1.9, 0.9), fact(5), untyped(\"u\"), hello(\"you\"));\n\
function loopy():int { var s:int; for (var j:int = 0; j < 4; j++) s += j; return s; } trace(loopy(), loopy());",
);
assert_eq!(a, ["hi you", "3 15 1 120 u undefined", "6 6"]);
}
#[test]
fn properties_are_read_and_set() {
let (log, r, m) = exec("hero.x = 10; hero.x += 5; hero.alpha = .5; trace(hero.x, hero.alpha, hero.name, currentFrame, this.currentFrame, hero.visible);\ngotoAndStop(4); trace(currentFrame);\nhero.rotation = hero.x * 2;");
assert_eq!(r, Ok(()));
assert_eq!(log, ["15 0.5 hero 1 1 true", "This Go to frame 4 and stop", "4"]);
assert_eq!(m.props.get(&("hero".into(), "rotation")), Some(&30.0));
// Reading an instance that isn't there stops the script there.
let (log, r, _) = exec("trace(\"a\");\ntrace(ghost.x);\ntrace(\"b\");");
assert_eq!(log, ["a"]);
assert_eq!(r, Err(Stop::Error { line: 2, message: "no instance named “ghost” here".into() }));
}
#[test]
fn listeners_name_their_events_and_functions() {
let c = ok("import flash.events.*;\nbtn.addEventListener(MouseEvent.CLICK, go);\naddEventListener(Event.ENTER_FRAME, tick);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { if (e.keyCode == Keyboard.LEFT) trace(\"left\"); });\nbtn.removeEventListener(MouseEvent.CLICK, go);\nfunction go(e:MouseEvent):void { MovieClip(e.currentTarget).gotoAndStop(2); trace(e.target.name); }\nfunction tick(e:Event):void {}\nhero.addEventListener(\"mouseOver\", go, false, 0, true);");
assert_eq!(c.inner.len(), 1);
assert_eq!(c.functions.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["go", "tick"]);
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
assert_eq!(r, Ok(()));
assert_eq!(m.log, ["listen click btn go", "listen enter_frame this tick", "listen key_down stage function at line 4, column 48", "unlisten click btn go", "listen over hero go"]);
// The listener functions: the event's key code, target and current target.
m.log.clear();
m.key = Some(37.0);
let key = c.inner[0].clone();
assert_eq!(run::run_listener(&mut m, &key, 1000).1, Ok(()));
let go = c.functions[0].clone();
assert_eq!(run::run_listener(&mut m, &go, 1000).1, Ok(()));
assert_eq!(m.log, ["left", "Current Go to frame 2 and stop", "e.target"]);
// Keyboard listeners belong on the stage; elsewhere they are ignored and noted.
let c = ok("addEventListener(KeyboardEvent.KEY_UP, f); function f(e) {}");
assert!(c.body.is_empty() && c.notes[0].message.starts_with("keys go to the stage"), "{c:?}");
}
#[test]
fn names_from_other_frames_link_through_the_timeline() {
let frame1 = ok("var score:int = 0;\nfunction addPoints(n:int):void { score += n; }\nfunction shout():String { return \"score \" + score; }");
let frame5 = ok("addPoints(3);\nscore = score * 2;\ntrace(shout(), lives);");
assert_eq!(frame5.free.iter().map(|f| (f.name.as_str(), f.call)).collect::<Vec<_>>(), [("addPoints", true), ("score", false), ("shout", true), ("lives", false)]);
let d = Decls::build([&frame1, &frame5]);
let p = d.problems(&frame5);
assert_eq!(p.len(), 1, "{p:?}");
assert_eq!((p[0].line, p[0].column), (3, 16));
assert!(p[0].message.starts_with("`lives` isn't a variable of this timeline"), "{}", p[0].message);
let ok5 = ok("addPoints(3);\nscore = score * 2;\ntrace(shout());");
let d = Decls::build([&frame1, &ok5]);
assert!(d.problems(&ok5).is_empty() && d.problems(&frame1).is_empty());
let mut m = Mock { decls: d, ..Mock::default() };
for c in [&frame1, &ok5] {
assert_eq!(run::run_script(&mut m, &c.body, &c.inner, 10_000).1, Ok(()));
}
assert_eq!(m.log, ["score 6"]);
// A function declared on two frames, or a variable with two types, is a problem.
let again = ok("function shout():String { return \"again\"; }\nvar score:String;");
let d = Decls::build([&frame1, &again]);
assert_eq!(d.problems(&again).len(), 2, "{:?}", d.problems(&again));
}
#[test]
fn fuel_stops_an_endless_loop_cleanly() {
let c = ok("trace(\"before\");\nwhile (true) {}\ntrace(\"after\");");
let mut m = Mock::default();
let (used, r) = run::run_script(&mut m, &c.body, &c.inner, 5_000);
assert_eq!((used, r), (5_000, Err(Stop::Fuel)));
assert_eq!(m.log, ["before"]);
// Recursion is bounded by depth, text by length, and both stop the run.
let (_, r, _) = exec("function f(n:int):int { return f(n + 1); } f(0);");
assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("more than 16 deep")), "{r:?}");
let (_, r, _) = exec("var s:String = \"x\"; while (true) s = s + s;");
assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("longer than 16384")), "{r:?}");
// Building text costs fuel for its length.
let c = ok("var s:String = \"\"; for (var i:int = 0; i < 100000; i++) s = s + \"ab\";");
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
assert_eq!(run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN).1, Err(Stop::Fuel));
}
#[test]
fn random_comes_from_the_world() {
let a = lines("var r:Number = Math.random(); trace(r >= 0 && r < 1, Math.floor(Math.random() * 6) + 1 <= 6);");
assert_eq!(a, ["true true"]);
}
#[test]
fn calls_outside_the_movie_are_ignored_and_noted() {
let c = ok("navigateToURL(new URLRequest(\"https://example.com\"), \"_blank\");\nflash.net.navigateToURL(x);\nExternalInterface.call(\"f\");\nfscommand(\"quit\");\nbtn.buttonMode = true;\nstop();");
assert_eq!(c.ops, vec![ScriptOp::Action(Action::Stop { target: t("") })]);
assert_eq!(c.body.len(), 1);
let lines: Vec<u32> = c.notes.iter().map(|n| n.line).collect();
assert_eq!(lines, [1, 2, 3, 4, 5]);
assert!(c.notes[0].message.contains("navigateToURL") && c.notes[0].message.contains("ignored"), "{:?}", c.notes);
@@ -127,50 +293,52 @@ fn calls_outside_the_movie_are_ignored_and_noted() {
#[test]
fn comments_white_space_and_semicolons_are_read_as_actionscript_does() {
// Line and block comments, CR LF line ends, no semicolons, a BOM, empty statements.
let a = actions("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\"");
assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }]);
let a = lines("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\"");
assert_eq!(a, ["This Stop", "This Play"]);
assert_eq!(err("stop() play()"), (1, 8, "expected `;` or a new line, found `play`".into()));
}
#[test]
fn every_problem_says_where_it_is() {
let cases: &[(&str, u32, u32, &str)] = &[
("stop();\nif (x) { play(); }", 2, 1, "`if` statements aren't supported yet"),
("var n:int = 0;", 1, 1, "variables (`var`) aren't supported yet"),
(" for (var i = 0; i < 3; i++) {}", 1, 3, "`for` loops aren't supported yet"),
("while (true) stop();", 1, 1, "`while` loops aren't supported yet"),
(" for each (var v in list) {}", 1, 3, "`for each` loops aren't supported yet"),
("for (var k in o) {}", 1, 1, "`for in` loops aren't supported yet"),
("switch (x) { case 1: stop(); }", 1, 1, "`switch` statements aren't supported yet"),
("hero.x += 5;", 1, 1, "`+=` reads a value first"),
("var a:Array = [];", 1, 7, "variables of type `Array` aren't supported yet"),
("var x:int = 1;", 1, 5, "`x` is already a name of the timeline"),
("hero.width = 5;", 1, 1, "setting `width` isn't supported yet"),
("score = 5;", 1, 1, "setting `score` isn't supported: variables"),
("foo();", 1, 1, "`foo` isn't declared in this frame script"),
("currentFrame = 5;", 1, 1, "`currentFrame` can only be read"),
("hero.addChild(x);", 1, 1, "calling `addChild` isn't supported"),
("gotoAndStop(0);", 1, 13, "a frame number is a whole number from 1"),
("gotoAndStop(1.5);", 1, 13, "a frame number is a whole number"),
("gotoAndStop(frame);", 1, 13, "reading `frame` isn't supported"),
("gotoAndStop();", 1, 1, "`gotoAndStop` takes a frame"),
("stop(1);", 1, 1, "`stop()` takes no arguments"),
("hero.nextScene();", 1, 1, "call `nextScene()` in the main timeline's own script"),
("trace(hero.x);", 1, 7, "reading properties isn't supported"),
("trace([1]);", 1, 7, "only values written out"),
("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "the stage isn't supported"),
("b.addEventListener(Event.ENTER_FRAME, f); function f(e) {}", 1, 20, "listening for Event.ENTER_FRAME isn't supported yet"),
("b.addEventListener(MouseEvent.CLICK, nope);", 1, 38, "`nope` isn't a function declared"),
("trace(hero.width);", 1, 7, "reading `width` isn't supported yet"),
("trace([1]);", 1, 7, "arrays aren't supported yet"),
("trace(stage.stageWidth);", 1, 7, "`stage.stageWidth` isn't supported yet"),
("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "mouse listeners on the stage"),
("b.addEventListener(Event.RESIZE, f); function f(e) {}", 1, 20, "listening for Event.RESIZE isn't supported yet"),
("b.addEventListener(MouseEvent.CLICK, f); function f() { stop(); }", 1, 42, "a listener function takes the event"),
("b.addEventListener(MouseEvent.CLICK, f, true); function f(e) {}", 1, 41, "capture-phase listeners"),
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { trace(e.target.name); }", 1, 64, "reading the event `e`"),
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { e.target.play(); }", 1, 58, "`target` can be a part inside"),
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { c.addEventListener(MouseEvent.CLICK, f); }", 1, 58, "adding a listener from inside a listener"),
("b.removeEventListener(MouseEvent.CLICK, f);", 1, 1, "removing listeners isn't supported yet"),
("function f() { f(); } f();", 1, 16, "`f` calls itself"),
("b.addEventListener(MouseEvent.CLICK, f); function f(e:MouseEvent) { trace(e.stageX); }", 1, 75, "reading the event's `stageX`"),
("b.removeEventListener(MouseEvent.CLICK, function (e) {});", 1, 41, "a function written in place can't be removed"),
("function stop() {}", 1, 1, "a function named `stop` would hide"),
("function f() {} function f() {}", 1, 17, "`f` is declared twice"),
("function f() { function g() {} } f();", 1, 16, "functions declared inside functions"),
("function f(n) { n.play(); } f(1);", 1, 17, "reading the parameter `n`"),
("function f(a:int, n) { n.play(); } f(1, 2);", 1, 24, "`n` is a variable, not an instance"),
("function f(a:int) {} f();", 1, 22, "`f` takes 1 argument, not 0"),
("function f(...rest) {}", 1, 15, "rest parameters"),
("var n:int; n.play();", 1, 12, "`n` is a variable, not an instance"),
("var s:String = \"ab\"; trace(s.length);", 1, 28, "reading `length` of a value"),
("hero_mc[\"arm\"].play();", 1, 1, "this isn't an instance"),
("hero_mc.x = \"10\";", 1, 13, "`x` is set to a number"),
("hero_mc.x = 1 / 0;", 1, 13, "the value must be a finite number"),
("trace(new Date());", 1, 7, "`new` isn't supported yet"),
("trace(1 & 2);", 1, 7, "the `&` operator isn't supported yet"),
("var n:int; n <<= 2;", 1, 12, "`<<=` isn't supported yet"),
("break;", 1, 1, "`break` is only for loops here"),
("trace(stop());", 1, 7, "`stop()` gives no value"),
("trace(Math.sqrt(4));", 1, 7, "`Math.sqrt` isn't supported yet"),
("trace(Keyboard.WIGGLE);", 1, 7, "`Keyboard.WIGGLE` isn't a key"),
("package { }", 1, 1, "`package` belongs to class files"),
("class Hero {}", 1, 1, "`class` belongs to class files"),
("public function f() {}", 1, 1, "`public` declarations belong to classes"),
@@ -183,9 +351,8 @@ fn every_problem_says_where_it_is() {
("stop(); #", 1, 9, "unexpected character '#'"),
("var re = /ab+c/;", 1, 10, "regular expressions aren't supported"),
("1 = 2;", 1, 3, "the left side of this assignment can't be assigned to"),
("x++;", 1, 1, "`++` and `--` read a value first"),
("é.play();", 1, 1, "`é` isn't an instance name AniCraft can address"),
("\tstop();\n\t\tif (a) {}", 2, 3, "`if` statements"),
("\tstop();\n\t\twith (a) {}", 2, 3, "`with` statements"),
];
for (src, line, col, msg) in cases {
let (l, c, m) = err(src);
@@ -195,19 +362,34 @@ fn every_problem_says_where_it_is() {
#[test]
fn every_problem_is_listed_and_nothing_half_runs() {
let p = compile("stop();\nvar a = 1;\nif (a) {}\nplay();\nhero.width = 3;").unwrap_err();
let p = compile("stop();\nvar a:Array;\nswitch (a) {}\nplay();\nhero.width = 3;").unwrap_err();
let at: Vec<(u32, u32)> = p.iter().map(|p| (p.line, p.column)).collect();
assert_eq!(at, [(2, 1), (3, 1), (5, 1)]);
assert_eq!(p[0].to_string(), "line 2, column 1: variables (`var`) aren't supported yet");
let many: String = (0..200).map(|i| format!("var v{i} = {i};\n")).collect();
assert_eq!(at, [(2, 7), (3, 1), (5, 1)]);
let many: String = (0..200).map(|i| format!("hero.w{i} = {i};\n")).collect();
assert_eq!(compile(&many).unwrap_err().len(), MAX_PROBLEMS);
}
#[test]
fn number_text_matches_actionscript() {
for (n, s) in [(0.0, "0"), (-0.0, "0"), (5.0, "5"), (-3.25, "-3.25"), (0.1 + 0.2, "0.30000000000000004"), (1e21, "1e+21"), (1.5e-7, "1.5e-7"), (123456789012.0, "123456789012"), (f64::NAN, "NaN"), (f64::NEG_INFINITY, "-Infinity"), (0.000001, "0.000001")] {
assert_eq!(lower::number_text(n), s, "{n}");
assert_eq!(number_text(n), s, "{n}");
}
for (s, n) in [("", 0.0), (" 12 ", 12.0), ("1e3", 1000.0), (".5", 0.5), ("5.", 5.0), ("-0x10", f64::NAN), ("0x10", 16.0), ("0b101", 5.0), ("+Infinity", f64::INFINITY), ("inf", f64::NAN), ("1_0", f64::NAN), ("\u{a0}7\u{feff}", 7.0), ("1e", f64::NAN), ("-", f64::NAN)] {
let v = string_number(s);
assert!(v == n || (v.is_nan() && n.is_nan()), "{s:?}: {v}");
}
assert_eq!((to_int32(4_294_967_296.0 + 5.0), to_int32(-1.5), to_uint32(-1.0), to_int32(f64::NAN)), (5, -1, 4_294_967_295, 0));
assert_eq!((run::round(0.49999999999999994), run::round(-0.5), run::round(1.5)), (0.0, 0.0, 2.0));
}
#[test]
fn the_ir_reads_and_writes_as_json() {
let c = ok("var n:Number = NaN; var s:String = \"a\"; if (n != n) trace(s + 1, -Infinity); function f(e:MouseEvent = null):void {} btn.addEventListener(MouseEvent.CLICK, f);");
let v = serde_json::to_value(&c).unwrap();
let back: Compiled = serde_json::from_value(v.clone()).unwrap();
assert_eq!(back, c);
let text = v.to_string();
assert!(text.contains("\"nan\"") && text.contains("{\"inf\":false}") && text.contains("\"s\":\"if\""), "{text}");
}
#[test]
@@ -218,25 +400,41 @@ fn limits_are_problems_not_crashes() {
assert!(err(&deep).2.contains("nested more than"));
let deep = format!("trace({}1);", "-".repeat(100_000));
assert!(err(&deep).2.contains("nested more than"));
let deep = format!("{}1;", "a = ".repeat(10_000));
let deep = format!("var a; {}1;", "a = ".repeat(10_000));
assert!(err(&deep).2.contains("nested more than"));
// A long row of operators would make a deep tree; it counts as nesting.
let long = format!("trace({}1);", "1 + ".repeat(10_000));
let m = err(&long).2;
assert!(m.contains("too many operators in a row") || m.contains("nested more than"), "{m}");
let deep = format!("b.addEventListener(\"click\", {}", "function (e) { ".repeat(5_000));
assert!(err(&deep).2.contains("nested more than"));
let long = "stop();".repeat(MAX_RUN_BYTES / 7 + 1);
assert!(err(&long).2.contains("longer than 256 KiB"));
let tokens = ";".repeat(MAX_TOKENS + 1);
assert!(err(&tokens).2.contains("tokens"));
let steps = "stop();".repeat(crate::MAX_ACTIONS + 1);
assert!(err(&steps).2.contains("at most 256 steps"));
// Calls that fan out are bounded, however deep they could go.
let mut src = String::from("function f0() { stop(); }\n");
for i in 1..16 {
src.push_str(&format!("function f{i}() {{ {} }}\n", format!("f{}(); ", i - 1).repeat(8)));
}
/// The deepest code the limits allow runs in a small stack: calls 16 deep, each as nested as
/// the parser lets code be.
#[test]
fn the_deepest_allowed_code_fits_a_small_stack() {
let nest = |depth: usize| format!("{}n{}", "(1 + ".repeat(depth), ")".repeat(depth));
let mut src = String::from("function f0(n:int):int { return n; }\n");
for i in 1..20 {
src.push_str(&format!("function f{i}(n:int):int {{ return f{}({}); }}\n", i - 1, nest(18)));
}
src.push_str("f15();");
let t0 = std::time::Instant::now();
assert!(compile(&src).is_err());
assert!(t0.elapsed().as_secs_f32() < 5.0);
src.push_str("trace(f19(0));");
let c = ok(&src);
let r = std::thread::Builder::new()
.stack_size(512 * 1024)
.spawn(move || {
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN).1
})
.unwrap()
.join()
.unwrap();
assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("deep")), "{r:?}");
}
/// A small deterministic generator (no clock, no randomness crate).
@@ -256,20 +454,25 @@ impl Rng {
#[test]
fn hostile_input_never_panics_and_ends_quickly() {
const PIECES: [&str; 64] = [
"stop", "play", "gotoAndStop", "(", ")", "{", "}", "[", "]", ";", ",", ".", "\n", " ", "\"a", "\"", "'", "\\", "/*", "*/", "//", "1", "0x", "1e", ".5", "e", "function", "f", "e:MouseEvent", ":void", "addEventListener", "MouseEvent.CLICK", "=", "+", "-", "!", "?", ":", "if", "else", "var", "for", "new", "this", "parent", "root", "MovieClip", "as", "trace", "x", "alpha", "é", "\u{0}", "\r", "\t", "<", ">", "...", "::", "..", ".<", "return", "import", "@",
const PIECES: [&str; 80] = [
"stop", "play", "gotoAndStop", "(", ")", "{", "}", "[", "]", ";", ",", ".", "\n", " ", "\"a", "\"", "'", "\\", "/*", "*/", "//", "1", "0x", "1e", ".5", "e", "function", "f", "e:MouseEvent", ":void", "addEventListener", "MouseEvent.CLICK", "=", "+", "-", "!", "?", ":", "if", "else", "var", "for", "new", "this", "parent", "root", "MovieClip", "as", "trace", "x", "alpha", "é", "\u{0}", "\r", "\t", "<", ">", "...", "::", "..", ".<", "return", "import", "@", "while", "do", "break", "continue", "int", "n", "++", "+=", "==", "&&", "||", "Math.random()", "e.keyCode", "stage", "Event.ENTER_FRAME", "removeEventListener",
];
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
let t0 = std::time::Instant::now();
let mut compiled = 0;
for _ in 0..4_000 {
for _ in 0..5_000 {
let n = rng.next() as usize % 80;
let src: String = (0..n).map(|_| rng.pick(&PIECES)).collect();
if compile(&src).is_ok() {
if let Ok(c) = compile(&src) {
compiled += 1;
// What compiles runs, within its fuel, whatever it is.
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
let _ = run::run_script(&mut m, &c.body, &c.inner, 2_000);
for f in &c.functions {
let _ = run::run_listener(&mut m, f, 2_000);
}
}
}
// Raw bytes as text, too.
for _ in 0..1_000 {
let n = rng.next() as usize % 200;
let bytes: Vec<u8> = (0..n).map(|_| rng.next() as u8).collect();
@@ -286,8 +489,65 @@ fn compiles_once_per_script() {
let b: *const crate::CompileResult = s.compiled();
assert!(std::ptr::eq(a, b));
assert!(s.runs());
// A copy compiles on its own (its text may change); equality ignores the cache.
let c = s.clone();
assert_eq!(c, s);
assert!(!crate::SourceScript::new(crate::Language::ActionScript1or2, "stop();").runs());
}
#[test]
fn trace_lines_are_cut_at_whole_characters() {
let long = "é".repeat(2000);
let cut = run::trace_line(long);
assert_eq!(cut.chars().count(), crate::MAX_TRACE_CHARS + 1);
let emoji = format!("{}{}", "a".repeat(crate::MAX_TRACE_CHARS - 1), "😀".repeat(5));
assert_eq!(run::trace_line(emoji).encode_utf16().count(), crate::MAX_TRACE_CHARS);
}
#[test]
fn a_full_budget_runs_quickly() {
let c = ok("var n:int = 0; var s:Number = 0; while (true) { n++; s += Math.abs(n % 7 - 3) * 0.5; }");
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
let t0 = std::time::Instant::now();
let (used, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
let ms = t0.elapsed().as_secs_f64() * 1000.0;
eprintln!("{used} fuel in {ms:.2} ms");
assert_eq!(r, Err(Stop::Fuel));
assert!(ms < 500.0, "{ms} ms");
}
#[test]
fn scripts_set_append_and_read_text_fields() {
let src = r#"
var n:int = 3;
score_txt.text = "Score: " + n;
score_txt.appendText("!");
score_txt.text += "?";
trace(score_txt.text, score_txt.length);
panel.name_txt.text = String(score_txt.length * 2);
var text:String = "a variable named text";
trace(text);
"#;
let c = ok(src);
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
m.texts.insert("score_txt".into(), String::new());
m.texts.insert("panel.name_txt".into(), "x".into());
let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
assert_eq!(r, Ok(()));
assert_eq!(m.texts["score_txt"], "Score: 3!?");
assert_eq!(m.texts["panel.name_txt"], "20");
assert!(m.log.contains(&"Score: 3!? 10".to_string()), "{:?}", m.log);
assert!(m.log.contains(&"a variable named text".to_string()), "a bare `text` stays a variable");
// Setting null stops the script with a message; `this.text` and the stage aren't fields.
let (_, r, _) = {
let c = ok("score_txt.text = null;");
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
m.texts.insert("score_txt".into(), String::new());
let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
((), r, ())
};
assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("not null")), "{r:?}");
assert!(err("this.text = 'x';").2.contains("isn't a text field"));
assert!(err("stage.text = 'x';").2.contains("text field") || err("stage.text = 'x';").2.contains("stage"));
assert!(err("a_txt.appendText();").2.contains("one argument"));
assert!(err("a_txt.length = 3;").2.contains("can only be read"));
}
+2 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "anicraft-audio"
description = "AniCraft L0: sound decoding (WAV, Ogg Vorbis, MP3), deterministic mixing and resampling, WAV writing, waveform peaks"
description = "AniCraft L0: sound decoding (via craft-audio), deterministic mixing and resampling, WAV writing, waveform peaks"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,10 +8,7 @@ publish.workspace = true
repository.workspace = true
[dependencies]
# Ogg Vorbis decoding, pure Rust (MIT OR Apache-2.0; its `ogg` reader is BSD-3-Clause).
lewton = { version = "0.10", default-features = false, features = ["ogg"] }
# MP3 decoding, pure Rust port of minimp3 (MIT OR Apache-2.0). No SIMD helper crates.
nanomp3 = { version = "0.2", default-features = false, features = ["std", "layer12"] }
craft-audio.workspace = true
[lints]
workspace = true
+27 -59
View File
@@ -13,10 +13,8 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable, clippy::indexing_slicing)]
pub mod mix;
mod mp3;
mod peaks;
mod player;
mod vorbis;
pub mod wav;
pub use mix::{EnvPoint, Envelope, MixOptions, Voice, VoiceKind, mix};
@@ -119,16 +117,12 @@ impl Format {
/// Told apart by content, not by file name.
pub fn sniff(data: &[u8]) -> Option<Format> {
if data.len() >= 12 && data.starts_with(b"RIFF") && data.get(8..12) == Some(b"WAVE") {
return Some(Format::Wav);
match craft_audio::detect_container(data, None)? {
craft_audio::Container::Wav => Some(Format::Wav),
craft_audio::Container::Ogg => Some(Format::Vorbis),
craft_audio::Container::MpegAudio => Some(Format::Mp3),
_ => None,
}
if data.starts_with(b"OggS") {
return Some(Format::Vorbis);
}
if data.starts_with(b"ID3") || nanomp3::detect(data) {
return Some(Format::Mp3);
}
None
}
}
@@ -163,50 +157,32 @@ impl std::error::Error for AudioError {}
/// Decodes a WAV, Ogg Vorbis or MP3 file (told apart by content).
pub fn decode(data: &[u8]) -> Result<Pcm, AudioError> {
match Format::sniff(data).ok_or(AudioError::UnknownFormat)? {
Format::Wav => wav::decode(data),
Format::Vorbis => guarded(|| vorbis::decode(data)),
Format::Mp3 => guarded(|| mp3::decode(data)),
let _ = Format::sniff(data).ok_or(AudioError::UnknownFormat)?;
let opts = craft_audio::DecodeOptions::default().with_max_samples(MAX_SAMPLES as u64);
let (_, buf) = craft_audio::decode_with(data, None, &opts).map_err(|e| match e {
craft_audio::AudioError::TooLarge(_) => AudioError::TooLong,
craft_audio::AudioError::Unsupported(what) => AudioError::Unsupported(what),
craft_audio::AudioError::Malformed(_) | craft_audio::AudioError::Encode(_) | craft_audio::AudioError::Io(_) => AudioError::Unreadable,
_ => AudioError::Unreadable,
})?;
let frames = buf.frames();
let ch_count = buf.channels.len();
if frames == 0 || ch_count == 0 {
return Err(AudioError::Empty);
}
}
/// Runs a third-party decoder on untrusted data: should it panic on a malformed file, the
/// file is reported unreadable instead of taking the app down (golden rule 1).
fn guarded(f: impl FnOnce() -> Result<Pcm, AudioError>) -> Result<Pcm, AudioError> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or(Err(AudioError::Unreadable))
}
/// Collects decoded interleaved samples with `channels` channels, keeping at most two (the
/// first two: front left and right in WAV and Vorbis order), within [`MAX_SAMPLES`].
pub(crate) struct Collector {
pub channels: usize,
pub samples: Vec<f32>,
}
impl Collector {
pub fn new(channels: usize) -> Collector {
Collector { channels: channels.max(1), samples: Vec::new() }
}
pub fn out_channels(&self) -> u16 {
if self.channels >= 2 { 2 } else { 1 }
}
/// Appends whole frames from `src`; `Err(TooLong)` past the limit.
pub fn push(&mut self, src: &[f32]) -> Result<(), AudioError> {
let keep = usize::from(self.out_channels());
if self.samples.len() + src.len() / self.channels * keep > MAX_SAMPLES {
return Err(AudioError::TooLong);
let out_channels = if ch_count >= 2 { 2 } else { 1 };
let mut samples = Vec::with_capacity(frames.saturating_mul(usize::from(out_channels)));
if out_channels == 1 {
if let Some(c0) = buf.channels.first() {
samples.extend_from_slice(c0.get(..frames).unwrap_or(c0));
}
if self.channels == keep {
self.samples.extend_from_slice(src);
} else {
for frame in src.chunks_exact(self.channels) {
self.samples.extend(frame.iter().take(keep));
}
} else if let (Some(c0), Some(c1)) = (buf.channels.first(), buf.channels.get(1)) {
for i in 0..frames {
samples.push(c0.get(i).copied().unwrap_or(0.0));
samples.push(c1.get(i).copied().unwrap_or(0.0));
}
Ok(())
}
Pcm::new(buf.sample_rate, out_channels, samples)
}
#[cfg(test)]
@@ -301,12 +277,4 @@ mod tests {
let m = Pcm::new(8000, 1, vec![0.3]).unwrap();
assert_eq!(m.frame(0), (0.3, 0.3));
}
#[test]
fn collector_keeps_the_front_pair_of_surround_sound() {
let mut c = Collector::new(6);
c.push(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]).unwrap();
assert_eq!(c.samples, vec![1.0, 2.0, 7.0, 8.0]);
assert_eq!(c.out_channels(), 2);
}
}
+2 -1
View File
@@ -201,7 +201,8 @@ fn interpolate(p: &Pcm, t: f64, looping: bool) -> (f32, f32) {
let j = if looping { j.rem_euclid(len.max(1)) } else { j };
if (0..len).contains(&j) { p.frame(j as usize) } else { (0.0, 0.0) }
};
let (y0, y1, y2, y3) = (get(i - 1), get(i), get(i + 1), get(i + 2));
// Saturating: a hostile skip can put `t` at the end of the `i64` range.
let (y0, y1, y2, y3) = (get(i.saturating_sub(1)), get(i), get(i.saturating_add(1)), get(i.saturating_add(2)));
(hermite(y0.0, y1.0, y2.0, y3.0, x), hermite(y0.1, y1.1, y2.1, y3.1, x))
}
-33
View File
@@ -1,33 +0,0 @@
//! MP3 (MPEG-1/2 audio layers I–III) through `nanomp3` (pure Rust, MIT OR Apache-2.0). The
//! MP3 patents have expired; decoding is royalty-free. Tags are skipped, and the encoder delay
//! and padding are trimmed when the file's LAME tag records them (gapless).
use crate::{AudioError, Collector, Pcm};
pub fn decode(data: &[u8]) -> Result<Pcm, AudioError> {
let mut r = nanomp3::SliceReader::<f32>::new(data);
let mut col: Option<Collector> = None;
let mut rate = 0;
let mut buf: Vec<f32> = Vec::new();
loop {
match r.read_frame() {
Ok(Some(frame)) => {
buf.clear();
buf.extend_from_slice(frame);
let ch = r.channels().map_or(1, |c| usize::from(c.num()));
let c = col.get_or_insert_with(|| Collector::new(ch));
if c.channels != ch {
break;
}
rate = r.sample_rate();
c.push(&buf)?;
}
Ok(None) => break,
// The format changed mid-stream or the data is damaged: keep what came before.
Err(_) if col.as_ref().is_some_and(|c| !c.samples.is_empty()) => break,
Err(_) => return Err(AudioError::Unreadable),
}
}
let col = col.ok_or(AudioError::Unreadable)?;
Pcm::new(rate, col.out_channels(), col.samples)
}
+308 -22
View File
@@ -3,14 +3,23 @@
//! got (the audio clock drives the stage during playback, so picture follows sound).
//!
//! What it plays is [`mix`](crate::mix) of the current voices, so playback and export agree
//! sample for sample, apart from short ramps at starts and stops that keep them click-free.
//! sample for sample, apart from short ramps at starts and stops that keep them click-free, and
//! the monitor volume (ADR 0095), which is the listener's and never reaches an export.
//!
//! **Event sounds play to their end** (ADR 0095): when looped playback jumps back, or the
//! playhead stops on the last frame, the event sounds still sounding carry on as *tails* on a
//! clock of their own, as Animate plays them. Only [`Player::stop`] (the user stopping
//! playback) silences them.
use crate::mix::{MixOptions, Voice, mix};
use crate::mix::{MixOptions, Voice, VoiceKind, mix};
use std::sync::Arc;
/// Length of the fade at a start or a stop (about 5 ms at 48 kHz).
pub const RAMP_FRAMES: u64 = 256;
/// The most event sounds carried on at once after a jump (the oldest go first).
pub const MAX_TAILS: usize = 64;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Idle,
@@ -28,13 +37,41 @@ pub struct Player {
started: u64,
/// Frames left of the fade-out after a stop.
stopping: Option<u64>,
/// Event sounds carried on after a jump or the end, on their own clock (`tail_pos`).
tails: Vec<Voice>,
tail_pos: u64,
/// The monitor volume asked for, and the one the last frame was played at (it glides to
/// the new value over [`RAMP_FRAMES`], so moving the slider never clicks).
volume: f32,
gain_now: f32,
/// Frames in the last buffer filled, and how far behind the device plays what it is given
/// (output frames): the frame heard is behind [`Player::position`] by these.
last_fill: u64,
latency: u64,
scratch: Vec<f32>,
tail_scratch: Vec<f32>,
}
impl Player {
/// A silent player for output at `rate`.
pub fn new(rate: u32) -> Player {
Player { voices: Arc::new(Vec::new()), rate: rate.max(1), mode: Mode::Idle, opts: MixOptions::default(), pos: 0, started: 0, stopping: None, scratch: Vec::new() }
Player {
voices: Arc::new(Vec::new()),
rate: rate.max(1),
mode: Mode::Idle,
opts: MixOptions::default(),
pos: 0,
started: 0,
stopping: None,
tails: Vec::new(),
tail_pos: 0,
volume: 1.0,
gain_now: 1.0,
last_fill: 0,
latency: 0,
scratch: Vec::new(),
tail_scratch: Vec::new(),
}
}
pub fn rate(&self) -> u32 {
@@ -47,14 +84,44 @@ impl Player {
self.voices = voices;
}
/// The monitor volume, `0..=1` (`0` is mute; non-finite values are mute). Playback only:
/// exports never hear it.
pub fn set_volume(&mut self, volume: f32) {
self.volume = if volume.is_finite() { volume.clamp(0.0, 1.0) } else { 0.0 };
}
pub fn volume(&self) -> f32 {
self.volume
}
/// Plays from output frame `from`: stream sounds from there, event sounds as their
/// keyframes are reached.
/// keyframes are reached. Event sounds already playing are cut (a new start).
pub fn play(&mut self, from: u64) {
self.tails.clear();
self.start(Mode::Playing, from, false);
}
/// Plays `frames` frames of the stream sounds at `from` (scrubbing).
/// Jumps playback to `from` (looped playback going round), letting the event sounds that
/// are sounding play to their end.
pub fn wrap(&mut self, from: u64) {
self.carry_events();
self.start(Mode::Playing, from, false);
}
/// The playhead stopped by itself on the last frame: streams end, event sounds play out.
pub fn finish(&mut self) {
if self.mode == Mode::Playing && self.stopping.is_none() {
self.carry_events();
self.mode = Mode::Idle;
}
}
/// Plays `frames` frames of the stream sounds at `from` (scrubbing). Event sounds playing
/// out after the end carry on.
pub fn scrub(&mut self, from: u64, frames: u64) {
if self.stopping.is_some() {
self.tails.clear();
}
self.start(Mode::Snippet { until: from.saturating_add(frames) }, from, true);
}
@@ -66,9 +133,27 @@ impl Player {
self.opts = MixOptions { origin: from, streams_only };
}
/// Fades out and goes quiet.
/// Moves the event voices sounding at the playhead onto the tail clock.
fn carry_events(&mut self) {
if self.mode != Mode::Playing || self.opts.streams_only {
return;
}
let (pos, origin, now) = (self.pos, self.opts.origin, self.tail_pos);
let carried = self.voices.iter().filter(|v| v.kind == VoiceKind::Event && v.gain != 0.0 && v.at >= origin && v.at < pos && v.end > pos).map(|v| {
let mut t = v.clone();
t.at = now;
t.end = now.saturating_add(v.end - pos);
t.skip = v.skip.saturating_add(pos - v.at);
t
});
self.tails.extend(carried);
let over = self.tails.len().saturating_sub(MAX_TAILS);
self.tails.drain(..over);
}
/// Fades out and goes quiet, event sounds playing out included.
pub fn stop(&mut self) {
if self.mode != Mode::Idle && self.stopping.is_none() {
if self.is_sounding() && self.stopping.is_none() {
self.stopping = Some(RAMP_FRAMES);
}
}
@@ -78,42 +163,89 @@ impl Player {
self.mode == Mode::Playing && self.stopping.is_none()
}
/// Anything to hear: playing, scrubbing, or event sounds playing out.
pub fn is_sounding(&self) -> bool {
self.mode != Mode::Idle || !self.tails.is_empty()
}
/// The next output frame to be played.
pub fn position(&self) -> u64 {
self.pos
}
/// How far behind the device plays what it is handed, in output frames (from the device's
/// timestamps; `0` when it doesn't say).
pub fn set_latency(&mut self, frames: u64) {
self.latency = frames.min(u64::from(self.rate));
}
/// The output frame being heard now, `since_fill` output frames of wall time after the
/// last buffer was filled: the start of that buffer, less the device's latency, plus the
/// time since (never past the buffer). This is the clock the playhead follows.
pub fn heard(&self, since_fill: u64) -> u64 {
let begun = self.pos.saturating_sub(self.last_fill).max(self.started);
begun.saturating_add(since_fill.min(self.last_fill)).saturating_sub(self.latency).max(self.started)
}
/// Fills a device buffer of interleaved `channels`-channel frames: left and right on the
/// first two channels (their average on a mono device), silence on any others, clipped to
/// `-1..=1`.
pub fn fill(&mut self, out: &mut [f32], channels: usize) {
let channels = channels.max(1);
let frames = out.len() / channels;
if self.mode == Mode::Idle || frames == 0 {
self.last_fill = frames as u64;
if !self.is_sounding() || frames == 0 {
out.fill(0.0);
self.gain_now = self.volume;
return;
}
self.scratch.clear();
self.scratch.resize(frames * 2, 0.0);
mix(&self.voices, self.rate, self.opts, self.pos, &mut self.scratch);
if self.mode != Mode::Idle {
mix(&self.voices, self.rate, self.opts, self.pos, &mut self.scratch);
}
let tails = !self.tails.is_empty();
if tails {
self.tail_scratch.resize(frames * 2, 0.0);
mix(&self.tails, self.rate, MixOptions::default(), self.tail_pos, &mut self.tail_scratch);
}
let ramp = RAMP_FRAMES as f32;
let glide = (self.volume - self.gain_now) / ramp;
let mut done = false;
for (k, (dst, src)) in out.chunks_exact_mut(channels).zip(self.scratch.as_chunks::<2>().0).enumerate() {
let p = self.pos + k as u64;
let mut env = ((p - self.started) as f32 / ramp).min(1.0);
if let Mode::Snippet { until } = self.mode {
env = env.min(until.saturating_sub(p) as f32 / ramp);
}
let p = self.pos.saturating_add(k as u64);
// The playhead's own sound: faded in at its start, out at a snippet's end.
let mut env = match self.mode {
Mode::Idle => 0.0,
Mode::Playing => ((p - self.started) as f32 / ramp).min(1.0),
Mode::Snippet { until } => ((p - self.started) as f32 / ramp).min(until.saturating_sub(p) as f32 / ramp).min(1.0),
};
let mut all = 1.0;
if let Some(left) = &mut self.stopping {
env = env.min(*left as f32 / ramp);
all = *left as f32 / ramp;
*left = left.saturating_sub(1);
}
if done || env <= 0.0 {
done |= self.stopping == Some(0) || matches!(self.mode, Mode::Snippet { until } if p >= until);
env = env.max(0.0);
if (self.volume - self.gain_now).abs() > glide.abs() {
self.gain_now += glide;
} else {
self.gain_now = self.volume;
}
let [mut l, mut r] = *src;
l *= env;
r *= env;
if tails && let Some([tl, tr]) = self.tail_scratch.as_chunks::<2>().0.get(k) {
l += tl;
r += tr;
}
if done || all <= 0.0 {
done = true;
dst.fill(0.0);
continue;
}
let [l, r] = *src;
let (l, r) = ((l * env).clamp(-1.0, 1.0), (r * env).clamp(-1.0, 1.0));
let g = all * self.gain_now;
let (l, r) = ((l * g).clamp(-1.0, 1.0), (r * g).clamp(-1.0, 1.0));
let (l, r) = (if l.is_finite() { l } else { 0.0 }, if r.is_finite() { r } else { 0.0 });
match dst {
[m] => *m = 0.5 * (l + r),
[a, b, rest @ ..] => {
@@ -124,10 +256,18 @@ impl Player {
[] => {}
}
}
self.pos = self.pos.saturating_add(frames as u64);
if done || self.stopping == Some(0) || matches!(self.mode, Mode::Snippet { until } if self.pos >= until) {
let n = frames as u64;
self.pos = self.pos.saturating_add(n);
self.tail_pos = self.tail_pos.saturating_add(n);
let now = self.tail_pos;
self.tails.retain(|t| t.end > now);
if matches!(self.mode, Mode::Snippet { until } if self.pos >= until) {
self.mode = Mode::Idle;
}
if done || self.stopping == Some(0) {
self.mode = Mode::Idle;
self.stopping = None;
self.tails.clear();
}
}
}
@@ -136,7 +276,7 @@ impl Player {
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
use super::*;
use crate::{Pcm, VoiceKind};
use crate::{EnvPoint, Envelope, Pcm, VoiceKind};
fn tone() -> Arc<Vec<Voice>> {
let pcm = Arc::new(Pcm::new(8000, 1, vec![0.5; 8000]).unwrap());
@@ -177,6 +317,7 @@ mod tests {
assert!(buf[0] > 0.49 && buf[2 * 200] < 0.2 && buf[2 * 300] == 0.0, "fades out over the ramp");
p.fill(&mut buf, 2);
assert!(buf.iter().all(|&s| s == 0.0), "then silent");
assert!(!p.is_sounding());
}
#[test]
@@ -192,4 +333,149 @@ mod tests {
p.fill(&mut buf, 2);
assert!(buf.iter().all(|&s| s == 0.0));
}
/// An event sound of 0.25 at frame 100, 2000 frames long, and a stream of 0.5 over 0..1000.
fn event_and_stream() -> Arc<Vec<Voice>> {
let quiet = Arc::new(Pcm::new(8000, 1, vec![0.25; 2000]).unwrap());
let loud = Arc::new(Pcm::new(8000, 1, vec![0.5; 1000]).unwrap());
Arc::new(vec![Voice::new(quiet, VoiceKind::Event, 100, 2100), Voice::new(loud, VoiceKind::Stream, 0, 1000)])
}
#[test]
fn event_sounds_play_to_their_end_across_a_loop_and_after_the_last_frame() {
let mut p = Player::new(8000);
p.set_voices(event_and_stream());
p.play(0);
let mut buf = vec![0.0; 2 * 1000];
p.fill(&mut buf, 2);
assert_eq!(buf[2 * 500], 0.75, "event and stream together");
// Looped playback goes round: the event (900 frames in) carries on beside the stream.
p.wrap(0);
p.fill(&mut buf, 2);
assert_eq!(buf[2 * 50], 0.25 + 0.5 * 50.0 / 256.0, "the old event, the new stream ramping in");
assert_eq!(buf[2 * 300], 0.25 + 0.5 + 0.25, "old event, stream and the event started again");
// The playhead stops on the last frame: only events play on, to their ends.
p.finish();
assert!(!p.is_playing() && p.is_sounding());
p.fill(&mut buf, 2);
assert_eq!(buf[2 * 10], 0.5, "both events, no stream");
assert_eq!(buf[2 * 200], 0.25, "the first event ended 1100 frames after the loop");
for _ in 0..3 {
p.fill(&mut buf, 2);
}
assert!(!p.is_sounding(), "everything played out");
assert!(buf.iter().all(|&s| s == 0.0));
}
#[test]
fn stop_silences_event_sounds_playing_out_and_a_new_play_cuts_them() {
let mut p = Player::new(8000);
p.set_voices(event_and_stream());
p.play(0);
let mut buf = vec![0.0; 2 * 1000];
p.fill(&mut buf, 2);
p.finish();
p.stop();
p.fill(&mut buf, 2);
assert!(buf[2 * 300..].iter().all(|&s| s == 0.0) && !p.is_sounding(), "Stop silences tails");
p.play(0);
p.fill(&mut buf, 2);
p.wrap(0);
p.play(0);
p.fill(&mut buf, 2);
assert_eq!(buf[2 * 50], 0.5 * 50.0 / 256.0, "a new start has no tails: only the stream, ramping in");
}
#[test]
fn the_monitor_volume_glides_and_scales_everything() {
let mut p = Player::new(8000);
p.set_voices(tone());
p.play(0);
let mut buf = vec![0.0; 2 * 1000];
p.fill(&mut buf, 2);
p.set_volume(0.5);
p.fill(&mut buf, 2);
assert!(buf[0] > 0.49, "glides, no jump");
assert!(buf[2 * 100] < 0.49 && buf[2 * 100] > 0.25);
assert_eq!(buf[2 * 400], 0.25);
p.set_volume(0.0);
p.fill(&mut buf, 2);
assert_eq!(buf[2 * 400], 0.0, "mute");
assert!(p.is_playing(), "muted still keeps the clock");
p.set_volume(f32::NAN);
assert_eq!(p.volume(), 0.0);
p.set_volume(7.0);
assert_eq!(p.volume(), 1.0);
}
#[test]
fn the_heard_frame_trails_the_mix_by_the_buffer_and_the_latency() {
let mut p = Player::new(8000);
p.set_voices(tone());
p.play(1000);
assert_eq!(p.heard(0), 1000, "nothing played yet: the start");
let mut buf = vec![0.0; 2 * 400];
p.fill(&mut buf, 2);
p.fill(&mut buf, 2);
assert_eq!(p.position(), 1800);
assert_eq!(p.heard(0), 1400, "the last buffer's start");
assert_eq!(p.heard(100), 1500);
assert_eq!(p.heard(10_000), 1800, "never past what was handed over");
p.set_latency(160);
assert_eq!(p.heard(0), 1240);
p.set_latency(u64::MAX);
assert_eq!(p.heard(0), 1000, "never before the start");
}
/// Hostile voices: envelopes at the ends of time, non-finite gains, huge skips, inverted
/// spans, every buffer and channel shape. Nothing panics and every sample is finite in
/// `-1..=1`.
#[test]
fn hostile_envelopes_and_voices_never_panic_or_leave_the_range() {
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let odd = [0, 1, 2, 255, 256, 1 << 20, u64::MAX / 3, u64::MAX - 1, u64::MAX];
let gains = [0.0, 1.0, -1.0, 0.5, 1e30, -1e30, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MIN_POSITIVE];
for round in 0..300 {
let rate = [8000, 1, 44_100, 48_000, 192_000][round % 5];
let pcm = Arc::new(Pcm::new([8000, 22_050, 48_000][round % 3], 1 + (round % 2) as u16, (0..64).map(|i| ((i as f32) * 0.37).sin() * 4.0).collect()).unwrap());
let mut voices = Vec::new();
for _ in 0..1 + next() % 4 {
let pick = |n: u64| odd[(n % odd.len() as u64) as usize];
let mut v = Voice::new(pcm.clone(), if next() % 2 == 0 { VoiceKind::Event } else { VoiceKind::Stream }, pick(next()) % 5000, pick(next()));
v.skip = pick(next());
v.gain = gains[(next() % gains.len() as u64) as usize];
let points = (0..next() % 20).map(|_| EnvPoint { at: pick(next()), left: gains[(next() % gains.len() as u64) as usize], right: gains[(next() % gains.len() as u64) as usize] }).collect();
v.envelope = Envelope::new(points).map(Arc::new);
voices.push(v);
}
let mut p = Player::new(rate);
p.set_voices(Arc::new(voices));
p.set_volume(gains[round % gains.len()]);
p.set_latency(next());
match round % 4 {
0 => p.play(next() % 10_000),
1 => p.scrub(odd[round % odd.len()], next() % 4000),
_ => p.play(odd[round % odd.len()]),
}
for i in 0..4 {
let ch = 1 + (next() % 6) as usize;
let mut buf = vec![0.0; ch * (next() % 700) as usize + (i % 3)];
p.fill(&mut buf, ch);
assert!(buf.iter().all(|s| s.is_finite() && (-1.0..=1.0).contains(s)), "round {round}");
if i == 1 {
p.wrap(next() % 3000);
}
if i == 2 {
p.finish();
}
let _ = p.heard(next());
}
}
}
}
-26
View File
@@ -1,26 +0,0 @@
//! Ogg Vorbis through `lewton` (pure Rust, MIT OR Apache-2.0).
use crate::{AudioError, Collector, Pcm};
use lewton::inside_ogg::OggStreamReader;
use lewton::samples::InterleavedSamples;
pub fn decode(data: &[u8]) -> Result<Pcm, AudioError> {
let mut r = OggStreamReader::new(std::io::Cursor::new(data)).map_err(|_| AudioError::Unreadable)?;
let rate = r.ident_hdr.audio_sample_rate;
let mut col = Collector::new(usize::from(r.ident_hdr.audio_channels));
loop {
match r.read_dec_packet_generic::<InterleavedSamples<f32>>() {
Ok(Some(p)) => {
if p.channel_count != col.channels {
break; // a chained stream with another layout: keep the first part
}
col.push(&p.samples)?;
}
Ok(None) => break,
// A damaged tail: keep what decoded before it.
Err(_) if !col.samples.is_empty() => break,
Err(_) => return Err(AudioError::Unreadable),
}
}
Pcm::new(rate, col.out_channels(), col.samples)
}
+22 -118
View File
@@ -1,12 +1,4 @@
//! WAV (RIFF WAVE) reading and writing, from the public RIFF and WAVE format descriptions
//! (Microsoft/IBM *Multimedia Programming Interface and Data Specifications 1.0*, 1991, and
//! the `WAVE_FORMAT_EXTENSIBLE` note).
//!
//! Reads integer PCM (8, 16, 24 and 32 bit) and IEEE float (32 and 64 bit), plain or
//! extensible, any channel count (the first two are kept). Writes 16-bit, 24-bit or 32-bit
//! float. Every read is bounds-checked: a damaged file is an error, never a crash.
use crate::{AudioError, MAX_SAMPLES, Pcm};
//! WAV (RIFF WAVE) writing via `craft-audio`.
/// Sample formats written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -28,101 +20,6 @@ impl Bits {
const PCM: u16 = 1;
const FLOAT: u16 = 3;
const EXTENSIBLE: u16 = 0xFFFE;
fn u16_at(d: &[u8], at: usize) -> Option<u16> {
Some(u16::from_le_bytes(d.get(at..at + 2)?.try_into().ok()?))
}
fn u32_at(d: &[u8], at: usize) -> Option<u32> {
Some(u32::from_le_bytes(d.get(at..at + 4)?.try_into().ok()?))
}
struct Fmt {
tag: u16,
channels: u16,
rate: u32,
block_align: u16,
bits: u16,
}
fn read_fmt(c: &[u8]) -> Option<Fmt> {
let mut f = Fmt { tag: u16_at(c, 0)?, channels: u16_at(c, 2)?, rate: u32_at(c, 4)?, block_align: u16_at(c, 12)?, bits: u16_at(c, 14)? };
if f.tag == EXTENSIBLE {
// cbSize, valid bits, channel mask, then the sub-format GUID whose first two bytes are
// the format code.
f.tag = u16_at(c, 24)?;
}
Some(f)
}
/// Decodes a WAV file.
pub fn decode(data: &[u8]) -> Result<Pcm, AudioError> {
if data.get(0..4) != Some(b"RIFF") || data.get(8..12) != Some(b"WAVE") {
return Err(AudioError::UnknownFormat);
}
let (mut fmt, mut body) = (None, None);
let mut at = 12usize;
// Chunks: id, size, data, a pad byte after odd sizes. Bounded by the data length.
while let (Some(id), Some(size)) = (data.get(at..at + 4), u32_at(data, at + 4)) {
let start = at + 8;
let end = start.saturating_add(size as usize).min(data.len());
let chunk = data.get(start..end).unwrap_or(&[]);
match id {
b"fmt " => fmt = read_fmt(chunk),
// Streamed files may give 0 or 0xFFFFFFFF as the size: the data runs to the end.
b"data" => body = Some(if size == 0 || size == u32::MAX { data.get(start..).unwrap_or(&[]) } else { chunk }),
_ => {}
}
if body.is_some() && fmt.is_some() {
break;
}
at = end + (size as usize & 1);
if end >= data.len() {
break;
}
}
let fmt = fmt.ok_or(AudioError::Unreadable)?;
let body = body.ok_or(AudioError::Empty)?;
if fmt.channels == 0 || fmt.channels > 32 {
return Err(AudioError::Unsupported(format!("{} channels", fmt.channels)));
}
let width = match (fmt.tag, fmt.bits) {
(PCM, 8) => 1usize,
(PCM, 16) => 2,
(PCM, 24) => 3,
(PCM, 32) | (FLOAT, 32) => 4,
(FLOAT, 64) => 8,
(PCM | FLOAT, b) => return Err(AudioError::Unsupported(format!("{b}-bit samples"))),
(t, _) => return Err(AudioError::Unsupported(format!("WAV codec 0x{t:04x} (only uncompressed PCM and float)"))),
};
let channels = usize::from(fmt.channels);
// Samples may sit in wider containers (block align); read each from its slot's start.
let block = usize::from(fmt.block_align).max(width * channels);
let slot = block / channels;
let frames = body.len() / block;
if frames.saturating_mul(channels.min(2)) > MAX_SAMPLES {
return Err(AudioError::TooLong);
}
let read = |s: &[u8]| -> f32 {
match (fmt.tag, width, s) {
(PCM, 1, [a, ..]) => (f32::from(*a) - 128.0) / 128.0,
(PCM, 2, [a, b, ..]) => f32::from(i16::from_le_bytes([*a, *b])) / 32_768.0,
(PCM, 3, [a, b, c, ..]) => (i32::from_le_bytes([0, *a, *b, *c]) >> 8) as f32 / 8_388_608.0,
(PCM, 4, [a, b, c, d, ..]) => (f64::from(i32::from_le_bytes([*a, *b, *c, *d])) / 2_147_483_648.0) as f32,
(FLOAT, 4, [a, b, c, d, ..]) => f32::from_le_bytes([*a, *b, *c, *d]),
(FLOAT, 8, [a, b, c, d, e, f, g, h, ..]) => f64::from_le_bytes([*a, *b, *c, *d, *e, *f, *g, *h]) as f32,
_ => 0.0,
}
};
// The first two channels are kept (front left and right in WAV channel order).
let keep = channels.min(2);
let mut out = Vec::with_capacity(frames * keep);
for f in body.chunks_exact(block) {
out.extend(f.chunks_exact(slot).take(keep).map(read));
}
Pcm::new(fmt.rate, keep as u16, out)
}
/// A WAV header for `frames` frames of `channels` channels.
pub fn header(rate: u32, channels: u16, bits: Bits, frames: u64) -> Option<Vec<u8>> {
@@ -166,29 +63,34 @@ pub fn append(out: &mut Vec<u8>, samples: &[f32], bits: Bits) {
/// A whole WAV file in memory (empty when it would not fit a WAV's 4 GB limit).
pub fn encode(rate: u32, channels: u16, samples: &[f32], bits: Bits) -> Vec<u8> {
let frames = samples.len() / usize::from(channels.max(1));
let Some(mut out) = header(rate, channels, bits, frames as u64) else { return Vec::new() };
append(&mut out, samples.get(..frames * usize::from(channels.max(1))).unwrap_or(&[]), bits);
out
let depth = match bits {
Bits::Int16 => craft_audio::BitDepth::Int16,
Bits::Int24 => craft_audio::BitDepth::Int24,
Bits::Float32 => craft_audio::BitDepth::Float32,
};
let buf = craft_audio::AudioBuffer::from_interleaved(rate, channels, samples);
let opts = craft_audio::EncodeOptions::new(craft_audio::EncodeFormat::Wav).with_bit_depth(depth);
craft_audio::encode(&buf, &opts).unwrap_or_default()
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
use super::*;
use crate::{AudioError, decode};
const EXTENSIBLE: u16 = 0xFFFE;
#[test]
fn sixteen_bit_round_trips_bit_exactly() {
let src: Vec<i16> = vec![0, 1, -1, 32_767, -32_768, 12_345, -54, 7];
let f: Vec<f32> = src.iter().map(|&v| f32::from(v) / 32_768.0).collect();
let wav = encode(22_050, 2, &f, Bits::Int16);
assert_eq!(wav.len(), 44 + 16);
let p = decode(&wav).unwrap();
assert_eq!((p.rate, p.channels, p.frames()), (22_050, 2, 4));
assert_eq!(p.samples, f);
let mut again = Vec::new();
append(&mut again, &p.samples, Bits::Int16);
assert_eq!(&again[..], &wav[44..], "bit-identical after a round trip");
let again = encode(22_050, 2, &p.samples, Bits::Int16);
assert_eq!(again, wav, "bit-identical after a round trip");
}
#[test]
@@ -231,7 +133,7 @@ mod tests {
w.extend_from_slice(&16u16.to_le_bytes());
w.extend_from_slice(&0x3fu32.to_le_bytes());
w.extend_from_slice(&PCM.to_le_bytes());
w.extend_from_slice(&[0; 14]);
w.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
w.extend_from_slice(b"data");
w.extend_from_slice(&12u32.to_le_bytes());
for v in [16_384i16, -16_384, 1, 2, 3, 4] {
@@ -243,11 +145,13 @@ mod tests {
#[test]
fn unsupported_and_damaged_files_say_so() {
let mut w = encode(8000, 1, &[0.0; 4], Bits::Int16);
w[20] = 2; // ADPCM
assert!(matches!(decode(&w), Err(AudioError::Unsupported(_))));
let ok = encode(8000, 1, &[0.0; 4], Bits::Int16);
assert_eq!(decode(&ok[..36]), Err(AudioError::Empty), "no data chunk");
let mut w = header(8000, 1, Bits::Int16, 4).unwrap();
append(&mut w, &[0.0; 4], Bits::Int16);
w[20] = 99; // unknown WAV codec tag
assert!(matches!(decode(&w), Err(AudioError::Unsupported(_) | AudioError::Unreadable)));
let mut ok = header(8000, 1, Bits::Int16, 4).unwrap();
append(&mut ok, &[0.0; 4], Bits::Int16);
assert!(decode(&ok[..36]).is_err(), "no data chunk");
assert_eq!(decode(&ok[..20]), Err(AudioError::Unreadable), "fmt cut short");
// A data chunk claiming more than there is reads what is there.
let mut long = ok.clone();
+5
View File
@@ -19,7 +19,12 @@ anicraft-doc.workspace = true
anicraft-engine.workspace = true
anicraft-render.workspace = true
anicraft-geom.workspace = true
anicraft-guide.workspace = true
serde_json.workspace = true
[dev-dependencies]
# Exporter plug-in fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception).
wat = "1.228"
[lints]
workspace = true
+209 -5
View File
@@ -18,10 +18,26 @@ USAGE:
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 apng|webp <file|--sample> --out <anim.png|anim.webp> [--from A] [--to B] [--scale S]
[--loop forever|N] [--background yes] [--overwrite yes]
full colour with real transparency (WebP: lossless)
anicraft-cli export <file|--sample> --format <id> --out <path> [--from A] [--to B] [--frame N]
[--options '<json>'] [--overwrite yes]
any export format: the built-in ones (gif, apng, webp,
lottie, html, video, svg, png, png-sequence, sprite-sheet)
and exporter plug-ins (by id, with --plugins); --options
are the plug-in's options, or a built-in's extra params
anicraft-cli formats lists every export format, plug-ins included (JSON)
anicraft-cli commands
anicraft-cli run <file|--sample> <script.json> [--save <out.anicraft>]
a JSON array of {cmd, params}, or a saved command
(one undo step; nothing changes if a step fails)
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 guide --out <folder> writes the user guide as HTML pages (open index.html)
anicraft-cli guide search <words> [--limit N] [--json yes]
searches the user guide: chapter, heading, page and a
passage for each result, best first (as its search page)
anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release)
anicraft-cli bench --check yes the default scenario against the budgets in
docs/performance.md; fails when one is missed
@@ -73,6 +89,12 @@ 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())),
// An Animate document imports as File › Open does (#226), untitled.
Some(p) if anicraft_engine::is_animate(std::path::Path::new(p)) => {
let mut s = Session::default();
s.execute("file.open", &serde_json::json!({"path": p})).map_err(|e| e.to_string())?;
Ok(s)
}
Some(p) => {
let doc = format::load(std::path::Path::new(p)).map_err(|e| format!("{p}: {e}"))?;
let mut s = Session::new(doc);
@@ -120,6 +142,30 @@ pub fn run(argv: &[String]) -> Result<String, String> {
let list: Vec<Value> = commands().iter().map(|c| c.to_json()).collect();
serde_json::to_string_pretty(&list).map_err(|e| e.to_string())
}
// The user guide as the static HTML book Help › User Guide opens (ADR 0069).
// Searching it, with the ranking the book's search page uses (ADR 0096).
"guide" if src == Some("search") => {
let words = a.positional.get(1..).unwrap_or_default().join(" ");
if anicraft_guide::search::terms(&words).is_empty() {
return Err("guide search needs words to look for, e.g. anicraft-cli guide search onion skin".into());
}
let limit = a.num::<usize>("limit")?.unwrap_or(10).clamp(1, 100);
let hits = anicraft_guide::search::search(anicraft_guide::PAGES, &anicraft_guide::search::sections(anicraft_guide::PAGES), &words, limit);
if a.flag("json").is_some_and(|v| v == "yes") {
let list: Vec<Value> = hits.iter().map(|h| json!({"chapter": h.chapter, "heading": h.heading, "url": h.url, "snippet": h.snippet, "score": h.score})).collect();
return serde_json::to_string_pretty(&list).map_err(|e| e.to_string());
}
if hits.is_empty() {
return Ok(format!("nothing in the user guide matches “{}”", words.trim()));
}
let lines: Vec<String> = hits.iter().enumerate().map(|(i, h)| format!("{}. {} · {}\n {}\n {}", i + 1, h.heading, h.chapter, h.url, h.snippet)).collect();
Ok(lines.join("\n\n"))
}
"guide" => {
let out = a.flag("out").ok_or("guide needs --out <folder>, or search <words>")?;
let n = anicraft_guide::write_site(std::path::Path::new(out)).map_err(|e| format!("{out}: {e}"))?;
Ok(format!("wrote {n} files of the user guide to {out}; open {out}/index.html"))
}
"info" => {
let s = session(&a, Some(src.ok_or("info needs a file or --sample")?))?;
serde_json::to_string_pretty(&s.info()).map_err(|e| e.to_string())
@@ -148,9 +194,11 @@ pub fn run(argv: &[String]) -> Result<String, String> {
}
exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string())
}
"gif" => {
let mut s = session(&a, Some(src.ok_or("gif needs a file or --sample")?))?;
let out = a.flag("out").ok_or("gif needs --out <anim.gif>")?;
"gif" | "apng" | "webp" => {
let mut s = session(&a, Some(src.ok_or(format!("{cmd} needs a file or --sample"))?))?;
let cmd = cmd.as_str();
let ext = if cmd == "apng" { "png" } else { cmd };
let out = a.flag("out").ok_or(format!("{cmd} needs --out <anim.{ext}>"))?;
let mut p = json!({"path": out});
if let Some(f) = one_based(&a, "from")? {
p["from"] = json!(f);
@@ -164,8 +212,23 @@ pub fn run(argv: &[String]) -> Result<String, String> {
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())
if cmd != "gif" {
match a.flag("loop") {
None | Some("forever") => {}
Some(n) => p["loop"] = json!(n.parse::<u32>().map_err(|_| format!("--loop is forever or how many times it plays, not '{n}'"))?),
}
if a.flag("background").is_some_and(|v| v == "yes" || v == "true") {
p["background"] = json!(true);
}
}
exec(&mut s, &format!("file.export_{cmd}"), &p).map(|v| v.to_string())
}
"formats" => {
let mut s = session(&a, None)?;
let v = exec(&mut s, "file.export_formats", &json!({}))?;
serde_json::to_string_pretty(&v["formats"]).map_err(|e| e.to_string())
}
"export" => export(&a, src),
"new" => {
let mut s = Session::default();
let out = a.flag("out").ok_or("new needs --out <file.anicraft>")?;
@@ -199,7 +262,16 @@ pub fn run(argv: &[String]) -> Result<String, String> {
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 parsed: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("{script}: expected a JSON array of {{cmd, params}} or a saved command: {e}"))?;
// A saved command (ADR 0097) runs as one transactional step, as in the app.
if parsed.is_object() {
let v = exec(&mut s, "macro.run", &json!({"path": script}))?;
if let Some(out) = a.flag("save") {
exec(&mut s, "file.save", &json!({"path": out}))?;
}
return serde_json::to_string_pretty(&v).map_err(|e| e.to_string());
}
let steps: Vec<Value> = serde_json::from_value(parsed).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))?;
@@ -230,6 +302,50 @@ pub fn run(argv: &[String]) -> Result<String, String> {
}
}
/// `export --format <id>`: a built-in format through its own command, or an exporter plug-in
/// through `file.export_plugin` (ADR 0088).
fn export(a: &Args, src: Option<&str>) -> Result<String, String> {
let mut s = session(a, Some(src.ok_or("export needs a file or --sample")?))?;
let id = a.flag("format").ok_or("export needs --format <id> (anicraft-cli formats lists them)")?;
let out = a.flag("out").ok_or("export needs --out <path>")?;
let list = exec(&mut s, "file.export_formats", &json!({}))?;
let formats = list["formats"].as_array().cloned().unwrap_or_default();
let Some(f) = formats.iter().find(|f| f["id"] == id) else {
let ids: Vec<&str> = formats.iter().filter_map(|f| f["id"].as_str()).collect();
return Err(format!("no export format '{id}' (formats: {}; exporter plug-ins load with --plugins <folder>)", ids.join(", ")));
};
let (cmd, target, plugin) = (f["command"].as_str().unwrap_or(""), f["target"].as_str().unwrap_or("path"), f["plugin"] == true);
let mut p = json!({ target: out });
let options: Option<Value> = a.flag("options").map(|t| serde_json::from_str(t).map_err(|e| format!("--options is not JSON: {e}"))).transpose()?;
if plugin {
p["format"] = json!(id);
if let Some(o) = options {
p["options"] = o;
}
} else if let Some(Value::Object(o)) = options {
for (k, v) in o {
p[k] = v;
}
} else if options.is_some() {
return Err("--options must be a JSON object".into());
}
if matches!(id, "png" | "svg") {
if let Some(f) = one_based(a, "frame")? {
p["frame"] = json!(f);
}
} else {
for k in ["from", "to"] {
if let Some(f) = one_based(a, k)? {
p[k] = json!(f);
}
}
}
if a.flag("overwrite").is_some_and(|v| v == "yes" || v == "true") {
p["confirm"] = json!(true);
}
exec(&mut s, cmd, &p).map(|v| v.to_string())
}
fn avg_ms(n: u32, mut f: impl FnMut(u32)) -> f64 {
let t = Instant::now();
for i in 0..n {
@@ -457,6 +573,17 @@ pub fn serve<R: BufRead, W: Write>(s: &mut Session, input: R, out: &mut W) -> st
mod tests {
use super::*;
/// #226: `info`, `render` and the other subcommands take an Animate document as File › Open
/// does (an import, untitled), not only `.anicraft` files.
#[test]
fn subcommands_open_animate_documents() {
let xfl = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../xfl/tests/corpus/shapes/shapes.xfl");
let s = open_session(Some(&xfl.display().to_string())).unwrap();
assert!(s.path.is_none() && !s.doc.timeline(0).layers.is_empty());
let info = run(&["info".to_string(), xfl.display().to_string()]).unwrap();
assert!(info.contains("\"layers\""), "{info}");
}
#[test]
fn serve_round_trip() {
let mut s = Session::default();
@@ -560,11 +687,88 @@ mod tests {
assert!(s.plugins.is_empty());
}
#[test]
fn export_any_format_built_in_or_plugin() {
let dir = std::env::temp_dir().join(format!("anicraft-cli-export-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("plugins")).unwrap();
let argv = |v: &[&str]| -> Vec<String> { v.iter().map(|s| s.to_string()).collect() };
// A built-in format by id.
let svg = dir.join("f.svg");
run(&argv(&["export", "--sample", "--format", "svg", "--frame", "3", "--out", svg.to_str().unwrap()])).unwrap();
assert!(std::fs::read_to_string(&svg).unwrap().contains("<svg"));
// An exporter plug-in that writes "frames:" and the count it was handed.
let m = r#"{"id":"org.test.count","name":"Count","kind":"exporter","format":{"name":"Count","extension":"txt"}}"#;
let req = r#"{"op":"movie"}"#;
let wat = format!(
r#"(module (import "anicraft" "call" (func $call (param i32 i32) (result i32))) (import "anicraft" "response" (func $response (param i32 i32) (result i32)))
(memory (export "memory") 4) (data (i32.const 1024) "{}") (data (i32.const 4096) "{}")
(func (export "ac_abi_version") (result i32) i32.const 1)
(func (export "ac_manifest") (result i64) (i64.or (i64.shl (i64.const {}) (i64.const 32)) (i64.const 1024)))
(func (export "ac_alloc") (param i32) (result i32) i32.const 60000)
(func (export "ac_export") (param i32 i32) (result i64) (local $n i32)
(local.set $n (call $response (i32.const 100000) (call $call (i32.const 4096) (i32.const {}))))
(i64.or (i64.shl (i64.extend_i32_u (local.get $n)) (i64.const 32)) (i64.const 100000))))"#,
m.replace('"', "\\22"),
req.replace('"', "\\22"),
m.len(),
req.len()
);
std::fs::write(dir.join("plugins").join("count.wasm"), wat::parse_str(&wat).unwrap()).unwrap();
let plugins = dir.join("plugins");
let listed = run(&argv(&["formats", "--plugins", plugins.to_str().unwrap()])).unwrap();
assert!(listed.contains("org.test.count") && listed.contains("\"gif\""));
let out = dir.join("movie.txt");
let v = run(&argv(&["export", "--sample", "--format", "org.test.count", "--from", "2", "--to", "5", "--out", out.to_str().unwrap(), "--plugins", plugins.to_str().unwrap()])).unwrap();
assert!(v.contains("\"frames\":4"), "{v}");
let movie: Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap();
assert_eq!((movie["result"]["from"].as_u64(), movie["result"]["frames"].as_u64()), (Some(1), Some(4)));
// Replacing it needs --overwrite yes; unknown formats name the known ones.
assert!(run(&argv(&["export", "--sample", "--format", "org.test.count", "--out", out.to_str().unwrap(), "--plugins", plugins.to_str().unwrap()])).is_err());
run(&argv(&["export", "--sample", "--format", "org.test.count", "--out", out.to_str().unwrap(), "--plugins", plugins.to_str().unwrap(), "--overwrite", "yes"])).unwrap();
let err = run(&argv(&["export", "--sample", "--format", "org.test.count", "--out", out.to_str().unwrap()])).unwrap_err();
assert!(err.contains("lottie") && err.contains("--plugins"), "{err}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn run_takes_a_saved_command_file() {
let dir = std::env::temp_dir().join(format!("anicraft-cli-macro-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Spin.json");
std::fs::write(&file, r#"{"format": "anicraft-command", "version": 1, "steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}]}"#).unwrap();
let out = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap();
let v: Value = serde_json::from_str(&out).unwrap();
assert_eq!((v["name"].as_str(), v["steps"].as_u64()), (Some("Spin"), Some(2)), "{out}");
// A failing step names itself and leaves nothing behind.
std::fs::write(&file, r#"{"steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}, {"cmd": "layer.set_height", "params": {"height": 7}}]}"#).unwrap();
let e = run(&["run".into(), "--sample".into(), file.display().to_string()]).unwrap_err();
assert!(e.contains("stopped at step 3 of 3"), "{e}");
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"));
assert!(run(&["guide".into()]).is_err());
}
#[test]
fn guide_search_prints_chapter_heading_page_and_passage() {
let s = |v: &[&str]| run(&v.iter().map(|x| x.to_string()).collect::<Vec<_>>());
let out = s(&["guide", "search", "onion", "skin"]).unwrap();
let first = out.lines().next().unwrap_or("");
assert_eq!(first, "1. Onion skin · The timeline", "{out}");
assert!(out.contains("timeline.html#onion-skin"), "{out}");
let json: Value = serde_json::from_str(&s(&["guide", "search", "export", "gif", "--json", "yes", "--limit", "3"]).unwrap()).unwrap();
let list = json.as_array().unwrap();
assert!(list.len() <= 3 && list[0]["url"] == "getting-started.html#export-a-gif-or-a-video", "{json}");
assert!(s(&["guide", "search", "zzzzqqq"]).unwrap().starts_with("nothing in the user guide matches"));
assert!(s(&["guide", "search"]).is_err() && s(&["guide", "search", "?!"]).is_err());
assert!(s(&["guide", "search", "pen", "--limit", "x"]).is_err());
}
}
+3 -4
View File
@@ -8,12 +8,11 @@ publish.workspace = true
repository.workspace = true
[dependencies]
craft-mime.workspace = true
anicraft-geom.workspace = true
serde = { workspace = true, features = ["rc"] }
# Bitmaps are kept as PNG and decoded on first use.
png.workspace = true
# Imported JPEGs are decoded and kept as PNG.
zune-jpeg.workspace = true
# Bitmaps are decoded and encoded via craft-image-codecs.
craft-image-codecs.workspace = true
anicraft-audio.workspace = true
# The timeline action IR keyframes and button instances carry (ADR 0024).
anicraft-actions.workspace = true
+135
View File
@@ -0,0 +1,135 @@
//! Drawing aids saved with the document (ADR 0076): each scene's guides, and how the grid and
//! the guides look. Whether they show and snap is the editor's (`anicraft_engine::ViewAids`):
//! a working preference, like Snap to Objects, not part of the artwork. None of this is ever
//! rendered into a picture or an export; the editor's stage draws it.
use crate::Rgba;
use serde::{Deserialize, Serialize};
/// Which way a guide runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GuideAxis {
/// A horizontal line at `y = at` (dragged from the top ruler).
Horizontal,
/// A vertical line at `x = at` (dragged from the left ruler).
Vertical,
}
impl GuideAxis {
pub fn key(self) -> &'static str {
match self {
GuideAxis::Horizontal => "horizontal",
GuideAxis::Vertical => "vertical",
}
}
/// `horizontal`/`h` or `vertical`/`v`.
pub fn parse(s: &str) -> Option<GuideAxis> {
match s.trim().to_ascii_lowercase().as_str() {
"horizontal" | "h" => Some(GuideAxis::Horizontal),
"vertical" | "v" => Some(GuideAxis::Vertical),
_ => None,
}
}
}
/// A guide: a line across the whole stage and pasteboard, in stage pixels from the stage's
/// top-left corner.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Guide {
pub axis: GuideAxis,
pub at: f32,
}
/// Most guides one scene keeps.
pub const MAX_GUIDES: usize = 1_000;
/// Farthest a guide may be from the stage's corner, in stage pixels (well past any pasteboard).
pub const GUIDE_REACH: f32 = 100_000.0;
/// The grid's spacing range, in stage pixels.
pub const GRID_MIN: f32 = 1.0;
pub const GRID_MAX: f32 = 4_096.0;
impl Guide {
/// A guide with its position kept in range; `None` for a position that isn't a number.
pub fn new(axis: GuideAxis, at: f32) -> Option<Guide> {
at.is_finite().then(|| Guide { axis, at: at.clamp(-GUIDE_REACH, GUIDE_REACH) })
}
}
/// How the grid looks (View › Grid › Edit Grid).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Grid {
/// Between vertical lines, in stage pixels.
pub spacing_x: f32,
/// Between horizontal lines, in stage pixels.
pub spacing_y: f32,
pub color: Rgba,
/// Drawn over the artwork; off (the default, as in Animate) it shows under it, on the stage.
pub over_objects: bool,
}
impl Default for Grid {
fn default() -> Self {
Grid { spacing_x: 20.0, spacing_y: 20.0, color: Rgba::hex(0x949494), over_objects: false }
}
}
impl Grid {
/// Spacing clamped to [`GRID_MIN`]..=[`GRID_MAX`] (non-numbers back to the default).
pub fn sanitized(self) -> Grid {
let sp = |v: f32| if v.is_finite() { v.clamp(GRID_MIN, GRID_MAX) } else { 20.0 };
Grid { spacing_x: sp(self.spacing_x), spacing_y: sp(self.spacing_y), color: self.color.sanitized(), over_objects: self.over_objects }
}
}
/// The grid and the guides' looks, saved with the document.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Aids {
pub grid: Grid,
pub guide_color: Rgba,
}
impl Default for Aids {
fn default() -> Self {
Aids { grid: Grid::default(), guide_color: Rgba::hex(0x3ec8f0) }
}
}
impl Aids {
pub fn is_default(&self) -> bool {
*self == Aids::default()
}
pub fn sanitized(self) -> Aids {
Aids { grid: self.grid.sanitized(), guide_color: self.guide_color.sanitized() }
}
}
/// Guides from a file kept to numbers in range, at most [`MAX_GUIDES`].
pub fn sanitize_guides(guides: &mut Vec<Guide>) {
guides.retain(|g| g.at.is_finite());
guides.truncate(MAX_GUIDES);
for g in guides.iter_mut() {
g.at = g.at.clamp(-GUIDE_REACH, GUIDE_REACH);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hostile_values_are_kept_in_range() {
let mut g = vec![Guide { axis: GuideAxis::Vertical, at: f32::NAN }, Guide { axis: GuideAxis::Horizontal, at: 1e30 }];
g.extend(std::iter::repeat_n(Guide { axis: GuideAxis::Vertical, at: 3.0 }, MAX_GUIDES + 5));
sanitize_guides(&mut g);
assert_eq!(g.len(), MAX_GUIDES);
assert_eq!(g[0], Guide { axis: GuideAxis::Horizontal, at: GUIDE_REACH });
let grid = Grid { spacing_x: 0.0, spacing_y: f32::INFINITY, ..Grid::default() }.sanitized();
assert_eq!((grid.spacing_x, grid.spacing_y), (GRID_MIN, 20.0));
assert_eq!(Guide::new(GuideAxis::Vertical, f32::NAN), None);
assert_eq!(GuideAxis::parse(" V "), Some(GuideAxis::Vertical));
assert_eq!(GuideAxis::parse("diagonal"), None);
}
}
+289 -36
View File
@@ -18,7 +18,14 @@
//! bone up its chain, each joint turns so the effector points at the target, clamped to the
//! joint's limits. It works on joint angles directly, so limits are a clamp per step and the
//! result is a pose by construction.
//!
//! A joint may also **slide** (ADR 0084, Animate's joint translation): along its parent's x and
//! y axes, within limits, measured in layer pixels. A pose then holds the slide next to the
//! angle, forward kinematics moves the joint (and what hangs from it) by it, and the solver
//! slides joints only where turning them can't reach. **Springs** (per-bone strength and
//! damping) add secondary motion on top of the keyed pose; see [`crate::spring`].
use crate::skin::{self, Skin};
use crate::{Element, ElementId, Keyframe, Layer};
use anicraft_geom::{Affine, Vec2};
use serde::{Deserialize, Serialize};
@@ -40,6 +47,8 @@ pub const IK_SWEEPS: usize = 2048;
/// How often a stalled solve bends its joints to get going again, and by how much (radians).
const IK_KICKS: usize = 4;
const IK_KICK: f32 = 0.3;
/// Farthest a joint may slide either way along an axis (layer units, pixels).
pub const MAX_SLIDE: f32 = 10_000.0;
/// Unique id of a bone within a document (from the document's id counter).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
@@ -61,14 +70,43 @@ impl Limits {
/// Finite, ordered and within [`MAX_LIMIT`]; `None` when nothing sane is left.
pub fn sanitized(self) -> Option<Limits> {
self.sanitized_within(MAX_LIMIT)
}
/// Finite, ordered and within `±bound`; `None` when nothing sane is left.
pub fn sanitized_within(self, bound: f32) -> Option<Limits> {
if !(self.min.is_finite() && self.max.is_finite()) {
return None;
}
let (a, b) = (self.min.clamp(-MAX_LIMIT, MAX_LIMIT), self.max.clamp(-MAX_LIMIT, MAX_LIMIT));
let (a, b) = (self.min.clamp(-bound, bound), self.max.clamp(-bound, bound));
Some(Limits { min: a.min(b), max: a.max(b) })
}
}
/// A bone's spring (ADR 0084): secondary motion that makes it lag behind and swing past the
/// pose it is keyed to when the bones it hangs from (or its own pose) move, then settle.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Spring {
/// How stiff the spring is, 0…1 (shown as 0–100): 0 is no spring at all; a stiffer spring
/// swings faster and lags less (from half a swing to ten swings a second).
pub strength: f32,
/// How quickly the swing dies down, 0…1 (shown as 0–100): 0 swings on, 1 absorbs all of it
/// (the same as no spring).
pub damping: f32,
}
impl Spring {
/// Whether it moves anything: some strength, and damping that lets it swing.
pub fn is_live(&self) -> bool {
self.strength > 0.0 && self.damping < 1.0
}
/// Both values finite and within 0…1; `None` when they aren't numbers.
pub fn sanitized(self) -> Option<Spring> {
(self.strength.is_finite() && self.damping.is_finite()).then(|| Spring { strength: self.strength.clamp(0.0, 1.0), damping: self.damping.clamp(0.0, 1.0) })
}
}
/// A bone: from a joint on its parent instance to its child instance, which it turns.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Bone {
@@ -92,9 +130,45 @@ pub struct Bone {
/// where it is while the rest of the armature follows a drag.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub pinned: bool,
/// How far the joint may slide along its parent's x axis (pixels, ADR 0084); `None`: it
/// doesn't slide that way.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slide_x: Option<Limits>,
/// How far the joint may slide along its parent's y axis (pixels); `None`: it doesn't.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slide_y: Option<Limits>,
/// The bone's spring (ADR 0084); `None`: none.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub spring: Option<Spring>,
}
impl Bone {
/// A bone as drawn: turning freely, not sliding, no spring, not pinned.
pub fn new(id: BoneId, parent: ElementId, child: ElementId, head: Vec2, tail: Vec2, rest: Affine) -> Bone {
Bone { id, name: String::new(), parent, child, head, tail, rest, limits: None, pinned: false, slide_x: None, slide_y: None, spring: None }
}
/// Whether the joint may slide at all.
pub fn slides(&self) -> bool {
self.slide_x.is_some() || self.slide_y.is_some()
}
/// Slide `v` as this joint allows it: each axis within its limits, 0 along an axis it
/// doesn't slide on.
pub fn allow_slide(&self, v: Vec2) -> Vec2 {
let axis = |l: Option<Limits>, x: f32| match l {
Some(l) if x.is_finite() => l.clamp(x.clamp(-MAX_SLIDE, MAX_SLIDE)),
Some(l) => l.clamp(0.0),
None => 0.0,
};
Vec2::new(axis(self.slide_x, v.x), axis(self.slide_y, v.y))
}
/// Its spring, when it has one that moves anything.
pub fn live_spring(&self) -> Option<Spring> {
self.spring.filter(Spring::is_live)
}
/// `a` as this joint allows it (finite, within its limits).
pub fn allow(&self, a: f32) -> f32 {
let a = if a.is_finite() { a.clamp(-MAX_ANGLE, MAX_ANGLE) } else { 0.0 };
@@ -111,6 +185,15 @@ impl Bone {
pub struct Armature {
#[serde(default)]
pub bones: Vec<Bone>,
/// A shape armature (ADR 0071): the bones are inside this shape and bend its outline. Its
/// bones join joint nodes (ids that are no element) instead of instances; see
/// [`crate::skin`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skin: Option<Skin>,
/// The armature's springs are turned off (Properties › Bone › Springs, ADR 0084): it plays
/// its keyed poses exactly, for posing without the swing.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub springs_off: bool,
}
impl Armature {
@@ -118,6 +201,12 @@ impl Armature {
self.bones.is_empty()
}
/// The shape a shape armature's bones are inside (ADR 0071); `None` for an armature of
/// symbol instances.
pub fn skin_shape(&self) -> Option<ElementId> {
self.skin.as_ref().map(|s| s.shape)
}
pub fn bone(&self, id: BoneId) -> Option<&Bone> {
self.bones.iter().find(|b| b.id == id)
}
@@ -127,6 +216,11 @@ impl Armature {
}
/// The bone that moves instance `el` (ends in it), if any.
/// Whether any spring moves the armature (springs on, a bone with a live spring).
pub fn has_springs(&self) -> bool {
!self.springs_off && self.bones.iter().any(|b| b.live_spring().is_some())
}
pub fn bone_into(&self, el: ElementId) -> Option<&Bone> {
self.bones.iter().find(|b| b.child == el)
}
@@ -152,8 +246,12 @@ impl Armature {
out
}
/// The instances no bone moves (one for an armature made with the Bone tool).
/// The instances no bone moves (one for an armature made with the Bone tool; a shape
/// armature's shape).
pub fn roots(&self) -> Vec<ElementId> {
if let Some(s) = self.skin_shape() {
return vec![s];
}
let mut out = Vec::new();
for b in &self.bones {
if self.bone_into(b.parent).is_none() && !out.contains(&b.parent) {
@@ -203,6 +301,9 @@ impl Armature {
continue;
}
b.limits = b.limits.and_then(Limits::sanitized);
b.slide_x = b.slide_x.and_then(|l| l.sanitized_within(MAX_SLIDE));
b.slide_y = b.slide_y.and_then(|l| l.sanitized_within(MAX_SLIDE));
b.spring = b.spring.and_then(Spring::sanitized);
if b.name.len() > MAX_NAME {
let cut = (0..=MAX_NAME).rev().find(|&i| b.name.is_char_boundary(i)).unwrap_or(0);
b.name.truncate(cut);
@@ -210,8 +311,12 @@ impl Armature {
kept.push(b);
}
// Order: a bone after the bone moving its parent. What never gets placed is a cycle.
// A shape armature's bones all hang from its shape.
let children: HashSet<ElementId> = kept.iter().map(|b| b.child).collect();
let mut placed: HashSet<ElementId> = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect();
let mut placed: HashSet<ElementId> = match self.skin_shape() {
Some(s) => HashSet::from([s]),
None => kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(),
};
let mut ordered = Vec::with_capacity(kept.len());
let mut rest = kept;
loop {
@@ -227,15 +332,35 @@ impl Armature {
}
ordered.truncate(MAX_BONES);
self.bones = ordered;
self.bones != before
let skin_changed = skin::sanitize(self);
self.bones != before || skin_changed
}
}
/// One joint's angle in a pose (radians, 0 as drawn).
/// One joint in a pose: its angle (radians, 0 as drawn) and how far it slides along its
/// parent's axes (pixels, ADR 0084; 0 for a joint that doesn't slide).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct JointAngle {
pub bone: BoneId,
pub angle: f32,
#[serde(default, skip_serializing_if = "is_zero")]
pub x: f32,
#[serde(default, skip_serializing_if = "is_zero")]
pub y: f32,
}
fn is_zero(v: &f32) -> bool {
*v == 0.0
}
impl JointAngle {
pub fn new(bone: BoneId, angle: f32) -> JointAngle {
JointAngle { bone, angle, x: 0.0, y: 0.0 }
}
pub fn slide(&self) -> Vec2 {
Vec2::new(self.x, self.y)
}
}
/// A pose: joint angles by bone. A bone it doesn't list is as drawn (angle 0).
@@ -256,7 +381,19 @@ impl Pose {
pub fn set(&mut self, b: BoneId, angle: f32) {
match self.0.iter_mut().find(|j| j.bone == b) {
Some(j) => j.angle = angle,
None => self.0.push(JointAngle { bone: b, angle }),
None => self.0.push(JointAngle::new(b, angle)),
}
}
/// How far bone `b`'s joint slides (0 when the pose doesn't list it).
pub fn slide(&self, b: BoneId) -> Vec2 {
self.0.iter().find(|j| j.bone == b).map_or(Vec2::ZERO, JointAngle::slide)
}
pub fn set_slide(&mut self, b: BoneId, v: Vec2) {
match self.0.iter_mut().find(|j| j.bone == b) {
Some(j) => (j.x, j.y) = (v.x, v.y),
None => self.0.push(JointAngle { bone: b, angle: 0.0, x: v.x, y: v.y }),
}
}
@@ -267,13 +404,29 @@ impl Pose {
/// Every bone of `arm` at the angle its joint allows: the pose as it shows.
pub fn allowed(&self, arm: &Armature) -> Pose {
Pose(arm.bones.iter().map(|b| JointAngle { bone: b.id, angle: b.allow(self.angle(b.id)) }).collect())
Pose(
arm.bones
.iter()
.map(|b| {
let s = b.allow_slide(self.slide(b.id));
JointAngle { bone: b.id, angle: b.allow(self.angle(b.id)), x: s.x, y: s.y }
})
.collect(),
)
}
/// The pose `t` of the way to `o`, joint by joint (angles blend linearly, so a joint that
/// turned a whole way round between keys turns that way in the tween).
/// The pose `t` of the way to `o`, joint by joint (angles and slides blend linearly, so a
/// joint that turned a whole way round between keys turns that way in the tween).
pub fn lerp(&self, o: &Pose, t: f32, arm: &Armature) -> Pose {
Pose(arm.bones.iter().map(|b| JointAngle { bone: b.id, angle: b.allow(anicraft_geom::lerp(self.angle(b.id), o.angle(b.id), t)) }).collect())
Pose(
arm.bones
.iter()
.map(|b| {
let s = b.allow_slide(self.slide(b.id).lerp(o.slide(b.id), t));
JointAngle { bone: b.id, angle: b.allow(anicraft_geom::lerp(self.angle(b.id), o.angle(b.id), t)), x: s.x, y: s.y }
})
.collect(),
)
}
/// Repairs a loaded pose: finite angles in range, one per bone, at most [`MAX_BONES`].
@@ -290,29 +443,37 @@ impl Pose {
j.angle = a;
changed = true;
}
for v in [&mut j.x, &mut j.y] {
let s = if v.is_finite() { v.clamp(-MAX_SLIDE, MAX_SLIDE) } else { 0.0 };
if s.to_bits() != v.to_bits() {
*v = s;
changed = true;
}
}
}
changed || self.0.len() != before
}
}
/// `R(angle)` about point `j`.
fn turn_about(j: Vec2, angle: f32) -> Affine {
pub(crate) fn turn_about(j: Vec2, angle: f32) -> Affine {
Affine::translate(j.x, j.y).mul(&Affine::rotate(angle)).mul(&Affine::translate(-j.x, -j.y))
}
/// Forward kinematics: the transform (in the layer's space) of every instance in `elements`
/// once `pose` turns the armature's joints. A root keeps its own transform; a child is placed
/// from its parent: `R_joint(angle) · parent · rest`. An instance whose parent isn't on the
/// keyframe keeps its own transform.
/// keyframe keeps its own transform. A shape armature's joint nodes (ADR 0071) are placed
/// the same way from the shape's transform.
pub fn place(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> HashMap<ElementId, Affine> {
let mut world: HashMap<ElementId, Affine> = elements.iter().map(|e| (e.id, e.transform)).collect();
let nodes = arm.skin.is_some();
for b in &arm.bones {
let Some(wp) = world.get(&b.parent).copied() else { continue };
if !world.contains_key(&b.child) {
if !nodes && !world.contains_key(&b.child) {
continue;
}
let j = wp.apply(b.head);
let wc = turn_about(j, b.allow(pose.angle(b.id))).mul(&wp.mul(&b.rest));
let (_, wc) = joint(b, &wp, b.allow(pose.angle(b.id)), b.allow_slide(pose.slide(b.id)));
if wc.is_finite() {
world.insert(b.child, wc);
}
@@ -320,12 +481,46 @@ pub fn place(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> HashMap<
world
}
/// Puts the instances of `elements` where `pose` has them (copy-on-write: only instances that
/// move are cloned). Returns whether any moved.
/// The layer-space step a joint slides by `s` (pixels along its parent `wp`'s x and y axes).
/// Exactly zero for no slide.
pub fn slide_step(wp: &Affine, s: Vec2) -> Vec2 {
if s == Vec2::ZERO {
return Vec2::ZERO;
}
let (ex, ey) = slide_axes(wp);
ex * s.x + ey * s.y
}
/// The unit directions a joint on parent `wp` slides along: its x and y axes in layer space.
pub fn slide_axes(wp: &Affine) -> (Vec2, Vec2) {
let ex = wp.apply_vector(Vec2::new(1.0, 0.0)).normalized();
let ey = wp.apply_vector(Vec2::new(0.0, 1.0)).normalized();
(if ex == Vec2::ZERO { Vec2::new(1.0, 0.0) } else { ex }, if ey == Vec2::ZERO { Vec2::new(0.0, 1.0) } else { ey })
}
/// One joint of forward kinematics: where bone `b`'s joint is and the transform of what it
/// moves, from its parent's transform `wp`, joint angle `a` and slide `s` (both as the joint
/// allows them). Without a slide this is exactly ADR 0043's `R_joint(a) · wp · rest`.
pub fn joint(b: &Bone, wp: &Affine, a: f32, s: Vec2) -> (Vec2, Affine) {
let d = slide_step(wp, s);
let base = wp.mul(&b.rest);
if d == Vec2::ZERO {
let j = wp.apply(b.head);
return (j, turn_about(j, a).mul(&base));
}
let j = wp.apply(b.head) + d;
(j, turn_about(j, a).mul(&Affine::translate(d.x, d.y).mul(&base)))
}
/// Puts the instances of `elements` where `pose` has them, and bends a shape armature's shape
/// (copy-on-write: only what changes is cloned). Returns whether anything changed.
pub fn apply(arm: &Armature, elements: &mut [Arc<Element>], pose: &Pose) -> bool {
if arm.is_empty() {
return false;
}
if arm.skin.is_some() {
return skin::apply(arm, elements, pose);
}
let world = place(arm, elements, pose);
let mut moved = false;
for e in elements.iter_mut() {
@@ -350,7 +545,7 @@ pub fn pose_at(layer: &Layer, frame: u32) -> Option<Pose> {
let idx = layer.keyframe_index_at(frame)?;
let kf: &Keyframe = layer.keyframes.get(idx)?;
let here = kf.pose.allowed(arm);
let (Some(tween), None) = (kf.tween, &kf.motion) else { return Some(here) };
let (Some(tween), None) = (&kf.tween, &kf.motion) else { return Some(here) };
let Some(next) = layer.keyframes.get(idx + 1) else { return Some(here) };
if next.start != kf.end() || frame == kf.start {
return Some(here);
@@ -367,21 +562,34 @@ pub struct BoneAt {
pub tail: Vec2,
/// The joint angle (radians, as the joint allows it).
pub angle: f32,
/// How far the joint slides (pixels along its parent's axes, as the joint allows it).
pub slide: Vec2,
}
/// Every bone's joint and end with the instances in `elements` placed as they show (posed:
/// what [`crate::evaluate_layer_elements`] gives on an armature layer).
pub fn bones_at(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> Vec<BoneAt> {
let world: HashMap<ElementId, Affine> = elements.iter().map(|e| (e.id, e.transform)).collect();
// A shape armature's joint nodes are no elements: forward kinematics places them.
let world: HashMap<ElementId, Affine> = if arm.skin.is_some() { place(arm, elements, pose) } else { elements.iter().map(|e| (e.id, e.transform)).collect() };
arm.bones
.iter()
.filter_map(|b| {
let (wp, wc) = (world.get(&b.parent)?, world.get(&b.child)?);
Some(BoneAt { id: b.id, head: wp.apply(b.head), tail: wc.apply(b.tail), angle: b.allow(pose.angle(b.id)) })
let slide = b.allow_slide(pose.slide(b.id));
Some(BoneAt { id: b.id, head: wp.apply(b.head) + slide_step(wp, slide), tail: wc.apply(b.tail), angle: b.allow(pose.angle(b.id)), slide })
})
.collect()
}
/// Layer point `p` in the space of the instance (or joint node) bone `id` moves, with the
/// armature posed by `pose`: the `local` for [`solve`] that makes the grabbed point follow a drag
/// from where it is, so grabbing a bone along its length never snaps its end to the pointer.
pub fn grab_point(arm: &Armature, elements: &[Arc<Element>], pose: &Pose, id: BoneId, p: Vec2) -> Option<Vec2> {
let child = arm.bone(id)?.child;
let q = place(arm, elements, pose).get(&child)?.inverse()?.apply(p);
(q.x.is_finite() && q.y.is_finite()).then_some(q)
}
/// What a solve came to.
#[derive(Clone, Debug, PartialEq)]
pub struct Solved {
@@ -408,20 +616,43 @@ pub fn movable_chain(arm: &Armature, id: BoneId) -> Vec<&Bone> {
/// sweep turns the joints from the dragged bone upward so the effector points at the target,
/// each clamped to its limits, until the effector is within [`IK_TOLERANCE`] or stops moving.
/// An unreachable target leaves the chain stretched straight toward it, the root where it was.
/// `None` when the armature has no bone `id` or its instances aren't on the keyframe.
///
/// Joints that slide (ADR 0084) slide only where turning can't reach: when the turning sweeps
/// leave the effector short of the target, a second round of sweeps also slides each joint, after
/// turning it, toward the target within its limits. A target the joints reach by turning is
/// solved exactly as without sliding. `None` when the armature has no bone `id` or its instances
/// aren't on the keyframe.
pub fn solve(arm: &Armature, elements: &[Arc<Element>], pose: &Pose, id: BoneId, local: Vec2, target: Vec2) -> Option<Solved> {
let bone = arm.bone(id)?;
if !(local.x.is_finite() && local.y.is_finite() && target.x.is_finite() && target.y.is_finite()) {
return None;
}
let chain: Vec<(BoneId, ElementId, Vec2)> = movable_chain(arm, id).iter().map(|b| (b.id, b.parent, b.head)).collect();
let mut pose = pose.allowed(arm);
let chain: Vec<&Bone> = movable_chain(arm, id);
let effector = |pose: &Pose| -> Option<(HashMap<ElementId, Affine>, Vec2)> {
let world = place(arm, elements, pose);
let e = world.get(&bone.child)?.apply(local);
Some((world, e))
};
let (_, start) = effector(&pose)?;
let start = pose.allowed(arm);
effector(&start)?;
let (mut pose, mut error) = ccd(arm, &chain, &effector, start, target, false);
if error > IK_TOLERANCE && chain.iter().any(|b| b.slides()) {
let (p, e) = ccd(arm, &chain, &effector, pose.clone(), target, true);
if e < error {
(pose, error) = (p, e);
}
}
Some(Solved { pose, error, chain: chain.len() })
}
/// The effector (with every instance's placement) for a pose; see [`solve`].
type Effector<'a> = dyn Fn(&Pose) -> Option<(HashMap<ElementId, Affine>, Vec2)> + 'a;
/// Cyclic coordinate descent from `pose` toward `target`, turning (and with `slide`, sliding)
/// the joints of `chain`. Returns the best pose seen and its error.
fn ccd(arm: &Armature, chain: &[&Bone], effector: &Effector<'_>, mut pose: Pose, target: Vec2, slide: bool) -> (Pose, f32) {
let chain: Vec<(BoneId, ElementId, Vec2)> = chain.iter().map(|b| (b.id, b.parent, b.head)).collect();
let Some((_, start)) = effector(&pose) else { return (pose, f32::INFINITY) };
let mut error = start.distance(target);
let mut best = (pose.clone(), error);
let mut kicks = 0;
@@ -439,19 +670,41 @@ pub fn solve(arm: &Armature, elements: &[Arc<Element>], pose: &Pose, id: BoneId,
for &(b, parent, head) in &chain {
let Some(wp) = world.get(&parent) else { continue };
let Some(joint) = arm.bone(b) else { continue };
let j = wp.apply(head);
let j = wp.apply(head) + slide_step(wp, pose.slide(b));
let (u, v) = (e - j, target - j);
if u.length() < 1e-6 || v.length() < 1e-6 {
continue;
if u.length() >= 1e-6 && v.length() >= 1e-6 {
let want = u.cross(v).atan2(u.dot(v));
let cur = pose.angle(b);
let next = joint.allow(cur + want);
let by = next - cur;
if by != 0.0 {
pose.set(b, next);
e = turn_about(j, by).apply(e);
turned = turned.max(by.abs());
}
}
let want = u.cross(v).atan2(u.dot(v));
let cur = pose.angle(b);
let next = joint.allow(cur + want);
let by = next - cur;
if by != 0.0 {
pose.set(b, next);
e = turn_about(j, by).apply(e);
turned = turned.max(by.abs());
// Then slide the joint (and all below it) toward the target, along the axes it
// slides on: the effector moves by the same step.
if slide && joint.slides() {
let (ex, ey) = slide_axes(wp);
let r = target - e;
let cur = pose.slide(b);
let want = match (joint.slide_x.is_some(), joint.slide_y.is_some()) {
(true, false) => Vec2::new(r.dot(ex), 0.0),
(false, true) => Vec2::new(0.0, r.dot(ey)),
_ => {
// r = ex·sx + ey·sy (the axes may be skewed).
let det = ex.cross(ey);
if det.abs() < 1e-6 { Vec2::new(r.dot(ex), r.dot(ey)) } else { Vec2::new(r.cross(ey) / det, ex.cross(r) / det) }
}
};
let next = joint.allow_slide(cur + want);
let by = next - cur;
if by != Vec2::ZERO {
pose.set_slide(b, next);
e = e + ex * by.x + ey * by.y;
turned = turned.max(by.length() * 1e-2);
}
}
}
let Some((_, e)) = effector(&pose) else { break };
@@ -482,7 +735,7 @@ pub fn solve(arm: &Armature, elements: &[Arc<Element>], pose: &Pose, id: BoneId,
if error < best.1 {
best = (pose, error);
}
Some(Solved { pose: best.0, error: best.1, chain: chain.len() })
best
}
#[cfg(test)]
+83 -5
View File
@@ -19,14 +19,14 @@ fn instance(id: ElementId, x: f32, y: f32) -> Arc<Element> {
fn bone(id: BoneId, parent: ElementId, child: ElementId) -> Bone {
// Every segment is 100 px long from its registration point; bones join end to start.
Bone { id, name: String::new(), parent, child, head: Vec2::new(100.0, 0.0), tail: Vec2::new(100.0, 0.0), rest: Affine::translate(100.0, 0.0), limits: None, pinned: false }
Bone::new(id, parent, child, Vec2::new(100.0, 0.0), Vec2::new(100.0, 0.0), Affine::translate(100.0, 0.0))
}
/// A three-segment chain lying along y = 100: the root from x = 100, the arm from 200 (its
/// joint), the hand from 300; the hand's end at 400. The arm and hand reach 200 px from the
/// shoulder joint at (200, 100).
fn chain() -> (Armature, Vec<Arc<Element>>) {
let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)] };
let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)], ..Default::default() };
(arm, vec![instance(ROOT, 100.0, 100.0), instance(ARM, 200.0, 100.0), instance(HAND, 300.0, 100.0)])
}
@@ -173,7 +173,7 @@ fn every_export_sees_the_pose() {
let mut k = Keyframe::new(0, 1);
k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) }));
seg.keyframes = vec![Arc::new(k)];
d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(seg)] } }));
d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(seg)] } }));
d.timeline_mut(0).layers = vec![Arc::new(armature_layer(Easing::Linear))];
d.sanitize();
let dl = evaluate(&d, 10);
@@ -208,7 +208,7 @@ fn sanitize_repairs_hostile_armatures() {
assert_eq!(arm.bone(BoneId(35)).unwrap().limits, None);
assert_eq!(arm.bone(BoneId(36)).unwrap().limits, Some(Limits { min: -1.0, max: 1.0 }));
assert!(!arm.sanitize(), "sanitizing twice changes nothing");
let mut p = Pose(vec![JointAngle { bone: B1, angle: f32::NAN }, JointAngle { bone: B1, angle: 1.0 }, JointAngle { bone: B2, angle: 1e30 }]);
let mut p = Pose(vec![JointAngle::new(B1, f32::NAN), JointAngle::new(B1, 1.0), JointAngle::new(B2, 1e30)]);
assert!(p.sanitize());
assert_eq!(p.0.len(), 2);
assert_eq!((p.angle(B1), p.angle(B2)), (0.0, MAX_ANGLE));
@@ -242,7 +242,7 @@ fn long_chains_and_collinear_targets_converge() {
bones.push(Bone { id: BoneId(5000 + i as u64), ..bone(BoneId(0), p, c) });
els.push(instance(c, 100.0 * (i + 1) as f32, 0.0));
}
let arm = Armature { bones };
let arm = Armature { bones, ..Default::default() };
let last = BoneId(5000 + n as u64 - 1);
let reach = 100.0 * n as f32;
for k in 0..12 {
@@ -254,3 +254,81 @@ fn long_chains_and_collinear_targets_converge() {
}
}
}
// Joint translation (ADR 0084).
#[test]
fn a_sliding_joint_moves_what_hangs_from_it_along_its_parents_axes() {
let (mut arm, els) = chain();
arm.bone_mut(B2).unwrap().slide_x = Some(Limits { min: -50.0, max: 50.0 });
let mut pose = Pose::default();
pose.set_slide(B2, Vec2::new(30.0, 99.0));
// Only x slides (y isn't enabled), along the arm's x axis: right, at rest.
assert_eq!(pose.allowed(&arm).slide(B2), Vec2::new(30.0, 0.0));
assert!(close(hand_end(&arm, &els, &pose), Vec2::new(430.0, 100.0), 1e-3));
// With the shoulder turned a quarter, the arm's x axis points down: so does the slide.
pose.set(B1, FRAC_PI_2);
assert!(close(hand_end(&arm, &els, &pose), Vec2::new(200.0, 330.0), 1e-3), "{:?}", hand_end(&arm, &els, &pose));
// The joint is drawn where it slid to.
let posed: Vec<Arc<Element>> = {
let w = place(&arm, &els, &pose);
els.iter().map(|e| Arc::new(Element { transform: w[&e.id], ..(**e).clone() })).collect()
};
let at = bones_at(&arm, &posed, &pose.allowed(&arm));
assert!(close(at[1].head, Vec2::new(200.0, 230.0), 1e-3), "{:?}", at[1]);
// The limits hold, whatever a file says.
pose.set_slide(B2, Vec2::new(1e9, 0.0));
assert_eq!(pose.allowed(&arm).slide(B2).x, 50.0);
// No slide: exactly the bits of turning alone.
let (plain, _) = chain();
let p = Pose(vec![JointAngle::new(B1, 0.3), JointAngle::new(B2, -0.2)]);
assert_eq!(place(&arm, &els, &p), place(&plain, &els, &p));
}
#[test]
fn ik_slides_a_joint_only_where_turning_cant_reach_and_within_its_limits() {
let (mut arm, els) = chain();
arm.bone_mut(B2).unwrap().slide_x = Some(Limits { min: 0.0, max: 80.0 });
// Within reach: the same solve as without sliding (no slide at all).
let (plain, _) = chain();
let t = Vec2::new(300.0, 180.0);
let (a, b) = (solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), t).unwrap(), solve(&plain, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), t).unwrap());
assert_eq!(a.pose.slide(B2), Vec2::ZERO);
assert_eq!(a.pose.angle(B1).to_bits(), b.pose.angle(B1).to_bits());
// Out of reach: the elbow slides out to get there.
let far = Vec2::new(250.0, 330.0);
let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), far).unwrap();
assert!(s.error <= 0.5, "{} px off, slide {:?}", s.error, s.pose.slide(B2));
assert!(s.pose.slide(B2).x > 0.0 && s.pose.slide(B2).x <= 80.0);
// Farther than the slide allows: it stops at its limit, stretched toward the target.
let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(900.0, 100.0)).unwrap();
assert_eq!(s.pose.slide(B2).x, 80.0);
assert!((s.error - (900.0 - 480.0)).abs() < 0.05, "{}", s.error);
// A piston: a joint that doesn't turn but slides along y.
let (mut arm, els) = chain();
let b = arm.bone_mut(B2).unwrap();
b.limits = Some(Limits { min: 0.0, max: 0.0 });
b.slide_y = Some(Limits { min: -40.0, max: 40.0 });
arm.bone_mut(B1).unwrap().limits = Some(Limits { min: 0.0, max: 0.0 });
let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(400.0, 125.0)).unwrap();
assert!((s.pose.slide(B2).y - 25.0).abs() < 0.01 && s.pose.angle(B2) == 0.0, "{:?}", s.pose);
}
#[test]
fn sanitize_repairs_hostile_slides() {
let (mut arm, _) = chain();
let b = arm.bone_mut(B2).unwrap();
b.slide_x = Some(Limits { min: f32::NAN, max: 3.0 });
b.slide_y = Some(Limits { min: 1e12, max: -1e12 });
b.spring = Some(Spring { strength: f32::INFINITY, damping: 0.5 });
assert!(arm.sanitize());
let b = arm.bone(B2).unwrap();
assert_eq!((b.slide_x, b.slide_y, b.spring), (None, Some(Limits { min: -MAX_SLIDE, max: MAX_SLIDE }), None));
let mut p = Pose(vec![JointAngle { bone: B2, angle: 0.0, x: f32::NAN, y: -1e20 }]);
assert!(p.sanitize());
assert_eq!(p.slide(B2), Vec2::new(0.0, -MAX_SLIDE));
// Older poses (no slides) still read; slides of 0 are not written.
let old: Pose = serde_json::from_str(r#"[{"bone":20,"angle":0.5}]"#).unwrap();
assert_eq!(old.slide(B1), Vec2::ZERO);
assert_eq!(serde_json::to_string(&old).unwrap(), r#"[{"bone":20,"angle":0.5}]"#);
}
+59 -55
View File
@@ -43,13 +43,25 @@ pub struct Bitmap {
/// The image as PNG.
#[serde(with = "base64_bytes")]
pub png: Arc<Vec<u8>>,
/// Allow Smoothing (ADR 0050): scaled or turned, the image is filtered between its pixels;
/// off, each pixel stays a hard-edged square (pixel art). On unless a file says otherwise.
#[serde(default = "yes", skip_serializing_if = "is_yes")]
pub smoothing: bool,
#[serde(skip)]
decoded: Arc<OnceLock<Option<Arc<Pixels>>>>,
}
fn yes() -> bool {
true
}
fn is_yes(b: &bool) -> bool {
*b
}
impl PartialEq for Bitmap {
fn eq(&self, o: &Bitmap) -> bool {
self.id == o.id && self.name == o.name && self.width == o.width && self.height == o.height && (Arc::ptr_eq(&self.png, &o.png) || self.png == o.png)
self.id == o.id && self.name == o.name && self.width == o.width && self.height == o.height && self.smoothing == o.smoothing && (Arc::ptr_eq(&self.png, &o.png) || self.png == o.png)
}
}
@@ -60,7 +72,7 @@ impl Bitmap {
let (width, height) = (px.width, px.height);
let decoded = OnceLock::new();
let _ = decoded.set(Some(Arc::new(px)));
Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), decoded: Arc::new(decoded) })
Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), smoothing: true, decoded: Arc::new(decoded) })
}
/// A bitmap from PNG or JPEG data (told apart by their signatures; JPEGs become PNG).
@@ -69,6 +81,18 @@ impl Bitmap {
Bitmap::from_png(id, name, png).ok_or(ImageError::Unreadable)
}
/// A bitmap from straight RGBA8 pixels, row by row (a decoded video frame, say). `None`
/// when the size is empty, over [`MAX_BITMAP_EDGE`] or doesn't match the pixels.
pub fn from_rgba(id: BitmapId, name: impl Into<String>, width: u32, height: u32, rgba: Vec<u8>) -> Option<Bitmap> {
if width == 0 || height == 0 || width > MAX_BITMAP_EDGE || height > MAX_BITMAP_EDGE || rgba.len() != width as usize * height as usize * 4 {
return None;
}
let png = encode_png(width, height, &rgba)?;
let decoded = OnceLock::new();
let _ = decoded.set(Some(Arc::new(Pixels { width, height, rgba })));
Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), smoothing: true, decoded: Arc::new(decoded) })
}
/// The decoded pixels (decoded once and shared by every clone). `None` for unreadable data.
pub fn pixels(&self) -> Option<Arc<Pixels>> {
self.decoded.get_or_init(|| decode_png(&self.png).map(Arc::new)).clone()
@@ -77,24 +101,15 @@ impl Bitmap {
/// Decodes PNG data to straight RGBA8, whatever its colour type and bit depth.
pub fn decode_png(data: &[u8]) -> Option<Pixels> {
let mut dec = png::Decoder::new(std::io::Cursor::new(data));
dec.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = dec.read_info().ok()?;
let (w, h) = reader.info().size();
if w == 0 || h == 0 || w > MAX_BITMAP_EDGE || h > MAX_BITMAP_EDGE {
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_width = MAX_BITMAP_EDGE;
opts.limits.max_height = MAX_BITMAP_EDGE;
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, data, &opts).ok()?;
let (width, height) = img.dimensions();
if width == 0 || height == 0 || width > MAX_BITMAP_EDGE || height > MAX_BITMAP_EDGE {
return None;
}
let mut buf = vec![0u8; reader.output_buffer_size()];
let info = reader.next_frame(&mut buf).ok()?;
let n = (w * h) as usize;
let rgba: Vec<u8> = match info.color_type {
png::ColorType::Rgba => buf.get(..n * 4)?.to_vec(),
png::ColorType::Rgb => buf.get(..n * 3)?.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect(),
png::ColorType::GrayscaleAlpha => buf.get(..n * 2)?.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0], p[1]]).collect(),
png::ColorType::Grayscale => buf.get(..n)?.iter().flat_map(|&g| [g, g, g, 255]).collect(),
png::ColorType::Indexed => return None, // expanded by normalize_to_color8
};
Some(Pixels { width: w, height: h, rgba })
Some(Pixels { width, height, rgba: img.to_rgba8() })
}
/// Why image data can't become a bitmap.
@@ -128,29 +143,21 @@ pub fn image_to_png(data: Vec<u8>) -> Result<Vec<u8>, ImageError> {
if !data.starts_with(&[0xff, 0xd8, 0xff]) {
return Err(ImageError::UnknownFormat);
}
use zune_jpeg::zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
let opts = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
let mut dec = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(&data), opts);
let rgba = dec.decode().map_err(|_| ImageError::Unreadable)?;
let (w, h) = dec.dimensions().ok_or(ImageError::Unreadable)?;
let (w, h) = (u32::try_from(w).map_err(|_| ImageError::BadSize)?, u32::try_from(h).map_err(|_| ImageError::BadSize)?);
if w == 0 || h == 0 || w > MAX_BITMAP_EDGE || h > MAX_BITMAP_EDGE || rgba.len() != w as usize * h as usize * 4 {
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_width = MAX_BITMAP_EDGE;
opts.limits.max_height = MAX_BITMAP_EDGE;
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, &data, &opts).map_err(|_| ImageError::Unreadable)?;
let (w, h) = img.dimensions();
if w == 0 || h == 0 || w > MAX_BITMAP_EDGE || h > MAX_BITMAP_EDGE {
return Err(ImageError::BadSize);
}
encode_png(w, h, &rgba).ok_or(ImageError::Unreadable)
encode_png(w, h, &img.to_rgba8()).ok_or(ImageError::Unreadable)
}
/// Straight RGBA8 pixels as PNG.
fn encode_png(w: u32, h: u32, rgba: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::new();
{
let mut enc = png::Encoder::new(&mut out, w, h);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
let mut wr = enc.write_header().ok()?;
wr.write_image_data(rgba).ok()?;
}
Some(out)
let img = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgba, rgba.to_vec()).ok()?;
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
/// Bytes as base64 text in files.
@@ -160,19 +167,7 @@ pub(crate) mod base64_bytes {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
for (i, shift) in [18, 12, 6, 0].into_iter().enumerate() {
if i <= chunk.len() {
out.push(ALPHABET[((n >> shift) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
craft_mime::base64::STANDARD.encode(data)
}
pub fn decode(text: &str) -> Option<Vec<u8>> {
@@ -210,6 +205,7 @@ pub(crate) mod base64_bytes {
}
}
pub use base64_bytes::decode as base64_decode;
pub use base64_bytes::encode as base64_encode;
#[cfg(test)]
@@ -217,15 +213,23 @@ mod tests {
use super::*;
fn png_of(w: u32, h: u32, rgba: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
encode_png(w, h, rgba).unwrap()
}
#[test]
fn shared_base64_encoder_preserves_all_byte_remainders() {
for (input, expected) in
[("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")]
{
let mut enc = png::Encoder::new(&mut out, w, h);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
let mut wr = enc.write_header().unwrap();
wr.write_image_data(rgba).unwrap();
assert_eq!(base64_bytes::encode(input.as_bytes()), expected);
}
let all: Vec<u8> = (0..=255).cycle().take(513).collect();
for len in 0..=all.len() {
let encoded = base64_bytes::encode(&all[..len]);
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
assert_eq!(encoded.bytes().rev().take_while(|b| *b == b'=').count(), (3 - len % 3) % 3);
assert_eq!(base64_bytes::decode(&encoded).as_deref(), Some(&all[..len]));
}
out
}
#[test]
+266 -45
View File
@@ -1,18 +1,22 @@
//! The camera layer (ADR 0027): a special layer at the top of a scene's timeline whose camera
//! views the stage. Its keyframes hold one [`ElementKind::Camera`] element, so the camera
//! The camera layer (ADR 0027, 0082): a special layer at the top of a scene's timeline whose
//! camera views the stage. Its keyframes hold one [`ElementKind::Camera`] element, so the camera
//! tweens like any instance (classic tweens and motion tweens): the element's transform is the
//! camera on the stage, `T(x, y) · R(rotation) · S(zoom)`, with the camera's centre at `(x, y)`,
//! and its colour effect's tint colours the whole view.
//! and its colour effect (None, Brightness, Tint or Advanced) colours the whole view.
//!
//! What the movie shows is the stage seen through the camera: every layer is drawn through
//! [`Camera::view`], which puts the camera's centre at the middle of the output, zoomed and
//! turned the other way. A layer's **depth** (Animate's Layer Depth) gives parallax: a layer
//! `depth` pixels behind the stage moves `FOCAL / (FOCAL + depth)` as far when the camera pans,
//! keeping its size (so a layer at depth 0 moves with the stage, a far background barely moves).
//! Everything here is pure: the camera at a frame is a function of the document.
//! turned the other way. A layer's **depth** (Animate's Layer Depth, keyable over time,
//! [`Layer::depth_at`]) places it in a pinhole perspective with a fixed focal length
//! ([`FOCAL`]): the camera at rest shows every layer as drawn, and its pans and zooms move and
//! scale a deeper layer less (ADR 0082). A layer at depth 0 is the stage plane, exactly as
//! before; a layer **attached** to the camera ignores it (titles, HUDs). Layers are drawn
//! deepest first, ties in timeline order ([`Timeline::draw_order`]). Everything here is pure:
//! the camera at a frame is a function of the document.
use crate::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements};
use crate::{ColorEffect, ColorTransform, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements};
use anicraft_geom::{Affine, Decomposed, Vec2};
use serde::{Deserialize, Serialize};
/// Smallest and largest camera zoom (5 % to 2,000 %).
pub const MIN_ZOOM: f32 = 0.05;
@@ -20,9 +24,29 @@ pub const MAX_ZOOM: f32 = 20.0;
/// Layer depth range, in pixels behind (positive) or in front of (negative) the stage.
pub const MIN_DEPTH: f32 = -500.0;
pub const MAX_DEPTH: f32 = 10_000.0;
/// Distance from the camera to the stage plane, in pixels: a layer this far behind the stage
/// moves half as much as the stage when the camera pans.
/// Distance from the camera to the stage plane at zoom 100 %, in pixels (the pinhole's focal
/// length): a layer this far behind the stage moves half as much as the stage when the camera
/// pans. Zooming moves the camera towards the stage: at zoom `z` it is `FOCAL / z` away.
pub const FOCAL: f32 = 1_000.0;
/// Nearest a layer may be to the camera and still show (pixels): a layer the camera has
/// reached or passed (a near layer under a strong zoom) isn't drawn.
pub const NEAR: f32 = FOCAL / 100.0;
/// Most depth keys one layer keeps.
pub const MAX_DEPTH_KEYS: usize = 4_096;
/// A layer's depth at one frame (ADR 0082): between two keys the depth travels linearly; before
/// the first and after the last it holds.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct DepthKey {
pub frame: u32,
pub depth: f32,
}
impl PartialEq for DepthKey {
fn eq(&self, o: &DepthKey) -> bool {
self.frame == o.frame && self.depth.to_bits() == o.depth.to_bits()
}
}
/// The camera at one frame, resolved and sanitized.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -33,16 +57,16 @@ pub struct Camera {
pub zoom: f32,
/// Radians, clockwise on the stage (the view turns the other way).
pub rotation: f32,
/// The tint colouring the whole view (`tint_amount` 0: none).
pub tint: Rgba,
pub tint_amount: f32,
/// The colour effect on everything the camera shows: None, Brightness, Tint or Advanced
/// (the camera has no opacity: Alpha reads as None and Advanced keeps alpha as it is).
pub color: ColorEffect,
}
impl Camera {
/// The camera at rest on `stage`: its centre at the stage's, zoom 100 %, no turn, no tint.
/// The view through it is the stage itself.
/// The camera at rest on `stage`: its centre at the stage's, zoom 100 %, no turn, no colour
/// effect. The view through it is the stage itself.
pub fn rest(stage: &Stage) -> Camera {
Camera { center: stage_center(stage), zoom: 1.0, rotation: 0.0, tint: Rgba::WHITE, tint_amount: 0.0 }
Camera { center: stage_center(stage), zoom: 1.0, rotation: 0.0, color: ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 } }
}
/// The camera a camera element describes (any element: its transform and colour effect).
@@ -55,13 +79,12 @@ impl Camera {
let center = Vec2::new(fin(d.tx, rest.center.x), fin(d.ty, rest.center.y));
let zoom = fin(d.sx.abs(), 1.0).clamp(MIN_ZOOM, MAX_ZOOM);
let rotation = fin(d.rotation, 0.0);
let c = el.color;
Camera { center, zoom, rotation, tint: c.tint.sanitized(), tint_amount: fin(c.tint_amount, 0.0).clamp(0.0, 1.0) }
Camera { center, zoom, rotation, color: camera_effect(&el.color) }
}
/// The camera element holding this camera (for commands).
pub fn to_element(&self, id: ElementId) -> Element {
Element { id, name: String::new(), transform: self.transform(), color: ColorEffect { alpha: 1.0, tint: self.tint, tint_amount: self.tint_amount }, kind: ElementKind::Camera }
Element { id, name: String::new(), transform: self.transform(), color: camera_effect(&self.color), kind: ElementKind::Camera }
}
/// The camera on the stage: `T(centre) · R(rotation) · S(zoom)`.
@@ -70,35 +93,78 @@ impl Camera {
}
/// The colour effect the camera puts on everything it shows.
pub fn color(&self) -> ColorEffect {
ColorEffect { alpha: 1.0, tint: self.tint, tint_amount: self.tint_amount }
pub fn color(&self) -> ColorTransform {
camera_effect(&self.color).transform()
}
/// Stage space → output space for a layer `depth` pixels behind the stage: the camera's
/// centre (moved by the layer's parallax) lands at the middle of the output, zoomed, and
/// turned against the camera's rotation.
pub fn view(&self, stage: &Stage, depth: f32) -> Affine {
/// Stage space → output space for the stage plane (a layer at depth 0): the camera's centre
/// lands at the middle of the output, zoomed, and turned against the camera's rotation.
pub fn stage_view(&self, stage: &Stage) -> Affine {
let mid = stage_center(stage);
let c = mid + (self.center - mid) * parallax(depth);
let c = self.center;
let m = Affine::translate(mid.x, mid.y).mul(&Affine::scale(self.zoom, self.zoom)).mul(&Affine::rotate(-self.rotation)).mul(&Affine::translate(-c.x, -c.y));
if m.is_finite() { m } else { Affine::IDENTITY }
}
/// Stage space → output space for a layer `depth` pixels behind the stage, by a pinhole
/// camera `FOCAL / zoom` from the stage plane (ADR 0082). The layer is drawn as it would be
/// seen if it stood that far back, enlarged so that the camera at rest shows it exactly as
/// drawn: for a stage point `p`, with `d = FOCAL / zoom + depth`,
/// `out = mid + R(−rotation) · ((FOCAL + depth) / d · (p − mid) − FOCAL / d · (centre − mid))`.
/// Depth 0 is [`Camera::stage_view`] exactly. `None` when the layer is at or behind the
/// camera (nearer than [`NEAR`]): it isn't drawn.
pub fn view(&self, stage: &Stage, depth: f32) -> Option<Affine> {
let depth = clamp_depth(depth);
if depth == 0.0 {
return Some(self.stage_view(stage));
}
let dist = FOCAL / self.zoom + depth;
if dist.is_nan() || dist < NEAR {
return None;
}
let mid = stage_center(stage);
let size = (FOCAL + depth) / dist;
let pan = (self.center - mid) * (FOCAL / dist);
let m = Affine::translate(mid.x, mid.y).mul(&Affine::rotate(-self.rotation)).mul(&Affine::translate(-pan.x, -pan.y)).mul(&Affine::scale(size, size)).mul(&Affine::translate(-mid.x, -mid.y));
Some(if m.is_finite() { m } else { Affine::IDENTITY })
}
/// How `layer` is placed at `frame` through this camera: by its depth then, or not at all
/// when attached (it stays on screen as drawn). `None`: the camera has passed it.
pub fn layer_view(&self, stage: &Stage, layer: &Layer, frame: u32) -> Option<Affine> {
if layer.attached { Some(Affine::IDENTITY) } else { self.view(stage, layer.depth_at(frame)) }
}
/// The camera's frame on the stage (what it sees), corners clockwise from the top left.
pub fn frame(&self, stage: &Stage) -> [Vec2; 4] {
let (w, h) = (stage.width as f32, stage.height as f32);
let inv = self.view(stage, 0.0).inverse().unwrap_or(Affine::IDENTITY);
let inv = self.stage_view(stage).inverse().unwrap_or(Affine::IDENTITY);
[Vec2::new(0.0, 0.0), Vec2::new(w, 0.0), Vec2::new(w, h), Vec2::new(0.0, h)].map(|p| inv.apply(p))
}
/// The stage point under output point `p` (layers at depth 0).
pub fn to_stage(&self, stage: &Stage, p: Vec2) -> Vec2 {
self.view(stage, 0.0).inverse().map_or(p, |m| m.apply(p))
self.stage_view(stage).inverse().map_or(p, |m| m.apply(p))
}
/// Whether the view is the stage as it is (nothing to apply).
pub fn is_rest(&self, stage: &Stage) -> bool {
*self == Camera::rest(stage) || (self.view(stage, 0.0) == Affine::IDENTITY && self.tint_amount <= 0.0)
let still = (self.center, self.zoom, self.rotation) == (stage_center(stage), 1.0, 0.0) || self.stage_view(stage) == Affine::IDENTITY;
still && self.color().is_identity()
}
}
/// The colour effect a camera can have: Alpha reads as None, and Advanced keeps alpha as it is
/// (the movie never fades out through its camera).
pub fn camera_effect(fx: &ColorEffect) -> ColorEffect {
match fx.sanitized() {
ColorEffect::Alpha(_) => ColorEffect::None,
ColorEffect::Advanced(mut t) => {
t.mul[3] = 1.0;
t.add[3] = 0.0;
ColorEffect::Advanced(t)
}
other => other,
}
}
@@ -107,8 +173,8 @@ pub fn stage_center(stage: &Stage) -> Vec2 {
Vec2::new(stage.width as f32 * 0.5, stage.height as f32 * 0.5)
}
/// How far a layer `depth` pixels behind the stage moves when the camera pans, as a fraction
/// of the stage's movement (1 at depth 0).
/// How far a layer `depth` pixels behind the stage moves when the camera pans at zoom 100 %,
/// as a fraction of the stage's movement (1 at depth 0).
pub fn parallax(depth: f32) -> f32 {
FOCAL / (FOCAL + clamp_depth(depth))
}
@@ -118,6 +184,68 @@ pub fn clamp_depth(depth: f32) -> f32 {
if depth.is_finite() { depth.clamp(MIN_DEPTH, MAX_DEPTH) } else { 0.0 }
}
impl Layer {
/// The layer's depth at `frame` (ADR 0082): its keys' when it has any (linear between two,
/// held outside them), else its one depth. Always in range.
pub fn depth_at(&self, frame: u32) -> f32 {
let keys = &self.depth_keys;
let Some(first) = keys.first() else { return clamp_depth(self.depth) };
// The first key after `frame` (keys are sorted by frame).
let next = keys.partition_point(|k| k.frame <= frame);
let d = match (next.checked_sub(1).and_then(|i| keys.get(i)), keys.get(next)) {
(Some(a), Some(b)) if b.frame > a.frame => {
let t = (frame - a.frame) as f32 / (b.frame - a.frame) as f32;
a.depth + (b.depth - a.depth) * t
}
(Some(a), _) => a.depth,
(None, _) => first.depth,
};
clamp_depth(d)
}
/// Whether the layer has a depth anywhere (a key or its one depth off the stage plane).
pub fn has_depth(&self) -> bool {
self.depth != 0.0 || self.depth_keys.iter().any(|k| k.depth != 0.0)
}
/// Whether the depth keys are sorted, one per frame, in range and not too many.
pub fn depth_keys_clean(&self) -> bool {
let keys = &self.depth_keys;
keys.len() <= MAX_DEPTH_KEYS && keys.windows(2).all(|w| w[0].frame < w[1].frame) && keys.iter().all(|k| clamp_depth(k.depth).to_bits() == k.depth.to_bits())
}
/// Keeps the depth keys sorted, one per frame, finite and in range, and at most
/// [`MAX_DEPTH_KEYS`]. Returns whether anything changed.
pub fn sanitize_depth_keys(&mut self) -> bool {
if self.depth_keys_clean() {
return false;
}
let keys = &mut self.depth_keys;
keys.truncate(MAX_DEPTH_KEYS);
for k in keys.iter_mut() {
k.depth = clamp_depth(k.depth);
}
// The last key given for a frame wins.
keys.reverse();
keys.sort_by_key(|k| k.frame);
keys.dedup_by_key(|k| k.frame);
true
}
/// Sets the depth at `frame` as a key (replacing one there), keeping the keys sorted.
pub fn set_depth_key(&mut self, frame: u32, depth: f32) {
let depth = clamp_depth(depth);
match self.depth_keys.binary_search_by_key(&frame, |k| k.frame) {
Ok(i) => {
if let Some(k) = self.depth_keys.get_mut(i) {
k.depth = depth;
}
}
Err(i) => self.depth_keys.insert(i, DepthKey { frame, depth }),
}
}
}
impl Timeline {
/// The camera layer, if the timeline has one (it is always the top layer).
pub fn camera_layer(&self) -> Option<&Layer> {
@@ -143,6 +271,27 @@ impl Timeline {
}
}
/// The order the layers are drawn in at `frame`, bottom first, as indices into `layers`
/// (ADR 0082): the deepest first, ties in timeline order (lower layers first). A masked
/// layer goes with its mask's depth, so a mask stays with the layers it masks. With every
/// layer on the stage plane this is the timeline order, bottom up.
pub fn draw_order(&self, frame: u32) -> Vec<usize> {
let n = self.layers.len();
let mut order: Vec<usize> = (0..n).rev().collect();
if !self.layers.iter().any(|l| l.has_depth()) {
return order;
}
let depth = |l: &Layer| -> f32 {
let mask = l.parent.and_then(|p| self.layer(p)).filter(|p| p.kind == LayerKind::Mask);
mask.unwrap_or(l).depth_at(frame)
};
let depths: Vec<f32> = self.layers.iter().map(|l| depth(l)).collect();
let at = |i: usize| depths.get(i).copied().unwrap_or(0.0);
// Stable: equal depths keep the bottom-up order. Depths are finite (clamped).
order.sort_by(|&a, &b| at(b).total_cmp(&at(a)));
order
}
/// The camera at `frame`, when the timeline has a visible camera layer with a camera on that
/// frame. A hidden camera layer is a camera turned off; a keyframe with no camera element is
/// the camera at rest.
@@ -174,8 +323,9 @@ mod tests {
#[test]
fn the_rest_camera_shows_the_stage_as_it_is() {
let c = Camera::rest(&stage());
assert_eq!(c.view(&stage(), 0.0), Affine::IDENTITY);
assert_eq!(c.view(&stage(), 5000.0), Affine::IDENTITY, "depth only matters when the camera moves");
assert_eq!(c.stage_view(&stage()), Affine::IDENTITY);
assert_eq!(c.view(&stage(), 5000.0), Some(Affine::IDENTITY), "depth only matters when the camera moves");
assert_eq!(c.view(&stage(), -400.0), Some(Affine::IDENTITY));
assert!(c.is_rest(&stage()));
let f = c.frame(&stage());
assert!(close(f[2], Vec2::new(200.0, 100.0)));
@@ -184,7 +334,7 @@ mod tests {
#[test]
fn zoom_doubles_sizes_about_the_camera_centre() {
let c = Camera { center: Vec2::new(60.0, 40.0), zoom: 2.0, ..Camera::rest(&stage()) };
let v = c.view(&stage(), 0.0);
let v = c.stage_view(&stage());
assert!(close(v.apply(Vec2::new(60.0, 40.0)), Vec2::new(100.0, 50.0)), "the centre lands mid-output");
assert!(close(v.apply(Vec2::new(70.0, 40.0)), Vec2::new(120.0, 50.0)), "10 px become 20");
// The frame sees half the stage's width.
@@ -195,7 +345,7 @@ mod tests {
#[test]
fn rotation_turns_the_view_the_other_way() {
let c = Camera { rotation: std::f32::consts::FRAC_PI_2, ..Camera::rest(&stage()) };
let v = c.view(&stage(), 0.0);
let v = c.stage_view(&stage());
// A point right of the centre ends up above it (the world turns counter-clockwise).
assert!(close(v.apply(Vec2::new(110.0, 50.0)), Vec2::new(100.0, 40.0)), "{:?}", v.apply(Vec2::new(110.0, 50.0)));
// Round trip through the element.
@@ -204,24 +354,95 @@ mod tests {
}
#[test]
fn depth_scales_the_pan_only() {
let c = Camera { center: Vec2::new(150.0, 50.0), zoom: 1.5, ..Camera::rest(&stage()) };
fn depth_zero_is_the_stage_view_bit_for_bit() {
let c = Camera { center: Vec2::new(131.7, 12.3), zoom: 1.37, rotation: 0.41, ..Camera::rest(&stage()) };
assert_eq!(c.view(&stage(), 0.0), Some(c.stage_view(&stage())));
assert_eq!(c.view(&stage(), -0.0), Some(c.stage_view(&stage())));
assert_eq!(c.view(&stage(), f32::NAN), Some(c.stage_view(&stage())), "a NaN depth is the stage plane");
}
#[test]
fn pans_move_a_layer_by_the_pinhole_ratio() {
// Analytic: a pan of 40 px at zoom 1 moves a layer at depth d by 40 · F / (F + d).
let c = Camera { center: Vec2::new(140.0, 50.0), ..Camera::rest(&stage()) };
for d in [-500.0_f32, -250.0, 0.0, 250.0, 1000.0, 3000.0, 10_000.0] {
let v = c.view(&stage(), d).unwrap_or(Affine::IDENTITY);
let moved = 100.0 - v.apply(Vec2::new(100.0, 50.0)).x;
let want = 40.0 * FOCAL / (FOCAL + d);
assert!((moved - want).abs() < 1e-3, "depth {d}: moved {moved}, want {want}");
assert!((v.mean_scale() - 1.0).abs() < 1e-5, "a pan keeps sizes at every depth");
}
assert!((parallax(FOCAL) - 0.5).abs() < 1e-6);
let near = c.view(&stage(), 0.0).apply(Vec2::new(150.0, 50.0));
let far = c.view(&stage(), FOCAL).apply(Vec2::new(125.0, 50.0));
assert!(close(near, Vec2::new(100.0, 50.0)) && close(far, Vec2::new(100.0, 50.0)), "a far layer moved half as far");
assert!((c.view(&stage(), FOCAL).mean_scale() - 1.5).abs() < 1e-4, "zoom is the same at every depth");
assert_eq!(clamp_depth(f32::NAN), 0.0);
assert_eq!(clamp_depth(-1e9), MIN_DEPTH);
}
#[test]
fn zooms_scale_a_deeper_layer_less() {
// Zoom 2: the camera is F / 2 from the stage. A layer F back is 1.5 F away: it grows by
// 2F / 1.5F = 4/3, the stage plane by 2.
let c = Camera { zoom: 2.0, ..Camera::rest(&stage()) };
let s = |d: f32| c.view(&stage(), d).map_or(0.0, |v| v.mean_scale());
assert!((s(0.0) - 2.0).abs() < 1e-5);
assert!((s(FOCAL) - 4.0 / 3.0).abs() < 1e-4, "{}", s(FOCAL));
assert!(s(MAX_DEPTH) > 1.0 && s(MAX_DEPTH) < s(FOCAL));
assert!(s(-250.0) > 2.0, "a nearer layer grows more");
// The centre stays put at every depth (the zoom is about the camera's axis).
let v = c.view(&stage(), 600.0).unwrap_or(Affine::IDENTITY);
assert!(close(v.apply(Vec2::new(100.0, 50.0)), Vec2::new(100.0, 50.0)));
// A layer the camera has passed isn't drawn: zoom 4 puts the camera 250 px from the
// stage, past a layer 400 px in front.
let past = Camera { zoom: 4.0, ..Camera::rest(&stage()) };
assert_eq!(past.view(&stage(), -400.0), None);
assert!(past.view(&stage(), -200.0).is_some());
}
#[test]
fn depth_keys_travel_linearly_and_hold_outside() {
let mut l = Layer::new(crate::LayerId(1), "x");
l.depth = 50.0;
assert_eq!(l.depth_at(7), 50.0, "no keys: the one depth");
l.set_depth_key(10, 100.0);
l.set_depth_key(20, 300.0);
assert_eq!(l.depth_at(0), 100.0);
assert_eq!(l.depth_at(15), 200.0, "the midpoint");
assert_eq!(l.depth_at(20), 300.0);
assert_eq!(l.depth_at(u32::MAX), 300.0);
l.set_depth_key(20, 1e30);
assert_eq!(l.depth_at(20), MAX_DEPTH);
// Hostile keys: unsorted, repeated, NaN, too many.
l.depth_keys = vec![DepthKey { frame: 5, depth: f32::NAN }, DepthKey { frame: 1, depth: -1e9 }, DepthKey { frame: 5, depth: 7.0 }];
assert!(l.sanitize_depth_keys());
assert_eq!(l.depth_keys, vec![DepthKey { frame: 1, depth: MIN_DEPTH }, DepthKey { frame: 5, depth: 7.0 }]);
assert!(!l.sanitize_depth_keys(), "already clean");
}
#[test]
fn camera_colour_effects_have_no_opacity() {
let mut c = Camera::rest(&stage());
c.color = ColorEffect::Brightness(0.5);
assert_eq!(c.color(), ColorTransform::brightness(0.5));
assert!(!c.is_rest(&stage()));
c.color = ColorEffect::Alpha(0.2);
assert!(c.color().is_identity() && c.is_rest(&stage()), "a camera never fades");
let mut t = ColorTransform::IDENTITY;
t.mul = [0.5, 1.0, 1.0, 0.1];
t.add = [0.2, 0.0, 0.0, -0.5];
c.color = ColorEffect::Advanced(t);
let got = c.color();
assert_eq!((got.mul[0], got.add[0], got.mul[3], got.add[3]), (0.5, 0.2, 1.0, 0.0));
let back = Camera::of_element(&c.to_element(ElementId(1)), &stage());
assert_eq!(back.color(), got);
}
#[test]
fn hostile_cameras_stay_finite() {
let mut el = Camera::rest(&stage()).to_element(ElementId(1));
el.transform = Affine { m: [f32::NAN, 0.0, 0.0, f32::INFINITY, f32::NAN, 1e30] };
el.color.tint_amount = f32::NAN;
el.color = ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN };
let c = Camera::of_element(&el, &stage());
assert!(c.view(&stage(), 0.0).is_finite());
assert!(c.stage_view(&stage()).is_finite());
for d in [f32::NAN, f32::INFINITY, -1e30, 1e30, MIN_DEPTH, MAX_DEPTH] {
assert!(c.view(&stage(), d).is_none_or(|v| v.is_finite()));
}
assert!((MIN_ZOOM..=MAX_ZOOM).contains(&c.zoom));
el.transform = Affine::scale(0.0, 0.0);
assert_eq!(Camera::of_element(&el, &stage()).zoom, MIN_ZOOM);
+114 -5
View File
@@ -1,6 +1,6 @@
//! Evaluation through the camera layer (ADR 0027).
use crate::camera::{Camera, FOCAL, MAX_DEPTH};
use crate::camera::{Camera, DepthKey, FOCAL, MAX_DEPTH};
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, MotionTween, Paint, Property, Rgba, Shape, Symbol, SymbolId, SymbolKind, Timeline, Tween, evaluate, evaluate_scene};
use anicraft_geom::{Affine, Path, Vec2};
use std::sync::Arc;
@@ -64,14 +64,13 @@ fn a_camera_zoom_doubles_sizes_about_its_centre_and_editing_keeps_stage_space()
#[test]
fn camera_rotation_and_tint_apply_to_the_whole_view() {
let mut d = one_square();
let cam = Camera { rotation: std::f32::consts::FRAC_PI_2, tint: Rgba::hex(0xff0000), tint_amount: 0.5, ..Camera::rest(&d.stage) };
let cam = Camera { rotation: std::f32::consts::FRAC_PI_2, color: ColorEffect::Tint { color: Rgba::hex(0xff0000), amount: 0.5 }, ..Camera::rest(&d.stage) };
with_camera(&mut d, &[(0, 20, cam, false)]);
let i = &evaluate(&d, 0).items[0];
// Stage point (105, 50) is right of the centre; the camera turned clockwise, so it shows
// above the middle. In the square's space that point is (10, 50).
assert!(i.transform.apply(Vec2::new(10.0, 50.0)).distance(Vec2::new(100.0, 45.0)) < 1e-3);
assert_eq!(i.color.tint_amount, 0.5);
assert_eq!(i.color.tint, Rgba::hex(0xff0000));
assert_eq!(i.color, crate::ColorTransform::tint(Rgba::hex(0xff0000), 0.5));
}
#[test]
@@ -141,7 +140,7 @@ fn the_camera_stays_on_top_alone_and_old_files_read_without_one() {
// A symbol's camera layer is a normal layer.
let mut sl = Layer::new(LayerId(80), "in symbol");
sl.kind = LayerKind::Camera;
d.library.push(Arc::new(Symbol { id: SymbolId(81), name: "S".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(sl)] } }));
d.library.push(Arc::new(Symbol { id: SymbolId(81), name: "S".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(sl)] } }));
d.sanitize();
assert_eq!(d.library[0].timeline.layers[0].kind, LayerKind::Normal);
// Depth round-trips, is left out when 0, and an old file reads at 0; hostile depths clamp.
@@ -172,3 +171,113 @@ fn a_keyframe_without_a_camera_is_the_camera_at_rest() {
assert!(d.timeline(0).camera_at(0, &d.stage).is_none());
assert_eq!(evaluate(&d, 0).items[0].transform, Affine::translate(95.0, 0.0));
}
/// Each item's x translation by element id.
fn xs(dl: &crate::DisplayList, id: u64) -> f32 {
dl.items.iter().find(|i| i.element == ElementId(id)).map_or(f32::NAN, |i| i.transform.translation().x)
}
#[test]
fn layers_at_depth_zero_are_bit_exact_through_any_camera() {
// The same scene with and without a deep layer elsewhere: the stage-plane layer's item is
// identical, bit for bit, to what the camera's stage view gives it.
let mut d = one_square();
let cam = Camera { center: Vec2::new(123.4, 56.7), zoom: 1.7, rotation: 0.3, ..Camera::rest(&d.stage) };
with_camera(&mut d, &[(0, 20, cam, false)]);
let before = evaluate(&d, 0).items[0].transform;
let want = cam.stage_view(&d.stage).mul(&Affine::translate(95.0, 0.0));
assert!(before.m.iter().zip(want.m).all(|(a, b)| (a - b).abs() < 1e-3), "the stage view: {before:?}");
let mut back = art_layer(50, square(11, 0.0));
back.depth = 400.0;
d.timeline_mut(0).layers.push(Arc::new(back));
let after = evaluate(&d, 0);
let it = after.items.iter().find(|i| i.element == ElementId(10)).unwrap();
assert_eq!(it.transform.m, before.m);
}
#[test]
fn a_pan_moves_layers_by_their_parallax_and_attached_layers_stay() {
let mut d = one_square();
let mut mid = art_layer(40, square(11, 95.0));
mid.depth = 250.0;
let mut far = art_layer(50, square(12, 95.0));
far.depth = 3000.0;
let mut hud = art_layer(60, square(13, 95.0));
hud.attached = true;
hud.depth = 900.0;
d.timeline_mut(0).layers.extend([Arc::new(mid), Arc::new(far)]);
d.timeline_mut(0).layers.insert(0, Arc::new(hud));
let cam = Camera { center: Vec2::new(150.0, 50.0), ..Camera::rest(&d.stage) };
with_camera(&mut d, &[(0, 20, cam, false)]);
let dl = evaluate(&d, 0);
// A pan of 50 px moves a layer at depth d by 50 · F / (F + d).
for (id, depth) in [(10, 0.0), (11, 250.0), (12, 3000.0)] {
let moved = 95.0 - xs(&dl, id);
let want = 50.0 * FOCAL / (FOCAL + depth);
assert!((moved - want).abs() < 1e-3, "{id}: moved {moved}, want {want}");
}
assert_eq!(xs(&dl, 13), 95.0, "the attached layer stays where it is on screen");
// While editing, every layer is in stage space.
let edit = evaluate_scene(&d, 0, 0);
assert!([10, 11, 12, 13].iter().all(|&id| xs(&edit, id) == 95.0));
}
#[test]
fn deeper_layers_draw_first_ties_in_timeline_order() {
let mut d = one_square();
// Top to bottom: 10 (depth 0), 11 (depth 500), 12 (depth 0), 13 (depth 500).
let deep = |id, el| {
let mut l = art_layer(id, el);
l.depth = 500.0;
Arc::new(l)
};
d.timeline_mut(0).layers.extend([deep(40, square(11, 0.0)), Arc::new(art_layer(50, square(12, 0.0))), deep(60, square(13, 0.0))]);
let ids = |dl: &crate::DisplayList| dl.items.iter().map(|i| i.element.0).collect::<Vec<_>>();
assert_eq!(ids(&evaluate_scene(&d, 0, 0)), [13, 11, 12, 10], "the deep pair first, each pair bottom-up");
assert_eq!(ids(&evaluate(&d, 0)), [13, 11, 12, 10], "the movie stacks as the stage does");
// All at depth 0: the timeline order, as always.
for l in &mut d.timeline_mut(0).layers {
Arc::make_mut(l).depth = 0.0;
}
assert_eq!(ids(&evaluate_scene(&d, 0, 0)), [13, 12, 11, 10]);
}
#[test]
fn a_depth_tween_is_halfway_at_its_midpoint() {
let mut d = one_square();
let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]);
l.depth_keys = vec![DepthKey { frame: 0, depth: 0.0 }, DepthKey { frame: 10, depth: 2000.0 }];
let cam = Camera { center: Vec2::new(140.0, 50.0), ..Camera::rest(&d.stage) };
with_camera(&mut d, &[(0, 20, cam, false)]);
assert_eq!(d.timeline(0).layers[1].depth_at(5), 1000.0);
// At frame 5 the layer is 1,000 px back: the 40 px pan moves it 20.
assert!((xs(&evaluate(&d, 5), 10) - 75.0).abs() < 1e-3);
assert!((xs(&evaluate(&d, 0), 10) - 55.0).abs() < 1e-3);
// Keys and attachment round-trip; older files read without them, and they are left out
// when unused.
let mut l = Layer::new(LayerId(5), "x");
let plain = serde_json::to_string(&l).unwrap();
assert!(!plain.contains("depth_keys") && !plain.contains("attached"));
l.depth_keys = vec![DepthKey { frame: 3, depth: 120.5 }];
l.attached = true;
let back: Layer = serde_json::from_str(&serde_json::to_string(&l).unwrap()).unwrap();
assert_eq!(back, l);
let old: Layer = serde_json::from_str(r#"{"id":5,"name":"x","depth":40}"#).unwrap();
assert!(old.depth_keys.is_empty() && !old.attached && old.depth_at(9) == 40.0);
// Hostile keys on load are sorted and clamped.
let mut d2 = Document::default();
Arc::make_mut(&mut d2.timeline_mut(0).layers[0]).depth_keys = vec![DepthKey { frame: 9, depth: f32::NAN }, DepthKey { frame: 2, depth: 1e20 }];
d2.sanitize();
assert_eq!(d2.timeline(0).layers[0].depth_keys, vec![DepthKey { frame: 2, depth: MAX_DEPTH }, DepthKey { frame: 9, depth: 0.0 }]);
}
#[test]
fn a_camera_brightness_colours_the_whole_view() {
let mut d = one_square();
let cam = Camera { color: ColorEffect::Brightness(-0.5), ..Camera::rest(&d.stage) };
with_camera(&mut d, &[(0, 20, cam, false)]);
assert!(d.timeline(0).camera_at(0, &d.stage).is_some(), "a colour alone is a camera that does something");
let i = &evaluate(&d, 0).items[0];
assert_eq!(i.transform, Affine::translate(95.0, 0.0), "nothing moved");
assert_eq!(i.color, crate::ColorTransform::brightness(-0.5));
}
+526
View File
@@ -0,0 +1,526 @@
//! Colour effects (ADR 0056): what Animate's Properties calls an instance's colour effect
//! *style* (None, Brightness, Tint, Advanced, Alpha), and the one colour transform every style
//! is (a multiply and an offset per channel).
//!
//! An element stores its [`ColorEffect`] as authored, so Properties shows the style and values
//! the artist chose (a tint keeps its colour at 0 %). Everything that draws works on its
//! [`ColorTransform`]: nested instances, the camera and onion skin compose their transforms
//! exactly (`concat` is the composition of the two maps), and every renderer applies the same
//! arithmetic to straight colour: `c ↦ clamp(c·multiply + offset, 0, 1)`.
//!
//! Brightness `b` is a tint towards white (`b > 0`) or black (`b < 0`) by `|b|`; a tint of
//! colour `t` by amount `k` multiplies each colour channel by `1 − k` and adds `k·t`; alpha
//! multiplies the alpha channel; Advanced is the transform itself (Animate's per-channel
//! percent and −255..255 offset, here as fractions: offset 1 is 255).
use crate::Rgba;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// A colour transform on straight (not premultiplied) colour: channel `i` (red, green, blue,
/// alpha) becomes `clamp(c·mul[i] + add[i], 0, 1)`. Offsets are fractions of the full range.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ColorTransform {
pub mul: [f32; 4],
pub add: [f32; 4],
}
impl Default for ColorTransform {
fn default() -> Self {
ColorTransform::IDENTITY
}
}
/// Animate's Advanced ranges: multipliers −100..=100 %, offsets −255..=255.
pub const ADVANCED_MUL: std::ops::RangeInclusive<f32> = -1.0..=1.0;
pub const ADVANCED_ADD: std::ops::RangeInclusive<f32> = -1.0..=1.0;
fn fin(v: f32, or: f32) -> f32 {
if v.is_finite() { v } else { or }
}
impl ColorTransform {
pub const IDENTITY: ColorTransform = ColorTransform { mul: [1.0; 4], add: [0.0; 4] };
/// Multiplies alpha by `a`.
pub fn alpha(a: f32) -> ColorTransform {
ColorTransform { mul: [1.0, 1.0, 1.0, a], add: [0.0; 4] }
}
/// Mixes colour `t` in by `k` (alpha untouched).
pub fn tint(t: Rgba, k: f32) -> ColorTransform {
let j = 1.0 - k;
ColorTransform { mul: [j, j, j, 1.0], add: [k * t.r, k * t.g, k * t.b, 0.0] }
}
/// Brightness `b` in −1..=1: a tint towards white or black by `|b|`.
pub fn brightness(b: f32) -> ColorTransform {
if b >= 0.0 { ColorTransform::tint(Rgba::WHITE, b) } else { ColorTransform::tint(Rgba::BLACK, -b) }
}
pub fn is_identity(&self) -> bool {
*self == ColorTransform::IDENTITY
}
/// `self` applied after `inner`: the effect of `inner` nested inside `self`. Exact (no clamp
/// between the two), so composing then applying is applying one then the other on colours
/// that stay in range.
pub fn concat(&self, inner: &ColorTransform) -> ColorTransform {
let mut out = ColorTransform::IDENTITY;
for i in 0..4 {
out.mul[i] = self.mul[i] * inner.mul[i];
out.add[i] = self.mul[i] * inner.add[i] + self.add[i];
}
out
}
pub fn lerp(&self, o: &ColorTransform, t: f32) -> ColorTransform {
let mut out = ColorTransform::IDENTITY;
for i in 0..4 {
out.mul[i] = anicraft_geom::lerp(self.mul[i], o.mul[i], t);
out.add[i] = anicraft_geom::lerp(self.add[i], o.add[i], t);
}
out
}
/// Non-finite values drawn as a channel of 0 (as a NaN colour always was).
pub fn sanitized(&self) -> ColorTransform {
let mut out = *self;
for i in 0..4 {
if !(out.mul[i].is_finite() && out.add[i].is_finite()) {
out.mul[i] = 0.0;
out.add[i] = 0.0;
}
}
out
}
/// The transform applied to straight colour `c`, clamped to `0..=1` (NaN to 0).
pub fn apply(&self, c: Rgba) -> Rgba {
let f = self.sanitized();
let ch = |v: f32, i: usize| {
let x = fin(v, 0.0) * f.mul[i] + f.add[i];
if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }
};
Rgba::new(ch(c.r, 0), ch(c.g, 1), ch(c.b, 2), ch(c.a, 3))
}
/// The alpha multiplier when alpha is only multiplied (no alpha offset): what can fade a
/// whole group at once.
pub fn alpha_factor(&self) -> Option<f32> {
(self.add[3] == 0.0).then(|| fin(self.mul[3], 0.0).clamp(0.0, 1.0))
}
/// The same transform with alpha untouched.
pub fn without_alpha(&self) -> ColorTransform {
let mut out = *self;
out.mul[3] = 1.0;
out.add[3] = 0.0;
out
}
/// Whether colour channels change (anything beyond alpha).
pub fn changes_colour(&self) -> bool {
self.mul[..3].iter().any(|m| *m != 1.0) || self.add[..3].iter().any(|a| *a != 0.0)
}
/// The alpha multiplier as an opacity estimate `0..=1` (picking, outlines).
pub fn opacity(&self) -> f32 {
fin(self.mul[3] + self.add[3], 0.0).clamp(0.0, 1.0)
}
}
/// The colour effect styles of Properties' Style menu, in menu order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorStyle {
None,
Brightness,
Tint,
Advanced,
Alpha,
}
impl ColorStyle {
pub const ALL: [ColorStyle; 5] = [ColorStyle::None, ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha];
/// The name used in files and commands.
pub fn key(self) -> &'static str {
match self {
ColorStyle::None => "none",
ColorStyle::Brightness => "brightness",
ColorStyle::Tint => "tint",
ColorStyle::Advanced => "advanced",
ColorStyle::Alpha => "alpha",
}
}
pub fn label(self) -> &'static str {
match self {
ColorStyle::None => "None",
ColorStyle::Brightness => "Brightness",
ColorStyle::Tint => "Tint",
ColorStyle::Advanced => "Advanced",
ColorStyle::Alpha => "Alpha",
}
}
pub fn from_key(s: &str) -> Option<ColorStyle> {
let s = s.trim().to_ascii_lowercase();
ColorStyle::ALL.into_iter().find(|x| x.key() == s)
}
}
/// An element's colour effect, as authored: one style and its values. Draw it through
/// [`ColorEffect::transform`].
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum ColorEffect {
#[default]
None,
/// Brightness −1..=1 (−100..=100 %).
Brightness(f32),
/// Tint colour (opaque) and amount 0..=1.
Tint { color: Rgba, amount: f32 },
/// Per-channel multiply and offset (Animate's Advanced).
Advanced(ColorTransform),
/// Alpha multiplier 0..=1.
Alpha(f32),
}
impl ColorEffect {
pub fn style(&self) -> ColorStyle {
match self {
ColorEffect::None => ColorStyle::None,
ColorEffect::Brightness(_) => ColorStyle::Brightness,
ColorEffect::Tint { .. } => ColorStyle::Tint,
ColorEffect::Advanced(_) => ColorStyle::Advanced,
ColorEffect::Alpha(_) => ColorStyle::Alpha,
}
}
/// What it does to colour (its values clamped into the style's range first).
pub fn transform(&self) -> ColorTransform {
match self.sanitized() {
ColorEffect::None => ColorTransform::IDENTITY,
ColorEffect::Brightness(b) => ColorTransform::brightness(b),
ColorEffect::Tint { color, amount } => ColorTransform::tint(color, amount),
ColorEffect::Advanced(t) => t,
ColorEffect::Alpha(a) => ColorTransform::alpha(a),
}
}
/// The values clamped into each style's range, non-finite ones to the style's rest value.
pub fn sanitized(&self) -> ColorEffect {
match *self {
ColorEffect::None => ColorEffect::None,
ColorEffect::Brightness(b) => ColorEffect::Brightness(fin(b, 0.0).clamp(-1.0, 1.0)),
ColorEffect::Tint { color, amount } => ColorEffect::Tint { color: color.sanitized().with_alpha(1.0), amount: fin(amount, 0.0).clamp(0.0, 1.0) },
ColorEffect::Advanced(t) => {
let mut o = t;
for i in 0..4 {
o.mul[i] = fin(t.mul[i], 1.0).clamp(*ADVANCED_MUL.start(), *ADVANCED_MUL.end());
o.add[i] = fin(t.add[i], 0.0).clamp(*ADVANCED_ADD.start(), *ADVANCED_ADD.end());
}
ColorEffect::Advanced(o)
}
ColorEffect::Alpha(a) => ColorEffect::Alpha(fin(a, 1.0).clamp(0.0, 1.0)),
}
}
/// The alpha multiplier the effect has (1 for styles that leave alpha alone).
pub fn alpha(&self) -> f32 {
self.transform().mul[3]
}
/// The effect with its alpha multiplier set to `a`, the rest kept (what ActionScript's
/// `alpha` and `element.set_alpha` do): None and Alpha become Alpha(a); Advanced keeps
/// its other channels; Brightness and Tint become Advanced when `a` isn't 1.
pub fn with_alpha(&self, a: f32) -> ColorEffect {
match *self {
ColorEffect::None | ColorEffect::Alpha(_) => ColorEffect::Alpha(a),
ColorEffect::Advanced(mut t) => {
t.mul[3] = a;
ColorEffect::Advanced(t)
}
ColorEffect::Brightness(_) | ColorEffect::Tint { .. } if a == 1.0 => *self,
ColorEffect::Brightness(_) | ColorEffect::Tint { .. } => {
let mut t = self.transform();
t.mul[3] = a;
ColorEffect::Advanced(t)
}
}
}
/// The effect in `style`, as close to this one as that style can be: Advanced is exactly
/// this transform; Alpha keeps the alpha multiplier; a tint keeps its colour; Brightness and
/// Tint otherwise start where they change nothing (the look doesn't jump when the style
/// changes, except to None).
pub fn to_style(&self, style: ColorStyle) -> ColorEffect {
if self.style() == style {
return *self;
}
match style {
ColorStyle::None => ColorEffect::None,
ColorStyle::Advanced => ColorEffect::Advanced(self.transform()),
ColorStyle::Alpha => ColorEffect::Alpha(fin(self.alpha(), 1.0).clamp(0.0, 1.0)),
ColorStyle::Brightness => ColorEffect::Brightness(0.0),
ColorStyle::Tint => ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 },
}
}
/// `inner` nested inside `self` as one effect (Break Apart): the other when either is None,
/// alphas multiplied, else the composed transform as Advanced.
pub fn nested(&self, inner: &ColorEffect) -> ColorEffect {
match (self, inner) {
(ColorEffect::None, x) | (x, ColorEffect::None) => *x,
(ColorEffect::Alpha(a), ColorEffect::Alpha(b)) => ColorEffect::Alpha(a * b),
(o, i) => ColorEffect::Advanced(o.transform().concat(&i.transform())),
}
}
/// Alpha `a`, or None at full opacity.
pub fn opacity(a: f32) -> ColorEffect {
if a < 1.0 { ColorEffect::Alpha(a) } else { ColorEffect::None }
}
/// The classic tween between two effects: within one style its values travel (a tint's
/// colour and amount); None meets any style as that style's rest value; any other change of
/// style travels in the Advanced space (multiplies and offsets), as in Animate.
pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect {
use anicraft_geom::lerp;
let rest = |s: ColorStyle| ColorEffect::None.to_style(s);
let (a, b) = match (self, o) {
(ColorEffect::None, ColorEffect::None) => return ColorEffect::None,
(ColorEffect::None, x) if x.style() != ColorStyle::Advanced => (rest(x.style()), *x),
(x, ColorEffect::None) if x.style() != ColorStyle::Advanced => (*x, rest(x.style())),
(x, y) => (*x, *y),
};
// A tint meeting None keeps its colour all the way.
let (a, b) = match (a, b) {
(ColorEffect::Tint { amount, .. }, ColorEffect::Tint { color, amount: k }) if self.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }),
(ColorEffect::Tint { color, amount }, ColorEffect::Tint { amount: k, .. }) if o.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }),
p => p,
};
match (a, b) {
(ColorEffect::Brightness(x), ColorEffect::Brightness(y)) => ColorEffect::Brightness(lerp(x, y, t)),
(ColorEffect::Alpha(x), ColorEffect::Alpha(y)) => ColorEffect::Alpha(lerp(x, y, t)),
(ColorEffect::Tint { color: c1, amount: k1 }, ColorEffect::Tint { color: c2, amount: k2 }) => ColorEffect::Tint { color: c1.lerp(c2, t), amount: lerp(k1, k2, t) },
(x, y) => ColorEffect::Advanced(x.transform().lerp(&y.transform(), t)),
}
}
/// The effect several families make together (a motion tween keying more than one, or an
/// older file's alpha with a tint): the one family when only one is in use, else Advanced
/// with them composed (alpha outermost, then brightness, tint, advanced).
pub fn compose(alpha: Option<f32>, brightness: Option<f32>, tint: Option<(Rgba, f32)>, advanced: Option<ColorTransform>) -> ColorEffect {
let n = usize::from(alpha.is_some()) + usize::from(brightness.is_some()) + usize::from(tint.is_some()) + usize::from(advanced.is_some());
if n == 1 {
if let Some(a) = alpha {
return ColorEffect::Alpha(a);
}
if let Some(b) = brightness {
return ColorEffect::Brightness(b);
}
if let Some((color, amount)) = tint {
return ColorEffect::Tint { color, amount };
}
if let Some(t) = advanced {
return ColorEffect::Advanced(t);
}
}
if n == 0 {
return ColorEffect::None;
}
let mut t = advanced.unwrap_or(ColorTransform::IDENTITY);
if let Some((c, k)) = tint {
t = ColorTransform::tint(c, k).concat(&t);
}
if let Some(b) = brightness {
t = ColorTransform::brightness(b).concat(&t);
}
if let Some(a) = alpha {
t = ColorTransform::alpha(a).concat(&t);
}
ColorEffect::Advanced(t)
}
}
// ----- files ---------------------------------------------------------------------------------
//
// Every effect is written with the fields older AniCraft files have (`alpha`, `tint`,
// `tint_amount`: the look as near as they can say it), so None, Alpha and Tint effects are
// written exactly as before. `style` (and `brightness`, `multiply`, `offset`) are added only
// when those fields alone would read back as something else. A file without `style` reads as
// it always looked: a tint, an alpha, both (Advanced), or none.
fn one() -> f32 {
1.0
}
fn white() -> Rgba {
Rgba::WHITE
}
#[derive(Serialize, Deserialize)]
struct Wire {
#[serde(default = "one")]
alpha: f32,
#[serde(default = "white")]
tint: Rgba,
#[serde(default)]
tint_amount: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
style: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
brightness: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
multiply: Option<[f32; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
offset: Option<[f32; 4]>,
}
/// What the legacy fields alone say.
fn legacy(alpha: f32, tint: Rgba, amount: f32) -> ColorEffect {
// Older builds clamped these where they drew them.
let (alpha, amount) = (fin(alpha, 1.0).clamp(0.0, 1.0), fin(amount, 0.0).clamp(0.0, 1.0));
let a = (alpha != 1.0).then_some(alpha);
let t = (amount != 0.0).then_some((tint, amount));
ColorEffect::compose(a, None, t, None)
}
impl Serialize for ColorEffect {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut w = Wire { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0, style: None, brightness: None, multiply: None, offset: None };
match *self {
ColorEffect::None => {}
ColorEffect::Alpha(a) => w.alpha = a,
ColorEffect::Tint { color, amount } => (w.tint, w.tint_amount) = (color, amount),
ColorEffect::Brightness(b) => {
(w.tint, w.tint_amount) = (if b >= 0.0 { Rgba::WHITE } else { Rgba::BLACK }, b.abs());
w.brightness = Some(b);
}
ColorEffect::Advanced(t) => {
w.alpha = t.mul[3];
(w.multiply, w.offset) = (Some(t.mul), Some(t.add));
}
}
if legacy(w.alpha, w.tint, w.tint_amount) != *self {
w.style = Some(self.style().key().to_string());
}
w.serialize(s)
}
}
impl<'de> Deserialize<'de> for ColorEffect {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let w = Wire::deserialize(d)?;
let fx = match w.style.as_deref().and_then(ColorStyle::from_key) {
None => legacy(w.alpha, w.tint, w.tint_amount),
Some(ColorStyle::None) => ColorEffect::None,
Some(ColorStyle::Alpha) => ColorEffect::Alpha(w.alpha),
Some(ColorStyle::Tint) => ColorEffect::Tint { color: w.tint, amount: w.tint_amount },
Some(ColorStyle::Brightness) => ColorEffect::Brightness(w.brightness.unwrap_or(0.0)),
Some(ColorStyle::Advanced) => ColorEffect::Advanced(ColorTransform { mul: w.multiply.unwrap_or([1.0; 4]), add: w.offset.unwrap_or([0.0; 4]) }),
};
Ok(fx.sanitized())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn close(a: Rgba, b: Rgba) -> bool {
(a.r - b.r).abs() < 1e-5 && (a.g - b.g).abs() < 1e-5 && (a.b - b.b).abs() < 1e-5 && (a.a - b.a).abs() < 1e-5
}
#[test]
fn styles_are_the_transforms_animate_documents() {
let c = Rgba::new(0.4, 0.2, 0.8, 1.0);
// Brightness +60 %: towards white; −50 %: towards black.
assert!(close(ColorEffect::Brightness(0.6).transform().apply(c), Rgba::new(0.4 * 0.4 + 0.6, 0.2 * 0.4 + 0.6, 0.8 * 0.4 + 0.6, 1.0)));
assert!(close(ColorEffect::Brightness(-0.5).transform().apply(c), Rgba::new(0.2, 0.1, 0.4, 1.0)));
// Tint 25 % red.
let t = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.25 }.transform().apply(c);
assert!(close(t, Rgba::new(0.4 * 0.75 + 0.25, 0.15, 0.6, 1.0)));
// Advanced: red ×50 %, green +51 (0.2), alpha ×80 % −25.5 (−0.1); clamped.
let adv = ColorTransform { mul: [0.5, 1.0, 1.0, 0.8], add: [0.0, 0.2, 0.5, -0.1] };
assert!(close(adv.apply(c), Rgba::new(0.2, 0.4, 1.0, 0.7)));
assert!(close(ColorEffect::Alpha(0.3).transform().apply(c), c.with_alpha(0.3)));
}
#[test]
fn composition_is_exact() {
let outer = ColorTransform::tint(Rgba::new(0.0, 0.5, 1.0, 1.0), 0.4);
let inner = ColorTransform { mul: [0.5, -0.2, 0.9, 0.7], add: [0.1, 0.6, 0.0, 0.05] };
let c = Rgba::new(0.3, 0.6, 0.2, 0.9);
assert!(close(outer.concat(&inner).apply(c), outer.apply(inner.apply(c))));
assert_eq!(ColorTransform::IDENTITY.concat(&inner), inner);
assert_eq!(inner.concat(&ColorTransform::IDENTITY), inner);
}
#[test]
fn nan_draws_a_zero_channel() {
let t = ColorTransform { mul: [f32::NAN, 1.0, 1.0, 1.0], add: [0.0; 4] };
assert_eq!(t.apply(Rgba::WHITE), Rgba::new(0.0, 1.0, 1.0, 1.0));
assert_eq!(ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN }.sanitized(), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 });
}
#[test]
fn tweens_within_a_style_and_across_styles() {
let red = Rgba::new(1.0, 0.0, 0.0, 1.0);
let blue = Rgba::new(0.0, 0.0, 1.0, 1.0);
assert_eq!(ColorEffect::Alpha(1.0).lerp(&ColorEffect::Alpha(0.0), 0.25), ColorEffect::Alpha(0.75));
assert_eq!(ColorEffect::None.lerp(&ColorEffect::Brightness(-1.0), 0.5), ColorEffect::Brightness(-0.5));
assert_eq!(ColorEffect::None.lerp(&ColorEffect::Tint { color: red, amount: 1.0 }, 0.5), ColorEffect::Tint { color: red, amount: 0.5 });
assert_eq!(ColorEffect::Tint { color: red, amount: 1.0 }.lerp(&ColorEffect::Tint { color: blue, amount: 1.0 }, 0.5), ColorEffect::Tint { color: Rgba::new(0.5, 0.0, 0.5, 1.0), amount: 1.0 });
// A style change travels in the advanced space: halfway between the two transforms.
let a = ColorEffect::Tint { color: red, amount: 1.0 };
let b = ColorEffect::Alpha(0.5);
let mid = a.lerp(&b, 0.5);
assert_eq!(mid.style(), ColorStyle::Advanced);
assert_eq!(mid.transform(), a.transform().lerp(&b.transform(), 0.5));
// The ends look like the keyframes.
assert_eq!(a.lerp(&b, 0.0).transform(), a.transform());
assert_eq!(a.lerp(&b, 1.0).transform(), b.transform());
}
#[test]
fn style_changes_keep_the_look_where_they_can() {
let fx = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.4 };
assert_eq!(fx.to_style(ColorStyle::Advanced).transform(), fx.transform());
assert_eq!(ColorEffect::Alpha(0.3).to_style(ColorStyle::Advanced).alpha(), 0.3);
assert_eq!(ColorEffect::Advanced(ColorTransform::alpha(0.3)).to_style(ColorStyle::Alpha), ColorEffect::Alpha(0.3));
assert!(fx.to_style(ColorStyle::Brightness).transform().is_identity());
assert_eq!(fx.with_alpha(0.5).transform(), ColorTransform::alpha(0.5).concat(&fx.transform()));
assert_eq!(fx.with_alpha(1.0), fx);
assert_eq!(ColorEffect::None.with_alpha(0.2), ColorEffect::Alpha(0.2));
}
#[test]
fn older_files_read_as_they_looked_and_simple_effects_write_as_before() {
let read = |s: &str| serde_json::from_str::<ColorEffect>(s).unwrap();
let white = r#""tint":{"r":1.0,"g":1.0,"b":1.0,"a":1.0}"#;
assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#)), ColorEffect::None);
assert_eq!(read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#)), ColorEffect::Alpha(0.5));
assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.25}}"#)), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.25 });
let both = read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.25}}"#));
assert_eq!(both.transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::WHITE, 0.25)));
// Byte for byte as before.
assert_eq!(serde_json::to_string(&ColorEffect::None).unwrap(), format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#));
assert_eq!(serde_json::to_string(&ColorEffect::Alpha(0.5)).unwrap(), format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#));
for fx in [
ColorEffect::None,
ColorEffect::Alpha(1.0),
ColorEffect::Alpha(0.25),
ColorEffect::Brightness(-0.5),
ColorEffect::Brightness(0.0),
ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.0 },
ColorEffect::Tint { color: Rgba::new(0.0, 0.5, 1.0, 1.0), amount: 0.75 },
ColorEffect::Advanced(ColorTransform { mul: [0.5, -1.0, 1.0, 0.75], add: [0.25, 0.0, -0.5, 0.125] }),
ColorEffect::Advanced(ColorTransform::IDENTITY),
] {
let json = serde_json::to_string(&fx).unwrap();
assert_eq!(read(&json), fx, "{json}");
}
// Brightness still reads, in older builds, as the tint it looks like.
let json = serde_json::to_string(&ColorEffect::Brightness(-0.5)).unwrap();
assert!(json.contains(r#""tint_amount":0.5"#) && json.contains(r#""style":"brightness""#), "{json}");
// Out-of-range values in a file are clamped; an unknown style reads as the legacy fields.
assert_eq!(read(r#"{"style":"brightness","brightness":7}"#), ColorEffect::Brightness(1.0));
assert_eq!(read(r#"{"style":"sepia","alpha":0.5}"#), ColorEffect::Alpha(0.5));
}
}
+935 -151
View File
File diff suppressed because it is too large. Load diff
+365
View File
@@ -0,0 +1,365 @@
use super::*;
fn all() -> Vec<Easing> {
let mut v: Vec<Easing> = Easing::named().collect();
v.extend([Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), Easing::Custom(Arc::new(wave()))]);
v
}
/// Three segments that overshoot both ways.
fn wave() -> CustomEase {
CustomEase::from_flat(&[(0.0, 0.0), (0.1, 0.6), (0.2, 1.3), (0.3, 1.3), (0.4, 1.3), (0.5, -0.2), (0.6, 0.4), (0.7, 1.0), (0.9, 1.0), (1.0, 1.0)].map(|(x, y)| Vec2::new(x, y))).unwrap()
}
#[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 presets_at_known_times() {
use std::f32::consts::PI;
let cases: [(Easing, f32, f32); 22] = [
(Easing::Linear, 0.3, 0.3),
(Easing::QuadIn, 0.5, 0.25),
(Easing::QuadOut, 0.5, 0.75),
(Easing::QuadInOut, 0.25, 0.125),
(Easing::CubicIn, 0.5, 0.125),
(Easing::CubicOut, 0.5, 0.875),
(Easing::QuartIn, 0.5, 0.0625),
(Easing::QuartInOut, 0.75, 0.96875),
(Easing::QuintIn, 0.5, 0.03125),
(Easing::QuintOut, 0.5, 0.96875),
(Easing::SineIn, 0.5, 1.0 - std::f32::consts::FRAC_1_SQRT_2),
(Easing::SineOut, 1.0 / 3.0, 0.5),
(Easing::SineInOut, 0.25, 0.5 * (1.0 - std::f32::consts::FRAC_1_SQRT_2)),
// (c + 1)/8 − c/4 with c = 1.70158: dips below zero first.
(Easing::BackIn, 0.5, -0.087_697_5),
(Easing::BackOut, 0.5, 1.087_697_5),
(Easing::CircIn, 0.6, 0.2),
(Easing::CircOut, 0.5, 0.866_025_4),
(Easing::BounceOut, 0.5, 0.765_625),
(Easing::BounceIn, 0.5, 0.234_375),
(Easing::BounceOut, 1.0 / 2.75, 1.0),
// −2⁻⁵ · sin(−5.75 · 2π/3) = −1/64; Out is its mirror.
(Easing::ElasticIn, 0.5, -0.015_625),
(Easing::ElasticOut, 0.5, 1.015_625),
];
for (e, t, want) in cases {
assert!((e.apply(t) - want).abs() < 1e-5, "{e:?} at {t}: {} vs {want}", e.apply(t));
}
assert!((Easing::Classic(-100.0).apply(0.5) - 0.25).abs() < 1e-6);
assert!((Easing::Classic(100.0).apply(0.5) - 0.75).abs() < 1e-6);
assert!((Easing::SineIn.apply(1.0 / 3.0) - (1.0 - (PI / 6.0).cos())).abs() < 1e-6);
}
#[test]
fn out_mirrors_in_and_in_out_is_symmetric() {
for f in EaseFamily::ALL {
let (i, o, io) = (Easing::preset(f, EaseDir::In), Easing::preset(f, EaseDir::Out), Easing::preset(f, EaseDir::InOut));
for k in 0..=40 {
let t = k as f32 / 40.0;
assert!((o.apply(t) - (1.0 - i.apply(1.0 - t))).abs() < 1e-5, "{f:?} at {t}");
assert!((io.apply(t) + io.apply(1.0 - t) - 1.0).abs() < 1e-5, "{f:?} at {t}");
assert!((io.apply(t * 0.5) - 0.5 * i.apply(t)).abs() < 1e-5, "{f:?} at {t}");
}
assert_eq!(Easing::preset(f, EaseDir::In).family(), Some((f, EaseDir::In)));
}
}
#[test]
fn monotonic_families_never_turn_back_and_the_others_overshoot() {
for e in all() {
let overshoots = matches!(e.family(), Some((EaseFamily::Back | EaseFamily::Elastic, _))) || e.custom().is_some();
// Bounce turns back (off the floor) without leaving 0..1.
let turns = overshoots || matches!(e.family(), Some((EaseFamily::Bounce, _)));
let (mut lo, mut hi, mut prev, mut turned) = (0.0f32, 1.0f32, -1e-6f32, false);
for i in 0..=400 {
let v = e.apply(i as f32 / 400.0);
turned |= v < prev - 1e-4;
prev = v;
lo = lo.min(v);
hi = hi.max(v);
}
assert_eq!(turned, turns, "{e:?}");
assert_eq!(lo < -1e-3 || hi > 1.0 + 1e-3, overshoots, "{e:?}: {lo}..{hi}");
}
}
#[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_eq!(Easing::ElasticOut.apply(f32::INFINITY), 0.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());
assert!(Easing::Custom(Arc::new(wave())).apply(f32::NAN).is_finite());
}
#[test]
fn bezier_forms_draw_the_same_curves() {
// Exact for these.
for e in [Easing::Linear, Easing::QuadIn, Easing::QuadOut, Easing::CubicIn, Easing::CubicOut, Easing::BackIn, Easing::BackOut, Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.2, 1.4, 0.6, -0.3)] {
let (a, b, c, d) = e.as_bezier().unwrap();
let bez = Easing::CubicBezier(a, b, c, d);
for i in 0..=20 {
let t = i as f32 / 20.0;
assert!((e.apply(t) - bez.apply(t)).abs() < 1e-3, "{e:?} at {t}");
}
}
for e in [Easing::QuadInOut, Easing::CubicInOut] {
let (a, b, c, d) = e.as_bezier().unwrap();
let bez = Easing::CubicBezier(a, b, c, d);
assert!((0..=20).all(|i| (e.apply(i as f32 / 20.0) - bez.apply(i as f32 / 20.0)).abs() < 0.08), "{e:?}");
}
// One curve can't draw a bounce or a multi-segment ease.
assert_eq!(Easing::BounceOut.as_bezier(), None);
assert_eq!(Easing::Custom(Arc::new(wave())).as_bezier(), None);
let one = Easing::Custom(Arc::new(CustomEase::from_bezier(0.1, 0.9, 0.3, 1.2)));
assert_eq!(one.as_bezier(), Some((0.1, 0.9, 0.3, 1.2)));
}
#[test]
fn every_preset_becomes_a_custom_curve_for_the_graph() {
for e in all() {
let c = e.to_custom();
assert!(c.points().len() <= MAX_EASE_POINTS, "{e:?}");
let exact = matches!(e.family(), Some((EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce, _))) || e.family().is_none();
let tol = if exact { 2e-4 } else { 5e-3 };
let mut worst = 0.0f32;
for i in 0..=500 {
let t = i as f32 / 500.0;
worst = worst.max((c.apply(t) - e.apply(t)).abs());
}
assert!(worst < tol, "{e:?}: off by {worst} with {} points", c.points().len());
}
}
#[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);
}
#[test]
fn names_round_trip_and_older_aliases_still_read() {
for e in Easing::named() {
let n = e.name().unwrap();
assert_eq!(Easing::from_name(&n), Some(e.clone()), "{n}");
// The file form is the same name.
assert_eq!(serde_json::to_string(&e).unwrap(), format!("\"{n}\""));
}
assert_eq!(Easing::from_name("back in-out"), Some(Easing::BackInOut));
assert_eq!(Easing::from_name("ease_in"), Some(Easing::QuadIn));
assert_eq!(Easing::from_name("Smooth"), Some(Easing::CubicBezier(0.25, 0.1, 0.25, 1.0)));
assert_eq!(Easing::from_name("wobble"), None);
assert_eq!(Easing::named().count(), 28);
assert_eq!(Easing::BounceInOut.label(), "Bounce In Out");
// Older files.
let old: Vec<Easing> = serde_json::from_str(r#"["QuadIn", {"Classic": 30.0}, {"CubicBezier": [0.1, 0.2, 0.3, 0.4]}, "Linear"]"#).unwrap();
assert_eq!(old, [Easing::QuadIn, Easing::Classic(30.0), Easing::CubicBezier(0.1, 0.2, 0.3, 0.4), Easing::Linear]);
}
#[test]
fn a_multi_segment_curve_evaluates_continuously_through_its_points() {
let c = wave();
assert_eq!(c.points().len(), 4);
for p in c.points() {
assert!((c.apply(p.at.x) - p.at.y).abs() < 1e-5 || p.at.x == 0.0, "{p:?}");
}
let mut prev = c.apply(0.0);
for i in 1..=10_000 {
let v = c.apply(i as f32 / 10_000.0);
assert!((v - prev).abs() < 2e-3, "a jump at {i}: {prev} → {v}");
prev = v;
}
// Rises past the end value, then falls back below where it was, as drawn.
assert!(c.apply(0.3) > 1.2 && c.apply(0.55) < 0.4);
}
#[test]
fn adding_a_point_keeps_the_shape() {
let c = wave();
let (d, i) = c.insert_at(0.42).unwrap();
assert_eq!((d.points().len(), i), (5, 2));
assert!(d.points()[2].smooth);
for k in 0..=200 {
let t = k as f32 / 200.0;
assert!((c.apply(t) - d.apply(t)).abs() < 1e-4, "at {t}");
}
// Not at an end or on a point.
assert!(c.insert_at(0.0).is_none() && c.insert_at(1.0).is_none() && c.insert_at(0.3).is_none() && c.insert_at(f32::NAN).is_none());
}
#[test]
fn point_edits_keep_time_running_forwards() {
let c = wave();
// Dragging a point past its neighbour stops at the neighbour.
let d = c.move_point(1, Vec2::new(0.95, 2.0)).unwrap();
assert_eq!(d.points()[1].at, Vec2::new(0.6, 2.0));
// The ends don't move.
assert!(c.move_point(0, Vec2::new(0.5, 0.5)).is_none() && c.move_point(3, Vec2::new(0.5, 0.5)).is_none());
// A handle dragged backwards in time stops at its point.
let h = c.move_handle(1, Handle::Out, Vec2::new(0.0, 5.0)).unwrap();
assert_eq!(h.points()[1].out.x, 0.0);
// A smooth point's other handle turns with it.
let s = c.set_smooth(1, true).unwrap();
let t = s.move_handle(1, Handle::Out, Vec2::new(0.45, 1.5)).unwrap();
let p = t.points()[1];
assert!(p.smooth && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-4, "{p:?}");
// A corner has its handles on the point.
let k = s.set_smooth(1, false).unwrap();
assert_eq!((k.points()[1].h_in, k.points()[1].out), (Vec2::ZERO, Vec2::ZERO));
// Removing.
assert_eq!(c.remove(2).unwrap().points().len(), 3);
assert!(c.remove(0).is_none() && c.remove(3).is_none());
}
/// Every segment's x control points lie between its ends, so x never decreases.
fn assert_forwards(c: &CustomEase) {
let pts = c.points();
assert!(pts.len() >= 2 && pts.len() <= MAX_EASE_POINTS);
assert_eq!((pts[0].at, pts[pts.len() - 1].at), (Vec2::ZERO, Vec2::new(1.0, 1.0)));
for i in 0..pts.len() - 1 {
let [a, b, cc, d] = c.segment(i).unwrap();
assert!(a.x <= b.x && b.x <= d.x && a.x <= cc.x && cc.x <= d.x, "segment {i}: {a:?} {b:?} {cc:?} {d:?}");
for v in [a, b, cc, d] {
assert!(v.is_finite() && v.y.abs() <= MAX_EASE_Y + 1e-4);
}
}
for k in 0..=100 {
assert!(c.apply(k as f32 / 100.0).is_finite());
}
}
#[test]
fn x_stays_monotonic_after_any_edit() {
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut rnd = || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 10_000) as f32 / 10_000.0
};
let mut c = wave();
for _ in 0..3000 {
let n = c.points().len();
let i = (rnd() * n as f32) as usize % n;
let to = Vec2::new(rnd() * 1.6 - 0.3, rnd() * 30.0 - 15.0);
let next = match (rnd() * 6.0) as u32 {
0 => c.insert_at(rnd()).map(|r| r.0),
1 => c.move_point(i, to),
2 => c.move_handle(i, Handle::In, to),
3 => c.move_handle(i, Handle::Out, to),
4 => c.set_smooth(i, rnd() > 0.5),
_ => if n > 6 { c.remove(i) } else { None },
};
if let Some(d) = next {
assert_forwards(&d);
c = d;
}
}
}
#[test]
fn hostile_curves_are_repaired() {
// NaN, reversed x, out-of-range values and handles reaching backwards.
let nan = EasePoint { at: Vec2::new(f32::NAN, 0.5), ..Default::default() };
let pts = vec![
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-5.0, f32::INFINITY), ..Default::default() },
EasePoint { at: Vec2::new(0.6, 400.0), h_in: Vec2::new(3.0, 0.0), out: Vec2::new(-2.0, 0.0), smooth: true },
nan,
EasePoint { at: Vec2::new(0.2, -1.0), ..Default::default() },
EasePoint { at: Vec2::new(-3.0, 0.0), out: Vec2::new(f32::NAN, 1.0), ..Default::default() },
];
let c = CustomEase::new(pts);
assert_eq!(c.points().len(), 4);
assert_forwards(&c);
assert_eq!(c.points()[2].at, Vec2::new(0.6, MAX_EASE_Y));
// Thousands of points are thinned to the cap, and stay a valid curve.
let many: Vec<EasePoint> = (0..20_000).map(|i| EasePoint { at: Vec2::new(((i * 7919) % 20_000) as f32 / 20_000.0, (i as f32 * 0.37).sin()), out: Vec2::new(0.5, 0.0), h_in: Vec2::new(-0.5, 0.0), smooth: false }).collect();
let c = CustomEase::new(many);
assert_eq!(c.points().len(), MAX_EASE_POINTS);
assert_forwards(&c);
// Too few points: the line.
assert_eq!(CustomEase::new(vec![nan]), CustomEase::linear());
// From a file, the same repairs.
let f: CustomEase = serde_json::from_str(r#"{"points": [{"at": {"x": 0.9, "y": 3.0}}, {"at": {"x": 0.1, "y": 0.0}, "out": {"x": -1.0, "y": 0.0}}, {"at": {"x": 0.5, "y": 0.5}}]}"#).unwrap();
assert_forwards(&f);
let e: Easing = serde_json::from_str(r#"{"Custom": {"points": []}}"#).unwrap();
assert_eq!(e, Easing::Custom(Arc::new(CustomEase::linear())));
}
#[test]
fn custom_eases_round_trip_through_files_and_flat_lists() {
let e = Easing::Custom(Arc::new(wave()));
let back: Easing = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
assert_eq!(back, e);
let flat = wave().to_flat();
assert_eq!(flat.len(), 10);
assert_eq!(CustomEase::from_flat(&flat), Some(wave()));
assert!(CustomEase::from_flat(&flat[..9]).is_none());
}
/// Four steps, as the sample ease plug-in samples them.
fn steps() -> SampledEase {
SampledEase::new("Stepped 4", "org.anicraft.stepped-ease", "steps4", (0..257).map(|i| ((i as f32 / 256.0) * 4.0).floor() / 4.0).collect())
}
#[test]
fn a_sampled_ease_reads_its_table_between_samples() {
let s = steps();
let e = Easing::Sampled(Arc::new(s.clone()));
assert_eq!((e.apply(0.0), e.apply(0.1), e.apply(0.25), e.apply(0.6), e.apply(0.9), e.apply(1.0)), (0.0, 0.0, 0.25, 0.5, 0.75, 1.0));
// Between two samples, the straight line between them.
let lin = SampledEase::new("Line", "p", "l", vec![0.0, 0.5, 1.0]);
assert!((lin.apply(0.25) - 0.25).abs() < 1e-6 && (lin.apply(0.75) - 0.75).abs() < 1e-6);
// Time outside 0..1, or not a number, is clamped.
assert_eq!((e.apply(-3.0), e.apply(7.0), e.apply(f32::NAN)), (0.0, 1.0, 0.0));
assert_eq!(e.label(), "Stepped 4");
assert!(e.family().is_none() && e.as_bezier().is_none());
assert_eq!(e.sampled().map(|s| (s.plugin(), s.ease())), Some(("org.anicraft.stepped-ease", "steps4")));
}
#[test]
fn a_sampled_ease_is_always_valid() {
let s = SampledEase::new(" ", "bad id!/..", "x\u{202e}y", vec![0.3, f32::NAN, 99.0, -f32::INFINITY, 0.2]);
assert_eq!(s.values(), &[0.0, 0.25, MAX_EASE_Y, 0.75, 1.0]);
assert_eq!((s.name(), s.plugin(), s.ease()), ("Plug-in ease", "badid..", "xy"));
assert_eq!(SampledEase::new("x", "p", "e", vec![]).values(), &[0.0, 1.0]);
assert_eq!(SampledEase::new("x", "p", "e", vec![0.5]).values(), &[0.0, 1.0]);
let long = SampledEase::new("x", "p", "e", (0..100_000).map(|i| i as f32 / 99_999.0).collect());
assert_eq!(long.values().len(), MAX_EASE_SAMPLES);
assert!((long.apply(0.5) - 0.5).abs() < 1e-3);
}
#[test]
fn a_sampled_ease_round_trips_through_the_file_format_and_survives_bad_files() {
let e = Easing::Sampled(Arc::new(steps()));
let text = serde_json::to_string(&e).unwrap();
assert!(text.starts_with("{\"Sampled\":{\"name\":\"Stepped 4\",\"plugin\":\"org.anicraft.stepped-ease\",\"ease\":\"steps4\",\"values\":[0.0,"), "{text}");
assert_eq!(serde_json::from_str::<Easing>(&text).unwrap(), e);
// A hand-edited table is made valid on load.
assert!(serde_json::from_str::<Easing>(r#"{"Sampled":{"values":[5,0.5,"x"]}}"#).is_err(), "a non-number value is a broken file, refused as any other");
let odd: Easing = serde_json::from_str(r#"{"Sampled":{"name":"Odd","values":[5,0.5,-20]}}"#).unwrap();
assert_eq!(odd.sampled().unwrap().values(), &[0.0, 0.5, 1.0]);
}
#[test]
fn a_sampled_ease_becomes_a_custom_curve_through_its_samples() {
let wave = SampledEase::new("Wave", "p", "w", (0..257).map(|i| { let t = i as f32 / 256.0; t + 0.2 * (t * std::f32::consts::TAU).sin() }).collect());
let c = wave.to_polyline();
assert_eq!(c.points().len(), POLYLINE_POINTS);
for i in 0..=100 {
let t = i as f32 / 100.0;
assert!((c.apply(t) - wave.apply(t)).abs() < 0.01, "t = {t}: {} vs {}", c.apply(t), wave.apply(t));
}
let short = SampledEase::new("Short", "p", "s", vec![0.0, 0.8, 1.0]).to_polyline();
assert_eq!(short.points().len(), 3);
assert!((short.apply(0.5) - 0.8).abs() < 1e-3);
}
+448 -106
View File
@@ -1,8 +1,9 @@
//! Timeline evaluation: `(document, frame) -> DisplayList`. Pure, deterministic, no caching.
use crate::camera::Camera;
use crate::nine_slice::Slicing;
use crate::player::PlayerState;
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, MaskMode, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
use anicraft_geom::walk::PathWalk;
use anicraft_geom::{Affine, FillRule, Path};
use std::borrow::Cow;
@@ -20,7 +21,8 @@ pub struct DisplayItem {
pub fill: Option<Paint>,
pub stroke: Option<Stroke>,
pub fill_rule: FillRule,
pub color: ColorEffect,
/// The colour transform of every instance around it, composed (ADR 0056).
pub color: ColorTransform,
/// The top-level layer and element this item came from (for picking).
pub layer: LayerId,
pub element: ElementId,
@@ -28,15 +30,24 @@ pub struct DisplayItem {
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.
/// Mask artwork: not drawn; it forms this clip: its fill area (strokes and opacity
/// ignored), or for a soft clip ([`DisplayList::clip_mode`]) its opacity or brightness as
/// drawn.
pub masks: Option<u32>,
/// Guide artwork: shown while editing, never in output.
pub guide: bool,
/// The innermost group this item fades with (see [`DisplayList::groups`]); `color.alpha`
/// The innermost group this item fades with (see [`DisplayList::groups`]); `color`
/// leaves out the groups' opacity.
pub group: Option<u32>,
/// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied).
pub image: Option<Arc<crate::Pixels>>,
/// Whether `image` is filtered between its pixels (the bitmap's Allow Smoothing, ADR 0050);
/// off, each pixel is a hard-edged square.
pub smooth: bool,
/// A warped bitmap fill (ADR 0079): the mesh, in the item's local space, that carries the
/// image as drawn (`rest`) to where it shows (`shown`); renderers draw the image through
/// its triangles. `None` for everything else (a warped shape's path is already bent).
pub warp: Option<Arc<crate::warp::WarpMesh>>,
}
/// Back-to-front list of shapes.
@@ -46,6 +57,9 @@ pub struct DisplayList {
/// 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>>,
/// How each clip's artwork reveals (ADR 0070), by clip index. Sparse: a clip past its end
/// is [`MaskMode::Coverage`], so lists that don't care leave it empty.
pub clip_modes: Vec<MaskMode>,
/// Groups that fade as one: a symbol instance with an opacity below 1 composites its
/// items together, then blends the result at `alpha`, so overlapping parts don't show
/// through each other. A group's items are one unbroken run of `items`, nested runs for
@@ -67,10 +81,28 @@ pub struct Group {
}
impl DisplayList {
/// How clip `c`'s artwork reveals (coverage when unset).
pub fn clip_mode(&self, c: u32) -> MaskMode {
self.clip_modes.get(c as usize).copied().unwrap_or_default()
}
/// Sets clip `c`'s mode (only a soft mode is stored; coverage stays implicit).
pub fn set_clip_mode(&mut self, c: u32, mode: MaskMode) {
let i = c as usize;
if mode.is_soft() && i < self.clip_parents.len() {
if self.clip_modes.len() <= i {
self.clip_modes.resize(i + 1, MaskMode::Coverage);
}
if let Some(m) = self.clip_modes.get_mut(i) {
*m = mode;
}
}
}
/// The opacity an item ends up with: its own times every group's it is in (what an item
/// looks like when nothing overlaps it; also what picking and outlines use).
pub fn effective_alpha(&self, item: &DisplayItem) -> f32 {
let mut a = item.color.alpha;
let mut a = item.color.opacity();
let mut g = item.group;
for _ in 0..self.groups.len() {
let Some(id) = g else { break };
@@ -102,6 +134,9 @@ impl DisplayList {
let gbase = self.groups.len() as u32;
let gshift = |g: Option<u32>| g.map(|g| g + gbase);
self.clip_parents.extend(other.clip_parents.into_iter().map(shift));
for (i, m) in other.clip_modes.into_iter().enumerate() {
self.set_clip_mode(base + i as u32, m);
}
self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) }));
self.items.extend(other.items.into_iter().map(|mut i| {
i.clip = shift(i.clip);
@@ -127,6 +162,25 @@ pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList {
out
}
/// A symbol's timeline at its own `frame`, in the symbol's space, as the stage edits it while the
/// symbol is open for editing (ADR 0045): what picking and bounds use then. Its layers are the
/// top-level ones, as a scene's are in [`evaluate_scene`].
pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayList {
let mut out = DisplayList::default();
eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY), &mut out, None);
out
}
/// [`evaluate_timeline`] placed by `xf` (symbol space to stage space): what an instance of the
/// timeline at `xf` shows, but with the timeline's own layers as the top-level ones, so each item
/// still says which of them it is on. The stage draws a symbol open in place this way when onion
/// skin or Edit Multiple Frames composes its frames (ADR 0051).
pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affine) -> DisplayList {
let mut out = DisplayList::default();
eval_timeline(doc, tl, frame, &Ctx::top(xf), &mut out, None);
out
}
/// Scene `scene` at its own `frame` as the movie shows it: through the scene's camera, each
/// layer shifted by its depth, the camera's tint over everything (ADR 0027). Without a camera
/// this is [`evaluate_scene`].
@@ -154,6 +208,7 @@ pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Aff
let mut out = DisplayList::default();
let mut cx = Ctx::top(xf);
cx.depth = 1;
cx.stage = false;
eval_timeline(doc, tl, frame, &cx, &mut out, play);
out
}
@@ -195,7 +250,20 @@ pub fn evaluate_guided<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk
Some((start, Cow::Owned(els)))
}
fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
/// [`evaluate_guided`] as the movie shows the layer at `fps` frames a second: an armature's
/// springs (ADR 0084) swing its bones by the motion up to the frame. This is what every
/// renderer, export, the player and the stage draw; commands edit the keyed pose
/// ([`evaluate_guided`]). The same as [`evaluate_guided`] without springs.
pub fn evaluate_shown<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>, fps: f32) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
let Some(arm) = layer.armature.as_deref().filter(|a| layer.kind == crate::LayerKind::Armature && a.has_springs()) else { return evaluate_guided(layer, frame, guide) };
let (start, els) = evaluate_tweened(layer, frame, guide)?;
let pose = crate::spring::sprung_pose(layer, frame, fps).unwrap_or_default();
let mut els = els.into_owned();
crate::armature::apply(arm, &mut els, &pose);
Some((start, Cow::Owned(els)))
}
pub(crate) fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
let idx = layer.keyframe_index_at(frame)?;
let kf = layer.keyframes.get(idx)?;
// A motion tween: its target follows the property curves (and its motion path, ADR 0030);
@@ -208,12 +276,12 @@ fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>)
}
return Some((kf.start, Cow::Owned(els)));
}
let Some(tween) = kf.tween else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
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 t = Progress::of(tween, (frame - kf.start) as f32 / kf.duration.max(1) as f32);
let morph = tween.kind == TweenKind::Shape;
let path = guide.map(|g| (g, tween.orient));
let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() };
@@ -229,14 +297,52 @@ fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>)
Some((kf.start, Cow::Owned(els)))
}
/// How far a classic tween has gone, eased, for each property group (ADR 0081): `main` for
/// what has no group (outlines, fills, strokes, a group's members), the rest each by its
/// group's ease (the tween's own when the group has none).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Progress {
pub main: f32,
pub position: f32,
pub rotation: f32,
pub scale: f32,
pub color: f32,
pub filters: f32,
}
impl Progress {
/// Everything at `t`.
pub fn uniform(t: f32) -> Progress {
Progress { main: t, position: t, rotation: t, scale: t, color: t, filters: t }
}
/// `tween` at linear progress `t`.
pub fn of(tween: &crate::Tween, t: f32) -> Progress {
let main = tween.easing.apply(t);
if tween.groups.is_empty() {
return Progress::uniform(main);
}
let g = |g: crate::EaseGroup| if tween.has_own(g) { tween.ease(g).apply(t) } else { main };
Progress { main, position: g(crate::EaseGroup::Position), rotation: g(crate::EaseGroup::Rotation), scale: g(crate::EaseGroup::Scale), color: g(crate::EaseGroup::Color), filters: g(crate::EaseGroup::Filters) }
}
}
/// Interpolates two elements; `None` when they cannot tween. With `morph` (a shape tween),
/// shapes of different structure blend through [`anicraft_geom::morph`], steered by `hints`
/// (shape hints in each element's own space, ADR 0023); otherwise a shape changes only when
/// both keyframes share its structure.
fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option<Element> {
fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option<Element> {
let t = pr.main;
let kind = match (&a.kind, &b.kind) {
(ElementKind::Shape(sa), ElementKind::Shape(sb)) => {
let path = if Arc::ptr_eq(&sa.path, &sb.path) && hints.is_empty() {
// Warped on both keyframes (ADR 0079): the pins tween and bend the outline as drawn.
let warp = match (sa.live_warp(), sb.live_warp()) {
(Some(wa), Some(wb)) if !morph || hints.is_empty() => wa.lerp(wb, t),
_ => None,
};
let path = if let Some(w) = &warp {
w.outline()
} else if Arc::ptr_eq(&sa.path, &sb.path) && hints.is_empty() {
sa.path.clone()
} else if morph {
anicraft_geom::morph::morph_hinted(&sa.path, &sb.path, hints, t).map(Arc::new).unwrap_or_else(|| sa.path.clone())
@@ -251,19 +357,54 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft
(Some(x), Some(y)) => Some(x.lerp(y, t)),
(x, _) => x.clone(),
};
ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge })
let warp = match warp {
Some(mut w) => {
w.shown = crate::warp::fingerprint(&path);
Some(Arc::new(w))
}
// Not tweening the pins: the shape keeps its warp only while it shows it.
None => sa.warp.clone().filter(|w| w.shows(&path)),
};
ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge, warp })
}
// An instance tweens its filters when both keyframes have the same kinds in the same
// order (Animate's rule); otherwise they hold.
(ElementKind::Symbol { symbol: s1, filters: fa, .. }, ElementKind::Symbol { symbol: s2, filters: fb, .. }) if s1 == s2 => {
let mut k = a.kind.clone();
if let (ElementKind::Symbol { filters, .. }, Some(lerped)) = (&mut k, crate::filter::lerp_filters(fa, fb, pr.filters)) {
*filters = lerped;
}
k
}
(ElementKind::Symbol { symbol: s1, .. }, ElementKind::Symbol { symbol: s2, .. }) if s1 == s2 => a.kind.clone(),
// Text tweens its placement and colour effect; the words stay the first keyframe's.
(ElementKind::Text(_), ElementKind::Text(_)) => a.kind.clone(),
(ElementKind::Camera, ElementKind::Camera) => ElementKind::Camera,
// A group tweens its placement and colour effect, and its members pair by order, layer by
// layer, tweening as they would on their own (ADR 0073); a member without a partner holds.
(ElementKind::Group { members: ma }, ElementKind::Group { members: mb }) => {
let mut members = ma.clone();
for (la, lb) in members.layers.iter_mut().zip(&mb.layers) {
let (Some(ka), Some(kb)) = (la.keyframe_at(0), lb.keyframe_at(0)) else { continue };
let els: Vec<Arc<Element>> = ka.elements.iter().enumerate().map(|(i, x)| kb.elements.get(i).and_then(|y| interpolate(x, y, Progress::uniform(t), morph, &[], None)).map_or_else(|| x.clone(), Arc::new)).collect();
if let Some(k) = Arc::make_mut(la).keyframe_mut(0) {
k.elements = els;
}
}
ElementKind::Group { members }
}
_ => return None,
};
let mut transform = a.transform.decompose().lerp(&b.transform.decompose(), t).compose();
if let Some((g, orient)) = guide {
transform = follow(g, orient, &a.transform, &b.transform, t, transform);
let (da, db) = (a.transform.decompose(), b.transform.decompose());
let mut d = da.lerp(&db, pr.position);
if pr.rotation != pr.position || pr.scale != pr.position {
let (r, s) = (da.lerp(&db, pr.rotation), da.lerp(&db, pr.scale));
(d.rotation, d.skew, d.sx, d.sy) = (r.rotation, r.skew, s.sx, s.sy);
}
Some(Element { id: a.id, name: a.name.clone(), transform, color: a.color.lerp(&b.color, t), kind })
let mut transform = d.compose();
if let Some((g, orient)) = guide {
transform = follow(g, orient, &a.transform, &b.transform, pr.position, transform);
}
Some(Element { id: a.id, name: a.name.clone(), transform, color: a.color.lerp(&b.color, pr.color), kind })
}
/// What a timeline is evaluated inside of.
@@ -271,11 +412,14 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft
struct Ctx {
/// Local → stage transform and colour effect of the enclosing instance.
xf: Affine,
color: ColorEffect,
color: ColorTransform,
depth: usize,
/// The top-level layer and element everything inside belongs to (for picking).
root: Option<(LayerId, ElementId)>,
outline: Option<Rgba>,
/// The stage as edited (ADR 0061): layers in outline mode are drawn as outlines. Off for
/// the movie (every export, the player): View as Outlines is an editing aid.
stage: bool,
/// The clip everything inside is drawn within.
clip: Option<u32>,
/// Set while evaluating mask artwork: everything inside forms this clip.
@@ -287,16 +431,20 @@ struct Ctx {
/// The camera the scene's layers are seen through (main timeline only; each layer's
/// transform comes from it and the layer's depth, and `xf` is ignored).
camera: Option<Camera>,
/// The 9-slice scaling of the instance whose timeline this is (ADR 0055): its own shapes go
/// through it, in place of the scale in `xf`. Not passed on to nested symbols.
slice: Option<Slicing>,
}
impl Ctx {
fn top(xf: Affine) -> Ctx {
Ctx { xf, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None }
Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None }
}
/// A main timeline seen through `camera`: its tint colours everything.
fn through(camera: Option<Camera>) -> Ctx {
let mut cx = Ctx::top(Affine::IDENTITY);
cx.stage = false;
if let Some(c) = camera {
cx.color = c.color();
cx.camera = Some(c);
@@ -335,7 +483,7 @@ pub fn guide_walk(guide: &Layer, frame: u32) -> Option<PathWalk> {
}
PathWalk::new(&pts)
}
ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => None,
ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None,
})
}
@@ -366,14 +514,22 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
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));
let c = out.clip_parents.len() as u32;
clips.push((layer.id, c));
out.clip_parents.push(cx.clip);
out.set_clip_mode(c, layer.mask_mode);
}
}
let clip_of = |id: LayerId| clips.iter().find(|(l, _)| *l == id).map(|(_, c)| *c);
// Folders draw nothing, and a hidden folder hides everything in it.
let has_folders = tl.layers.iter().any(|l| l.kind == LayerKind::Folder);
for (index, layer) in tl.layers.iter().enumerate().rev() {
// Deepest first, ties in timeline order (ADR 0082); depth belongs to a scene's own layers.
// (Only sorted when some layer has a depth: nested timelines allocate nothing.)
let sorted = (cx.depth == 0 && tl.layers.iter().any(|l| l.has_depth())).then(|| tl.draw_order(frame));
let n = tl.layers.len();
for k in 0..n {
let index = sorted.as_ref().map_or(n - 1 - k, |o| o.get(k).copied().unwrap_or(n));
let Some(layer) = tl.layers.get(index) else { continue };
// Guide artwork is listed (marked, for editing) but never drawn; inside mask artwork
// it plays no part at all.
let is_guide = layer.kind == LayerKind::Guide;
@@ -390,100 +546,286 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
let guide = cx.guide || is_guide;
// A layer guided by a guide layer: its tweens follow the guide's first path.
let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame));
let Some((kf_start, elements)) = evaluate_guided(layer, frame, walk.as_ref()) else { continue };
let layer_outline = cx.outline.or(if layer.outline { Some(layer.color) } else { None });
// Through a camera, each layer is placed by the camera and its own depth.
let layer_xf = cx.camera.map_or(cx.xf, |c| c.view(&doc.stage, layer.depth));
let Some((kf_start, elements)) = evaluate_shown(layer, frame, walk.as_ref(), doc.stage.fps) else { continue };
let layer_outline = cx.outline.or(if layer.outline && cx.stage { Some(layer.color) } else { None });
// Through a camera, each layer is placed by the camera and its own depth (an attached
// layer stays put); a layer the camera has passed isn't drawn.
let layer_xf = match cx.camera {
Some(c) => match c.layer_view(&doc.stage, layer, frame) {
Some(v) => v,
None => continue,
},
None => cx.xf,
};
let lc = LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf };
for el in elements.iter() {
// In the player, a symbol instance has its own path, and maybe properties a script set.
let child = match (&el.kind, play) {
(ElementKind::Symbol { .. }, Some(p)) => Some(p.child(el.id)),
_ => None,
eval_element(doc, cx, &lc, el, out, play);
}
}
}
/// The layer an element is drawn on, as [`eval_element`] needs it.
#[derive(Clone, Copy)]
struct LayerCtx<'a> {
layer: &'a Layer,
frame: u32,
/// The first frame of the keyframe the element is on.
kf_start: u32,
clip: Option<u32>,
masks: Option<u32>,
guide: bool,
outline: Option<Rgba>,
/// The layer's space (and, inside a group, the group's) to stage space.
xf: Affine,
}
fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: &mut DisplayList, play: Option<&Play<'_>>) {
let LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf } = *lc;
// In the player, a symbol instance has its own path, and maybe properties a script set.
let child = match (&el.kind, play) {
(ElementKind::Symbol { .. }, Some(p)) => Some(p.child(el.id)),
// So is a dynamic or input text field (ADR 0066).
(ElementKind::Text(t), Some(p)) if t.field.is_some() => Some(p.child(el.id)),
_ => None,
};
let set;
let el: &Element = match child.as_ref().and_then(|c| c.state.props.get(&c.path)) {
Some(ov) if !ov.shown() => return,
Some(ov) => {
set = ov.apply(el);
&set
}
None => el,
};
let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id));
let xf = layer_xf.mul(&el.transform);
let fx = el.color.transform();
let color = cx.color.concat(&fx);
match &el.kind {
ElementKind::Shape(s) => {
// Inside a 9-slice instance, the shape's outline is cut and mapped (bitmap
// fills scale normally, as in Animate).
let sliced = cx.slice.filter(|_| !matches!(s.fill, Some(Paint::Bitmap { .. }))).map(|sl| sliced_shape(s, &el.transform, &sl));
let is_sliced = sliced.is_some();
let (path, transform, fill, stroke) = match sliced {
Some(x) => x,
None => (s.path.clone(), xf, s.fill.clone(), s.stroke.clone()),
};
let set;
let el: &Element = match child.as_ref().and_then(|c| c.state.props.get(&c.path)) {
Some(ov) if !ov.shown() => continue,
Some(ov) => {
set = ov.apply(el);
&set
out.items.push(DisplayItem {
path,
transform,
fill,
stroke,
fill_rule: s.fill_rule,
color,
layer: root_layer,
element: root_el,
outline: layer_outline,
clip,
masks,
guide,
group: cx.group,
image: match &s.fill {
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels),
_ => None,
},
smooth: match &s.fill {
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing),
_ => true,
},
// A bitmap bent by its warp is drawn through the mesh (ADR 0079).
warp: match &s.fill {
Some(Paint::Bitmap { .. }) if !is_sliced => s.live_warp().filter(|w| !w.at_rest()).and_then(crate::warp::Warp::mesh).map(Arc::new),
_ => None,
},
});
}
ElementKind::Text(t) => {
let item = |path: Arc<Path>, transform: Affine, fill: Option<Paint>, stroke: Option<Stroke>, clip: Option<u32>, masks: Option<u32>| DisplayItem {
path,
transform,
fill,
stroke,
fill_rule: FillRule::NonZero,
color,
layer: root_layer,
element: root_el,
outline: layer_outline,
clip,
masks,
guide,
group: cx.group,
image: None,
smooth: true,
warp: None,
};
match &t.field {
// Mask artwork: a field's text masks; its box and border don't.
Some(f) if masks.is_none() => {
let live = child.as_ref().map(|c| (c.state.fields.get(&c.path), c.state.focus.as_deref() == Some(c.path.as_slice())));
field_items(t, f, live, xf, clip, out, item);
}
None => el,
};
let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id));
let xf = layer_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.clone(),
fill_rule: s.fill_rule,
color,
layer: root_layer,
element: root_el,
outline: layer_outline,
clip,
masks,
guide,
group: cx.group,
image: match &s.fill {
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels),
_ => None,
},
}),
ElementKind::Text(t) => out.items.push(DisplayItem {
path: t.outline.clone(),
transform: xf,
fill: Some(Paint::Solid(t.color)),
stroke: None,
fill_rule: FillRule::NonZero,
color,
layer: root_layer,
element: root_el,
outline: layer_outline,
clip,
masks,
guide,
group: cx.group,
image: None,
}),
ElementKind::Camera => {}
ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => {
let Some(sym) = doc.symbol(*symbol) else { continue };
let len = sym.timeline.frame_count();
let local = match (sym.kind, &child) {
// A graphic keeps step with this timeline: loop mode and first frame apply.
(SymbolKind::Graphic, _) => loop_mode.local_frame(frame.saturating_sub(kf_start), *first_frame, len),
// In the player, movie clips and buttons are where it has them.
(SymbolKind::MovieClip, Some(c)) => c.state.clip_frame(&c.path, len),
(SymbolKind::Button, Some(c)) => c.state.button_frame(&c.path, len),
// A movie clip plays its own timeline on a loop from when the instance
// appeared, carrying on across keyframes that hold the same instance.
(SymbolKind::MovieClip, None) => frame.saturating_sub(instance_start(layer, frame, el.id, *symbol)) % len.max(1),
// While editing, a button shows its Up frame.
(SymbolKind::Button, None) => 0,
};
// An instance below full opacity fades as one: its contents composite in a
// group at full opacity, and the group blends at the instance's alpha. (Mask
// artwork ignores opacity, so it never needs one.)
// A blend mode composites the instance on its own too, then blends it.
let fade = el.color.alpha.clamp(0.0, 1.0);
let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || !filters.is_empty()) {
let gid = out.groups.len() as u32;
out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: filters.iter().map(crate::Filter::sanitized).collect(), clip });
(cx.color.concat(&ColorEffect { alpha: 1.0, ..el.color }), Some(gid))
} else {
(color, cx.group)
};
let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, clip, masks, guide, group, camera: None };
eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref());
_ => {
let path = child.as_ref().and_then(|c| c.state.fields.get(&c.path)).and_then(|s| s.look.as_ref()).map_or_else(|| t.outline.clone(), |l| l.outline.clone());
out.items.push(item(path, xf, Some(Paint::Solid(t.color)), None, clip, masks));
}
}
}
ElementKind::Camera => {}
// A group (ADR 0073): its members, placed and coloured by it, as if they stood on its layer
// (graphics and movie clips inside keep time with it), picked as it. Below full opacity it
// fades as one, as an instance does.
ElementKind::Group { members } => {
if cx.depth > MAX_SYMBOL_DEPTH + crate::MAX_GROUP_DEPTH {
return;
}
let fade = fx.alpha_factor().unwrap_or(1.0);
let (color, group) = if masks.is_none() && fade < 1.0 - 1e-4 {
let gid = out.groups.len() as u32;
out.groups.push(Group { parent: cx.group, alpha: fade, blend: crate::BlendMode::Normal, filters: Arc::from(Vec::new()), clip });
(cx.color.concat(&fx.without_alpha()), Some(gid))
} else {
(color, cx.group)
};
let inner = Ctx { color, depth: cx.depth + 1, root: Some((root_layer, root_el)), group, slice: None, camera: None, ..*cx };
let lc = LayerCtx { xf, ..*lc };
for m in members.layers.iter().rev().filter(|l| l.visible && l.kind != LayerKind::Guide).filter_map(|l| l.keyframe_at(0)).flat_map(|k| k.elements.iter()) {
eval_element(doc, &inner, &lc, m, out, play);
}
}
ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => {
let Some(sym) = doc.symbol(*symbol) else { return };
let len = sym.timeline.frame_count();
let local = match (sym.kind, &child) {
// A graphic keeps step with this timeline: loop mode and first frame apply.
(SymbolKind::Graphic, _) => loop_mode.local_frame(frame.saturating_sub(kf_start), *first_frame, len),
// In the player, movie clips and buttons are where it has them.
(SymbolKind::MovieClip, Some(c)) => c.state.clip_frame(&c.path, len),
(SymbolKind::Button, Some(c)) => c.state.button_frame(&c.path, len),
// A movie clip plays its own timeline on a loop from when the instance
// appeared, carrying on across keyframes that hold the same instance.
(SymbolKind::MovieClip, None) => frame.saturating_sub(instance_start(layer, frame, el.id, *symbol)) % len.max(1),
// While editing, a button shows its Up frame.
(SymbolKind::Button, None) => 0,
};
// An instance below full opacity fades as one: its contents composite in a
// group at full opacity, and the group blends at the instance's alpha. (Mask
// artwork ignores opacity, so it never needs one.)
// A blend mode composites the instance on its own too, then blends it.
// An alpha offset (Advanced) changes each item's alpha on its own: it stays
// in the items' transform, and the group (for a blend or filters) is opaque.
let fade = fx.alpha_factor().unwrap_or(1.0);
let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || crate::filter::any_active(filters)) {
let gid = out.groups.len() as u32;
out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: crate::filter::active(filters).into(), clip });
let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx };
(cx.color.concat(&inner), Some(gid))
} else {
(color, cx.group)
};
// A symbol with 9-slice guides, scaled: its shapes are sliced (ADR 0055).
let slice = crate::nine_slice::slicing(doc, sym, &el.transform).map(|s| Slicing { post: layer_xf.mul(&s.post), ..s });
let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, stage: cx.stage, clip, masks, guide, group, camera: None, slice };
eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref());
}
}
}
/// The highlight behind selected text in a focused field.
pub const SELECTION: Rgba = Rgba::new(0.62, 0.78, 1.0, 1.0);
/// A dynamic or input field's items (ADR 0066): its background, its text cut to its box, the
/// selection and caret when it has the keyboard, and its border. `live` is its state in the
/// player (and whether it is focused); without one, it shows its authored outline.
fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option<&crate::field::FieldState>, bool)>, xf: Affine, clip: Option<u32>, out: &mut DisplayList, item: impl Fn(Arc<Path>, Affine, Option<Paint>, Option<Stroke>, Option<u32>, Option<u32>) -> DisplayItem) {
let (w, h) = (t.box_width.max(0.0), t.box_height.max(0.0));
let rect = Arc::new(Path::rect(0.0, 0.0, w, h));
if f.background {
out.items.push(item(rect.clone(), xf, Some(Paint::Solid(f.background_color)), None, clip, None));
}
// The box clips what is inside it.
let inner = out.clip_parents.len() as u32;
out.clip_parents.push(clip);
out.items.push(item(rect.clone(), xf, Some(Paint::Solid(Rgba::BLACK)), None, clip, Some(inner)));
let (state, focused) = live.unwrap_or((None, false));
let scroll = state.map_or(anicraft_geom::Vec2::ZERO, |s| s.scroll);
let text_xf = xf.mul(&Affine::translate(-scroll.x, -scroll.y));
let look = state.and_then(|s| s.look.as_deref());
// The selection, under the text.
if let (true, Some(st), Some(look)) = (focused, state, look) {
let (a, b) = st.selection();
if a != b {
for (row, l) in look.lines.iter().enumerate() {
let (from, to) = (a.max(l.start), b.min(l.end));
if from > to || (from == to && !(a <= l.end && b > l.end)) {
continue;
}
let (x0, x1) = (l.x_at(from), if b > l.end { l.x_at(l.end) + t.size * 0.25 } else { l.x_at(to) });
let y = row as f32 * look.line_height;
let r = Path::rect(crate::FIELD_GUTTER + x0, crate::FIELD_GUTTER + y, (x1 - x0).max(0.0), look.line_height);
out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(SELECTION)), None, Some(inner), None));
}
}
}
// The text: laid out by the player when it changed, else the authored outline (a field whose
// text changed but couldn't be laid out shows none).
let outline = match (state.and_then(|s| s.text.as_ref()), look) {
(_, Some(l)) => Some(l.outline.clone()),
(None, None) => Some(t.outline.clone()),
(Some(_), None) => None,
};
if let Some(path) = outline {
out.items.push(item(path, text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None));
}
// The caret, in an input field with the keyboard and nothing selected.
if let (true, Some(st), crate::TextKind::Input) = (focused, state, f.kind)
&& st.caret == st.anchor
{
let (at, lh) = look.map_or((anicraft_geom::Vec2::ZERO, t.size * 1.2), |l| (l.caret_at(st.caret), l.line_height));
let r = Path::rect(crate::FIELD_GUTTER + at.x - 0.5, crate::FIELD_GUTTER + at.y, 1.0, lh);
out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None));
}
if f.border {
let mut s = Stroke::new(f.border_color, 1.0);
s.style.join = crate::Join::Miter;
out.items.push(item(rect, xf, None, Some(s), clip, None));
}
}
/// A shape inside a 9-slice instance (ADR 0055): its outline placed by its own transform, then
/// cut at the guides and mapped piecewise; drawn by the instance's transform without its scale.
/// The stroke keeps its width (times the shape's own scale inside the symbol); gradients follow
/// the map, their size the shape's own scale times the instance's.
fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc<Path>, Affine, Option<Paint>, Option<Stroke>) {
let path = Arc::new(anicraft_geom::slice::slice_path(&s.path, own, &sl.map));
let k = own.mean_scale();
let stroke = s.stroke.as_ref().map(|st| if (k - 1.0).abs() > 1e-6 { st.scaled(k) } else { st.clone() });
let at = |p: anicraft_geom::Vec2| sl.map.map(own.apply(p));
let size = k * sl.scale.mean_scale();
let fill = s.fill.as_ref().map(|f| {
let mut f = f.clone();
match &mut f {
Paint::Linear { start, end, .. } => {
*start = at(*start);
*end = at(*end);
}
Paint::Radial { center, radius, matrix, .. } => {
// The ring's shape (its matrix's linear part) stays, round the mapped centre.
let c = at(matrix.apply(*center));
let l = Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] };
if *matrix != Affine::IDENTITY {
*matrix = Affine::translate(c.x, c.y).mul(&l).mul(&Affine::translate(-c.x, -c.y));
}
*center = c;
*radius *= size;
}
Paint::Solid(_) | Paint::Bitmap { .. } => {}
}
f
});
(path, sl.post, fill, stroke)
}
#[cfg(test)]
#[path = "eval_tests.rs"]
mod tests;
+129 -7
View File
@@ -1,5 +1,5 @@
use super::*;
use crate::{Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind};
use crate::{ColorEffect, Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind};
fn shape_el(id: u64, x: f32) -> Element {
Element {
@@ -85,7 +85,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() {
},
);
tl.layers.push(Arc::new(layer));
d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, timeline: tl }));
d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: tl }));
push(
layer0(&mut d),
0,
@@ -93,7 +93,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() {
id: ElementId(60),
name: String::new(),
transform: Affine::translate(100.0, 0.0),
color: ColorEffect { alpha: 0.5, ..Default::default() },
color: ColorEffect::Alpha(0.5),
kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() },
},
);
@@ -101,7 +101,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() {
assert_eq!(dl.items.len(), MAX_SYMBOL_DEPTH);
assert_eq!(dl.items[0].transform.translation().x, 100.0);
// The instance's opacity is its group's: it fades as one.
assert_eq!((dl.items[0].color.alpha, dl.effective_alpha(&dl.items[0])), (1.0, 0.5));
assert_eq!((dl.items[0].color.mul[3], dl.effective_alpha(&dl.items[0])), (1.0, 0.5));
assert_eq!(dl.groups.len(), 1);
assert!(dl.items.iter().all(|i| i.element == ElementId(60)));
}
@@ -140,7 +140,7 @@ 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, linkage: None, timeline: mask_doc().timeline(0).clone() }));
d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: mask_doc().timeline(0).clone() }));
let inst = Element {
id: ElementId(60),
name: String::new(),
@@ -156,6 +156,27 @@ fn masks_inside_symbols_nest_in_the_instance_clip() {
assert_eq!(inner, vec![(Some(0), None), (Some(1), None), (Some(1), None), (Some(0), Some(1))]);
}
#[test]
fn a_soft_mask_layer_gives_its_clip_its_mode() {
let mut d = mask_doc();
assert_eq!((evaluate(&d, 0).clip_mode(0), evaluate(&d, 0).clip_modes.len()), (crate::MaskMode::Coverage, 0), "coverage stays implicit");
Arc::make_mut(&mut d.timeline_mut(0).layers[0]).mask_mode = crate::MaskMode::Luminance;
let dl = evaluate(&d, 0);
assert_eq!(dl.clip_mode(0), crate::MaskMode::Luminance);
// Appended lists keep their modes on their renumbered clips.
let mut a = evaluate(&mask_doc(), 0);
a.append(dl);
assert_eq!((a.clip_mode(0), a.clip_mode(1)), (crate::MaskMode::Coverage, crate::MaskMode::Luminance));
// The mode is saved only when it isn't coverage, and older files (without it) open as coverage.
let json = serde_json::to_string(&*d.timeline(0).layers[0]).unwrap();
assert!(json.contains("\"mask_mode\":\"luminance\""), "{json}");
let plain = serde_json::to_string(&*mask_doc().timeline(0).layers[0]).unwrap();
assert!(!plain.contains("mask_mode"));
let back: Layer = serde_json::from_str(&json).unwrap();
assert_eq!(back.mask_mode, crate::MaskMode::Luminance);
assert_eq!(serde_json::from_str::<Layer>(&plain).unwrap().mask_mode, crate::MaskMode::Coverage);
}
#[test]
fn appending_lists_renumbers_clips() {
let d = mask_doc();
@@ -295,7 +316,7 @@ fn movie_clips_play_their_own_timeline_graphics_keep_step_buttons_hold_up() {
})
.collect();
let mut d = Document::default();
d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, timeline: Timeline { layers: vec![Arc::new(st)] } }));
d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(st)] } }));
// The same instance on two keyframes back to back (frames 0–4 and 5–11), moved on the second.
let inst = |x: f32| Element {
id: ElementId(60),
@@ -352,7 +373,7 @@ fn a_motion_tween_drives_each_property_on_its_own_curve() {
let d = motion_doc();
let at = |f| {
let dl = evaluate(&d, f);
(dl.items[0].transform.translation().x, dl.items[0].color.alpha)
(dl.items[0].transform.translation().x, dl.items[0].color.mul[3])
};
assert_eq!(at(0), (0.0, 1.0));
// X eases in over 0..12 (a quarter of the way at half time); alpha runs linearly over 0..23.
@@ -463,3 +484,104 @@ fn shape_hints_survive_a_round_trip_and_old_files_have_none() {
let old: Keyframe = serde_json::from_str(r#"{"start":0,"duration":3}"#).unwrap();
assert!(old.hints.is_empty());
}
/// A tween from (0, 0), unturned, full size and opaque to (100, 0), half a turn, double size
/// and transparent, over 10 frames.
fn group_doc(tween: Tween) -> Document {
let mut d = Document::default();
let mut a = shape_el(10, 0.0);
a.color = ColorEffect::Alpha(1.0);
let mut b = shape_el(10, 100.0);
b.transform = Affine::translate(100.0, 0.0).mul(&Affine::rotate(std::f32::consts::FRAC_PI_2)).mul(&Affine::scale(2.0, 2.0));
b.color = ColorEffect::Alpha(0.0);
let mut k0 = Keyframe::new(0, 10);
k0.elements.push(Arc::new(a));
k0.tween = Some(tween);
let mut k1 = Keyframe::new(10, 1);
k1.elements.push(Arc::new(b));
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
d
}
#[test]
fn classic_tweens_ease_each_property_group_its_own_way() {
use crate::EaseGroup;
let mut tw = Tween::new(Easing::Linear, TweenKind::Classic);
tw.set_ease(EaseGroup::Position, Some(Easing::BounceOut));
tw.set_ease(EaseGroup::Scale, Some(Easing::QuadIn));
tw.set_ease(EaseGroup::Color, Some(Easing::CubicOut));
let d = group_doc(tw.clone());
let it = |f| {
let dl = evaluate(&d, f);
let i = &dl.items[0];
(i.transform.decompose(), i.color.mul[3])
};
let (m, alpha) = it(5);
assert!((m.tx - 100.0 * Easing::BounceOut.apply(0.5)).abs() < 1e-2, "position: {}", m.tx);
assert!((m.sx - (1.0 + Easing::QuadIn.apply(0.5))).abs() < 1e-3, "scale: {}", m.sx);
// Rotation has no ease of its own: the tween's (linear).
assert!((m.rotation - std::f32::consts::FRAC_PI_4).abs() < 1e-3, "rotation: {}", m.rotation);
assert!((alpha - (1.0 - Easing::CubicOut.apply(0.5))).abs() < 1e-3, "colour: {alpha}");
// Groups stay in order, once each; clearing one gives it the tween's ease again.
tw.set_ease(EaseGroup::Position, Some(Easing::SineIn));
assert_eq!(tw.groups.iter().map(|g| g.0).collect::<Vec<_>>(), [EaseGroup::Position, EaseGroup::Scale, EaseGroup::Color]);
tw.set_ease(EaseGroup::Scale, None);
assert_eq!(tw.ease(EaseGroup::Scale), &Easing::Linear);
// With one ease for everything, every group follows it exactly as before.
let one = group_doc(Tween::new(Easing::QuadOut, TweenKind::Classic));
let mut same = Tween::new(Easing::QuadOut, TweenKind::Classic);
for g in EaseGroup::ALL {
same.set_ease(g, Some(Easing::QuadOut));
}
let both = group_doc(same);
for f in 0..=10 {
assert_eq!(evaluate(&one, f).items[0].transform, evaluate(&both, f).items[0].transform);
}
// Older files' tweens (no groups) still read.
let t: Tween = serde_json::from_str(r#"{"easing": "QuadIn"}"#).unwrap();
assert!(t.groups.is_empty());
}
#[test]
fn a_custom_ease_drives_a_classic_tween() {
let c = crate::CustomEase::from_flat(&[(0.0, 0.0), (0.2, 1.5), (0.4, 1.5), (0.5, 1.2), (0.6, 0.9), (0.8, 1.0), (1.0, 1.0)].map(|(x, y)| anicraft_geom::Vec2::new(x, y))).unwrap();
let e = Easing::Custom(Arc::new(c.clone()));
let d = tween_doc(e);
for f in 0..10 {
let x = evaluate(&d, f).items[0].transform.translation().x;
assert!((x - 100.0 * c.apply(f as f32 / 10.0)).abs() < 1e-2, "frame {f}: {x}");
}
// It overshoots past the second keyframe and comes back.
assert!(evaluate(&d, 5).items[0].transform.translation().x > 100.0);
}
#[test]
fn instance_filters_tween_when_they_pair_up() {
use crate::Filter;
let mut d = Document::default();
let sid = SymbolId(90);
d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(Layer::new(LayerId(91), "x"))] } }));
let inst = |filters: Vec<Filter>| Element { id: ElementId(92), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: filters.into_iter().map(Into::into).collect(), events: Vec::new() } };
let blur = |b: f32| Filter::Blur { blur_x: b, blur_y: b, quality: 1 };
let mut tw = Tween::new(Easing::Linear, TweenKind::Classic);
tw.set_ease(crate::EaseGroup::Filters, Some(Easing::QuadIn));
let mut k0 = Keyframe::new(0, 10);
k0.elements.push(Arc::new(inst(vec![blur(0.0), Filter::new("glow").unwrap()])));
k0.tween = Some(tw);
let mut k1 = Keyframe::new(10, 1);
k1.elements.push(Arc::new(inst(vec![blur(40.0), Filter::new("glow").unwrap()])));
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
let filters = |f| match &crate::evaluate_layer_elements(&d.timeline(0).layers[0], f).unwrap().1[0].kind {
ElementKind::Symbol { filters, .. } => filters.clone(),
_ => Vec::new(),
};
assert_eq!(filters(5)[0], blur(40.0 * 0.25).into(), "eased by the filters group's ease");
// Lists that don't pair up hold the first keyframe's.
let e = |f: Filter| crate::FilterEntry::from(f);
assert_eq!(crate::filter::lerp_filters(&[e(blur(1.0))], &[e(Filter::new("glow").unwrap())], 0.5), None);
assert_eq!(crate::filter::lerp_filters(&[e(blur(1.0))], &[e(blur(1.0)), e(blur(2.0))], 0.5), None);
// A switched-off filter still pairs up (and stays off, as the first keyframe has it).
let off = crate::FilterEntry { filter: blur(0.0), enabled: false };
let got = crate::filter::lerp_filters(std::slice::from_ref(&off), &[e(blur(10.0))], 0.5).unwrap();
assert_eq!(got, vec![crate::FilterEntry { filter: blur(5.0), enabled: false }]);
}
+390
View File
@@ -0,0 +1,390 @@
//! Text fields while a movie plays (ADR 0066): what a dynamic or input field holds, where its
//! caret and selection are, and the editing that keys and the pointer do to it.
//!
//! Everything here is pure data and pure functions, like the rest of the player: the same field,
//! look and keys always give the same text, caret and selection. Laying text out needs the
//! fonts, which live a layer above (`anicraft-text`), so the player asks its host for a
//! [`FieldLook`] whenever a field's text changes and keeps it in the state; drawing a state then
//! needs nothing else.
use crate::{FIELD_GUTTER, LineType, MAX_FIELD_CHARS, TextBlock, TextField, TextKind};
use anicraft_geom::{Path, Vec2};
use std::sync::Arc;
/// One laid-out line's characters and caret places (indices count `char`s of the shown text).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CaretLine {
/// The first character on the line and the boundary after its last.
pub start: u32,
pub end: u32,
/// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending; `x` from
/// the text's left edge (the box's, less the gutter).
pub stops: Vec<(u32, f32)>,
}
impl CaretLine {
/// The caret's x at boundary `i`.
pub fn x_at(&self, i: u32) -> f32 {
let mut x = self.stops.first().map_or(0.0, |s| s.1);
for &(c, sx) in &self.stops {
if c > i {
break;
}
x = sx;
}
x
}
/// The boundary nearest `x`.
pub fn index_at(&self, x: f32) -> u32 {
let mut best = (self.start, f32::INFINITY);
for &(c, sx) in &self.stops {
let d = (sx - x).abs();
if d < best.1 {
best = (c, d);
}
}
best.0.clamp(self.start, self.end)
}
}
/// A field's text laid out: its outline (in the box's space, the gutter applied, as a text
/// block's outline is) and where the caret can stand.
#[derive(Clone, Debug, PartialEq)]
pub struct FieldLook {
pub outline: Arc<Path>,
/// Top line first; never empty.
pub lines: Arc<[CaretLine]>,
/// From one line's top to the next's.
pub line_height: f32,
/// The laid-out text's size (it may be bigger than the box, which clips it).
pub width: f32,
pub height: f32,
}
impl FieldLook {
/// The line holding boundary `i`: the last that starts at or before it.
pub fn line_of(&self, i: u32) -> usize {
let mut at = 0;
for (n, l) in self.lines.iter().enumerate() {
if l.start <= i {
at = n;
} else {
break;
}
}
at
}
/// The caret's place at boundary `i`: x from the text's left, and the line's top.
pub fn caret_at(&self, i: u32) -> Vec2 {
let n = self.line_of(i);
let x = self.lines.get(n).map_or(0.0, |l| l.x_at(i));
Vec2::new(x, n as f32 * self.line_height)
}
/// The boundary nearest a point in the text's space.
pub fn index_at(&self, p: Vec2) -> u32 {
let h = self.line_height.max(1e-3);
let row = if p.y.is_finite() { (p.y / h).floor().max(0.0) as usize } else { 0 };
let row = row.min(self.lines.len().saturating_sub(1));
self.lines.get(row).map_or(0, |l| l.index_at(p.x))
}
}
/// What a field holds while the movie plays.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FieldState {
/// Its text once a script or the viewer changed it; `None`: the timeline's own (so a
/// keyframe with other words still shows them).
pub text: Option<String>,
/// The text laid out (the host's work); `None` while it shows the authored outline.
pub look: Option<Arc<FieldLook>>,
/// The caret and the other end of the selection (character boundaries; equal: nothing
/// selected).
pub caret: u32,
pub anchor: u32,
/// How far the text has scrolled to keep the caret in view (pixels, never negative).
pub scroll: Vec2,
}
impl FieldState {
/// The field's text: what was set, or the block's own.
pub fn value<'a>(&'a self, block: &'a TextBlock) -> &'a str {
self.text.as_deref().unwrap_or(&block.text)
}
/// The selected range, low end first.
pub fn selection(&self) -> (u32, u32) {
(self.caret.min(self.anchor), self.caret.max(self.anchor))
}
/// The selected text.
pub fn selected(&self, block: &TextBlock) -> String {
let (a, b) = self.selection();
slice(self.value(block), a, b).to_string()
}
}
/// The byte offset of character boundary `i` in `s` (its end when past it).
pub fn byte_at(s: &str, i: u32) -> usize {
s.char_indices().nth(i as usize).map_or(s.len(), |(b, _)| b)
}
/// The characters of `s` from boundary `a` to `b`.
pub fn slice(s: &str, a: u32, b: u32) -> &str {
let (x, y) = (byte_at(s, a.min(b)), byte_at(s, a.max(b)));
s.get(x..y).unwrap_or("")
}
/// Characters in `s`, as boundaries count them.
pub fn chars(s: &str) -> u32 {
s.chars().count().min(u32::MAX as usize) as u32
}
/// Text a script sets, as a field keeps it: at most [`MAX_FIELD_CHARS`] characters, with `\r`
/// and `\r\n` (ActionScript's line ends) as line breaks.
pub fn fit(field: &TextField, text: &str) -> String {
let _ = field;
text.replace("\r\n", "\n").replace('\r', "\n").chars().take(MAX_FIELD_CHARS).collect()
}
/// What an editing key does (the ActionScript key codes the player receives).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Edit {
Left,
Right,
Up,
Down,
Home,
End,
Backspace,
Delete,
Enter,
SelectAll,
}
impl Edit {
/// The edit a key code makes, if any.
pub fn from_key(code: u32) -> Option<Edit> {
Some(match code {
37 => Edit::Left,
39 => Edit::Right,
38 => Edit::Up,
40 => Edit::Down,
36 => Edit::Home,
35 => Edit::End,
8 => Edit::Backspace,
46 => Edit::Delete,
13 => Edit::Enter,
_ => return None,
})
}
}
/// What an edit changed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Changed {
pub text: bool,
pub caret: bool,
}
/// A focused field being edited: its block (style and authored text), its state, and whether
/// the viewer may change the text (input fields) or only select it.
pub struct Editor<'a> {
pub block: &'a TextBlock,
pub field: &'a TextField,
pub st: &'a mut FieldState,
}
impl Editor<'_> {
fn len(&self) -> u32 {
chars(self.st.value(self.block))
}
fn editable(&self) -> bool {
self.field.kind == TextKind::Input
}
/// Replaces the selection with `s` (typed characters, a paste or a line break).
pub fn insert(&mut self, s: &str) -> Changed {
if !self.editable() {
return Changed::default();
}
let one = !self.field.lines.multiline();
let mut add: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !one)).collect();
let (a, b) = self.st.selection();
let value = self.st.value(self.block).to_string();
let kept = chars(&value) - (b - a);
let room = if self.field.max_chars > 0 { self.field.max_chars.saturating_sub(kept) } else { u32::MAX };
let room = room.min((MAX_FIELD_CHARS as u32).saturating_sub(kept));
if chars(&add) > room {
add = add.chars().take(room as usize).collect();
}
if add.is_empty() && a == b {
return Changed::default();
}
let mut next = String::with_capacity(value.len() + add.len());
next.push_str(slice(&value, 0, a));
next.push_str(&add);
next.push_str(slice(&value, b, u32::MAX));
let caret = a + chars(&add);
self.st.text = Some(next);
self.st.caret = caret;
self.st.anchor = caret;
Changed { text: true, caret: true }
}
/// One editing key; `shift` extends the selection with caret moves.
pub fn key(&mut self, e: Edit, shift: bool, look: Option<&FieldLook>) -> Changed {
let len = self.len();
let (a, b) = self.st.selection();
let moved = |st: &mut FieldState, to: u32, shift: bool| {
st.caret = to.min(len);
if !shift {
st.anchor = st.caret;
}
Changed { text: false, caret: true }
};
match e {
Edit::SelectAll => {
self.st.anchor = 0;
self.st.caret = len;
Changed { text: false, caret: true }
}
Edit::Left if !shift && a != b => moved(self.st, a, false),
Edit::Right if !shift && a != b => moved(self.st, b, false),
Edit::Left => {
let to = self.st.caret.saturating_sub(1);
moved(self.st, to, shift)
}
Edit::Right => {
let to = self.st.caret.saturating_add(1);
moved(self.st, to, shift)
}
Edit::Home | Edit::End | Edit::Up | Edit::Down => {
let Some(look) = look else {
let to = if matches!(e, Edit::Home | Edit::Up) { 0 } else { len };
return moved(self.st, to, shift);
};
let n = look.line_of(self.st.caret);
let line = look.lines.get(n);
let to = match e {
Edit::Home => line.map_or(0, |l| l.start),
Edit::End => line.map_or(len, |l| l.end),
_ => {
let x = line.map_or(0.0, |l| l.x_at(self.st.caret));
let target = if e == Edit::Up { n.checked_sub(1) } else { Some(n + 1).filter(|m| *m < look.lines.len()) };
match target.and_then(|m| look.lines.get(m)) {
Some(l) => l.index_at(x),
None if e == Edit::Up => 0,
None => len,
}
}
};
moved(self.st, to, shift)
}
Edit::Backspace | Edit::Delete if !self.editable() => Changed::default(),
Edit::Backspace | Edit::Delete if a != b => self.insert(""),
Edit::Backspace => {
if a == 0 {
return Changed::default();
}
self.st.anchor = a - 1;
self.insert("")
}
Edit::Delete => {
if b >= len {
return Changed::default();
}
self.st.anchor = a;
self.st.caret = b + 1;
self.insert("")
}
Edit::Enter if self.field.lines.multiline() => self.insert("\n"),
Edit::Enter => Changed::default(),
}
}
/// The pointer at `p` (the text's space): pressed (`extend`: dragging from an earlier press).
pub fn point(&mut self, p: Vec2, extend: bool, look: Option<&FieldLook>) -> Changed {
let i = look.map_or(self.len(), |l| l.index_at(p + self.st.scroll)).min(self.len());
self.st.caret = i;
if !extend {
self.st.anchor = i;
}
Changed { text: false, caret: true }
}
}
/// Keeps the caret in view: scrolls the text so the caret's line fits in the box's height and
/// (when lines don't wrap) the caret in its width.
pub fn scroll_to_caret(block: &TextBlock, field: &TextField, st: &mut FieldState) {
let Some(look) = st.look.clone() else {
st.scroll = Vec2::ZERO;
return;
};
let view = Vec2::new((block.box_width - 2.0 * FIELD_GUTTER).max(1.0), (block.box_height - 2.0 * FIELD_GUTTER).max(1.0));
let c = look.caret_at(st.caret);
let mut s = st.scroll;
if field.lines != LineType::Multiline {
if c.x - s.x > view.x {
s.x = c.x - view.x;
}
if c.x < s.x {
s.x = c.x;
}
} else {
s.x = 0.0;
}
if c.y + look.line_height - s.y > view.y {
s.y = c.y + look.line_height - view.y;
}
if c.y < s.y {
s.y = c.y;
}
// Never past the text's end.
s.x = s.x.min((look.width - view.x).max(0.0)).max(0.0);
s.y = s.y.min((look.height - view.y).max(0.0)).max(0.0);
st.scroll = if s.x.is_finite() && s.y.is_finite() { s } else { Vec2::ZERO };
}
/// A look for tests: every character `cw` wide and `lh` tall (a square per visible one), lines
/// broken at `\n` and, with `wrap`, after as many characters as fit.
#[cfg(test)]
pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option<f32>) -> FieldLook {
let per = wrap.map(|w| ((w / cw).floor() as u32).max(1));
let mut lines = Vec::new();
let mut outline = Path::new();
let (mut start, mut col, mut stops, mut width) = (0u32, 0u32, vec![(0u32, 0.0f32)], 0.0f32);
let mut i = 0u32;
for c in text.chars() {
if c == '\n' {
lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) });
i += 1;
(start, col) = (i, 0);
stops.push((i, 0.0));
continue;
}
if per.is_some_and(|p| col == p) {
lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) });
(start, col) = (i, 0);
stops.push((i, 0.0));
}
if !c.is_whitespace() {
let r = Path::rect(FIELD_GUTTER + col as f32 * cw + 1.0, FIELD_GUTTER + lines.len() as f32 * lh + 1.0, cw - 2.0, lh - 2.0);
outline.cmds.extend(r.cmds);
}
col += 1;
i += 1;
stops.push((i, col as f32 * cw));
width = width.max(col as f32 * cw);
}
lines.push(CaretLine { start, end: i, stops });
let n = lines.len();
FieldLook { outline: Arc::new(outline), lines: lines.into(), line_height: lh, width, height: n as f32 * lh }
}
#[cfg(test)]
#[path = "field_tests.rs"]
mod tests;
+182
View File
@@ -0,0 +1,182 @@
use super::*;
use crate::{Rgba, TextAlign};
fn block(text: &str, f: TextField) -> TextBlock {
TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f), on_path: None }
}
/// Runs edits on a field as the player does: each change of text lays it out again (10 px per
/// character, 10 px lines) and keeps the caret in view.
struct Rig {
block: TextBlock,
field: TextField,
st: FieldState,
}
impl Rig {
fn new(text: &str, kind: TextKind, lines: LineType) -> Rig {
let field = TextField { lines, ..TextField::new(kind) };
let mut r = Rig { block: block(text, field.clone()), field, st: FieldState::default() };
r.relayout();
r
}
fn relayout(&mut self) {
let shown = self.field.shown(self.st.value(&self.block));
self.st.look = Some(Arc::new(mono_look(&shown, 10.0, 10.0, self.field.wrap_width(self.block.box_width))));
scroll_to_caret(&self.block, &self.field, &mut self.st);
}
fn apply(&mut self, ch: Changed) {
if ch.text {
self.relayout();
} else {
scroll_to_caret(&self.block, &self.field, &mut self.st);
}
}
fn ed(&mut self) -> (Editor<'_>, Option<Arc<FieldLook>>) {
let look = self.st.look.clone();
(Editor { block: &self.block, field: &self.field, st: &mut self.st }, look)
}
fn key(&mut self, e: Edit, shift: bool) -> &mut Self {
let (mut ed, look) = self.ed();
let ch = ed.key(e, shift, look.as_deref());
self.apply(ch);
self
}
fn typed(&mut self, s: &str) -> &mut Self {
for c in s.chars() {
let (mut ed, _) = self.ed();
let ch = ed.insert(&c.to_string());
self.apply(ch);
}
self
}
fn click(&mut self, x: f32, y: f32, extend: bool) -> &mut Self {
let (mut ed, look) = self.ed();
let ch = ed.point(Vec2::new(x, y), extend, look.as_deref());
self.apply(ch);
self
}
fn text(&self) -> &str {
self.st.value(&self.block)
}
}
#[test]
fn typing_moves_the_caret_and_keys_edit_around_it() {
let mut r = Rig::new("", TextKind::Input, LineType::Single);
r.typed("hello");
assert_eq!((r.text(), r.st.caret, r.st.anchor), ("hello", 5, 5));
r.key(Edit::Left, false).key(Edit::Left, false).typed("X");
assert_eq!((r.text(), r.st.caret), ("helXlo", 4));
r.key(Edit::Backspace, false);
assert_eq!((r.text(), r.st.caret), ("hello", 3));
r.key(Edit::Delete, false);
assert_eq!((r.text(), r.st.caret), ("helo", 3));
r.key(Edit::Home, false);
assert_eq!(r.st.caret, 0);
r.key(Edit::Backspace, false);
assert_eq!(r.text(), "helo", "nothing before the caret");
r.key(Edit::End, false).key(Edit::Delete, false);
assert_eq!((r.text(), r.st.caret), ("helo", 4), "nothing after it");
// Enter types nothing in a one-line field; control characters never go in.
r.key(Edit::Enter, false).typed("\u{7}\t");
assert_eq!(r.text(), "helo");
}
#[test]
fn shift_selects_and_typing_replaces_the_selection() {
let mut r = Rig::new("abcdef", TextKind::Input, LineType::Single);
r.click(20.0, 5.0, false);
assert_eq!(r.st.caret, 2, "a click puts the caret at the nearest boundary");
r.key(Edit::Right, true).key(Edit::Right, true);
assert_eq!(r.st.selection(), (2, 4));
assert_eq!(r.st.selected(&r.block), "cd");
// An arrow without Shift collapses the selection to its side.
r.key(Edit::Left, false);
assert_eq!((r.st.caret, r.st.anchor), (2, 2));
r.key(Edit::End, true);
assert_eq!(r.st.selection(), (2, 6));
r.typed("Z");
assert_eq!((r.text(), r.st.caret), ("abZ", 3));
// Dragging extends from where the press was; Backspace deletes the selection.
r.click(0.0, 5.0, false).click(19.0, 5.0, true);
assert_eq!(r.st.selection(), (0, 2));
r.key(Edit::Backspace, false);
assert_eq!((r.text(), r.st.caret), ("Z", 0));
r.key(Edit::SelectAll, false);
assert_eq!(r.st.selection(), (0, 1));
}
#[test]
fn multiline_fields_take_enter_and_move_between_lines() {
let mut r = Rig::new("", TextKind::Input, LineType::MultilineNoWrap);
r.typed("abc").key(Edit::Enter, false).typed("de");
assert_eq!(r.text(), "abc\nde");
assert_eq!(r.st.caret, 6);
r.key(Edit::Up, false);
assert_eq!(r.st.caret, 2, "up keeps the column");
r.key(Edit::End, false);
assert_eq!(r.st.caret, 3);
r.key(Edit::Down, false);
assert_eq!(r.st.caret, 6, "down to the shorter line's end");
r.key(Edit::Down, false);
assert_eq!(r.st.caret, 6, "down from the last line goes to the end");
r.key(Edit::Up, false).key(Edit::Up, false);
assert_eq!(r.st.caret, 0, "up from the first line goes to the start");
// Clicking on the second line.
r.click(17.0, 14.0, false);
assert_eq!(r.st.caret, 6, "x 17 on line 2 is nearest the boundary after d");
}
#[test]
fn max_chars_and_passwords() {
let mut r = Rig::new("", TextKind::Input, LineType::Password);
r.field.max_chars = 4;
r.typed("secret");
assert_eq!(r.text(), "secr", "at most max_chars");
let shown = r.field.shown(r.text());
assert_eq!(shown, "****");
// A paste is cut to the room left, and single-line fields drop its line breaks.
let mut r = Rig::new("ab", TextKind::Input, LineType::Single);
r.field.max_chars = 6;
r.key(Edit::End, false);
let (mut ed, _) = r.ed();
let ch = ed.insert("c\nd\nefgh");
r.apply(ch);
assert_eq!(r.text(), "abcdef");
}
#[test]
fn dynamic_fields_select_but_never_change() {
let mut r = Rig::new("read only", TextKind::Dynamic, LineType::Single);
r.typed("x").key(Edit::Backspace, false).key(Edit::Delete, false);
assert_eq!(r.text(), "read only");
assert!(r.st.text.is_none(), "untouched");
r.key(Edit::SelectAll, false);
assert_eq!(r.st.selected(&r.block), "read only");
}
#[test]
fn one_line_fields_scroll_to_keep_the_caret_in_view() {
// The box shows 50 px of text (54 less the gutters): five characters.
let mut r = Rig::new("", TextKind::Input, LineType::Single);
r.typed("abcdefgh");
assert_eq!(r.st.scroll.x, 30.0, "the caret at 80 px shows at the right edge");
r.key(Edit::Home, false);
assert_eq!(r.st.scroll.x, 0.0);
// Multiline: lines wrap and it scrolls down instead (the box shows two 10 px lines).
let mut r = Rig::new("", TextKind::Input, LineType::Multiline);
r.typed("aaaaabbbbbccccc");
assert_eq!(r.st.look.as_ref().map(|l| l.lines.len()), Some(3));
assert_eq!((r.st.scroll.x, r.st.scroll.y), (0.0, 10.0));
}
#[test]
fn script_text_is_capped_and_takes_actionscript_line_ends() {
let f = TextField::new(TextKind::Dynamic);
assert_eq!(fit(&f, "a\rb\r\nc"), "a\nb\nc");
assert_eq!(chars(&fit(&f, &"x".repeat(MAX_FIELD_CHARS + 10))), MAX_FIELD_CHARS as u32);
assert_eq!(slice("héllo", 1, 3), "él");
assert_eq!(slice("héllo", 4, 99), "o");
assert_eq!(byte_at("héllo", 2), 3);
}
+285
View File
@@ -401,6 +401,291 @@ impl Filter {
}
}
/// A number of a filter a motion tween can animate (ADR 0092), in the units the Motion Editor
/// and the Filters panel show: pixels, percent (strength) and degrees.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum FilterParam {
BlurX,
BlurY,
/// Percent (100 = the filter's full strength).
Strength,
/// Degrees, clockwise from the right; not wrapped in keys, so 0 → 720 turns twice.
Angle,
Distance,
/// Adjust Color's four.
Brightness,
Contrast,
Saturation,
Hue,
}
impl FilterParam {
pub const ALL: [FilterParam; 9] = [
FilterParam::BlurX,
FilterParam::BlurY,
FilterParam::Strength,
FilterParam::Angle,
FilterParam::Distance,
FilterParam::Brightness,
FilterParam::Contrast,
FilterParam::Saturation,
FilterParam::Hue,
];
/// The name in files and commands (`blur_x`, `strength`…), as the filter's own field.
pub fn key(self) -> &'static str {
match self {
FilterParam::BlurX => "blur_x",
FilterParam::BlurY => "blur_y",
FilterParam::Strength => "strength",
FilterParam::Angle => "angle",
FilterParam::Distance => "distance",
FilterParam::Brightness => "brightness",
FilterParam::Contrast => "contrast",
FilterParam::Saturation => "saturation",
FilterParam::Hue => "hue",
}
}
pub fn from_key(s: &str) -> Option<FilterParam> {
let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_");
let s = match s.as_str() {
"blurx" => "blur_x",
"blury" => "blur_y",
other => other,
};
FilterParam::ALL.into_iter().find(|p| p.key() == s)
}
pub fn label(self) -> &'static str {
match self {
FilterParam::BlurX => "Blur X",
FilterParam::BlurY => "Blur Y",
FilterParam::Strength => "Strength",
FilterParam::Angle => "Angle",
FilterParam::Distance => "Distance",
FilterParam::Brightness => "Brightness",
FilterParam::Contrast => "Contrast",
FilterParam::Saturation => "Saturation",
FilterParam::Hue => "Hue",
}
}
pub fn unit(self) -> &'static str {
match self {
FilterParam::BlurX | FilterParam::BlurY | FilterParam::Distance => "px",
FilterParam::Strength => "%",
FilterParam::Angle | FilterParam::Hue => "°",
FilterParam::Brightness | FilterParam::Contrast | FilterParam::Saturation => "",
}
}
/// Values a key may hold (the filter itself then brings the value into its own range).
pub fn range(self) -> std::ops::RangeInclusive<f32> {
match self {
FilterParam::BlurX | FilterParam::BlurY => 0.0..=MAX_BLUR,
FilterParam::Strength => 0.0..=1000.0,
FilterParam::Angle => -100_000.0..=100_000.0,
FilterParam::Distance => -1000.0..=1000.0,
FilterParam::Brightness | FilterParam::Contrast | FilterParam::Saturation => -100.0..=100.0,
FilterParam::Hue => -180.0..=180.0,
}
}
fn index(self) -> usize {
FilterParam::ALL.iter().position(|p| *p == self).unwrap_or(0)
}
}
/// How many [`FilterParam`]s there are.
pub const FILTER_PARAMS: usize = 9;
impl Filter {
/// The numbers of this filter a motion tween can animate, in the Filters panel's order.
pub fn params(&self) -> &'static [FilterParam] {
use FilterParam::*;
match self {
Filter::Blur { .. } => &[BlurX, BlurY],
Filter::Glow { .. } => &[BlurX, BlurY, Strength],
Filter::DropShadow { .. } | Filter::Bevel { .. } | Filter::GradientGlow { .. } | Filter::GradientBevel { .. } => &[BlurX, BlurY, Strength, Angle, Distance],
Filter::AdjustColor { .. } => &[Brightness, Contrast, Saturation, Hue],
}
}
/// The filter's value of `p` in the Motion Editor's units; `None` when it has no such number.
pub fn param(&self, p: FilterParam) -> Option<f32> {
if !self.params().contains(&p) {
return None;
}
let mut out = None;
self.visit(p, |v, scale| out = Some(*v * scale));
out
}
/// Sets `p` to `v` (Motion Editor units, brought into the filter's range when drawn); false
/// when the filter has no such number.
pub fn set_param(&mut self, p: FilterParam, v: f32) -> bool {
if !self.params().contains(&p) || !v.is_finite() {
return false;
}
let mut done = false;
self.visit_mut(p, |x, scale| {
*x = v / scale;
done = true;
});
done
}
/// The field holding `p` and the factor to the Motion Editor's units (strength in percent).
fn visit(&self, p: FilterParam, f: impl FnOnce(&f32, f32)) {
let mut c = self.clone();
c.visit_mut(p, |x, s| f(x, s));
}
fn visit_mut(&mut self, p: FilterParam, f: impl FnOnce(&mut f32, f32)) {
use FilterParam as P;
let field: Option<(&mut f32, f32)> = match (self, p) {
(Filter::Blur { blur_x, .. }, P::BlurX) => Some((blur_x, 1.0)),
(Filter::Blur { blur_y, .. }, P::BlurY) => Some((blur_y, 1.0)),
(Filter::DropShadow { blur_x, .. } | Filter::Glow { blur_x, .. } | Filter::Bevel { blur_x, .. } | Filter::GradientGlow { blur_x, .. } | Filter::GradientBevel { blur_x, .. }, P::BlurX) => Some((blur_x, 1.0)),
(Filter::DropShadow { blur_y, .. } | Filter::Glow { blur_y, .. } | Filter::Bevel { blur_y, .. } | Filter::GradientGlow { blur_y, .. } | Filter::GradientBevel { blur_y, .. }, P::BlurY) => Some((blur_y, 1.0)),
(Filter::DropShadow { strength, .. } | Filter::Glow { strength, .. } | Filter::Bevel { strength, .. } | Filter::GradientGlow { strength, .. } | Filter::GradientBevel { strength, .. }, P::Strength) => Some((strength, 100.0)),
(Filter::DropShadow { angle, .. } | Filter::Bevel { angle, .. } | Filter::GradientGlow { angle, .. } | Filter::GradientBevel { angle, .. }, P::Angle) => Some((angle, 1.0)),
(Filter::DropShadow { distance, .. } | Filter::Bevel { distance, .. } | Filter::GradientGlow { distance, .. } | Filter::GradientBevel { distance, .. }, P::Distance) => Some((distance, 1.0)),
(Filter::AdjustColor { brightness, .. }, P::Brightness) => Some((brightness, 1.0)),
(Filter::AdjustColor { contrast, .. }, P::Contrast) => Some((contrast, 1.0)),
(Filter::AdjustColor { saturation, .. }, P::Saturation) => Some((saturation, 1.0)),
(Filter::AdjustColor { hue, .. }, P::Hue) => Some((hue, 1.0)),
_ => None,
};
if let Some((x, s)) = field {
f(x, s);
}
}
}
/// A filter's number addressed in an instance's list (ADR 0092): the filter's place (0 is the
/// first, applied first) and the number.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FilterProp {
pub slot: u8,
pub param: FilterParam,
}
/// Most filter slots a motion tween addresses (an instance holds at most 16 filters).
pub const MAX_FILTER_SLOTS: u8 = 16;
impl FilterProp {
/// Its place among the filter properties: by slot, then in [`FilterParam::ALL`] order.
pub fn index(self) -> usize {
usize::from(self.slot) * FILTER_PARAMS + self.param.index()
}
}
fn yes() -> bool {
true
}
fn is_on(b: &bool) -> bool {
*b
}
/// One filter in an instance's list (ADR 0091): the filter and whether it is on. A filter
/// switched off keeps its settings and its place but draws nothing: [`active`] leaves it out,
/// so every renderer and export sees exactly the list without it. In files it is the filter's
/// own object with `"enabled": false` added (left out when on), so files from before open as
/// they were.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FilterEntry {
#[serde(flatten)]
pub filter: Filter,
#[serde(default = "yes", skip_serializing_if = "is_on")]
pub enabled: bool,
}
impl From<Filter> for FilterEntry {
fn from(filter: Filter) -> FilterEntry {
FilterEntry { filter, enabled: true }
}
}
impl FilterEntry {
/// The same entry with its filter in range.
pub fn sanitized(&self) -> FilterEntry {
FilterEntry { filter: self.filter.sanitized(), enabled: self.enabled }
}
}
/// The filters that draw, in order and in range: the ones switched on.
pub fn active(list: &[FilterEntry]) -> Vec<Filter> {
list.iter().filter(|e| e.enabled).map(|e| e.filter.sanitized()).collect()
}
/// Whether any filter in the list draws.
pub fn any_active(list: &[FilterEntry]) -> bool {
list.iter().any(|e| e.enabled)
}
/// Whether two lists pair up for a tween: the same kinds in the same order (Animate's rule;
/// switched-off filters count, so switching one off never breaks a tween).
pub fn pairs_up(a: &[FilterEntry], b: &[FilterEntry]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| std::mem::discriminant(&x.filter) == std::mem::discriminant(&y.filter))
}
/// The classic tween between two filter lists (ADR 0081, 0091): when both have the same kinds
/// in the same order, each filter's numbers and colours travel (switches such as Inner and
/// Knockout, the quality, and whether the filter is on stay the first keyframe's; ramps travel
/// stop by stop when they have as many stops). `None` when the lists are equal or don't pair
/// up: the first list holds.
pub fn lerp_filters(a: &[FilterEntry], b: &[FilterEntry], t: f32) -> Option<Vec<FilterEntry>> {
if a == b || !pairs_up(a, b) {
return None;
}
a.iter().zip(b).map(|(x, y)| Some(FilterEntry { filter: x.filter.lerp(&y.filter, t)?, enabled: x.enabled })).collect()
}
fn ramp_lerp(a: &[GradientStop], b: &[GradientStop], t: f32) -> Vec<GradientStop> {
if a.len() != b.len() {
return a.to_vec();
}
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()
}
impl Filter {
/// This filter part way to `o` (see [`lerp_filters`]); `None` when `o` is another kind.
pub fn lerp(&self, o: &Filter, t: f32) -> Option<Filter> {
use anicraft_geom::lerp as l;
Some(match (self, o) {
(Filter::Blur { blur_x, blur_y, quality }, Filter::Blur { blur_x: bx, blur_y: by, .. }) => Filter::Blur { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), quality: *quality },
(Filter::DropShadow { blur_x, blur_y, strength, quality, angle, distance, color, inner, knockout, hide_object }, Filter::DropShadow { blur_x: bx, blur_y: by, strength: s, angle: an, distance: d, color: c, .. }) => {
Filter::DropShadow { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), strength: l(*strength, *s, t), quality: *quality, angle: l(*angle, *an, t), distance: l(*distance, *d, t), color: color.lerp(*c, t), inner: *inner, knockout: *knockout, hide_object: *hide_object }
}
(Filter::Glow { blur_x, blur_y, strength, quality, color, inner, knockout }, Filter::Glow { blur_x: bx, blur_y: by, strength: s, color: c, .. }) => {
Filter::Glow { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), strength: l(*strength, *s, t), quality: *quality, color: color.lerp(*c, t), inner: *inner, knockout: *knockout }
}
(Filter::Bevel { blur_x, blur_y, strength, quality, angle, distance, shadow_color, highlight_color, side, knockout }, Filter::Bevel { blur_x: bx, blur_y: by, strength: s, angle: an, distance: d, shadow_color: sc, highlight_color: hc, .. }) => Filter::Bevel {
blur_x: l(*blur_x, *bx, t),
blur_y: l(*blur_y, *by, t),
strength: l(*strength, *s, t),
quality: *quality,
angle: l(*angle, *an, t),
distance: l(*distance, *d, t),
shadow_color: shadow_color.lerp(*sc, t),
highlight_color: highlight_color.lerp(*hc, t),
side: *side,
knockout: *knockout,
},
(Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout }, Filter::GradientGlow { blur_x: bx, blur_y: by, strength: s, angle: an, distance: d, stops: st, .. }) => {
Filter::GradientGlow { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), strength: l(*strength, *s, t), quality: *quality, angle: l(*angle, *an, t), distance: l(*distance, *d, t), stops: ramp_lerp(stops, st, t), side: *side, knockout: *knockout }
}
(Filter::GradientBevel { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout }, Filter::GradientBevel { blur_x: bx, blur_y: by, strength: s, angle: an, distance: d, stops: st, .. }) => {
Filter::GradientBevel { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), strength: l(*strength, *s, t), quality: *quality, angle: l(*angle, *an, t), distance: l(*distance, *d, t), stops: ramp_lerp(stops, st, t), side: *side, knockout: *knockout }
}
(Filter::AdjustColor { brightness, contrast, saturation, hue }, Filter::AdjustColor { brightness: b, contrast: c, saturation: s, hue: h }) => Filter::AdjustColor { brightness: l(*brightness, *b, t), contrast: l(*contrast, *c, t), saturation: l(*saturation, *s, t), hue: l(*hue, *h, t) },
_ => return None,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
+131
View File
@@ -0,0 +1,131 @@
//! Gradient options, fill frames and fitting (ADR 0074).
use super::*;
fn stops() -> Vec<GradientStop> {
vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }]
}
fn near(a: &Affine, b: &Affine) -> bool {
a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() <= 1e-4 * x.abs().max(y.abs()).max(1.0))
}
#[test]
fn spread_maps_positions_onto_the_ramp() {
for (t, pad, reflect, repeat) in [(-0.25, 0.0, 0.25, 0.75), (0.0, 0.0, 0.0, 0.0), (0.4, 0.4, 0.4, 0.4), (1.25, 1.0, 0.75, 0.25), (2.5, 1.0, 0.5, 0.5), (-1.5, 0.0, 0.5, 0.5)] {
assert!((Spread::Pad.apply(t) - pad).abs() < 1e-6, "pad {t}");
assert!((Spread::Reflect.apply(t) - reflect).abs() < 1e-6, "reflect {t}");
assert!((Spread::Repeat.apply(t) - repeat).abs() < 1e-6, "repeat {t}");
}
for s in Spread::ALL {
assert_eq!(s.apply(f32::NAN), 0.0);
assert!((0.0..=1.0).contains(&s.apply(f32::INFINITY)));
assert_eq!(Spread::from_key(s.key()), Some(s));
}
assert_eq!(Spread::from_key("pad"), Some(Spread::Pad));
assert_eq!(Spread::from_key("mirror"), None);
}
#[test]
fn frames_round_trip_for_every_fill_kind() {
// Linear: x from start to end, y square to it at the same length.
let lin = Paint::linear(Vec2::new(10.0, 20.0), Vec2::new(30.0, 20.0), stops());
let f = lin.frame(None).unwrap();
assert!(near(&f, &Affine { m: [10.0, 0.0, 0.0, 10.0, 20.0, 20.0] }), "{f:?}");
assert_eq!(lin.with_frame(&f, None), lin);
// Radial: a circle stays a plain circle, with no matrix.
let rad = Paint::radial(Vec2::new(5.0, 6.0), 4.0, stops());
let f = rad.frame(None).unwrap();
assert!(near(&f, &Affine { m: [4.0, 0.0, 0.0, 4.0, 5.0, 6.0] }));
assert_eq!(rad.with_frame(&f, None), rad);
// A turned ellipse keeps its centre and its x axis's length as the radius.
let ell = Affine::translate(50.0, 40.0).mul(&Affine::rotate(0.5)).mul(&Affine::scale(30.0, 10.0));
let p = rad.with_frame(&ell, None);
match &p {
Paint::Radial { center, radius, matrix, .. } => {
assert!(center.distance(Vec2::new(50.0, 40.0)) < 1e-4);
assert!((radius - 30.0).abs() < 1e-4);
assert!(near(&matrix.mul(&Affine::translate(center.x, center.y)), &Affine::translate(center.x, center.y).mul(&Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] })), "the matrix turns about the centre");
}
other => panic!("{other:?}"),
}
assert!(near(&p.frame(None).unwrap(), &ell));
// Bitmap: the box onto one copy of the image.
let bmp = Paint::Bitmap { bitmap: BitmapId(1), repeat: true, matrix: Affine::translate(3.0, 4.0).mul(&Affine::scale(2.0, 2.0)) };
let f = bmp.frame(Some((10.0, 6.0))).unwrap();
assert!(f.apply(Vec2::new(-1.0, -1.0)).distance(Vec2::new(3.0, 4.0)) < 1e-4, "top-left of the image");
assert!(f.apply(Vec2::new(1.0, 1.0)).distance(Vec2::new(23.0, 16.0)) < 1e-4, "bottom-right");
assert_eq!(bmp.frame(None), None, "a bitmap needs its size");
assert!(near(&match bmp.with_frame(&f, Some((10.0, 6.0))) {
Paint::Bitmap { matrix, .. } => matrix,
_ => Affine::IDENTITY,
}, &Affine::translate(3.0, 4.0).mul(&Affine::scale(2.0, 2.0))));
// Solid colours have no frame; a frame that isn't finite changes nothing.
assert_eq!(Paint::Solid(Rgba::WHITE).frame(None), None);
assert_eq!(rad.with_frame(&Affine { m: [f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0] }, None), rad);
}
#[test]
fn radial_gradients_follow_any_transform_exactly() {
// A skew turns the circle into a tilted ellipse: the frame is carried exactly, focal point
// and all.
let mut rad = Paint::radial(Vec2::new(10.0, 0.0), 5.0, stops());
if let Paint::Radial { focal, .. } = &mut rad {
*focal = 0.5;
}
let skew = Affine { m: [1.0, 0.0, 0.7, 2.0, 3.0, -1.0] };
let moved = rad.transformed(&skew);
assert!(near(&moved.frame(None).unwrap(), &skew.mul(&rad.frame(None).unwrap())));
assert!(matches!(moved, Paint::Radial { focal, .. } if focal == 0.5));
// A plain move keeps a plain circle.
assert!(matches!(rad.transformed(&Affine::translate(4.0, 4.0)), Paint::Radial { matrix, .. } if matrix == Affine::IDENTITY));
}
#[test]
fn fitting_places_a_fill_on_the_shape() {
let b = Rect { min: Vec2::new(0.0, 0.0), max: Vec2::new(200.0, 100.0) };
match Paint::linear(Vec2::ZERO, Vec2::new(1.0, 1.0), stops()).fitted(&b) {
Paint::Linear { start, end, .. } => assert_eq!((start, end), (Vec2::new(0.0, 50.0), Vec2::new(200.0, 50.0))),
other => panic!("{other:?}"),
}
match Paint::radial(Vec2::ZERO, 1.0, stops()).fitted(&b) {
Paint::Radial { center, radius, matrix, .. } => assert_eq!((center, radius, matrix), (Vec2::new(100.0, 50.0), 100.0, Affine::IDENTITY)),
other => panic!("{other:?}"),
}
let bmp = Paint::Bitmap { bitmap: BitmapId(2), repeat: false, matrix: Affine::scale(3.0, 3.0) };
assert_eq!(bmp.fitted(&b), Paint::Bitmap { bitmap: BitmapId(2), repeat: true, matrix: Affine::IDENTITY });
// Stops and options stay; an empty box changes nothing.
let mut rep = Paint::linear(Vec2::ZERO, Vec2::new(1.0, 0.0), stops());
if let Paint::Linear { spread, linear_rgb, .. } = &mut rep {
*spread = Spread::Repeat;
*linear_rgb = true;
}
assert!(matches!(rep.fitted(&b), Paint::Linear { spread: Spread::Repeat, linear_rgb: true, .. }));
assert_eq!(rep.fitted(&Rect::EMPTY), rep);
}
#[test]
fn older_files_open_and_plain_gradients_are_stored_as_before() {
let old = r#"{"Radial":{"center":{"x":1.0,"y":2.0},"radius":3.0,"stops":[{"offset":0.0,"color":{"r":0.0,"g":0.0,"b":0.0,"a":1.0}}]}}"#;
let p: Paint = serde_json::from_str(old).unwrap();
assert!(matches!(p, Paint::Radial { spread: Spread::Pad, linear_rgb: false, focal, matrix, .. } if focal == 0.0 && matrix == Affine::IDENTITY));
let back = serde_json::to_string(&p).unwrap();
assert!(!back.contains("spread") && !back.contains("focal") && !back.contains("matrix") && !back.contains("linear_rgb"), "{back}");
// Set options are written, and read back.
let mut q = Paint::linear(Vec2::ZERO, Vec2::new(1.0, 0.0), stops());
if let Paint::Linear { spread, linear_rgb, .. } = &mut q {
*spread = Spread::Reflect;
*linear_rgb = true;
}
let text = serde_json::to_string(&q).unwrap();
assert!(text.contains("\"spread\":\"reflect\"") && text.contains("\"linear_rgb\":true"), "{text}");
assert_eq!(serde_json::from_str::<Paint>(&text).unwrap(), q);
}
#[test]
fn radial_gradients_tween_through_their_frames() {
let a = Paint::radial(Vec2::ZERO, 10.0, stops());
let b = a.with_frame(&Affine::translate(100.0, 0.0).mul(&Affine::scale(30.0, 10.0)), None);
let mid = a.lerp(&b, 0.5);
assert!(near(&mid.frame(None).unwrap(), &Affine { m: [20.0, 0.0, 0.0, 10.0, 50.0, 0.0] }), "{mid:?}");
}
+1 -1
View File
@@ -84,7 +84,7 @@ impl Layer {
/// Whether keyframe `i` starts a shape tween that runs into the next keyframe.
pub fn is_shape_tween(&self, i: usize) -> bool {
let (Some(k), Some(next)) = (self.keyframes.get(i), self.keyframes.get(i + 1)) else { return false };
k.motion.is_none() && k.tween.is_some_and(|t| t.kind == TweenKind::Shape) && next.start == k.end()
k.motion.is_none() && k.tween.as_ref().is_some_and(|t| t.kind == TweenKind::Shape) && next.start == k.end()
}
/// The shape tween whose hints `frame` shows or edits, and which side: a frame inside a
+928 -59
View File
File diff suppressed because it is too large. Load diff
+532
View File
@@ -0,0 +1,532 @@
//! How the Library is organised (ADR 0050): folders, the folder each item is in, names unique
//! within a folder, how often each item is used, and which items nothing reaches.
//!
//! The organisation is kept apart from the items themselves ([`Document::library_tree`]): moving
//! or renaming a folder touches one small table, never a symbol's timeline, and documents from
//! before folders open with every item at the top level.
use crate::{BitmapId, Document, ElementId, ElementKind, LayerId, Paint, SoundId, Symbol, SymbolId, Timeline};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
/// Unique id of a Library folder (from the document's id counter).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct FolderId(pub u64);
/// A symbol, bitmap or sound in the Library.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LibraryItem {
Symbol(SymbolId),
Bitmap(BitmapId),
Sound(SoundId),
}
impl LibraryItem {
/// The id inside, whatever the kind (ids are unique across kinds within a document).
pub fn raw(self) -> u64 {
match self {
LibraryItem::Symbol(i) => i.0,
LibraryItem::Bitmap(i) => i.0,
LibraryItem::Sound(i) => i.0,
}
}
}
/// One row of the Library: an item or a folder.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum LibraryEntry {
Item(LibraryItem),
Folder(FolderId),
}
/// A Library folder. Folders nest; `parent` is `None` at the top level.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LibraryFolder {
pub id: FolderId,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<FolderId>,
}
/// The Library's folders and where each item is.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct LibraryTree {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub folders: Vec<LibraryFolder>,
/// The folder each item is in. An item not listed is at the top level.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty", with = "placed_list")]
pub placed: BTreeMap<LibraryItem, FolderId>,
}
impl LibraryTree {
pub fn is_empty(&self) -> bool {
self.folders.is_empty() && self.placed.is_empty()
}
}
/// `placed` as a list of `{"symbol": 3, "folder": 7}` (JSON object keys must be strings).
mod placed_list {
use super::{FolderId, LibraryItem};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize)]
struct Placed {
#[serde(flatten)]
item: LibraryItem,
folder: FolderId,
}
pub fn serialize<S: Serializer>(m: &BTreeMap<LibraryItem, FolderId>, s: S) -> Result<S::Ok, S::Error> {
s.collect_seq(m.iter().map(|(item, folder)| Placed { item: *item, folder: *folder }))
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<BTreeMap<LibraryItem, FolderId>, D::Error> {
let v: Vec<Placed> = Vec::deserialize(d)?;
Ok(v.into_iter().map(|p| (p.item, p.folder)).collect())
}
}
/// Most folders in a Library.
pub const MAX_FOLDERS: usize = 10_000;
/// Deepest folder nesting (a top-level folder is at depth 1).
pub const MAX_FOLDER_DEPTH: usize = 32;
/// Longest Library name (characters).
pub const MAX_NAME_CHARS: usize = 256;
/// Why a name can't be used for a Library item or folder.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NameError {
Empty,
TooLong,
/// `/` separates folders in a path (`Characters/Ball`).
Slash,
/// The folder already holds an item or folder of that name (case aside).
Taken(String),
}
impl std::fmt::Display for NameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NameError::Empty => write!(f, "a Library name can't be empty"),
NameError::TooLong => write!(f, "a Library name is at most {MAX_NAME_CHARS} characters"),
NameError::Slash => write!(f, "a Library name can't contain “/” (it separates folders)"),
NameError::Taken(n) => write!(f, "this folder already has an item named “{n}”"),
}
}
}
/// Library names compare without case, as in Animate.
fn same_name(a: &str, b: &str) -> bool {
a == b || a.to_lowercase() == b.to_lowercase()
}
/// A name trimmed and checked for the Library's rules (not for clashes).
pub fn clean_name(name: &str) -> Result<String, NameError> {
let n = name.trim();
if n.is_empty() {
return Err(NameError::Empty);
}
if n.chars().count() > MAX_NAME_CHARS {
return Err(NameError::TooLong);
}
if n.contains('/') {
return Err(NameError::Slash);
}
Ok(n.to_string())
}
impl Document {
/// Every item in the Library: symbols, then bitmaps, then sounds.
pub fn library_items(&self) -> impl Iterator<Item = LibraryItem> + '_ {
self.library
.iter()
.map(|s| LibraryItem::Symbol(s.id))
.chain(self.bitmaps.iter().map(|b| LibraryItem::Bitmap(b.id)))
.chain(self.sounds.iter().map(|s| LibraryItem::Sound(s.id)))
}
pub fn has_item(&self, item: LibraryItem) -> bool {
self.item_name(item).is_some()
}
pub fn item_name(&self, item: LibraryItem) -> Option<&str> {
match item {
LibraryItem::Symbol(id) => self.symbol(id).map(|s| s.name.as_str()),
LibraryItem::Bitmap(id) => self.bitmap(id).map(|b| b.name.as_str()),
LibraryItem::Sound(id) => self.sound(id).map(|s| s.name.as_str()),
}
}
pub fn folder(&self, id: FolderId) -> Option<&LibraryFolder> {
self.library_tree.folders.iter().find(|f| f.id == id)
}
pub fn has_entry(&self, e: LibraryEntry) -> bool {
match e {
LibraryEntry::Item(i) => self.has_item(i),
LibraryEntry::Folder(f) => self.folder(f).is_some(),
}
}
pub fn entry_name(&self, e: LibraryEntry) -> Option<&str> {
match e {
LibraryEntry::Item(i) => self.item_name(i),
LibraryEntry::Folder(f) => self.folder(f).map(|f| f.name.as_str()),
}
}
/// The folder `e` is in (`None`: the top level).
pub fn parent_of(&self, e: LibraryEntry) -> Option<FolderId> {
match e {
LibraryEntry::Item(i) => self.library_tree.placed.get(&i).copied(),
LibraryEntry::Folder(f) => self.folder(f).and_then(|f| f.parent),
}
}
/// The folders from the top level down to `id` (inclusive). Bounded, so a damaged tree can't
/// loop.
pub fn folder_chain(&self, id: FolderId) -> Vec<FolderId> {
let mut out = Vec::new();
let mut at = Some(id);
while let Some(f) = at.and_then(|i| self.folder(i)) {
if out.len() >= MAX_FOLDER_DEPTH || out.contains(&f.id) {
break;
}
out.push(f.id);
at = f.parent;
}
out.reverse();
out
}
/// `e`'s place as a path, `Characters/Hero/Ball` (`/` joins folder names).
pub fn entry_path(&self, e: LibraryEntry) -> String {
let mut parts: Vec<&str> = self.parent_of(e).map(|p| self.folder_chain(p)).unwrap_or_default().into_iter().filter_map(|f| self.folder(f).map(|x| x.name.as_str())).collect();
parts.push(self.entry_name(e).unwrap_or(""));
parts.join("/")
}
/// Whether `inner` is `outer` or inside it, at any depth.
pub fn folder_within(&self, inner: FolderId, outer: FolderId) -> bool {
self.folder_chain(inner).contains(&outer)
}
/// The folders and items directly in `parent` (`None`: the top level), folders first.
pub fn library_children(&self, parent: Option<FolderId>) -> Vec<LibraryEntry> {
let folders = self.library_tree.folders.iter().filter(|f| f.parent == parent).map(|f| LibraryEntry::Folder(f.id));
let items = self.library_items().filter(|i| self.library_tree.placed.get(i).copied() == parent).map(LibraryEntry::Item);
folders.chain(items).collect()
}
/// Everything inside folder `id` at any depth (not the folder itself): folders, then items.
pub fn folder_contents(&self, id: FolderId) -> Vec<LibraryEntry> {
let inside: Vec<FolderId> = self.library_tree.folders.iter().filter(|f| f.id != id && self.folder_within(f.id, id)).map(|f| f.id).collect();
let mut all = inside.clone();
all.push(id);
let items = self.library_items().filter(|i| self.library_tree.placed.get(i).is_some_and(|f| all.contains(f)));
inside.into_iter().map(LibraryEntry::Folder).chain(items.map(LibraryEntry::Item)).collect()
}
/// How deep folder `id` is (1 at the top level).
pub fn folder_depth(&self, id: FolderId) -> usize {
self.folder_chain(id).len()
}
/// How many folder levels `id` holds, itself included (1 for a folder without subfolders).
pub fn folder_height(&self, id: FolderId) -> usize {
let base = self.folder_depth(id);
self.library_tree.folders.iter().filter(|f| self.folder_within(f.id, id)).map(|f| self.folder_depth(f.id) + 1 - base).max().unwrap_or(1)
}
/// Whether folder `parent` already holds something named `name` (case aside), other than
/// `except`.
pub fn name_taken(&self, parent: Option<FolderId>, name: &str, except: Option<LibraryEntry>) -> bool {
self.library_children(parent).into_iter().filter(|e| Some(*e) != except).any(|e| self.entry_name(e).is_some_and(|n| same_name(n, name)))
}
/// `name` checked for the Library's rules and for a clash in `parent`.
pub fn check_name(&self, parent: Option<FolderId>, name: &str, except: Option<LibraryEntry>) -> Result<String, NameError> {
let n = clean_name(name)?;
if self.name_taken(parent, &n, except) {
return Err(NameError::Taken(n));
}
Ok(n)
}
/// `wanted`, or `wanted 2`, `wanted 3`, … whichever `parent` doesn't hold yet.
pub fn unique_name(&self, parent: Option<FolderId>, wanted: &str) -> String {
let base: String = wanted.trim().replace('/', "-").chars().take(MAX_NAME_CHARS - 8).collect();
let base = if base.is_empty() { "Item".to_string() } else { base };
if !self.name_taken(parent, &base, None) {
return base;
}
let siblings = self.library_children(parent).len() + 2;
(2..=siblings).map(|n| format!("{base} {n}")).find(|c| !self.name_taken(parent, c, None)).unwrap_or(base)
}
/// `stem 1`, `stem 2`, … the first that `parent` doesn't hold, counting from `start`.
pub fn numbered_name(&self, parent: Option<FolderId>, stem: &str, start: usize) -> String {
let end = start + self.library_children(parent).len() + 1;
(start.max(1)..=end).map(|n| format!("{stem} {n}")).find(|c| !self.name_taken(parent, c, None)).unwrap_or_else(|| format!("{stem} {end}"))
}
/// Moves `e` into folder `to` (`None`: the top level). No checks: see `library.move`.
pub fn place_entry(&mut self, e: LibraryEntry, to: Option<FolderId>) {
let tree = Arc::make_mut(&mut self.library_tree);
match e {
LibraryEntry::Item(i) => match to {
Some(f) => {
tree.placed.insert(i, f);
}
None => {
tree.placed.remove(&i);
}
},
LibraryEntry::Folder(id) => {
if let Some(f) = tree.folders.iter_mut().find(|f| f.id == id) {
f.parent = to;
}
}
}
}
/// The folder at `path` (`Characters/Hero`), made where missing. `None` for an empty path,
/// or when the Library can't hold more folders or nesting.
pub fn ensure_folder_path(&mut self, path: &str) -> Option<FolderId> {
let mut parent: Option<FolderId> = None;
for (depth, part) in path.split('/').map(str::trim).filter(|p| !p.is_empty()).enumerate() {
if depth >= MAX_FOLDER_DEPTH {
break;
}
let part: String = part.chars().take(MAX_NAME_CHARS).collect();
let found = self.library_tree.folders.iter().find(|f| f.parent == parent && same_name(&f.name, &part)).map(|f| f.id);
parent = Some(match found {
Some(id) => id,
None => {
if self.library_tree.folders.len() >= MAX_FOLDERS {
return parent;
}
let id = FolderId(self.alloc_id());
Arc::make_mut(&mut self.library_tree).folders.push(LibraryFolder { id, name: part, parent });
id
}
});
}
parent
}
/// How many times each item is used: symbol instances, shapes filled with a bitmap and
/// keyframes playing a sound, counted once per keyframe on every timeline (scenes and
/// symbols). Items used nowhere are left out.
pub fn library_uses(&self) -> HashMap<LibraryItem, usize> {
let mut uses: HashMap<LibraryItem, usize> = HashMap::new();
// (Groups' timelines are walked by `visit_refs` itself.)
for tl in self.scenes.iter().map(|s| &s.timeline).chain(self.library.iter().map(|s| &s.timeline)) {
visit_refs(tl, |item| *uses.entry(item).or_default() += 1);
}
uses
}
/// The items nothing in the movie reaches: not placed in any scene, nor inside a symbol
/// that is (at any depth). Symbols with a linkage class count as reached, since scripts
/// can make them by name. In Library order.
pub fn unused_items(&self) -> Vec<LibraryItem> {
let mut reached: HashSet<LibraryItem> = HashSet::new();
let mut stack: Vec<SymbolId> = self.library.iter().filter(|s| s.linkage.is_some()).map(|s| s.id).collect();
for s in &stack {
reached.insert(LibraryItem::Symbol(*s));
}
let reach = |item: LibraryItem, reached: &mut HashSet<LibraryItem>, stack: &mut Vec<SymbolId>| {
if reached.insert(item)
&& let LibraryItem::Symbol(id) = item
{
stack.push(id);
}
};
for scene in &self.scenes {
visit_refs(&scene.timeline, |item| reach(item, &mut reached, &mut stack));
}
// Each symbol is walked at most once (it enters the stack when first reached).
while let Some(id) = stack.pop() {
if let Some(sym) = self.symbol(id) {
visit_refs(&sym.timeline, |item| reach(item, &mut reached, &mut stack));
}
}
self.library_items().filter(|i| !reached.contains(i)).collect()
}
/// Whether symbol `outer` is `inner` or holds an instance of it at any depth (so placing
/// `inner` inside `outer` would make a symbol contain itself).
pub fn symbol_contains(&self, outer: SymbolId, inner: SymbolId) -> bool {
let mut seen: HashSet<SymbolId> = HashSet::new();
let mut stack = vec![outer];
while let Some(id) = stack.pop() {
if id == inner {
return true;
}
if !seen.insert(id) {
continue;
}
if let Some(sym) = self.symbol(id) {
visit_refs(&sym.timeline, |item| {
if let LibraryItem::Symbol(s) = item {
stack.push(s);
}
});
}
}
false
}
/// A copy of symbol `id` named `name`, with fresh layer and element ids, in the same
/// folder, right after it in the Library. Its linkage class stays with the original (a
/// class names one symbol). The new symbol's id, or `None` if there is no such symbol.
pub fn duplicate_symbol(&mut self, id: SymbolId, name: String) -> Option<SymbolId> {
let at = self.library.iter().position(|s| s.id == id)?;
let src = self.library.get(at)?.clone();
let new_id = SymbolId(self.alloc_id());
let timeline = fresh_ids(&src.timeline, &mut || self.alloc_id());
let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, scale_grid_kept: src.scale_grid_kept, scale_grid: src.scale_grid, timeline };
self.library.insert(at + 1, Arc::new(copy));
if let Some(f) = self.library_tree.placed.get(&LibraryItem::Symbol(id)).copied() {
Arc::make_mut(&mut self.library_tree).placed.insert(LibraryItem::Symbol(new_id), f);
}
Some(new_id)
}
/// Repairs a loaded Library tree: folders with unique ids and usable names, parents that
/// exist, no cycles, nesting within [`MAX_FOLDER_DEPTH`], and only placements of items and
/// folders that exist. Touches the tree only if something needs it.
pub(crate) fn sanitize_library_tree(&mut self, max_id: &mut u64) {
let ok = |d: &Document| {
let t = &d.library_tree;
let mut ids = HashSet::new();
t.folders.len() <= MAX_FOLDERS
&& t.folders.iter().all(|f| ids.insert(f.id) && clean_name(&f.name).as_deref() == Ok(f.name.as_str()) && f.parent.is_none_or(|p| p != f.id && d.folder(p).is_some()))
&& t.folders.iter().all(|f| d.folder_chain(f.id).first().is_some_and(|top| d.folder(*top).is_some_and(|x| x.parent.is_none())))
&& t.placed.iter().all(|(i, f)| d.has_item(*i) && d.folder(*f).is_some())
};
for f in &self.library_tree.folders {
*max_id = (*max_id).max(f.id.0);
}
if ok(self) {
return;
}
let mut tree = (*self.library_tree).clone();
let mut seen = HashSet::new();
tree.folders.retain(|f| seen.insert(f.id));
tree.folders.truncate(MAX_FOLDERS);
for (i, f) in tree.folders.iter_mut().enumerate() {
let name: String = f.name.trim().replace('/', "-").chars().take(MAX_NAME_CHARS).collect();
f.name = if name.is_empty() { format!("Folder {}", i + 1) } else { name };
}
let ids: HashSet<FolderId> = tree.folders.iter().map(|f| f.id).collect();
for f in &mut tree.folders {
if f.parent.is_some_and(|p| p == f.id || !ids.contains(&p)) {
f.parent = None;
}
}
// Cycles and over-deep chains: the first folder found on one goes to the top level.
for i in 0..tree.folders.len() {
let Some(start) = tree.folders.get(i).map(|f| f.id) else { continue };
let mut at = tree.folders.get(i).and_then(|f| f.parent);
let mut steps = 1;
let mut bad = false;
while let Some(p) = at {
steps += 1;
if p == start || steps > MAX_FOLDER_DEPTH {
bad = true;
break;
}
at = tree.folders.iter().find(|f| f.id == p).and_then(|f| f.parent);
}
if bad && let Some(f) = tree.folders.get_mut(i) {
f.parent = None;
}
}
let items: HashSet<LibraryItem> = self.library_items().collect();
tree.placed.retain(|i, f| items.contains(i) && ids.contains(f));
self.library_tree = Arc::new(tree);
}
}
/// Calls `f` once per Library reference on each keyframe of `tl`: symbol instances, bitmap
/// fills and the keyframe's sound, inside groups too (ADR 0073).
pub fn visit_refs(tl: &Timeline, mut f: impl FnMut(LibraryItem)) {
visit_refs_in(tl, &mut f, 0);
}
fn visit_refs_in(tl: &Timeline, f: &mut impl FnMut(LibraryItem), depth: usize) {
if depth > crate::MAX_GROUP_DEPTH {
return;
}
for l in &tl.layers {
for k in &l.keyframes {
for e in &k.elements {
match &e.kind {
ElementKind::Symbol { symbol, .. } => f(LibraryItem::Symbol(*symbol)),
ElementKind::Shape(s) => {
if let Some(Paint::Bitmap { bitmap, .. }) = &s.fill {
f(LibraryItem::Bitmap(*bitmap));
}
}
ElementKind::Group { members } => visit_refs_in(members, f, depth + 1),
ElementKind::Text(_) | ElementKind::Camera => {}
}
}
if let Some(s) = &k.sound {
f(LibraryItem::Sound(s.sound));
}
}
}
}
/// `tl` with new layer and element ids from `alloc`, every reference to them (layer parents,
/// motion tween targets, bone ends) following. An element keeps one id across keyframes, as
/// tweens need.
pub fn fresh_ids(tl: &Timeline, alloc: &mut dyn FnMut() -> u64) -> Timeline {
let mut layers: HashMap<LayerId, LayerId> = HashMap::new();
let mut elements: HashMap<ElementId, ElementId> = HashMap::new();
for l in &tl.layers {
layers.entry(l.id).or_insert_with(|| LayerId(alloc()));
for k in &l.keyframes {
for e in &k.elements {
elements.entry(e.id).or_insert_with(|| ElementId(alloc()));
}
}
}
let el = |id: ElementId| elements.get(&id).copied().unwrap_or(id);
let out = tl
.layers
.iter()
.map(|l| {
let mut l = (**l).clone();
l.id = layers.get(&l.id).copied().unwrap_or(l.id);
l.parent = l.parent.map(|p| layers.get(&p).copied().unwrap_or(p));
if let Some(a) = &mut l.armature {
for b in &mut Arc::make_mut(a).bones {
b.parent = el(b.parent);
b.child = el(b.child);
}
}
for k in &mut l.keyframes {
let k = Arc::make_mut(k);
for e in &mut k.elements {
Arc::make_mut(e).id = el(e.id);
}
if let Some(m) = &mut k.motion {
m.target = el(m.target);
}
}
Arc::new(l)
})
.collect();
Timeline { layers: out }
}
#[cfg(test)]
#[path = "library_tests.rs"]
mod tests;
+195
View File
@@ -0,0 +1,195 @@
use super::*;
use crate::{Element, Layer, Linkage, Symbol, SymbolKind, sample};
fn instance(d: &mut Document, symbol: SymbolId) -> Arc<Element> {
Arc::new(Element {
id: ElementId(d.alloc_id()),
name: String::new(),
transform: Default::default(),
color: Default::default(),
kind: ElementKind::Symbol { symbol, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() },
})
}
/// A symbol named `name` holding instances of `inside`.
fn add_symbol(d: &mut Document, name: &str, inside: &[SymbolId]) -> SymbolId {
let id = SymbolId(d.alloc_id());
let mut layer = Layer::new(LayerId(d.alloc_id()), "Layer 1");
let els: Vec<_> = inside.iter().map(|s| instance(d, *s)).collect();
if let Some(k) = layer.keyframe_mut(0) {
k.elements = els;
}
d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(layer)] } }));
id
}
fn sym(d: &Document, name: &str) -> SymbolId {
d.library.iter().find(|s| s.name == name).map(|s| s.id).unwrap_or(SymbolId(0))
}
#[test]
fn folders_round_trip_and_older_files_open_without_them() {
let mut d = sample::demo();
let plain = serde_json::to_string(&d).unwrap();
assert!(!plain.contains("library_tree"), "a Library without folders writes nothing new");
let back: Document = serde_json::from_str(&plain).unwrap();
assert!(back.library_tree.is_empty());
let chars = d.ensure_folder_path("Characters/Hero").unwrap();
let ball = sym(&d, "Ball");
d.place_entry(LibraryEntry::Item(LibraryItem::Symbol(ball)), Some(chars));
let json = serde_json::to_string(&d).unwrap();
assert!(json.contains(&format!("{{\"symbol\":{},\"folder\":{}}}", ball.0, chars.0)), "{json}");
let mut back: Document = serde_json::from_str(&json).unwrap();
back.sanitize();
assert_eq!(back.library_tree, d.library_tree);
assert_eq!(back.entry_path(LibraryEntry::Item(LibraryItem::Symbol(ball))), "Characters/Hero/Ball");
}
#[test]
fn folder_paths_are_made_once_and_matched_without_case() {
let mut d = Document::default();
let a = d.ensure_folder_path("Characters/Hero").unwrap();
let b = d.ensure_folder_path(" characters / HERO ").unwrap();
assert_eq!(a, b);
assert_eq!(d.library_tree.folders.len(), 2);
assert_eq!(d.folder_depth(a), 2);
assert_eq!(d.ensure_folder_path(""), None);
assert_eq!(d.ensure_folder_path("//"), None);
let top = d.folder_chain(a)[0];
assert_eq!(d.folder_height(top), 2);
assert!(d.folder_within(a, top) && !d.folder_within(top, a));
// Nesting stops at the limit instead of growing without end.
let deep = vec!["x"; MAX_FOLDER_DEPTH + 10].join("/");
let f = d.ensure_folder_path(&deep).unwrap();
assert_eq!(d.folder_depth(f), MAX_FOLDER_DEPTH);
}
#[test]
fn names_are_unique_per_folder_without_case() {
let mut d = sample::demo();
let f = d.ensure_folder_path("Props").unwrap();
let ball = LibraryEntry::Item(LibraryItem::Symbol(sym(&d, "Ball")));
assert_eq!(d.check_name(None, "ball", None), Err(NameError::Taken("ball".into())));
assert_eq!(d.check_name(None, " Ball ", Some(ball)).as_deref(), Ok("Ball"), "an item may keep its own name");
assert_eq!(d.check_name(Some(f), "Ball", None).as_deref(), Ok("Ball"), "another folder may hold the same name");
assert_eq!(d.check_name(None, "a/b", None), Err(NameError::Slash));
assert_eq!(d.check_name(None, " ", None), Err(NameError::Empty));
assert_eq!(d.check_name(None, &"x".repeat(MAX_NAME_CHARS + 1), None), Err(NameError::TooLong));
assert_eq!(d.check_name(None, "props", None), Err(NameError::Taken("props".into())), "folders and items share a folder's names");
assert_eq!(d.unique_name(None, "Ball"), "Ball 2");
assert_eq!(d.unique_name(None, "Ball copy"), "Ball copy");
assert_eq!(d.numbered_name(None, "Symbol", 1), "Symbol 1");
add_symbol(&mut d, "Symbol 1", &[]);
assert_eq!(d.numbered_name(None, "Symbol", 1), "Symbol 2");
}
#[test]
fn damaged_trees_are_repaired_on_load() {
let mut d = sample::demo();
let ball = LibraryItem::Symbol(sym(&d, "Ball"));
let t = Arc::make_mut(&mut d.library_tree);
let f = |id: u64, name: &str, parent: Option<u64>| LibraryFolder { id: FolderId(id), name: name.into(), parent: parent.map(FolderId) };
t.folders = vec![f(900, "A", Some(901)), f(901, "B", Some(900)), f(902, " ", Some(902)), f(903, "C/D", Some(999)), f(900, "Dup", None)];
t.placed.insert(ball, FolderId(901));
t.placed.insert(LibraryItem::Sound(SoundId(12345)), FolderId(900));
t.placed.insert(LibraryItem::Symbol(SymbolId(77777)), FolderId(900));
d.sanitize();
let t = &d.library_tree;
assert_eq!(t.folders.len(), 4, "the duplicate id is dropped");
assert!(t.folders.iter().all(|f| d.folder_chain(f.id).len() <= 2), "the cycle is broken");
assert!(t.folders.iter().all(|f| f.parent != Some(f.id) && f.parent.is_none_or(|p| d.folder(p).is_some())));
assert!(t.folders.iter().all(|f| clean_name(&f.name).is_ok()), "{:?}", t.folders);
assert_eq!(t.placed.len(), 1, "only items that exist stay placed");
assert!(d.next_id > 903, "folder ids stay unique");
// A sane tree is left alone (same Arc).
let before = d.library_tree.clone();
d.sanitize();
assert!(Arc::ptr_eq(&before, &d.library_tree));
}
#[test]
fn uses_count_every_keyframe_and_unused_follows_reachability() {
let mut d = sample::demo();
let (ball, star) = (sym(&d, "Ball"), sym(&d, "Star"));
let uses = d.library_uses();
assert!(uses.get(&LibraryItem::Symbol(ball)).copied().unwrap_or(0) > 0);
assert!(uses.get(&LibraryItem::Symbol(star)).copied().unwrap_or(0) > 0);
assert!(d.unused_items().is_empty(), "the sample uses everything");
// Inner is used only inside Outer, which nothing places: both are unused, though Inner
// has a use.
let inner = add_symbol(&mut d, "Inner", &[]);
let outer = add_symbol(&mut d, "Outer", &[inner, inner]);
assert_eq!(d.library_uses().get(&LibraryItem::Symbol(inner)), Some(&2));
assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(inner), LibraryItem::Symbol(outer)]);
// A linkage class makes a symbol reachable (scripts make it by name), and what it holds.
if let Some(s) = d.library.iter_mut().find(|s| s.id == outer) {
Arc::make_mut(s).linkage = Some(Linkage { class: "Outer".into(), base: String::new() });
}
assert!(d.unused_items().is_empty());
// Cycles terminate.
let a = add_symbol(&mut d, "A", &[]);
let b = add_symbol(&mut d, "B", &[a]);
if let Some(s) = d.library.iter_mut().find(|s| s.id == a) {
let layer = Arc::make_mut(&mut Arc::make_mut(s).timeline.layers[0]);
let e = Arc::new(Element { id: ElementId(5_000_000), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: b, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } });
layer.keyframe_mut(0).unwrap().elements.push(e);
}
assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(a), LibraryItem::Symbol(b)]);
assert!(d.symbol_contains(a, b) && d.symbol_contains(b, a) && d.symbol_contains(a, a));
assert!(!d.symbol_contains(inner, outer) && d.symbol_contains(outer, inner));
}
#[test]
fn a_duplicate_has_fresh_ids_and_keeps_its_folder() {
let mut d = sample::demo();
let star = sym(&d, "Star");
let f = d.ensure_folder_path("FX").unwrap();
d.place_entry(LibraryEntry::Item(LibraryItem::Symbol(star)), Some(f));
if let Some(s) = d.library.iter_mut().find(|s| s.id == star) {
Arc::make_mut(s).linkage = Some(Linkage { class: "Star".into(), base: String::new() });
}
let copy = d.duplicate_symbol(star, "Star copy".into()).unwrap();
let (a, b) = (d.symbol(star).unwrap(), d.symbol(copy).unwrap());
assert_eq!(b.name, "Star copy");
assert_eq!(b.kind, a.kind);
assert!(b.linkage.is_none(), "a class names one symbol");
assert_eq!(d.parent_of(LibraryEntry::Item(LibraryItem::Symbol(copy))), Some(f));
let ids = |s: &Symbol| -> HashSet<u64> { s.timeline.layers.iter().flat_map(|l| std::iter::once(l.id.0).chain(l.keyframes.iter().flat_map(|k| k.elements.iter().map(|e| e.id.0)))).collect() };
assert!(ids(a).is_disjoint(&ids(b)));
assert_eq!(ids(a).len(), ids(b).len());
// Same artwork: only ids differ, and an element keeps one id across its keyframes.
for (la, lb) in a.timeline.layers.iter().zip(&b.timeline.layers) {
assert_eq!(la.keyframes.len(), lb.keyframes.len());
for (ka, kb) in la.keyframes.iter().zip(&lb.keyframes) {
for (ea, eb) in ka.elements.iter().zip(&kb.elements) {
assert_eq!((&ea.kind, ea.transform), (&eb.kind, eb.transform));
}
}
let first: Vec<u64> = lb.keyframes.iter().filter_map(|k| k.elements.first().map(|e| e.id.0)).collect();
if first.len() > 1 && la.keyframes.iter().filter_map(|k| k.elements.first().map(|e| e.id.0)).collect::<HashSet<_>>().len() == 1 {
assert!(first.windows(2).all(|w| w[0] == w[1]));
}
}
let order: Vec<SymbolId> = d.library.iter().map(|s| s.id).collect();
let at = order.iter().position(|s| *s == star).unwrap();
assert_eq!(order[at + 1], copy, "the copy sits right after its original");
assert_eq!(d.duplicate_symbol(SymbolId(424242), "x".into()), None);
}
#[test]
fn folder_contents_reach_every_depth() {
let mut d = sample::demo();
let a = d.ensure_folder_path("A").unwrap();
let ab = d.ensure_folder_path("A/B").unwrap();
let c = d.ensure_folder_path("C").unwrap();
let ball = LibraryItem::Symbol(sym(&d, "Ball"));
d.place_entry(LibraryEntry::Item(ball), Some(ab));
let inside = d.folder_contents(a);
assert_eq!(inside, vec![LibraryEntry::Folder(ab), LibraryEntry::Item(ball)]);
assert!(d.folder_contents(c).is_empty());
assert_eq!(d.library_children(Some(ab)), vec![LibraryEntry::Item(ball)]);
assert!(d.library_children(None).starts_with(&[LibraryEntry::Folder(a), LibraryEntry::Folder(c)]));
assert!(!d.library_children(None).contains(&LibraryEntry::Item(ball)));
}
+1101 -74
View File
File diff suppressed because it is too large. Load diff
+411
View File
@@ -0,0 +1,411 @@
//! Retiming a motion tween (ADR 0083): moving property keys in time, stretching the tween with
//! its span, and joining two tweens into one. Pure data edits; `evaluate` is untouched.
//!
//! Frames are offsets into the span, as everywhere in a [`MotionTween`].
use super::{MotionTween, Pin, Property, PropertyKey, Props, Track, own_value};
use crate::{Easing, Element};
/// A property key picked for retiming: its property and its frame (offset into the span).
pub type KeyRef = (Property, u32);
/// Values closer than this are the same (the join compares objects' values).
const SAME: f32 = 1e-4;
impl MotionTween {
/// The keys `keys` names that exist, with the X and Y keys of a pinned frame taken together
/// (they are the place of the path point pinned there, ADR 0049): sorted, no repeats.
pub fn retime_selection(&self, keys: &[KeyRef]) -> Vec<KeyRef> {
let pins = self.live_pins();
let mut out: Vec<KeyRef> = Vec::with_capacity(keys.len());
let add = |out: &mut Vec<KeyRef>, k: KeyRef| {
if self.track(k.0).is_some_and(|t| t.key_at(k.1).is_some()) && !out.contains(&k) {
out.push(k);
}
};
for &(p, f) in keys.iter().take(super::MAX_KEYS * 4) {
add(&mut out, (p, f));
if matches!(p, Property::X | Property::Y) && pins.iter().any(|q| q.frame == f) {
add(&mut out, (Property::X, f));
add(&mut out, (Property::Y, f));
}
}
out.sort_by_key(|(p, f)| (p.index(), *f));
out
}
/// How far `by` frames the keys can really go: none before the span's first frame or after
/// `last` (a key already past it stays where it is), and none onto or past a key of its
/// track that isn't moving. The result has `by`'s sign (or is 0) and is never larger.
pub fn retime_limit(&self, keys: &[KeyRef], by: i64, last: u32) -> i64 {
let sel = self.retime_selection(keys);
let (mut lo, mut hi) = (i64::MIN, i64::MAX);
for t in &self.tracks {
let picked = |f: u32| sel.contains(&(t.property, f));
for (i, k) in t.keys.iter().enumerate() {
if !picked(k.frame) {
continue;
}
let f = i64::from(k.frame);
// The neighbours that stay put bound it; moving ones travel with it.
let prev = i.checked_sub(1).and_then(|j| t.keys.get(j)).filter(|q| !picked(q.frame)).map_or(-1, |q| i64::from(q.frame));
let next = t.keys.get(i + 1).filter(|q| !picked(q.frame)).map_or(i64::MAX, |q| i64::from(q.frame));
let top = i64::from(last).max(f);
lo = lo.max(prev + 1 - f);
hi = hi.min(next.saturating_sub(1).min(top) - f);
}
}
if lo > hi {
return 0;
}
by.clamp(lo.min(0), hi.max(0))
}
/// Moves the keys `keys` names by `by` frames, as far as [`MotionTween::retime_limit`]
/// lets them: values and eases travel with their keys, and a pinned path point's pin with
/// its X and Y keys. Returns how far they went and where they are now.
pub fn move_keys(&mut self, keys: &[KeyRef], by: i64, last: u32) -> (i64, Vec<KeyRef>) {
let sel = self.retime_selection(keys);
let by = self.retime_limit(&sel, by, last);
let shift = |f: u32| u32::try_from(i64::from(f) + by).unwrap_or(f);
if by == 0 {
return (0, sel);
}
let pinned: Vec<u32> = self.live_pins().iter().map(|q| q.frame).filter(|f| sel.contains(&(Property::X, *f)) && sel.contains(&(Property::Y, *f))).collect();
for t in &mut self.tracks {
let p = t.property;
for k in &mut t.keys {
if sel.contains(&(p, k.frame)) {
k.frame = shift(k.frame);
}
}
}
for q in &mut self.pins {
if pinned.contains(&q.frame) {
q.frame = shift(q.frame);
}
}
// The limits keep every track in order; a pin whose keys moved apart lets go.
self.pins = self.live_pins();
(by, sel.into_iter().map(|(p, f)| (p, shift(f))).collect())
}
/// Stretches the tween from a span of `from` frames to one of `to`, as dragging the span's
/// end does in Animate: every key (and pinned frame) keeps its place in proportion, the
/// first frame on the first and the last on the last. Keys that would land on one frame are
/// spread onto the frames beside it; only when a track has more keys than the span has
/// frames do keys become one (on the first frame the first key stays, elsewhere the later
/// key's value and ease win). A span of one frame has nothing to stretch.
pub fn stretch(&mut self, from: u32, to: u32) {
let (a, b) = (u64::from(from.saturating_sub(1)), u64::from(to.saturating_sub(1)));
if a == 0 || a == b {
return;
}
let map = |f: u32| i64::try_from((u64::from(f) * b + a / 2) / a).unwrap_or(i64::MAX);
let (old_last, new_last) = (a as u32, b as i64);
// Where each key of the X track goes: the pins follow their frames' keys.
let mut x_moves: Vec<(u32, u32)> = Vec::new();
for t in &mut self.tracks {
let mut at: Vec<i64> = t.keys.iter().map(|k| map(k.frame)).collect();
// Apart going forward, then back inside the span from its last frame.
let mut floor = i64::MIN;
for c in &mut at {
*c = (*c).max(floor);
floor = c.saturating_add(1);
}
let inside = t.keys.iter().filter(|k| k.frame <= old_last).count();
let mut cap = new_last;
for i in (0..inside).rev() {
if let Some(c) = at.get_mut(i) {
*c = (*c).min(cap).max(0);
cap = *c - 1;
}
}
let mut keys: Vec<PropertyKey> = Vec::with_capacity(t.keys.len());
for (k, f) in t.keys.iter().zip(at) {
let frame = u32::try_from(f).unwrap_or(u32::MAX);
if t.property == Property::X {
x_moves.push((k.frame, frame));
}
let k = PropertyKey { frame, ..k.clone() };
match keys.last_mut() {
Some(prev) if prev.frame >= k.frame && prev.frame == 0 => {}
Some(prev) if prev.frame >= k.frame => *prev = PropertyKey { frame: prev.frame, ..k },
_ => keys.push(k),
}
}
t.keys = keys;
}
let mut pins: Vec<Pin> = Vec::with_capacity(self.pins.len());
for q in &self.pins {
let frame = x_moves.iter().find(|(f, _)| *f == q.frame).map_or_else(|| u32::try_from(map(q.frame)).unwrap_or(u32::MAX), |m| m.1);
if pins.last().is_none_or(|p| p.frame < frame) {
pins.push(Pin { frame, ..*q });
}
}
self.pins = pins;
self.pins = self.live_pins();
}
/// This tween over `frames` frames followed by `next` (the next span's, whose object's own
/// values are `next_base`), as one tween over both spans (Join Motion). When `next` is what
/// splitting this one at `frames` gives, the join is exact: this tween comes back, its keys
/// past the first span included. Otherwise each property keeps its values on every frame:
/// this tween's keys before the cut, `next`'s after it, with a key holding the value up to
/// the cut where the two differ. `None` when either has a motion path and they aren't one
/// split tween (joining two paths isn't supported yet).
pub fn join(&self, base: &Element, frames: u32, next: &MotionTween, next_base: &Element) -> Option<MotionTween> {
let pa = Props::of(base);
if frames > 0 && self.split_at(&pa, frames) == *next && self.apply(base, frames as f32) == *next_base {
return Some(self.clone());
}
if self.path.is_some() || next.path.is_some() || frames == 0 {
return None;
}
let last = frames - 1;
let mut tracks = Vec::new();
// Every property, and the filters' numbers both objects have (ADR 0092; a filter only
// one of them has can't be joined, and its track goes).
let mut props: Vec<Property> = Property::ALL.to_vec();
for t in self.tracks.iter().chain(&next.tracks).filter(|t| t.property.is_filter()) {
if !props.contains(&t.property) && own_value(base, t.property).is_some() && own_value(next_base, t.property).is_some() {
props.push(t.property);
}
}
props.sort_by_key(|p| p.index());
for p in props {
let (ta, tb) = (self.track(p), next.track(p));
let (va, vb) = (own_value(base, p).unwrap_or(0.0), own_value(next_base, p).unwrap_or(0.0));
if ta.is_none() && tb.is_none() && (va - vb).abs() <= SAME {
continue;
}
// This span's part: its keys before the cut, and its value on its last frame when
// a segment runs on past it.
let mut keys: Vec<PropertyKey> = match ta {
Some(t) => {
let mut v: Vec<PropertyKey> = t.keys.iter().filter(|k| k.frame < frames).cloned().collect();
let runs_on = t.keys.iter().any(|k| k.frame > last);
if (v.is_empty() || runs_on) && t.key_at(last).is_none() {
let at = if v.is_empty() { 0 } else { last };
let ease = t.segment_at(at).and_then(|i| t.keys.get(i)).map_or(Easing::Linear, |k| k.ease.clone());
v.push(PropertyKey { frame: at, value: t.value_at(at as f32).unwrap_or(va), ease });
}
v
}
None => vec![PropertyKey { frame: 0, value: va, ease: Easing::Linear }],
};
let end = keys.last().map_or(va, |k| k.value);
// The next span's part, after the cut. Its rotation turns on from where this one
// ended (the same look, whole turns added), so the curve doesn't spin back.
let mut after: Vec<PropertyKey> = match tb {
Some(t) => t.keys.iter().map(|k| PropertyKey { frame: k.frame.saturating_add(frames), ..k.clone() }).collect(),
None => vec![PropertyKey { frame: frames, value: vb, ease: Easing::Linear }],
};
if p == Property::Rotation
&& let Some(first) = after.first()
{
let turns = ((end - first.value) / 360.0).round() * 360.0;
for k in &mut after {
k.value = p.clamp(k.value + turns);
}
}
let start = after.first().map_or(end, |k| k.value);
if let Some(k) = keys.last_mut() {
// The step at the cut: hold this span's value to its last frame, then jump.
if (start - end).abs() > SAME {
if k.frame < last {
let hold = PropertyKey { frame: last, value: end, ease: Easing::Linear };
k.ease = Easing::Linear;
keys.push(hold);
} else {
k.ease = Easing::Linear;
}
}
}
keys.extend(after);
keys.truncate(super::MAX_KEYS);
tracks.push(Track { property: p, keys });
}
Some(MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new() })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ColorEffect, ElementId, ElementKind, Shape};
use anicraft_geom::{Affine, Path, Vec2};
fn el(x: f32, y: f32) -> Element {
Element {
id: ElementId(1),
name: String::new(),
transform: Affine::translate(x, y),
color: ColorEffect::default(),
kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), crate::Paint::Solid(crate::Rgba::BLACK))),
}
}
fn tween(tracks: &[(Property, &[(u32, f32)])]) -> MotionTween {
let mut m = MotionTween::new(ElementId(1));
for (p, keys) in tracks {
m.tracks.push(Track { property: *p, keys: keys.iter().map(|&(frame, value)| PropertyKey { frame, value, ease: Easing::Linear }).collect() });
}
m
}
fn frames(m: &MotionTween, p: Property) -> Vec<u32> {
m.track(p).map(|t| t.keys.iter().map(|k| k.frame).collect()).unwrap_or_default()
}
#[test]
fn a_moved_key_keeps_its_value_and_ease() {
let mut m = tween(&[(Property::X, &[(0, 0.0), (10, 100.0), (20, 50.0)])]);
if let Some(k) = m.track_mut(Property::X).and_then(|t| t.keys.get_mut(1)) {
k.ease = Easing::QuadIn;
}
let (by, now) = m.move_keys(&[(Property::X, 10)], 4, 20);
assert_eq!((by, now), (4, vec![(Property::X, 14)]));
let t = m.track(Property::X).expect("track");
let k = t.keys.get(1).expect("key");
assert_eq!((k.frame, k.value, &k.ease), (14, 100.0, &Easing::QuadIn));
assert_eq!(t.value_at(14.0), Some(100.0));
}
#[test]
fn no_key_crosses_or_lands_on_a_neighbour() {
let mut m = tween(&[(Property::X, &[(0, 0.0), (10, 100.0), (20, 50.0)])]);
// Right: up to the frame before the next key. Left: up to the frame after the first.
assert_eq!(m.retime_limit(&[(Property::X, 10)], 50, 30), 9);
assert_eq!(m.retime_limit(&[(Property::X, 10)], -50, 30), -9);
// Never before the first frame, or after the last (the span's 30 frames).
assert_eq!(m.retime_limit(&[(Property::X, 0)], -3, 30), 0);
assert_eq!(m.retime_limit(&[(Property::X, 20)], 40, 25), 5);
// Keys moving together don't bound each other.
assert_eq!(m.retime_limit(&[(Property::X, 10), (Property::X, 20)], 40, 30), 10);
m.move_keys(&[(Property::X, 10)], 1000, 30);
assert_eq!(frames(&m, Property::X), vec![0, 19, 20]);
// Fuzz: every move keeps every track strictly in order and inside the span.
let mut seed = 7u32;
let mut rnd = |n: u32| {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(seed >> 8) % n
};
for _ in 0..500 {
let p = if rnd(2) == 0 { Property::X } else { Property::Y };
let pick: Vec<KeyRef> = (0..rnd(3) + 1).map(|_| (p, rnd(31))).collect();
let by = i64::from(rnd(41)) - 20;
let mut m2 = tween(&[(Property::X, &[(0, 0.0), (5, 1.0), (6, 2.0), (30, 3.0)]), (Property::Y, &[(3, 0.0), (9, 1.0)])]);
m2.move_keys(&pick, by, 30);
for t in &m2.tracks {
assert!(t.keys.windows(2).all(|w| matches!(w, [a, b] if a.frame < b.frame)), "{pick:?} {by}: {:?}", t.keys);
assert!(t.keys.iter().all(|k| k.frame <= 30));
}
assert!(m2.is_sane());
}
}
#[test]
fn keys_across_properties_move_together() {
let mut m = tween(&[(Property::X, &[(0, 0.0), (10, 100.0)]), (Property::Rotation, &[(0, 0.0), (8, 90.0), (12, 180.0)])]);
// The rotation key at 12 stops the X key at 10 going further than 3 frames.
let (by, _) = m.move_keys(&[(Property::X, 10), (Property::Rotation, 8)], 6, 20);
assert_eq!(by, 3);
assert_eq!(frames(&m, Property::X), vec![0, 13]);
assert_eq!(frames(&m, Property::Rotation), vec![0, 11, 12]);
}
#[test]
fn a_pinned_frames_keys_and_pin_move_together() {
let mut m = tween(&[(Property::X, &[(0, 0.0), (10, 50.0), (20, 100.0)]), (Property::Y, &[(0, 0.0), (10, 0.0), (20, 0.0)])]);
let mut path = Path::new();
path.move_to(Vec2::new(0.0, 0.0));
path.cubic_to(Vec2::new(10.0, -20.0), Vec2::new(40.0, -20.0), Vec2::new(50.0, 0.0));
path.cubic_to(Vec2::new(60.0, 20.0), Vec2::new(90.0, 20.0), Vec2::new(100.0, 0.0));
m.path = Some(path);
m.pins = vec![Pin { frame: 10, anchor: 1 }];
assert_eq!(m.live_pins().len(), 1);
// Picking only X still takes Y along: they are the point's place.
let (by, now) = m.move_keys(&[(Property::X, 10)], 3, 20);
assert_eq!(by, 3);
assert_eq!(now, vec![(Property::X, 13), (Property::Y, 13)]);
assert_eq!(m.pins, vec![Pin { frame: 13, anchor: 1 }]);
}
#[test]
fn stretching_scales_keys_in_proportion() {
// 21 frames (0..=20) to 41 (0..=40): every key doubles its offset.
let mut m = tween(&[(Property::X, &[(0, 0.0), (5, 10.0), (10, 20.0), (20, 40.0)])]);
let before = m.clone();
m.stretch(21, 41);
assert_eq!(frames(&m, Property::X), vec![0, 10, 20, 40]);
// Values at the keys are kept, and between them the curve is the same, stretched.
for f in 0..=20 {
let (a, b) = (before.track(Property::X).and_then(|t| t.value_at(f as f32)), m.track(Property::X).and_then(|t| t.value_at(2.0 * f as f32)));
assert_eq!(a, b, "frame {f}");
}
// And back: a round trip.
m.stretch(41, 21);
assert_eq!(m, before);
// Analytic: 0..=30 into 0..=20 rounds f · 20/30 to the nearest frame.
let mut m = tween(&[(Property::X, &[(0, 0.0), (7, 1.0), (15, 2.0), (30, 3.0)])]);
m.stretch(31, 21);
assert_eq!(frames(&m, Property::X), vec![0, 5, 10, 20]);
}
#[test]
fn a_much_shorter_span_merges_keys_into_the_later_one() {
// Spread first: 0, 1, 2, 10 of 0..=10 into 0..=4 land on 0, 0, 0, 4 and go to 0, 1, 2, 4.
let mut m = tween(&[(Property::X, &[(0, 0.0), (1, 5.0), (2, 9.0), (10, 20.0)])]);
let mut spread = m.clone();
spread.stretch(11, 5);
assert_eq!(frames(&spread, Property::X), vec![0, 1, 2, 4]);
// Four keys in three frames: the first stays, the last two win the frames after it.
m.stretch(11, 3);
let t = m.track(Property::X).expect("track");
assert_eq!(t.keys.iter().map(|k| (k.frame, k.value)).collect::<Vec<_>>(), vec![(0, 0.0), (1, 9.0), (2, 20.0)]);
assert!(m.is_sane());
// A one-frame span has nothing to stretch.
let mut one = tween(&[(Property::X, &[(0, 0.0)])]);
one.stretch(1, 30);
assert_eq!(frames(&one, Property::X), vec![0]);
}
#[test]
fn split_then_join_gives_the_tween_back() {
let base = el(0.0, 0.0);
let mut m = tween(&[(Property::X, &[(0, 0.0), (10, 100.0), (20, 0.0)]), (Property::Rotation, &[(0, 0.0), (20, 400.0)])]);
if let Some(k) = m.track_mut(Property::X).and_then(|t| t.keys.first_mut()) {
k.ease = Easing::CubicBezier(0.4, 0.0, 0.2, 1.0);
}
let props = Props::of(&base);
let tail = m.split_at(&props, 6);
let tail_base = m.apply(&base, 6.0);
assert_eq!(m.join(&base, 6, &tail, &tail_base), Some(m.clone()));
}
#[test]
fn joining_two_tweens_keeps_every_frame() {
let a = el(0.0, 0.0);
let ma = tween(&[(Property::X, &[(0, 0.0), (9, 90.0)])]);
// The second span's object starts elsewhere and turns.
let b = el(200.0, 10.0);
let mb = tween(&[(Property::Rotation, &[(0, 0.0), (5, 45.0)])]);
let j = ma.join(&a, 10, &mb, &b).expect("joins");
for f in 0..10 {
let want = ma.apply(&a, f as f32).transform;
let got = j.apply(&a, f as f32).transform;
assert!(want.m.iter().zip(got.m).all(|(w, g)| (w - g).abs() < 1e-3), "frame {f}: {want:?} {got:?}");
}
for f in 0..6 {
let want = mb.apply(&b, f as f32).transform;
let got = j.apply(&a, (10 + f) as f32).transform;
assert!(want.m.iter().zip(got.m).all(|(w, g)| (w - g).abs() < 1e-3), "frame {}: {want:?} {got:?}", 10 + f);
}
assert!(j.is_sane());
// Two motion paths don't join (yet).
let mut pa = ma.clone();
pa.path = Some(Path::rect(0.0, 0.0, 10.0, 10.0));
assert_eq!(pa.join(&a, 10, &mb, &b), None);
}
}
+84
View File
@@ -0,0 +1,84 @@
//! 9-slice scaling of symbol instances (ADR 0055), as part of evaluation.
//!
//! A symbol with a [`ScaleGrid`] is drawn so that scaling an instance keeps the corners outside
//! its guides unscaled: the instance's transform is decomposed (`T · R · Skew · S`), and instead
//! of `S` the symbol's own shapes go through the 9-slice map of its box scaled by `S`
//! ([`anicraft_geom::slice`]); translation, rotation and skew apply after. Strokes keep their
//! width. Nested symbols, text and bitmap fills inside scale normally, as in Animate.
use crate::{Document, ElementKind, LayerKind, ScaleGrid, Symbol};
use anicraft_geom::slice::{Axis, Slice9};
use anicraft_geom::{Affine, Rect};
/// How a sliced instance's shapes are drawn (see the module docs).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Slicing {
/// Symbol space to sliced space.
pub map: Slice9,
/// The instance's transform without its scale: sliced space to the parent's space.
pub post: Affine,
/// The scale left out of `post` (what plain scaling would have applied).
pub scale: Affine,
}
/// Instance scale this close to 1 on both axes draws the symbol as it is.
const UNSCALED: f32 = 1e-4;
/// The box 9-slice scaling divides: the control-point bounds of everything on the symbol's
/// keyframes (guide layers left out), so the box doesn't move as the symbol plays. Strokes don't
/// widen it: they keep their width.
pub fn symbol_box(doc: &Document, sym: &Symbol) -> Rect {
let mut r = Rect::EMPTY;
for layer in sym.timeline.layers.iter().filter(|l| !matches!(l.kind, LayerKind::Guide | LayerKind::Folder | LayerKind::Camera)) {
for k in &layer.keyframes {
for e in &k.elements {
let b = match &e.kind {
ElementKind::Shape(s) => s.path.bounds().transformed(&e.transform),
_ => e.bounds(doc),
};
if b.min.x.is_finite() && b.max.x.is_finite() && b.min.y.is_finite() && b.max.y.is_finite() {
r = r.union(&b);
}
}
}
}
r
}
/// The slicing of an instance of `sym` placed by `transform`, or `None` when it draws normally:
/// no guides, no scale to absorb, or nothing to divide.
pub(crate) fn slicing(doc: &Document, sym: &Symbol, transform: &Affine) -> Option<Slicing> {
let grid = sym.scale_grid.filter(|g| g.check().is_ok())?;
let d = transform.decompose();
let (sx, sy) = (d.sx, d.sy.abs());
if ((sx - 1.0).abs() < UNSCALED && (sy - 1.0).abs() < UNSCALED) || !sx.is_finite() || !sy.is_finite() {
return None;
}
let b = symbol_box(doc, sym);
if b.is_empty() {
return None;
}
map_for(&grid, &b, sx, sy).map(|map| {
// `transform` is T·R·K·S; S = scale(sx, ±sy). Keep a flip in `post` (sliced magnitudes).
let flip = if d.sy < 0.0 { -1.0 } else { 1.0 };
let rest = anicraft_geom::Decomposed { sx: 1.0, sy: flip, ..d }.compose();
Slicing { map, post: rest, scale: Affine::scale(sx, sy) }
})
}
/// Whether an instance of `sym` placed by `transform` is drawn 9-sliced (exporters that place
/// symbols themselves say when they can't).
pub fn slices(doc: &Document, sym: &Symbol, transform: &Affine) -> bool {
slicing(doc, sym, transform).is_some()
}
/// The 9-slice map of box `b` with guides `grid`, scaled by `sx`, `sy` (both at least 0). An
/// axis with no extent (a symbol only a line high) scales plainly.
pub fn map_for(grid: &ScaleGrid, b: &Rect, sx: f32, sy: f32) -> Option<Slice9> {
let axis = |lo: f32, a: f32, c: f32, hi: f32, k: f32| if hi > lo { Axis::new(lo, a, c, hi, k) } else { Axis::new(lo, lo, lo + 1.0, lo + 1.0, k) };
Some(Slice9 { x: axis(b.min.x, grid.left, grid.right, b.max.x, sx)?, y: axis(b.min.y, grid.top, grid.bottom, b.max.y, sy)? })
}
#[cfg(test)]
#[path = "nine_slice_tests.rs"]
mod tests;
+171
View File
@@ -0,0 +1,171 @@
//! 9-slice scaling (ADR 0055), analytically: what evaluation draws for a scaled instance.
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, ScaleGrid, Shape, Symbol, SymbolId, SymbolKind, Timeline, evaluate};
use anicraft_geom::{Affine, Path, Vec2};
use std::sync::Arc;
const SYM: SymbolId = SymbolId(900);
fn el(id: u64, transform: Affine, kind: ElementKind) -> Element {
Element { id: ElementId(id), name: String::new(), transform, color: ColorEffect::default(), kind }
}
fn instance(of: SymbolId, transform: Affine) -> Element {
el(1, transform, ElementKind::Symbol { symbol: of, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() })
}
/// A 100×40 rounded rectangle (corner radius 10) at the symbol's origin, guides 10 in from each
/// edge, with `extra` inside it, and one instance of it on the stage placed by `xf`.
fn doc(xf: Affine, grid: Option<ScaleGrid>, extra: Vec<Element>) -> Document {
let mut d = Document::default();
let mut shape = Shape::filled(Path::rounded_rect(0.0, 0.0, 100.0, 40.0, 10.0), Paint::Solid(Rgba::BLACK));
shape.stroke = Some(crate::Stroke::new(Rgba::WHITE, 2.0));
let mut k = Keyframe::new(0, 1);
k.elements.push(Arc::new(el(2, Affine::IDENTITY, ElementKind::Shape(shape))));
k.elements.extend(extra.into_iter().map(Arc::new));
let mut layer = Layer::new(LayerId(901), "art");
layer.keyframes = vec![Arc::new(k)];
d.library.push(Arc::new(Symbol { id: SYM, name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(layer)] } }));
let mut k = Keyframe::new(0, 1);
k.elements.push(Arc::new(instance(SYM, xf)));
Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k)];
d
}
const GRID: ScaleGrid = ScaleGrid { left: 10.0, right: 90.0, top: 10.0, bottom: 30.0 };
/// The stage-space outline of the first item, finely flattened.
fn outline(d: &Document) -> Vec<Vec2> {
let dl = evaluate(d, 0);
let it = &dl.items[0];
it.path.flatten(&it.transform, 0.005).into_iter().flat_map(|l| l.points).collect()
}
/// How far `p` is from the polyline `pts` (closed).
fn dist(pts: &[Vec2], p: Vec2) -> f32 {
let n = pts.len();
(0..n).map(|i| anicraft_geom::segment_distance(p, pts[i], pts[(i + 1) % n])).fold(f32::INFINITY, f32::min)
}
/// A point on the source corner arc of the rounded rectangle, `a` radians round the corner
/// centred at `c`.
fn arc(c: Vec2, a: f32) -> Vec2 {
c + Vec2::new(a.cos(), a.sin()) * 10.0
}
#[test]
fn a_rounded_rect_scaled_3x_keeps_its_corner_radii_exact() {
let d = doc(Affine::scale(3.0, 3.0), Some(GRID), Vec::new());
let pts = outline(&d);
// The box lands where plain scaling puts it: 0..300 by 0..120.
let (lo, hi) = pts.iter().fold((Vec2::new(f32::MAX, f32::MAX), Vec2::new(f32::MIN, f32::MIN)), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))));
assert!((lo.x).abs() < 1e-3 && (lo.y).abs() < 1e-3 && (hi.x - 300.0).abs() < 1e-3 && (hi.y - 120.0).abs() < 1e-3, "{lo:?} {hi:?}");
// Each corner is the same radius-10 arc, moved to its corner of the bigger box.
let corners = [(Vec2::new(10.0, 10.0), Vec2::ZERO, 180.0f32), (Vec2::new(90.0, 10.0), Vec2::new(200.0, 0.0), 270.0), (Vec2::new(90.0, 30.0), Vec2::new(200.0, 80.0), 0.0), (Vec2::new(10.0, 30.0), Vec2::new(0.0, 80.0), 90.0)];
for (c, shift, from) in corners {
for i in 0..=8 {
let a = (from + i as f32 * 90.0 / 8.0).to_radians();
let want = arc(c, a) + shift;
let d = dist(&pts, want);
assert!(d < 0.02, "corner at {c:?}, {i}/8: {d}");
// And the arc's centre is still 10 from it: the radius is exact, not stretched.
assert!(((want - (c + shift)).length() - 10.0).abs() < 1e-3);
}
}
// Without guides, the same instance is a plain 3× scale (corners radius 30).
let plain = evaluate(&doc(Affine::scale(3.0, 3.0), None, Vec::new()), 0);
assert_eq!(plain.items[0].transform, Affine::scale(3.0, 3.0));
}
#[test]
fn the_centre_scales_by_the_remainder_and_edges_one_way() {
// 2× wide, 1.5× high: 200 × 60. The centre is 200 − 20 = 180 wide (80 → 180) and
// 60 − 20 = 40 high (20 → 40).
let d = doc(Affine::scale(2.0, 1.5), Some(GRID), Vec::new());
let it = &evaluate(&d, 0).items[0];
let map = |p: Vec2| it.transform.apply(p);
let pts = outline(&d);
// The middle of the top edge (50, 0) lands at (100, 0); of the left edge (0, 20) at (0, 30).
assert!(dist(&pts, Vec2::new(100.0, 0.0)) < 1e-3);
assert!(dist(&pts, Vec2::new(0.0, 30.0)) < 1e-3);
// The straight top edge runs from x = 10 to x = 190 (the corners are 10 each).
assert!(dist(&pts, Vec2::new(10.0, 0.0)) < 1e-3 && dist(&pts, Vec2::new(190.0, 0.0)) < 1e-3);
// The stroke keeps its width (no scale is left in the item's transform).
assert_eq!(map(Vec2::new(1.0, 0.0)) - map(Vec2::ZERO), Vec2::new(1.0, 0.0));
assert_eq!(it.stroke.as_ref().map(|s| s.width), Some(2.0));
}
#[test]
fn no_spare_space_clamps_the_corners_and_closes_the_centre() {
// 0.1× wide: 10 across, less than the corners' 20. They share it (5 each) and the centre is
// a line; nothing turns inside out.
let d = doc(Affine::scale(0.1, 1.0), Some(GRID), Vec::new());
let pts = outline(&d);
assert!(pts.iter().all(|p| p.x >= -1e-3 && p.x <= 10.0 + 1e-3), "{pts:?}");
assert!(dist(&pts, Vec2::new(5.0, 0.0)) < 1e-3);
// Exactly no spare space (0.2× → 20 across): corners full size, the centre a line.
let pts = outline(&doc(Affine::scale(0.2, 1.0), Some(GRID), Vec::new()));
assert!(dist(&pts, arc(Vec2::new(10.0, 10.0), 225f32.to_radians())) < 0.02);
assert!(pts.iter().all(|p| p.x <= 20.0 + 1e-3));
// Zero scale: everything on one line, still finite.
let pts = outline(&doc(Affine::scale(0.0, 1.0), Some(GRID), Vec::new()));
assert!(pts.iter().all(|p| p.x.abs() < 1e-3 && p.y.is_finite()));
}
#[test]
fn rotation_skew_and_flips_apply_after_slicing() {
let rot = 30f32.to_radians();
let xf = Affine::translate(400.0, 300.0).mul(&Affine::rotate(rot)).mul(&Affine::scale(3.0, 3.0));
let d = doc(xf, Some(GRID), Vec::new());
let it = &evaluate(&d, 0).items[0];
// The item's transform is the instance's translation and rotation, with no scale.
let expect = Affine::translate(400.0, 300.0).mul(&Affine::rotate(rot));
assert!(it.transform.m.iter().zip(expect.m).all(|(a, b)| (a - b).abs() < 1e-4), "{:?}", it.transform);
// The sliced corner (the top-right arc, moved by 200) turns with the instance.
let pts = outline(&d);
let want = expect.apply(arc(Vec2::new(90.0, 10.0), 315f32.to_radians()) + Vec2::new(200.0, 0.0));
assert!(dist(&pts, want) < 0.02);
// A horizontal flip slices by the magnitude, then mirrors.
let flip = doc(Affine::scale(3.0, -3.0), Some(GRID), Vec::new());
let it = &evaluate(&flip, 0).items[0];
assert!((it.transform.determinant() + 1.0).abs() < 1e-4);
let pts = outline(&flip);
assert!(dist(&pts, Vec2::new(300.0, -120.0)).is_finite() && pts.iter().all(|p| p.y <= 1e-3 && p.y >= -120.0 - 1e-3));
}
#[test]
fn unscaled_instances_and_nested_symbols_draw_as_they_are() {
// At scale 1 nothing is cut: the symbol's own path is drawn, shared.
let d = doc(Affine::translate(5.0, 5.0), Some(GRID), Vec::new());
let dl = evaluate(&d, 0);
let ElementKind::Shape(s) = &d.symbol(SYM).unwrap().timeline.layers[0].keyframes[0].elements[0].kind else { panic!("the panel is a shape") };
let sym_path = s.path.clone();
assert!(Arc::ptr_eq(&dl.items[0].path, &sym_path));
// A nested symbol inside scales normally: its item carries the whole 3× scale.
let mut d = doc(Affine::scale(3.0, 3.0), Some(GRID), vec![instance(SymbolId(950), Affine::translate(50.0, 20.0))]);
let mut k = Keyframe::new(0, 1);
k.elements.push(Arc::new(el(3, Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::WHITE))))));
let mut l = Layer::new(LayerId(951), "dot");
l.keyframes = vec![Arc::new(k)];
d.library.push(Arc::new(Symbol { id: SymbolId(950), name: "Dot".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(l)] } }));
let dl = evaluate(&d, 0);
let dot = dl.items.iter().find(|i| i.path.bounds().width() == 4.0).unwrap();
assert_eq!(dot.transform, Affine::scale(3.0, 3.0).mul(&Affine::translate(50.0, 20.0)));
}
#[test]
fn hostile_guides_and_scales_never_break_evaluation() {
for grid in [
ScaleGrid { left: 90.0, right: 10.0, top: 10.0, bottom: 30.0 },
ScaleGrid { left: f32::NAN, right: 10.0, top: 10.0, bottom: 30.0 },
ScaleGrid { left: -1e9, right: 1e9, top: -5.0, bottom: 500.0 },
ScaleGrid { left: 50.0, right: 50.0, top: 20.0, bottom: 20.0 },
] {
for xf in [Affine::scale(3.0, 3.0), Affine::scale(1e-30, 1e30), Affine::scale(f32::INFINITY, 1.0), Affine { m: [0.0, 0.0, 0.0, 0.0, 1.0, 1.0] }] {
let dl = evaluate(&doc(xf, Some(grid), Vec::new()), 0);
for it in &dl.items {
let _ = it.path.flatten(&it.transform, 0.25);
}
}
}
}
+8 -1
View File
@@ -41,10 +41,17 @@ pub fn build_table(doc: &Document) -> Vec<Arc<Path>> {
for layer in &tl.layers {
for k in &layer.keyframes {
for e in &k.elements {
// A warped shape's outline as drawn (ADR 0079) is written once too.
if let ElementKind::Shape(s) = &e.kind
&& let Some(w) = &s.warp
&& seen.insert(Arc::as_ptr(&w.rest) as usize, ()).is_none()
{
out.push(w.rest.clone());
}
let path = match &e.kind {
ElementKind::Shape(s) => &s.path,
ElementKind::Text(t) => &t.outline,
ElementKind::Symbol { .. } | ElementKind::Camera => continue,
ElementKind::Symbol { .. } | ElementKind::Camera | ElementKind::Group { .. } => continue,
};
if seen.insert(Arc::as_ptr(path) as usize, ()).is_none() {
out.push(path.clone());
+942 -50
View File
File diff suppressed because it is too large. Load diff
+366 -3
View File
@@ -33,7 +33,7 @@ fn layer(id: u64, keys: Vec<Arc<Keyframe>>) -> Arc<Layer> {
}
fn symbol(id: u64, kind: SymbolKind, layers: Vec<Arc<Layer>>) -> Arc<Symbol> {
Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, timeline: Timeline { layers } })
Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers } })
}
fn doc(root: Vec<Arc<Layer>>, library: Vec<Arc<Symbol>>) -> Document {
@@ -342,6 +342,97 @@ fn entered_keyframes_start_their_sounds_in_clips_and_graphics_with_layer_volumes
assert_eq!(started(&start(&m, &mut NoScripts)), vec![(1, 1.0), (3, 0.0)]);
}
// ----- Sounds on button frames (ADR 0057) --------------------------------------------------------
/// [`button_doc`] with a sound on each state frame (ids 10 Up, 11 Over, 12 Down, 13 Hit; Over's
/// a stream), on a layer at half volume, the button on a layer at half volume too.
fn sounding_button() -> Document {
use crate::SoundSync::{Event, Stream};
let mut d = button_doc();
let art = |id| vec![rect(id, 0.0, 0.0, 10.0, 10.0)];
let mut sounds = (*layer(34, vec![with_sound(kf(0, 1, vec![], vec![], ""), 10, Event), with_sound(kf(1, 1, vec![], vec![], ""), 11, Stream), with_sound(kf(2, 1, vec![], vec![], ""), 12, Event), with_sound(kf(3, 1, vec![], vec![], ""), 13, Event)])).clone();
sounds.volume = 0.5;
let states = layer(31, vec![kf(0, 1, art(32), vec![], ""), kf(1, 1, art(32), vec![], ""), kf(2, 1, art(32), vec![], ""), kf(3, 1, vec![rect(33, 0.0, 0.0, 100.0, 100.0)], vec![], "")]);
d.library = vec![symbol(300, SymbolKind::Button, vec![Arc::new(sounds), states])];
Arc::make_mut(&mut d.timeline_mut(0).layers[1]).volume = 0.5;
let tone: Vec<f32> = (0..800).map(|i| (i as f32 * 0.1).sin() * 0.5).collect();
for id in 10..14 {
let data = anicraft_audio::wav::encode(8000, 1, &tone, anicraft_audio::wav::Bits::Float32);
d.sounds.push(Arc::new(crate::Sound::from_data(crate::SoundId(id), format!("s{id}.wav"), data).expect("a WAV")));
}
d
}
#[test]
fn a_button_plays_the_sound_of_the_state_it_enters() {
let d = sounding_button();
let at = |x, y| Vec2::new(x, y);
let s = start(&d, &mut NoScripts);
assert!(s.sounds.is_empty(), "a button on the stage is silent until the pointer comes");
// Over: the Over frame's sound, as an event (a button frame has no span to stream over), at
// the volumes of both layers.
let s = step(&d, &s.state, &[Event::Move(at(150.0, 150.0))], &mut NoScripts);
assert_eq!(started(&s), vec![(11, 0.25)]);
assert_eq!(s.sounds[0].sound.sync, crate::SoundSync::Event);
// Moving about inside it plays nothing more.
let s = step(&d, &s.state, &[Event::Move(at(160.0, 150.0))], &mut NoScripts);
assert!(s.sounds.is_empty());
// Pressed: Down's. Released over it: Hit's (the SWF format's Down → Over sound).
let s = input(&d, &s.state, &[Event::Down(at(160.0, 150.0))], &mut NoScripts);
assert_eq!(started(&s), vec![(12, 0.25)]);
let s = input(&d, &s.state, &[Event::Up(at(160.0, 150.0))], &mut NoScripts);
assert_eq!(started(&s), vec![(13, 0.25)]);
// Left: Up's.
let s = step(&d, &s.state, &[Event::Leave], &mut NoScripts);
assert_eq!(started(&s), vec![(10, 0.25)]);
// Arriving and pressing in one event: Over's, then Down's.
let s = input(&d, &s.state, &[Event::Down(at(150.0, 150.0))], &mut NoScripts);
assert_eq!(started(&s), vec![(11, 0.25), (12, 0.25)]);
// Dragged off while pressed, back on and released off: nothing (no state with a sound).
let s = input(&d, &s.state, &[Event::Move(at(400.0, 400.0)), Event::Move(at(150.0, 150.0)), Event::Move(at(400.0, 400.0)), Event::Up(at(400.0, 400.0))], &mut NoScripts);
assert!(s.sounds.is_empty(), "{:?}", started(&s));
}
#[test]
fn button_sounds_follow_the_frames_a_button_has_and_stay_out_of_the_soundtrack() {
// A two-frame button (Up and Over): pressing it shows Over still, and plays nothing.
let mut d = sounding_button();
let short = Timeline { layers: d.library[0].timeline.layers.iter().map(|l| {
let mut l = (**l).clone();
l.keyframes.truncate(2);
Arc::new(l)
}).collect() };
Arc::make_mut(&mut d.library[0]).timeline = short;
let s = start(&d, &mut NoScripts);
// Its Up frame is its hit area (10 × 10 at 100, 100).
let s = input(&d, &s.state, &[Event::Move(Vec2::new(105.0, 105.0)), Event::Down(Vec2::new(105.0, 105.0))], &mut NoScripts);
assert_eq!(started(&s), vec![(11, 0.25)]);
// The mix and every export leave buttons out: they only sound under the pointer.
assert!(crate::sound::voices(&sounding_button(), 48_000).is_empty());
}
#[test]
fn the_hit_overlay_is_the_area_the_pointer_finds() {
let d = button_doc();
let s = start(&d, &mut NoScripts);
let tint = Rgba::new(1.0, 0.0, 0.0, 1.0);
let dl = hit_overlay(&d, &s.state, tint, 0.4);
// One area: the Hit frame's 100 × 100 square at (100, 100), tinted, in one group at 40 %.
assert_eq!(dl.items.len(), 1);
assert_eq!(dl.groups.first().map(|g| g.alpha), Some(0.4));
let i = &dl.items[0];
assert_eq!((i.color, i.group), (ColorTransform::tint(tint, 1.0), Some(0)));
assert_eq!(i.color.apply(Rgba::new(0.1, 0.6, 0.9, 0.8)), Rgba::new(1.0, 0.0, 0.0, 0.8), "every colour becomes the tint, its alpha kept");
for p in [Vec2::new(101.0, 101.0), Vec2::new(199.0, 150.0), Vec2::new(50.0, 50.0), Vec2::new(201.0, 150.0)] {
assert_eq!(i.path.contains(p, &i.transform, i.fill_rule), hit(&d, &s.state, p).is_some(), "{p:?}");
}
// A hidden button has no area; a movie without buttons none at all.
assert!(hit_overlay(&doc(vec![], vec![]), &PlayerState::default(), tint, 0.4).items.is_empty());
assert_eq!(hit_frame(4), 3);
assert_eq!(hit_frame(3), 0);
assert_eq!(hit_frame(0), 0);
}
// ----- ActionScript (ADR 0013 tier 2) -----------------------------------------------------------
/// `k` with a kept ActionScript 3.0 script in place of its actions.
@@ -353,7 +444,7 @@ fn as3(k: Arc<Keyframe>, src: &str) -> Arc<Keyframe> {
/// The state without the listeners scripts add (hand-made actions use handlers instead).
fn lean(st: &PlayerState) -> PlayerState {
PlayerState { listeners: BTreeMap::new(), ..st.clone() }
PlayerState { listeners: BTreeMap::new(), seq: 0, ..st.clone() }
}
/// Plays both documents through the same pointer events and asserts the same movie: state and
@@ -403,7 +494,7 @@ fn actionscript_and_hand_made_actions_play_the_same_movie() {
#[test]
fn a_script_outside_the_subset_does_not_run_at_all() {
let d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nif (true) { play(); }")])], vec![]);
let d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nswitch (1) { }")])], vec![]);
let s = run(&d, 3);
assert!(s.state.root.playing && s.output.is_empty(), "nothing of it ran: {:?}", s.output);
assert_eq!(s.state.root.frame, 3);
@@ -448,3 +539,275 @@ fn next_scene_in_a_movie_clip_script_stays_in_its_clip() {
assert_eq!(s.state.scene, 0);
assert_eq!(s.output, ["Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"]);
}
// ----- ActionScript small logic (ADR 0052) ---------------------------------------------
/// A one-layer main timeline of `frames` frames with scripts on some of them, and `extra` layers.
fn scripted(frames: u32, scripts: &[(u32, &str)], extra: Vec<Arc<Layer>>, library: Vec<Arc<Symbol>>) -> Document {
let mut keys = Vec::new();
let mut starts: Vec<u32> = scripts.iter().map(|(f, _)| *f).collect();
starts.push(frames);
for (i, (f, src)) in scripts.iter().enumerate() {
let end = starts.get(i + 1).copied().unwrap_or(frames);
keys.push(if src.is_empty() { kf(*f, end - f, vec![], vec![], "") } else { as3(kf(*f, end - f, vec![], vec![], ""), src) });
}
let mut layers = vec![layer(1, keys)];
layers.extend(extra);
doc(layers, library)
}
fn outputs(d: &Document, steps: usize) -> Vec<String> {
let mut s = start(d, &mut NoScripts);
let mut out = s.output.clone();
for _ in 0..steps {
s = step(d, &s.state, &[], &mut NoScripts);
out.extend(s.output.iter().cloned());
}
out
}
#[test]
fn timeline_variables_and_functions_live_across_frames() {
let d = scripted(4, &[(0, "var score:int = 10;\nfunction bump(k:int):int { score += k; return score; }\ntrace(\"start \" + score + \" \" + level);"), (2, "trace(bump(5), bump(1.9), level);\nlevel = \"two\";"), (3, "trace(level);\nvar level:String = \"one\"; trace(level); stop();")], vec![], vec![]);
// `level` is declared on frame 4 but is the timeline's from the start (null until set).
assert_eq!(outputs(&d, 5), ["start 10 null", "15 16 null", "two", "one"]);
let s = run(&d, 5);
assert_eq!(s.state.vars.get(&Vec::new()).and_then(|v| v.get("score")), Some(&Value::Num(16.0)));
// A script that uses a name no frame declares doesn't run at all.
let d = scripted(3, &[(0, "trace(\"one\");"), (1, "trace(\"two\"); trace(nobody);")], vec![], vec![]);
assert_eq!(outputs(&d, 2), ["one"]);
assert_eq!(link_problems(&d, TimelineRef::Root, d.scenes[0].timeline.layers[0].keyframes[1].script.as_ref().and_then(FrameScript::source).unwrap().compiled().as_ref().unwrap())[0].message, "`nobody` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)");
}
#[test]
fn each_movie_clip_instance_keeps_its_own_variables() {
// A two-frame clip counts its loops; two instances count apart, and one that leaves the
// stage and comes back starts again.
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![as3(kf(0, 2, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], ""), "var n:int; n++; trace(name + \" \" + n);")])]);
let a = layer(2, vec![kf(0, 8, vec![inst(3, 100, "a", 0.0, 0.0, vec![])], vec![], "")]);
let b = layer(3, vec![kf(0, 3, vec![inst(4, 100, "b", 50.0, 0.0, vec![])], vec![], ""), kf(3, 2, vec![], vec![], ""), kf(5, 3, vec![inst(5, 100, "b", 50.0, 0.0, vec![])], vec![], "")]);
let d = scripted(8, &[(0, "")], vec![a, b], vec![clip]);
let out = outputs(&d, 6);
assert_eq!(out, ["a 1", "b 1", "a 2", "b 2", "a 3", "b 1", "a 4"], "{out:?}");
}
#[test]
fn enter_frame_listeners_run_every_frame_until_removed() {
let src = "var t:int = 0;\nstop();\naddEventListener(Event.ENTER_FRAME, tick);\nfunction tick(e:Event):void {\n t++;\n trace(\"tick \" + t + \" on \" + currentFrame + \" of \" + totalFrames);\n if (t == 3) { removeEventListener(Event.ENTER_FRAME, tick); gotoAndStop(2); }\n}";
let d = scripted(3, &[(0, src), (1, "trace(\"frame 2 runs after the listener\");")], vec![], vec![]);
assert_eq!(outputs(&d, 5), ["tick 1 on 1 of 3", "tick 2 on 1 of 3", "tick 3 on 1 of 3", "frame 2 runs after the listener"]);
assert!(run(&d, 5).state.listeners.is_empty());
}
#[test]
fn keys_reach_the_stage_listeners_with_their_codes() {
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 1, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "")])]);
let src = "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, down);\nstage.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent):void { trace(\"up \" + e.keyCode); });\nfunction down(e:KeyboardEvent):void {\n if (e.keyCode == Keyboard.RIGHT) hero.x += 10;\n else if (e.keyCode == Keyboard.LEFT) hero.x -= 10;\n trace(e.keyCode, hero.x, e.target == stage);\n}";
let d = scripted(2, &[(0, src)], vec![layer(2, vec![kf(0, 2, vec![inst(3, 100, "hero", 30.0, 40.0, vec![])], vec![], "")])], vec![clip]);
let s = start(&d, &mut NoScripts);
assert_eq!(s.state.stage.len(), 2);
let s = step(&d, &s.state, &[Event::KeyDown(39), Event::KeyDown(39), Event::KeyUp(39)], &mut NoScripts);
assert_eq!(s.output, ["39 40 true", "39 50 true", "up 39"]);
// Between frames too.
let s = input(&d, &s.state, &[Event::KeyDown(37)], &mut NoScripts);
assert_eq!(s.output, ["37 40 true"]);
assert_eq!(s.state.props.get(&vec![ElementId(3)]).and_then(|o| o.x), Some(40.0));
}
#[test]
fn scripts_read_instance_and_timeline_properties() {
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 3, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "walk")])]);
let mut hero = (*inst(3, 100, "hero", 30.0, 40.0, vec![])).clone();
hero.transform = Affine::translate(30.25, 40.0).mul(&Affine::scale(2.0, 0.5));
hero.color = crate::ColorEffect::Alpha(0.3);
let src = "stop();\ntrace(hero.x, hero.y, hero.scaleX, hero.scaleY, hero.rotation, hero.alpha, hero.visible, hero.name);\ntrace(hero.currentFrame, hero.totalFrames, hero.currentLabel, currentFrame, totalFrames, currentLabel, this.name);\nhero.x = 0.1; hero.alpha = hero.alpha + 0.2; hero.visible = false;\ntrace(hero.x, hero.alpha, hero.visible);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { trace(mouseX, mouseY, hero.mouseX, stage.mouseY); });";
let k = as3(kf(0, 2, vec![], vec![], "intro"), src);
let mut hk = Keyframe::new(0, 2);
hk.elements = vec![Arc::new(hero)];
let d = doc(vec![layer(1, vec![k]), layer(2, vec![Arc::new(hk)])], vec![clip]);
let s = start(&d, &mut NoScripts);
assert_eq!(s.output, ["30.25 40 2 0.5 0 0.3 true hero", "1 3 walk 1 2 intro root1", "0.1 0.5 false"]);
let s = input(&d, &s.state, &[Event::Move(Vec2::new(50.5, 60.0)), Event::Leave, Event::KeyDown(32)], &mut NoScripts);
// The pointer's last place stays after it leaves; a clip sees it in its own space.
assert_eq!(s.output, ["50.5 60 25.2 60"]);
}
#[test]
fn random_numbers_are_seeded_and_repeat() {
let src = "trace(Math.random(), Math.floor(Math.random() * 6) + 1);";
let d = scripted(2, &[(0, src)], vec![], vec![]);
let a = start_seeded(&d, 7, &mut NoScripts).output;
let b = start_seeded(&d, 7, &mut NoScripts).output;
let c = start_seeded(&d, 8, &mut NoScripts).output;
assert_eq!(a, b);
assert_ne!(a, c);
// The generator itself: in [0, 1), and spread out.
let mut r = Rng::seeded(DEFAULT_SEED);
let v: Vec<f64> = (0..10_000).map(|_| r.next_f64()).collect();
assert!(v.iter().all(|x| (0.0..1.0).contains(x)));
let mean = v.iter().sum::<f64>() / v.len() as f64;
assert!((mean - 0.5).abs() < 0.02, "{mean}");
assert_eq!(start(&d, &mut NoScripts).output, start_seeded(&d, DEFAULT_SEED, &mut NoScripts).output);
}
#[test]
fn an_endless_loop_stops_its_script_and_the_movie_plays_on() {
let d = scripted(3, &[(0, "trace(\"a\");\nwhile (true) { }\ntrace(\"never\");"), (1, "trace(\"frame 2\");")], vec![], vec![]);
let s = start(&d, &mut NoScripts);
assert_eq!(s.output, ["a", "Script on frame 1 of the main timeline stopped: it ran more than 100000 steps (an endless loop?)"]);
let s = step(&d, &s.state, &[], &mut NoScripts);
assert_eq!((s.state.root.frame, s.output.as_slice()), (1, ["frame 2".to_string()].as_slice()));
// A runtime error stops only its script.
let d = scripted(2, &[(0, "trace(\"x\");\ntrace(ghost.x);\ntrace(\"y\");")], vec![], vec![]);
assert_eq!(start(&d, &mut NoScripts).output, ["x", "Script on frame 1 of the main timeline stopped: line 2: no instance named “ghost” here"]);
// Many listeners that each loop share one step's fuel; the step ends with one message.
let mut src = String::from("stop();\n");
for i in 0..15 {
src.push_str(&format!("addEventListener(Event.ENTER_FRAME, function (e:Event):void {{ var n:int = {i}; while (true) n++; }});\n"));
}
let d = scripted(2, &[(0, &src)], vec![], vec![]);
let s = step(&d, &start(&d, &mut NoScripts).state, &[], &mut NoScripts);
assert_eq!(s.output.iter().filter(|l| l.ends_with("(an endless loop?)")).count(), 10, "{:?}", s.output);
assert!(s.output.last().is_some_and(|l| l.starts_with("Stopped running actions this frame: scripts ran more than 1000000 steps")), "{:?}", s.output);
}
#[test]
fn listeners_know_their_target_and_current_target() {
let mut d = button_doc();
{
let tl = d.timeline_mut(0);
let l0 = Arc::make_mut(&mut tl.layers[0]);
l0.keyframes[0] = as3(l0.keyframes[0].clone(), "stop();\ngo.addEventListener(MouseEvent.CLICK, clicked);\nfunction clicked(e:MouseEvent):void { trace(e.target.name, e.currentTarget == go, e.target != stage, e.currentTarget.x); report(e); }\nfunction report(ev:MouseEvent):void { trace(\"from \" + ev.currentTarget.name); }");
let k = Arc::make_mut(&mut Arc::make_mut(&mut tl.layers[1]).keyframes[0]);
if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind {
events.clear();
}
}
let p = Vec2::new(150.0, 150.0);
let s = step(&d, &start(&d, &mut NoScripts).state, &[Event::Move(p), Event::Down(p), Event::Up(p)], &mut NoScripts);
assert_eq!(s.output, ["go true true 100", "from go"]);
}
#[test]
fn scripted_play_is_deterministic() {
let src = "var n:Number = 0;\naddEventListener(Event.ENTER_FRAME, function (e:Event):void { n += Math.random(); if (n > 2) { trace(n); n = 0; } });";
let d = scripted(4, &[(0, src)], vec![], vec![]);
let play = || {
let mut s = start_seeded(&d, 3, &mut NoScripts);
let mut out = Vec::new();
for _ in 0..40 {
s = step(&d, &s.state, &[Event::KeyDown(65)], &mut NoScripts);
out.extend(s.output.clone());
}
(s.state, out)
};
let (a, b) = (play(), play());
assert!(!a.1.is_empty());
assert_eq!(a, b);
}
// ----- text fields (ADR 0066) ---------------------------------------------------------------
/// A host that lays fields out in a 10 px monospace (the fonts live above this crate).
struct Mono;
impl ScriptHost for Mono {
fn run(&mut self, _: &PluginScript, _: &ScriptContext<'_>) -> ScriptRun {
ScriptRun::default()
}
fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option<FieldLook> {
let f = block.field.as_ref()?;
Some(crate::field::mono_look(shown, 10.0, 10.0, f.wrap_width(block.box_width)))
}
}
fn field(id: u64, name: &str, text: &str, kind: TextKind, x: f32, y: f32) -> Arc<Element> {
let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }), on_path: None };
Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) })
}
fn field_doc(script: &str) -> Document {
let fields = vec![field(5, "score_txt", "0", TextKind::Dynamic, 10.0, 10.0), field(6, "name_txt", "", TextKind::Input, 10.0, 50.0), field(7, "", "", TextKind::Input, 10.0, 90.0)];
doc(vec![layer(1, vec![as3(kf(0, 1, fields, vec![], ""), script)])], vec![])
}
fn text_of(st: &PlayerState, id: u64) -> Option<String> {
st.fields.get(&vec![ElementId(id)]).and_then(|f| f.text.clone())
}
#[test]
fn scripts_set_and_read_dynamic_text() {
let d = field_doc("stop();\nvar n:int = 0;\nscore_txt.text = \"Score: \" + n;\nscore_txt.appendText(\"!\");\ntrace(score_txt.text, score_txt.length, name_txt.text == \"\");\nscore_txt.x = 20;\nghost_txt.text = \"x\";");
let s = start(&d, &mut Mono);
assert_eq!(text_of(&s.state, 5).as_deref(), Some("Score: 0!"));
assert!(s.output.contains(&"Score: 0! 9 true".to_string()), "{:?}", s.output);
assert!(s.output.iter().any(|l| l.contains("no instance named “ghost_txt”")), "{:?}", s.output);
// Laid out by the host, drawn in place of the authored outline, where the script moved it.
let look = s.state.fields.get(&vec![ElementId(5)]).and_then(|f| f.look.clone()).expect("laid out");
assert_eq!(look.lines[0].end, 9);
let dl = evaluate_player(&d, &s.state);
assert!(dl.items.iter().any(|i| Arc::ptr_eq(&i.path, &look.outline) && i.transform.m[4] == 20.0));
// Without a host that can lay out, the text is still set and read; it draws only its box.
let s2 = start(&d, &mut NoScripts);
assert_eq!(text_of(&s2.state, 5).as_deref(), Some("Score: 0!"));
// Static text and other instances aren't fields.
let d = field_doc("hero.text = \"x\";");
assert!(start(&d, &mut Mono).output.iter().any(|l| l.contains("no instance named “hero”")));
}
#[test]
fn the_viewer_types_into_input_fields_and_scripts_read_it() {
let d = field_doc("stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\nfunction onKey(e:KeyboardEvent):void {\n if (e.keyCode == Keyboard.ENTER) { score_txt.text = \"Hello, \" + name_txt.text; }\n}");
let mut h = Mono;
let s = start(&d, &mut h);
// A click in the input field gives it the keyboard; typing goes in, editing keys edit.
let mut ev = vec![Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0))];
ev.extend("Adx".chars().map(Event::Char));
ev.extend([Event::KeyDown(8), Event::KeyDown(37), Event::Char('a'), Event::KeyDown(35), Event::Char('!')]);
let s = input(&d, &s.state, &ev, &mut h);
assert_eq!(s.state.focus, Some(vec![ElementId(6)]));
assert_eq!(text_of(&s.state, 6).as_deref(), Some("Aad!"));
// Shift+Home selects; typing replaces it; Enter reaches the stage's key listener too.
let s = input(&d, &s.state, &[Event::KeyDown(16), Event::KeyDown(36), Event::KeyUp(16), Event::Char('B'), Event::Char('o'), Event::KeyDown(13)], &mut h);
assert_eq!(text_of(&s.state, 6).as_deref(), Some("Bo"));
assert_eq!(text_of(&s.state, 5).as_deref(), Some("Hello, Bo"));
// The focused field draws its caret; a click elsewhere takes the keyboard away.
let caret = |st: &PlayerState| evaluate_player(&d, st).items.iter().filter(|i| i.fill.is_some() && i.masks.is_none() && i.path.bounds().width() <= 1.01 && i.path.bounds().height() > 5.0).count();
assert_eq!(caret(&s.state), 1);
let s = input(&d, &s.state, &[Event::Down(Vec2::new(300.0, 300.0)), Event::Up(Vec2::new(300.0, 300.0)), Event::Char('z')], &mut h);
assert_eq!(s.state.focus, None);
assert_eq!(text_of(&s.state, 6).as_deref(), Some("Bo"), "no field, no typing");
assert_eq!(caret(&s.state), 0);
// A dynamic field takes no typing; Tab goes from input field to input field.
let s = input(&d, &s.state, &[Event::Down(Vec2::new(20.0, 15.0)), Event::Up(Vec2::new(20.0, 15.0)), Event::Char('q')], &mut h);
assert_eq!(s.state.focus, Some(vec![ElementId(5)]), "a selectable dynamic field can be focused");
assert_eq!(text_of(&s.state, 5).as_deref(), Some("Hello, Bo"));
let s = input(&d, &s.state, &[Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0)), Event::KeyDown(9)], &mut h);
assert_eq!(s.state.focus, Some(vec![ElementId(7)]));
let s = input(&d, &s.state, &[Event::KeyDown(9)], &mut h);
assert_eq!(s.state.focus, Some(vec![ElementId(6)]), "Tab wraps round");
assert_eq!(s.state.fields.get(&vec![ElementId(6)]).map(|f| f.selection()), Some((0, 2)), "and selects the field's text");
}
#[test]
fn fields_draw_their_box_and_the_authored_text_everywhere() {
let d = field_doc("");
// The authoring frame and the player draw the authored outline, a border, inside a clip.
for dl in [evaluate(&d, 0), evaluate_player(&d, &start(&d, &mut NoScripts).state)] {
let texts = dl.items.iter().filter(|i| i.path.bounds() == Path::rect(2.0, 2.0, 8.0, 8.0).bounds() && i.masks.is_none()).count();
assert_eq!(texts, 3);
assert_eq!(dl.items.iter().filter(|i| i.stroke.is_some()).count(), 3, "three borders");
assert_eq!(dl.items.iter().filter(|i| i.masks.is_some()).count(), 3, "each box clips its text");
assert_eq!(dl.clip_parents.len(), 3);
}
}
#[test]
fn typing_is_deterministic() {
let d = field_doc("stop();");
let ev: Vec<Event> = [Event::Down(Vec2::new(30.0, 55.0)), Event::Up(Vec2::new(30.0, 55.0))].into_iter().chain("deterministic".chars().map(Event::Char)).chain([Event::KeyDown(16), Event::KeyDown(37), Event::KeyDown(37), Event::Char('X')]).collect();
let a = step(&d, &start(&d, &mut Mono).state, &ev, &mut Mono);
let b = step(&d, &start(&d, &mut Mono).state, &ev, &mut Mono);
assert_eq!(a, b);
assert_eq!(text_of(&a.state, 6).as_deref(), Some("deterministX"));
}
+422
View File
@@ -0,0 +1,422 @@
//! Publish Settings (ADR 0060): which formats File › Publish writes, each with its options and
//! output name, kept in the document as Animate keeps them.
//!
//! Every format is always present, in the fixed order Publish runs them; a format is on or off.
//! Outputs are templates relative to the document's folder: `{name}` is the document's file name
//! without its extension. A file written before publish settings existed has none and gets
//! [`PublishProfile::default`] (the HTML canvas page on, the rest off) the first time it opens.
use serde::{Deserialize, Serialize};
/// The formats File › Publish can write, in the order it writes them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PublishFormat {
Html,
Gif,
Apng,
Webp,
Video,
Lottie,
SpriteSheet,
PngSequence,
Png,
Svg,
Audio,
}
impl PublishFormat {
/// Every format, in the order Publish runs them.
pub const ALL: [PublishFormat; 11] = [
PublishFormat::Html,
PublishFormat::Gif,
PublishFormat::Apng,
PublishFormat::Webp,
PublishFormat::Video,
PublishFormat::Lottie,
PublishFormat::SpriteSheet,
PublishFormat::PngSequence,
PublishFormat::Png,
PublishFormat::Svg,
PublishFormat::Audio,
];
/// The stable key used by commands and the file format.
pub fn key(self) -> &'static str {
match self {
PublishFormat::Html => "html",
PublishFormat::Gif => "gif",
PublishFormat::Apng => "apng",
PublishFormat::Webp => "webp",
PublishFormat::Video => "video",
PublishFormat::Lottie => "lottie",
PublishFormat::SpriteSheet => "sprite_sheet",
PublishFormat::PngSequence => "png_sequence",
PublishFormat::Png => "png",
PublishFormat::Svg => "svg",
PublishFormat::Audio => "audio",
}
}
pub fn from_key(key: &str) -> Option<PublishFormat> {
PublishFormat::ALL.into_iter().find(|f| f.key() == key)
}
/// The English name of the format (translated where it is drawn).
pub fn label(self) -> &'static str {
match self {
PublishFormat::Html => "HTML canvas",
PublishFormat::Gif => "Animated GIF",
PublishFormat::Apng => "Animated PNG",
PublishFormat::Webp => "Animated WebP",
PublishFormat::Video => "Video",
PublishFormat::Lottie => "Lottie",
PublishFormat::SpriteSheet => "Sprite sheet",
PublishFormat::PngSequence => "PNG sequence",
PublishFormat::Png => "PNG image",
PublishFormat::Svg => "SVG image",
PublishFormat::Audio => "Audio",
}
}
/// The output a new profile gives the format.
pub fn default_output(self) -> &'static str {
match self {
PublishFormat::Html => "{name}.html",
PublishFormat::Gif => "{name}.gif",
// Not {name}.png: the PNG image has that.
PublishFormat::Apng => "{name}_animated.png",
PublishFormat::Webp => "{name}.webp",
PublishFormat::Video => "{name}.webm",
PublishFormat::Lottie => "{name}.json",
PublishFormat::SpriteSheet => "{name}_sheet.png",
PublishFormat::PngSequence => "{name}_frames",
PublishFormat::Png => "{name}.png",
PublishFormat::Svg => "{name}.svg",
PublishFormat::Audio => "{name}.wav",
}
}
/// The file extensions the output may end in (none for the PNG sequence: a folder).
pub fn extensions(self) -> &'static [&'static str] {
match self {
PublishFormat::Html => &["html", "htm"],
PublishFormat::Gif => &["gif"],
PublishFormat::Apng => &["png", "apng"],
PublishFormat::Webp => &["webp"],
PublishFormat::Video => &["webm", "mp4"],
PublishFormat::Lottie => &["json"],
PublishFormat::SpriteSheet | PublishFormat::Png => &["png"],
PublishFormat::PngSequence => &[],
PublishFormat::Svg => &["svg"],
PublishFormat::Audio => &["wav"],
}
}
}
/// Longest output template, in characters.
pub const MAX_OUTPUT_CHARS: usize = 512;
/// Longest HTML page title, in characters.
pub const MAX_TITLE_CHARS: usize = 256;
/// Largest export scale.
pub const MAX_PUBLISH_SCALE: f32 = 8.0;
/// Most plays an animated PNG or WebP's loop count says (WebP stores it in 16 bits).
pub const MAX_PLAYS: u32 = 65_535;
/// Movie frames to publish (every scene in order, 0-based): `None` ends are the movie's ends.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct FrameRange {
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub to: Option<u32>,
}
macro_rules! format_settings {
($(#[$meta:meta])* $name:ident, $format:expr, $enabled:expr, { $($(#[$fmeta:meta])* $field:ident : $ty:ty = $default:expr),* $(,)? }) => {
$(#[$meta])*
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct $name {
/// Publish writes this format.
pub enabled: bool,
/// A path relative to the document's folder; `{name}` is the document's name.
pub output: String,
$($(#[$fmeta])* pub $field: $ty,)*
}
impl Default for $name {
fn default() -> Self {
$name { enabled: $enabled, output: $format.default_output().to_string(), $($field: $default,)* }
}
}
};
}
format_settings!(
/// The movie as one web page (`file.export_html`, ADR 0028).
HtmlSettings, PublishFormat::Html, true, {
/// The page's title; empty: the output's file name.
title: String = String::new(),
sound: bool = true,
fit: bool = true,
}
);
format_settings!(
/// An animated GIF (`file.export_gif`).
GifSettings, PublishFormat::Gif, false, {
range: FrameRange = FrameRange::default(),
scale: f32 = 1.0,
#[serde(rename = "loop")]
looping: bool = true,
}
);
format_settings!(
/// An animated PNG: full colour, real alpha (`file.export_apng`, ADR 0063).
ApngSettings, PublishFormat::Apng, false, {
range: FrameRange = FrameRange::default(),
scale: f32 = 1.0,
/// How many times it plays; 0: forever.
#[serde(rename = "loop")]
plays: u32 = 0,
/// The stage colour behind it; off: transparent.
background: bool = false,
}
);
format_settings!(
/// An animated WebP, lossless (`file.export_webp`, ADR 0063).
WebpSettings, PublishFormat::Webp, false, {
range: FrameRange = FrameRange::default(),
scale: f32 = 1.0,
/// How many times it plays; 0: forever.
#[serde(rename = "loop")]
plays: u32 = 0,
/// The stage colour behind it; off: transparent.
background: bool = false,
}
);
format_settings!(
/// WebM or MP4 through the user's ffmpeg (`file.export_video`).
VideoSettings, PublishFormat::Video, false, {
range: FrameRange = FrameRange::default(),
scale: f32 = 1.0,
audio: bool = true,
}
);
format_settings!(
/// A Lottie animation (`file.export_lottie`).
LottieSettings, PublishFormat::Lottie, false, {
range: FrameRange = FrameRange::default(),
background: bool = false,
}
);
format_settings!(
/// A sprite sheet and its JSON frame map (`file.export_sprite_sheet`).
SpriteSheetSettings, PublishFormat::SpriteSheet, false, {
range: FrameRange = FrameRange::default(),
scale: f32 = 1.0,
/// 0: as square as it can be.
columns: u32 = 0,
padding: u32 = 0,
background: bool = false,
}
);
format_settings!(
/// One PNG per frame in a folder (`file.export_png_sequence`).
PngSequenceSettings, PublishFormat::PngSequence, false, {
range: FrameRange = FrameRange::default(),
scale: f32 = 1.0,
}
);
format_settings!(
/// One frame as a PNG (`file.export_png`).
PngSettings, PublishFormat::Png, false, {
/// The movie frame (0-based, every scene in order).
frame: u32 = 0,
scale: f32 = 1.0,
}
);
format_settings!(
/// One frame as an SVG (`file.export_svg`).
SvgSettings, PublishFormat::Svg, false, {
/// The movie frame (0-based, every scene in order).
frame: u32 = 0,
}
);
format_settings!(
/// The movie's soundtrack as a WAV (`file.export_audio`).
AudioSettings, PublishFormat::Audio, false, {
range: FrameRange = FrameRange::default(),
rate: u32 = 44_100,
/// 16, 24, or 32 (float).
bits: u32 = 16,
}
);
/// What File › Publish writes: every format with its options (ADR 0060).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PublishProfile {
pub html: HtmlSettings,
pub gif: GifSettings,
pub apng: ApngSettings,
pub webp: WebpSettings,
pub video: VideoSettings,
pub lottie: LottieSettings,
pub sprite_sheet: SpriteSheetSettings,
pub png_sequence: PngSequenceSettings,
pub png: PngSettings,
pub svg: SvgSettings,
pub audio: AudioSettings,
}
fn clean_scale(s: f32) -> f32 {
if s.is_finite() && s > 0.0 { s.min(MAX_PUBLISH_SCALE) } else { 1.0 }
}
fn clip(s: &mut String, max: usize) {
if s.chars().count() > max {
*s = s.chars().take(max).collect();
}
}
impl PublishProfile {
pub fn is_default(&self) -> bool {
*self == PublishProfile::default()
}
/// Whether Publish writes `f`, and its output template.
pub fn target(&self, f: PublishFormat) -> (bool, &str) {
match f {
PublishFormat::Html => (self.html.enabled, &self.html.output),
PublishFormat::Gif => (self.gif.enabled, &self.gif.output),
PublishFormat::Apng => (self.apng.enabled, &self.apng.output),
PublishFormat::Webp => (self.webp.enabled, &self.webp.output),
PublishFormat::Video => (self.video.enabled, &self.video.output),
PublishFormat::Lottie => (self.lottie.enabled, &self.lottie.output),
PublishFormat::SpriteSheet => (self.sprite_sheet.enabled, &self.sprite_sheet.output),
PublishFormat::PngSequence => (self.png_sequence.enabled, &self.png_sequence.output),
PublishFormat::Png => (self.png.enabled, &self.png.output),
PublishFormat::Svg => (self.svg.enabled, &self.svg.output),
PublishFormat::Audio => (self.audio.enabled, &self.audio.output),
}
}
/// `f`'s on/off switch and output template, to change.
pub fn target_mut(&mut self, f: PublishFormat) -> (&mut bool, &mut String) {
match f {
PublishFormat::Html => (&mut self.html.enabled, &mut self.html.output),
PublishFormat::Gif => (&mut self.gif.enabled, &mut self.gif.output),
PublishFormat::Apng => (&mut self.apng.enabled, &mut self.apng.output),
PublishFormat::Webp => (&mut self.webp.enabled, &mut self.webp.output),
PublishFormat::Video => (&mut self.video.enabled, &mut self.video.output),
PublishFormat::Lottie => (&mut self.lottie.enabled, &mut self.lottie.output),
PublishFormat::SpriteSheet => (&mut self.sprite_sheet.enabled, &mut self.sprite_sheet.output),
PublishFormat::PngSequence => (&mut self.png_sequence.enabled, &mut self.png_sequence.output),
PublishFormat::Png => (&mut self.png.enabled, &mut self.png.output),
PublishFormat::Svg => (&mut self.svg.enabled, &mut self.svg.output),
PublishFormat::Audio => (&mut self.audio.enabled, &mut self.audio.output),
}
}
/// The formats that are on, in publishing order.
pub fn enabled(&self) -> Vec<PublishFormat> {
PublishFormat::ALL.into_iter().filter(|f| self.target(*f).0).collect()
}
/// Brings every value into range, so whatever a file holds, publishing can run: scales in
/// (0, 8], a known sample rate and bit depth, bounded text.
pub fn sanitize(&mut self) {
for f in PublishFormat::ALL {
let (_, output) = self.target_mut(f);
clip(output, MAX_OUTPUT_CHARS);
if output.trim().is_empty() {
*output = f.default_output().to_string();
}
}
clip(&mut self.html.title, MAX_TITLE_CHARS);
for s in [&mut self.gif.scale, &mut self.apng.scale, &mut self.webp.scale, &mut self.video.scale, &mut self.sprite_sheet.scale, &mut self.png_sequence.scale, &mut self.png.scale] {
*s = clean_scale(*s);
}
self.sprite_sheet.padding = self.sprite_sheet.padding.min(256);
self.apng.plays = self.apng.plays.min(MAX_PLAYS);
self.webp.plays = self.webp.plays.min(MAX_PLAYS);
self.sprite_sheet.columns = self.sprite_sheet.columns.min(10_000);
self.audio.rate = self.audio.rate.clamp(8_000, 192_000);
if !matches!(self.audio.bits, 16 | 24 | 32) {
self.audio.bits = 16;
}
for r in [&mut self.gif.range, &mut self.apng.range, &mut self.webp.range, &mut self.video.range, &mut self.lottie.range, &mut self.sprite_sheet.range, &mut self.png_sequence.range, &mut self.audio.range] {
if let (Some(a), Some(b)) = (r.from, r.to)
&& b < a
{
*r = FrameRange { from: Some(b), to: Some(a) };
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_round_trip_and_defaults_are_distinct() {
for f in PublishFormat::ALL {
assert_eq!(PublishFormat::from_key(f.key()), Some(f));
}
let p = PublishProfile::default();
assert_eq!(p.enabled(), vec![PublishFormat::Html], "a new document publishes its web page");
let mut outs: Vec<&str> = PublishFormat::ALL.iter().map(|f| p.target(*f).1).collect();
outs.sort_unstable();
outs.dedup();
assert_eq!(outs.len(), PublishFormat::ALL.len(), "no two formats write the same file by default");
}
#[test]
fn profile_round_trips_and_missing_fields_default() {
let mut p = PublishProfile::default();
p.gif.enabled = true;
p.gif.scale = 0.5;
p.gif.looping = false;
p.gif.range = FrameRange { from: Some(2), to: Some(9) };
p.html.title = "Walk".into();
p.audio.bits = 24;
let text = serde_json::to_string(&p).unwrap();
assert!(text.contains("\"loop\":false") && text.contains("\"enabled\":true"), "{text}");
let back: PublishProfile = serde_json::from_str(&text).unwrap();
assert_eq!(back, p);
// A profile from an older build, with fields and formats missing.
let partial: PublishProfile = serde_json::from_str(r#"{"gif": {"enabled": true}}"#).unwrap();
assert!(partial.gif.enabled && partial.html.enabled);
assert_eq!(partial.gif.output, "{name}.gif");
assert_eq!(partial.gif.scale, 1.0);
assert_eq!((partial.apng.plays, partial.webp.background, partial.webp.enabled), (0, false, false), "formats newer than the file get their defaults");
let mut q = PublishProfile::default();
q.apng.plays = 3;
q.webp.background = true;
let text = serde_json::to_string(&q).unwrap();
assert!(text.contains("\"apng\"") && text.contains("\"loop\":3"), "{text}");
assert_eq!(serde_json::from_str::<PublishProfile>(&text).unwrap(), q);
}
#[test]
fn sanitize_brings_everything_into_range() {
let mut p = PublishProfile::default();
p.gif.scale = f32::NAN;
p.png.scale = 1e9;
p.audio.rate = 5;
p.audio.bits = 7;
p.sprite_sheet.padding = u32::MAX;
p.webp.plays = u32::MAX;
p.video.output = " ".into();
p.html.title = "x".repeat(10_000);
p.lottie.range = FrameRange { from: Some(9), to: Some(2) };
p.sanitize();
assert_eq!((p.gif.scale, p.png.scale, p.audio.rate, p.audio.bits, p.sprite_sheet.padding), (1.0, MAX_PUBLISH_SCALE, 8_000, 16, 256));
assert_eq!(p.video.output, "{name}.webm");
assert_eq!(p.webp.plays, MAX_PLAYS);
assert_eq!(p.html.title.chars().count(), MAX_TITLE_CHARS);
assert_eq!(p.lottie.range, FrameRange { from: Some(2), to: Some(9) });
}
}
+13 -12
View File
@@ -41,19 +41,19 @@ fn key(start: u32, duration: u32, elements: Vec<Arc<Element>>, tween: Option<Eas
/// 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 }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 };
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), 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)]) },
Paint::radial(Vec2::new(-16.0, -18.0), 70.0, 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, linkage: None, timeline: Timeline { layers: vec![ball_layer] } }));
d.library.push(Arc::new(Symbol { id: ball_id, name: "Ball".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, 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);
@@ -67,7 +67,7 @@ pub fn demo() -> Document {
})
.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, linkage: None, timeline: Timeline { layers: vec![star_layer] } }));
d.library.push(Arc::new(Symbol { id: star_id, name: "Star".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![star_layer] } }));
// --- main timeline (index 0 = top) ---------------------------------------------------
const LEN: u32 = 48;
@@ -85,7 +85,8 @@ pub fn demo() -> Document {
let ball_keys = poses
.iter()
.enumerate()
.map(|(i, &(start, (x, y, sx, sy), easing))| {
.map(|(i, (start, (x, y, sx, sy), easing))| {
let (start, (x, y, sx, sy), easing) = (*start, (*x, *y, *sx, *sy), easing.clone());
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))
@@ -101,7 +102,7 @@ pub fn demo() -> Document {
// 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_shape = Shape::filled(Path::ellipse(0.0, 0.0, 90.0, 90.0), Paint::radial(Vec2::ZERO, 90.0, 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()
@@ -132,7 +133,7 @@ pub fn demo() -> Document {
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)]) },
Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(0.0, h), 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)]);
@@ -147,7 +148,7 @@ pub fn demo() -> Document {
/// whose last frame traces a line and goes back to the menu.
pub fn interactive() -> Document {
use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, Target};
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 };
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), next_id: 1 };
const LEN: u32 = 36;
let solid = |c: u32| Paint::Solid(Rgba::hex(c));
@@ -161,7 +162,7 @@ pub fn interactive() -> Document {
let (up, over, down) = (face(&mut d, 0x3d8bfd), face(&mut d, 0x6aa8ff), face(&mut d, 0x2a64c0));
let hit_area = el(&mut d, "hit", Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(-120.0, -50.0, 240.0, 100.0), solid(0x000000))));
let states = layer(d.alloc_id(), "states", 0x4fa3ff, vec![key(0, 1, up, None), key(1, 1, over, None), key(2, 1, down, None), key(3, 1, vec![hit_area], None)]);
d.library.push(Arc::new(Symbol { id: button_id, name: "Play Button".into(), kind: SymbolKind::Button, linkage: None, timeline: Timeline { layers: vec![states] } }));
d.library.push(Arc::new(Symbol { id: button_id, name: "Play Button".into(), kind: SymbolKind::Button, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![states] } }));
// A movie clip that spins on its own timeline.
let spinner_id = SymbolId(d.alloc_id());
@@ -175,7 +176,7 @@ pub fn interactive() -> Document {
})
.collect();
let spin = layer(d.alloc_id(), "spin", 0xffd54a, spin_keys);
d.library.push(Arc::new(Symbol { id: spinner_id, name: "Spinner".into(), kind: SymbolKind::MovieClip, linkage: None, timeline: Timeline { layers: vec![spin] } }));
d.library.push(Arc::new(Symbol { id: spinner_id, name: "Spinner".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![spin] } }));
// Main timeline: actions on top, then the button (menu frame), the show, the backdrop.
let mut menu = key(0, 1, Vec::new(), None);
@@ -211,7 +212,7 @@ pub fn interactive() -> Document {
/// `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 }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 };
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), 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 || {
@@ -249,7 +250,7 @@ pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document {
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(), merge: false }),
kind: ElementKind::Shape(Shape { path: path.clone(), fill: Some(fill.clone()), stroke: None, fill_rule: Default::default(), merge: false, warp: None }),
})
})
.collect();
+334
View File
@@ -0,0 +1,334 @@
//! Shape armatures (ADR 0071): bones drawn inside one shape, whose outline bends with them.
//!
//! A shape armature is an [`Armature`] with a [`Skin`]. Its bones join *joint nodes* instead of
//! symbol instances: the root bones start on the shape itself (its element id) and every other
//! bone starts on the node of the bone it hangs from. A node is a frame that the bone into it
//! turns; at rest every node's frame is the shape's own local space, so a bone's head and tail
//! are points of the shape as it was drawn, and a node's transform under a pose is the bone's
//! **skinning matrix**. Forward and inverse kinematics are ADR 0043's ([`crate::armature::place`],
//! [`crate::armature::solve`]): nothing about posing is new.
//!
//! The skin keeps the outline as it was drawn (`rest`) and one [`Binding`] per anchor of it
//! (every `MoveTo`, `LineTo`, `QuadTo` and `CubicTo` end, in path order): the bones the anchor
//! follows and how much. Automatic binding ([`auto_binding`]) weighs each bone by the inverse
//! fourth power of the anchor's distance to the bone's segment, keeps the strongest
//! [`MAX_INFLUENCES`] and normalises them to sum to 1; the Bind tool (`bone.bind`) overrides
//! anchors by hand. The posed outline ([`deform`]) is linear blend skinning: each anchor moves
//! by the weighted sum of its bones' matrices, and each handle by the blend of the anchor it
//! belongs to, so curves stay smooth through a bend. Stroke width is drawn after the outline
//! (the shape's own transform is untouched), so strokes keep their width.
//!
//! Linear blend skinning is the standard method (N. Magnenat-Thalmann, R. Laperrière and
//! D. Thalmann, *Joint-dependent local deformations for hand animation and object grasping*,
//! Graphics Interface 1988; J. P. Lewis, M. Cordner and N. Fong, *Pose space deformation*,
//! SIGGRAPH 2000, §2, which names it skeleton subspace deformation).
use crate::armature::{Armature, BoneId, Pose};
use crate::{Element, ElementId, ElementKind};
use anicraft_geom::{Affine, Path, PathCmd, Vec2, segment_distance};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
/// Most bones one anchor follows.
pub const MAX_INFLUENCES: usize = 4;
/// Most anchors a shape with bones may have (a hand-drawn shape has tens to a few thousand).
pub const MAX_SKIN_POINTS: usize = 20_000;
/// Distances below this count as this (px), so an anchor on a bone has a finite weight.
const NEAR: f32 = 0.5;
/// A bone whose share is below this after normalising is dropped from the anchor.
const FAINT: f32 = 0.01;
/// One bone's share of an anchor: `[bone, weight]` in files.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Influence(pub BoneId, pub f32);
/// The bones one anchor follows. Weights are positive and sum to 1; an anchor with none stays
/// where it was drawn.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Binding {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub bones: Vec<Influence>,
/// Set with the Bind tool: automatic binding (after adding or removing a bone) leaves it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub manual: bool,
}
impl Binding {
/// The share bone `b` has of this anchor (0 when it doesn't follow it).
pub fn weight(&self, b: BoneId) -> f32 {
self.bones.iter().find(|i| i.0 == b).map_or(0.0, |i| i.1)
}
/// Keeps positive, finite weights of bones in `keep` (one each, the strongest
/// [`MAX_INFLUENCES`]) and scales them to sum to 1. Returns whether anything changed.
pub fn normalize(&mut self, keep: impl Fn(BoneId) -> bool) -> bool {
let before = self.bones.clone();
let mut seen = Vec::with_capacity(self.bones.len());
self.bones.retain(|i| i.1.is_finite() && i.1 > 0.0 && keep(i.0) && !seen.contains(&i.0) && {
seen.push(i.0);
true
});
self.bones.sort_by(|a, b| b.1.total_cmp(&a.1));
self.bones.truncate(MAX_INFLUENCES);
let sum: f32 = self.bones.iter().map(|i| i.1).sum();
if sum > 0.0 && sum.is_finite() {
for i in &mut self.bones {
i.1 /= sum;
}
} else {
self.bones.clear();
}
self.bones != before
}
}
/// How a shape is bound to its armature's bones.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Skin {
/// The shape the bones are inside (an element of the armature layer's keyframes).
pub shape: ElementId,
/// The outline as it was drawn, in the shape's local space: the pose of every bone at 0.
pub rest: Arc<Path>,
/// One per anchor of `rest`, in path order.
#[serde(default)]
pub points: Vec<Binding>,
}
impl Skin {
/// A skin for `shape` drawn as `rest`, its anchors not yet bound.
pub fn new(shape: ElementId, rest: Arc<Path>) -> Skin {
let points = vec![Binding::default(); anchors(&rest).len()];
Skin { shape, rest, points }
}
}
/// The anchors of `path` in order: every command's end point.
pub fn anchors(path: &Path) -> Vec<Vec2> {
path.cmds
.iter()
.filter_map(|c| match *c {
PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p),
PathCmd::Close => None,
})
.collect()
}
/// Where every bone of a shape armature lies as drawn, in the shape's space: its joint and end.
pub fn rest_segments(arm: &Armature) -> Vec<(BoneId, Vec2, Vec2)> {
// Every node's rest frame is the shape's space (`rest` is the identity for shape bones), so
// composing the rests places each bone; a hand-edited file with other rests still works.
let mut node: HashMap<ElementId, Affine> = HashMap::new();
let root = arm.skin.as_ref().map(|s| s.shape);
arm.bones
.iter()
.filter_map(|b| {
let wp = if Some(b.parent) == root { Affine::IDENTITY } else { *node.get(&b.parent)? };
let wc = wp.mul(&b.rest);
node.insert(b.child, wc);
Some((b.id, wp.apply(b.head), wc.apply(b.tail)))
})
.collect()
}
/// Automatic binding of an anchor at `p` (the shape's space, as drawn): each bone weighs
/// `1 / max(d, 0.5)⁴` where `d` is the distance from `p` to the bone's segment; the strongest
/// [`MAX_INFLUENCES`] are kept, faint ones (under 1 %) dropped, and the rest sum to 1. An anchor
/// near one bone follows it alone; one near a joint shares it between the bones that meet
/// there, so the outline bends smoothly. Empty only without bones.
pub fn auto_binding(segments: &[(BoneId, Vec2, Vec2)], p: Vec2) -> Binding {
let mut bones: Vec<Influence> = segments
.iter()
.map(|&(id, a, b)| {
let d = segment_distance(p, a, b).max(NEAR);
Influence(id, 1.0 / (d * d * d * d))
})
.filter(|i| i.1.is_finite() && i.1 > 0.0)
.collect();
// Weighed relative to the nearest bone, so a far-away shape keeps finite numbers.
let top = bones.iter().map(|i| i.1).fold(0.0f32, f32::max);
if top > 0.0 {
for i in &mut bones {
i.1 /= top;
}
}
let mut out = Binding { bones, manual: false };
out.normalize(|_| true);
let before = out.bones.len();
out.bones.retain(|i| i.1 >= FAINT);
if out.bones.len() != before {
out.normalize(|_| true);
}
out
}
/// Binds every anchor not bound by hand afresh (after the bones changed), and repairs the hand
/// bound ones: bones that went away leave them, and one left with none goes back to automatic
/// (an anchor unbound by hand on purpose stays unbound). Keeps one binding per anchor.
pub fn rebind(arm: &mut Armature) {
let segments = rest_segments(arm);
let ids: Vec<BoneId> = arm.bones.iter().map(|b| b.id).collect();
let Some(skin) = arm.skin.as_mut() else { return };
let pts = anchors(&skin.rest);
skin.points.resize(pts.len(), Binding::default());
for (b, &p) in skin.points.iter_mut().zip(&pts) {
if b.manual {
let had = !b.bones.is_empty();
b.normalize(|id| ids.contains(&id));
if !had || !b.bones.is_empty() {
continue;
}
}
*b = auto_binding(&segments, p);
}
}
/// Every bone's skinning matrix under `pose`: how the pose moves the shape's space near it (the
/// identity at rest, exactly).
pub fn matrices(arm: &Armature, pose: &Pose) -> HashMap<BoneId, Affine> {
let Some(skin) = &arm.skin else { return HashMap::new() };
let mut node: HashMap<ElementId, Affine> = HashMap::new();
node.insert(skin.shape, Affine::IDENTITY);
let mut out = HashMap::with_capacity(arm.bones.len());
for b in &arm.bones {
let Some(wp) = node.get(&b.parent).copied() else { continue };
let (a, s) = (b.allow(pose.angle(b.id)), b.allow_slide(pose.slide(b.id)));
let wc = if a == 0.0 && s == anicraft_geom::Vec2::ZERO { wp.mul(&b.rest) } else { crate::armature::joint(b, &wp, a, s).1 };
if wc.is_finite() {
node.insert(b.child, wc);
out.insert(b.id, wc);
}
}
out
}
/// The blend of `binding`'s bone matrices; `None` when it doesn't move (no bones, or every one
/// of them at rest), so a point at rest is kept bit for bit.
fn blend(binding: &Binding, m: &HashMap<BoneId, Affine>) -> Option<Affine> {
let mut moved = false;
let mut acc = [0.0f32; 6];
let mut total = 0.0f32;
for &Influence(b, w) in &binding.bones {
let x = m.get(&b).copied().unwrap_or(Affine::IDENTITY);
moved |= x != Affine::IDENTITY;
for (a, v) in acc.iter_mut().zip(x.m) {
*a += w * v;
}
total += w;
}
if !moved || total <= 0.0 {
return None;
}
// Weights sum to 1; dividing keeps a hand-edited file's rounding from scaling the shape.
Some(Affine { m: acc.map(|v| v / total) })
}
fn mix(a: Option<Affine>, b: Option<Affine>) -> Option<Affine> {
match (a, b) {
(None, None) => None,
(a, b) => {
let (a, b) = (a.unwrap_or(Affine::IDENTITY), b.unwrap_or(Affine::IDENTITY));
let mut m = [0.0f32; 6];
for (i, v) in m.iter_mut().enumerate() {
*v = 0.5 * (a.m.get(i).copied().unwrap_or(0.0) + b.m.get(i).copied().unwrap_or(0.0));
}
Some(Affine { m })
}
}
}
/// The outline `pose` bends the skin's shape into (the shape's space): linear blend skinning of
/// every anchor, each cubic handle moving with the anchor it leaves or enters and a quadratic's
/// control with the mean of its two ends. At rest (or where no bound bone turned) points are
/// exactly as drawn.
pub fn deform(arm: &Armature, pose: &Pose) -> Option<Arc<Path>> {
let skin = arm.skin.as_ref()?;
let m = matrices(arm, pose);
if m.values().all(|x| *x == Affine::IDENTITY) {
return Some(skin.rest.clone());
}
let none = Binding::default();
let mut idx = 0usize;
let at = |i: usize| blend(skin.points.get(i).unwrap_or(&none), &m);
let on = |x: Option<Affine>, p: Vec2| x.map_or(p, |x| x.apply(p));
let mut prev: Option<Affine> = None;
let mut cmds = Vec::with_capacity(skin.rest.cmds.len());
for c in &skin.rest.cmds {
let next = match *c {
PathCmd::Close => {
cmds.push(PathCmd::Close);
continue;
}
_ => at(idx),
};
idx += 1;
cmds.push(match *c {
PathCmd::MoveTo(p) => PathCmd::MoveTo(on(next, p)),
PathCmd::LineTo(p) => PathCmd::LineTo(on(next, p)),
PathCmd::QuadTo(q, p) => PathCmd::QuadTo(on(mix(prev, next), q), on(next, p)),
PathCmd::CubicTo(c1, c2, p) => PathCmd::CubicTo(on(prev, c1), on(next, c2), on(next, p)),
PathCmd::Close => PathCmd::Close,
});
prev = next;
}
Some(Arc::new(Path { cmds }))
}
/// Puts the skin's shape in `elements` in the outline `pose` bends it into (copy-on-write).
/// Returns whether it changed.
pub fn apply(arm: &Armature, elements: &mut [Arc<Element>], pose: &Pose) -> bool {
let Some(skin) = &arm.skin else { return false };
let Some(e) = elements.iter_mut().find(|e| e.id == skin.shape) else { return false };
let ElementKind::Shape(s) = &e.kind else { return false };
let Some(path) = deform(arm, pose) else { return false };
if Arc::ptr_eq(&s.path, &path) || *s.path == *path {
return false;
}
if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind {
s.path = path;
}
true
}
/// The points of a shape armature's shape in `elements` (evaluated: posed), in point order, in
/// the layer's space: the anchors of its outline as it shows.
pub fn points_shown(arm: &Armature, elements: &[Arc<Element>]) -> Vec<Vec2> {
let Some(skin) = &arm.skin else { return Vec::new() };
elements
.iter()
.find(|e| e.id == skin.shape)
.and_then(|e| match &e.kind {
ElementKind::Shape(sh) => Some(anchors(&sh.path).into_iter().map(|p| e.transform.apply(p)).collect()),
_ => None,
})
.unwrap_or_default()
}
/// Repairs a loaded skin against its armature: the rest outline within [`MAX_SKIN_POINTS`]
/// anchors (else the skin goes), one binding per anchor, weights of bones that exist, positive
/// and summing to 1; unbound automatic anchors are bound. Returns whether anything changed.
pub fn sanitize(arm: &mut Armature) -> bool {
let Some(skin) = &arm.skin else { return false };
let n = anchors(&skin.rest).len();
if n > MAX_SKIN_POINTS || arm.bones.iter().any(|b| b.child == skin.shape) {
arm.skin = None;
return true;
}
let before = arm.skin.clone();
let ids: Vec<BoneId> = arm.bones.iter().map(|b| b.id).collect();
let segments = rest_segments(arm);
let Some(skin) = arm.skin.as_mut() else { return false };
let pts = anchors(&skin.rest);
skin.points.resize(n, Binding::default());
for (b, &p) in skin.points.iter_mut().zip(&pts) {
b.normalize(|id| ids.contains(&id));
if b.bones.is_empty() && !b.manual {
*b = auto_binding(&segments, p);
}
}
arm.skin != before
}
#[cfg(test)]
#[path = "skin_tests.rs"]
mod tests;
+302
View File
@@ -0,0 +1,302 @@
//! Shape armatures: binding, skinning, posing and files (ADR 0071).
use super::*;
use crate::armature::{Bone, place, pose_at, solve};
use crate::{ColorEffect, Document, Easing, Keyframe, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Tween, evaluate, evaluate_layer_elements};
use std::f32::consts::FRAC_PI_2;
const TAIL: ElementId = ElementId(10);
const B1: BoneId = BoneId(20);
const B2: BoneId = BoneId(21);
const N1: ElementId = ElementId(30);
const N2: ElementId = ElementId(31);
fn bone(id: BoneId, parent: ElementId, child: ElementId, head: Vec2, tail: Vec2) -> Bone {
Bone::new(id, parent, child, head, tail, Affine::IDENTITY)
}
/// A tail 200 px long and 20 px thick along y = 0 (anchors every 25 px along both edges), with
/// a cubic tip, drawn at (100, 100) on the stage; two bones along its middle meet at x = 100.
fn outline() -> Path {
let mut p = Path::new();
p.move_to(Vec2::new(0.0, -10.0));
for i in 1..=8 {
p.line_to(Vec2::new(25.0 * i as f32, -10.0));
}
p.cubic_to(Vec2::new(215.0, -10.0), Vec2::new(215.0, 10.0), Vec2::new(200.0, 10.0));
for i in (0..8).rev() {
p.line_to(Vec2::new(25.0 * i as f32, 10.0));
}
p.close();
p
}
fn rig() -> (Armature, Vec<Arc<Element>>) {
let path = Arc::new(outline());
let mut arm = Armature {
bones: vec![bone(B1, TAIL, N1, Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)), bone(B2, N1, N2, Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0))],
skin: Some(Skin::new(TAIL, path.clone())),
..Default::default()
};
rebind(&mut arm);
let shape = Shape { path, ..Shape::filled(Path::new(), Paint::Solid(Rgba::BLACK)) }.with_stroke(Rgba::BLACK, 3.0);
let el = Arc::new(Element { id: TAIL, name: String::new(), transform: Affine::translate(100.0, 100.0), color: ColorEffect::default(), kind: ElementKind::Shape(shape) });
(arm, vec![el])
}
fn path_of(els: &[Arc<Element>]) -> Arc<Path> {
match &els[0].kind {
ElementKind::Shape(s) => s.path.clone(),
_ => panic!("not a shape"),
}
}
fn close(a: Vec2, b: Vec2, tol: f32) -> bool {
a.distance(b) <= tol
}
/// `p` turned by `a` about `j`.
fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 {
let (s, c) = a.sin_cos();
let d = p - j;
Vec2::new(j.x + d.x * c - d.y * s, j.y + d.x * s + d.y * c)
}
#[test]
fn automatic_weights_sum_to_one_and_follow_the_nearest_bone() {
let (arm, _) = rig();
let skin = arm.skin.as_ref().unwrap();
let pts = anchors(&skin.rest);
assert_eq!(skin.points.len(), pts.len(), "one binding per anchor");
for (b, p) in skin.points.iter().zip(&pts) {
let sum: f32 = b.bones.iter().map(|i| i.1).sum();
assert!((sum - 1.0).abs() < 1e-5, "{p:?}: weights sum to {sum}");
assert!(b.bones.len() <= MAX_INFLUENCES && b.bones.iter().all(|i| i.1 > 0.0));
}
// Far along each bone an anchor follows it alone; at the joint the two share it equally.
let at = |x: f32| skin.points.iter().zip(&pts).find(|(_, p)| **p == Vec2::new(x, -10.0)).map(|(b, _)| b.clone()).unwrap();
assert_eq!(at(25.0).bones, vec![Influence(B1, 1.0)]);
assert_eq!(at(175.0).bones, vec![Influence(B2, 1.0)]);
let joint = at(100.0);
assert!((joint.weight(B1) - 0.5).abs() < 1e-5 && (joint.weight(B2) - 0.5).abs() < 1e-5, "{joint:?}");
// In between the nearer bone weighs more.
let near = at(125.0);
assert!(near.weight(B2) > near.weight(B1) && near.weight(B1) > 0.0, "{near:?}");
}
#[test]
fn the_rest_pose_reproduces_the_shape_exactly() {
let (arm, mut els) = rig();
let drawn = path_of(&els);
// No pose, and a pose that lists every bone at 0.
for pose in [Pose::default(), Pose(vec![crate::JointAngle::new(B1, 0.0), crate::JointAngle::new(B2, 0.0)])] {
let rest = deform(&arm, &pose).unwrap();
assert!(Arc::ptr_eq(&rest, &drawn), "the very path as drawn");
assert!(!apply(&arm, &mut els, &pose), "nothing changes");
}
// A pose that turns one bone leaves the anchors only the other bone moves bit for bit.
let mut pose = Pose::default();
pose.set(B2, 0.7);
let bent = deform(&arm, &pose).unwrap();
assert_eq!(bent.cmds[1], drawn.cmds[1], "x = 25 follows the first bone only");
assert_eq!(bent.cmds[0], drawn.cmds[0]);
}
#[test]
fn a_quarter_bend_turns_bound_points_about_the_joint() {
let (arm, mut els) = rig();
let drawn = path_of(&els);
let mut pose = Pose::default();
pose.set(B2, FRAC_PI_2);
assert!(apply(&arm, &mut els, &pose));
let bent = path_of(&els);
let skin = arm.skin.as_ref().unwrap();
let joint = Vec2::new(100.0, 0.0);
let (rest, now) = (anchors(&drawn), anchors(&bent));
for ((b, r), n) in skin.points.iter().zip(&rest).zip(&now) {
let w2 = b.weight(B2);
if w2 == 1.0 {
assert!(close(*n, turned(*r, joint, FRAC_PI_2), 1e-3), "{r:?} → {n:?}");
} else if w2 == 0.0 {
assert_eq!(n, r, "{r:?} follows the first bone, which didn't turn");
} else {
// A shared anchor moves part of the way: the blend of rest and the full turn.
let want = *r * (1.0 - w2) + turned(*r, joint, FRAC_PI_2) * w2;
assert!(close(*n, want, 1e-3), "{r:?}: {n:?} vs {want:?}");
}
}
// The tip (200, ±10) swings down to (90…110, 100), and its cubic handles turn with it.
assert!(close(now[8], Vec2::new(110.0, 100.0), 1e-3), "{:?}", now[8]);
let PathCmd::CubicTo(c1, c2, end) = bent.cmds[9] else { panic!("{:?}", bent.cmds[9]) };
assert!(close(c1, turned(Vec2::new(215.0, -10.0), joint, FRAC_PI_2), 1e-3));
assert!(close(c2, turned(Vec2::new(215.0, 10.0), joint, FRAC_PI_2), 1e-3));
assert!(close(end, Vec2::new(90.0, 100.0), 1e-3));
// The shape keeps its transform and its stroke's width.
assert_eq!(els[0].transform, Affine::translate(100.0, 100.0));
let ElementKind::Shape(s) = &els[0].kind else { panic!("not a shape") };
assert_eq!(s.stroke.as_ref().map(|s| s.width), Some(3.0));
// Turning the first bone carries the second: the tip goes round the root joint too.
let mut pose = Pose::default();
pose.set(B1, FRAC_PI_2);
let tip = anchors(&deform(&arm, &pose).unwrap())[8];
assert!(close(tip, turned(Vec2::new(200.0, -10.0), Vec2::new(0.0, 0.0), FRAC_PI_2), 1e-3), "{tip:?}");
}
#[test]
fn joint_nodes_are_placed_by_forward_kinematics() {
let (arm, els) = rig();
let mut pose = Pose::default();
pose.set(B2, FRAC_PI_2);
let w = place(&arm, &els, &pose);
// The second bone's end, on the stage: the shape is at (100, 100), the joint at (200, 100).
assert!(close(w[&N2].apply(Vec2::new(200.0, 0.0)), Vec2::new(200.0, 200.0), 1e-3));
let at = crate::armature::bones_at(&arm, &els, &pose);
assert_eq!(at.len(), 2, "bones of a shape show although their nodes are no elements");
assert!(close(at[1].head, Vec2::new(200.0, 100.0), 1e-4) && close(at[1].tail, Vec2::new(200.0, 200.0), 1e-3));
assert_eq!(arm.roots(), vec![TAIL]);
}
#[test]
fn inverse_kinematics_bends_the_shape() {
let (arm, els) = rig();
// Drag the tail's end (stage (300, 100)) up to (250, 0): both bones turn.
let target = Vec2::new(250.0, 0.0);
let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(200.0, 0.0), target).unwrap();
assert!(s.error <= 0.01, "{} px off", s.error);
assert_eq!(s.chain, 2);
let tip = place(&arm, &els, &s.pose)[&N2].apply(Vec2::new(200.0, 0.0));
assert!(close(tip, target, 0.02));
// The outline's anchors on the bone's end follow it (they're bound to the end bone only).
let mut moved = els.clone();
apply(&arm, &mut moved, &s.pose);
let tip_anchor = moved[0].transform.apply(anchors(&path_of(&moved))[8]);
assert!(tip_anchor.distance(target) < 11.0, "{tip_anchor:?}");
}
fn tail_layer(easing: Easing) -> Layer {
let (arm, els) = rig();
let mut l = Layer::new(LayerId(1), "Armature_1");
l.kind = LayerKind::Armature;
l.armature = Some(Arc::new(arm));
let mut a = Keyframe::new(0, 10);
a.elements = els.clone();
a.tween = Some(Tween { easing, ..Tween::default() });
let mut b = Keyframe::new(10, 5);
b.elements = els;
b.pose.set(B2, FRAC_PI_2);
l.keyframes = vec![Arc::new(a), Arc::new(b)];
l
}
#[test]
fn poses_tween_the_outline_with_easing() {
let l = tail_layer(Easing::Linear);
let tip = |f: u32| {
let (_, els) = evaluate_layer_elements(&l, f).unwrap();
anchors(&path_of(&els))[8]
};
let rest = Vec2::new(200.0, -10.0);
let joint = Vec2::new(100.0, 0.0);
assert_eq!(tip(0), rest, "exact at the first key");
assert!(close(tip(10), turned(rest, joint, FRAC_PI_2), 1e-3), "exact at the second key");
// Half way the tip has turned 45°: angles tween, the outline follows (not a straight morph).
assert!(close(tip(5), turned(rest, joint, FRAC_PI_2 * 0.5), 1e-3), "{:?}", tip(5));
let eased = tail_layer(Easing::QuadIn);
assert!((pose_at(&eased, 5).unwrap().angle(B2) - FRAC_PI_2 * 0.25).abs() < 1e-6);
}
#[test]
fn every_export_sees_the_bent_shape_and_files_keep_it() {
let mut d = Document::default();
d.timeline_mut(0).layers = vec![Arc::new(tail_layer(Easing::Linear))];
d.sanitize();
let dl = evaluate(&d, 10);
let item = dl.items.iter().find(|i| i.element == TAIL).unwrap();
let tip = item.transform.apply(anchors(&item.path)[8]);
assert!(close(tip, Vec2::new(210.0, 200.0), 1e-3), "the display list draws the bent tail: {tip:?}");
let json = serde_json::to_string(&d).unwrap();
let back: Document = serde_json::from_str(&json).unwrap();
assert_eq!(back, d);
assert!(back.timeline(0).layers[0].armature.as_ref().unwrap().skin.is_some());
// The joint nodes' ids are counted, so new ids never collide with them.
assert!(d.next_id > N2.0);
// An armature written before shape armatures reads as one without a skin.
let old: Armature = serde_json::from_str(r#"{"bones": []}"#).unwrap();
assert!(old.skin.is_none());
assert!(!serde_json::to_string(&old).unwrap().contains("skin"));
}
#[test]
fn sanitize_repairs_hostile_skins() {
let (mut arm, _) = rig();
let skin = arm.skin.as_mut().unwrap();
skin.points.truncate(3);
skin.points[0] = Binding { bones: vec![Influence(B1, f32::NAN), Influence(BoneId(99), 1.0), Influence(B2, 3.0), Influence(B2, 1.0)], manual: true };
skin.points[1] = Binding { bones: vec![Influence(B1, -1.0)], manual: false };
skin.points[2] = Binding { bones: vec![], manual: true };
assert!(arm.sanitize());
let skin = arm.skin.as_ref().unwrap();
assert_eq!(skin.points.len(), anchors(&skin.rest).len(), "one per anchor again");
assert_eq!(skin.points[0].bones, vec![Influence(B2, 1.0)], "unknown bones, NaN and repeats go; the rest sums to 1");
assert!(!skin.points[1].bones.is_empty(), "an automatic anchor left with nothing is bound again");
assert!(skin.points[2].bones.is_empty(), "an anchor unbound by hand stays unbound");
assert!(!arm.sanitize(), "sanitizing twice changes nothing");
// A bone that starts somewhere other than the shape, and a shape that is a bone's node.
let (mut arm, _) = rig();
arm.bones.push(bone(BoneId(40), ElementId(77), ElementId(78), Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)));
arm.sanitize();
assert_eq!(arm.bones.len(), 2, "every bone of a shape armature hangs from the shape");
let (mut arm, _) = rig();
arm.bones.push(bone(BoneId(41), N2, TAIL, Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)));
arm.sanitize();
assert!(arm.skin.is_none() || arm.bones.iter().all(|b| b.child != TAIL));
}
#[test]
fn hand_binding_survives_new_bones() {
let (mut arm, _) = rig();
let skin = arm.skin.as_mut().unwrap();
skin.points[1] = Binding { bones: vec![Influence(B2, 1.0)], manual: true };
skin.points[2] = Binding { bones: vec![], manual: true };
arm.bones.push(bone(BoneId(22), N2, ElementId(32), Vec2::new(200.0, 0.0), Vec2::new(210.0, 0.0)));
rebind(&mut arm);
let skin = arm.skin.as_ref().unwrap();
assert_eq!(skin.points[1].bones, vec![Influence(B2, 1.0)], "kept as bound by hand");
assert!(skin.points[2].bones.is_empty(), "kept unbound");
// Taking its bone away sends a hand-bound anchor back to automatic.
let mut arm = arm.clone();
arm.bones.retain(|b| b.id != B2 && b.id != BoneId(22));
rebind(&mut arm);
assert_eq!(arm.skin.as_ref().unwrap().points[1].bones, vec![Influence(B1, 1.0)]);
}
/// Skinning cost: a shape of 2,000 anchors on 16 bones, posed (debug builds are slower).
#[test]
fn skinning_is_fast() {
let mut p = Path::new();
p.move_to(Vec2::new(0.0, -10.0));
for i in 1..1000 {
p.line_to(Vec2::new(i as f32 * 0.8, -10.0));
}
for i in (0..1000).rev() {
p.line_to(Vec2::new(i as f32 * 0.8, 10.0));
}
p.close();
let mut bones = Vec::new();
for i in 0..16u64 {
let parent = if i == 0 { TAIL } else { ElementId(100 + i - 1) };
bones.push(bone(BoneId(200 + i), parent, ElementId(100 + i), Vec2::new(50.0 * i as f32, 0.0), Vec2::new(50.0 * (i + 1) as f32, 0.0)));
}
let mut arm = Armature { bones, skin: Some(Skin::new(TAIL, Arc::new(p))), ..Default::default() };
let t = std::time::Instant::now();
rebind(&mut arm);
let bind = t.elapsed();
let pose = Pose(arm.bones.iter().map(|b| crate::JointAngle::new(b.id, 0.1)).collect());
let t = std::time::Instant::now();
for _ in 0..10 {
std::hint::black_box(deform(&arm, &pose));
}
let per = t.elapsed() / 10;
println!("2,000 anchors × 16 bones: bind {bind:?}, deform {per:?}");
assert!(per.as_millis() < 50, "{per:?}");
}
+4 -3
View File
@@ -445,7 +445,7 @@ fn sounding_symbols(doc: &Document) -> HashSet<SymbolId> {
if k.sound.is_some() && set.insert(sym.id) {
queue.push(sym.id);
}
for el in &k.elements {
for el in crate::expand_groups(&k.elements).iter() {
if let ElementKind::Symbol { symbol, .. } = &el.kind {
shown_in.entry(*symbol).or_default().push(sym.id);
}
@@ -485,7 +485,8 @@ impl<'a> Layout<'a> {
if let Some(fs) = &k.sound {
self.sound(fs, k, st, gain);
}
for el in &k.elements {
// (A symbol inside a group plays as if it were on the group's layer, ADR 0073.)
for el in crate::expand_groups(&k.elements).iter() {
if matches!(&el.kind, ElementKind::Symbol { symbol, .. } if self.sounding.contains(symbol)) {
self.instance(layer, k, el, st, gain, depth);
}
@@ -565,7 +566,7 @@ impl<'a> Layout<'a> {
let enters = pa == s0 || (pa == st.l0 && st.enters);
self.looped(tl, g, (pa - s0) % len, n, len, enters, gain, depth);
}
// Buttons wait for the pointer: their sounds are not in this slice (ADR 0039).
// Buttons sound only under the pointer, in the interactive player (ADR 0057).
(SymbolKind::Button, _) => {}
}
}
+2 -2
View File
@@ -194,7 +194,7 @@ fn nested(kind: SymbolKind, len: u32, inner: &[(u32, u32, Option<FrameSound>)],
// Pad the symbol's timeline to `len` frames with a second, silent layer.
let mut pad = Layer::new(LayerId(11), "pad");
pad.keyframes = vec![Arc::new(Keyframe::new(0, len))];
d.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } }));
d.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } }));
let mut l = Layer::new(LayerId(1), "outer");
l.keyframes = instances
.iter()
@@ -347,7 +347,7 @@ fn start_skips_a_playing_sound_and_stop_cuts_it() {
fn scenes_play_in_order_guides_are_silent_and_missing_sounds_are_skipped() {
let mut d = doc_with(&[(0, 3, with(SoundSync::Event, 1, false))], vec![ramp_sound(7, 100)]);
let first = d.scenes[0].clone();
d.scenes.insert(0, Arc::new(Scene { name: "Intro".into(), timeline: first.timeline.clone() }));
d.scenes.insert(0, Arc::new(Scene { name: "Intro".into(), timeline: first.timeline.clone(), guides: Vec::new() }));
assert_eq!(spans(&voices(&d, 8000)), vec![(VoiceKind::Event, 0, 100), (VoiceKind::Event, 3000, 3100)]);
Arc::make_mut(&mut d.timeline_mut(0).layers[0]).kind = LayerKind::Guide;
assert_eq!(voices(&d, 8000).len(), 1, "guide layers are not exported, so not heard");
+186
View File
@@ -0,0 +1,186 @@
//! Bone springs (ADR 0084): secondary motion as a pure function of time.
//!
//! A bone with a [`Spring`](crate::armature::Spring) lags behind the pose it is keyed to and
//! swings past it when the bones it hangs from move (or its own keyed angle changes), then
//! settles back. Each sprung bone carries an angle `φ` off its keyed angle, driven by how the
//! keyed motion *accelerates* (the joint's linear acceleration across the bone and the keyed
//! direction's angular acceleration: the inertia of a pendulum on a moving pivot) and pulled
//! back by a damped spring:
//!
//! ```text
//! φ'' = −θ_key'' − (a_joint · n) / L − ω² φ − 2ζω φ'
//! ```
//!
//! where `θ_key` is the bone's world direction as keyed (relative to its parent as it swings, so
//! springs chain), `n` the bone's normal and `L` its length. Strength sets the natural frequency
//! `ω` (half a swing to ten swings a second), damping the ratio `ζ`.
//!
//! **No simulation state is stored.** [`sprung_pose`] re-runs the motion from a fixed start for
//! every frame it is asked about: at most [`SPRING_SECONDS`] back (and never before the run of
//! keyframes the frame is on), assuming the armature was still before that. Every step is a
//! fixed function of the frames before it, so seeking to a frame gives exactly the bits playing
//! to it does, and every export, the player and the stage agree. Steps are bounded (at most
//! [`MAX_SPRING_FRAMES`] frames of [`SUBSTEPS`] each), and the integrator is backward Euler, which
//! is stable for any strength, damping and frame rate. Damping 1, strength 0 or springs turned
//! off on the armature give the keyed pose bit for bit.
use crate::armature::{self, Armature, Pose};
use crate::{ElementId, Layer};
use anicraft_geom::{Affine, Vec2};
use std::collections::HashMap;
use std::f32::consts::{PI, TAU};
/// How far back a spring's motion is followed (seconds). Motion in the older half of that
/// window counts less and less ([`taper`]), so every swing has died away this long after the
/// motion that caused it, smoothly, with no jump when it drops out of the window.
pub const SPRING_SECONDS: f32 = 6.0;
/// Most frames one spring evaluation follows (bounds the work at high frame rates).
pub const MAX_SPRING_FRAMES: u32 = 720;
/// Integration steps per frame.
pub const SUBSTEPS: u32 = 4;
/// Farthest a spring swings a bone off its keyed angle (radians, half a turn either way).
pub const MAX_SWING: f32 = PI;
/// Natural frequency (radians a second) of strength `s` (0…1): 0.5 Hz up to 10 Hz, evenly
/// spread in pitch.
pub fn omega(strength: f32) -> f32 {
TAU * 0.5 * 20f32.powf(strength.clamp(0.0, 1.0))
}
/// Damping ratio of damping `d` (0…1): 0 swings on, ⅔ is critical (no overshoot), 1 is
/// infinite (the swing never starts).
pub fn zeta(damping: f32) -> f32 {
let d = damping.clamp(0.0, 1.0);
if d >= 1.0 { f32::INFINITY } else { 0.5 * d / (1.0 - d) }
}
/// How much motion `age` frames old still drives a spring, in a window of `window` frames: all of
/// it in the newer half, then easing smoothly to none at the window's start.
pub fn taper(age: u32, window: u32) -> f32 {
let x = age as f32 / window.max(1) as f32;
if x <= 0.5 {
return 1.0;
}
let s = ((x - 0.5) * 2.0).clamp(0.0, 1.0);
1.0 - s * s * (3.0 - 2.0 * s)
}
/// The frame rate springs run at, from the stage's (sane, 1–240 fps).
fn sane_fps(fps: f32) -> f32 {
if fps.is_finite() && fps > 0.0 { fps.clamp(1.0, 240.0) } else { 24.0 }
}
/// The first frame of the unbroken run of non-empty keyframes `frame` is on.
fn run_start(layer: &Layer, frame: u32) -> Option<u32> {
let mut i = layer.keyframe_index_at(frame)?;
while i > 0 {
let (Some(prev), Some(cur)) = (layer.keyframes.get(i - 1), layer.keyframes.get(i)) else { break };
if prev.end() != cur.start || prev.elements.is_empty() {
break;
}
i -= 1;
}
layer.keyframes.get(i).map(|k| k.start)
}
/// Wraps an angle difference into (−π, π].
fn wrap(a: f32) -> f32 {
let w = (a + PI).rem_euclid(TAU) - PI;
if w <= -PI { w + TAU } else { w }
}
/// What a sprung bone remembers between steps of one evaluation (never stored anywhere).
#[derive(Clone, Copy, Default)]
struct Swing {
phi: f32,
vel: f32,
/// The joint and keyed direction one and two frames back.
hist: Option<[(Vec2, f32); 2]>,
}
/// The pose layer `layer` shows at `frame` at `fps` frames a second: its keyed pose
/// ([`armature::pose_at`]) with each sprung bone swung by its spring. Exactly the keyed pose
/// when no spring moves anything. `None` where [`armature::pose_at`] is.
pub fn sprung_pose(layer: &Layer, frame: u32, fps: f32) -> Option<Pose> {
let keyed = armature::pose_at(layer, frame)?;
let Some(arm) = layer.armature.as_deref().filter(|a| a.has_springs()) else { return Some(keyed) };
let fps = sane_fps(fps);
let window = ((fps * SPRING_SECONDS).ceil() as u32).min(MAX_SPRING_FRAMES);
let run = run_start(layer, frame).unwrap_or(frame);
let first = run.max(frame.saturating_sub(window));
// Two frames before the window (where there are any) only give the motion's speed, so a
// window that starts mid-move doesn't kick the springs as if the move began there.
let warm = run.max(first.saturating_sub(2));
let mut swings = vec![Swing::default(); arm.bones.len()];
for f in warm..=frame {
let Some(pose) = armature::pose_at(layer, f) else { continue };
let Some((_, els)) = crate::eval::evaluate_tweened(layer, f, None) else { continue };
let world: HashMap<ElementId, Affine> = els.iter().map(|e| (e.id, e.transform)).collect();
let weight = if f >= first { taper(frame - f, window) } else { 0.0 };
step(arm, world, &pose, &mut swings, 1.0 / fps, weight);
}
let mut out = keyed.allowed(arm);
for (b, s) in arm.bones.iter().zip(&swings) {
if s.phi != 0.0 && b.live_spring().is_some() {
out.set(b.id, b.allow(keyed.angle(b.id) + s.phi));
}
}
Some(out)
}
/// One frame: places the armature from the roots in `world` (the keyframe's own transforms)
/// by `pose`, each sprung bone swung by its spring, which is advanced `dt` seconds with the
/// frame's motion counting `weight` (0: the frame only records the motion).
fn step(arm: &Armature, mut world: HashMap<ElementId, Affine>, pose: &Pose, swings: &mut [Swing], dt: f32, weight: f32) {
let nodes = arm.skin.is_some();
for (b, sw) in arm.bones.iter().zip(swings.iter_mut()) {
let Some(wp) = world.get(&b.parent).copied() else { continue };
if !nodes && !world.contains_key(&b.child) {
continue;
}
let (key, slide) = (b.allow(pose.angle(b.id)), b.allow_slide(pose.slide(b.id)));
let (j, keyed) = armature::joint(b, &wp, key, slide);
let mut angle = key;
if let Some(sp) = b.live_spring() {
let tip = keyed.apply(b.tail) - j;
let len = tip.length();
let theta = tip.y.atan2(tip.x);
if let Some([(j1, t1), (j2, t2)]) = sw.hist.filter(|_| weight > 0.0) {
// The keyed motion's accelerations over the last frame, as finite differences.
let alpha = (wrap(theta - t1) - wrap(t1 - t2)) / (dt * dt);
let acc = (j - j1 - (j1 - j2)) * (1.0 / (dt * dt));
let (w, z) = (omega(sp.strength), zeta(sp.damping));
let h = dt / SUBSTEPS as f32;
for _ in 0..SUBSTEPS {
let dir = Vec2::new((theta + sw.phi).cos(), (theta + sw.phi).sin());
let lin = if len > 1e-3 { acc.dot(dir.perp()) / len } else { 0.0 };
let drive = -(alpha + lin) * weight;
// Backward Euler: stable for any stiffness and damping.
sw.vel = (sw.vel + h * (drive - w * w * sw.phi)) / (1.0 + h * 2.0 * z * w + h * h * w * w);
sw.phi += h * sw.vel;
}
if !(sw.phi.is_finite() && sw.vel.is_finite()) {
(sw.phi, sw.vel) = (0.0, 0.0);
}
if sw.phi.abs() > MAX_SWING {
(sw.phi, sw.vel) = (sw.phi.clamp(-MAX_SWING, MAX_SWING), 0.0);
}
// A joint limit stops the swing.
let allowed = b.allow(key + sw.phi);
if allowed != key + sw.phi {
(sw.phi, sw.vel) = (allowed - key, 0.0);
}
}
sw.hist = Some([(j, theta), sw.hist.map_or((j, theta), |h| h[0])]);
angle = b.allow(key + sw.phi);
}
let wc = if angle == key { keyed } else { armature::joint(b, &wp, angle, slide).1 };
if wc.is_finite() {
world.insert(b.child, wc);
}
}
}
#[cfg(test)]
#[path = "spring_tests.rs"]
mod tests;
+209
View File
@@ -0,0 +1,209 @@
//! Bone springs (ADR 0084): secondary motion that is a pure function of time.
use super::*;
use crate::armature::{Bone, BoneId, Limits, Spring};
use crate::{BlendMode, ColorEffect, Document, Element, ElementKind, Keyframe, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Symbol, SymbolId, SymbolKind, Timeline, Tween, evaluate};
use anicraft_geom::Path;
use std::sync::Arc;
const ROOT: ElementId = ElementId(10);
const ARM: ElementId = ElementId(11);
const HAND: ElementId = ElementId(12);
const B1: BoneId = BoneId(20);
const B2: BoneId = BoneId(21);
const SEG: SymbolId = SymbolId(1);
fn instance(id: ElementId, x: f32, y: f32) -> Arc<Element> {
let kind = ElementKind::Symbol { symbol: SEG, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() };
Arc::new(Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind })
}
fn bone(id: BoneId, parent: ElementId, child: ElementId) -> Bone {
Bone::new(id, parent, child, Vec2::new(100.0, 0.0), Vec2::new(100.0, 0.0), Affine::translate(100.0, 0.0))
}
/// A tail of two bones lying to the right of its body (the root), which drops 300 px between
/// frames 0 and 10 and then holds still until frame 300. Both bones have `spring`.
fn tail(spring: Option<Spring>) -> Layer {
let mut b1 = bone(B1, ROOT, ARM);
let mut b2 = bone(B2, ARM, HAND);
b1.spring = spring;
b2.spring = spring;
let arm = crate::armature::Armature { bones: vec![b1, b2], ..Default::default() };
let mut l = Layer::new(LayerId(1), "Armature_1");
l.kind = LayerKind::Armature;
l.armature = Some(Arc::new(arm));
let mut a = Keyframe::new(0, 10);
a.elements = vec![instance(ROOT, 100.0, 100.0), instance(ARM, 200.0, 100.0), instance(HAND, 300.0, 100.0)];
a.tween = Some(Tween::default());
let mut b = Keyframe::new(10, 290);
b.elements = vec![instance(ROOT, 100.0, 400.0), instance(ARM, 200.0, 400.0), instance(HAND, 300.0, 400.0)];
l.keyframes = vec![Arc::new(a), Arc::new(b)];
l
}
const BOUNCY: Spring = Spring { strength: 0.4, damping: 0.25 };
fn bits(p: &Pose) -> Vec<(u64, u32, u32, u32)> {
p.0.iter().map(|j| (j.bone.0, j.angle.to_bits(), j.x.to_bits(), j.y.to_bits())).collect()
}
#[test]
fn a_spring_swings_the_tail_behind_the_motion_and_back() {
let l = tail(Some(BOUNCY));
// As the body drops, the tail lags: it turns up (a negative angle, y down).
let early = sprung_pose(&l, 5, 24.0).unwrap();
assert!(early.angle(B1) < -0.05, "lags at {}°", early.angle(B1).to_degrees());
// Once the body stops, the tail swings on past the keyed pose (down), then settles.
let swing: Vec<f32> = (10..60).map(|f| sprung_pose(&l, f, 24.0).unwrap().angle(B1)).collect();
assert!(swing.iter().any(|a| *a > 0.05), "overshoots: {swing:?}");
let late = sprung_pose(&l, 110, 24.0).unwrap();
assert!(late.angle(B1).abs() < 0.01 && late.angle(B2).abs() < 0.01, "settling: {}° {}°", late.angle(B1).to_degrees(), late.angle(B2).to_degrees());
// The keyed pose is untouched: springs are evaluated, never stored.
assert_eq!(crate::armature::pose_at(&l, 5).unwrap().angle(B1), 0.0);
}
#[test]
fn the_spring_settles_to_the_keyed_pose_exactly() {
let l = tail(Some(BOUNCY));
// A window's length after the body stopped, the shown pose is the keyed one bit for bit.
let after = 10 + (24.0 * SPRING_SECONDS) as u32 + 3;
assert_eq!(bits(&sprung_pose(&l, after, 24.0).unwrap()), bits(&crate::armature::pose_at(&l, after).unwrap().allowed(l.armature.as_deref().unwrap())));
// Before anything moves nothing swings.
assert_eq!(sprung_pose(&l, 0, 24.0).unwrap().angle(B1), 0.0);
}
#[test]
fn seeking_equals_playing_bit_for_bit() {
let l = tail(Some(BOUNCY));
let played: Vec<_> = (0..140).map(|f| bits(&sprung_pose(&l, f, 24.0).unwrap())).collect();
// Any order, any number of times: the same bits.
let mut order: Vec<u32> = (0..140).collect();
order.reverse();
order.rotate_left(37);
for f in order {
assert_eq!(bits(&sprung_pose(&l, f, 24.0).unwrap()), played[f as usize], "frame {f}");
}
}
#[test]
fn damping_one_strength_zero_and_springs_off_are_no_spring() {
let keyed = tail(None);
let cases = [tail(Some(Spring { strength: 0.6, damping: 1.0 })), tail(Some(Spring { strength: 0.0, damping: 0.2 })), {
let mut l = tail(Some(BOUNCY));
let mut arm = (**l.armature.as_ref().unwrap()).clone();
arm.springs_off = true;
l.armature = Some(Arc::new(arm));
l
}];
for l in &cases {
for f in 0..60 {
assert_eq!(bits(&sprung_pose(l, f, 24.0).unwrap()), bits(&sprung_pose(&keyed, f, 24.0).unwrap()), "frame {f}");
let (a, b) = (crate::eval::evaluate_shown(l, f, None, 24.0).unwrap().1, crate::eval::evaluate_guided(&keyed, f, None).unwrap().1);
assert!(a.iter().zip(b.iter()).all(|(x, y)| x.transform == y.transform));
}
}
}
#[test]
fn heavier_damping_settles_sooner_and_a_stiffer_spring_lags_less() {
let swing = |s: Spring| (10..80).map(|f| sprung_pose(&tail(Some(s)), f, 24.0).unwrap().angle(B1).abs()).fold(0.0f32, f32::max);
let after = |s: Spring, f: u32| sprung_pose(&tail(Some(s)), f, 24.0).unwrap().angle(B1).abs();
assert!(after(Spring { damping: 0.6, ..BOUNCY }, 40) < after(BOUNCY, 40) + 1e-6);
let lag = |s: Spring| sprung_pose(&tail(Some(s)), 5, 24.0).unwrap().angle(B1).abs();
assert!(lag(Spring { strength: 0.9, ..BOUNCY }) < lag(BOUNCY));
assert!(swing(BOUNCY) <= MAX_SWING);
}
#[test]
fn the_same_motion_in_seconds_swings_alike_at_any_frame_rate() {
// At 48 fps the drop takes 20 frames: the same second-based motion.
let mut l48 = tail(Some(BOUNCY));
Arc::make_mut(&mut l48.keyframes[0]).duration = 20;
Arc::make_mut(&mut l48.keyframes[1]).start = 20;
let (a, b) = (sprung_pose(&tail(Some(BOUNCY)), 20, 24.0).unwrap().angle(B1), sprung_pose(&l48, 40, 48.0).unwrap().angle(B1));
assert!((a - b).abs() < 0.25 * a.abs().max(b.abs()), "{a} vs {b}");
}
#[test]
fn joint_limits_stop_a_spring() {
let mut l = tail(Some(Spring { strength: 0.2, damping: 0.0 }));
let mut arm = (**l.armature.as_ref().unwrap()).clone();
let lim = Limits { min: -0.05, max: 0.05 };
arm.bone_mut(B1).unwrap().limits = Some(lim);
l.armature = Some(Arc::new(arm));
for f in 0..120 {
let a = sprung_pose(&l, f, 24.0).unwrap().angle(B1);
assert!((lim.min..=lim.max).contains(&a), "frame {f}: {a}");
}
}
#[test]
fn hostile_springs_and_frame_rates_stay_bounded() {
for s in [Spring { strength: 1.0, damping: 0.0 }, Spring { strength: 1e-9, damping: 0.0 }, Spring { strength: 0.5, damping: 0.999_999 }] {
let l = tail(Some(s));
for fps in [f32::NAN, 0.0, -5.0, 1.0, 1e9, 240.0] {
for f in [0, 3, 9, 10, 11, 50, 299, 300, 100_000] {
if let Some(p) = sprung_pose(&l, f, fps) {
assert!(p.0.iter().all(|j| j.angle.is_finite() && j.angle.abs() <= MAX_SWING + 1e-3), "{s:?} at {fps} fps, frame {f}: {p:?}");
}
}
}
}
// Loading clamps what a file says.
assert_eq!(Spring { strength: 7.0, damping: -3.0 }.sanitized(), Some(Spring { strength: 1.0, damping: 0.0 }));
assert_eq!(Spring { strength: f32::NAN, damping: 0.5 }.sanitized(), None);
assert!(omega(f32::NAN).is_finite() || omega(f32::NAN).is_nan());
assert_eq!(zeta(1.0), f32::INFINITY);
}
#[test]
fn every_export_sees_the_spring() {
let mut d = Document::default();
let mut seg = Layer::new(LayerId(2), "seg");
let mut k = Keyframe::new(0, 1);
k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) }));
seg.keyframes = vec![Arc::new(k)];
d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(seg)] } }));
d.timeline_mut(0).layers = vec![Arc::new(tail(Some(BOUNCY)))];
d.sanitize();
let hand = |d: &Document, f: u32| evaluate(d, f).items.iter().find(|i| i.element == HAND).map(|i| i.transform.translation()).unwrap();
let mut still = d.clone();
Arc::make_mut(Arc::make_mut(&mut still.timeline_mut(0).layers[0]).armature.as_mut().unwrap()).springs_off = true;
assert!(hand(&d, 14).distance(hand(&still, 14)) > 2.0, "the display list draws the swing");
assert_eq!(hand(&d, 200), hand(&still, 200), "and the settled pose exactly");
// The file keeps the springs; older files (without them) read as before.
let json = serde_json::to_string(&d).unwrap();
assert!(json.contains("\"spring\""));
let back: Document = serde_json::from_str(&json).unwrap();
assert_eq!(back, d);
assert!(!serde_json::to_string(&still.timeline(0).layers[0].keyframes[0]).unwrap().contains("\"x\""), "poses without slides are written as before");
}
/// The cost of one frame with springs: the whole window is followed again for every frame.
#[test]
fn springs_are_fast_enough_to_play() {
// 16 sprung bones in a chain on a moving root.
let mut bones = Vec::new();
let mut a = Keyframe::new(0, 10);
let mut b = Keyframe::new(10, 290);
a.elements.push(instance(ElementId(1000), 0.0, 0.0));
b.elements.push(instance(ElementId(1000), 0.0, 300.0));
for i in 0..16u64 {
let (p, c) = (ElementId(1000 + i), ElementId(1001 + i));
bones.push(Bone { spring: Some(BOUNCY), ..bone(BoneId(5000 + i), p, c) });
a.elements.push(instance(c, 100.0 * (i + 1) as f32, 0.0));
b.elements.push(instance(c, 100.0 * (i + 1) as f32, 300.0));
}
a.tween = Some(Tween::default());
let mut l = Layer::new(LayerId(1), "Armature_1");
l.kind = LayerKind::Armature;
l.armature = Some(Arc::new(crate::armature::Armature { bones, ..Default::default() }));
l.keyframes = vec![Arc::new(a), Arc::new(b)];
let t = std::time::Instant::now();
for f in 150..160 {
std::hint::black_box(sprung_pose(&l, f, 24.0));
}
let per = t.elapsed() / 10;
println!("16 sprung bones, 24 fps ({} frames followed): {per:?} per frame", (24.0 * SPRING_SECONDS) as u32);
assert!(per < std::time::Duration::from_millis(250), "{per:?}");
}
+266
View File
@@ -0,0 +1,266 @@
//! The document's swatches (ADR 0078): saved colours and gradients, as Animate keeps them per
//! document in its Swatches panel.
//!
//! A swatch is a colour (with alpha) or a gradient's ramp and options, never its geometry: a
//! gradient swatch poured on a shape is fitted to it, as a new gradient is. A new document
//! starts with [`default_set`]; a document file that has no swatches (every file before ADR
//! 0078) opens with that set too, and the set is not written while it is unchanged.
//!
//! GIMP palettes (`.gpl`, an open plain-text format) import through [`parse_gpl`].
use crate::{GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Spread, is_false, is_zero};
use serde::{Deserialize, Serialize};
/// Most swatches a document keeps (Animate's panel holds a few hundred at most).
pub const MAX_SWATCHES: usize = 1024;
/// Longest swatch name, in characters.
pub const MAX_SWATCH_NAME: usize = 128;
/// One saved colour or gradient.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Swatch {
/// Shown on hover (empty: the colour's hex).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
pub paint: SwatchPaint,
}
/// What a swatch holds.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SwatchPaint {
Solid {
color: Rgba,
},
Linear {
stops: Vec<GradientStop>,
#[serde(default, skip_serializing_if = "Spread::is_pad")]
spread: Spread,
#[serde(default, skip_serializing_if = "is_false")]
linear_rgb: bool,
},
Radial {
stops: Vec<GradientStop>,
#[serde(default, skip_serializing_if = "Spread::is_pad")]
spread: Spread,
#[serde(default, skip_serializing_if = "is_false")]
linear_rgb: bool,
#[serde(default, skip_serializing_if = "is_zero")]
focal: f32,
},
}
impl SwatchPaint {
/// The swatch of a fill: its colour, or its gradient's ramp and options (where it lies is
/// left behind). `None` for a bitmap fill, which a swatch can't hold.
pub fn from_paint(p: &Paint) -> Option<SwatchPaint> {
match p {
Paint::Solid(c) => Some(SwatchPaint::Solid { color: *c }),
Paint::Linear { stops, spread, linear_rgb, .. } => Some(SwatchPaint::Linear { stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb }),
Paint::Radial { stops, spread, linear_rgb, focal, .. } => Some(SwatchPaint::Radial { stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb, focal: *focal }),
Paint::Bitmap { .. } => None,
}
}
/// Its colour, or its gradient's first stop.
pub fn primary_color(&self) -> Rgba {
match self {
SwatchPaint::Solid { color } => *color,
SwatchPaint::Linear { stops, .. } | SwatchPaint::Radial { stops, .. } => stops.first().map_or(Rgba::BLACK, |s| s.color),
}
}
pub fn stops(&self) -> Option<&[GradientStop]> {
match self {
SwatchPaint::Solid { .. } => None,
SwatchPaint::Linear { stops, .. } | SwatchPaint::Radial { stops, .. } => Some(stops),
}
}
pub fn is_gradient(&self) -> bool {
!matches!(self, SwatchPaint::Solid { .. })
}
/// The key `paint.set_fill` and swatch files use for its kind.
pub fn kind(&self) -> &'static str {
match self {
SwatchPaint::Solid { .. } => "solid",
SwatchPaint::Linear { .. } => "linear",
SwatchPaint::Radial { .. } => "radial",
}
}
/// Repaired: colours in range, 2 to [`MAX_GRADIENT_STOPS`] stops in order, the focal point
/// in range. `None` when it can't be (a gradient with fewer than two stops).
pub fn sanitized(&self) -> Option<SwatchPaint> {
let stops = |s: &[GradientStop]| -> Option<Vec<GradientStop>> {
if s.len() < 2 {
return None;
}
let mut v: Vec<GradientStop> = s.iter().take(MAX_GRADIENT_STOPS).map(|g| GradientStop { offset: if g.offset.is_finite() { g.offset.clamp(0.0, 1.0) } else { 0.0 }, color: g.color.sanitized() }).collect();
v.sort_by(|a, b| a.offset.total_cmp(&b.offset));
Some(v)
};
Some(match self {
SwatchPaint::Solid { color } => SwatchPaint::Solid { color: color.sanitized() },
SwatchPaint::Linear { stops: s, spread, linear_rgb } => SwatchPaint::Linear { stops: stops(s)?, spread: *spread, linear_rgb: *linear_rgb },
SwatchPaint::Radial { stops: s, spread, linear_rgb, focal } => SwatchPaint::Radial { stops: stops(s)?, spread: *spread, linear_rgb: *linear_rgb, focal: if focal.is_finite() { focal.clamp(-MAX_FOCAL, MAX_FOCAL) } else { 0.0 } },
})
}
}
impl Swatch {
pub fn new(name: &str, paint: SwatchPaint) -> Swatch {
Swatch { name: clean_name(name), paint }
}
pub fn solid(c: Rgba) -> Swatch {
Swatch { name: String::new(), paint: SwatchPaint::Solid { color: c } }
}
/// Repaired (see [`SwatchPaint::sanitized`]), its name trimmed and bounded.
pub fn sanitized(&self) -> Option<Swatch> {
Some(Swatch { name: clean_name(&self.name), paint: self.paint.sanitized()? })
}
}
/// A swatch name: one line, trimmed, at most [`MAX_SWATCH_NAME`] characters.
pub fn clean_name(s: &str) -> String {
s.chars().filter(|c| !c.is_control()).take(MAX_SWATCH_NAME).collect::<String>().trim().to_string()
}
fn stop(offset: f32, rgb: u32) -> GradientStop {
GradientStop { offset, color: Rgba::hex(rgb) }
}
/// A new document's swatches: greys from black to white, the primaries and secondaries (the
/// picker's web-safe palette has the rest), then seven gradients.
pub fn default_set() -> Vec<Swatch> {
let colours = [0x000000, 0x333333, 0x666666, 0x999999, 0xcccccc, 0xffffff, 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0x00ffff, 0xff00ff];
let mut v: Vec<Swatch> = colours.iter().map(|c| Swatch::solid(Rgba::hex(*c))).collect();
let linear = |stops| SwatchPaint::Linear { stops, spread: Spread::Pad, linear_rgb: false };
let radial = |stops| SwatchPaint::Radial { stops, spread: Spread::Pad, linear_rgb: false, focal: 0.0 };
v.extend([
Swatch::new("Black to white", linear(vec![stop(0.0, 0x000000), stop(1.0, 0xffffff)])),
Swatch::new("White to black", radial(vec![stop(0.0, 0xffffff), stop(1.0, 0x000000)])),
Swatch::new("Red ball", radial(vec![stop(0.0, 0xff8080), stop(1.0, 0x990000)])),
Swatch::new("Green ball", radial(vec![stop(0.0, 0x80ff80), stop(1.0, 0x006600)])),
Swatch::new("Blue ball", radial(vec![stop(0.0, 0x80b0ff), stop(1.0, 0x000099)])),
Swatch::new("Spectrum", linear(vec![stop(0.0, 0xff0000), stop(0.2, 0xffff00), stop(0.4, 0x00ff00), stop(0.6, 0x00ffff), stop(0.8, 0x0000ff), stop(1.0, 0xff00ff)])),
Swatch::new("Gold", linear(vec![stop(0.0, 0xfff2a8), stop(0.5, 0xd4a017), stop(1.0, 0x7a5200)])),
]);
v
}
/// Whether `v` is exactly the default set (then a document file leaves it out).
pub fn is_default_set(v: &[Swatch]) -> bool {
let d = default_set();
v.len() == d.len() && v.iter().zip(&d).all(|(a, b)| a == b)
}
/// Largest palette file read, in bytes.
pub const MAX_PALETTE_BYTES: usize = 1 << 20;
/// Reads a GIMP palette (`.gpl`): a `GIMP Palette` line, optional `Name:` and `Columns:`
/// lines and `#` comments, then one colour per line, `R G B` (0 to 255) and an optional name.
/// Lines that aren't colours are skipped; at most [`MAX_SWATCHES`] colours are read. The
/// palette's own name comes back with the colours.
pub fn parse_gpl(text: &str) -> Result<(String, Vec<Swatch>), String> {
if text.len() > MAX_PALETTE_BYTES {
return Err("the palette file is too large".into());
}
let mut lines = text.lines();
let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim();
if first != "GIMP Palette" {
return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into());
}
let mut name = String::new();
let mut out = Vec::new();
for line in lines {
let l = line.trim();
if l.is_empty() || l.starts_with('#') {
continue;
}
if let Some(n) = l.strip_prefix("Name:") {
name = clean_name(n);
continue;
}
if l.starts_with("Columns:") || l.starts_with("Channels:") {
continue;
}
let mut parts = l.split_whitespace();
let channel = |s: Option<&str>| s.and_then(|v| v.parse::<u16>().ok()).filter(|v| *v <= 255).map(|v| f32::from(v) / 255.0);
let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue };
let rest: Vec<&str> = parts.collect();
let label = rest.join(" ");
// GIMP names unnamed colours "Untitled"; the hex says more.
let label = if label == "Untitled" { String::new() } else { label };
out.push(Swatch::new(&label, SwatchPaint::Solid { color: Rgba::new(r, g, b, 1.0) }));
if out.len() >= MAX_SWATCHES {
break;
}
}
if out.is_empty() {
return Err("the palette has no colours in it".into());
}
Ok((name, out))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_default_set_is_valid_and_recognised() {
let d = default_set();
assert_eq!(d.len(), 19);
assert!(is_default_set(&d));
assert!(d.iter().all(|s| s.sanitized().as_ref() == Some(s)), "nothing to repair");
assert_eq!(d.iter().filter(|s| s.paint.is_gradient()).count(), 7);
let mut other = d.clone();
other.swap(0, 1);
assert!(!is_default_set(&other));
assert!(!is_default_set(&[]));
}
#[test]
fn swatches_are_repaired() {
let bad = Swatch { name: " a\nb ".into(), paint: SwatchPaint::Radial { stops: vec![GradientStop { offset: 2.0, color: Rgba::new(f32::NAN, 9.0, -1.0, 1.0) }, GradientStop { offset: -1.0, color: Rgba::WHITE }], spread: Spread::Pad, linear_rgb: false, focal: 5.0 } };
let s = bad.sanitized().unwrap();
assert_eq!(s.name, "ab");
let SwatchPaint::Radial { stops, focal, .. } = &s.paint else { panic!() };
assert_eq!((stops[0].offset, stops[1].offset), (0.0, 1.0), "in order and in range");
assert_eq!(stops[1].color, Rgba::new(0.0, 1.0, 0.0, 1.0));
assert_eq!(*focal, MAX_FOCAL);
let one = Swatch { name: String::new(), paint: SwatchPaint::Linear { stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }], spread: Spread::Pad, linear_rgb: false } };
assert!(one.sanitized().is_none(), "a gradient needs two stops");
assert_eq!(clean_name(&"x".repeat(500)).chars().count(), MAX_SWATCH_NAME);
}
#[test]
fn a_swatch_keeps_a_fills_ramp_not_its_geometry() {
let p = Paint::linear(crate::Vec2::new(5.0, 5.0), crate::Vec2::new(50.0, 5.0), vec![stop(0.0, 0xff0000), stop(1.0, 0x0000ff)]);
let s = SwatchPaint::from_paint(&p).unwrap();
assert_eq!(s.kind(), "linear");
assert_eq!(s.primary_color(), Rgba::hex(0xff0000));
assert!(SwatchPaint::from_paint(&Paint::Bitmap { bitmap: crate::BitmapId(1), repeat: true, matrix: crate::Affine::IDENTITY }).is_none());
}
#[test]
fn gimp_palettes_are_read() {
let text = "GIMP Palette\nName: Brand\nColumns: 4\n# a comment\n255 0 0\tCrimson red\n 0 128 255 Untitled\n300 0 0 too bright\nnot a colour\n\n10 20 30\n";
let (name, sw) = parse_gpl(text).unwrap();
assert_eq!(name, "Brand");
assert_eq!(sw.len(), 3);
assert_eq!(sw[0].name, "Crimson red");
assert_eq!(sw[0].paint, SwatchPaint::Solid { color: Rgba::hex(0xff0000) });
assert_eq!(sw[1].name, "", "GIMP's Untitled shows as the hex");
assert_eq!(sw[2].paint.primary_color().to_hex(), "#0a141e");
// A byte-order mark and Windows line ends are fine.
assert!(parse_gpl("\u{feff}GIMP Palette\r\n1 2 3\r\n").is_ok());
for bad in ["", "JASC-PAL\n0 0 0", "GIMP Palette\nName: empty\n", "GIMP Palette\n1 2\n"] {
assert!(parse_gpl(bad).is_err(), "{bad:?}");
}
let many = format!("GIMP Palette\n{}", "1 2 3\n".repeat(MAX_SWATCHES + 10));
assert_eq!(parse_gpl(&many).unwrap().1.len(), MAX_SWATCHES, "bounded");
assert!(parse_gpl(&"x".repeat(MAX_PALETTE_BYTES + 1)).is_err());
}
}
+329
View File
@@ -0,0 +1,329 @@
//! The templates AniCraft ships with (ADR 0065): small documents built by code, so nothing
//! binary is committed and every line of them is original work. Each sets up a stage size and
//! frame rate, named layers ready to draw on, and guides on a locked guide layer (shown while
//! editing, never in output). They open as new, untitled documents (`file.new_from_template`).
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, SymbolKind, Timeline};
use anicraft_geom::{Affine, Path, Vec2};
use std::sync::Arc;
/// A built-in template: its id (for commands), name and category (English; the shell
/// translates them where they are drawn), what it is for, and how it is built.
pub struct Template {
pub id: &'static str,
pub name: &'static str,
pub category: &'static str,
pub description: &'static str,
pub build: fn() -> Document,
}
/// Every built-in template, in the order the start screen shows them.
pub static TEMPLATES: [Template; 6] = [
Template { id: "banner-728x90", name: "Leaderboard banner", category: "Advertising", description: "A 728 × 90 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer", build: banner_728x90 },
Template { id: "banner-300x250", name: "Rectangle banner", category: "Advertising", description: "A 300 × 250 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer", build: banner_300x250 },
Template { id: "social-square", name: "Social square", category: "Social", description: "A 1080 × 1080 post at 30 fps, 15 seconds long, with a safe margin and thirds on a guide layer", build: social_square },
Template { id: "storyboard", name: "Storyboard 16:9", category: "Storyboard", description: "Six 2-second panels at 1920 × 1080, labelled Panel 1 to 6, with action- and title-safe areas", build: storyboard },
Template { id: "character-turnaround", name: "Character turnaround", category: "Character", description: "Front, three-quarter, side and back views side by side, on head-height guides eight heads tall", build: turnaround },
Template { id: "lip-sync", name: "Lip-sync mouth chart", category: "Character", description: "A Mouth graphic symbol with ten labelled mouth shapes to redraw, placed on a face guide", build: lip_sync },
];
/// The built-in template with this id.
pub fn find(id: &str) -> Option<&'static Template> {
TEMPLATES.iter().find(|t| t.id == id)
}
/// The colour guides are drawn in (the guide layer's colour too, so the stage shows them alike).
const GUIDE: u32 = 0x4fa3ff;
/// A second, quieter guide colour for secondary lines.
const GUIDE_SOFT: u32 = 0x9cc8ff;
fn blank(width: u32, height: u32, fps: f32) -> Document {
let mut d = Document { stage: Stage { width, height, fps, background: Rgba::WHITE }, ..Document::default() };
d.timeline_mut(0).layers.clear();
d
}
fn element(d: &mut Document, name: &str, transform: Affine, shape: Shape) -> Arc<Element> {
Arc::new(Element { id: ElementId(d.alloc_id()), name: name.into(), transform, color: ColorEffect::default(), kind: ElementKind::Shape(shape) })
}
/// A stroked line from `a` to `b`.
fn line(d: &mut Document, name: &str, a: (f32, f32), b: (f32, f32), color: u32, width: f32) -> Arc<Element> {
let mut p = Path::new();
p.move_to(Vec2::new(a.0, a.1)).line_to(Vec2::new(b.0, b.1));
element(d, name, Affine::IDENTITY, Shape { path: Arc::new(p), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false, warp: None })
}
/// A stroked rectangle outline, `(x, y, w, h)`.
fn outline(d: &mut Document, name: &str, (x, y, w, h): (f32, f32, f32, f32), color: u32, width: f32) -> Arc<Element> {
element(d, name, Affine::IDENTITY, Shape { path: Arc::new(Path::rect(x, y, w, h)), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false, warp: None })
}
/// A layer holding `elements` in one keyframe `frames` long.
fn layer(d: &mut Document, name: &str, kind: LayerKind, color: u32, frames: u32, elements: Vec<Arc<Element>>) -> Arc<Layer> {
let mut l = Layer::new(LayerId(d.alloc_id()), name);
l.kind = kind;
l.color = Rgba::hex(color);
// Guides stay put while drawing over them.
l.locked = kind == LayerKind::Guide;
let mut k = Keyframe::new(0, frames.max(1));
k.elements = elements;
l.keyframes = vec![Arc::new(k)];
Arc::new(l)
}
/// Drawing layers, empty, top first.
fn drawing_layers(d: &mut Document, names: &[&str], frames: u32) -> Vec<Arc<Layer>> {
let palette = [0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65];
names.iter().enumerate().map(|(i, n)| layer(d, n, LayerKind::Normal, palette[i % palette.len()], frames, Vec::new())).collect()
}
/// A banner: the safe area (inset by a tenth of the short edge) and the edge on a guide layer,
/// layers for the call to action, text and artwork, and a soft background.
fn banner(width: u32, height: u32) -> Document {
const FRAMES: u32 = 24 * 15;
let mut d = blank(width, height, 24.0);
let (w, h) = (width as f32, height as f32);
let m = (w.min(h) * 0.1).round();
let guides = vec![outline(&mut d, "Safe area", (m, m, w - 2.0 * m, h - 2.0 * m), GUIDE, 1.0), outline(&mut d, "Edge", (0.5, 0.5, w - 1.0, h - 1.0), GUIDE_SOFT, 1.0)];
let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)];
layers.extend(drawing_layers(&mut d, &["Call to action", "Text", "Artwork"], FRAMES));
let bg = element(&mut d, "background", Affine::IDENTITY, Shape::filled(Path::rect(0.0, 0.0, w, h), Paint::Solid(Rgba::hex(0xeef2f7))));
let mut back = layer(&mut d, "Background", LayerKind::Normal, 0x7e57c2, FRAMES, vec![bg]);
Arc::make_mut(&mut back).locked = true;
layers.push(back);
d.timeline_mut(0).layers = layers;
d
}
fn banner_728x90() -> Document {
banner(728, 90)
}
fn banner_300x250() -> Document {
banner(300, 250)
}
/// A square post: a safe margin, the thirds and the centre on a guide layer.
fn social_square() -> Document {
const FRAMES: u32 = 30 * 15;
let mut d = blank(1080, 1080, 30.0);
let s = 1080.0;
let m = 60.0;
let mut guides = vec![outline(&mut d, "Safe margin", (m, m, s - 2.0 * m, s - 2.0 * m), GUIDE, 2.0)];
for (i, t) in [s / 3.0, s * 2.0 / 3.0].into_iter().enumerate() {
guides.push(line(&mut d, &format!("Third {}", i + 1), (t, 0.0), (t, s), GUIDE_SOFT, 1.0));
guides.push(line(&mut d, &format!("Third {}", i + 3), (0.0, t), (s, t), GUIDE_SOFT, 1.0));
}
guides.push(line(&mut d, "Centre", (s / 2.0 - 20.0, s / 2.0), (s / 2.0 + 20.0, s / 2.0), GUIDE, 2.0));
guides.push(line(&mut d, "Centre", (s / 2.0, s / 2.0 - 20.0), (s / 2.0, s / 2.0 + 20.0), GUIDE, 2.0));
let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)];
layers.extend(drawing_layers(&mut d, &["Text", "Artwork", "Background"], FRAMES));
d.timeline_mut(0).layers = layers;
d
}
/// A storyboard for 16:9: the action-safe (93 %) and title-safe (90 %) areas and the centre on a
/// guide layer, and a Panels layer of six labelled 2-second keyframes (an animatic as it plays).
fn storyboard() -> Document {
const PANEL: u32 = 48;
const PANELS: u32 = 6;
let mut d = blank(1920, 1080, 24.0);
let (w, h) = (1920.0, 1080.0);
let safe = |d: &mut Document, name: &str, keep: f32, color: u32| {
let (mx, my) = (w * (1.0 - keep) / 2.0, h * (1.0 - keep) / 2.0);
outline(d, name, (mx, my, w - 2.0 * mx, h - 2.0 * my), color, 2.0)
};
let guides = vec![
safe(&mut d, "Action safe", 0.93, GUIDE),
safe(&mut d, "Title safe", 0.90, GUIDE_SOFT),
line(&mut d, "Centre", (w / 2.0 - 30.0, h / 2.0), (w / 2.0 + 30.0, h / 2.0), GUIDE, 2.0),
line(&mut d, "Centre", (w / 2.0, h / 2.0 - 30.0), (w / 2.0, h / 2.0 + 30.0), GUIDE, 2.0),
];
let total = PANEL * PANELS;
let guide = layer(&mut d, "Safe areas", LayerKind::Guide, GUIDE, total, guides);
let notes = layer(&mut d, "Notes", LayerKind::Normal, 0xffd54a, total, Vec::new());
let mut panels = Layer::new(LayerId(d.alloc_id()), "Panels");
panels.color = Rgba::hex(0xff6b4a);
panels.keyframes = (0..PANELS)
.map(|i| {
let mut k = Keyframe::new(i * PANEL, PANEL);
k.label = format!("Panel {}", i + 1);
Arc::new(k)
})
.collect();
d.timeline_mut(0).layers = vec![guide, notes, Arc::new(panels)];
d
}
/// A turnaround: five views side by side (a centre line each) on horizontal lines a head
/// apart, eight heads from the top of the head to the ground, and a layer per view.
fn turnaround() -> Document {
let mut d = blank(1920, 1080, 24.0);
let (left, right, top, ground) = (60.0, 1860.0, 120.0, 960.0);
let head = (ground - top) / 8.0;
let mut guides = Vec::new();
for i in 0..=8 {
let y = top + head * i as f32;
let (color, width) = if i == 0 || i == 8 { (GUIDE, 2.0) } else { (GUIDE_SOFT, 1.0) };
let name = match i {
0 => "Top of head".to_string(),
8 => "Ground".to_string(),
n => format!("Head {n}"),
};
guides.push(line(&mut d, &name, (left, y), (right, y), color, width));
}
let views = ["Front", "Three-quarter", "Side", "Three-quarter back", "Back"];
let col = (right - left) / views.len() as f32;
for (i, v) in views.iter().enumerate() {
let x = left + col * (i as f32 + 0.5);
guides.push(line(&mut d, v, (x, top - 30.0), (x, ground + 30.0), GUIDE, 1.5));
}
let mut layers = vec![layer(&mut d, "Turnaround guides", LayerKind::Guide, GUIDE, 1, guides)];
layers.extend(drawing_layers(&mut d, &views, 1));
d.timeline_mut(0).layers = layers;
d
}
/// The mouth shapes of a lip-sync chart, as frame labels and placeholder shapes to redraw.
pub const MOUTHS: [&str; 10] = ["Rest", "AI", "E", "O", "U", "CDGKNRSThYZ", "FV", "L", "MBP", "WQ"];
/// A lip-sync chart: a Mouth graphic symbol with a labelled keyframe per mouth shape (each with
/// a simple placeholder), placed at Single Frame on a face guide, so each keyframe of the Mouth
/// layer picks a shape by its first frame.
fn lip_sync() -> Document {
const FRAMES: u32 = 24;
let mut d = blank(1280, 720, 24.0);
let lips = Rgba::hex(0x8e3b46);
let mouth = |path: Path| Shape::filled(path, Paint::Solid(lips)).with_stroke(Rgba::hex(0x5a1f28), 3.0);
let shapes = [
mouth(Path::rounded_rect(-50.0, -4.0, 100.0, 8.0, 4.0)),
mouth(Path::ellipse(0.0, 0.0, 55.0, 35.0)),
mouth(Path::ellipse(0.0, 0.0, 60.0, 20.0)),
mouth(Path::ellipse(0.0, 0.0, 35.0, 40.0)),
mouth(Path::ellipse(0.0, 0.0, 22.0, 26.0)),
mouth(Path::rounded_rect(-55.0, -14.0, 110.0, 28.0, 12.0)),
mouth(Path::rounded_rect(-50.0, -10.0, 100.0, 20.0, 8.0)),
mouth(Path::ellipse(0.0, 0.0, 45.0, 30.0)),
mouth(Path::rounded_rect(-50.0, -3.0, 100.0, 6.0, 3.0)),
mouth(Path::ellipse(0.0, 0.0, 18.0, 20.0)),
];
let sym_id = SymbolId(d.alloc_id());
let mut inner = Layer::new(LayerId(d.alloc_id()), "Mouth");
inner.color = Rgba::hex(0xff6b4a);
let mut keys = Vec::with_capacity(shapes.len());
for (i, (label, shape)) in MOUTHS.iter().zip(shapes).enumerate() {
let mut k = Keyframe::new(i as u32, 1);
k.label = (*label).to_string();
k.elements = vec![element(&mut d, &format!("{label} mouth"), Affine::IDENTITY, shape)];
keys.push(Arc::new(k));
}
inner.keyframes = keys;
d.library.push(Arc::new(Symbol { id: sym_id, name: "Mouth".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, scale_grid_kept: None, timeline: Timeline { layers: vec![Arc::new(inner)] } }));
let (cx, cy) = (640.0, 340.0);
let face = element(&mut d, "Head", Affine::IDENTITY, Shape { path: Arc::new(Path::ellipse(cx, cy, 200.0, 250.0)), fill: None, stroke: Some(Stroke::new(Rgba::hex(GUIDE), 2.0)), fill_rule: Default::default(), merge: false, warp: None });
let guides = vec![
face,
line(&mut d, "Eye line", (cx - 200.0, cy), (cx + 200.0, cy), GUIDE_SOFT, 1.0),
line(&mut d, "Centre line", (cx, cy - 250.0), (cx, cy + 250.0), GUIDE_SOFT, 1.0),
line(&mut d, "Mouth line", (cx - 120.0, cy + 130.0), (cx + 120.0, cy + 130.0), GUIDE_SOFT, 1.0),
];
let instance = Arc::new(Element {
id: ElementId(d.alloc_id()),
name: "mouth".into(),
transform: Affine::translate(cx, cy + 130.0),
color: ColorEffect::default(),
kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: crate::BlendMode::Normal, filters: Vec::new(), events: Vec::new() },
});
let layers = vec![
layer(&mut d, "Face guide", LayerKind::Guide, GUIDE, FRAMES, guides),
layer(&mut d, "Mouth", LayerKind::Normal, 0xff6b4a, FRAMES, vec![instance]),
layer(&mut d, "Head", LayerKind::Normal, 0x66bb6a, FRAMES, Vec::new()),
];
d.timeline_mut(0).layers = layers;
d
}
/// A copy of `doc` with its guide layers drawn as artwork, their lines `widen` times as wide: a
/// template's picture shows its guides (which output never does), and a small picture needs
/// them wider to see them.
pub fn with_guides_shown(doc: &Document, widen: f32) -> Document {
let widen = if widen.is_finite() { widen.clamp(1.0, 16.0) } else { 1.0 };
let show = |tl: &mut Timeline| {
for l in &mut tl.layers {
if l.kind != LayerKind::Guide {
continue;
}
let l = Arc::make_mut(l);
l.kind = LayerKind::Normal;
for k in &mut l.keyframes {
for e in &mut Arc::make_mut(k).elements {
if let ElementKind::Shape(sh) = &e.kind
&& let Some(st) = &sh.stroke
{
let mut sh = sh.clone();
sh.stroke = Some(Stroke { width: st.width * widen, ..st.clone() });
Arc::make_mut(e).kind = ElementKind::Shape(sh);
}
}
}
}
};
let mut d = doc.clone();
for scene in &mut d.scenes {
show(&mut Arc::make_mut(scene).timeline);
}
for sym in &mut d.library {
show(&mut Arc::make_mut(sym).timeline);
}
d
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_template_builds_a_consistent_document() {
let mut ids = std::collections::HashSet::new();
for t in &TEMPLATES {
assert!(ids.insert(t.id), "{} is listed once", t.id);
assert!(find(t.id).is_some_and(|f| std::ptr::eq(f, t)));
let d = (t.build)();
assert!(d.stage.width > 0 && d.stage.height > 0 && d.stage.fps > 0.0, "{}", t.id);
let tl = d.timeline(0);
assert!(tl.layers.len() >= 3, "{}: named layers to draw on", t.id);
assert!(tl.layers.iter().any(|l| l.kind == LayerKind::Guide && l.locked), "{}: a locked guide layer", t.id);
// Ids are unique and below `next_id`, so editing never reuses one.
let mut seen = std::collections::HashSet::new();
let mut check = |id: u64| assert!(id < d.next_id && seen.insert(id), "{}: id {id}", t.id);
for l in &tl.layers {
check(l.id.0);
l.keyframes.iter().flat_map(|k| k.elements.iter()).for_each(|e| check(e.id.0));
}
for s in &d.library {
check(s.id.0);
}
// Guides never render; the picture with them shown is not blank.
assert!(crate::evaluate(&d, 0).items.iter().all(|i| i.guide || tl.layer(i.layer).is_some_and(|l| l.kind != LayerKind::Guide)));
assert!(crate::evaluate(&with_guides_shown(&d, 4.0), 0).items.iter().any(|i| !i.guide), "{}", t.id);
}
// The sizes the task asks for.
let size = |id: &str| find(id).map(|t| (t.build)().stage).map(|s| (s.width, s.height, s.fps));
assert_eq!(size("banner-728x90"), Some((728, 90, 24.0)));
assert_eq!(size("banner-300x250"), Some((300, 250, 24.0)));
assert_eq!(size("social-square"), Some((1080, 1080, 30.0)));
assert_eq!(size("storyboard"), Some((1920, 1080, 24.0)));
}
#[test]
fn the_storyboard_and_mouth_chart_are_labelled() {
let d = storyboard();
let panels = d.timeline(0).layers.iter().find(|l| l.name == "Panels").map(|l| l.keyframes.iter().map(|k| k.label.clone()).collect::<Vec<_>>());
assert_eq!(panels.map(|p| p.len()), Some(6));
assert_eq!(d.timeline(0).frame_count(), 6 * 48);
let d = lip_sync();
let labels: Vec<String> = d.library.first().map(|s| s.timeline.layers.iter().flat_map(|l| l.keyframes.iter().map(|k| k.label.clone())).collect()).unwrap_or_default();
assert_eq!(labels, MOUTHS.map(str::to_string).to_vec());
}
}
+641
View File
@@ -0,0 +1,641 @@
//! Asset Warp (ADR 0079): a deformation mesh over a shape or a bitmap, bent by pins.
//!
//! A [`Warp`] sits on a [`Shape`] (a bitmap on the stage is a shape filled with its image). It
//! keeps the artwork's outline as it was drawn (`rest`), a mesh **resolution**, and the
//! **pins**: each a point of the artwork as drawn (`rest`) and where it is now (`at`), both in
//! the shape's own space. The mesh is not stored: it is a grid over the rest outline's bounds,
//! `resolution` cells along the longer side (square-ish cells, each split into two triangles,
//! the diagonals alternating so the grid has no preferred direction), so it is always the same
//! for the same artwork.
//!
//! **Deformation** is the rigid moving-least-squares deformation of S. Schaefer, T. McPhail and
//! J. Warren, *Image deformation using moving least squares* (SIGGRAPH 2006, §2.3), evaluated at
//! the mesh's vertices: each vertex `v` moves by the rotation and translation that best carry
//! the pins near it (weighted `1 / |p − v|²`) to where they are. It interpolates the pins
//! exactly, is as rigid as possible locally (no shear, no scale), is a closed form per vertex
//! (no solver, no iterations, nothing to converge), and depends only on the pins, so it is
//! deterministic and its cost is bounded: vertices × pins. Between vertices the mesh is
//! piecewise affine, so a bitmap is drawn as textured triangles and a shape's outline maps
//! through the same triangles: the shape and the bitmap bend the same way.
//!
//! **The outline.** Straight edges are split where they cross the mesh's edges, so a line
//! maps exactly to the mesh's image of it (a bitmap's outline is exactly the mesh's border).
//! Curves are split into pieces no longer than half a cell, each end mapped through the mesh
//! and each handle by the triangle of the end it belongs to, so curves stay smooth. **At rest**
//! (every pin where it was placed) the outline is the drawing, bit for bit: the very `Arc` of
//! the rest path.
//!
//! **The file holds what shows.** Commands write the bent outline into the shape's `path` and
//! its fingerprint into `shown`. A shape whose path no longer has that fingerprint was edited
//! by another tool since: its warp is stale, [`Shape::live_warp`] ignores it, and the next warp
//! command starts again from the shape as it now is ([`Warp::rebased`]). Pins tween between
//! keyframes with the keyframe's easing (as bone poses do, ADR 0043): `evaluate` blends the
//! pins and bends the rest outline, so a tween never accumulates drift.
use crate::Shape;
use anicraft_geom::{Path, PathCmd, Vec2};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
/// Fewest and most cells along the mesh's longer side, and the resolution a new warp has.
pub const MIN_RESOLUTION: u32 = 2;
pub const MAX_RESOLUTION: u32 = 48;
pub const DEFAULT_RESOLUTION: u32 = 12;
/// Most pins on one warp.
pub const MAX_PINS: usize = 128;
/// Most anchors a warped outline may have (Optimize first beyond it).
pub const MAX_WARP_POINTS: usize = 20_000;
/// Most commands a bent outline may have; past it curves and lines are not split.
const MAX_BENT_CMDS: usize = 400_000;
/// Most pieces one curve is split into.
const MAX_SPLIT: usize = 32;
/// Largest artwork a warp covers (local units on either side).
pub const MAX_EXTENT: f32 = 1_000_000.0;
/// Two pins closer than this (local units, as drawn) are one place.
pub const PIN_SPACING: f32 = 0.5;
/// Unique id of a pin within a document (from the document's id counter).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PinId(pub u64);
/// A pin: a point of the artwork as drawn, and where it is now (the shape's space).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Pin {
pub id: PinId,
pub rest: Vec2,
pub at: Vec2,
}
fn default_resolution() -> u32 {
DEFAULT_RESOLUTION
}
/// A warp mesh on a shape (see the module docs).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Warp {
/// The outline as it was drawn, in the shape's space.
#[serde(with = "crate::path_table")]
pub rest: Arc<Path>,
/// Cells along the mesh's longer side ([`MIN_RESOLUTION`]..=[`MAX_RESOLUTION`]).
#[serde(default = "default_resolution")]
pub resolution: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub pins: Vec<Pin>,
/// Fingerprint of the outline the warp gave the shape ([`fingerprint`]).
#[serde(default)]
pub shown: u64,
}
impl PartialEq for Warp {
fn eq(&self, o: &Warp) -> bool {
crate::arc_eq(&self.rest, &o.rest) && self.resolution == o.resolution && self.pins == o.pins && self.shown == o.shown
}
}
/// The deformation mesh as drawn: every vertex as drawn (`rest`) and bent (`shown`), and the
/// triangles (indices into both), in the shape's space, in drawing order.
#[derive(Clone, Debug, PartialEq)]
pub struct WarpMesh {
pub rest: Vec<Vec2>,
pub shown: Vec<Vec2>,
pub tris: Vec<[u32; 3]>,
}
/// The mesh's grid: `nx × ny` cells from `min` to `max`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Grid {
pub min: Vec2,
pub max: Vec2,
pub nx: u32,
pub ny: u32,
}
impl Grid {
/// The grid over `rest`'s control-point bounds with `resolution` cells along the longer side
/// (an extent under 1 unit is widened to 1, about its middle). `None` for an empty or
/// unbounded outline.
pub fn of(rest: &Path, resolution: u32) -> Option<Grid> {
let b = rest.bounds();
if !(b.min.is_finite() && b.max.is_finite()) || b.max.x < b.min.x || b.max.y < b.min.y {
return None;
}
if b.min.x.abs().max(b.min.y.abs()).max(b.max.x.abs()).max(b.max.y.abs()) > MAX_EXTENT {
return None;
}
let widen = |lo: f32, hi: f32| if hi - lo < 1.0 { ((lo + hi) * 0.5 - 0.5, (lo + hi) * 0.5 + 0.5) } else { (lo, hi) };
let (x0, x1) = widen(b.min.x, b.max.x);
let (y0, y1) = widen(b.min.y, b.max.y);
let (w, h) = (x1 - x0, y1 - y0);
let r = resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION);
let size = w.max(h) / r as f32;
let cells = |len: f32| {
let n = (len / size).ceil();
if n.is_finite() { (n as u32).clamp(1, r) } else { 1 }
};
Some(Grid { min: Vec2::new(x0, y0), max: Vec2::new(x1, y1), nx: cells(w), ny: cells(h) })
}
/// The x of column line `i` (exactly the bounds at either end).
pub fn x(&self, i: u32) -> f32 {
if i >= self.nx { self.max.x } else { self.min.x + (self.max.x - self.min.x) * i as f32 / self.nx as f32 }
}
/// The y of row line `j`.
pub fn y(&self, j: u32) -> f32 {
if j >= self.ny { self.max.y } else { self.min.y + (self.max.y - self.min.y) * j as f32 / self.ny as f32 }
}
/// Vertices, row by row: `(nx + 1) × (ny + 1)`.
pub fn vertices(&self) -> Vec<Vec2> {
let mut out = Vec::with_capacity(((self.nx + 1) * (self.ny + 1)) as usize);
for j in 0..=self.ny {
for i in 0..=self.nx {
out.push(Vec2::new(self.x(i), self.y(j)));
}
}
out
}
fn vertex(&self, i: u32, j: u32) -> u32 {
j * (self.nx + 1) + i
}
/// Whether cell `(i, j)`'s diagonal runs from its top-left to its bottom-right corner (else
/// from its top-right to its bottom-left): they alternate like a chequerboard.
fn falling(i: u32, j: u32) -> bool {
(i + j).is_multiple_of(2)
}
/// The two triangles of cell `(i, j)`, as vertex indices.
fn cell_tris(&self, i: u32, j: u32) -> [[u32; 3]; 2] {
let (a, b, c, d) = (self.vertex(i, j), self.vertex(i + 1, j), self.vertex(i, j + 1), self.vertex(i + 1, j + 1));
if Grid::falling(i, j) { [[a, b, d], [a, d, c]] } else { [[a, b, c], [b, d, c]] }
}
/// Every triangle, cell by cell, row by row.
pub fn triangles(&self) -> Vec<[u32; 3]> {
let mut out = Vec::with_capacity((2 * self.nx * self.ny) as usize);
for j in 0..self.ny {
for i in 0..self.nx {
out.extend(self.cell_tris(i, j));
}
}
out
}
/// The cell `p` falls in (clamped to the grid, so points just outside use the edge cells).
fn cell(&self, p: Vec2) -> (u32, u32) {
let at = |v: f32, lo: f32, hi: f32, n: u32| {
let k = ((v - lo) / (hi - lo) * n as f32).floor();
if k.is_finite() { (k.max(0.0) as u32).min(n - 1) } else { 0 }
};
(at(p.x, self.min.x, self.max.x, self.nx), at(p.y, self.min.y, self.max.y, self.ny))
}
/// The triangle (vertex indices) of the grid that holds `p`.
pub fn locate(&self, p: Vec2) -> [u32; 3] {
let (i, j) = self.cell(p);
let [t0, t1] = self.cell_tris(i, j);
let (x0, y0) = (self.x(i), self.y(j));
let (cw, ch) = ((self.x(i + 1) - x0).max(1e-12), (self.y(j + 1) - y0).max(1e-12));
let (u, v) = ((p.x - x0) / cw, (p.y - y0) / ch);
let first = if Grid::falling(i, j) { u >= v } else { u + v <= 1.0 };
if first { t0 } else { t1 }
}
/// The parameters in `(0, 1)` where the segment `a → b` crosses an edge of the mesh, in
/// order: column and row lines, then each cell's diagonal.
fn crossings(&self, a: Vec2, b: Vec2, out: &mut Vec<f32>) {
out.clear();
let d = b - a;
if d.x != 0.0 {
for i in 1..self.nx {
let t = (self.x(i) - a.x) / d.x;
if t > 0.0 && t < 1.0 {
out.push(t);
}
}
}
if d.y != 0.0 {
for j in 1..self.ny {
let t = (self.y(j) - a.y) / d.y;
if t > 0.0 && t < 1.0 {
out.push(t);
}
}
}
out.sort_by(f32::total_cmp);
out.dedup_by(|x, y| (*x - *y).abs() < 1e-6);
// Inside each cell the segment may still cross the cell's diagonal.
let mut diag = Vec::new();
let mut t0 = 0.0f32;
for &t1 in out.iter().chain(std::iter::once(&1.0)) {
let mid = a + d * ((t0 + t1) * 0.5);
let (i, j) = self.cell(mid);
let (p, q) = if Grid::falling(i, j) { (Vec2::new(self.x(i), self.y(j)), Vec2::new(self.x(i + 1), self.y(j + 1))) } else { (Vec2::new(self.x(i + 1), self.y(j)), Vec2::new(self.x(i), self.y(j + 1))) };
let e = q - p;
let den = d.cross(e);
if den.abs() > 1e-12 {
let t = (p - a).cross(e) / den;
if t > t0 + 1e-6 && t < t1 - 1e-6 {
diag.push(t);
}
}
t0 = t1;
}
out.extend(diag);
out.sort_by(f32::total_cmp);
}
}
/// Barycentric coordinates of `p` in triangle `(a, b, c)` (extrapolated outside it); `None` for
/// a triangle with no area.
fn barycentric(a: Vec2, b: Vec2, c: Vec2, p: Vec2) -> Option<(f32, f32, f32)> {
let det = (b - a).cross(c - a);
if det.abs() <= 1e-12 || det.is_nan() {
return None;
}
let l1 = (p - a).cross(c - a) / det;
let l2 = (b - a).cross(p - a) / det;
Some((1.0 - l1 - l2, l1, l2))
}
/// The rigid moving-least-squares deformation (Schaefer et al. 2006, §2.3) of `v` by pins
/// `(from, to)`, with weights `1 / |from − v|²`: the rotation and translation that best carry
/// the pins near `v` where they go, applied to `v`. A point on a pin goes with it; with one pin
/// everything moves with it; with none nothing moves. Computed in `f64`.
pub fn mls_rigid(pins: &[(Vec2, Vec2)], v: Vec2) -> Vec2 {
if pins.is_empty() {
return v;
}
let (vx, vy) = (f64::from(v.x), f64::from(v.y));
let (mut sw, mut px, mut py, mut qx, mut qy) = (0.0f64, 0.0, 0.0, 0.0, 0.0);
let mut ws = Vec::with_capacity(pins.len());
for &(p, q) in pins {
let (dx, dy) = (f64::from(p.x) - vx, f64::from(p.y) - vy);
let d2 = dx * dx + dy * dy;
if d2 < 1e-12 {
return q;
}
let w = 1.0 / d2;
ws.push(w);
sw += w;
px += w * f64::from(p.x);
py += w * f64::from(p.y);
qx += w * f64::from(q.x);
qy += w * f64::from(q.y);
}
if !(sw > 0.0 && sw.is_finite()) {
return v;
}
let (px, py, qx, qy) = (px / sw, py / sw, qx / sw, qy / sw);
// The best rotation: its cosine and sine are the weighted dot and cross of the centred pins.
let (mut dot, mut cross) = (0.0f64, 0.0f64);
for (&(p, q), &w) in pins.iter().zip(&ws) {
let (ax, ay) = (f64::from(p.x) - px, f64::from(p.y) - py);
let (bx, by) = (f64::from(q.x) - qx, f64::from(q.y) - qy);
dot += w * (ax * bx + ay * by);
cross += w * (ax * by - ay * bx);
}
let r = dot.hypot(cross);
let (c, s) = if r > 1e-18 && r.is_finite() { (dot / r, cross / r) } else { (1.0, 0.0) };
let (dx, dy) = (vx - px, vy - py);
let out = Vec2::new((qx + c * dx - s * dy) as f32, (qy + s * dx + c * dy) as f32);
if out.is_finite() { out } else { v }
}
/// A fingerprint of `path`'s commands and coordinates (FNV-1a over their bits): how a warp
/// knows the outline is still the one it gave the shape.
pub fn fingerprint(path: &Path) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
let mut eat = |bits: u32| {
for b in bits.to_le_bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
};
for c in &path.cmds {
let (tag, pts): (u32, [Option<Vec2>; 3]) = match *c {
PathCmd::MoveTo(p) => (1, [Some(p), None, None]),
PathCmd::LineTo(p) => (2, [Some(p), None, None]),
PathCmd::QuadTo(a, p) => (3, [Some(a), Some(p), None]),
PathCmd::CubicTo(a, b, p) => (4, [Some(a), Some(b), Some(p)]),
PathCmd::Close => (5, [None, None, None]),
};
eat(tag);
for p in pts.into_iter().flatten() {
eat(p.x.to_bits());
eat(p.y.to_bits());
}
}
h
}
/// How many anchors (command ends) `path` has.
pub fn anchor_count(path: &Path) -> usize {
path.cmds.iter().filter(|c| !matches!(c, PathCmd::Close)).count()
}
/// The bent mesh: the grid's vertices as drawn and where the pins carry them.
struct Bent {
grid: Grid,
rest: Vec<Vec2>,
shown: Vec<Vec2>,
}
impl Bent {
fn at(&self, i: u32) -> (Vec2, Vec2) {
let i = i as usize;
(self.rest.get(i).copied().unwrap_or_default(), self.shown.get(i).copied().unwrap_or_default())
}
/// `p` (as drawn) mapped through triangle `tri`'s affine map (extrapolated outside it).
fn through(&self, tri: [u32; 3], p: Vec2) -> Vec2 {
let [(ra, sa), (rb, sb), (rc, sc)] = tri.map(|i| self.at(i));
match barycentric(ra, rb, rc, p) {
Some((l0, l1, l2)) => {
let out = sa * l0 + sb * l1 + sc * l2;
if out.is_finite() { out } else { p }
}
None => p + (sa - ra),
}
}
/// `p` (as drawn) where the mesh carries it, and the triangle that did.
fn map(&self, p: Vec2) -> (Vec2, [u32; 3]) {
let tri = self.grid.locate(p);
(self.through(tri, p), tri)
}
}
impl Warp {
/// A warp of the outline `rest` with no pins.
pub fn new(rest: Arc<Path>, resolution: u32) -> Warp {
let shown = fingerprint(&rest);
Warp { rest, resolution: resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION), pins: Vec::new(), shown }
}
/// Every pin where it was placed: the artwork shows as drawn.
pub fn at_rest(&self) -> bool {
self.pins.iter().all(|p| p.at == p.rest)
}
pub fn pin(&self, id: PinId) -> Option<&Pin> {
self.pins.iter().find(|p| p.id == id)
}
pub fn grid(&self) -> Option<Grid> {
Grid::of(&self.rest, self.resolution)
}
fn bent(&self) -> Option<Bent> {
let grid = self.grid()?;
let rest = grid.vertices();
let pins: Vec<(Vec2, Vec2)> = self.pins.iter().map(|p| (p.rest, p.at)).collect();
let shown = if self.at_rest() { rest.clone() } else { rest.iter().map(|&v| mls_rigid(&pins, v)).collect() };
Some(Bent { grid, rest, shown })
}
/// The mesh as it shows (`None` for an outline with no extent).
pub fn mesh(&self) -> Option<WarpMesh> {
let b = self.bent()?;
Some(WarpMesh { tris: b.grid.triangles(), rest: b.rest, shown: b.shown })
}
/// Where point `p` of the artwork as drawn shows now.
pub fn map(&self, p: Vec2) -> Vec2 {
if self.at_rest() {
return p;
}
self.bent().map_or(p, |b| b.map(p).0)
}
/// The point of the artwork as drawn that shows at `p` (the topmost triangle there, as the
/// mesh draws); `None` off the mesh.
pub fn unmap(&self, p: Vec2) -> Option<Vec2> {
let b = self.bent()?;
if self.at_rest() {
return (p.x >= b.grid.min.x && p.x <= b.grid.max.x && p.y >= b.grid.min.y && p.y <= b.grid.max.y).then_some(p);
}
let tris = b.grid.triangles();
for tri in tris.iter().rev() {
let [(ra, sa), (rb, sb), (rc, sc)] = tri.map(|i| b.at(i));
let Some((l0, l1, l2)) = barycentric(sa, sb, sc, p) else { continue };
let eps = -1e-4;
if l0 >= eps && l1 >= eps && l2 >= eps {
let r = ra * l0 + rb * l1 + rc * l2;
return r.is_finite().then_some(r);
}
}
None
}
/// The outline as the pins bend it (the rest path itself, shared, at rest).
pub fn outline(&self) -> Arc<Path> {
if self.at_rest() {
return self.rest.clone();
}
match self.bent() {
Some(b) => Arc::new(bend(&self.rest, &b)),
None => self.rest.clone(),
}
}
/// Whether `path` is the outline this warp last gave its shape.
pub fn shows(&self, path: &Path) -> bool {
fingerprint(path) == self.shown
}
/// The warp of `path` (the shape as it now is, edited since by another tool), its pins kept
/// where they show: they are its new rest, so nothing moves.
pub fn rebased(&self, path: Arc<Path>) -> Warp {
let mut w = Warp::new(path, self.resolution);
w.pins = self.pins.iter().map(|p| Pin { id: p.id, rest: p.at, at: p.at }).collect();
w
}
/// This warp's pins blended `t` of the way to `o`'s (pins pair by id; one without a partner
/// holds). `None` unless both bend the same artwork on the same mesh.
pub fn lerp(&self, o: &Warp, t: f32) -> Option<Warp> {
if !(crate::arc_eq(&self.rest, &o.rest) && self.resolution == o.resolution) {
return None;
}
let mut w = self.clone();
for p in &mut w.pins {
if let Some(q) = o.pin(p.id) {
p.at = p.at.lerp(q.at, t);
}
}
Some(w)
}
/// Repairs a loaded warp: the resolution in range, finite pins (one per id, at most
/// [`MAX_PINS`]). `false` when nothing usable is left (no extent, too many points): the
/// shape keeps the outline it shows.
pub fn sanitize(&mut self) -> bool {
if self.grid().is_none() || anchor_count(&self.rest) > MAX_WARP_POINTS {
return false;
}
self.resolution = self.resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION);
let near = |v: Vec2| v.is_finite() && v.x.abs() <= MAX_EXTENT && v.y.abs() <= MAX_EXTENT;
let mut seen = Vec::with_capacity(self.pins.len());
self.pins.retain(|p| {
let keep = near(p.rest) && near(p.at) && !seen.contains(&p.id);
seen.push(p.id);
keep
});
self.pins.truncate(MAX_PINS);
true
}
}
impl Shape {
/// The shape's warp while its outline is still the one the warp gave it.
pub fn live_warp(&self) -> Option<&Warp> {
self.warp.as_deref().filter(|w| w.shows(&self.path))
}
/// Sets the shape's warp to `w` and its outline to what `w` bends it into.
pub fn set_warp(&mut self, mut w: Warp) {
let path = w.outline();
w.shown = fingerprint(&path);
self.path = path;
self.warp = Some(Arc::new(w));
}
}
/// Splits cubic `(p0, c1, c2, p3)` at `t`.
fn split_cubic(p0: Vec2, c1: Vec2, c2: Vec2, p3: Vec2, t: f32) -> ([Vec2; 4], [Vec2; 4]) {
let (a, b, c) = (p0.lerp(c1, t), c1.lerp(c2, t), c2.lerp(p3, t));
let (d, e) = (a.lerp(b, t), b.lerp(c, t));
let f = d.lerp(e, t);
([p0, a, d, f], [f, e, c, p3])
}
fn split_quad(p0: Vec2, c: Vec2, p2: Vec2, t: f32) -> ([Vec2; 3], [Vec2; 3]) {
let (a, b) = (p0.lerp(c, t), c.lerp(p2, t));
let m = a.lerp(b, t);
([p0, a, m], [m, b, p2])
}
/// How many pieces a curve with control polygon length `len` is split into.
fn pieces(len: f32, step: f32) -> usize {
let n = (len / step).ceil();
if n.is_finite() { (n as usize).clamp(1, MAX_SPLIT) } else { 1 }
}
/// `rest` bent through the mesh (see the module docs).
fn bend(rest: &Path, b: &Bent) -> Path {
let g = &b.grid;
let step = (((g.max.x - g.min.x) / g.nx as f32).min((g.max.y - g.min.y) / g.ny as f32) * 0.5).max(1e-3);
// Splitting is skipped past the command budget (each anchor still maps through the mesh).
let split = rest.cmds.len().saturating_mul(MAX_SPLIT) <= MAX_BENT_CMDS || estimate(rest, g, step) <= MAX_BENT_CMDS;
let mut out: Vec<PathCmd> = Vec::with_capacity(rest.cmds.len() * 4);
let mut ts = Vec::new();
let mut cur = Vec2::ZERO;
let mut start = Vec2::ZERO;
// The last anchor's triangle: a cubic's first handle moves with it.
let mut cur_tri = g.locate(cur);
let line = |out: &mut Vec<PathCmd>, a: Vec2, p: Vec2, ts: &mut Vec<f32>| {
if split {
g.crossings(a, p, ts);
for &t in ts.iter() {
out.push(PathCmd::LineTo(b.map(a.lerp(p, t)).0));
}
}
let (q, tri) = b.map(p);
out.push(PathCmd::LineTo(q));
tri
};
for c in &rest.cmds {
match *c {
PathCmd::MoveTo(p) => {
let (q, tri) = b.map(p);
out.push(PathCmd::MoveTo(q));
(cur, start, cur_tri) = (p, p, tri);
}
PathCmd::LineTo(p) => {
cur_tri = line(&mut out, cur, p, &mut ts);
cur = p;
}
PathCmd::QuadTo(c, p) => {
let n = if split { pieces(cur.distance(c) + c.distance(p), step) } else { 1 };
let mut rest_q = [cur, c, p];
for k in 0..n {
let left = n - k;
let (piece, tail) = if left > 1 { split_quad(rest_q[0], rest_q[1], rest_q[2], 1.0 / left as f32) } else { (rest_q, rest_q) };
let (q, tri) = b.map(piece[2]);
out.push(PathCmd::QuadTo(b.map(piece[1]).0, q));
cur_tri = tri;
rest_q = tail;
}
cur = p;
}
PathCmd::CubicTo(c1, c2, p) => {
let n = if split { pieces(cur.distance(c1) + c1.distance(c2) + c2.distance(p), step) } else { 1 };
let mut rest_c = [cur, c1, c2, p];
for k in 0..n {
let left = n - k;
let (piece, tail) = if left > 1 { split_cubic(rest_c[0], rest_c[1], rest_c[2], rest_c[3], 1.0 / left as f32) } else { (rest_c, rest_c) };
let (q, tri) = b.map(piece[3]);
out.push(PathCmd::CubicTo(b.through(cur_tri, piece[1]), b.through(tri, piece[2]), q));
cur_tri = tri;
rest_c = tail;
}
cur = p;
}
PathCmd::Close => {
// The closing edge is a straight line too: split it like one.
if cur != start {
if split {
g.crossings(cur, start, &mut ts);
for &t in &ts {
out.push(PathCmd::LineTo(b.map(cur.lerp(start, t)).0));
}
}
let (q, tri) = b.map(start);
out.push(PathCmd::LineTo(q));
cur_tri = tri;
}
out.push(PathCmd::Close);
cur = start;
}
}
}
Path { cmds: out }
}
/// A cheap upper bound of the bent outline's commands.
fn estimate(rest: &Path, g: &Grid, step: f32) -> usize {
let lines = (g.nx + g.ny) as usize * 2 + 1;
let mut cur = Vec2::ZERO;
let mut n = 0usize;
for c in &rest.cmds {
n = n.saturating_add(match *c {
PathCmd::MoveTo(p) => {
cur = p;
1
}
PathCmd::LineTo(p) => {
cur = p;
lines
}
PathCmd::QuadTo(a, p) => {
let k = pieces(cur.distance(a) + a.distance(p), step);
cur = p;
k
}
PathCmd::CubicTo(a, b, p) => {
let k = pieces(cur.distance(a) + a.distance(b) + b.distance(p), step);
cur = p;
k
}
PathCmd::Close => lines + 1,
});
}
n
}
#[cfg(test)]
#[path = "warp_tests.rs"]
mod tests;
+244
View File
@@ -0,0 +1,244 @@
use super::*;
use crate::{Easing, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, Tween, evaluate_layer_elements};
use anicraft_geom::Affine;
fn pin(id: u64, rest: (f32, f32), at: (f32, f32)) -> Pin {
Pin { id: PinId(id), rest: Vec2::new(rest.0, rest.1), at: Vec2::new(at.0, at.1) }
}
fn blob() -> Arc<Path> {
Arc::new(Path::ellipse(100.0, 50.0, 100.0, 50.0))
}
fn anchors(p: &Path) -> Vec<Vec2> {
p.cmds
.iter()
.filter_map(|c| match *c {
PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p),
PathCmd::Close => None,
})
.collect()
}
#[test]
fn rest_pose_reproduces_the_artwork_exactly() {
let rest = blob();
let mut w = Warp::new(rest.clone(), 12);
// No pins, then pins exactly where they were placed: the very path, shared.
assert!(Arc::ptr_eq(&w.outline(), &rest));
w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (190.0, 50.0), (190.0, 50.0))];
assert!(w.at_rest());
assert!(Arc::ptr_eq(&w.outline(), &rest));
assert_eq!(w.map(Vec2::new(33.3, 12.5)), Vec2::new(33.3, 12.5));
assert_eq!(w.mesh().map(|m| m.rest == m.shown), Some(true));
}
#[test]
fn mls_interpolates_pins_and_is_rigid_with_one_or_two() {
// One pin: everything moves with it.
let one = [(Vec2::new(0.0, 0.0), Vec2::new(5.0, -3.0))];
assert_eq!(mls_rigid(&one, Vec2::new(40.0, 40.0)), Vec2::new(45.0, 37.0));
// Two pins turned a quarter turn about their middle: every point turns with them.
let two = [(Vec2::new(-10.0, 0.0), Vec2::new(0.0, -10.0)), (Vec2::new(10.0, 0.0), Vec2::new(0.0, 10.0))];
for v in [Vec2::new(3.0, 7.0), Vec2::new(-20.0, 4.0), Vec2::new(0.0, 0.0)] {
let f = mls_rigid(&two, v);
let want = Vec2::new(-v.y, v.x);
assert!(f.distance(want) < 1e-3, "{v:?} → {f:?}, want {want:?}");
}
// On a pin: exactly its target.
assert_eq!(mls_rigid(&two, Vec2::new(10.0, 0.0)), Vec2::new(0.0, 10.0));
assert_eq!(mls_rigid(&[], Vec2::new(1.0, 2.0)), Vec2::new(1.0, 2.0));
}
#[test]
fn a_single_moved_pin_moves_nearby_points_most() {
let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 300.0, 100.0)), 12);
// Three pins along the strip; the right one is pulled down.
w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (150.0, 50.0), (150.0, 50.0)), pin(3, (290.0, 50.0), (290.0, 90.0))];
let moved = |x: f32| w.map(Vec2::new(x, 50.0)).distance(Vec2::new(x, 50.0));
let (near, mid, far) = (moved(270.0), moved(200.0), moved(40.0));
assert!(near > mid && mid > far, "{near} > {mid} > {far}");
assert!(near > 25.0 && far < 3.0, "near {near}, far {far}");
// The pins themselves are where they were put (to within the mesh's interpolation).
for p in &w.pins {
assert!(w.map(p.rest).distance(p.at) < 1.5, "{p:?} → {:?}", w.map(p.rest));
}
}
#[test]
fn deformation_is_as_rigid_as_possible() {
// Rigidity: how much each triangle's map stretches or shears (its singular values' distance
// from 1). A pure turn of the pins turns the mesh rigidly; a bend stays near rigid.
let distortion = |w: &Warp| {
let m = w.mesh().unwrap_or_else(unreachable_mesh);
let mut worst = 0.0f32;
for t in &m.tris {
let [a, b, c] = t.map(|i| i as usize);
let (r0, r1, r2) = (m.rest[a], m.rest[b], m.rest[c]);
let (s0, s1, s2) = (m.shown[a], m.shown[b], m.shown[c]);
// The linear part J with J·(r1 − r0, r2 − r0) = (s1 − s0, s2 − s0).
let (e1, e2, f1, f2) = (r1 - r0, r2 - r0, s1 - s0, s2 - s0);
let det = e1.cross(e2);
let inv = [e2.y / det, -e2.x / det, -e1.y / det, e1.x / det];
let j = [f1.x * inv[0] + f2.x * inv[2], f1.x * inv[1] + f2.x * inv[3], f1.y * inv[0] + f2.y * inv[2], f1.y * inv[1] + f2.y * inv[3]];
let (p, q, r, s) = (j[0], j[1], j[2], j[3]);
let e = (p * p + q * q + r * r + s * s) * 0.5;
let d = (p * s - q * r).abs();
let disc = (e * e - d * d).max(0.0).sqrt();
let (big, small) = ((e + disc).sqrt(), (e - disc).max(0.0).sqrt());
worst = worst.max((big - 1.0).abs()).max((small - 1.0).abs());
}
worst
};
let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 200.0, 100.0)), 10);
let turn = Affine::translate(100.0, 50.0).mul(&Affine::rotate(0.6)).mul(&Affine::translate(-100.0, -50.0));
w.pins = [(20.0, 20.0), (180.0, 30.0), (100.0, 90.0)].iter().enumerate().map(|(i, &(x, y))| Pin { id: PinId(i as u64), rest: Vec2::new(x, y), at: turn.apply(Vec2::new(x, y)) }).collect();
assert!(distortion(&w) < 1e-3, "a turn is rigid: {}", distortion(&w));
// A bend: one end of a strip turned down by 30°.
w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (100.0, 50.0), (100.0, 50.0)), pin(3, (190.0, 50.0), (178.0, 95.0))];
let d = distortion(&w);
assert!(d < 0.25, "a bend stays near rigid: {d}");
}
fn unreachable_mesh() -> WarpMesh {
WarpMesh { rest: Vec::new(), shown: Vec::new(), tris: Vec::new() }
}
#[test]
fn straight_edges_follow_the_mesh_exactly() {
// A bitmap's outline is a rectangle: bent, it is exactly the mesh's border.
let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 120.0, 60.0)), 6);
w.pins = vec![pin(1, (0.0, 0.0), (0.0, 0.0)), pin(2, (120.0, 60.0), (150.0, 90.0))];
let m = w.mesh().unwrap_or_else(unreachable_mesh);
let g = w.grid().unwrap_or(Grid { min: Vec2::ZERO, max: Vec2::ZERO, nx: 1, ny: 1 });
assert_eq!((g.nx, g.ny), (6, 3));
let pts = anchors(&w.outline());
// Every border vertex of the mesh is on the bent outline.
for (i, v) in m.rest.iter().enumerate() {
let border = v.x == 0.0 || v.y == 0.0 || v.x == 120.0 || v.y == 60.0;
if border {
assert!(pts.iter().any(|p| p.distance(m.shown[i]) < 1e-3), "border vertex {v:?} missing");
}
}
// And the outline has no point the border doesn't (straight lines between them).
assert_eq!(pts.len(), 2 * (6 + 3) + 1);
}
#[test]
fn curves_split_and_stay_close_to_the_true_deformation() {
let mut w = Warp::new(blob(), 16);
w.pins = vec![pin(1, (0.0, 50.0), (0.0, 50.0)), pin(2, (100.0, 50.0), (100.0, 50.0)), pin(3, (200.0, 50.0), (190.0, 100.0))];
let bent = w.outline();
assert!(bent.cmds.len() > blob().cmds.len());
// Points of the bent outline lie near where the exact MLS deformation puts the drawn curve.
let pins: Vec<(Vec2, Vec2)> = w.pins.iter().map(|p| (p.rest, p.at)).collect();
let truth: Vec<Vec2> = (0..400).map(|i| {
let a = i as f32 / 400.0 * std::f32::consts::TAU;
mls_rigid(&pins, Vec2::new(100.0 + 100.0 * a.cos(), 50.0 + 50.0 * a.sin()))
}).collect();
for p in anchors(&bent) {
let d = truth.iter().map(|t| t.distance(p)).fold(f32::MAX, f32::min);
assert!(d < 2.0, "{p:?} is {d} from the true curve");
}
}
#[test]
fn unmap_finds_the_drawn_point() {
let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 200.0, 100.0)), 8);
w.pins = vec![pin(1, (20.0, 50.0), (20.0, 50.0)), pin(2, (180.0, 50.0), (200.0, 80.0))];
for p in [Vec2::new(50.0, 30.0), Vec2::new(150.0, 70.0), Vec2::new(190.0, 10.0)] {
let shown = w.map(p);
let back = w.unmap(shown).unwrap_or(Vec2::new(f32::NAN, 0.0));
assert!(back.distance(p) < 1e-2, "{p:?} → {shown:?} → {back:?}");
}
assert_eq!(w.unmap(Vec2::new(-500.0, 0.0)), None);
}
#[test]
fn deterministic_and_bounded() {
let mut w = Warp::new(blob(), 1000);
assert_eq!(w.resolution, MAX_RESOLUTION);
w.pins = (0..MAX_PINS as u64).map(|i| pin(i, (i as f32, 50.0), (i as f32 + 3.0, 50.0 + (i % 7) as f32))).collect();
let (a, b) = (w.outline(), w.outline());
assert_eq!(fingerprint(&a), fingerprint(&b));
let m = w.mesh().unwrap_or_else(unreachable_mesh);
assert!(m.rest.len() <= ((MAX_RESOLUTION + 1) * (MAX_RESOLUTION + 1)) as usize);
// Tiny, flat and enormous artwork never fails.
for p in [Path::line(Vec2::new(0.0, 0.0), Vec2::new(0.0, 0.0)), Path::line(Vec2::new(0.0, 5.0), Vec2::new(300.0, 5.0)), Path::rect(0.0, 0.0, 1e7, 1.0), Path::default()] {
let mut w = Warp::new(Arc::new(p), 12);
w.pins = vec![pin(1, (0.0, 5.0), (40.0, 9.0)), pin(2, (100.0, 5.0), (100.0, 5.0))];
let out = w.outline();
assert!(out.cmds.iter().all(|c| match *c {
PathCmd::MoveTo(p) | PathCmd::LineTo(p) => p.is_finite(),
_ => true,
}));
}
// Hostile pins are dropped on load; the rest stays.
let mut h = Warp::new(blob(), 0);
h.pins = vec![pin(1, (f32::NAN, 0.0), (0.0, 0.0)), pin(2, (1.0, 1.0), (2.0, 2.0)), pin(2, (3.0, 3.0), (3.0, 3.0))];
assert!(h.sanitize());
assert_eq!(h.pins.len(), 1);
assert_eq!(h.resolution, MIN_RESOLUTION);
}
fn warped_layer(at_end: (f32, f32), easing: Easing) -> (Layer, Warp) {
let mut shape = Shape::filled(Path::rect(0.0, 0.0, 200.0, 100.0), Paint::Solid(Rgba::hex(0x3080ff)));
let mut w = Warp::new(shape.path.clone(), 8);
w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (190.0, 50.0), (190.0, 50.0))];
shape.set_warp(w.clone());
let el = |s: Shape| Arc::new(Element { id: ElementId(5), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Shape(s) });
let mut end = shape.clone();
let mut w2 = w.clone();
if let Some(p) = w2.pins.get_mut(1) {
p.at = Vec2::new(at_end.0, at_end.1);
}
end.set_warp(w2);
let mut layer = Layer::new(LayerId(1), "Art");
let mut a = Keyframe::new(0, 10);
a.elements = vec![el(shape)];
a.tween = Some(Tween { easing, ..Default::default() });
let mut b = Keyframe::new(10, 1);
b.elements = vec![el(end)];
layer.keyframes = vec![Arc::new(a), Arc::new(b)];
(layer, w)
}
fn shape_at(layer: &Layer, frame: u32) -> Shape {
let (_, els) = evaluate_layer_elements(layer, frame).unwrap_or((0, std::borrow::Cow::Owned(Vec::new())));
match els.first().map(|e| &e.kind) {
Some(ElementKind::Shape(s)) => s.clone(),
_ => Shape::filled(Path::default(), Paint::Solid(Rgba::BLACK)),
}
}
#[test]
fn pins_tween_between_keyframes() {
let (layer, w) = warped_layer((190.0, 150.0), Easing::Linear);
let mid = shape_at(&layer, 5);
let mw = mid.live_warp().cloned().unwrap_or_else(|| w.clone());
// Halfway the pulled pin is halfway, and the outline is the mesh bent by the halfway pins.
assert_eq!(mw.pin(PinId(2)).map(|p| p.at), Some(Vec2::new(190.0, 100.0)));
let mut want = w.clone();
if let Some(p) = want.pins.get_mut(1) {
p.at = Vec2::new(190.0, 100.0);
}
assert_eq!(*mid.path, *want.outline());
// At the keyframes: exactly what they hold.
assert!(Arc::ptr_eq(&shape_at(&layer, 0).path, &w.rest));
// Easing applies to the pins as it does to bone poses.
let (eased, _) = warped_layer((190.0, 150.0), Easing::QuadIn);
let ep = shape_at(&eased, 5).live_warp().and_then(|w| w.pin(PinId(2)).map(|p| p.at.y)).unwrap_or(0.0);
assert!(ep < 100.0 && ep > 50.0, "{ep}");
}
#[test]
fn a_shape_edited_by_another_tool_drops_out_of_its_warp() {
let (layer, _) = warped_layer((190.0, 150.0), Easing::Linear);
let mut s = shape_at(&layer, 10);
assert!(s.live_warp().is_some());
s.path = Arc::new(s.path.transformed(&Affine::translate(1.0, 0.0)));
assert!(s.live_warp().is_none());
let w = s.warp.as_deref().cloned().unwrap_or_else(|| Warp::new(blob(), 4)).rebased(s.path.clone());
// Rebased, nothing moves: the edited outline is the new rest and the pins stay where they show.
assert!(w.at_rest() && w.pins.iter().any(|p| p.rest == Vec2::new(190.0, 150.0)));
}
+304
View File
@@ -0,0 +1,304 @@
//! Painted weights and reshaping a bound shape (ADR 0090), on top of shape armatures (ADR 0071).
//!
//! **Painting.** The Bind tool's brush changes how much one bone moves the points under it: each
//! dab reaches the points within its radius with a smooth falloff (`(1 − (d/r)²)²`, 1 at the
//! centre, 0 at the rim, with no kink at either), times the brush's strength. *Add* raises the
//! bone's share, *Subtract* lowers it, *Smooth* pulls it toward the falloff-weighted mean of the
//! bone's share at the points around it. After every change the point's weights are normalised
//! ([`with_share`]): the bone keeps the share it was painted to and the point's other bones share
//! what is left in the proportions they had, so the weights always sum to 1. A point that
//! followed only the painted bone gives what it loses to the bones automatic binding would give
//! it (its nearest other bones), so subtracting is never a no-op on a multi-bone shape. Painted
//! points become hand-bound (`manual`), so adding a bone later doesn't undo the painting.
//!
//! **Reshaping.** Editing the outline at rest (Subselection: moving, adding, deleting or
//! converting points) gives the skin a new rest outline. [`reshape`] carries the binding over:
//! anchors are matched old to new in path order by exact position (an edit that keeps the number
//! of anchors keeps every binding by index), deleted anchors drop theirs, and each new anchor
//! gets the weights of its matched neighbours along its subpath, blended by its distance along
//! the outline between them. A new subpath with no neighbours is bound automatically. Nothing
//! else changes, so the rest pose shows the edited outline bit for bit.
use crate::armature::BoneId;
use crate::skin::{Binding, Influence, Skin, anchors, auto_binding};
use anicraft_geom::{Path, PathCmd, Vec2};
use std::collections::HashMap;
use std::sync::Arc;
/// Largest brush radius (px).
pub const MAX_RADIUS: f32 = 2000.0;
/// Most dabs one paint command takes.
pub const MAX_DABS: usize = 4096;
/// What a dab does to the painted bone's share.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Brush {
Add,
Subtract,
Smooth,
}
impl Brush {
pub fn key(self) -> &'static str {
match self {
Brush::Add => "add",
Brush::Subtract => "subtract",
Brush::Smooth => "smooth",
}
}
pub fn parse(s: &str) -> Option<Brush> {
match s {
"add" => Some(Brush::Add),
"subtract" => Some(Brush::Subtract),
"smooth" => Some(Brush::Smooth),
_ => None,
}
}
}
/// One brush: what it does, its radius (px) and its strength at the centre (0…1).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Dab {
pub brush: Brush,
pub radius: f32,
pub strength: f32,
}
/// How much a dab of radius `r` reaches a point `d` away: `(1 − (d/r)²)²` inside, 0 outside.
pub fn falloff(d: f32, r: f32) -> f32 {
if !(r > 0.0 && d.is_finite()) || d >= r {
return 0.0;
}
let x = d / r;
let u = 1.0 - x * x;
u * u
}
/// `b` with bone `bone`'s share set to `w` (clamped to 0…1) and the point's other bones sharing
/// the rest in their old proportions; when it has no other bones, `fallback` names the bones
/// that take the rest (by weight). Normalised (the strongest four, summing to 1) and hand-bound.
/// With no other bone at all the bone keeps the whole point, or none of it when `w` is 0.
pub fn with_share(b: &Binding, bone: BoneId, w: f32, fallback: impl FnOnce() -> Vec<Influence>) -> Binding {
let w = if w.is_finite() { w.clamp(0.0, 1.0) } else { b.weight(bone) };
let mut others: Vec<Influence> = b.bones.iter().copied().filter(|i| i.0 != bone && i.1.is_finite() && i.1 > 0.0).collect();
if others.is_empty() && w < 1.0 {
others = fallback().into_iter().filter(|i| i.0 != bone && i.1.is_finite() && i.1 > 0.0).collect();
}
let rest: f32 = others.iter().map(|i| i.1).sum();
let mut out = Binding { bones: Vec::with_capacity(others.len() + 1), manual: true };
if w > 0.0 {
out.bones.push(Influence(bone, w));
}
if rest > 0.0 && rest.is_finite() {
out.bones.extend(others.iter().map(|i| Influence(i.0, i.1 / rest * (1.0 - w))));
}
out.normalize(|_| true);
out
}
/// The bones automatic binding gives a point at `p` (as drawn) leaving out `bone`: who takes a
/// point's weight when the only bone it followed gives some up.
pub fn others_at(segments: &[(BoneId, Vec2, Vec2)], bone: BoneId, p: Vec2) -> Vec<Influence> {
let without: Vec<(BoneId, Vec2, Vec2)> = segments.iter().copied().filter(|s| s.0 != bone).collect();
if without.is_empty() {
return Vec::new();
}
auto_binding(&without, p).bones
}
/// Paints bone `bone`'s share onto the skin's points: one dab of `with` at each of `dabs`,
/// reaching the points within its radius (both measured where `shown` has the points: on the
/// stage as they show). `segments` are the bones as drawn
/// ([`crate::skin::rest_segments`]). Returns how many points changed.
pub fn paint(skin: &mut Skin, segments: &[(BoneId, Vec2, Vec2)], shown: &[Vec2], bone: BoneId, dabs: &[Vec2], with: Dab) -> usize {
let brush = with.brush;
let radius = if with.radius.is_finite() { with.radius.clamp(0.0, MAX_RADIUS) } else { 0.0 };
let strength = if with.strength.is_finite() { with.strength.clamp(0.0, 1.0) } else { 0.0 };
if radius <= 0.0 || strength <= 0.0 {
return 0;
}
let rest = anchors(&skin.rest);
let n = skin.points.len().min(shown.len()).min(rest.len());
let mut changed = vec![false; n];
let mut near: Vec<(usize, f32)> = Vec::new();
for &c in dabs.iter().take(MAX_DABS) {
if !(c.x.is_finite() && c.y.is_finite()) {
continue;
}
near.clear();
for (i, p) in shown.iter().take(n).enumerate() {
// A cheap box test first: most points are far from a dab.
if (p.x - c.x).abs() >= radius || (p.y - c.y).abs() >= radius {
continue;
}
let f = falloff(p.distance(c), radius);
if f > 0.0 {
near.push((i, f));
}
}
// Smoothing pulls toward the mean before this dab changed anything.
let mean = if brush == Brush::Smooth {
let (sum, wsum) = near.iter().fold((0.0f32, 0.0f32), |(s, t), &(i, f)| (s + f * skin.points.get(i).map_or(0.0, |b| b.weight(bone)), t + f));
if wsum > 0.0 { sum / wsum } else { 0.0 }
} else {
0.0
};
for &(i, f) in &near {
let (Some(b), Some(&at)) = (skin.points.get_mut(i), rest.get(i)) else { continue };
let w = b.weight(bone);
let target = match brush {
Brush::Add => w + strength * f,
Brush::Subtract => w - strength * f,
Brush::Smooth => w + strength * f * (mean - w),
}
.clamp(0.0, 1.0);
if (target - w).abs() <= 1e-6 {
continue;
}
let next = with_share(b, bone, target, || others_at(segments, bone, at));
if next != *b {
*b = next;
if let Some(c) = changed.get_mut(i) {
*c = true;
}
}
}
}
changed.iter().filter(|c| **c).count()
}
/// Which subpath each anchor of `path` is on, and each subpath's anchor range and whether it is
/// closed (a `Close`, or ending where it starts).
fn subpaths(path: &Path) -> (Vec<usize>, Vec<(usize, usize, bool)>) {
let mut of = Vec::new();
let mut subs: Vec<(usize, usize, bool)> = Vec::new();
for c in &path.cmds {
match c {
PathCmd::MoveTo(_) => {
subs.push((of.len(), of.len() + 1, false));
of.push(subs.len() - 1);
}
PathCmd::Close => {
if let Some(s) = subs.last_mut() {
s.2 = true;
}
}
_ => {
if subs.is_empty() {
subs.push((0, 0, false));
}
let k = subs.len() - 1;
if let Some(s) = subs.last_mut() {
s.1 = of.len() + 1;
}
of.push(k);
}
}
}
let pts = anchors(path);
for s in &mut subs {
if let (Some(a), Some(b)) = (pts.get(s.0), pts.get(s.1.saturating_sub(1))) {
s.2 |= s.1 > s.0 + 1 && a == b;
}
}
(of, subs)
}
/// The binding of a new rest outline `path` for `skin`'s bindings (see the module docs):
/// matched anchors keep theirs, new ones blend their neighbours', deleted ones drop theirs.
/// `segments` bind a new subpath that has no neighbours. One binding per anchor of `path`.
pub fn reshape(skin: &Skin, path: &Path, segments: &[(BoneId, Vec2, Vec2)]) -> Vec<Binding> {
let old = anchors(&skin.rest);
let new = anchors(path);
let none = Binding::default();
if old.len() == new.len() {
// Points moved or turned smooth: the same anchors, the same bindings.
return (0..new.len()).map(|i| skin.points.get(i).cloned().unwrap_or_default()).collect();
}
// Match in path order by exact position: each new anchor takes the first old anchor after
// the last match that sits where it does.
let key = |p: Vec2| (p.x.to_bits(), p.y.to_bits());
let mut at: HashMap<(u32, u32), Vec<usize>> = HashMap::with_capacity(old.len());
for (i, p) in old.iter().enumerate() {
at.entry(key(*p)).or_default().push(i);
}
let mut matched: Vec<Option<usize>> = Vec::with_capacity(new.len());
let mut next_old = 0usize;
for p in &new {
let m = at.get(&key(*p)).and_then(|v| {
let k = v.partition_point(|&i| i < next_old);
v.get(k).copied()
});
if let Some(i) = m {
next_old = i + 1;
}
matched.push(m);
}
let (of, subs) = subpaths(path);
let binding = |i: usize| skin.points.get(i).unwrap_or(&none);
(0..new.len())
.map(|j| {
if let Some(i) = matched.get(j).copied().flatten() {
return binding(i).clone();
}
let p = new.get(j).copied().unwrap_or(Vec2::ZERO);
let Some(&(s, e, closed)) = of.get(j).and_then(|k| subs.get(*k)) else { return auto_binding(segments, p) };
let len = e.saturating_sub(s).max(1);
// Walks from `j` one way along its subpath (wrapping round a closed one) to the
// nearest matched anchor, adding up the distance between anchors on the way.
let walk = |forward: bool| -> Option<(usize, f32)> {
let (mut k, mut d) = (j, 0.0f32);
for _ in 1..len {
let step = if forward {
if k + 1 < e { k + 1 } else if closed { s } else { return None }
} else if k > s {
k - 1
} else if closed {
e - 1
} else {
return None;
};
d += new.get(k).zip(new.get(step)).map_or(0.0, |(a, b)| a.distance(*b));
k = step;
if let Some(i) = matched.get(k).copied().flatten() {
return Some((i, d));
}
}
None
};
match (walk(false), walk(true)) {
(Some((a, da)), Some((b, db))) => {
let t = if da + db > 0.0 { da / (da + db) } else { 0.5 };
blend(binding(a), binding(b), t)
}
(Some((a, _)), None) | (None, Some((a, _))) => binding(a).clone(),
(None, None) => auto_binding(segments, p),
}
})
.collect()
}
/// `(1 − t)·a + t·b`, normalised; hand-bound when either is.
fn blend(a: &Binding, b: &Binding, t: f32) -> Binding {
let mut bones: Vec<Influence> = a.bones.iter().map(|i| Influence(i.0, i.1 * (1.0 - t))).collect();
for i in &b.bones {
match bones.iter_mut().find(|x| x.0 == i.0) {
Some(x) => x.1 += i.1 * t,
None => bones.push(Influence(i.0, i.1 * t)),
}
}
let mut out = Binding { bones, manual: a.manual || b.manual };
out.normalize(|_| true);
out
}
/// `skin` with its rest outline replaced by `path` and its binding carried over ([`reshape`]).
pub fn reshaped(skin: &Skin, path: Arc<Path>, segments: &[(BoneId, Vec2, Vec2)]) -> Skin {
let points = reshape(skin, &path, segments);
Skin { shape: skin.shape, rest: path, points }
}
#[cfg(test)]
#[path = "weights_tests.rs"]
mod tests;
+264
View File
@@ -0,0 +1,264 @@
//! Painted weights and reshaping (ADR 0090).
use super::*;
use crate::armature::{Armature, Bone, Pose};
use crate::skin::{deform, rebind, rest_segments};
use crate::ElementId;
use anicraft_geom::Affine;
const SHAPE: ElementId = ElementId(10);
const B1: BoneId = BoneId(20);
const B2: BoneId = BoneId(21);
/// A bar 200 px long, 20 px thick along y = 0 with anchors every 25 px on both edges, and two
/// bones along its middle meeting at x = 100 (the shape drawn at the origin).
fn rig() -> Armature {
let mut p = Path::new();
p.move_to(Vec2::new(0.0, -10.0));
for i in 1..=8 {
p.line_to(Vec2::new(25.0 * i as f32, -10.0));
}
for i in (0..=8).rev() {
p.line_to(Vec2::new(25.0 * i as f32, 10.0));
}
p.close();
let bones = vec![
Bone::new(B1, SHAPE, ElementId(30), Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Affine::IDENTITY),
Bone::new(B2, ElementId(30), ElementId(31), Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0), Affine::IDENTITY),
];
let mut arm = Armature { bones, skin: Some(Skin::new(SHAPE, Arc::new(p))), ..Default::default() };
rebind(&mut arm);
arm
}
fn skin(arm: &Armature) -> &Skin {
arm.skin.as_ref().expect("a skin")
}
fn sums_to_one(b: &Binding) -> bool {
b.bones.is_empty() || ((b.bones.iter().map(|i| i.1).sum::<f32>() - 1.0).abs() < 1e-5 && b.bones.len() <= crate::skin::MAX_INFLUENCES && b.bones.iter().all(|i| i.1 > 0.0))
}
fn paint_on(arm: &mut Armature, bone: BoneId, dabs: &[Vec2], radius: f32, strength: f32, brush: Brush) -> usize {
let segments = rest_segments(arm);
let shown = anchors(&skin(arm).rest);
let k = arm.skin.as_mut().expect("a skin");
paint(k, &segments, &shown, bone, dabs, Dab { brush, radius, strength })
}
#[test]
fn falloff_is_one_at_the_centre_and_zero_at_the_rim() {
assert_eq!(falloff(0.0, 10.0), 1.0);
assert_eq!(falloff(10.0, 10.0), 0.0);
assert_eq!(falloff(20.0, 10.0), 0.0);
assert!(falloff(5.0, 10.0) > 0.5 && falloff(5.0, 10.0) < 0.6);
assert_eq!(falloff(1.0, 0.0), 0.0);
assert_eq!(falloff(f32::NAN, 10.0), 0.0);
}
#[test]
fn painted_weights_stay_normalised() {
let mut arm = rig();
for brush in [Brush::Add, Brush::Subtract, Brush::Smooth, Brush::Add] {
for bone in [B1, B2] {
let dabs: Vec<Vec2> = (0..40).map(|i| Vec2::new(5.0 * i as f32, if i % 2 == 0 { -10.0 } else { 10.0 })).collect();
paint_on(&mut arm, bone, &dabs, 30.0, 0.35, brush);
assert!(skin(&arm).points.iter().all(sums_to_one), "{brush:?} on {bone:?}: {:?}", skin(&arm).points);
}
}
}
#[test]
fn painting_is_local_to_the_radius() {
let mut arm = rig();
let before = skin(&arm).points.clone();
let centre = Vec2::new(25.0, -10.0);
let changed = paint_on(&mut arm, B2, &[centre], 30.0, 1.0, Brush::Add);
let pts = anchors(&skin(&arm).rest);
assert!(changed > 0);
for (i, p) in pts.iter().enumerate() {
if p.distance(centre) >= 30.0 {
assert_eq!(skin(&arm).points[i], before[i], "point {i} at {p:?} is outside the brush");
}
}
// The point under the centre now follows B2 entirely (strength 100 at the centre), and is
// hand-bound, so a new bone doesn't undo it.
assert_eq!(skin(&arm).points[1].weight(B2), 1.0);
assert!(skin(&arm).points[1].manual);
}
#[test]
fn add_raises_subtract_lowers_and_smooth_evens_out() {
let mut arm = rig();
let at = Vec2::new(100.0, -10.0);
let w0 = skin(&arm).points[4].weight(B1);
paint_on(&mut arm, B1, &[at], 20.0, 0.2, Brush::Add);
let w1 = skin(&arm).points[4].weight(B1);
assert!(w1 > w0, "{w0} → {w1}");
paint_on(&mut arm, B1, &[at, at, at], 20.0, 0.2, Brush::Subtract);
let w2 = skin(&arm).points[4].weight(B1);
assert!(w2 < w1, "{w1} → {w2}");
// A point that follows only B1 gives what it loses to B2, its nearest other bone.
let mut arm = rig();
assert_eq!(skin(&arm).points[1].weight(B1), 1.0);
paint_on(&mut arm, B1, &[Vec2::new(25.0, -10.0)], 5.0, 0.5, Brush::Subtract);
let b = &skin(&arm).points[1];
assert!((b.weight(B1) - 0.5).abs() < 1e-5 && (b.weight(B2) - 0.5).abs() < 1e-5, "{b:?}");
// Smoothing a sharp step makes the bone's shares closer to each other.
let mut arm = rig();
let spread = |arm: &Armature| {
let w: Vec<f32> = skin(arm).points.iter().map(|b| b.weight(B1)).collect();
w.iter().cloned().fold(f32::MIN, f32::max) - w.iter().cloned().fold(f32::MAX, f32::min)
};
let before = spread(&arm);
let dabs: Vec<Vec2> = (0..=16).map(|i| Vec2::new(12.5 * i as f32, 0.0)).collect();
for _ in 0..10 {
paint_on(&mut arm, B1, &dabs, 400.0, 1.0, Brush::Smooth);
}
assert!(spread(&arm) < before * 0.5, "{before} → {}", spread(&arm));
assert!(skin(&arm).points.iter().all(sums_to_one));
}
#[test]
fn nothing_paints_without_strength_or_radius() {
let mut arm = rig();
let before = skin(&arm).points.clone();
assert_eq!(paint_on(&mut arm, B1, &[Vec2::new(25.0, -10.0)], 0.0, 1.0, Brush::Add), 0);
assert_eq!(paint_on(&mut arm, B1, &[Vec2::new(25.0, -10.0)], 30.0, 0.0, Brush::Add), 0);
assert_eq!(paint_on(&mut arm, B1, &[Vec2::new(f32::NAN, 0.0)], 30.0, 1.0, Brush::Add), 0);
assert_eq!(skin(&arm).points, before);
}
#[test]
fn with_share_keeps_the_other_bones_proportions() {
let b = Binding { bones: vec![Influence(B1, 0.5), Influence(B2, 0.3), Influence(BoneId(9), 0.2)], manual: false };
let x = with_share(&b, B1, 0.8, Vec::new);
assert!((x.weight(B1) - 0.8).abs() < 1e-6);
assert!((x.weight(B2) - 0.12).abs() < 1e-6 && (x.weight(BoneId(9)) - 0.08).abs() < 1e-6);
assert!(x.manual && sums_to_one(&x));
// Without other bones, the fallback takes the rest; without any, the bone keeps it all.
let only = Binding { bones: vec![Influence(B1, 1.0)], manual: false };
assert!((with_share(&only, B1, 0.25, || vec![Influence(B2, 1.0)]).weight(B2) - 0.75).abs() < 1e-6);
assert_eq!(with_share(&only, B1, 0.25, Vec::new).weight(B1), 1.0);
assert!(with_share(&only, B1, 0.0, Vec::new).bones.is_empty());
}
/// The shape's rest outline with its edges' anchors where `edit` puts them.
fn edited(arm: &Armature, edit: impl FnOnce(&mut Path)) -> Path {
let mut p = (*skin(arm).rest).clone();
edit(&mut p);
p
}
#[test]
fn moving_points_keeps_every_binding() {
let arm = rig();
let p = edited(&arm, |p| {
if let Some(PathCmd::LineTo(q)) = p.cmds.get_mut(3) {
q.y -= 15.0;
}
});
let out = reshape(skin(&arm), &p, &rest_segments(&arm));
assert_eq!(out, skin(&arm).points);
}
#[test]
fn an_inserted_point_blends_its_neighbours() {
let mut arm = rig();
// Make the neighbours different by hand: anchor 3 (x = 75) follows B1, anchor 4 (x = 100) B2.
if let Some(k) = arm.skin.as_mut() {
k.points[3] = Binding { bones: vec![Influence(B1, 1.0)], manual: true };
k.points[4] = Binding { bones: vec![Influence(B2, 1.0)], manual: true };
}
// A point a quarter of the way from x = 75 to x = 100.
let p = edited(&arm, |p| {
p.cmds.insert(4, PathCmd::LineTo(Vec2::new(81.25, -10.0)));
});
let out = reshape(skin(&arm), &p, &rest_segments(&arm));
assert_eq!(out.len(), anchors(&p).len());
let b = &out[4];
assert!((b.weight(B1) - 0.75).abs() < 1e-5 && (b.weight(B2) - 0.25).abs() < 1e-5, "{b:?}");
assert!(b.manual && sums_to_one(b));
// Every other anchor keeps its binding.
assert_eq!(&out[..4], &skin(&arm).points[..4]);
assert_eq!(&out[5..], &skin(&arm).points[4..]);
}
#[test]
fn a_deleted_point_drops_its_binding() {
let mut arm = rig();
if let Some(k) = arm.skin.as_mut() {
k.points[5] = Binding { bones: vec![Influence(B1, 0.6), Influence(B2, 0.4)], manual: true };
}
let p = edited(&arm, |p| {
p.cmds.remove(4);
});
let out = reshape(skin(&arm), &p, &rest_segments(&arm));
let mut want = skin(&arm).points.clone();
want.remove(4);
assert_eq!(out, want);
}
#[test]
fn a_new_subpath_is_bound_automatically_and_closing_points_copy_the_start() {
let arm = rig();
let p = edited(&arm, |p| {
p.move_to(Vec2::new(150.0, -5.0));
p.line_to(Vec2::new(160.0, -5.0));
p.line_to(Vec2::new(160.0, 5.0));
p.close();
});
let segments = rest_segments(&arm);
let out = reshape(skin(&arm), &p, &segments);
let n = skin(&arm).points.len();
assert_eq!(out.len(), n + 3);
assert_eq!(out[n], auto_binding(&segments, Vec2::new(150.0, -5.0)));
// An explicit closing point at the start of a closed subpath takes the start's weights.
let p = edited(&arm, |p| {
let close = p.cmds.len() - 1;
p.cmds.insert(close, PathCmd::LineTo(Vec2::new(0.0, -10.0)));
});
let out = reshape(skin(&arm), &p, &segments);
assert_eq!(out.last(), skin(&arm).points.first());
}
#[test]
fn the_rest_pose_is_the_reshaped_outline_bit_for_bit() {
let arm = rig();
let p = Arc::new(edited(&arm, |p| {
p.cmds.insert(4, PathCmd::LineTo(Vec2::new(87.5, -10.0)));
if let Some(PathCmd::LineTo(q)) = p.cmds.get_mut(10) {
q.y -= 3.0;
}
}));
let mut arm2 = arm.clone();
arm2.skin = Some(reshaped(skin(&arm), p.clone(), &rest_segments(&arm)));
let rest = deform(&arm2, &Pose::default()).expect("an outline");
assert!(Arc::ptr_eq(&rest, &p));
// Bent, the new point moves with the bones like its neighbours: between them.
let mut pose = Pose::default();
pose.set(B2, std::f32::consts::FRAC_PI_2);
let bent = anchors(&deform(&arm2, &pose).expect("an outline"));
assert_eq!(bent.len(), anchors(&p).len());
assert!(bent.iter().all(|q| q.x.is_finite() && q.y.is_finite()));
}
#[test]
fn painting_a_large_shape_is_fast() {
// 20,000 points in a row, 32 dabs of radius 40.
let mut p = Path::new();
p.move_to(Vec2::new(0.0, 0.0));
for i in 1..20_000 {
p.line_to(Vec2::new(i as f32 * 0.1, (i % 7) as f32));
}
let bones = vec![Bone::new(B1, SHAPE, ElementId(30), Vec2::new(0.0, 0.0), Vec2::new(1000.0, 0.0), Affine::IDENTITY), Bone::new(B2, ElementId(30), ElementId(31), Vec2::new(1000.0, 0.0), Vec2::new(2000.0, 0.0), Affine::IDENTITY)];
let mut arm = Armature { bones, skin: Some(Skin::new(SHAPE, Arc::new(p))), ..Default::default() };
rebind(&mut arm);
let dabs: Vec<Vec2> = (0..32).map(|i| Vec2::new(900.0 + 10.0 * i as f32, 3.0)).collect();
let t = std::time::Instant::now();
let n = paint_on(&mut arm, B2, &dabs, 40.0, 0.3, Brush::Add);
let ms = t.elapsed().as_secs_f64() * 1000.0;
eprintln!("painting 32 dabs over 20,000 points changed {n} in {ms:.2} ms");
assert!(n > 0);
assert!(ms < 2000.0);
}
+202
View File
@@ -269,6 +269,155 @@ impl ProfilePreset {
}
}
impl WidthProfile {
/// This profile carried onto a piece of its stroke (ADR 0093): the piece runs along the
/// stretches `spans` of `path` (the stroke's path, in path positions: `k + t` is parameter
/// `t` of the segment command `k` draws, as `anicraft_geom::planar::Piece::spans` gives
/// them; a stretch with `to < from` runs backwards). The piece's width at each place is the
/// stroke's width there: every width point inside a stretch moves to the same place on the
/// piece (positions are rescaled by arc length), and where the piece starts, ends or jumps
/// mid-profile, a point there holds the width it had. Running backwards swaps left and
/// right. `None` when the piece has one width.
pub fn along(&self, path: &Path, spans: &[[f64; 2]]) -> Option<WidthProfile> {
let m = Measure::new(path);
let pts = self.points();
let (first, last) = (pts.first().map_or(0.0, |p| p.t), pts.last().map_or(1.0, |p| p.t));
let inside = |f: f32| f > first + MERGE && f < last - MERGE;
// Each stretch: its subpath, and where it starts and ends along it (arc length).
let parts: Vec<(usize, f64, f64)> = spans.iter().take(4096).filter_map(|sp| Some((m.locate(sp[0])?, m.locate(sp[1])?))).filter(|(a, b)| a.0 == b.0).map(|(a, b)| (a.0, a.1, b.1)).collect();
let total: f64 = parts.iter().map(|(_, a, b)| (b - a).abs()).sum();
if !total.is_finite() || total <= 1e-9 {
return Some(self.clone());
}
let mut out: Vec<WidthPoint> = Vec::new();
let mut cum = 0.0f64;
let side = |f: f32, fwd: bool| {
let (l, r) = self.at(f);
if fwd { (l, r) } else { (r, l) }
};
for (i, &(sub, a, b)) in parts.iter().enumerate() {
let len = m.sub_len.get(sub).copied().unwrap_or(0.0);
if !len.is_finite() || len <= 1e-12 {
continue;
}
let (fa, fb) = ((a / len) as f32, (b / len) as f32);
let fwd = b >= a;
let q = |s: f64| ((cum + (s - a).abs()) / total) as f32;
// Joined to the stretch before it without a jump: its points carry on.
let joined_before = i > 0 && parts.get(i - 1).is_some_and(|&(ps, _, pb)| ps == sub && (pb - a).abs() < 1e-6 * len.max(1.0));
let joined_after = parts.get(i + 1).is_some_and(|&(ns, na, _)| ns == sub && (na - b).abs() < 1e-6 * len.max(1.0));
let mark = |s: f64, f: f32, out: &mut Vec<WidthPoint>| {
let (l, r) = side(f, fwd);
out.push(WidthPoint::new(q(s), l, r));
};
// A width point of the stroke's own already sits there.
let has_point = |f: f32| pts.iter().any(|p| (p.t - f).abs() < 1e-6);
if !joined_before && (i > 0 || inside(fa)) && !has_point(fa) {
mark(a, fa, &mut out);
}
let (lo, hi) = (fa.min(fb) - 1e-6, fa.max(fb) + 1e-6);
let within: Vec<&WidthPoint> = pts.iter().filter(|p| p.t >= lo && p.t <= hi).collect();
let ordered: Box<dyn Iterator<Item = &&WidthPoint>> = if fwd { Box::new(within.iter()) } else { Box::new(within.iter().rev()) };
for p in ordered {
let (l, r) = if fwd { (p.left, p.right) } else { (p.right, p.left) };
out.push(WidthPoint::new(q(f64::from(p.t) * len), l, r));
}
if !joined_after && (i + 1 < parts.len() || inside(fb)) && !has_point(fb) {
mark(b, fb, &mut out);
}
cum += (b - a).abs();
}
if out.len() > MAX_WIDTH_POINTS {
// Evenly spaced, the ends kept.
let n = out.len();
let k = MAX_WIDTH_POINTS;
out = (0..k).filter_map(|i| out.get(i * (n - 1) / (k - 1)).copied()).collect();
}
if out.is_empty() {
// No point falls on the piece: it lies where the width holds, one width all along.
let f = parts.first().and_then(|&(sub, a, _)| m.sub_len.get(sub).filter(|l| **l > 1e-12).map(|l| (a / l) as f32)).unwrap_or(0.0);
let fwd = parts.first().is_none_or(|&(_, a, b)| b >= a);
let (l, r) = side(f, fwd);
out.push(WidthPoint::new(0.0, l, r));
}
WidthProfile::new(out)
}
}
/// Arc lengths along a path's subpaths, by path position.
struct Measure {
/// Each drawn command: its index, subpath, arc length where it starts, and its curve.
segs: Vec<(usize, usize, f64, [Vec2; 4])>,
sub_len: Vec<f64>,
}
impl Measure {
fn new(path: &Path) -> Measure {
use anicraft_geom::PathCmd;
let mut segs = Vec::new();
let mut sub_len: Vec<f64> = Vec::new();
let (mut start, mut cur, mut acc) = (Vec2::ZERO, Vec2::ZERO, 0.0f64);
let line = |a: Vec2, b: Vec2| [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b];
for (k, c) in path.cmds.iter().enumerate().take(1 << 20) {
let curve = match *c {
PathCmd::MoveTo(p) => {
if !sub_len.is_empty() || !segs.is_empty() {
sub_len.push(acc);
}
(start, cur, acc) = (p, p, 0.0);
continue;
}
PathCmd::LineTo(p) => line(cur, p),
PathCmd::QuadTo(q, p) => [cur, cur.lerp(q, 2.0 / 3.0), p.lerp(q, 2.0 / 3.0), p],
PathCmd::CubicTo(a, b, p) => [cur, a, b, p],
PathCmd::Close => line(cur, start),
};
segs.push((k, sub_len.len(), acc, curve));
acc += cubic_length(&curve, 1.0);
cur = curve[3];
}
sub_len.push(acc);
Measure { segs, sub_len }
}
/// The subpath and arc length from its start at path position `u`.
fn locate(&self, u: f64) -> Option<(usize, f64)> {
if !u.is_finite() {
return None;
}
let k = u.floor();
let t = u - k;
// Position `k + 1` is the end of command `k`.
let (k, t) = if t == 0.0 && k >= 1.0 && !self.segs.iter().any(|s| s.0 as f64 == k) { (k - 1.0, 1.0) } else { (k, t) };
let i = self.segs.partition_point(|s| (s.0 as f64) < k);
match self.segs.get(i) {
Some(&(cmd, sub, at, c)) if cmd as f64 == k => Some((sub, at + cubic_length(&c, t))),
// The end of the last command (or of one before a MoveTo).
_ => {
let &(_, sub, at, c) = self.segs.get(i.checked_sub(1)?)?;
(t == 0.0).then(|| (sub, at + cubic_length(&c, 1.0)))
}
}
}
}
/// Arc length of a cubic from 0 to `t` (composite five-point Gauss–Legendre on 16 pieces).
fn cubic_length(c: &[Vec2; 4], t: f64) -> f64 {
const G: [(f64, f64); 5] = [(0.046_910_077_030_668, 0.118_463_442_528_094_5), (0.230_765_344_947_158_45, 0.239_314_335_249_683_2), (0.5, 0.284_444_444_444_444_4), (0.769_234_655_052_841_6, 0.239_314_335_249_683_2), (0.953_089_922_969_332, 0.118_463_442_528_094_5)];
let t = t.clamp(0.0, 1.0);
let p = c.map(|v| (f64::from(v.x), f64::from(v.y)));
let speed = |s: f64| {
let u = 1.0 - s;
let (d0, d1, d2) = (3.0 * u * u, 6.0 * u * s, 3.0 * s * s);
let dx = d0 * (p[1].0 - p[0].0) + d1 * (p[2].0 - p[1].0) + d2 * (p[3].0 - p[2].0);
let dy = d0 * (p[1].1 - p[0].1) + d1 * (p[2].1 - p[1].1) + d2 * (p[3].1 - p[2].1);
(dx * dx + dy * dy).sqrt()
};
const N: usize = 16;
let h = t / N as f64;
(0..N).map(|i| G.iter().map(|&(x, w)| w * speed((i as f64 + x) * h)).sum::<f64>() * h).sum()
}
/// The unit normal on the left of direction `d` on a y-down screen (`-d.perp()`).
pub fn left_normal(d: Vec2) -> Vec2 {
Vec2::new(d.y, -d.x)
@@ -403,4 +552,57 @@ mod tests {
assert_eq!(sq[0].length(), 40.0);
assert!(nearest_on_stroke(&[], Vec2::ZERO).is_none());
}
fn near(a: (f32, f32), b: (f32, f32), tol: f32) -> bool {
(a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol
}
#[test]
fn a_piece_of_a_stroke_keeps_the_widths_it_had_there() {
// An asymmetric swell along a 100-long line (command 1 draws it).
let line = Path::line(Vec2::ZERO, Vec2::new(100.0, 0.0));
let p = WidthProfile::new(vec![WidthPoint::new(0.0, 0.5, 1.0), WidthPoint::new(0.4, 3.0, 2.0), WidthPoint::new(1.0, 1.0, 0.25)]).unwrap();
// Uncut: the same profile.
let whole = p.along(&line, &[[1.0, 2.0]]).unwrap();
for (a, b) in whole.points().iter().zip(p.points()) {
assert!((a.t - b.t).abs() < 1e-5 && a.left == b.left && a.right == b.right, "{whole:?}");
}
// The stretch from 20 to 70: its point at 0.4 moves to (40 − 20) / 50 = 0.4 of the piece,
// and every place on the piece has the width it had on the stroke.
let piece = p.along(&line, &[[1.2, 1.7]]).unwrap();
for k in 0..=20 {
let u = k as f32 / 20.0;
let src = 0.2 + 0.5 * u;
assert!(near(piece.at(u), p.at(src), 0.12), "at {u}: {:?} vs {:?}", piece.at(u), p.at(src));
}
assert!(piece.points().iter().any(|w| (w.t - 0.4).abs() < 1e-4 && w.left == 3.0), "{piece:?}");
// Backwards: the far end comes first, and left and right swap.
let back = p.along(&line, &[[1.7, 1.2]]).unwrap();
for k in 0..=20 {
let u = k as f32 / 20.0;
let (l, r) = p.at(0.7 - 0.5 * u);
assert!(near(back.at(u), (r, l), 0.12), "back at {u}: {:?} vs {:?}", back.at(u), (r, l));
}
// A piece where the width holds (past the last point) has none of its own.
let flat = WidthProfile::new(vec![WidthPoint::new(0.0, 0.0, 0.0), WidthPoint::new(0.5, 2.0, 2.0)]).unwrap();
assert!(flat.along(&line, &[[1.6, 2.0]]).is_some_and(|q| q.at(0.0) == (2.0, 2.0) && q.at(1.0) == (2.0, 2.0)));
let one = WidthProfile::new(vec![WidthPoint::new(0.0, 0.0, 0.0), WidthPoint::new(0.5, 1.0, 1.0)]).unwrap();
assert!(one.along(&line, &[[1.6, 2.0]]).is_none(), "nominal all along: uniform");
}
#[test]
fn pieces_across_segments_and_hostile_spans() {
// Two segments of 50 and 50: the stretch 25..75 crosses from command 1 into command 2.
let mut path = Path::new();
path.move_to(Vec2::ZERO);
path.line_to(Vec2::new(50.0, 0.0));
path.line_to(Vec2::new(50.0, 50.0));
let p = WidthProfile::new(vec![WidthPoint::new(0.0, 1.0, 1.0), WidthPoint::new(1.0, 3.0, 3.0)]).unwrap();
let piece = p.along(&path, &[[1.5, 2.0], [2.0, 2.5]]).unwrap();
assert!(near(piece.at(0.0), p.at(0.25), 1e-3) && near(piece.at(1.0), p.at(0.75), 1e-3), "{piece:?}");
// Positions past the path, not numbers, or nothing: never a panic.
let _ = p.along(&path, &[[f64::NAN, 9.0], [-4.0, 1e300]]);
assert!(p.along(&path, &[]).is_some());
assert!(p.along(&Path::new(), &[[1.0, 2.0]]).is_some());
}
}
+8 -3
View File
@@ -15,16 +15,21 @@ anicraft-xfl.workspace = true
anicraft-svg.workspace = true
anicraft-text.workspace = true
anicraft-plugins.workspace = true
craft-anicraft-format.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
rayon.workspace = true
web-time.workspace = true
gif.workspace = true
craft-gif.workspace = true
craft-image-codecs.workspace = true
craft-apng-container.workspace = true
craft-webp.workspace = true
regex.workspace = true
[dev-dependencies]
# Decodes exported sheets in tests (already in the tree through the renderer).
png.workspace = true
# Packs the XFL corpus into .fla archives in tests (ADR 0054; already in the tree through xfl).
miniz_oxide = "0.8"
# Plug-in test fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception).
wat = "1.228"
+454
View File
@@ -0,0 +1,454 @@
//! Animated PNG and animated WebP export (ADR 0063): full colour and real alpha, for the web
//! and chat apps, where an animated GIF has 256 colours and 1-bit transparency.
//!
//! Both formats share one pipeline. Frames render in parallel, a batch at a time (memory stays
//! bounded), as GIF export does. A frame identical to the one before it is merged into that
//! frame's delay. Every other frame is cut down to the rectangle that changed since the frame
//! before and compressed in parallel as an image of its own (a PNG, or a lossless WebP); the
//! compressed data is then put into one file in order, by hand, chunk by chunk:
//!
//! * **APNG** (the APNG specification): `IHDR`, `acTL`, then per frame an `fcTL` (its region,
//! delay, dispose op none, blend op) and its `IDAT` / `fdAT` data. Delays are exact fractions
//! of the document's frame rate (2 frames at 29.97 fps: 200/2997 s). A region whose changed
//! pixels are all opaque blends *over* the frame before, with its unchanged pixels left
//! transparent (they compress to almost nothing); otherwise it replaces (*source*).
//! * **WebP** (the WebP container specification): `VP8X`, `ANIM`, then an `ANMF` per frame
//! wrapping its `VP8L` (lossless) bitstream. Regions start on even pixels, as the format
//! needs, and replace what was there (no blending: the decoders' blend rounds opaque pixels).
//! Durations are whole milliseconds; each is rounded from the exact time the frame starts, so
//! the error never adds up and the running time is exact to the millisecond.
//!
//! A delay longer than one frame header can hold goes on, after the frame, as frames that
//! change nothing (one transparent pixel blended over), so timing is never cut short.
use crate::params::*;
use crate::{EngineError, Result, Session};
use anicraft_render::{View, render};
use rayon::prelude::*;
use serde_json::{Value, json};
use std::path::PathBuf;
/// The two animated formats.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Apng,
Webp,
}
impl Kind {
fn name(self) -> &'static str {
match self {
Kind::Apng => "animated PNG",
Kind::Webp => "animated WebP",
}
}
}
/// Largest animation made (frames × pixels), as for GIF: time stays bounded.
pub const MAX_ANIM_PIXELS: u64 = 600 * 1280 * 720;
/// WebP canvases and frames are at most 16384 px per side.
pub const MAX_WEBP_EDGE: u32 = 16_384;
/// Pixels rendered at once (a batch of frames), so memory stays bounded at any size.
const BATCH_PIXELS: u64 = 32 * 1024 * 1024;
/// Most plays a loop count says (both formats store it in 16 bits for WebP's sake).
pub const MAX_PLAYS: u32 = anicraft_doc::publish::MAX_PLAYS;
/// Longest WebP frame duration (24 bits of milliseconds).
const MAX_WEBP_MS: u64 = 0xFF_FFFF;
/// A rectangle of the canvas, in pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rect {
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
}
/// One frame, compressed: the region it covers, whether it blends over what is there (else it
/// replaces it), and its image data (PNG `IDAT` data, or a raw `VP8L` payload).
struct Encoded {
rect: Rect,
over: bool,
data: Vec<u8>,
}
/// The frame rate as a fraction `p / q` frames per second: 24 → 24/1, 29.97 → 2997/100,
/// 23.976 → 2997/125. Rates no small fraction matches are taken to a thousandth.
pub fn fps_ratio(fps: f32) -> (u64, u64) {
let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 24.0 };
for q in 1..=1001u64 {
let p = (fps * q as f64).round();
if p >= 1.0 && (p / q as f64 - fps).abs() <= fps * 1e-6 {
return (p as u64, q);
}
}
let p = ((fps * 1000.0).round() as u64).max(1);
let g = gcd(p, 1000);
(p / g, 1000 / g)
}
fn gcd(mut a: u64, mut b: u64) -> u64 {
while b != 0 {
(a, b) = (b, a % b);
}
a.max(1)
}
/// When frame `t` (from the first exported) starts, in whole milliseconds, rounded from the
/// exact time at `p / q` fps.
pub fn start_ms(t: u64, (p, q): (u64, u64)) -> u64 {
let p = u128::from(p.max(1));
((2 * u128::from(t) * 1000 * u128::from(q) + p) / (2 * p)) as u64
}
/// The APNG delays (numerator, denominator in seconds) of a frame shown from frame `start` for
/// `count` frames: one exact fraction, or more when it is longer than one `fcTL` holds.
pub fn apng_delays(start: u64, count: u64, (p, q): (u64, u64)) -> Vec<(u16, u16)> {
let mut out = Vec::new();
if let Ok(den) = u16::try_from(p) {
// `count` frames last count·q/p s; pieces of at most 65535/q frames always fit.
let most = (u64::from(u16::MAX) / q.max(1)).max(1);
let mut left = count;
while left > 0 {
let m = left.min(most);
let (num, g) = (m * q, gcd(m * q, p));
out.push((u16::try_from(num / g).unwrap_or(u16::MAX), u16::try_from(u64::from(den) / g).unwrap_or(den)));
left -= m;
}
} else {
// A rate with a huge denominator: milliseconds, rounded from each frame's start.
let mut ms = start_ms(start + count, (p, q)) - start_ms(start, (p, q));
while ms > 0 {
let m = ms.min(u64::from(u16::MAX));
out.push((m as u16, 1000));
ms -= m;
}
}
if out.is_empty() {
out.push((0, 1));
}
out
}
/// The WebP durations (milliseconds) of a frame shown from frame `start` for `count` frames:
/// one, or more when it is longer than one `ANMF` holds.
pub fn webp_durations(start: u64, count: u64, ratio: (u64, u64)) -> Vec<u32> {
let mut ms = start_ms(start + count, ratio).saturating_sub(start_ms(start, ratio));
let mut out = Vec::new();
loop {
let m = ms.min(MAX_WEBP_MS);
out.push(m as u32);
ms -= m;
if ms == 0 {
return out;
}
}
}
/// The smallest rectangle holding every pixel where RGBA8 images `a` and `b` (`w` × `h`) differ,
/// or `None` when they are the same.
pub fn changed(a: &[u8], b: &[u8], w: u32, h: u32) -> Option<Rect> {
let stride = w as usize * 4;
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0u32, 0u32);
for y in 0..h {
let at = y as usize * stride;
let (Some(ra), Some(rb)) = (a.get(at..at + stride), b.get(at..at + stride)) else { break };
if ra == rb {
continue;
}
let (pa, pb) = (ra.as_chunks::<4>().0, rb.as_chunks::<4>().0);
let first = pa.iter().zip(pb).position(|(u, v)| u != v).unwrap_or(0) as u32;
let last = pa.iter().zip(pb).rposition(|(u, v)| u != v).unwrap_or(0) as u32;
x0 = x0.min(first);
x1 = x1.max(last);
y0 = y0.min(y);
y1 = y;
}
(y0 != u32::MAX).then(|| Rect { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 })
}
/// Rectangle `r` of RGBA8 image `px` (`w` wide).
fn crop(px: &[u8], w: u32, r: Rect) -> Vec<u8> {
let stride = w as usize * 4;
let mut out = Vec::with_capacity(r.w as usize * r.h as usize * 4);
for y in r.y..r.y + r.h {
let at = y as usize * stride + r.x as usize * 4;
if let Some(row) = px.get(at..at + r.w as usize * 4) {
out.extend_from_slice(row);
}
}
out
}
/// What frame `cur` writes after frame `before` (none: it is the first, and covers the canvas):
/// the region, whether it blends over, and its pixels.
fn region(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> (Rect, bool, Vec<u8>) {
let full = Rect { x: 0, y: 0, w, h };
let Some(before) = before else { return (full, false, cur.to_vec()) };
let mut r = changed(before, cur, w, h).unwrap_or(full);
match kind {
Kind::Webp => {
// Frame offsets are stored halved: the region starts on an even pixel.
let (ex, ey) = (r.x & !1, r.y & !1);
r = Rect { x: ex, y: ey, w: r.w + (r.x - ex), h: r.h + (r.y - ey) };
(r, false, crop(cur, w, r))
}
Kind::Apng => {
let (old, new) = (crop(before, w, r), crop(cur, w, r));
let (po, pn) = (old.as_chunks::<4>().0, new.as_chunks::<4>().0);
if po.iter().zip(pn).all(|(o, n)| o == n || n[3] == 255) {
// Every changed pixel is opaque: blend over, unchanged pixels transparent.
let mut px = Vec::with_capacity(new.len());
for (o, n) in po.iter().zip(pn) {
px.extend_from_slice(if o == n { &[0, 0, 0, 0] } else { n });
}
(r, true, px)
} else {
(r, false, new)
}
}
}
}
/// A standalone PNG's image data: its `IDAT` chunks' contents, joined.
fn idat(png: &[u8]) -> Result<Vec<u8>> {
let mut out = Vec::new();
let mut at = 8usize;
while let Some(head) = png.get(at..at + 8) {
let len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize;
let data = png.get(at + 8..at + 8 + len).ok_or_else(|| EngineError::Format("the PNG encoder wrote a short chunk".into()))?;
if &head[4..8] == b"IDAT" {
out.extend_from_slice(data);
}
at += 12 + len;
}
Ok(out)
}
/// A RIFF file's first chunk named `id`, payload only; craft-webp owns container framing.
fn riff_chunk<'a>(riff: &'a [u8], id: &[u8; 4]) -> Option<&'a [u8]> {
let mut at = 12usize;
while let Some(head) = riff.get(at..at + 8) {
let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
let whole = 8 + len + (len & 1);
if &head[0..4] == id {
return riff.get(at + 8..at + 8 + len);
}
at += whole;
}
None
}
/// Compresses `px` (`w` × `h` RGBA8) as one frame's data.
fn compress(kind: Kind, px: &[u8], w: u32, h: u32) -> Result<Vec<u8>> {
let fail = |e: String| EngineError::Format(format!("{} frame: {e}", kind.name()));
let img = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgba, px.to_vec())
.map_err(|e| fail(e.to_string()))?;
match kind {
Kind::Apng => {
let opts = craft_image_codecs::EncodeOptions {
png_compression: craft_image_codecs::PngCompression::Best,
..Default::default()
};
let buf = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &opts).map_err(|e| fail(e.to_string()))?;
idat(&buf)
}
Kind::Webp => {
let opts = craft_image_codecs::EncodeOptions { webp_lossless: true, ..Default::default() };
let buf = craft_image_codecs::encode(&img, craft_image_codecs::Format::WebP, &opts).map_err(|e| fail(e.to_string()))?;
riff_chunk(&buf, b"VP8L").map(<[u8]>::to_vec).ok_or_else(|| fail("the WebP encoder wrote no lossless image".into()))
}
}
}
fn encode(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> Result<Encoded> {
let (rect, over, px) = region(kind, before, cur, w, h);
Ok(Encoded { rect, over, data: compress(kind, &px, rect.w, rect.h)? })
}
/// A frame that changes nothing (one transparent pixel blended over the top-left corner): how
/// a delay too long for one frame header goes on.
fn still(kind: Kind) -> Result<Encoded> {
Ok(Encoded { rect: Rect { x: 0, y: 0, w: 1, h: 1 }, over: true, data: compress(kind, &[0, 0, 0, 0], 1, 1)? })
}
// ----- the files ---------------------------------------------------------------------------
/// The shared container owns PNG chunks, CRCs and APNG sequence validation.
/// Frame selection, compression and exact rational timing remain AniCraft policy.
fn apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> Result<Vec<u8>> {
use craft_apng_container::apng::Frame;
// Bound the output by the already-compressed payloads plus exact framing.
// Pixel/frame budgets are enforced before rendering, unchanged by this adapter.
let budget = frames
.iter()
.enumerate()
.try_fold(65usize, |size, (index, (f, _))| size.checked_add(50 + if index == 0 { 0 } else { 4 }).and_then(|n| n.checked_add(f.data.len())))
.ok_or_else(|| EngineError::Format("animated PNG output size overflow".into()))?;
let frames: Vec<_> = frames
.iter()
.map(|(f, (num, den))| Frame {
width: f.rect.w,
height: f.rect.h,
x: f.rect.x,
y: f.rect.y,
delay_num: *num,
delay_den: *den,
over: f.over,
data: &f.data,
})
.collect();
craft_apng_container::apng::encode(w, h, plays, &frames, budget).map_err(|e| EngineError::Format(e.to_string()))
}
/// The animated WebP container is shared; frame selection, delta rectangles and timing
/// remain application policy. `Encoded::data` is a raw VP8L payload, not a RIFF chunk.
fn webp_file(w: u32, h: u32, plays: u32, alpha: bool, background: [u8; 4], frames: &[(&Encoded, u32)]) -> Result<Vec<u8>> {
use craft_webp::anim::{AnimFrame, AnimOptions, Payload};
let frames: Vec<_> = frames
.iter()
.map(|(f, ms)| AnimFrame {
x: f.rect.x,
y: f.rect.y,
width: f.rect.w,
height: f.rect.h,
duration_ms: *ms,
blend: f.over,
dispose_to_background: false,
payload: Payload::Lossless { vp8l: &f.data },
})
.collect();
let [r, g, b, a] = background;
let opts = AnimOptions { loop_count: u16::try_from(plays).unwrap_or(u16::MAX), background_bgra: [b, g, r, a], alpha, ..Default::default() };
craft_webp::anim::animation(w, h, &frames, &opts).map_err(|e| EngineError::Format(e.to_string()))
}
// ----- the command -------------------------------------------------------------------------
/// How many times it plays: `loop` true (or absent) forever (0), false once, or a count.
pub(crate) fn plays(p: &Value) -> Result<u32> {
match p.get("loop") {
None | Some(Value::Null) | Some(Value::Bool(true)) => Ok(0),
Some(Value::Bool(false)) => Ok(1),
Some(v) => v
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| *n <= MAX_PLAYS)
.ok_or_else(|| EngineError::Param(format!("param 'loop' must be true (forever), false (once) or how many times it plays (0 is forever, at most {MAX_PLAYS})"))),
}
}
/// `file.export_apng` and `file.export_webp`.
pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let path = PathBuf::from(str_req(p, "path")?);
// The whole movie: every scene in order.
let last = s.doc.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 = crate::cmds_file::scale_param(p)?;
let plays = plays(p)?;
let background = opt_bool(p, "background")?.unwrap_or(false);
let mut view = View::stage(&s.doc, scale);
if !background {
view.background = None;
}
let (w, h) = (view.width.max(1), view.height.max(1));
if kind == Kind::Webp && (w > MAX_WEBP_EDGE || h > MAX_WEBP_EDGE) {
return Err(EngineError::Param(format!("WebP frames are at most {MAX_WEBP_EDGE} px per side; lower 'scale'")));
}
let n = u64::from(to - from) + 1;
if n * u64::from(w) * u64::from(h) > MAX_ANIM_PIXELS {
return Err(EngineError::Param(format!("that {} would be too large ({n} frames at {w}×{h}); lower 'scale' or the frame range", kind.name())));
}
let doc = &s.doc;
let job = s.job.as_deref();
let started = web_time::Instant::now();
let batch = (BATCH_PIXELS / (u64::from(w) * u64::from(h))).clamp(2, 16) as usize;
// Each distinct frame: its first frame (from 0) and how many frames it shows for.
let mut shown: Vec<(u64, u64)> = Vec::new();
let mut encoded: Vec<Encoded> = Vec::new();
let mut prev: Option<Vec<u8>> = None;
let frames: Vec<u32> = (from..=to).collect();
for (b, chunk) in frames.chunks(batch).enumerate() {
let images: Vec<Vec<u8>> = chunk
.par_iter()
.map(|&f| {
let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?;
crate::publish::tick(job, 1)?;
Ok(pm.to_rgba8())
})
.collect::<Result<_>>()?;
// A frame like the one before it only lengthens that frame's delay.
let mut fresh: Vec<usize> = Vec::new();
let mut last_seen: Option<&[u8]> = prev.as_deref();
for (i, img) in images.iter().enumerate() {
match shown.last_mut() {
Some((_, count)) if last_seen == Some(img.as_slice()) => *count += 1,
_ => {
shown.push(((b * batch + i) as u64, 1));
fresh.push(i);
}
}
last_seen = Some(img.as_slice());
}
let made = (0..fresh.len())
.into_par_iter()
.map(|k| {
let cur = fresh.get(k).and_then(|&i| images.get(i)).ok_or_else(|| EngineError::Format("lost a frame".into()))?;
let before = match k.checked_sub(1) {
None => prev.as_deref(),
Some(j) => fresh.get(j).and_then(|&i| images.get(i)).map(Vec::as_slice),
};
encode(kind, before, cur, w, h)
})
.collect::<Result<Vec<_>>>()?;
encoded.extend(made);
if let Some(&i) = fresh.last() {
prev = images.into_iter().nth(i);
}
}
let ratio = fps_ratio(doc.stage.fps);
let pad = still(kind)?;
let bytes = match kind {
Kind::Apng => {
let mut list: Vec<(&Encoded, (u16, u16))> = Vec::new();
for (e, &(start, count)) in encoded.iter().zip(&shown) {
for (k, d) in apng_delays(start, count, ratio).into_iter().enumerate() {
list.push((if k == 0 { e } else { &pad }, d));
}
}
apng_file(w, h, plays, &list)?
}
Kind::Webp => {
let mut list: Vec<(&Encoded, u32)> = Vec::new();
for (e, &(start, count)) in encoded.iter().zip(&shown) {
for (k, d) in webp_durations(start, count, ratio).into_iter().enumerate() {
list.push((if k == 0 { e } else { &pad }, d));
}
}
let padded = list.len() > encoded.len();
let c = s.doc.stage.background.sanitized();
let q = |v: f32| (v * 255.0).round() as u8;
let bg = if background { [q(c.r), q(c.g), q(c.b), 255] } else { [0; 4] };
webp_file(w, h, plays, !background || padded, bg, &list)?
}
};
crate::vfs::write(&path, &bytes)?;
Ok(json!({
"written": path.display().to_string(),
"frames": n,
"stored_frames": encoded.len(),
"bytes": bytes.len(),
"width": w,
"height": h,
"loop": plays,
"ms": started.elapsed().as_millis() as u64,
}))
}
#[cfg(test)]
#[path = "anim_tests.rs"]
mod tests;
+497
View File
@@ -0,0 +1,497 @@
use super::*;
use crate::Session;
use anicraft_doc::sample;
use serde_json::json;
use std::path::Path;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
}
fn tmp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("anicraft-anim-{}-{name}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// What the CPU renderer draws for movie frames `from..=to`, as straight RGBA8.
fn renders(doc: &anicraft_doc::Document, from: u32, to: u32, scale: f32, background: bool) -> Vec<Vec<u8>> {
let mut view = View::stage(doc, scale);
if !background {
view.background = None;
}
(from..=to).map(|f| render(&anicraft_doc::evaluate(doc, f), &view).unwrap().0.to_rgba8()).collect()
}
/// An APNG decoded as a player shows it (the APNG specification's compositing): each frame's
/// canvas, its delay (num, den), its region and blend op, and the play count.
struct ApngFrame {
canvas: Vec<u8>,
delay: (u16, u16),
rect: Rect,
over: bool,
}
struct Apng {
frames: Vec<ApngFrame>,
plays: u32,
size: (u32, u32),
}
fn decode_apng(bytes: &[u8]) -> Apng {
assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
let mut pos = 8usize;
let mut ihdr = [0u8; 13];
let mut num_frames = 0u32;
let mut plays = 0u32;
struct RawFc {
w: u32,
h: u32,
x: u32,
y: u32,
delay_num: u16,
delay_den: u16,
dispose: u8,
blend: u8,
idat: Vec<u8>,
}
let mut raw_frames: Vec<RawFc> = Vec::new();
while pos + 12 <= bytes.len() {
let len = u32::from_be_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = bytes[pos + 4..pos + 8].try_into().unwrap();
let data = &bytes[pos + 8..pos + 8 + len];
pos += 12 + len;
match &kind {
b"IHDR" => ihdr.copy_from_slice(data),
b"acTL" => {
num_frames = u32::from_be_bytes(data[0..4].try_into().unwrap());
plays = u32::from_be_bytes(data[4..8].try_into().unwrap());
}
b"fcTL" => {
raw_frames.push(RawFc {
w: u32::from_be_bytes(data[4..8].try_into().unwrap()),
h: u32::from_be_bytes(data[8..12].try_into().unwrap()),
x: u32::from_be_bytes(data[12..16].try_into().unwrap()),
y: u32::from_be_bytes(data[16..20].try_into().unwrap()),
delay_num: u16::from_be_bytes(data[20..22].try_into().unwrap()),
delay_den: u16::from_be_bytes(data[22..24].try_into().unwrap()),
dispose: data[24],
blend: data[25],
idat: Vec::new(),
});
}
b"IDAT" => {
if let Some(f) = raw_frames.last_mut() {
f.idat.extend_from_slice(data);
}
}
b"fdAT" => {
if let Some(f) = raw_frames.last_mut() {
f.idat.extend_from_slice(&data[4..]);
}
}
b"IEND" => break,
_ => {}
}
}
assert_eq!(raw_frames.len(), num_frames as usize);
let w = u32::from_be_bytes(ihdr[0..4].try_into().unwrap());
let h = u32::from_be_bytes(ihdr[4..8].try_into().unwrap());
assert_eq!((ihdr[8], ihdr[9]), (8, 6), "8-bit RGBA");
let mut canvas = vec![0u8; (w * h * 4) as usize];
let mut frames = Vec::new();
let push_chunk = |out: &mut Vec<u8>, tag: &[u8; 4], payload: &[u8]| {
out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
out.extend_from_slice(tag);
out.extend_from_slice(payload);
let mut crc_buf = Vec::with_capacity(4 + payload.len());
crc_buf.extend_from_slice(tag);
crc_buf.extend_from_slice(payload);
out.extend_from_slice(&anicraft_xfl::zip::crc32(&crc_buf).to_be_bytes());
};
for fc in raw_frames {
assert_eq!(fc.dispose, 0, "DisposeOp::None");
let over = fc.blend == 1;
let r = Rect { x: fc.x, y: fc.y, w: fc.w, h: fc.h };
assert!(r.x + r.w <= w && r.y + r.h <= h);
let mut frame_png = Vec::from(&b"\x89PNG\r\n\x1a\n"[..]);
let mut f_ihdr = ihdr;
f_ihdr[0..4].copy_from_slice(&r.w.to_be_bytes());
f_ihdr[4..8].copy_from_slice(&r.h.to_be_bytes());
push_chunk(&mut frame_png, b"IHDR", &f_ihdr);
push_chunk(&mut frame_png, b"IDAT", &fc.idat);
push_chunk(&mut frame_png, b"IEND", &[]);
let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &frame_png).unwrap();
assert_eq!(img.dimensions(), (r.w, r.h));
let buf = img.to_rgba8();
for y in 0..r.h {
for x in 0..r.w {
let s = ((y * r.w + x) * 4) as usize;
let d = (((r.y + y) * w + r.x + x) * 4) as usize;
let src = &buf[s..s + 4];
if over {
// Exact for the pixels the exporter blends: transparent or opaque.
assert!(src[3] == 0 || src[3] == 255, "an over-blended pixel is neither transparent nor opaque");
if src[3] == 255 {
canvas[d..d + 4].copy_from_slice(src);
}
} else {
canvas[d..d + 4].copy_from_slice(src);
}
}
}
frames.push(ApngFrame { canvas: canvas.clone(), delay: (fc.delay_num, fc.delay_den), rect: r, over });
}
Apng { frames, plays, size: (w, h) }
}
/// The frames an APNG shows, one per movie frame at `ratio` fps (each delay is a whole number
/// of movie frames, exactly).
fn apng_movie(a: &Apng, (p, q): (u64, u64)) -> Vec<Vec<u8>> {
let mut out = Vec::new();
for f in &a.frames {
let (num, den) = (u64::from(f.delay.0), u64::from(f.delay.1));
// num/den s = k·q/p s
assert_eq!((num * p) % (den * q), 0, "a delay of {num}/{den} s is not a whole number of frames at {p}/{q} fps");
for _ in 0..num * p / (den * q) {
out.push(f.canvas.clone());
}
}
out
}
/// A WebP decoded as a player shows it: each frame's canvas and duration.
/// An animated WebP's frames (canvas, milliseconds), loop count, size and whether it has alpha.
struct Webp {
frames: Vec<(Vec<u8>, u32)>,
loop_count: u16,
size: (u32, u32),
alpha: bool,
}
fn decode_webp(bytes: &[u8]) -> Webp {
let info = craft_webp::scan(bytes, 1024).unwrap();
assert!(!info.frames.is_empty());
let decoded = craft_image_codecs::decode_webp_frames(bytes, &craft_image_codecs::DecodeOptions::default()).unwrap();
let frames = decoded.into_iter().map(|f| (f.image.to_rgba8(), f.delay_ms)).collect();
Webp { frames, loop_count: info.loop_count.unwrap_or(0), size: (info.width, info.height), alpha: info.alpha }
}
/// The frames a WebP shows, one per movie frame: the frame showing when each starts.
fn webp_movie(frames: &[(Vec<u8>, u32)], n: u64, ratio: (u64, u64)) -> Vec<Vec<u8>> {
let mut starts = Vec::new();
let mut t = 0u64;
for (_, ms) in frames {
starts.push(t);
t += u64::from(*ms);
}
assert_eq!(t, start_ms(n, ratio), "the running time is exact to the millisecond");
(0..n).map(|f| {
let at = start_ms(f, ratio);
let i = starts.iter().rposition(|s| *s <= at).unwrap();
frames[i].0.clone()
})
.collect()
}
fn same(got: &[Vec<u8>], want: &[Vec<u8>], what: &str) {
assert_eq!(got.len(), want.len(), "{what}: frame count");
for (k, (g, w)) in got.iter().zip(want).enumerate() {
assert!(g == w, "{what}: frame {} differs from the CPU renderer", k + 1);
}
}
/// A ball that holds still for 10 frames, jumps, and holds 6 more: 16 frames, 2 pictures.
fn holds() -> Session {
let mut s = Session::default();
run(&mut s, "draw.ellipse", json!({"x": 40, "y": 40, "w": 60, "h": 60}));
run(&mut s, "timeline.goto", json!({"frame": 10}));
run(&mut s, "timeline.insert_keyframe", json!({}));
run(&mut s, "edit.select_all", json!({}));
run(&mut s, "element.translate", json!({"dx": 200, "dy": 30}));
run(&mut s, "timeline.goto", json!({"frame": 15}));
run(&mut s, "timeline.insert_frame", json!({}));
assert_eq!(s.frame_count(), 16);
s
}
#[test]
fn frame_rates_are_exact_fractions() {
assert_eq!(fps_ratio(24.0), (24, 1));
assert_eq!(fps_ratio(29.97), (2997, 100));
assert_eq!(fps_ratio(23.976), (2997, 125));
assert_eq!(fps_ratio(12.5), (25, 2));
assert_eq!(fps_ratio(f32::NAN), (24, 1));
assert_eq!(fps_ratio(-3.0), (24, 1));
// Millisecond starts round from the exact time, so the error never adds up.
assert_eq!(start_ms(24, (24, 1)), 1000);
assert_eq!(start_ms(1, (30, 1)), 33);
assert_eq!(start_ms(2, (30, 1)), 67);
assert_eq!(start_ms(2997, (2997, 100)), 100_000);
assert_eq!(webp_durations(0, 3, (30, 1)), vec![100]);
let total: u32 = (0..30).flat_map(|i| webp_durations(i, 1, (30, 1))).sum();
assert_eq!(total, 1000);
// APNG delays are fractions of the frame rate, reduced.
assert_eq!(apng_delays(0, 1, (24, 1)), vec![(1, 24)]);
assert_eq!(apng_delays(0, 6, (24, 1)), vec![(1, 4)]);
assert_eq!(apng_delays(5, 2, (2997, 100)), vec![(200, 2997)]);
// Longer than one fcTL holds: more pieces, adding up exactly.
let long = apng_delays(0, 200_000, (2997, 100));
assert!(long.len() > 1);
let frames: u64 = long.iter().map(|&(n, d)| u64::from(n) * 2997 / (u64::from(d) * 100)).sum();
assert_eq!(frames, 200_000);
// A rate with a huge denominator falls back to milliseconds, still adding up.
let odd = (100_003, 1000);
let ms: u64 = apng_delays(0, 1000, odd).iter().map(|&(n, d)| {
assert_eq!(d, 1000);
u64::from(n)
}).sum();
assert_eq!(ms, start_ms(1000, odd));
let hours = webp_durations(0, 100_000, (1, 1));
assert_eq!(hours.iter().map(|&m| u64::from(m)).sum::<u64>(), 100_000_000);
assert!(hours.iter().all(|&m| u64::from(m) <= MAX_WEBP_MS) && hours.len() > 1);
}
#[test]
fn the_changed_rectangle_is_tight() {
let (w, h) = (8u32, 6u32);
let a = vec![0u8; (w * h * 4) as usize];
assert_eq!(changed(&a, &a, w, h), None);
let mut b = a.clone();
b[((2 * w + 3) * 4 + 1) as usize] = 9; // (3, 2)
b[((4 * w + 6) * 4 + 3) as usize] = 9; // (6, 4)
assert_eq!(changed(&a, &b, w, h), Some(Rect { x: 3, y: 2, w: 4, h: 3 }));
// WebP regions start on even pixels; APNG's stay tight.
let (r, over, px) = region(Kind::Webp, Some(&a), &b, w, h);
assert_eq!((r, over, px.len()), (Rect { x: 2, y: 2, w: 5, h: 3 }, false, 5 * 3 * 4));
let (r, over, _) = region(Kind::Apng, Some(&a), &b, w, h);
assert_eq!((r, over), (Rect { x: 3, y: 2, w: 4, h: 3 }, false), "semi-transparent changes replace");
let mut c = a.clone();
c[((2 * w + 3) * 4) as usize..((2 * w + 3) * 4 + 4) as usize].copy_from_slice(&[1, 2, 3, 255]);
let (r, over, px) = region(Kind::Apng, Some(&a), &c, w, h);
assert_eq!((r, over, px), (Rect { x: 3, y: 2, w: 1, h: 1 }, true, vec![1, 2, 3, 255]), "opaque changes blend over");
}
#[test]
fn apng_frames_match_the_renderer_exactly() {
let dir = tmp("apng");
let mut s = Session::new(sample::demo());
for background in [false, true] {
let path = dir.join(format!("walk-{background}.png"));
let v = run(&mut s, "file.export_apng", json!({"path": path.display().to_string(), "scale": 0.25, "to": 23, "background": background}));
assert_eq!(v["frames"], 24);
let bytes = std::fs::read(&path).unwrap();
assert_eq!(v["bytes"], bytes.len());
let a = decode_apng(&bytes);
assert_eq!(a.plays, 0, "loops forever by default");
let want = renders(&s.doc, 0, 23, 0.25, background);
assert_eq!(a.size, (320, 180));
same(&apng_movie(&a, fps_ratio(s.doc.stage.fps)), &want, "APNG");
// Frames after the first cover only what changed.
assert!(a.frames.iter().skip(1).any(|f| f.rect.w * f.rect.h < 320 * 180), "dirty rectangles");
if background {
assert!(a.frames.iter().skip(1).all(|f| f.over), "opaque frames blend over");
}
// The default image is the first frame, and a plain PNG reader sees it.
assert_eq!((a.frames[0].rect.w, a.frames[0].rect.h, a.frames[0].rect.x, a.frames[0].rect.y), (320, 180, 0, 0));
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn webp_frames_match_the_renderer_exactly() {
let dir = tmp("webp");
let mut s = Session::new(sample::demo());
for background in [false, true] {
let path = dir.join(format!("walk-{background}.webp"));
let v = run(&mut s, "file.export_webp", json!({"path": path.display().to_string(), "scale": 0.25, "from": 4, "to": 27, "background": background}));
assert_eq!(v["frames"], 24);
let bytes = std::fs::read(&path).unwrap();
assert!(bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP");
assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len());
let Webp { frames, loop_count, size, alpha } = decode_webp(&bytes);
assert_eq!((size, alpha), ((320, 180), !background));
assert_eq!(loop_count, 0);
let want = renders(&s.doc, 4, 27, 0.25, background);
same(&webp_movie(&frames, 24, fps_ratio(s.doc.stage.fps)), &want, "WebP");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn identical_frames_merge_into_longer_delays() {
let dir = tmp("holds");
let mut s = holds();
let ratio = fps_ratio(s.doc.stage.fps);
let want = renders(&s.doc, 0, 15, 1.0, false);
let png = dir.join("holds.png");
let v = run(&mut s, "file.export_apng", json!({"path": png.display().to_string(), "loop": 3}));
assert_eq!((v["frames"].as_u64(), v["stored_frames"].as_u64(), v["loop"].as_u64()), (Some(16), Some(2), Some(3)));
let a = decode_apng(&std::fs::read(&png).unwrap());
assert_eq!(a.frames.len(), 2);
assert_eq!(a.plays, 3);
let fps = s.doc.stage.fps;
assert_eq!(a.frames[0].delay, apng_delays(0, 10, ratio)[0], "10 frames at {fps} fps");
same(&apng_movie(&a, ratio), &want, "held APNG");
let webp = dir.join("holds.webp");
let v = run(&mut s, "file.export_webp", json!({"path": webp.display().to_string(), "loop": false}));
assert_eq!(v["stored_frames"], 2);
let Webp { frames, loop_count, .. } = decode_webp(&std::fs::read(&webp).unwrap());
assert_eq!(frames.len(), 2);
assert_eq!(loop_count, 1);
same(&webp_movie(&frames, 16, ratio), &want, "held WebP");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn bad_params_are_refused_and_overwrites_confirm() {
let dir = tmp("params");
let mut s = holds();
let at = |n: &str| dir.join(n).display().to_string();
for id in ["file.export_apng", "file.export_webp"] {
for bad in [json!({"loop": -1}), json!({"loop": 70_000}), json!({"loop": "yes"}), json!({"scale": 0}), json!({"from": 9, "to": 2}), json!({"background": 3})] {
let mut p = bad.clone();
p["path"] = json!(at("x.out"));
assert!(s.execute(id, &p).is_err(), "{id} {bad}");
}
assert!(s.execute(id, &json!({"path": at("big.out"), "scale": 8})).is_err(), "{id}: too large");
assert!(!Path::new(&at("x.out")).exists() && !Path::new(&at("big.out")).exists());
let path = at(&format!("once-{id}.out"));
run(&mut s, id, json!({"path": path, "to": 1}));
assert!(s.execute(id, &json!({"path": path})).is_err(), "{id}: replacing a file asks first");
run(&mut s, id, json!({"path": path, "confirm": true}));
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_cancelled_publish_stops_the_export() {
let mut s = Session::new(sample::demo());
let job = std::sync::Arc::new(crate::publish::Control::default());
job.cancel();
s.job = Some(job);
let dir = tmp("cancel");
let path = dir.join("walk.webp");
let e = s.execute("file.export_webp", &json!({"path": path.display().to_string(), "scale": 0.1})).unwrap_err();
assert!(matches!(e, EngineError::Cancelled), "{e}");
assert!(!path.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "a measurement: cargo test --release -p anicraft-engine anim::tests::sizes -- --ignored --nocapture"]
fn sizes() {
// docs/performance.md › Animated exports: the sample, every frame, at full size and half.
let dir = tmp("sizes");
for scale in [1.0, 0.5] {
let mut s = Session::new(sample::demo());
let mut row = format!("scale {scale}:");
for (id, ext, extra) in [
("file.export_gif", "gif", json!({})),
("file.export_apng", "png", json!({"background": true})),
("file.export_apng", "png", json!({})),
("file.export_webp", "webp", json!({"background": true})),
("file.export_webp", "webp", json!({})),
] {
let mut p = extra.clone();
p["path"] = json!(dir.join(format!("walk-{scale}-{}.{ext}", extra.as_object().map_or(0, |o| o.len()))).display().to_string());
p["scale"] = json!(scale);
p["confirm"] = json!(true);
let t = std::time::Instant::now();
let v = run(&mut s, id, p);
row.push_str(&format!(" | {id} {extra}: {} KB, {} stored, {} ms", v["bytes"].as_u64().unwrap() / 1024, v["stored_frames"], t.elapsed().as_millis()));
}
println!("{row}");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn shared_webp_container_preserves_payload_timing_loop_and_alpha() {
let px = [12, 34, 56, 128];
let f = encode(Kind::Webp, None, &px, 1, 1).unwrap();
assert_eq!(f.data.first(), Some(&0x2f), "raw VP8L payload, not a nested chunk");
let bytes = webp_file(1, 1, 7, true, [1, 2, 3, 4], &[(&f, 123)]).unwrap();
let anim = riff_chunk(&bytes, b"ANIM").unwrap();
assert_eq!(anim, &[3, 2, 1, 4, 7, 0]);
let frame = riff_chunk(&bytes, b"ANMF").unwrap();
assert_eq!(&frame[12..15], &[123, 0, 0], "single-frame duration is retained on the wire");
// The pinned image decoder treats one-frame WebP as a still image (delay 0).
// Check that contract separately, then use two distinct frames to exercise playback timing.
let decoded = decode_webp(&bytes);
assert_eq!(decoded.frames, vec![(px.to_vec(), 0)]);
let second_px = [90, 80, 70, 160];
let second = encode(Kind::Webp, None, &second_px, 1, 1).unwrap();
let animation = webp_file(1, 1, 7, true, [1, 2, 3, 4], &[(&f, 123), (&second, 47)]).unwrap();
let decoded = decode_webp(&animation);
assert_eq!(decoded.size, (1, 1));
assert_eq!(decoded.loop_count, 7);
assert!(decoded.alpha);
assert_eq!(decoded.frames, vec![(px.to_vec(), 123), (second_px.to_vec(), 47)]);
assert!(webp_file(1, 1, 0, false, [0; 4], &[]).is_err());
assert!(webp_file(1, 1, 0, false, [0; 4], &[(&f, 1 << 24)]).is_err());
}
// Frozen pre-cutover assembly oracle (original APNG implementation by Tanish Manku).
fn png_chunk(out: &mut Vec<u8>, id: &[u8; 4], data: &[u8]) -> Result<()> {
let len =
u32::try_from(data.len()).ok().filter(|l| *l < 1 << 31).ok_or_else(|| EngineError::Format("an animated PNG frame is too large".into()))?;
out.extend_from_slice(&len.to_be_bytes());
let from = out.len();
out.extend_from_slice(id);
out.extend_from_slice(data);
let crc = anicraft_xfl::zip::crc32(out.get(from..).unwrap_or(&[]));
out.extend_from_slice(&crc.to_be_bytes());
Ok(())
}
/// The APNG file: frames with their delays (the first frame is the default image).
fn legacy_apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> Result<Vec<u8>> {
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
let mut ihdr = Vec::with_capacity(13);
ihdr.extend_from_slice(&w.to_be_bytes());
ihdr.extend_from_slice(&h.to_be_bytes());
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA, deflate, adaptive filters, no interlace
png_chunk(&mut out, b"IHDR", &ihdr)?;
let count = u32::try_from(frames.len()).map_err(|_| EngineError::Format("too many frames".into()))?;
let mut actl = count.to_be_bytes().to_vec();
actl.extend_from_slice(&plays.to_be_bytes());
png_chunk(&mut out, b"acTL", &actl)?;
let mut seq = 0u32;
for (k, (f, (num, den))) in frames.iter().enumerate() {
let mut fctl = Vec::with_capacity(26);
for v in [seq, f.rect.w, f.rect.h, f.rect.x, f.rect.y] {
fctl.extend_from_slice(&v.to_be_bytes());
}
fctl.extend_from_slice(&num.to_be_bytes());
fctl.extend_from_slice(&den.to_be_bytes());
fctl.extend_from_slice(&[0, u8::from(f.over)]); // dispose: none; blend: source or over
png_chunk(&mut out, b"fcTL", &fctl)?;
seq += 1;
if k == 0 {
png_chunk(&mut out, b"IDAT", &f.data)?;
} else {
let mut fdat = Vec::with_capacity(f.data.len() + 4);
fdat.extend_from_slice(&seq.to_be_bytes());
fdat.extend_from_slice(&f.data);
png_chunk(&mut out, b"fdAT", &fdat)?;
seq += 1;
}
}
png_chunk(&mut out, b"IEND", &[])?;
Ok(out)
}
#[test]
fn shared_apng_container_preserves_exact_wire_bytes() {
let first = Encoded { rect: Rect { x: 0, y: 0, w: 3, h: 2 }, over: false, data: vec![1, 2, 3] };
let second = Encoded { rect: Rect { x: 2, y: 1, w: 1, h: 1 }, over: true, data: vec![4, 5] };
for plays in [0, 1, 7] {
for delay in [(0, 0), (200, 2997), (u16::MAX, u16::MAX)] {
let frames = [(&first, delay), (&second, (1, 100)), (&second, (0, 1))];
assert_eq!(apng_file(3, 2, plays, &frames).unwrap(), legacy_apng_file(3, 2, plays, &frames).unwrap());
}
}
assert!(apng_file(3, 2, 0, &[]).is_err());
assert!(apng_file(3, 2, 0, &[(&second, (1, 1))]).is_err());
}
+515
View File
@@ -0,0 +1,515 @@
//! The brush library (ADR 0068): brush presets, the built-in ones and the user's own.
//!
//! A preset is a set of tip settings (size, shape, angle, roundness, smoothing), a pressure
//! curve, what pressure drives (size, opacity), and shaping (tapers, dab spacing, a ragged
//! edge). Everything is a parameter: no bitmaps, so a preset is a few numbers, renders at any
//! size and gives the same outline from the same points every time.
//!
//! The built-ins are AniCraft's own, made from these parameters. The user's presets belong to
//! the session (they survive New and Open, like recent files); the desktop app keeps them in
//! its preferences and puts them back at start, so the engine never reads the settings folder.
//! A brush set moves between computers as a small JSON file (`brush.preset_export`/`_import`).
use crate::params::*;
use crate::{EngineError, Result};
use anicraft_geom::brush::{Shaping, TiltResponse, Tip, TipShape};
use anicraft_geom::pressure::PressureCurve;
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// Most presets of the user's own.
pub const MAX_USER_PRESETS: usize = 200;
/// Longest preset name, in characters.
pub const MAX_NAME: usize = 64;
/// Largest brush set file read.
pub const MAX_FILE_BYTES: u64 = 1 << 20;
/// What a brush set file says it is.
pub const FILE_FORMAT: &str = "anicraft-brushes";
pub const FILE_VERSION: u32 = 1;
/// A tip shape as a preset stores it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Shape {
#[default]
Round,
Square,
}
impl Shape {
pub fn tip(self) -> TipShape {
match self {
Shape::Round => TipShape::Round,
Shape::Square => TipShape::Square,
}
}
pub fn from_tip(t: TipShape) -> Shape {
match t {
TipShape::Round => Shape::Round,
TipShape::Square => Shape::Square,
}
}
pub fn key(self) -> &'static str {
match self {
Shape::Round => "round",
Shape::Square => "square",
}
}
}
/// A brush preset. Percentages are as Properties shows them.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct BrushPreset {
pub name: String,
/// Diameter (or side), stage units.
pub size: f32,
pub shape: Shape,
/// Degrees, clockwise.
pub angle: f32,
/// The narrow side as a percentage of the wide one (5..=100).
pub roundness: f32,
/// 0..=100.
pub smoothing: f32,
/// How pen pressure maps before it drives size or opacity.
pub curve: PressureCurve,
/// Pressure varies the size (from 10 % to 100 %).
pub pressure_size: bool,
/// Pressure varies the paint's opacity (the stroke's average, ADR 0068).
pub pressure_opacity: bool,
/// Percentages of the stroke's length (0..=50).
pub taper_start: f32,
pub taper_end: f32,
/// 0: a continuous stroke; otherwise dabs this far apart, as a percentage of the size
/// (5..=1000).
pub spacing: f32,
/// A ragged edge, worn in by up to this percentage of the size (0..=50).
pub jitter: f32,
/// A paper grain of holes through the paint, as a percentage (0..=100; ADR 0093).
pub texture: f32,
/// Dabs thrown either side of the line, up to this percentage of the size (0..=200).
pub scatter: f32,
/// The pen's tilt turns the tip (its angle plus the pen's azimuth).
pub tilt_angle: bool,
/// The pen's tilt widens the tip (up to twice as wide lying flat).
pub tilt_width: bool,
}
impl Default for BrushPreset {
/// The Brush tool's own defaults (ADR 0033).
fn default() -> Self {
BrushPreset {
name: String::new(),
size: 10.0,
shape: Shape::Round,
angle: 0.0,
roundness: 100.0,
smoothing: 50.0,
curve: PressureCurve::LINEAR,
pressure_size: true,
pressure_opacity: false,
taper_start: 0.0,
taper_end: 0.0,
spacing: 0.0,
jitter: 0.0,
texture: 0.0,
scatter: 0.0,
tilt_angle: false,
tilt_width: false,
}
}
}
/// The built-in presets: `(key, name)`, in the order the library shows them.
pub const BUILTIN: [(&str, &str); 9] = [
("pencil", "Pencil"),
("ink_pen", "Ink Pen"),
("calligraphy", "Flat Calligraphy"),
("round_taper", "Round Taper"),
("marker", "Marker"),
("chalk", "Chalk"),
("dotted", "Dotted"),
("charcoal", "Charcoal"),
("spatter", "Spatter"),
];
/// A one-line description of each built-in preset, for tooltips.
pub fn builtin_hint(key: &str) -> &'static str {
match key {
"pencil" => "A thin line with short tapered ends; it takes a firm press to paint wide.",
"ink_pen" => "A smooth inking line that follows a light touch and tapers at both ends.",
"calligraphy" => "A flat nib at 45°: thick and thin strokes by direction.",
"round_taper" => "A round brush that swells from a point and thins back to one.",
"marker" => "A chisel-tipped marker of one width, whatever the pressure.",
"chalk" => "A broad stroke with a ragged, worn edge.",
"dotted" => "Round dots spaced along the stroke.",
"charcoal" => "A soft, broad stroke with the paper's grain showing through; it follows the pen's tilt.",
"spatter" => "Drops of paint thrown either side of the stroke.",
_ => "",
}
}
/// A built-in preset by key.
pub fn builtin(key: &str) -> Option<BrushPreset> {
let (_, name) = BUILTIN.iter().find(|(k, _)| *k == key)?;
let d = BrushPreset { name: (*name).to_string(), ..BrushPreset::default() };
Some(match key {
"pencil" => BrushPreset { size: 3.0, smoothing: 30.0, curve: PressureCurve::FIRM, taper_start: 5.0, taper_end: 5.0, ..d },
"ink_pen" => BrushPreset { size: 6.0, smoothing: 60.0, curve: PressureCurve::SOFT, taper_start: 12.0, taper_end: 18.0, ..d },
"calligraphy" => BrushPreset { size: 18.0, angle: 45.0, roundness: 15.0, smoothing: 50.0, ..d },
"round_taper" => BrushPreset { size: 14.0, smoothing: 55.0, taper_start: 35.0, taper_end: 35.0, ..d },
"marker" => BrushPreset { size: 16.0, shape: Shape::Square, angle: 30.0, roundness: 45.0, smoothing: 40.0, pressure_size: false, ..d },
"chalk" => BrushPreset { size: 20.0, roundness: 80.0, angle: 20.0, smoothing: 40.0, jitter: 18.0, ..d },
"dotted" => BrushPreset { size: 8.0, smoothing: 60.0, pressure_size: false, spacing: 220.0, ..d },
"charcoal" => BrushPreset { size: 24.0, roundness: 60.0, angle: 30.0, smoothing: 45.0, curve: PressureCurve::SOFT, jitter: 8.0, texture: 35.0, tilt_angle: true, tilt_width: true, ..d },
"spatter" => BrushPreset { size: 7.0, smoothing: 50.0, spacing: 60.0, scatter: 140.0, ..d },
_ => d,
})
}
impl BrushPreset {
/// The values clamped to their ranges (a file or a hand-edited preference).
pub fn sanitized(mut self) -> BrushPreset {
let d = BrushPreset::default();
let c = |v: f32, lo: f32, hi: f32, def: f32| if v.is_finite() { v.clamp(lo, hi) } else { def };
self.name = clean_name(&self.name).unwrap_or_default();
self.size = c(self.size, *crate::cmds_brush::SIZE_RANGE.start(), *crate::cmds_brush::SIZE_RANGE.end(), d.size);
self.angle = c(self.angle, -1e6, 1e6, 0.0).rem_euclid(180.0);
self.roundness = c(self.roundness, 5.0, 100.0, 100.0);
self.smoothing = c(self.smoothing, 0.0, 100.0, d.smoothing);
self.curve = PressureCurve::new(self.curve.points());
self.taper_start = c(self.taper_start, 0.0, 50.0, 0.0);
self.taper_end = c(self.taper_end, 0.0, 50.0, 0.0);
self.spacing = c(self.spacing, 0.0, 1000.0, 0.0);
if self.spacing > 0.0 {
self.spacing = self.spacing.max(5.0);
}
self.jitter = c(self.jitter, 0.0, 50.0, 0.0);
self.texture = c(self.texture, 0.0, 100.0, 0.0);
self.scatter = c(self.scatter, 0.0, 200.0, 0.0);
self
}
pub fn tip(&self) -> Tip {
Tip { shape: self.shape.tip(), size: self.size, angle: self.angle, roundness: self.roundness / 100.0 }
}
pub fn shaping(&self) -> Shaping {
Shaping {
taper_start: self.taper_start / 100.0,
taper_end: self.taper_end / 100.0,
spacing: self.spacing / 100.0,
jitter: self.jitter / 100.0,
texture: self.texture / 100.0,
scatter: self.scatter / 100.0,
tilt: TiltResponse { angle: self.tilt_angle, width: self.tilt_width },
}
.sanitized()
}
/// The tip's size factor input at a measured pressure: the curve's output when pressure
/// drives the size, else full.
pub fn size_pressure(&self, pressure: f32) -> f32 {
if self.pressure_size { self.curve.map(pressure) } else { 1.0 }
}
/// The settings without the name, as command params (what `draw.brush` takes).
pub fn params(&self) -> Value {
let mut v = serde_json::to_value(self).unwrap_or_default();
if let Some(o) = v.as_object_mut() {
o.remove("name");
}
v
}
/// This preset with any settings `p` gives instead (the params of `draw.brush` and
/// `brush.preset_save`). Refuses values out of range.
pub fn with_params(&self, p: &Value) -> Result<BrushPreset> {
let mut b = self.clone();
let r = crate::cmds_brush::ranged;
b.size = r(p, "size", crate::cmds_brush::SIZE_RANGE, b.size)?;
b.shape = match opt_str(p, "shape")? {
None => b.shape,
Some("round") => Shape::Round,
Some("square") => Shape::Square,
Some(other) => return Err(EngineError::Param(format!("unknown tip shape '{other}' (round or square)"))),
};
if let Some(a) = opt_f32(p, "angle")? {
if !a.is_finite() || a.abs() > 1e6 {
return Err(EngineError::Param("param 'angle' must be a finite number of degrees".into()));
}
b.angle = a;
}
b.roundness = r(p, "roundness", 5.0..=100.0, b.roundness)?;
b.smoothing = r(p, "smoothing", 0.0..=100.0, b.smoothing)?;
if let Some(c) = curve_param(p, "curve")? {
b.curve = c;
}
b.pressure_size = opt_bool(p, "pressure_size")?.unwrap_or(b.pressure_size);
b.pressure_opacity = opt_bool(p, "pressure_opacity")?.unwrap_or(b.pressure_opacity);
b.taper_start = r(p, "taper_start", 0.0..=50.0, b.taper_start)?;
b.taper_end = r(p, "taper_end", 0.0..=50.0, b.taper_end)?;
b.spacing = r(p, "spacing", 0.0..=1000.0, b.spacing)?;
if b.spacing > 0.0 && b.spacing < 5.0 {
return Err(EngineError::Param("param 'spacing' must be 0 (a continuous stroke) or from 5 to 1000 %".into()));
}
b.jitter = r(p, "jitter", 0.0..=50.0, b.jitter)?;
b.texture = r(p, "texture", 0.0..=100.0, b.texture)?;
b.scatter = r(p, "scatter", 0.0..=200.0, b.scatter)?;
b.tilt_angle = opt_bool(p, "tilt_angle")?.unwrap_or(b.tilt_angle);
b.tilt_width = opt_bool(p, "tilt_width")?.unwrap_or(b.tilt_width);
Ok(b)
}
}
/// The `curve` param: a preset name (`linear`, `soft`, `firm`) or `[[pressure, output], ..]`
/// (both 0..1).
pub fn curve_param(p: &Value, key: &str) -> Result<Option<PressureCurve>> {
let bad = || EngineError::Param(format!("param '{key}' must be linear, soft, firm or a list of [pressure, output] pairs from 0 to 1"));
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(k)) => PressureCurve::preset(k).map(Some).ok_or_else(bad),
Some(Value::Array(list)) => {
if list.is_empty() || list.len() > 64 {
return Err(bad());
}
let pts = 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() && (-1e-3..=1.001).contains(f)).ok_or_else(bad);
Ok([n(0)?, n(1)?])
})
.collect::<Result<Vec<[f32; 2]>>>()?;
Ok(Some(PressureCurve::new(&pts)))
}
Some(_) => Err(bad()),
}
}
/// A name as kept: trimmed, one line, at most [`MAX_NAME`] characters; `None` when empty.
pub fn clean_name(s: &str) -> Option<String> {
let one: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
let t: String = one.trim().chars().take(MAX_NAME).collect();
let t = t.trim().to_string();
(!t.is_empty()).then_some(t)
}
/// Whether two names are the same preset (case doesn't matter).
fn same_name(a: &str, b: &str) -> bool {
a.trim().to_lowercase() == b.trim().to_lowercase()
}
/// Whether `name` is a built-in preset's (by key or by name).
pub fn is_builtin_name(name: &str) -> bool {
BUILTIN.iter().any(|(k, n)| same_name(k, name) || same_name(n, name))
}
/// The user's own presets, in the order they were saved.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct BrushLibrary {
user: Vec<BrushPreset>,
}
/// A brush set file.
#[derive(Serialize, Deserialize)]
struct BrushFile {
format: String,
version: u32,
brushes: Vec<Value>,
}
impl BrushLibrary {
pub fn user(&self) -> &[BrushPreset] {
&self.user
}
pub fn is_empty(&self) -> bool {
self.user.is_empty()
}
/// A library from untrusted entries (preferences, a file): bad entries and names skipped,
/// values clamped, names made unique, at most [`MAX_USER_PRESETS`].
pub fn from_values(values: impl IntoIterator<Item = Value>) -> BrushLibrary {
let mut lib = BrushLibrary::default();
for v in values.into_iter().take(MAX_USER_PRESETS * 4) {
if let Ok(p) = serde_json::from_value::<BrushPreset>(v) {
let _ = lib.add_unique(p);
}
}
lib
}
/// The same library with every entry sanitized (after deserializing preferences).
pub fn sanitized(self) -> BrushLibrary {
BrushLibrary::from_values(self.user.into_iter().filter_map(|p| serde_json::to_value(p).ok()))
}
/// A preset by built-in key, built-in name or the user's name (case doesn't matter; the
/// user's own win only where no built-in has the name, which saving refuses anyway).
pub fn find(&self, name: &str) -> Option<BrushPreset> {
if let Some((k, _)) = BUILTIN.iter().find(|(k, n)| *k == name || same_name(n, name)) {
return builtin(k);
}
self.user.iter().find(|p| same_name(&p.name, name)).cloned()
}
pub fn position(&self, name: &str) -> Option<usize> {
self.user.iter().position(|p| same_name(&p.name, name))
}
/// Saves `p` under its name, replacing the user's preset of that name. Returns whether it
/// replaced one.
pub fn save(&mut self, p: BrushPreset) -> Result<bool> {
let p = p.sanitized();
let name = clean_name(&p.name).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?;
if is_builtin_name(&name) {
return Err(EngineError::Param(format!("'{name}' is a built-in brush; save yours under another name")));
}
let p = BrushPreset { name, ..p };
if let Some(i) = self.position(&p.name)
&& let Some(slot) = self.user.get_mut(i)
{
*slot = p;
return Ok(true);
}
if self.user.len() >= MAX_USER_PRESETS {
return Err(EngineError::State(format!("you have {MAX_USER_PRESETS} brushes already; delete some first")));
}
self.user.push(p);
Ok(false)
}
/// Adds `p`, renaming it ("Ink 2", "Ink 3", ..) if the name is taken. Returns its name.
pub fn add_unique(&mut self, p: BrushPreset) -> Result<String> {
let p = p.sanitized();
let base = clean_name(&p.name).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?;
let taken = |lib: &BrushLibrary, n: &str| is_builtin_name(n) || lib.position(n).is_some();
let mut name = base.clone();
let mut k = 2;
while taken(self, &name) {
if k > MAX_USER_PRESETS + 10 {
return Err(EngineError::State("too many brushes of that name".into()));
}
let suffix = format!(" {k}");
name = format!("{}{suffix}", base.chars().take(MAX_NAME.saturating_sub(suffix.chars().count())).collect::<String>().trim_end());
k += 1;
}
if self.user.len() >= MAX_USER_PRESETS {
return Err(EngineError::State(format!("you have {MAX_USER_PRESETS} brushes already; delete some first")));
}
self.user.push(BrushPreset { name: name.clone(), ..p });
Ok(name)
}
pub fn rename(&mut self, name: &str, to: &str) -> Result<String> {
let i = self.position(name).ok_or_else(|| EngineError::Param(format!("you have no brush named '{name}'")))?;
let to = clean_name(to).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?;
if is_builtin_name(&to) {
return Err(EngineError::Param(format!("'{to}' is a built-in brush's name")));
}
if self.position(&to).is_some_and(|j| j != i) {
return Err(EngineError::Param(format!("you already have a brush named '{to}'")));
}
if let Some(p) = self.user.get_mut(i) {
p.name = to.clone();
}
Ok(to)
}
pub fn delete(&mut self, name: &str) -> Result<BrushPreset> {
let i = self.position(name).ok_or_else(|| EngineError::Param(format!("you have no brush named '{name}'")))?;
Ok(self.user.remove(i))
}
/// A brush set file holding `presets`.
pub fn file_json(presets: &[BrushPreset]) -> String {
let f = BrushFile { format: FILE_FORMAT.into(), version: FILE_VERSION, brushes: presets.iter().filter_map(|p| serde_json::to_value(p).ok()).collect() };
serde_json::to_string_pretty(&f).unwrap_or_default()
}
/// The presets in a brush set file (bad entries skipped; values clamped).
pub fn parse_file(text: &str) -> Result<Vec<BrushPreset>> {
let f: BrushFile = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("not a brush set file: {e}")))?;
if f.format != FILE_FORMAT {
return Err(EngineError::Param(format!("not a brush set file (its format is '{}')", f.format.chars().take(40).collect::<String>())));
}
if f.version > FILE_VERSION {
return Err(EngineError::Param(format!("this brush set is version {}, newer than this AniCraft reads ({FILE_VERSION})", f.version)));
}
Ok(f.brushes.into_iter().take(MAX_USER_PRESETS * 4).filter_map(|v| serde_json::from_value::<BrushPreset>(v).ok()).map(BrushPreset::sanitized).filter(|p| !p.name.is_empty()).collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtins_are_named_and_in_range() {
for (key, name) in BUILTIN {
let p = builtin(key).unwrap();
assert_eq!(p.name, name);
assert_eq!(p.clone().sanitized(), p, "{key} is already in range");
assert!(!builtin_hint(key).is_empty());
}
assert_eq!(BrushPreset::default().shaping(), Shaping::default(), "the plain brush shapes nothing");
}
#[test]
fn saving_renaming_and_deleting() {
let mut lib = BrushLibrary::default();
assert!(!lib.save(BrushPreset { name: " My ink \n".into(), size: 1e9, ..BrushPreset::default() }).unwrap());
assert_eq!(lib.user()[0].name, "My ink");
assert_eq!(lib.user()[0].size, 2000.0, "clamped");
assert!(lib.save(BrushPreset { name: "my INK".into(), size: 4.0, ..BrushPreset::default() }).unwrap(), "same name replaces");
assert_eq!(lib.user().len(), 1);
assert!(lib.save(BrushPreset { name: "Chalk".into(), ..BrushPreset::default() }).is_err(), "a built-in's name");
assert!(lib.save(BrushPreset { name: " ".into(), ..BrushPreset::default() }).is_err());
assert_eq!(lib.add_unique(BrushPreset { name: "My ink".into(), ..BrushPreset::default() }).unwrap(), "My ink 2");
assert_eq!(lib.add_unique(BrushPreset { name: "chalk".into(), ..BrushPreset::default() }).unwrap(), "chalk 2");
assert_eq!(lib.rename("my ink 2", "Wet").unwrap(), "Wet");
assert!(lib.rename("Wet", "My Ink").is_err() && lib.rename("Wet", "Marker").is_err() && lib.rename("nope", "x").is_err());
assert_eq!(lib.find("wet").map(|p| p.name), Some("Wet".into()));
assert_eq!(lib.find("ink_pen").map(|p| p.name), Some("Ink Pen".into()));
assert_eq!(lib.find("ink pen").map(|p| p.size), Some(6.0));
assert_eq!(lib.delete("WET").unwrap().name, "Wet");
assert!(lib.delete("Wet").is_err());
}
#[test]
fn brush_set_files_round_trip_and_reject_junk() {
let mine = vec![BrushPreset { name: "A".into(), curve: PressureCurve::SOFT, jitter: 12.0, ..BrushPreset::default() }, builtin("dotted").unwrap()];
let text = BrushLibrary::file_json(&mine);
assert_eq!(BrushLibrary::parse_file(&text).unwrap(), mine);
assert!(BrushLibrary::parse_file("{}").is_err());
assert!(BrushLibrary::parse_file(r#"{"format": "other", "version": 1, "brushes": []}"#).is_err());
assert!(BrushLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 99, "brushes": []}"#).is_err());
// Bad entries are skipped, out-of-range values clamped, older files without the newer
// fields read with defaults.
let got = BrushLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 1, "brushes": [7, {"name": ""}, {"name": "Old", "size": -4, "spacing": 2, "curve": [[0.5, 9]]}]}"#).unwrap();
assert_eq!(got.len(), 1);
assert_eq!((got[0].size, got[0].spacing, got[0].smoothing), (0.1, 5.0, 50.0));
assert_eq!(got[0].curve.points(), &[[0.0, 1.0], [0.5, 1.0], [1.0, 1.0]]);
// Preferences: the library as a list.
let lib = BrushLibrary::from_values(serde_json::from_str::<Vec<Value>>(&serde_json::to_string(&mine).unwrap()).unwrap());
assert_eq!(lib.user().len(), 2);
assert_eq!(lib.user()[1].name, "Dotted 2", "a built-in's name is renamed");
}
#[test]
fn params_override_a_preset() {
let p = builtin("calligraphy").unwrap();
let q = p.with_params(&serde_json::json!({"size": 30, "curve": "firm", "taper_end": 20})).unwrap();
assert_eq!((q.size, q.curve, q.taper_end, q.roundness), (30.0, PressureCurve::FIRM, 20.0, 15.0));
let q = p.with_params(&serde_json::json!({"curve": [[0, 0.2], [1, 0.8]]})).unwrap();
assert_eq!(q.curve.map(0.0), 0.2);
for bad in [serde_json::json!({"curve": "wobbly"}), serde_json::json!({"curve": [[0, 2]]}), serde_json::json!({"curve": []}), serde_json::json!({"spacing": 2}), serde_json::json!({"jitter": 60}), serde_json::json!({"shape": "star"})] {
assert!(p.with_params(&bad).is_err(), "{bad}");
}
// The params name every setting and read back as the same preset.
let back = BrushPreset::default().with_params(&p.params()).unwrap();
assert_eq!(BrushPreset { name: p.name.clone(), ..back }, p);
}
}
+306
View File
@@ -0,0 +1,306 @@
//! The brush library, pressure curves and the Paint Brush (ADR 0068).
use crate::Session;
use crate::brush_library::BUILTIN;
use anicraft_doc::{ElementKind, Shape};
use anicraft_geom::Affine;
use serde_json::{Value, json};
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
}
fn blank() -> Session {
let mut s = Session::new(anicraft_doc::Document::default());
run(&mut s, "draw.object_drawing", json!({"on": true}));
s
}
fn shapes(s: &Session) -> Vec<Shape> {
s.visible_elements()
.iter()
.filter_map(|e| match &e.kind {
ElementKind::Shape(sh) => Some(sh.clone()),
_ => None,
})
.collect()
}
fn area(sh: &Shape) -> f32 {
sh.path
.flatten(&Affine::IDENTITY, 0.01)
.iter()
.map(|pl| {
let n = pl.points.len();
((0..n).map(|i| pl.points[i].cross(pl.points[(i + 1) % n])).sum::<f32>() * 0.5).abs()
})
.sum()
}
/// A 400-unit wave with the pressure swelling from 0.3 to 1 and back.
fn wave() -> Vec<[f32; 3]> {
(0..=80)
.map(|i| {
let t = i as f32 / 80.0;
[100.0 + 400.0 * t, 200.0 + 30.0 * (t * std::f32::consts::TAU).sin(), 0.3 + 0.7 * (t * std::f32::consts::PI).sin()]
})
.collect()
}
/// The wave's length (polyline).
fn wave_length() -> f32 {
wave().windows(2).map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt()).sum()
}
fn painted(preset: &str, extra: Value) -> (Shape, Value) {
let mut s = blank();
let mut p = json!({"points": wave(), "preset": preset, "color": "#203040"});
if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) {
o.extend(e.clone());
}
let r = run(&mut s, "draw.brush", p);
let all = shapes(&s);
assert_eq!(all.len(), 1, "{preset}: one shape");
(all[0].clone(), r)
}
#[test]
fn every_preset_paints_within_its_area_bounds() {
let len = wave_length();
// (key, least, most) area as a part of length × size: what each preset's settings allow.
let bounds = [
("pencil", 0.4, 0.65), // a firm curve thins the light parts; short tapers
("ink_pen", 0.7, 0.9), // a soft curve keeps it wide; tapered ends
("calligraphy", 0.45, 0.7), // a 15 % flat nib: thick and thin by direction
("round_taper", 0.55, 0.75), // swells from a point and back
("marker", 0.75, 0.95), // a square chisel at 45 %, no pressure
("chalk", 0.35, 0.55), // its edge worn in
// Dots 2.2 sizes apart, each a quarter π of size²: π / 8.8 = 0.357 of length × size.
("dotted", 0.33, 0.38),
("charcoal", 0.38, 0.52), // a 60 % oval with the paper grain through it
("spatter", 0.4, 0.65), // dabs 0.6 sizes apart, 60–100 % of the size, thrown aside
];
assert_eq!(bounds.len(), BUILTIN.len(), "every built-in has bounds");
for (key, lo, hi) in bounds {
let b = crate::brush_library::builtin(key).unwrap();
let (sh, _) = painted(key, json!({}));
let a = area(&sh) / (len * b.size);
assert!((lo..=hi).contains(&a), "{key}: {a:.3} of length × size, want {lo}..{hi}");
assert!(sh.stroke.is_none() && sh.fill.is_some(), "{key} paints a fill");
}
// Dots are separate loops; chalk's edge is ragged (many more anchors than a plain stroke).
let (dots, _) = painted("dotted", json!({}));
let loops = dots.path.cmds.iter().filter(|c| matches!(c, anicraft_geom::PathCmd::MoveTo(_))).count();
let want = (wave_length() / (8.0 * 2.2)).floor() as usize + 1;
assert!(loops.abs_diff(want) <= 2, "{loops} dots, about {want}");
let (chalk, _) = painted("chalk", json!({}));
let (plain, _) = painted("chalk", json!({"jitter": 0}));
assert!(chalk.path.anchors().len() > 2 * plain.path.anchors().len());
}
#[test]
fn the_same_points_and_settings_give_identical_outlines() {
for (key, _) in BUILTIN {
for as_stroke in [false, true] {
let (a, _) = painted(key, json!({"as_stroke": as_stroke}));
let (b, _) = painted(key, json!({"as_stroke": as_stroke}));
assert_eq!(a.path, b.path, "{key} as_stroke {as_stroke}");
assert_eq!(a.stroke, b.stroke);
}
}
}
#[test]
fn pressure_curves_map_before_the_size() {
// A steady half pressure: soft paints wider than linear, firm narrower.
let pts: Vec<[f32; 3]> = (0..=40).map(|i| [100.0 + i as f32 * 10.0, 100.0, 0.5]).collect();
let area_with = |curve: Value| {
let mut s = blank();
run(&mut s, "draw.brush", json!({"points": pts, "size": 20, "curve": curve}));
area(&shapes(&s)[0])
};
let (lin, soft, firm) = (area_with(json!("linear")), area_with(json!("soft")), area_with(json!("firm")));
// Linear: factor 0.1 + 0.9 × 0.5 = 0.55 of 20 across 400.
assert!((lin - 400.0 * 11.0).abs() / (400.0 * 11.0) < 0.06, "{lin}");
assert!(soft > lin * 1.15 && firm < lin * 0.85, "{soft} {lin} {firm}");
// A curve of points: flat at 1 paints full size at any pressure.
let full = area_with(json!([[0, 1], [1, 1]]));
assert!((full - 400.0 * 20.0).abs() / (400.0 * 20.0) < 0.06, "{full}");
// Pressure off: full size too.
let mut s = blank();
run(&mut s, "draw.brush", json!({"points": pts, "size": 20, "pressure_size": false}));
assert!((area(&shapes(&s)[0]) - full).abs() < full * 0.01);
}
#[test]
fn pressure_can_set_the_opacity() {
let pts: Vec<[f32; 3]> = (0..=10).map(|i| [i as f32 * 10.0, 50.0, 0.4]).collect();
let mut s = blank();
run(&mut s, "draw.brush", json!({"points": pts, "pressure_opacity": true, "color": "#ff0000"}));
let Some(anicraft_doc::Paint::Solid(c)) = shapes(&s)[0].fill else { panic!("solid") };
assert!((c.a - 0.4).abs() < 1e-3, "{}", c.a);
// A mouse (no pressure) paints opaque.
run(&mut s, "draw.brush", json!({"points": [[0, 100], [100, 100]], "pressure_opacity": true}));
let Some(anicraft_doc::Paint::Solid(c)) = shapes(&s)[1].fill else { panic!("solid") };
assert_eq!(c.a, 1.0);
}
#[test]
fn the_paint_brush_draws_a_width_profiled_stroke() {
let mut s = blank();
s.style.stroke = anicraft_doc::Rgba::hex(0x123456);
let r = run(&mut s, "draw.brush", json!({"points": wave(), "size": 16, "as_stroke": true, "taper_end": 30}));
assert_eq!(r["kind"], "paint_brush");
let sh = &shapes(&s)[0];
assert!(sh.fill.is_none(), "a line, not a fill");
let st = sh.stroke.as_ref().unwrap();
assert_eq!((st.width, st.color), (16.0, anicraft_doc::Rgba::hex(0x123456)), "the brush's size in the stroke colour");
let prof = st.profile.as_ref().expect("pressure and a taper make a profile");
let n = prof.points().len();
assert!((3..=anicraft_doc::MAX_WIDTH_POINTS).contains(&n), "{n} width points");
assert_eq!(r["width_points"], n);
// Thin at the light start, full in the middle, tapered to a point at the end.
let (l0, _) = prof.at(0.0);
let (lm, rm) = prof.at(0.5);
let (l1, _) = prof.at(1.0);
assert!(l0 < 0.5 && lm > 0.9 && (lm - rm).abs() < 1e-6 && l1 < 0.1, "{l0} {lm} {l1}");
// The Width tool edits it afterwards.
let id = r["element"].as_u64().unwrap();
run(&mut s, "stroke.set_width_point", json!({"id": id, "t": 0.5, "left": 3, "right": 3}));
let sh = &shapes(&s)[0];
assert!(sh.stroke.as_ref().and_then(|st| st.profile.as_ref()).is_some_and(|p| p.at(0.5).0 > 2.9));
// A mouse stroke with no taper is a plain line of one width (it merges off Object Drawing).
let mut s = blank();
run(&mut s, "draw.object_drawing", json!({"on": false}));
let r = run(&mut s, "draw.brush", json!({"points": [[0, 0], [50, 10], [100, 0]], "as_stroke": true}));
assert_eq!(r["merged"], true);
assert!(shapes(&s).iter().all(|sh| sh.stroke.as_ref().is_none_or(|st| st.profile.is_none())));
// One point is no line.
assert!(blank().execute("draw.brush", &json!({"points": [[5, 5]], "as_stroke": true})).is_err());
}
#[test]
fn user_brushes_are_saved_listed_renamed_and_deleted() {
let mut s = blank();
let v = run(&mut s, "brush.preset_list", json!({}));
assert_eq!(v["presets"].as_array().map(Vec::len), Some(BUILTIN.len()));
assert_eq!(v["presets"][0]["key"], "pencil");
let v = run(&mut s, "brush.preset_save", json!({"name": "Wet Ink", "from": "ink_pen", "size": 9, "curve": [[0, 0], [0.5, 0.8], [1, 1]]}));
assert_eq!((v["name"].as_str(), v["replaced"].as_bool()), (Some("Wet Ink"), Some(false)));
let list = run(&mut s, "brush.preset_list", json!({}));
let mine = &list["presets"][BUILTIN.len()];
assert_eq!((mine["name"].as_str(), mine["builtin"].as_bool(), mine["size"].as_f64(), mine["taper_end"].as_f64()), (Some("Wet Ink"), Some(false), Some(9.0), Some(18.0)), "from the ink pen, size changed");
// Painting with it by name equals painting with its settings.
run(&mut s, "draw.brush", json!({"points": wave(), "preset": "wet ink"}));
let mut t = blank();
run(&mut t, "draw.brush", json!({"points": wave(), "preset": "ink_pen", "size": 9, "curve": [[0, 0], [0.5, 0.8], [1, 1]]}));
assert_eq!(shapes(&s)[0].path, shapes(&t)[0].path);
assert!(s.execute("draw.brush", &json!({"points": wave(), "preset": "nope"})).is_err());
// Brushes aren't the document's: saving and renaming leave it as it is.
let doc = s.doc.clone();
run(&mut s, "brush.preset_rename", json!({"name": "Wet Ink", "to": "Dry Ink"}));
run(&mut s, "brush.preset_save", json!({"name": "Spare"}));
run(&mut s, "brush.preset_delete", json!({"name": "Spare", "confirm": true}));
assert!(s.doc == doc);
assert!(s.execute("brush.preset_save", &json!({"name": "Marker"})).is_err(), "built-in names are taken");
// Deleting can't be undone, so it asks first.
assert!(s.confirmation("brush.preset_delete", &json!({"name": "dry ink"})).is_some_and(|c| c.irreversible));
assert!(s.confirmation("brush.preset_delete", &json!({"name": "nope"})).is_none());
assert!(s.execute("brush.preset_delete", &json!({"name": "Dry Ink"})).is_err(), "needs confirm");
run(&mut s, "brush.preset_delete", json!({"name": "Dry Ink", "confirm": true}));
assert!(s.brushes.is_empty());
// They survive New and Open.
run(&mut s, "brush.preset_save", json!({"name": "Keep"}));
s.replace_document(anicraft_doc::Document::default(), None);
assert_eq!(s.brushes.user().len(), 1);
}
#[test]
fn brush_sets_export_and_import_as_json() {
crate::vfs::use_memory();
let mut s = blank();
assert!(s.execute("brush.preset_export", &json!({"path": "none.json"})).is_err(), "nothing of yours yet");
run(&mut s, "brush.preset_save", json!({"name": "Grit", "from": "chalk", "jitter": 30}));
run(&mut s, "brush.preset_save", json!({"name": "Dots", "from": "dotted", "spacing": 150}));
let v = run(&mut s, "brush.preset_export", json!({"path": "set.json"}));
assert_eq!(v["brushes"], 2);
let text = crate::vfs::read_to_string(std::path::Path::new("set.json")).unwrap();
assert!(text.contains("\"format\": \"anicraft-brushes\"") && text.contains("\"Grit\""));
// Exporting over the file asks first.
assert!(s.confirmation("brush.preset_export", &json!({"path": "set.json"})).is_some_and(|c| c.irreversible));
// Another computer: the set comes in whole; names already there get a number.
let mut t = blank();
run(&mut t, "brush.preset_save", json!({"name": "Grit"}));
let v = run(&mut t, "brush.preset_import", json!({"path": "set.json"}));
assert_eq!(v["imported"], json!(["Grit 2", "Dots"]));
assert_eq!(t.brushes.find("Grit 2").map(|b| b.jitter), Some(30.0));
// Built-ins can be exported by name too.
let v = run(&mut s, "brush.preset_export", json!({"path": "two.json", "names": ["chalk", "Dots"], "confirm": true}));
assert_eq!(v["brushes"], 2);
// Junk is refused.
crate::vfs::put(std::path::Path::new("junk.json"), b"{\"format\": 3}".to_vec()).unwrap();
for bad in [json!({"path": "junk.json"}), json!({"path": "missing.json"}), json!({})] {
assert!(t.execute("brush.preset_import", &bad).is_err(), "{bad}");
}
}
#[test]
fn plug_ins_may_list_brushes_but_not_change_them() {
use crate::cmds_plugin::plugin_may_call;
assert!(plugin_may_call("brush.preset_list").is_ok());
for id in ["brush.preset_save", "brush.preset_rename", "brush.preset_delete", "brush.preset_export", "brush.preset_import"] {
assert!(plugin_may_call(id).is_err(), "{id}");
}
}
#[test]
fn previews_are_drawn_by_the_renderer() {
for (key, _) in BUILTIN {
let b = crate::brush_library::builtin(key).unwrap();
for as_stroke in [false, true] {
let px = crate::cmds_brush::preview(&b, as_stroke, 160, 48, 2.0, anicraft_doc::Rgba::hex(0x000000)).unwrap();
let rgba = px.to_premul_rgba8();
let inked = rgba.chunks(4).filter(|p| p[3] > 128).count();
assert!(inked > 60, "{key} as_stroke {as_stroke}: {inked} pixels");
assert!(rgba.chunks(4).filter(|p| p[3] == 0).count() > inked, "{key}: mostly transparent");
}
}
assert!(crate::cmds_brush::preview(&crate::brush_library::BrushPreset::default(), false, 2, 2, 1.0, anicraft_doc::Rgba::hex(0)).is_err());
}
/// Measured numbers for ADR 0068: `cargo test --release -p anicraft-engine preset_timings -- --ignored --nocapture`.
#[test]
#[ignore]
fn preset_timings() {
for (key, _) in BUILTIN {
for as_stroke in [false, true] {
let mut ms: Vec<f64> = (0..15)
.map(|_| {
let mut s = blank();
let t = std::time::Instant::now();
run(&mut s, "draw.brush", json!({"points": wave(), "preset": key, "as_stroke": as_stroke}));
t.elapsed().as_secs_f64() * 1000.0
})
.collect();
ms.sort_by(f64::total_cmp);
let (sh, _) = painted(key, json!({"as_stroke": as_stroke}));
eprintln!("{key:12} stroke {as_stroke:5}: median {:6.2} ms, {} anchors", ms[7], sh.path.anchors().len());
}
}
let b = crate::brush_library::builtin("chalk").unwrap();
let t = std::time::Instant::now();
for _ in 0..10 {
crate::cmds_brush::preview(&b, false, 300, 80, 2.0, anicraft_doc::Rgba::hex(0)).unwrap();
}
eprintln!("chalk preview 300x80: {:.2} ms each", t.elapsed().as_secs_f64() * 100.0);
}
#[test]
fn simplified_profiles_stay_close_and_small() {
let pts: Vec<(f32, f32)> = (0..256).map(|i| i as f32 / 255.0).map(|t| (t, 0.5 + 0.4 * (t * 9.0).sin())).collect();
let kept = crate::cmds_brush::simplify_profile(&pts, 0.015, 64);
assert!(kept.len() <= 64 && kept.len() > 8, "{}", kept.len());
assert_eq!((kept.first(), kept.last()), (pts.first(), pts.last()));
let noisy: Vec<(f32, f32)> = (0..256).map(|i| (i as f32 / 255.0, if i % 2 == 0 { 0.1 } else { 1.0 })).collect();
assert!(crate::cmds_brush::simplify_profile(&noisy, 0.015, 64).len() <= 64);
}
+82 -1
View File
@@ -196,7 +196,7 @@ fn bad_params_are_errors() {
json!({"points": [[0, 0]], "size": 0}),
json!({"points": [[0, 0]], "size": 1e9}),
json!({"points": [[0, 0]], "shape": "star"}),
json!({"points": [[0, 0]], "mode": "inside"}),
json!({"points": [[0, 0]], "mode": "outside"}),
json!({"points": [[0, 0]], "roundness": 1}),
json!({"points": [[0, 0]], "smoothing": 101}),
json!({"points": [[0, 0], [1e7, 0]]}),
@@ -226,3 +226,84 @@ fn a_calligraphic_stroke_merges_whole() {
.collect();
assert!(areas[0] > 7000.0 && (areas[0] - areas[1]).abs() < 1.0, "{areas:?}");
}
// ----- ADR 0093: tilt and texture --------------------------------------------------------------
/// A horizontal drag 200 long at y 100 with the pen held at `altitude` toward `azimuth`.
fn tilted(altitude: f32, azimuth: f32) -> Vec<[f32; 5]> {
(0..=30).map(|i| [100.0 + 200.0 * i as f32 / 30.0, 100.0, 1.0, altitude, azimuth]).collect()
}
#[test]
fn tilt_turns_and_widens_the_tip_and_a_mouse_is_unaffected() {
// A flat nib along the drag paints thin; the pen leaning across it (90°) stands it up.
let flat = json!({"size": 20, "roundness": 20, "angle": 0, "smoothing": 0});
let paint = |extra: Value, pts: Value| {
let mut s = blank(true);
let mut p = flat.clone();
p["points"] = pts;
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
run(&mut s, "draw.brush", p);
shapes(&s).remove(0).0
};
let across = paint(json!({"tilt_angle": true}), json!(tilted(30.0, 90.0)));
assert!((bounds(&across).height() - 20.0).abs() < 0.8, "{:?}", bounds(&across));
// Off, or without tilt in the points (a mouse), the nib stays as set.
let off = paint(json!({}), json!(tilted(30.0, 90.0)));
assert!((bounds(&off).height() - 4.0).abs() < 0.8, "{:?}", bounds(&off));
let mouse = paint(json!({"tilt_angle": true, "tilt_width": true}), json!(stroke(100.0, 100.0, 300.0, 100.0)));
assert_eq!(mouse, paint(json!({}), json!(stroke(100.0, 100.0, 300.0, 100.0))), "no tilt, no change");
// Width: a round 10 brush laid flat paints 20 wide (1 + lean), half way down 15.
let round = |alt: f32| {
let mut s = blank(true);
run(&mut s, "draw.brush", json!({"points": tilted(alt, 0.0), "size": 10, "smoothing": 0, "tilt_width": true}));
bounds(&shapes(&s).remove(0).0).height()
};
assert!((round(0.0) - 20.0).abs() < 0.5 && (round(45.0) - 15.0).abs() < 0.5 && (round(90.0) - 10.0).abs() < 0.5, "{} {} {}", round(0.0), round(45.0), round(90.0));
// The Paint Brush: tilt widens its stroke's profile.
let mut s = blank(true);
run(&mut s, "draw.brush", json!({"points": tilted(0.0, 0.0), "size": 6, "as_stroke": true, "tilt_width": true, "pressure_size": false}));
let (sh, _) = shapes(&s).remove(0);
let prof = sh.stroke.as_ref().and_then(|st| st.profile.clone()).expect("a profile");
assert!((prof.at(0.5).0 - 2.0).abs() < 0.02, "{:?}", prof.at(0.5));
// Bad tilts are errors; tilt past the ends is clamped.
assert!(s.execute("draw.brush", &json!({"points": [[0, 0, 1, "up", 0]]})).is_err());
assert!(s.execute("draw.brush", &json!({"points": [[0, 0, 1, 0]]})).is_err(), "altitude without azimuth");
run(&mut s, "draw.brush", json!({"points": [[0, 0, 1, -40, 1000]], "tilt_width": true}));
}
#[test]
fn textured_and_scattered_brushes_paint_vector_fills_that_merge() {
let mut s = blank(false);
let r = run(&mut s, "draw.brush", json!({"points": stroke(100.0, 200.0, 400.0, 220.0), "preset": "charcoal"}));
assert_eq!(r["merged"], true, "raw paint, merged like any other");
let raw: Vec<Shape> = shapes(&s).into_iter().map(|(sh, _)| sh).collect();
assert!(raw.iter().all(|sh| sh.merge && fill_of(sh).is_some()));
let holes: usize = raw.iter().map(|sh| sh.path.cmds.iter().filter(|c| matches!(c, anicraft_geom::PathCmd::MoveTo(_))).count()).sum();
assert!(holes > 10, "the paper grain shows through: {holes} loops");
// The same stroke again gives the same paint.
let mut t = blank(false);
run(&mut t, "draw.brush", json!({"points": stroke(100.0, 200.0, 400.0, 220.0), "preset": "charcoal"}));
assert_eq!(shapes(&s), shapes(&t));
// Spatter throws drops either side; the file keeps them.
run(&mut s, "draw.brush", json!({"points": stroke(100.0, 400.0, 400.0, 400.0), "preset": "spatter", "color": BLUE}));
let json = crate::format::to_json(&s.doc).unwrap();
assert_eq!(crate::format::from_json(&json).unwrap(), s.doc);
for p in [json!({"points": [[0, 0]], "texture": 101}), json!({"points": [[0, 0]], "scatter": -1}), json!({"points": [[0, 0]], "tilt_angle": "yes"})] {
assert!(s.execute("draw.brush", &p).is_err(), "{p}");
}
let _ = RED;
}
#[test]
fn a_pressured_paint_brush_line_is_raw_now() {
// ADR 0068 drew these as objects because profiles didn't merge; ADR 0093 merges them.
let mut s = blank(false);
let pts: Vec<[f32; 3]> = (0..=20).map(|i| [100.0 + 10.0 * i as f32, 100.0, 0.2 + 0.04 * i as f32]).collect();
run(&mut s, "draw.brush", json!({"points": pts, "as_stroke": true, "size": 8}));
let all = shapes(&s);
assert_eq!(all.len(), 1);
assert!(all[0].0.merge && all[0].0.stroke.as_ref().is_some_and(|st| st.profile.is_some()));
}
+32 -5
View File
@@ -17,11 +17,11 @@ 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("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y}]} plays the movie with its actions and frame scripts from the first frame; returns the output and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn),
c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y} or {tick, type: key_down|key_up|key, key: code|letter|LEFT…}], seed?: Math.random()'s seed (default 0)} plays the movie with its actions and frame scripts from the first frame; returns the output, the sounds it started ({tick, sound, name, sync, gain}; buttons' as the pointer changes their state) and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn),
c("actions.set", "Set Actions", "", None, "{actions: [{op: stop|play|goto_and_play|goto_and_stop|next_frame|prev_frame|next_scene|prev_scene|trace|set_property, target?, frame?, scene?, message?, property?, value?}] | plugin: id, entry?, symbol?: id (a movie clip's timeline), layer?, frame?} sets what the keyframe at the frame runs; or {element, event: click|press|release|over|out, actions} sets an instance's event handler. An empty list clears it", true, set),
c("actions.clear", "Clear Actions", "", None, "{symbol?, layer?, frame?} clears the keyframe's actions; {element, event?} clears an instance's handlers (one event, or all)", true, clear),
c("actions.list", "List Actions", "", None, "{} every keyframe with actions or a frame script and every instance with event handlers, in every scene and symbol", false, list),
c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance for actions", true, set_name),
c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance, or a dynamic or input text field, for actions and scripts", true, set_name),
]
}
@@ -37,7 +37,7 @@ pub(crate) enum Scope {
/// A timeline commands address: a scene's (the one being edited) or a library symbol's.
fn timeline_mut(s: &mut Session, symbol: Option<SymbolId>, scope: Scope) -> Result<&mut Timeline> {
match symbol {
None => Ok(s.doc.timeline_mut(s.scene)),
None => crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing),
Some(id) => {
let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?;
if scope == Scope::Runs && sym.kind != SymbolKind::MovieClip {
@@ -232,7 +232,14 @@ fn set_name(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Param(format!("“{name}” can't be an instance name: use letters, digits, _ or $ (no spaces), not starting with a digit, at most {} characters", actions::MAX_NAME_CHARS)));
}
let e = instance_mut(s, p)?.clone();
interactive_kind(s, &e)?;
// Dynamic and input text fields take names too (ADR 0066); static text has none.
match &e.kind {
ElementKind::Text(t) if t.field.is_some() => {}
ElementKind::Text(_) => return Err(EngineError::State("static text has no instance name: make it dynamic or input text first (Properties › Text type)".into())),
_ => {
interactive_kind(s, &e)?;
}
}
let el = instance_mut(s, p)?;
el.name = name.clone();
Ok(json!({"element": el.id.0, "name": name}))
@@ -241,6 +248,8 @@ fn set_name(s: &mut Session, p: &Value) -> Result<Value> {
/// Most steps and events of a headless test.
const MAX_TEST_STEPS: u32 = 10_000;
const MAX_TEST_EVENTS: usize = 10_000;
/// Most started sounds `control.test_movie` lists (the rest are counted).
const MAX_TEST_SOUNDS: usize = 10_000;
fn test_movie(s: &mut Session, p: &Value) -> Result<Value> {
let fps = s.doc.stage.fps.max(1.0);
@@ -259,16 +268,34 @@ fn test_movie(s: &mut Session, p: &Value) -> Result<Value> {
}
Some(_) => return Err(EngineError::Param("param 'events' must be a list".into())),
}
let seed = opt_u64(p, "seed")?.unwrap_or(anicraft_doc::player::DEFAULT_SEED);
let mut runner = ScriptRunner::new(&s.plugins);
let mut movie = Movie::start(&s.doc, &mut runner);
let mut movie = Movie::start_seeded(&s.doc, seed, &mut runner);
// The sounds the movie started (buttons' under the pointer too, ADR 0057), in order.
let mut sounds: Vec<Value> = Vec::new();
let mut more = 0usize;
let mut heard = |movie: &mut Movie, doc: &anicraft_doc::Document| {
for (tick, st) in movie.take_sounds() {
if sounds.len() >= MAX_TEST_SOUNDS {
more += 1;
continue;
}
let name = doc.sound(st.sound.sound).map(|x| x.name.clone());
sounds.push(json!({"tick": tick, "sound": st.sound.sound.0, "name": name, "sync": st.sound.sync.key(), "gain": st.gain}));
}
};
heard(&mut movie, &s.doc);
for tick in 1..=u64::from(frames) {
let events: Vec<_> = timed.iter().filter(|(t, _)| *t == tick).flat_map(|(_, e)| e.iter().copied()).collect();
movie.step(&s.doc, &events, &mut runner);
heard(&mut movie, &s.doc);
}
let nodes = anicraft_doc::player::tree(&s.doc, &movie.state);
Ok(json!({
"steps": frames,
"output": movie.output.iter().map(|(t, l)| json!({"tick": t, "line": l})).collect::<Vec<_>>(),
"sounds": sounds,
"more_sounds": more,
"state": state_view(&s.doc, &movie.state, &nodes, None),
"script_runs": runner.runs,
"script_fuel": runner.fuel_used,
+511 -48
View File
@@ -11,8 +11,10 @@
use crate::cmds_timeline::insert_keyframe_at;
use crate::params::*;
use crate::{CommandSpec, EngineError, KeyEdit, MAX_FRAME, Result, Session};
use anicraft_doc::armature::{self, Armature, Bone, BoneId, Limits, MAX_BONES, MAX_LIMIT, MAX_NAME};
use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Rgba, Tween, evaluate_layer_elements};
use anicraft_doc::armature::{self, Armature, Bone, BoneId, Limits, MAX_BONES, MAX_LIMIT, MAX_NAME, MAX_SLIDE, Spring};
use anicraft_doc::skin::{self, Binding, Influence, MAX_SKIN_POINTS, Skin};
use anicraft_doc::weights::{self, Brush, Dab, MAX_DABS, MAX_RADIUS};
use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Rgba, Shape, Tween, evaluate_layer_elements};
use anicraft_geom::{Affine, Vec2};
use serde_json::{Value, json};
use std::sync::Arc;
@@ -23,16 +25,29 @@ pub fn specs() -> Vec<CommandSpec> {
c(
"bone.add",
"Add Bone",
"{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint, stage px; default the end of the bone into `from`, else its registration point), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)",
"{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint on a root instance, stage px, default its registration point; from an instance that hangs from a bone the joint is always that bone's end, so chains stay joined), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)",
true,
add as crate::RunFn,
),
c(
"bone.add_in_shape",
"Add Bone in Shape",
"{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone); the shape's points are bound to the nearest bones",
true,
add_in_shape,
),
c("bone.bind", "Bind Points", "{bone, points?: [point index…] (default every point; see bone.info with points), mode?: \"only\" (the points follow just this bone; default) | \"add\" (they share it with the bones they follow) | \"remove\" | \"auto\" (back to automatic binding)} → {bone, changed, bound (how many points the bone moves)}. A shape armature's binding: which points of the shape follow which bone", true, bind),
c("bone.paint_weights", "Paint Weights", "{bone, at: [[x, y]…] (dab centres, stage px, at most 4096), radius? (px, 1–2000, default 20), strength? (0–100 at the centre, default 25), mode?: \"add\" (default) | \"subtract\" | \"smooth\", frame?} → {bone, changed, bound}. The Bind tool's brush: raises, lowers or evens out how much the bone moves the shape's points within the radius of each dab (a smooth falloff to the rim); each point's weights stay normalised (its other bones share what is left) and the points become hand-bound. A drag sends many in one gesture: one undo step", true, paint_weights),
c("bone.set_weight", "Set Point Weight", "{bone, points: [point index…] (see bone.info with points), weight (0–100: the bone's share of each point)} sets exactly how much the bone moves the points; their other bones share the rest in proportion (a point that followed only this bone gives the rest to its nearest other bones). Hand-bound", true, set_weight),
c("bone.remove", "Remove Bone", "{bone} removes it and the bones below it; the instances they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); asks first when the armature has more than one pose", true, remove),
c("bone.set_limits", "Joint Limits", "{bone, constrain?: bool (false: turns freely), min?, max? (°, −360…360, from where it was drawn)} limits how far the joint turns, in every pose", true, set_limits),
c("bone.set_translation", "Joint Translation", "{bone, axis: \"x\" | \"y\" (along the axes of what the bone starts on, as it is turned), enabled?: bool (false: the joint doesn't slide that way), constrain?: bool (false: slides freely), min?, max? (px, ±10,000, from where it was drawn)} lets the joint slide, in every pose; posing (bone.solve, the Selection tool) slides it only where turning can't reach", true, set_translation),
c("bone.set_spring", "Bone Spring", "{bone, strength? (0–100: 0 is no spring; stiffer swings faster and lags less), damping? (0–100: how quickly the swing dies down; 100 absorbs it all)} secondary motion: the bone lags behind and swings past its pose as the bones it hangs from move, then settles. Evaluated, never stored: the keyed poses don't change", true, set_spring),
c("bone.enable_springs", "Enable Springs", "{enabled: bool, layer? (the armature layer) | bone?} turns the armature's springs on or off (off: it plays its keyed poses exactly, as while posing)", true, enable_springs),
c("bone.pin", "Pin Bone", "{bone, pinned: bool} a pinned bone (and the bones it hangs from) stays put while dragging bones below it", true, pin),
c("bone.pose", "Pose Bone", "{bone?, angle? (°, the joint angle: 0 as drawn), rotate_by? (°), dx?, dy? (moves the whole armature), layer? (the armature layer, when no bone is given), frame?} keys the pose at the frame", true, pose),
c("bone.pose", "Pose Bone", "{bone?, angle? (°, the joint angle: 0 as drawn), rotate_by? (°), slide_x?, slide_y? (px: how far the joint slides, within its translation limits), dx?, dy? (moves the whole armature), layer? (the armature layer, when no bone is given), frame?} keys the pose at the frame", true, pose),
c("bone.solve", "Drag Bone", "{bone, x, y (stage px: where the bone's end goes), local?: [x, y] (the point dragged, in the bone's instance's space; default its end), frame?} → {reached, error (px), chain}; inverse kinematics turns the bone and the bones above it (limits respected, pinned bones kept)", true, solve),
c("bone.info", "Armatures", "{frame?, layer?} → every armature on the scene at the frame: its bones with joint and end (stage px), joint angle and limits (°), pinned", false, info),
c("bone.info", "Armatures", "{frame?, layer?, points?: bool} → every armature on the scene at the frame: its bones with joint and end (stage px, as keyed), joint angle and limits (°), slide and translation limits (px), spring (0–100) and its swing at the frame (°, what the spring adds to the angle), pinned; whether springs are on; a shape armature's shape, how many points each bone moves, and with points the shape's points (stage px) and the bones each follows", false, info),
]
}
@@ -46,7 +61,7 @@ struct Found {
/// Instance `id` on the scene at the playhead (as it shows: tweened, posed).
fn find_instance(s: &Session, id: ElementId) -> Option<Found> {
let tl = s.doc.timeline(s.scene);
let tl = s.timeline();
tl.layers.iter().enumerate().find_map(|(index, l)| {
let (_, els) = evaluate_layer_elements(l, s.frame)?;
let el = els.iter().find(|e| e.id == id)?.clone();
@@ -56,8 +71,8 @@ fn find_instance(s: &Session, id: ElementId) -> Option<Found> {
/// The armature layer holding bone `id`, and its armature.
fn find_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc<Armature>)> {
s.doc
.timeline(s.scene)
s
.timeline()
.layers
.iter()
.filter(|l| l.kind == LayerKind::Armature)
@@ -85,7 +100,7 @@ fn opt_point(p: &Value, key: &str) -> Result<Option<Vec2>> {
}
fn unlocked(s: &Session, id: LayerId) -> Result<()> {
let tl = s.doc.timeline(s.scene);
let tl = s.timeline();
let l = tl.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
if l.locked || tl.locked_by_folder(id) {
return Err(EngineError::State(format!("layer '{}' is locked", l.name)));
@@ -105,7 +120,7 @@ fn take_off(s: &mut Session, layer: LayerId, id: ElementId) -> Result<()> {
/// A layer name `base_N` no layer of the scene has yet.
fn fresh_name(s: &Session, base: &str) -> String {
let tl = s.doc.timeline(s.scene);
let tl = s.timeline();
(1..).map(|n| format!("{base}{n}")).find(|n| tl.layers.iter().all(|l| &l.name != n)).unwrap_or_else(|| base.to_string())
}
@@ -119,6 +134,32 @@ fn rebake(layer: &mut Layer) {
}
}
/// A new armature layer at `index` holding `arm` and `elements` on one pose that spans from the
/// keyframe of `from` at the playhead to the end of the timeline (a classic tween on it, so
/// poses keyed later tween).
fn armature_layer(s: &mut Session, from: LayerId, index: usize, elements: Vec<Arc<Element>>, arm: Armature) -> Result<LayerId> {
let (start, end) = s.timeline().layer(from).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end()));
let end = end.max(s.frame_count());
if s.timeline().layers.len() >= 1000 {
return Err(EngineError::State("too many layers (limit 1000)".into()));
}
let lid = LayerId(s.doc.alloc_id());
let mut layer = Layer::new(lid, fresh_name(s, "Armature_"));
layer.kind = LayerKind::Armature;
// Bones show in the layer colour: a green that reads on light and dark artwork.
layer.color = Rgba::hex(0x2fb67c);
layer.armature = Some(Arc::new(arm));
let mut k = Keyframe::new(start, end.saturating_sub(start).max(1));
k.elements = elements;
k.tween = Some(Tween::default());
layer.keyframes = vec![Arc::new(k)];
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?;
layer.parent = tl.container_at(index, LayerKind::Armature);
tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer));
tl.repair_masks();
Ok(lid)
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
let req = |k: &str| opt_u64(p, k)?.map(ElementId).ok_or_else(|| EngineError::Param(format!("param '{k}' (an instance id) is required")));
let (from, to) = (req("from")?, req("to")?);
@@ -142,7 +183,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
unlocked(s, x.layer)?;
}
let tl = s.doc.timeline(s.scene);
let tl = s.timeline();
let arm_of = |x: &Found| (x.kind == LayerKind::Armature).then(|| tl.layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default());
let (fa, ta) = (arm_of(&f), arm_of(&t));
match (&fa, &ta) {
@@ -158,17 +199,19 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let (wf, wt) = (f.el.transform, t.el.transform);
let singular = || EngineError::State("an instance scaled to nothing can't hold a bone".into());
let (inv_f, inv_t) = (wf.inverse().ok_or_else(singular)?, wt.inverse().ok_or_else(singular)?);
// The joint: given, else the end of the bone into `from` (a chain joins end to start), else
// its registration point.
// The joint. An instance that already hangs from a bone has one joint, that bone's end: every
// bone from it starts there, wherever on the instance the drag began, so the chain stays
// joined end to start and turns about the joints it shows, as in Animate (#239). A root's
// bones start where given (a torso's shoulders and hips), else at its registration point.
let into_from = fa.as_ref().and_then(|a| a.bone_into(from)).map(|b| wf.apply(b.tail));
let head = head.or(into_from).unwrap_or(wf.translation());
let head = into_from.or(head).unwrap_or(wf.translation());
let tail = tail.unwrap_or(wt.translation());
let rest = inv_f.mul(&wt);
if !rest.is_finite() || rest.inverse().is_none() {
return Err(singular());
}
let id = BoneId(s.doc.alloc_id());
let bone = Bone { id, name, parent: from, child: to, head: inv_f.apply(head), tail: inv_t.apply(tail), rest, limits: None, pinned: false };
let bone = Bone { name, ..Bone::new(id, from, to, inv_f.apply(head), inv_t.apply(tail), rest) };
take_off(s, t.layer, to)?;
let lid = match fa {
Some(_) => {
@@ -184,30 +227,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
f.layer
}
None => {
// The first bone: both instances move to a new armature layer above them, whose one
// pose spans from their keyframe to the end of the timeline.
let (start, end) = s.doc.timeline(s.scene).layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end()));
let end = end.max(s.frame_count());
// The first bone: both instances move to a new armature layer above them.
take_off(s, f.layer, from)?;
if s.doc.timeline(s.scene).layers.len() >= 1000 {
return Err(EngineError::State("too many layers (limit 1000)".into()));
}
let lid = LayerId(s.doc.alloc_id());
let mut layer = Layer::new(lid, fresh_name(s, "Armature_"));
layer.kind = LayerKind::Armature;
// Bones show in the layer colour: a green that reads on light and dark artwork.
layer.color = Rgba::hex(0x2fb67c);
layer.armature = Some(Arc::new(Armature { bones: vec![bone] }));
let mut k = Keyframe::new(start, end.saturating_sub(start).max(1));
k.elements = vec![f.el.clone(), t.el.clone()];
k.tween = Some(Tween::default());
layer.keyframes = vec![Arc::new(k)];
let index = f.index.min(t.index);
let tl = s.doc.timeline_mut(s.scene);
layer.parent = tl.container_at(index, LayerKind::Armature);
tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer));
tl.repair_masks();
lid
let arm = Armature { bones: vec![bone], ..Default::default() };
armature_layer(s, f.layer, f.index.min(t.index), vec![f.el.clone(), t.el.clone()], arm)?
}
};
s.layer = lid;
@@ -229,8 +252,11 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let mut left = (*arm).clone();
left.bones.retain(|b| !gone.contains(&b.id));
let dissolve = left.is_empty();
let freed: Vec<ElementId> = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() };
let tl = s.doc.timeline(s.scene);
// A shape armature's bones move no instances: only without bones does its shape go.
let skinned = arm.skin.is_some();
skin::rebind(&mut left);
let freed: Vec<ElementId> = if dissolve { arm.members() } else if skinned { Vec::new() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() };
let tl = s.timeline();
let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
let (start, end) = (layer.keyframes.first().map_or(0, |k| k.start), layer.end_frame());
@@ -244,7 +270,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let mut k = Keyframe::new(start, end.saturating_sub(start).max(1));
k.elements = shown;
freed_layer.keyframes = vec![Arc::new(k)];
let tl = s.doc.timeline_mut(s.scene);
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?;
if dissolve {
tl.layers.retain(|l| l.id != lid);
tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer));
@@ -257,12 +283,15 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
}
l.armature = Some(Arc::new(left));
rebake(l);
tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer));
if !skinned {
tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer));
}
}
tl.repair_masks();
s.layer = if dissolve { new_id } else { lid };
s.selection.clear();
Ok(json!({"removed": gone.iter().map(|b| b.0).collect::<Vec<_>>(), "freed": freed.iter().map(|e| e.0).collect::<Vec<_>>(), "layer": new_id.0, "armature_removed": dissolve}))
let layer = if dissolve || !skinned { new_id } else { lid };
Ok(json!({"removed": gone.iter().map(|b| b.0).collect::<Vec<_>>(), "freed": freed.iter().map(|e| e.0).collect::<Vec<_>>(), "layer": layer.0, "armature_removed": dissolve}))
}
fn set_limits(s: &mut Session, p: &Value) -> Result<Value> {
@@ -308,6 +337,108 @@ fn set_limits(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"bone": id.0, "constrain": limits.is_some(), "min": limits.map(|l| l.min.to_degrees()), "max": limits.map(|l| l.max.to_degrees())}))
}
/// The translation limits of an axis that slides freely.
const FREE: Limits = Limits { min: -MAX_SLIDE, max: MAX_SLIDE };
fn set_translation(s: &mut Session, p: &Value) -> Result<Value> {
let id = bone_param(p)?;
let axis = str_req(p, "axis")?;
let along_x = match axis {
"x" => true,
"y" => false,
_ => return Err(EngineError::Param("param 'axis' must be \"x\" or \"y\"".into())),
};
let (enabled, constrain) = (opt_bool(p, "enabled")?, opt_bool(p, "constrain")?);
let (min, max) = (opt_f32(p, "min")?, opt_f32(p, "max")?);
for v in [min, max].into_iter().flatten() {
if !(-MAX_SLIDE..=MAX_SLIDE).contains(&v) {
return Err(EngineError::Param("joint translation limits must be within ±10,000 px".into()));
}
}
let (lid, arm) = find_bone(s, id)?;
unlocked(s, lid)?;
let b = arm.bone(id).ok_or_else(|| EngineError::State("no such bone".into()))?;
let cur = if along_x { b.slide_x } else { b.slide_y };
let limits = if enabled == Some(false) {
None
} else if enabled.is_none() && constrain.is_none() && min.is_none() && max.is_none() {
return Err(EngineError::Param("give 'enabled', 'constrain' or limits ('min', 'max')".into()));
} else if constrain == Some(false) {
Some(FREE)
} else if constrain.is_none() && min.is_none() && max.is_none() {
// Enabling: freely, or as it was.
Some(cur.unwrap_or(FREE))
} else {
// Constraining without numbers: 50 px either way.
let base = cur.filter(|l| *l != FREE).unwrap_or(Limits { min: -50.0, max: 50.0 });
let l = Limits { min: min.unwrap_or(base.min), max: max.unwrap_or(base.max) };
if l.min > l.max {
return Err(EngineError::Param("the joint's min must be at most its max".into()));
}
Some(l)
};
let mut arm = (*arm).clone();
if let Some(b) = arm.bone_mut(id) {
if along_x {
b.slide_x = limits;
} else {
b.slide_y = limits;
}
}
let l = s.layer_mut(Some(lid))?;
// Every pose keeps to the new limits.
if let Some(b) = arm.bone(id) {
for k in &mut l.keyframes {
let v = k.pose.slide(id);
if b.allow_slide(v) != v {
Arc::make_mut(k).pose.set_slide(id, b.allow_slide(v));
}
}
}
l.armature = Some(Arc::new(arm));
rebake(l);
Ok(json!({"bone": id.0, "axis": axis, "enabled": limits.is_some(), "constrain": limits.is_some_and(|l| l != FREE), "min": limits.map(|l| l.min), "max": limits.map(|l| l.max)}))
}
fn set_spring(s: &mut Session, p: &Value) -> Result<Value> {
let id = bone_param(p)?;
let (strength, damping) = (opt_f32(p, "strength")?, opt_f32(p, "damping")?);
if strength.is_none() && damping.is_none() {
return Err(EngineError::Param("give 'strength' or 'damping' (0–100)".into()));
}
for (k, v) in [("strength", strength), ("damping", damping)] {
if v.is_some_and(|v| !(0.0..=100.0).contains(&v)) {
return Err(EngineError::Param(format!("param '{k}' must be between 0 and 100")));
}
}
let (lid, arm) = find_bone(s, id)?;
unlocked(s, lid)?;
let mut arm = (*arm).clone();
let springs = !arm.springs_off;
let b = arm.bone_mut(id).ok_or_else(|| EngineError::State("no such bone".into()))?;
let cur = b.spring.unwrap_or(Spring { strength: 0.0, damping: 0.0 });
let next = Spring { strength: strength.map_or(cur.strength, |v| v / 100.0), damping: damping.map_or(cur.damping, |v| v / 100.0) };
// Nothing set is no spring: the file says nothing.
b.spring = (next.strength > 0.0 || next.damping > 0.0).then_some(next);
s.layer_mut(Some(lid))?.armature = Some(Arc::new(arm));
Ok(json!({"bone": id.0, "strength": next.strength * 100.0, "damping": next.damping * 100.0, "springs": springs}))
}
fn enable_springs(s: &mut Session, p: &Value) -> Result<Value> {
let enabled = opt_bool(p, "enabled")?.ok_or_else(|| EngineError::Param("param 'enabled' (true or false) is required".into()))?;
let lid = match (opt_u64(p, "bone")?.map(BoneId), opt_u64(p, "layer")?) {
(Some(b), _) => find_bone(s, b)?.0,
(None, Some(l)) => LayerId(l),
(None, None) => s.layer,
};
unlocked(s, lid)?;
let l = s.layer_mut(Some(lid))?;
let mut arm = l.armature.as_deref().cloned().filter(|_| l.kind == LayerKind::Armature).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?;
arm.springs_off = !enabled;
l.armature = Some(Arc::new(arm));
Ok(json!({"layer": lid.0, "springs": enabled}))
}
fn pin(s: &mut Session, p: &Value) -> Result<Value> {
let id = bone_param(p)?;
let pinned = opt_bool(p, "pinned")?.ok_or_else(|| EngineError::Param("param 'pinned' (true or false) is required".into()))?;
@@ -328,7 +459,7 @@ fn edit_pose<T>(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Ar
if frame > MAX_FRAME {
return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}")));
}
let arm = s.doc.timeline(s.scene).layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?;
let arm = s.timeline().layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?;
// Past the end a pose carries on from the last one (not a blank keyframe).
{
let l = s.layer_mut(Some(lid))?;
@@ -354,14 +485,18 @@ fn edit_pose<T>(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Ar
fn pose(s: &mut Session, p: &Value) -> Result<Value> {
let bone = opt_u64(p, "bone")?.map(BoneId);
let (angle, rotate_by, dx, dy) = (opt_f32(p, "angle")?, opt_f32(p, "rotate_by")?, opt_f32(p, "dx")?, opt_f32(p, "dy")?);
let (slide_x, slide_y) = (opt_f32(p, "slide_x")?, opt_f32(p, "slide_y")?);
if [slide_x, slide_y].into_iter().flatten().any(|v| !v.is_finite() || v.abs() > MAX_SLIDE) {
return Err(EngineError::Param("params 'slide_x' and 'slide_y' must be within ±10,000 px".into()));
}
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
let lid = match (bone, opt_u64(p, "layer")?) {
(Some(b), _) => find_bone(s, b)?.0,
(None, Some(l)) => LayerId(l),
(None, None) => s.layer,
};
if bone.is_none() && (angle.is_some() || rotate_by.is_some()) {
return Err(EngineError::Param("param 'bone' says which joint 'angle' or 'rotate_by' turns".into()));
if bone.is_none() && (angle.is_some() || rotate_by.is_some() || slide_x.is_some() || slide_y.is_some()) {
return Err(EngineError::Param("param 'bone' says which joint 'angle', 'rotate_by' or the slide moves".into()));
}
let v = edit_pose(s, lid, frame, |arm, kf| {
let mut out = json!({"layer": lid.0});
@@ -371,6 +506,15 @@ fn pose(s: &mut Session, p: &Value) -> Result<Value> {
kf.pose.set(b.id, next);
out["bone"] = json!(b.id.0);
out["angle"] = json!(next.to_degrees());
if slide_x.is_some() || slide_y.is_some() {
if !b.slides() {
return Err(EngineError::State("that joint doesn't slide: turn on its X or Y translation first (bone.set_translation)".into()));
}
let was = kf.pose.slide(b.id);
let v = b.allow_slide(Vec2::new(slide_x.unwrap_or(was.x), slide_y.unwrap_or(was.y)));
kf.pose.set_slide(b.id, v);
out["slide"] = json!([v.x, v.y]);
}
}
if dx.is_some() || dy.is_some() {
let by = Affine::translate(dx.unwrap_or(0.0), dy.unwrap_or(0.0));
@@ -411,7 +555,8 @@ fn solve(s: &mut Session, p: &Value) -> Result<Value> {
fn info(s: &mut Session, p: &Value) -> Result<Value> {
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
let only = opt_u64(p, "layer")?.map(LayerId);
let tl = s.doc.timeline(s.scene);
let with_points = opt_bool(p, "points")?.unwrap_or(false);
let tl = s.timeline();
let deg = |v: f32| v.to_degrees();
let pt = |v: Vec2| json!([v.x, v.y]);
let list: Vec<Value> = tl
@@ -421,8 +566,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
.filter_map(|l| {
let arm = l.armature.as_deref()?;
let pose = armature::pose_at(l, frame).unwrap_or_default();
let shown = anicraft_doc::spring::sprung_pose(l, frame, s.doc.stage.fps).unwrap_or_default();
let (_, els) = evaluate_layer_elements(l, frame).unwrap_or((0, std::borrow::Cow::Borrowed(&[])));
let at = armature::bones_at(arm, &els, &pose);
let limits = |l: Option<Limits>| l.map(|l| json!({"min": l.min, "max": l.max, "constrain": l != FREE}));
let bones: Vec<Value> = arm
.bones
.iter()
@@ -435,11 +582,327 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
"angle": deg(b.allow(pose.angle(b.id))),
"min": b.limits.map(|l| deg(l.min)), "max": b.limits.map(|l| deg(l.max)),
"pinned": b.pinned,
"slide": g.map(|g| pt(g.slide)),
"slide_x": limits(b.slide_x), "slide_y": limits(b.slide_y),
"spring": b.spring.map(|sp| json!({"strength": sp.strength * 100.0, "damping": sp.damping * 100.0})),
"swing": deg(shown.angle(b.id) - b.allow(pose.angle(b.id))),
"points": arm.skin.as_ref().map(|k| k.points.iter().filter(|x| x.weight(b.id) > 0.0).count()),
})
})
.collect();
Some(json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::<Vec<_>>(), "poses": poses(l), "bones": bones}))
let mut out = json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::<Vec<_>>(), "poses": poses(l), "bones": bones, "shape": arm.skin_shape().map(|e| e.0), "springs": !arm.springs_off});
if with_points && let Some(k) = &arm.skin {
out["points"] = json!(skin::points_shown(arm, &els).iter().zip(&k.points).map(|(at, b)| json!({"at": pt(*at), "bones": b.bones.iter().map(|i| json!([i.0.0, i.1])).collect::<Vec<_>>(), "manual": b.manual})).collect::<Vec<_>>());
}
Some(out)
})
.collect();
Ok(json!({"frame": frame, "armatures": list}))
}
fn add_in_shape(s: &mut Session, p: &Value) -> Result<Value> {
let shape = opt_u64(p, "shape")?.map(ElementId);
let parent = opt_u64(p, "parent")?.map(BoneId);
let head = opt_point(p, "head")?;
let tail = opt_point(p, "tail")?.ok_or_else(|| EngineError::Param("param 'tail' ([x, y], stage px: where the bone ends) is required".into()))?;
let name = opt_str(p, "name")?.unwrap_or("").trim().to_string();
if name.len() > MAX_NAME {
return Err(EngineError::Param(format!("param 'name' must be at most {MAX_NAME} bytes")));
}
let frame = s.frame;
// The armature the bone joins (none yet for the first bone), the shape, the node the bone
// starts on, and its joint on the stage.
let (existing, found, from, head) = match (parent, shape) {
(Some(b), _) => {
let (lid, arm) = find_bone(s, b)?;
let sh = arm.skin_shape().ok_or_else(|| EngineError::State("that bone joins symbol instances: continue it with bone.add".into()))?;
if shape.is_some_and(|x| x != sh) {
return Err(EngineError::Param("that bone is in another shape".into()));
}
let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("the armature's shape isn't on the stage at frame {}", frame + 1)))?;
let node = arm.bone(b).map(|x| x.child).ok_or_else(|| EngineError::State("no such bone".into()))?;
let end = s.timeline().layer(lid).and_then(|l| {
let (_, els) = evaluate_layer_elements(l, frame)?;
let pose = armature::pose_at(l, frame).unwrap_or_default();
armature::bones_at(&arm, &els, &pose).into_iter().find(|g| g.id == b).map(|g| g.tail)
});
let head = head.or(end).ok_or_else(|| EngineError::State(format!("the bone isn't on the stage at frame {}", frame + 1)))?;
(Some((lid, arm)), f, node, head)
}
(None, Some(sh)) => {
let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("no shape with id {} on the stage at frame {}", sh.0, frame + 1)))?;
let ElementKind::Shape(shp) = &f.el.kind else {
return Err(EngineError::State("bones inside a shape need a shape: for symbol instances, drag from one to another (bone.add)".into()));
};
let head = head.ok_or_else(|| EngineError::Param("param 'head' ([x, y], stage px: where the bone starts, inside the shape) is required".into()))?;
let existing = match f.kind {
LayerKind::Normal => None,
LayerKind::Armature => {
let arm = s.timeline().layer(f.layer).and_then(|l| l.armature.clone()).filter(|a| a.skin_shape() == Some(sh)).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?;
Some((f.layer, arm))
}
_ => return Err(EngineError::State("bones go inside shapes on normal layers (not on guide or mask layers)".into())),
};
// A bone starts inside the shape (on its fill, or on its line).
let reach = shp.stroke.as_ref().map_or(0.0, |k| k.width * 0.5 * f.el.transform.mean_scale()) + 2.0;
let inside = (shp.fill.is_some() && shp.path.contains(head, &f.el.transform, shp.fill_rule)) || shp.path.distance_to_edge(head, &f.el.transform) <= reach;
if !inside {
return Err(EngineError::State("start the bone inside the shape".into()));
}
(existing, f, sh, head)
}
(None, None) => return Err(EngineError::Param("give 'shape' (the shape's id, for the first bone) or 'parent' (a bone to continue from)".into())),
};
unlocked(s, found.layer)?;
if head.distance(tail) < 1.0 {
return Err(EngineError::Param("a bone needs a length: drag from its joint to its end".into()));
}
let ElementKind::Shape(shp) = &found.el.kind else { return Err(EngineError::State("that isn't a shape".into())) };
// The node the bone starts on, as placed at the playhead: the bone's points go back through
// it to the shape as drawn (a new bone is at rest in every pose).
let node = match &existing {
Some((lid, arm)) => {
let l = s.timeline().layer(*lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
let (_, els) = evaluate_layer_elements(l, frame).ok_or_else(|| EngineError::State("the armature isn't on this frame".into()))?;
let pose = armature::pose_at(l, frame).unwrap_or_default();
armature::place(arm, &els, &pose).get(&from).copied()
}
None => Some(found.el.transform),
};
let inv = node.and_then(|m| m.inverse()).ok_or_else(|| EngineError::State("a shape scaled to nothing can't hold a bone".into()))?;
let (h, t) = (inv.apply(head), inv.apply(tail));
if !(h.x.is_finite() && h.y.is_finite() && t.x.is_finite() && t.y.is_finite()) {
return Err(EngineError::State("a shape scaled to nothing can't hold a bone".into()));
}
if existing.as_ref().is_some_and(|(_, a)| a.bones.len() >= MAX_BONES) {
return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones")));
}
if existing.is_none() && skin::anchors(&shp.path).len() > MAX_SKIN_POINTS {
return Err(EngineError::State(format!("bones go inside shapes of at most {MAX_SKIN_POINTS} points: simplify it first (Modify › Shape › Optimize)")));
}
let id = BoneId(s.doc.alloc_id());
let child = ElementId(s.doc.alloc_id());
let bone = Bone { name, ..Bone::new(id, from, child, h, t, Affine::IDENTITY) };
let (lid, created) = match existing {
Some((lid, arm)) => {
let mut arm = (*arm).clone();
arm.bones.push(bone);
skin::rebind(&mut arm);
let l = s.layer_mut(Some(lid))?;
l.armature = Some(Arc::new(arm));
rebake(l);
(lid, false)
}
None => {
// An armature's shape is an object: merge drawing (ADR 0031) no longer cuts it.
let mut el = (*found.el).clone();
if let ElementKind::Shape(x) = &mut el.kind {
x.merge = false;
}
let mut arm = Armature { bones: vec![bone], skin: Some(Skin::new(found.el.id, shp.path.clone())), ..Default::default() };
skin::rebind(&mut arm);
take_off(s, found.layer, found.el.id)?;
(armature_layer(s, found.layer, found.index, vec![Arc::new(el)], arm)?, true)
}
};
s.layer = lid;
s.selection.clear();
let bound = s.timeline().layer(lid).and_then(|l| l.armature.as_ref()).and_then(|a| a.skin.as_ref()).map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count());
Ok(json!({"bone": id.0, "layer": lid.0, "created": created, "points": bound}))
}
fn bind(s: &mut Session, p: &Value) -> Result<Value> {
let id = bone_param(p)?;
let mode = opt_str(p, "mode")?.unwrap_or("only");
if !matches!(mode, "only" | "add" | "remove" | "auto") {
return Err(EngineError::Param("param 'mode' must be \"only\", \"add\", \"remove\" or \"auto\"".into()));
}
let (lid, arm) = find_bone(s, id)?;
unlocked(s, lid)?;
let n = arm.skin.as_ref().map(|k| k.points.len()).ok_or_else(|| EngineError::State("that bone joins symbol instances: only bones inside a shape bind its points".into()))?;
let bad = || EngineError::Param(format!("param 'points' must be a list of point indices below {n} (see bone.info with points)"));
let points: Vec<usize> = match p.get("points") {
None | Some(Value::Null) => (0..n).collect(),
Some(Value::Array(a)) if a.len() <= MAX_SKIN_POINTS => a.iter().map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n).ok_or_else(bad)).collect::<Result<_>>()?,
Some(_) => return Err(bad()),
};
let mut arm = (*arm).clone();
let segments = skin::rest_segments(&arm);
let Some(k) = arm.skin.as_mut() else { return Err(EngineError::State("that bone isn't inside a shape".into())) };
let anchors = skin::anchors(&k.rest);
let mut changed = 0usize;
for i in points {
let (Some(b), Some(&at)) = (k.points.get_mut(i), anchors.get(i)) else { continue };
let next = match mode {
"only" => Binding { bones: vec![Influence(id, 1.0)], manual: true },
"add" if b.weight(id) > 0.0 => continue,
"add" => {
// An equal share with the bones the point already follows.
let share = 1.0 / (b.bones.len() + 1) as f32;
let mut x = Binding { bones: b.bones.iter().map(|i| Influence(i.0, i.1 * (1.0 - share))).collect(), manual: true };
x.bones.push(Influence(id, share));
x.normalize(|_| true);
x
}
"remove" => {
let mut x = Binding { bones: b.bones.iter().copied().filter(|i| i.0 != id).collect(), manual: true };
x.normalize(|_| true);
x
}
_ => skin::auto_binding(&segments, at),
};
if *b != next {
*b = next;
changed += 1;
}
}
let bound = k.points.iter().filter(|b| b.weight(id) > 0.0).count();
let l = s.layer_mut(Some(lid))?;
l.armature = Some(Arc::new(arm));
rebake(l);
Ok(json!({"bone": id.0, "changed": changed, "bound": bound}))
}
/// The point indices in param `key`, each below `n`.
fn point_list(p: &Value, key: &str, n: usize) -> Result<Vec<usize>> {
let bad = || EngineError::Param(format!("param '{key}' must be a list of point indices below {n} (see bone.info with points)"));
match p.get(key) {
Some(Value::Array(a)) if a.len() <= MAX_SKIN_POINTS => a.iter().map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n).ok_or_else(bad)).collect(),
_ => Err(bad()),
}
}
/// How many points bone `id` moves.
fn bound_count(arm: &Armature, id: BoneId) -> usize {
arm.skin.as_ref().map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count())
}
/// A bone inside a shape, its unlocked armature layer and the armature.
fn shape_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc<Armature>)> {
let (lid, arm) = find_bone(s, id)?;
unlocked(s, lid)?;
if arm.skin.is_none() {
return Err(EngineError::State("that bone joins symbol instances: only bones inside a shape have weights on its points".into()));
}
Ok((lid, arm))
}
fn paint_weights(s: &mut Session, p: &Value) -> Result<Value> {
let id = bone_param(p)?;
let bad = || EngineError::Param(format!("param 'at' must be a list of at most {MAX_DABS} [x, y] points (stage px, within ±1,000,000)"));
let list = p.get("at").and_then(Value::as_array).filter(|a| a.len() <= MAX_DABS).ok_or_else(bad)?;
let dabs: Vec<Vec2> = list
.iter()
.map(|v| {
let a = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?;
let n = |i: usize| a.get(i).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() <= f64::from(MAX_COORD)).map(|v| v as f32).ok_or_else(bad);
Ok(Vec2::new(n(0)?, n(1)?))
})
.collect::<Result<_>>()?;
let radius = opt_f32(p, "radius")?.unwrap_or(20.0);
if !(1.0..=MAX_RADIUS).contains(&radius) {
return Err(EngineError::Param(format!("param 'radius' must be between 1 and {MAX_RADIUS} px")));
}
let strength = opt_f32(p, "strength")?.unwrap_or(25.0);
if !(0.0..=100.0).contains(&strength) {
return Err(EngineError::Param("param 'strength' must be between 0 and 100".into()));
}
let brush = match opt_str(p, "mode")? {
None => Brush::Add,
Some(m) => Brush::parse(m).ok_or_else(|| EngineError::Param("param 'mode' must be \"add\", \"subtract\" or \"smooth\"".into()))?,
};
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
let (lid, arm) = shape_bone(s, id)?;
// The points where the stage shows them at the frame: the brush paints what the artist sees.
let shown = s.timeline().layer(lid).and_then(|l| evaluate_layer_elements(l, frame)).map(|(_, els)| skin::points_shown(&arm, &els)).unwrap_or_default();
if shown.is_empty() {
return Err(EngineError::State(format!("the bone's shape isn't on the stage at frame {}", frame + 1)));
}
let mut arm = (*arm).clone();
let segments = skin::rest_segments(&arm);
let changed = match arm.skin.as_mut() {
Some(k) => weights::paint(k, &segments, &shown, id, &dabs, Dab { brush, radius, strength: strength / 100.0 }),
None => 0,
};
let bound = bound_count(&arm, id);
if changed > 0 {
let l = s.layer_mut(Some(lid))?;
l.armature = Some(Arc::new(arm));
rebake(l);
}
Ok(json!({"bone": id.0, "changed": changed, "bound": bound, "mode": brush.key()}))
}
fn set_weight(s: &mut Session, p: &Value) -> Result<Value> {
let id = bone_param(p)?;
let w = f32_req(p, "weight")?;
if !(0.0..=100.0).contains(&w) {
return Err(EngineError::Param("param 'weight' must be between 0 and 100".into()));
}
let (lid, arm) = shape_bone(s, id)?;
let n = arm.skin.as_ref().map_or(0, |k| k.points.len());
let points = point_list(p, "points", n)?;
let mut arm = (*arm).clone();
let segments = skin::rest_segments(&arm);
let Some(k) = arm.skin.as_mut() else { return Err(EngineError::State("that bone isn't inside a shape".into())) };
let rest = skin::anchors(&k.rest);
let mut changed = 0usize;
for &i in &points {
let (Some(b), Some(&at)) = (k.points.get_mut(i), rest.get(i)) else { continue };
let next = weights::with_share(b, id, w / 100.0, || weights::others_at(&segments, id, at));
if *b != next {
*b = next;
changed += 1;
}
}
let shares: Vec<Value> = points.iter().map(|&i| json!(k.points.get(i).map(|b| b.bones.iter().map(|x| json!([x.0.0, x.1 * 100.0])).collect::<Vec<_>>()).unwrap_or_default())).collect();
let bound = bound_count(&arm, id);
let l = s.layer_mut(Some(lid))?;
l.armature = Some(Arc::new(arm));
rebake(l);
Ok(json!({"bone": id.0, "changed": changed, "bound": bound, "weights": shares}))
}
/// Whether element `id` is the shape of the shape armature on the active layer (so point edits
/// reshape the skin instead of a keyframe's artwork).
pub(crate) fn is_skin_shape(s: &Session, id: ElementId) -> bool {
s.timeline().layer(s.layer).is_some_and(|l| l.kind == LayerKind::Armature && l.armature.as_ref().and_then(|a| a.skin_shape()) == Some(id))
}
/// Reshaping a bound shape (ADR 0090): `edit` changes the shape's outline as drawn (its rest
/// outline, with the shape's transform at the playhead), which needs the armature at rest there.
/// The binding is carried over to the new outline (moved points keep their weights, new points
/// blend their neighbours', deleted ones drop theirs) and every pose bends the new outline. One
/// undo step, like any command.
pub(crate) fn reshape<T>(s: &mut Session, id: ElementId, edit: impl FnOnce(&mut Shape, Affine) -> Result<T>) -> Result<T> {
let (lid, frame) = (s.layer, s.frame);
unlocked(s, lid)?;
let tl = s.timeline();
let l = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
let arm = l.armature.clone().ok_or_else(|| EngineError::State("that is not an armature layer".into()))?;
let k = arm.skin.as_ref().filter(|k| k.shape == id).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?;
let pose = armature::pose_at(l, frame).ok_or_else(|| EngineError::State(format!("the armature isn't on frame {}", frame + 1)))?;
if skin::matrices(&arm, &pose).values().any(|m| *m != Affine::IDENTITY) {
return Err(EngineError::State("reshape a shape with bones at its rest pose: go to a frame where every bone is as drawn (angle 0, no slide), or pose them back".into()));
}
let (_, els) = evaluate_layer_elements(l, frame).ok_or_else(|| EngineError::State(format!("the armature isn't on frame {}", frame + 1)))?;
let el = els.iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?;
let ElementKind::Shape(shape) = &el.kind else { return Err(EngineError::State("that isn't a shape".into())) };
let mut shape = shape.clone();
shape.path = k.rest.clone();
let out = edit(&mut shape, el.transform)?;
if *shape.path == *k.rest {
return Ok(out);
}
let n = skin::anchors(&shape.path).len();
if n > MAX_SKIN_POINTS {
return Err(EngineError::State(format!("a shape with bones has at most {MAX_SKIN_POINTS} points")));
}
let skin = weights::reshaped(k, shape.path.clone(), &skin::rest_segments(&arm));
let mut arm = (*arm).clone();
arm.skin = Some(skin);
let l = s.layer_mut(Some(lid))?;
l.armature = Some(Arc::new(arm));
rebake(l);
Ok(out)
}
+392 -31
View File
@@ -2,26 +2,35 @@
//! tip sweeps, in the fill colour. Off Object Drawing it is a raw shape that merges with the
//! drawing (ADR 0031), placed by the paint mode.
use crate::cmds_draw::{MAX_EXTENT, object_param};
use crate::brush_library::{BUILTIN, BrushLibrary, BrushPreset, MAX_FILE_BYTES, MAX_USER_PRESETS, builtin, builtin_hint, clean_name};
use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param};
use crate::merge::{self, Order};
use crate::params::*;
use crate::{CommandSpec, EngineError, Result, Session};
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Paint, Shape};
use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tip, TipShape, outline};
use anicraft_geom::{Affine, FillRule, PathCmd, Vec2};
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, MAX_WIDTH_POINTS, Paint, Rgba, Shape, Stroke, WidthPoint, WidthProfile};
use anicraft_geom::planar;
use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tilt, Tip, TipShape, centre_stroke, outline_shaped};
use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2};
use serde_json::{Value, json};
use std::sync::Arc;
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec {
id: "draw.brush",
label: "Brush Stroke",
menu: "",
shortcut: None,
params: "{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), mode?: normal|fills|behind (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas), color? (default: the fill colour), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}",
mutates: true,
run: draw_brush,
}]
let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run };
vec![
c(
"draw.brush",
"Brush Stroke",
"{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}",
true,
draw_brush as crate::RunFn,
),
c("brush.preset_list", "Brush Presets", "{} the built-in brushes and yours, with their settings", false, preset_list),
c("brush.preset_save", "Save Brush", "{name, from? (a preset to start from; default: the plain brush), size?, shape?, angle?, roundness?, smoothing?, curve?, pressure_size?, pressure_opacity?, taper_start?, taper_end?, spacing?, jitter?, texture?, scatter?, tilt_angle?, tilt_width? (as draw.brush)} saves a brush of your own (replacing yours of that name; kept in your preferences)", false, preset_save),
c("brush.preset_rename", "Rename Brush", "{name, to}", false, preset_rename),
c("brush.preset_delete", "Delete Brush", "{name} deletes a brush of your own (asks first: it can't be undone)", false, preset_delete),
c("brush.preset_export", "Export Brushes", "{path, names? (default: all yours)} writes your brushes to a brush set file (JSON)", false, preset_export),
c("brush.preset_import", "Import Brushes", "{path} adds the brushes in a brush set file to yours (a name you have already gets a number)", false, preset_import),
]
}
/// Brush sizes, in stage units.
@@ -34,16 +43,22 @@ pub enum PaintMode {
Normal,
Fills,
Behind,
/// Only inside the selected fills (ADR 0080).
Selection,
/// Only inside the fill the stroke starts on (ADR 0080).
Inside,
}
impl PaintMode {
pub const ALL: [PaintMode; 3] = [PaintMode::Normal, PaintMode::Fills, PaintMode::Behind];
pub const ALL: [PaintMode; 5] = [PaintMode::Normal, PaintMode::Fills, PaintMode::Behind, PaintMode::Selection, PaintMode::Inside];
pub fn key(self) -> &'static str {
match self {
PaintMode::Normal => "normal",
PaintMode::Fills => "fills",
PaintMode::Behind => "behind",
PaintMode::Selection => "selection",
PaintMode::Inside => "inside",
}
}
pub fn label(self) -> &'static str {
@@ -51,6 +66,8 @@ impl PaintMode {
PaintMode::Normal => "Paint Normal",
PaintMode::Fills => "Paint Fills",
PaintMode::Behind => "Paint Behind",
PaintMode::Selection => "Paint Selection",
PaintMode::Inside => "Paint Inside",
}
}
pub fn hint(self) -> &'static str {
@@ -58,12 +75,15 @@ impl PaintMode {
PaintMode::Normal => "Paints over lines and fills on the layer.",
PaintMode::Fills => "Paints over fills and empty areas, leaving lines alone.",
PaintMode::Behind => "Paints only empty areas, behind the lines and fills on the layer.",
PaintMode::Selection => "Paints only inside the selected fills, leaving lines alone.",
PaintMode::Inside => "Paints only inside the fill where the stroke starts, leaving lines alone. Started on empty stage, it paints only the empty area there.",
}
}
fn order(self) -> Order {
match self {
PaintMode::Normal => Order::Top,
PaintMode::Fills => Order::UnderLines,
// Clipped paint never covers a line either (ADR 0080).
PaintMode::Fills | PaintMode::Selection | PaintMode::Inside => Order::UnderLines,
PaintMode::Behind => Order::Behind,
}
}
@@ -72,8 +92,51 @@ impl PaintMode {
}
}
/// Where Paint Selection and Paint Inside may paint (ADR 0080).
enum Region {
/// Inside this outline (keyframe space, even-odd).
Clip(Path),
/// Only empty areas: Paint Inside started on open, empty stage (as Paint Behind).
Empty,
/// Nowhere, and why.
Nowhere(&'static str),
}
const TOO_MUCH: &str = "there is too much artwork there to paint inside at once; paint a smaller area";
/// The region a clipped paint mode paints in: the union of the selected shapes' fills on the
/// active layer (Paint Selection), or the topmost fill under `start` there, else the empty area
/// the lines and fills close off around it (Paint Inside). Merged paint lies under drawing
/// objects, so off Object Drawing only raw fills count (an object is edited inside it).
fn paint_region(s: &mut Session, mode: PaintMode, start: Vec2, object: bool) -> Result<Region> {
let els = s.editable_keyframe()?.elements.clone();
let filled = |e: &Element| match &e.kind {
ElementKind::Shape(sh) if sh.fill.is_some() && (object || sh.merge) => Some((sh.path.transformed(&e.transform), sh.fill_rule)),
_ => None,
};
let too_much = || EngineError::State(TOO_MUCH.into());
if mode == PaintMode::Selection {
let here = s.layer;
let picked: Vec<(Path, FillRule)> = els.iter().filter(|e| s.selection.contains(here, e.id)).filter_map(|e| filled(e)).collect();
if picked.is_empty() {
return Ok(Region::Nowhere(if s.selection.on(here).is_empty() { "select the fills to paint inside first" } else { "the selection has no fills to paint inside" }));
}
let refs: Vec<(&Path, FillRule)> = picked.iter().map(|(p, r)| (p, *r)).collect();
return Ok(Region::Clip(planar::union(&refs).ok_or_else(too_much)?));
}
let on = els.iter().rev().find_map(|e| filled(e).filter(|(p, r)| p.contains(start, &Affine::IDENTITY, *r)));
if let Some((path, rule)) = on {
// The fill's own rule, as even-odd loops.
return Ok(Region::Clip(planar::union(&[(&path, rule)]).ok_or_else(too_much)?));
}
Ok(match merge::enclosed_area(&els, start) {
Some(area) => Region::Clip(area),
None => Region::Empty,
})
}
pub(crate) fn samples(p: &Value) -> Result<Vec<Sample>> {
let bad = || EngineError::Param("param 'points' must be a list of [x, y] or [x, y, pressure]".into());
let bad = || EngineError::Param("param 'points' must be a list of [x, y], [x, y, pressure] or [x, y, pressure, altitude, azimuth]".into());
let list = p.get("points").and_then(Value::as_array).ok_or_else(bad)?;
if list.is_empty() {
return Err(EngineError::Param("param 'points' needs at least one point".into()));
@@ -83,7 +146,7 @@ pub(crate) fn samples(p: &Value) -> Result<Vec<Sample>> {
}
list.iter()
.map(|v| {
let xyp = v.as_array().filter(|a| (2..=3).contains(&a.len())).ok_or_else(bad)?;
let xyp = v.as_array().filter(|a| matches!(a.len(), 2 | 3 | 5)).ok_or_else(bad)?;
let n = |i: usize| xyp.get(i).and_then(Value::as_f64).map(|f| f as f32).filter(|f| f.is_finite());
let at = Vec2::new(n(0).ok_or_else(bad)?, n(1).ok_or_else(bad)?);
// Pressure is a measurement: tablets and arithmetic stray a little past 0..1, so it
@@ -92,7 +155,19 @@ pub(crate) fn samples(p: &Value) -> Result<Vec<Sample>> {
None => 1.0,
Some(_) => n(2).ok_or_else(|| EngineError::Param("a point's pressure must be a number from 0 to 1".into()))?.clamp(0.0, 1.0),
};
Ok(Sample { at, pressure })
// Tilt (ADR 0093): the pen's altitude (90 upright .. 0 flat) and azimuth (the way
// it leans on the stage, clockwise from +x), both in degrees, as Pointer Events
// report them. A measurement too: the altitude is clamped, the azimuth wraps.
let tilt = match (xyp.get(3), xyp.get(4)) {
(Some(_), Some(_)) => {
let bad_tilt = || EngineError::Param("a point's altitude and azimuth must be numbers of degrees".into());
let altitude = n(3).filter(|a| a.abs() <= 1e6).ok_or_else(bad_tilt)?.clamp(0.0, 90.0);
let azimuth = n(4).filter(|a| a.abs() <= 1e6).ok_or_else(bad_tilt)?;
Some(Tilt { altitude, azimuth })
}
_ => None,
};
Ok(Sample { at, pressure, tilt })
})
.collect()
}
@@ -132,49 +207,335 @@ pub(crate) fn tip(p: &Value) -> Result<Tip> {
Ok(Tip { shape, size, angle, roundness: roundness / 100.0 })
}
/// The brush a command paints with: its `preset` (or the plain brush) with the params' own
/// settings on top.
pub fn brush_param(s: &Session, p: &Value) -> Result<BrushPreset> {
let base = match opt_str(p, "preset")? {
Some(name) => s.brushes.find(name).ok_or_else(|| EngineError::Param(format!("no brush named '{name}' (brush.preset_list lists them)")))?,
None => BrushPreset::default(),
};
base.with_params(p)
}
/// The stroke's opacity factor when pressure drives it: the average mapped pressure.
pub fn pressure_opacity(b: &BrushPreset, pts: &[Sample]) -> f32 {
if !b.pressure_opacity || pts.is_empty() {
return 1.0;
}
(pts.iter().map(|x| b.curve.map(x.pressure)).sum::<f32>() / pts.len() as f32).clamp(0.05, 1.0)
}
fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
let pts = bounded_samples(p)?;
let tip = tip(p)?;
let b = brush_param(s, p)?;
let tip = b.tip();
let size = tip.size;
let smoothing = ranged(p, "smoothing", 0.0..=100.0, 50.0)?;
let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false);
let unit = ranged(p, "unit", 0.001..=1000.0, 1.0)?;
let mode_key = opt_str(p, "mode")?.unwrap_or("normal");
let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills or behind)")))?;
let color = opt_color(p, "color")?.unwrap_or(s.style.fill);
let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills, behind, selection or inside)")))?;
let color = opt_color(p, "color")?.unwrap_or(if as_stroke { s.style.stroke } else { s.style.fill });
let color = Rgba { a: color.a * pressure_opacity(&b, &pts), ..color };
let object = object_param(s, p)?;
// Pressure through the curve (ADR 0068) before it sizes the tip.
let pts: Vec<Sample> = pts.iter().map(|x| Sample { pressure: b.size_pressure(x.pressure), ..*x }).collect();
// Smoothing and accuracy are screen distances, so a stroke looks the same at any zoom: at 50
// the centre line may wander 3.3 screen points from the hand, at 0 a third of a point.
// The outline is fitted within a third of a screen point, or a hundredth of the size for
// small brushes (so a small dab is still round).
let path = outline(&pts, &tip, unit * (0.3 + smoothing * 0.06), (unit * 0.35).min(size * 0.01));
let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(size * 0.01));
if as_stroke {
return paint_stroke(s, &pts, &b, smoothing, tol, color, object);
}
let start = pts.first().map_or(Vec2::ZERO, |x| x.at);
let mut path = outline_shaped(&pts, &tip, &b.shaping(), smoothing, tol);
if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) {
return Err(EngineError::Param("the stroke is too small to paint".into()));
}
// Paint Selection and Paint Inside (ADR 0080): the outline clipped to the region, then
// merged as usual. Nothing changes when nothing is painted (no keyframe made, no step).
let mut order = mode.order();
// Paint Selection keeps the selection: the region, to select again after the merge.
let mut kept_region: Option<Path> = None;
if matches!(mode, PaintMode::Selection | PaintMode::Inside) {
let before = s.doc.clone();
let region = paint_region(s, mode, start, object);
let clipped = match region {
Ok(Region::Clip(r)) => {
let c = planar::intersect(&path, FillRule::EvenOdd, &r).ok_or_else(|| EngineError::State(TOO_MUCH.into()));
kept_region = (mode == PaintMode::Selection).then_some(r);
Some(c)
}
Ok(Region::Empty) => None,
Ok(Region::Nowhere(why)) => {
s.doc = before;
return Ok(json!({"painted": false, "mode": mode.key(), "elements": [], "reason": why}));
}
Err(e) => Some(Err(e)),
};
match clipped {
None => order = Order::Behind,
Some(Err(e)) => {
s.doc = before;
return Err(e);
}
Some(Ok(p)) if !p.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) => {
s.doc = before;
let why = if mode == PaintMode::Selection { "the stroke doesn't reach the selected fills" } else { "nothing to paint there" };
return Ok(json!({"painted": false, "mode": mode.key(), "elements": [], "reason": why}));
}
Some(Ok(p)) => path = p,
}
}
let c = path.bounds().center();
let local = path.transformed(&Affine::translate(-c.x, -c.y));
// A gradient or bitmap in the fill swatch paints too, locked or fitted (ADR 0074), unless a
// colour was given or pressure sets the opacity.
let fill = match &s.style.fill_paint {
Some(_) if p.get("color").is_none_or(Value::is_null) && color.a >= 1.0 => s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()),
_ => Paint::Solid(color),
};
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(path.transformed(&Affine::translate(-c.x, -c.y))), fill: Some(Paint::Solid(color)), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }),
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }),
};
if s.editable_keyframe()?.elements.len() >= 100_000 {
return Err(EngineError::State("too many elements on this keyframe".into()));
}
if object {
let kf = s.editable_keyframe()?;
match mode {
match order {
// Behind everything on the layer.
PaintMode::Behind => kf.elements.insert(0, Arc::new(el)),
PaintMode::Normal | PaintMode::Fills => kf.elements.push(Arc::new(el)),
Order::Behind => kf.elements.insert(0, Arc::new(el)),
Order::Top | Order::UnderLines => kf.elements.push(Arc::new(el)),
}
// Paint Selection: the selected objects stay selected, for the next stroke.
if kept_region.is_none() {
s.select_only([id]);
}
s.select_only([id]);
return Ok(json!({"element": id.0, "elements": [id.0], "mode": mode.key(), "merged": false}));
}
let merged = merge::merge_in_order(s, vec![el], mode.order())?;
s.select_only(merged);
let ids: Vec<u64> = s.selection.id_list();
let merged = merge::merge_in_order(s, vec![el], order)?;
let ids: Vec<u64> = merged.iter().map(|e| e.0).collect();
match &kept_region {
// Paint Selection: what lies in the region (the selected fills' pieces and the paint)
// stays selected, for the next stroke.
Some(region) => {
let inside = pieces_in(s, region);
s.select_only(inside);
}
None => s.select_only(merged),
}
Ok(json!({"element": ids.first(), "elements": ids, "mode": mode.key(), "merged": true}))
}
/// The raw fills on the active keyframe that cover part of `region` (keyframe space, even-odd).
fn pieces_in(s: &mut Session, region: &Path) -> Vec<ElementId> {
let Ok(kf) = s.editable_keyframe() else { return Vec::new() };
let bounds = region.bounds();
kf.elements
.iter()
.filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_some() && !sh.path.bounds().transformed(&e.transform).intersect(&bounds).is_empty()))
.filter(|e| match &e.kind {
ElementKind::Shape(sh) => planar::intersect(&sh.path.transformed(&e.transform), sh.fill_rule, region).is_some_and(|p| !p.is_empty()),
_ => false,
})
.map(|e| e.id)
.collect()
}
/// Width points a Paint Brush stroke's profile is simplified from (evenly along its length).
const PROFILE_SAMPLES: usize = 256;
/// How closely the simplified profile follows the brush's widths (a factor of the size).
const PROFILE_TOLERANCE: f32 = 0.015;
/// The Paint Brush (ADR 0068): the smoothed centre line as a stroke of the brush's size in the
/// stroke colour, its width profile following the pressure and tapers, so the Width tool edits
/// it afterwards. A stroke of one width is a plain line and merges like the Pencil's.
fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32, tol: f32, color: Rgba, object: bool) -> Result<Value> {
let (path, factors) = centre_stroke(pts, &b.shaping(), smoothing, tol * 0.25, PROFILE_SAMPLES);
if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) {
return Err(EngineError::Param("the stroke is too short to draw a line".into()));
}
let kept = simplify_profile(&factors, PROFILE_TOLERANCE, MAX_WIDTH_POINTS);
let profile = WidthProfile::new(kept.iter().map(|(t, f)| WidthPoint::new(*t, *f, *f)).collect());
let stroke = Stroke::new(color, b.size).with_profile(profile);
let c = path.bounds().center();
let mut v = add_shape(s, "paint_brush", path.transformed(&Affine::translate(-c.x, -c.y)), c, None, Some(stroke), object)?;
v["width_points"] = json!(kept.len());
Ok(v)
}
/// The fewest of `pts` (`(t, factor)`, sorted) that stay within `tol` of the rest by straight
/// lines between them (Ramer–Douglas–Peucker), widening the tolerance until at most `max` are
/// kept. The ends always stay.
pub fn simplify_profile(pts: &[(f32, f32)], tol: f32, max: usize) -> Vec<(f32, f32)> {
let n = pts.len();
if n <= 2 {
return pts.to_vec();
}
let mut tol = tol.max(1e-4);
for _ in 0..12 {
let mut keep = vec![false; n];
if let Some(k) = keep.first_mut() {
*k = true;
}
if let Some(k) = keep.last_mut() {
*k = true;
}
let mut stack = vec![(0usize, n - 1)];
while let Some((a, z)) = stack.pop() {
let (Some(pa), Some(pz)) = (pts.get(a), pts.get(z)) else { continue };
let mut worst = (0.0f32, a);
for i in a + 1..z {
let Some(q) = pts.get(i) else { continue };
let t = if pz.0 - pa.0 > 1e-9 { (q.0 - pa.0) / (pz.0 - pa.0) } else { 0.0 };
let d = (q.1 - (pa.1 + (pz.1 - pa.1) * t)).abs();
if d > worst.0 {
worst = (d, i);
}
}
if worst.0 > tol {
if let Some(k) = keep.get_mut(worst.1) {
*k = true;
}
stack.push((a, worst.1));
stack.push((worst.1, z));
}
}
let out: Vec<(f32, f32)> = pts.iter().zip(&keep).filter(|(_, k)| **k).map(|(p, _)| *p).collect();
if out.len() <= max.max(2) {
return out;
}
tol *= 1.6;
}
// Still too many (a wildly varying pressure): evenly spaced points.
let m = max.max(2);
(0..m).filter_map(|i| pts.get(i * (n - 1) / (m - 1))).copied().collect()
}
// ----- the brush library (ADR 0068) ---------------------------------------------------------
fn preset_json(p: &BrushPreset, key: Option<&str>) -> Value {
let mut v = p.params();
v["name"] = json!(p.name);
v["builtin"] = json!(key.is_some());
if let Some(k) = key {
v["key"] = json!(k);
v["hint"] = json!(builtin_hint(k));
}
v
}
fn preset_list(s: &mut Session, _: &Value) -> Result<Value> {
let mut list: Vec<Value> = BUILTIN.iter().filter_map(|(k, _)| builtin(k).map(|p| preset_json(&p, Some(k)))).collect();
list.extend(s.brushes.user().iter().map(|p| preset_json(p, None)));
Ok(json!({"presets": list, "yours": s.brushes.user().len()}))
}
fn preset_save(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_req(p, "name")?;
let base = match opt_str(p, "from")? {
Some(from) => s.brushes.find(from).ok_or_else(|| EngineError::Param(format!("no brush named '{from}'")))?,
None => BrushPreset::default(),
};
let b = BrushPreset { name: name.to_string(), ..base.with_params(p)? };
let replaced = s.brushes.save(b)?;
let saved = clean_name(name).and_then(|n| s.brushes.position(&n)).and_then(|i| s.brushes.user().get(i)).map(|x| x.name.clone());
Ok(json!({"name": saved, "replaced": replaced, "yours": s.brushes.user().len()}))
}
fn preset_rename(s: &mut Session, p: &Value) -> Result<Value> {
let to = s.brushes.rename(str_req(p, "name")?, str_req(p, "to")?)?;
Ok(json!({"name": to}))
}
fn preset_delete(s: &mut Session, p: &Value) -> Result<Value> {
let gone = s.brushes.delete(str_req(p, "name")?)?;
Ok(json!({"deleted": gone.name, "yours": s.brushes.user().len()}))
}
fn preset_export(s: &mut Session, p: &Value) -> Result<Value> {
let path = std::path::PathBuf::from(str_req(p, "path")?);
let chosen: Vec<BrushPreset> = match p.get("names") {
None | Some(Value::Null) => s.brushes.user().to_vec(),
Some(Value::Array(names)) => names
.iter()
.take(MAX_USER_PRESETS * 2)
.map(|n| {
let n = n.as_str().ok_or_else(|| EngineError::Param("param 'names' must be a list of brush names".into()))?;
s.brushes.find(n).ok_or_else(|| EngineError::Param(format!("no brush named '{n}'")))
})
.collect::<Result<_>>()?,
Some(_) => return Err(EngineError::Param("param 'names' must be a list of brush names".into())),
};
if chosen.is_empty() {
return Err(EngineError::State("there are no brushes of your own to export yet (save one first)".into()));
}
let text = BrushLibrary::file_json(&chosen);
crate::vfs::write(&path, text.as_bytes())?;
Ok(json!({"written": path.display().to_string(), "brushes": chosen.len(), "bytes": text.len()}))
}
fn preset_import(s: &mut Session, p: &Value) -> Result<Value> {
let path = std::path::PathBuf::from(str_req(p, "path")?);
if crate::vfs::len(&path)? > MAX_FILE_BYTES {
return Err(EngineError::Param(format!("{} is too large to be a brush set", path.display())));
}
let found = BrushLibrary::parse_file(&crate::vfs::read_to_string(&path)?)?;
if found.is_empty() {
return Err(EngineError::Param("the brush set has no brushes in it".into()));
}
let mut names = Vec::with_capacity(found.len());
for b in found {
match s.brushes.add_unique(b) {
Ok(n) => names.push(n),
Err(e) if names.is_empty() => return Err(e),
// The library filled up part way: say what came in.
Err(_) => break,
}
}
Ok(json!({"imported": names, "yours": s.brushes.user().len()}))
}
/// Where a preview's stroke runs on a `w` × `h` area: an S across it, the pressure swelling
/// in the middle (so pressure, curves and tapers show).
pub fn preview_points(w: f32, h: f32) -> Vec<[f32; 3]> {
(0..=48)
.map(|i| {
let t = i as f32 / 48.0;
let x = w * (0.1 + 0.8 * t);
let y = h * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin());
[x, y, 0.25 + 0.75 * (t * std::f32::consts::PI).sin()]
})
.collect()
}
/// A brush's stroke preview, drawn by the CPU renderer on a transparent `w` × `h` image (in
/// pixels; `scale` pixels per point): the preview stroke in `color`, the brush's size kept
/// where it fits (between 2 and 40 % of the height). `as_stroke` previews the Paint Brush.
pub fn preview(preset: &BrushPreset, as_stroke: bool, w: u32, h: u32, scale: f32, color: Rgba) -> Result<anicraft_render::Pixmap> {
let scale = if scale.is_finite() { scale.clamp(0.25, 8.0) } else { 1.0 };
let (pw, ph) = (w as f32 / scale, h as f32 / scale);
if !(pw >= 8.0 && ph >= 8.0 && w <= 4096 && h <= 4096) {
return Err(EngineError::Param("a brush preview is 8 to 4096 pixels across".into()));
}
let mut doc = anicraft_doc::Document::default();
doc.stage.width = pw.ceil() as u32;
doc.stage.height = ph.ceil() as u32;
let mut scratch = Session::new(doc);
let mut params = BrushPreset { size: preset.size.clamp(2.0, (ph * 0.4).max(2.0)), ..preset.clone() }.params();
params["points"] = json!(preview_points(pw, ph));
params["color"] = json!(format!("#{:02x}{:02x}{:02x}", (color.r.clamp(0.0, 1.0) * 255.0).round() as u8, (color.g.clamp(0.0, 1.0) * 255.0).round() as u8, (color.b.clamp(0.0, 1.0) * 255.0).round() as u8));
params["object"] = json!(true);
params["as_stroke"] = json!(as_stroke);
scratch.execute("draw.brush", &params)?;
let dl = anicraft_doc::evaluate(&scratch.doc, 0);
let view = anicraft_render::View { transform: Affine::scale(scale, scale), width: w, height: h, background: None };
Ok(anicraft_render::render(&dl, &view)?.0)
}
+110 -28
View File
@@ -1,5 +1,6 @@
//! Camera commands (ADR 0027): add and remove the scene's camera layer, set the camera at a
//! frame (pan, zoom, rotation, tint), read it back, and give layers a depth for parallax.
//! frame (pan, zoom, rotation, colour effect), read it back, give layers a depth (keyable over
//! time) for perspective, and attach layers to the camera (ADR 0027, 0082).
//!
//! `camera.set` edits the camera like any instance: through [`Session::editable_keyframe`], so
//! inside a classic tween it keys the playhead and inside a motion tween it becomes property
@@ -23,18 +24,29 @@ pub fn specs() -> Vec<CommandSpec> {
"Camera",
"",
None,
"{x?, y? (camera centre, stage px), dx?, dy? (pan by), zoom? (%, 5–2000), zoom_by? (factor), rotation? (°), rotate_by? (°), tint? (#rrggbb), tint_amount? (%), reset?: bool, frame?}",
"{x?, y? (camera centre, stage px), dx?, dy? (pan by), zoom? (%, 5–2000), zoom_by? (factor), rotation? (°), rotate_by? (°), reset?: bool, frame?, and the colour effect as element.set_color_effect takes it: style?: none|brightness|tint|advanced, brightness? (%), tint? (#rrggbb), tint_amount? (%), red_multiplier? … blue_offset? (the camera has no opacity: no alpha values)}",
true,
set,
),
c("camera.info", "Camera Info", "", None, "{frame?} → the camera at the frame (x, y, zoom %, rotation °, tint) and its frame on the stage", false, info),
c("layer.set_depth", "Layer Depth", "", None, "{depth (px behind the stage, −500…10000; deeper layers move less when the camera pans), layer?}", true, set_depth),
c(
"layer.set_depth",
"Layer Depth",
"",
None,
"{depth (px behind the stage, −500…10000; through the camera a deeper layer moves and scales less, and draws behind nearer ones), layer?, key?: bool (default: whether the layer's depth is keyed), frame? (default: the playhead)} with `key` sets a depth key at the frame (the first key away from frame 0 also keys frame 0 with the depth it had), so the depth tweens linearly between keys; `key: false` makes the depth one value again (ADR 0082)",
true,
set_depth,
),
c("layer.remove_depth_key", "Remove Depth Key", "", None, "{layer?, frame? (default: the playhead)} removes the layer's depth key at the frame; removing the last one leaves the depth it had there", true, remove_depth_key),
c("layer.set_attached", "Attach Layer to Camera", "", None, "{attached?: bool (default: toggles), layer?} an attached layer stays where it is on screen while the camera moves (titles, HUDs); its depth plays no part (ADR 0082)", true, set_attached),
c("layer.depths", "Layer Depths", "", None, "{frame?} → {camera: bool, layers: [{layer, name, depth, keyed, key_here, attached}]} the layers that can have a depth, nearest first (ties in timeline order), at the frame", false, depths),
]
}
/// The scene's camera layer id.
pub(crate) fn camera_layer(s: &Session) -> Option<LayerId> {
s.doc.timeline(s.scene).camera_layer().map(|l| l.id)
s.timeline().camera_layer().map(|l| l.id)
}
fn no_camera() -> EngineError {
@@ -42,12 +54,16 @@ fn no_camera() -> EngineError {
}
fn add(s: &mut Session, _: &Value) -> Result<Value> {
// A scene has the camera, not a symbol (ADR 0027, 0045).
if !s.editing.is_empty() {
return Err(EngineError::State("the camera belongs to a scene: close the symbol you are editing first (Edit › Edit Document)".into()));
}
if let Some(id) = camera_layer(s) {
s.layer = id;
s.selection.clear();
return Ok(json!({"layer": id.0, "added": false}));
}
if s.doc.timeline(s.scene).layers.len() >= 1000 {
if s.timeline().layers.len() >= 1000 {
return Err(EngineError::State("too many layers (limit 1000)".into()));
}
let id = LayerId(s.doc.alloc_id());
@@ -61,7 +77,7 @@ fn add(s: &mut Session, _: &Value) -> Result<Value> {
let mut k = Keyframe::new(0, frames);
k.elements.push(Arc::new(Camera::rest(&s.doc.stage).to_element(el)));
layer.keyframes = vec![Arc::new(k)];
let tl = s.doc.timeline_mut(s.scene);
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?;
tl.layers.insert(0, Arc::new(layer));
tl.repair_masks();
s.layer = id;
@@ -71,11 +87,11 @@ fn add(s: &mut Session, _: &Value) -> Result<Value> {
fn remove(s: &mut Session, _: &Value) -> Result<Value> {
let id = camera_layer(s).ok_or_else(no_camera)?;
let tl = s.doc.timeline_mut(s.scene);
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?;
tl.layers.retain(|l| l.id != id);
tl.repair_masks();
if s.layer == id {
s.layer = s.doc.timeline(s.scene).layers.first().map_or(LayerId(0), |l| l.id);
s.layer = s.timeline().layers.first().map_or(LayerId(0), |l| l.id);
s.selection.clear();
}
Ok(json!({"removed": id.0}))
@@ -109,8 +125,10 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
let num = |k: &str| opt_f32(p, k);
let (x, y, dx, dy) = (num("x")?, num("y")?, num("dx")?, num("dy")?);
let (zoom, zoom_by, rotation, rotate_by) = (num("zoom")?, num("zoom_by")?, num("rotation")?, num("rotate_by")?);
let tint = opt_color(p, "tint")?;
let tint_amount = num("tint_amount")?;
let effect = crate::cmds_draw::EffectEdit::parse(p)?;
if effect.as_ref().is_some_and(|e| e.touches_alpha()) {
return Err(EngineError::Param("the camera has no opacity: give brightness, tint or advanced colour values (no alpha)".into()));
}
let reset = opt_bool(p, "reset")?.unwrap_or(false);
if let Some(z) = zoom
&& !(MIN_ZOOM * 100.0..=MAX_ZOOM * 100.0).contains(&z)
@@ -120,9 +138,6 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
if zoom_by.is_some_and(|f| f <= 0.0) {
return Err(EngineError::Param("param 'zoom_by' must be above 0".into()));
}
if tint_amount.is_some_and(|a| !(0.0..=100.0).contains(&a)) {
return Err(EngineError::Param("param 'tint_amount' must be between 0 and 100 (%)".into()));
}
let stage = s.doc.stage;
// A camera is created on a keyframe that has none (a blank camera keyframe is at rest).
// (Its id is taken only when it is used, so a no-op leaves the document unchanged.)
@@ -153,17 +168,14 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
c.rotation = r.to_radians();
}
c.rotation += rotate_by.unwrap_or(0.0).to_radians();
if let Some(t) = tint {
c.tint = t.with_alpha(1.0);
}
if let Some(a) = tint_amount {
c.tint_amount = a / 100.0;
if let Some(e) = &effect {
c.color = camera::camera_effect(&e.apply(&c.color));
}
// Keep the centre on a sane plane (a long drag can't fling it to infinity).
let lim = 1_000_000.0;
c.center = Vec2::new(c.center.x.clamp(-lim, lim), c.center.y.clamp(-lim, lim));
el.transform = c.transform();
el.color = c.color();
el.color = c.to_element(el.id).color;
Ok(c)
})();
s.layer = layer;
@@ -179,7 +191,7 @@ fn camera_json(c: &Camera, stage: &anicraft_doc::Stage) -> Value {
let f = c.frame(stage);
json!({
"x": c.center.x, "y": c.center.y, "zoom": c.zoom * 100.0, "rotation": c.rotation.to_degrees(),
"tint": c.tint.to_hex(), "tint_amount": c.tint_amount * 100.0,
"color_effect": crate::color_effect_json(&c.color),
"frame": f.iter().map(|p| json!([p.x, p.y])).collect::<Vec<_>>(),
})
}
@@ -187,25 +199,95 @@ fn camera_json(c: &Camera, stage: &anicraft_doc::Stage) -> Value {
fn info(s: &mut Session, p: &Value) -> Result<Value> {
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
let Some(id) = camera_layer(s) else { return Ok(json!({"camera": false})) };
let tl = s.doc.timeline(s.scene);
let tl = s.timeline();
let on = tl.camera_layer().is_some_and(|l| l.visible);
let mut v = s.doc.timeline(s.scene).camera_state_at(frame, &s.doc.stage).map_or_else(|| json!({}), |c| camera_json(&c, &s.doc.stage));
let mut v = s.timeline().camera_state_at(frame, &s.doc.stage).map_or_else(|| json!({}), |c| camera_json(&c, &s.doc.stage));
v["camera"] = json!(true);
v["layer"] = json!(id.0);
v["on"] = json!(on);
Ok(v)
}
/// The layer a depth or attachment command acts on: a scene's layer with artwork.
fn depth_layer<'a>(s: &'a mut Session, p: &Value) -> Result<&'a mut Layer> {
// Depth belongs to a scene's own layers; artwork inside a symbol moves with its instance.
if !s.editing.is_empty() {
return Err(EngineError::State("layer depth belongs to a scene's layers: close the symbol you are editing first (Edit › Edit Document)".into()));
}
let lid = opt_u64(p, "layer")?.map(LayerId);
let layer = s.layer_mut(lid)?;
if !has_depth_kind(layer.kind) {
return Err(EngineError::State(format!("'{}' has no depth of its own (only layers with artwork do)", layer.name)));
}
Ok(layer)
}
/// Whether a layer of this kind has a depth (and can be attached to the camera).
fn has_depth_kind(kind: LayerKind) -> bool {
!matches!(kind, LayerKind::Camera | LayerKind::Folder | LayerKind::Guide)
}
fn set_depth(s: &mut Session, p: &Value) -> Result<Value> {
let depth = f32_req(p, "depth")?;
if !(camera::MIN_DEPTH..=camera::MAX_DEPTH).contains(&depth) {
return Err(EngineError::Param(format!("param 'depth' must be between {} and {}", camera::MIN_DEPTH, camera::MAX_DEPTH)));
}
let lid = opt_u64(p, "layer")?.map(LayerId);
let layer = s.layer_mut(lid)?;
if matches!(layer.kind, LayerKind::Camera | LayerKind::Folder) {
return Err(EngineError::State(format!("'{}' has no depth of its own (only layers with artwork do)", layer.name)));
let key = opt_bool(p, "key")?;
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}")));
}
layer.depth = depth;
Ok(json!({"layer": layer.id.0, "depth": depth}))
let layer = depth_layer(s, p)?;
let keyed = key.unwrap_or(!layer.depth_keys.is_empty());
if keyed {
if layer.depth_keys.len() >= camera::MAX_DEPTH_KEYS && layer.depth_keys.binary_search_by_key(&frame, |k| k.frame).is_err() {
return Err(EngineError::State(format!("a layer keeps at most {} depth keys", camera::MAX_DEPTH_KEYS)));
}
// The first key: what came before keeps the depth the layer had.
if layer.depth_keys.is_empty() && frame > 0 && layer.depth != depth {
let was = layer.depth;
layer.set_depth_key(0, was);
}
layer.set_depth_key(frame, depth);
layer.depth = 0.0;
} else {
layer.depth_keys.clear();
layer.depth = depth;
}
Ok(json!({"layer": layer.id.0, "depth": depth, "keyed": keyed, "keys": layer.depth_keys.len()}))
}
fn remove_depth_key(s: &mut Session, p: &Value) -> Result<Value> {
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
let layer = depth_layer(s, p)?;
let i = layer.depth_keys.binary_search_by_key(&frame, |k| k.frame).map_err(|_| EngineError::State(format!("'{}' has no depth key on frame {}", layer.name, frame.saturating_add(1))))?;
let here = layer.depth_at(frame);
layer.depth_keys.remove(i);
if layer.depth_keys.is_empty() {
layer.depth = here;
}
Ok(json!({"layer": layer.id.0, "keys": layer.depth_keys.len(), "depth": layer.depth_at(frame)}))
}
fn set_attached(s: &mut Session, p: &Value) -> Result<Value> {
let on = opt_bool(p, "attached")?;
let layer = depth_layer(s, p)?;
layer.attached = on.unwrap_or(!layer.attached);
Ok(json!({"layer": layer.id.0, "attached": layer.attached}))
}
fn depths(s: &mut Session, p: &Value) -> Result<Value> {
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
let tl = s.doc.timeline(s.scene);
let mut rows: Vec<(usize, &Layer)> = tl.layers.iter().enumerate().filter(|(_, l)| has_depth_kind(l.kind)).map(|(i, l)| (i, &**l)).collect();
// Nearest first; ties in timeline order (top first).
rows.sort_by(|a, b| a.1.depth_at(frame).total_cmp(&b.1.depth_at(frame)).then(a.0.cmp(&b.0)));
let layers: Vec<Value> = rows
.iter()
.map(|(_, l)| {
let key_here = l.depth_keys.iter().any(|k| k.frame == frame);
json!({"layer": l.id.0, "name": l.name, "depth": l.depth_at(frame), "keyed": !l.depth_keys.is_empty(), "key_here": key_here, "attached": l.attached})
})
.collect();
Ok(json!({"camera": tl.camera_layer().is_some(), "layers": layers}))
}
Loaded 100 of 527 files, more files were not shown because too many files have changed in this diff. Show more