diff --git a/.gitattributes b/.gitattributes index 80c58656..46a94cd2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -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 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..daeab9e7 --- /dev/null +++ b/.github/dependabot.yml @@ -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)" diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 32b4a1ea..30a60ea3 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -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 diff --git a/.github/workflows/platforms.yml b/.github/workflows/platforms.yml new file mode 100644 index 00000000..6af14859 --- /dev/null +++ b/.github/workflows/platforms.yml @@ -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" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d99e4a98..304f6cbd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 }} diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml index 4c02bdcd..5dd670bd 100644 --- a/.github/workflows/web.yml +++ b/.github/workflows/web.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 2132c555..061934eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 0ee9d2b8..71ed329e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -19,15 +19,18 @@ shaders or SDK code). | Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) | | Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | | 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 | | 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) | (`icons/.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) | (`icons/.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), , 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* (, 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* (, 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* (, 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`), , 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, (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*, ; 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, (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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 19338ff8..c24cdf20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ` 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 + ` (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 ` 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 ``). 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 diff --git a/Cargo.lock b/Cargo.lock index 02888be6..cc4b72fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,6 +134,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "aligned-vec" version = "0.6.4" @@ -143,6 +152,21 @@ dependencies = [ "equator", ] +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -207,17 +231,20 @@ dependencies = [ [[package]] name = "anicraft" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-audio", "anicraft-doc", "anicraft-engine", "anicraft-geom", "anicraft-gpu", + "anicraft-guide", "anicraft-render", "cpal", + "craft-update", "eframe", "egui", + "fmv-macos-events", "fontdb", "js-sys", "rfd", @@ -226,14 +253,16 @@ dependencies = [ "sys-locale", "wasm-bindgen", "wasm-bindgen-futures", + "wat", "web-sys", "web-time", + "winreg", "winresource", ] [[package]] name = "anicraft-actions" -version = "0.1.0" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -241,39 +270,40 @@ dependencies = [ [[package]] name = "anicraft-audio" -version = "0.1.0" +version = "0.3.0" dependencies = [ - "lewton", - "nanomp3", + "craft-audio", ] [[package]] name = "anicraft-cli" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-engine", "anicraft-geom", + "anicraft-guide", "anicraft-render", "serde_json", + "wat", ] [[package]] name = "anicraft-doc" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-actions", "anicraft-audio", "anicraft-geom", - "png 0.17.16", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "craft-mime", "serde", "serde_json", - "zune-jpeg", ] [[package]] name = "anicraft-engine" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -282,9 +312,14 @@ dependencies = [ "anicraft-svg", "anicraft-text", "anicraft-xfl", - "gif", - "png 0.17.16", + "craft-anicraft-format", + "craft-gif", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "craft-webp", + "miniz_oxide 0.8.9", "rayon", + "regex", "serde", "serde_json", "thiserror 2.0.21", @@ -295,7 +330,7 @@ dependencies = [ [[package]] name = "anicraft-geom" -version = "0.1.0" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -303,12 +338,13 @@ dependencies = [ [[package]] name = "anicraft-gpu" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", "anicraft-render", "bytemuck", + "naga", "pollster 1.0.1", "rayon", "thiserror 2.0.21", @@ -316,9 +352,18 @@ dependencies = [ "wgpu", ] +[[package]] +name = "anicraft-guide" +version = "0.3.0" +dependencies = [ + "craft-html", + "pulldown-cmark", + "serde_json", +] + [[package]] name = "anicraft-plugins" -version = "0.1.0" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -329,12 +374,14 @@ dependencies = [ [[package]] name = "anicraft-render" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", "boa_engine", - "png 0.17.16", + "craft-html", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "craft-lottie", "rayon", "serde_json", "thiserror 2.0.21", @@ -342,7 +389,7 @@ dependencies = [ [[package]] name = "anicraft-svg" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", @@ -353,7 +400,7 @@ dependencies = [ [[package]] name = "anicraft-text" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-geom", "fontdb", @@ -363,21 +410,24 @@ dependencies = [ [[package]] name = "anicraft-xfl" -version = "0.1.0" +version = "0.3.0" dependencies = [ "anicraft-doc", "anicraft-geom", "anicraft-text", "anicraft-xml", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "craft-xfl", "miniz_oxide 0.8.9", - "png 0.17.16", "thiserror 2.0.21", ] [[package]] name = "anicraft-xml" -version = "0.1.0" +version = "0.3.0" dependencies = [ + "craft-xfl", + "craft-xml", "thiserror 2.0.21", ] @@ -602,6 +652,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.10.0" @@ -617,6 +673,12 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -629,6 +691,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -799,6 +870,16 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "brotli-decompressor" +version = "6.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -825,12 +906,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - [[package]] name = "byteorder-lite" version = "0.1.0" @@ -932,6 +1007,15 @@ dependencies = [ "libc", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "num-traits", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -986,6 +1070,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -996,6 +1089,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -1009,7 +1112,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -1022,10 +1125,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "core_maths" version = "0.1.1" @@ -1065,6 +1174,8 @@ dependencies = [ "block2 0.6.2", "coreaudio-rs", "dasp_sample", + "futures-channel", + "futures-util", "jni", "js-sys", "libc", @@ -1080,11 +1191,257 @@ dependencies = [ "objc2-core-audio-types", "objc2-core-foundation", "objc2-foundation 0.3.2", + "wasm-bindgen", + "wasm-bindgen-futures", "web-sys", "windows", "windows-core", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "craft-anicraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "craft-audio" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "craft-media", + "log", + "symphonia", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" + +[[package]] +name = "craft-gif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "gif", +] + +[[package]] +name = "craft-html" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" + +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b#55b1d7f3c598b600a130ae63f4a40334a230ae7b" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "exr", + "flate2", + "half", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b#55b1d7f3c598b600a130ae63f4a40334a230ae7b" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-lottie" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b421e6777343cba6c017295e318624e419b95323#b421e6777343cba6c017295e318624e419b95323" +dependencies = [ + "craft-zip", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b#55b1d7f3c598b600a130ae63f4a40334a230ae7b" +dependencies = [ + "brotli-decompressor", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b)", + "quick-xml 0.41.0", + "serde", +] + +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "brotli-decompressor", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)", + "quick-xml 0.41.0", + "serde", +] + +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "chrono", + "craft-codepage", + "encoding_rs", +] + +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=55b1d7f3c598b600a130ae63f4a40334a230ae7b#55b1d7f3c598b600a130ae63f4a40334a230ae7b" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-update" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a#6ac2a6a34ae83fc0f0bfb25a569ba6388b72266a" +dependencies = [ + "chrono", + "dunce", + "flate2", + "getrandom 0.3.4", + "log", + "plist", + "rustix 1.1.5", + "semver", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "ureq", + "verifysign", + "winreg", + "winsafe", + "zip", +] + +[[package]] +name = "craft-webp" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0c144b7d983899d4b5b281046dd03a8b1ab35fbb#0c144b7d983899d4b5b281046dd03a8b1ab35fbb" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xfl" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11#b67b9f90c50091a3090f93fa054c34e409edba11" +dependencies = [ + "craft-xml", + "miniz_oxide 0.8.9", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11#b67b9f90c50091a3090f93fa054c34e409edba11" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b421e6777343cba6c017295e318624e419b95323#b421e6777343cba6c017295e318624e419b95323" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -1125,6 +1482,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1157,6 +1524,16 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1216,6 +1593,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dynify" version = "0.1.2" @@ -1340,6 +1723,7 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", + "webbrowser", "winit", ] @@ -1372,6 +1756,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -1501,6 +1899,28 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "extended" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" + [[package]] name = "fast-float2" version = "0.2.4" @@ -1534,6 +1954,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -1557,6 +1987,17 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "fmv-macos-events" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55" +dependencies = [ + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "foldhash" version = "0.1.5" @@ -1618,6 +2059,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -1695,6 +2145,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1705,6 +2165,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1724,8 +2195,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", + "wasm-bindgen", ] [[package]] @@ -1925,6 +2398,15 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hayro-jpeg2000" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd", +] + [[package]] name = "hermit-abi" version = "0.5.3" @@ -1937,6 +2419,22 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "icu_collections" version = "2.0.0" @@ -2026,6 +2524,27 @@ dependencies = [ "zerovec", ] +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "image" version = "0.25.10" @@ -2034,10 +2553,25 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "gif", "moxcms", "num-traits", - "png 0.18.1", + "png", + "qoi", "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", ] [[package]] @@ -2151,6 +2685,12 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-encoder" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" + [[package]] name = "js-sys" version = "0.3.106" @@ -2191,6 +2731,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "leb128fmt" version = "0.1.0" @@ -2198,15 +2744,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] -name = "lewton" -version = "0.10.2" +name = "lebe" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "777b48df9aaab155475a83a7df3070395ea1ac6902f5cd062b8f2b028075c030" -dependencies = [ - "byteorder", - "ogg", - "tinyvec", -] +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" [[package]] name = "libc" @@ -2357,6 +2898,34 @@ dependencies = [ "pxfm", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" @@ -2395,21 +2964,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "nanomp3" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acd9a8d0592a17ee5211aae2f976e6dc2f6846135d1f49665b3f19a7afd23435" -dependencies = [ - "nanomp3-core", -] - -[[package]] -name = "nanomp3-core" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63fa2238e662d3d3c1a71168b3278f23422cf9bf76f6943ee6b1c2581d74eb5c" - [[package]] name = "ndk" version = "0.9.0" @@ -2440,6 +2994,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2466,6 +3032,15 @@ dependencies = [ "serde", ] +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2896,15 +3471,6 @@ dependencies = [ "objc2-foundation 0.2.2", ] -[[package]] -name = "ogg" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6951b4e8bf21c8193da321bcce9c9dd2e13c858fe078bf9054a288b419ae5d6e" -dependencies = [ - "byteorder", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -2917,6 +3483,12 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "orbclient" version = "0.3.55" @@ -3093,16 +3665,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] -name = "png" -version = "0.17.16" +name = "plist" +version = "1.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", + "base64", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", ] [[package]] @@ -3222,12 +3794,39 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +[[package]] +name = "pulldown-cmark" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" +dependencies = [ + "bitflags 2.13.2", + "memchr", + "pulldown-cmark-escape", + "unicase", +] + +[[package]] +name = "pulldown-cmark-escape" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" + [[package]] name = "pxfm" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "quick-error" version = "2.0.1" @@ -3243,6 +3842,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -3375,6 +3983,41 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "regress" version = "0.10.5" @@ -3418,6 +4061,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -3465,6 +4122,80 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3486,6 +4217,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -3498,6 +4238,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3509,6 +4272,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "serde" @@ -3573,6 +4340,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3766,6 +4544,209 @@ dependencies = [ "serde", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symphonia" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7edef6a96b696d4e0cab5ee9ebb7ca155ed95f30a6b45bbb8b97d2727f02424" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac", + "symphonia-bundle-mp3", + "symphonia-codec-aac", + "symphonia-codec-adpcm", + "symphonia-codec-alac", + "symphonia-codec-pcm", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-caf", + "symphonia-format-isomp4", + "symphonia-format-mkv", + "symphonia-format-ogg", + "symphonia-format-riff", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-flac" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6405d5c34ff6f8f7ca08a4101efe66d21e180f7322ef9359900a0e55698a7892" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98ea5ffc8716bff677dfb3b01b420c7b758de901a72b8c330bf2040ab74b4add" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-aac" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5bf8e39552d34a3c4c98333370e62f48c92456d2e814f273b5c3ad7c4a5f45c" +dependencies = [ + "lazy_static", + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-adpcm" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "445932ecb0c59362fde9c082dd63a75380650c5077fdb8b80b8cac850442a74c" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-alac" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920a78f96f3cf62932d0c497959c0cc2100ef36b03c7ca1417b260f432a482d8" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e04ba75686acbe43542fdd374571195f0530c0b7785ca25cc6840e9c6c4b6eea" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73d90b4fcf796137cc683c538282804ff9629f8ad9dbfd881fcbba331ac4e986" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-common" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acc3fcc18ec9b8cdd48614e259c4cf0d27b71d41e5d9b120b42c5adab12d7c4" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-core" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c412864d599d4750d0c3d684d7e093ec05e5309681ef5252cc1096a437f6e0" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "lazy_static", + "log", + "num-complex", + "smallvec", +] + +[[package]] +name = "symphonia-format-caf" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab64327ee1920531c5bf86cf7e9cd1a599d57013ddc30691da62683cefc65191" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-format-isomp4" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e681a70e1870d34e02abf1dbc51e4267c3f1827801474e8870be8c689fc4dc3" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-format-mkv" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d015c5c0558864665894b3f4cbd95e10abb01b9c868e751c72670f326a56360e" +dependencies = [ + "lazy_static", + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5495e7f7e3c7035328d82b6d6e377eef289bb0c4105bdeb557fc93a833f994" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ff70929083a8c1a5f6cd7c904b6071c7914ad04739b510c2f7239dfc9b7dabe" +dependencies = [ + "extended", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-metadata" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83713a97705d77bdef7cdbc0768fd6e5a54e4cd7e48d60a806ae85639e2c87c6" +dependencies = [ + "lazy_static", + "log", + "regex-lite", + "smallvec", + "symphonia-core", +] + [[package]] name = "syn" version = "2.0.119" @@ -3834,6 +4815,22 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -4075,6 +5072,18 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -4086,6 +5095,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + [[package]] name = "unicode-general-category" version = "1.1.0" @@ -4110,6 +5125,53 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + [[package]] name = "utf16_iter" version = "1.1.0" @@ -4119,6 +5181,21 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + [[package]] name = "utf_types" version = "1.0.0" @@ -4163,6 +5240,16 @@ dependencies = [ "vello_common", ] +[[package]] +name = "verifysign" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6efd25aadc22c756a9012267fae0b130278d335d6ceb512ec02ce82029b5ca9" +dependencies = [ + "core-foundation 0.10.1", + "windows-sys 0.61.2", +] + [[package]] name = "version_check" version = "0.9.5" @@ -4179,6 +5266,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -4495,7 +5588,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml", + "quick-xml 0.41.0", "quote", ] @@ -4531,6 +5624,31 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4945,7 +6063,7 @@ dependencies = [ "calloop 0.13.0", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -4990,6 +6108,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + [[package]] name = "winresource" version = "0.1.34" @@ -5000,6 +6128,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "winsafe" +version = "0.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -5251,6 +6385,26 @@ dependencies = [ "synstructure 0.14.0", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerotrie" version = "0.2.5" @@ -5286,6 +6440,25 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zip" +version = "9.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -5304,6 +6477,15 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.5.15" @@ -5313,6 +6495,15 @@ dependencies = [ "zune-core", ] +[[package]] +name = "zune-jpegxl" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4" +dependencies = [ + "zune-core", +] + [[package]] name = "zvariant" version = "5.15.1" diff --git a/Cargo.toml b/Cargo.toml index 15bb9237..6b256d28 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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. diff --git a/README.md b/README.md index 1770b5e9..eb6390d7 100644 --- a/README.md +++ b/README.md @@ -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--linux-riscv64.tar.gz`, a tarball only. | Build | File | Notes | |---|---|---| -| Static site | `anicraft-web-.zip` | Runs in a modern browser; host it on any static server | +| Static site | `anicraft-web-.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 diff --git a/assets/icons/anicraft-bind.svg b/assets/icons/anicraft-bind.svg new file mode 100644 index 00000000..c7842936 --- /dev/null +++ b/assets/icons/anicraft-bind.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/anicraft-clip-stage.svg b/assets/icons/anicraft-clip-stage.svg new file mode 100644 index 00000000..fe7070f0 --- /dev/null +++ b/assets/icons/anicraft-clip-stage.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/assets/icons/anicraft-gradient-transform.svg b/assets/icons/anicraft-gradient-transform.svg new file mode 100644 index 00000000..907d4395 --- /dev/null +++ b/assets/icons/anicraft-gradient-transform.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/anicraft-insert-blank-keyframe.svg b/assets/icons/anicraft-insert-blank-keyframe.svg new file mode 100644 index 00000000..8310bdd3 --- /dev/null +++ b/assets/icons/anicraft-insert-blank-keyframe.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-insert-frame.svg b/assets/icons/anicraft-insert-frame.svg new file mode 100644 index 00000000..cdb94a6c --- /dev/null +++ b/assets/icons/anicraft-insert-frame.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-insert-keyframe.svg b/assets/icons/anicraft-insert-keyframe.svg new file mode 100644 index 00000000..f7bf3e4c --- /dev/null +++ b/assets/icons/anicraft-insert-keyframe.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-layer.svg b/assets/icons/anicraft-layer.svg new file mode 100644 index 00000000..6a8eda2f --- /dev/null +++ b/assets/icons/anicraft-layer.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-paint-brush.svg b/assets/icons/anicraft-paint-brush.svg new file mode 100644 index 00000000..0a82f625 --- /dev/null +++ b/assets/icons/anicraft-paint-brush.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/anicraft-panel-actions.svg b/assets/icons/anicraft-panel-actions.svg new file mode 100644 index 00000000..32535104 --- /dev/null +++ b/assets/icons/anicraft-panel-actions.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-panel-explorer.svg b/assets/icons/anicraft-panel-explorer.svg new file mode 100644 index 00000000..f88ab935 --- /dev/null +++ b/assets/icons/anicraft-panel-explorer.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/icons/anicraft-panel-history.svg b/assets/icons/anicraft-panel-history.svg new file mode 100644 index 00000000..fc724601 --- /dev/null +++ b/assets/icons/anicraft-panel-history.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-panel-library.svg b/assets/icons/anicraft-panel-library.svg new file mode 100644 index 00000000..00e89929 --- /dev/null +++ b/assets/icons/anicraft-panel-library.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-panel-output.svg b/assets/icons/anicraft-panel-output.svg new file mode 100644 index 00000000..d6a74563 --- /dev/null +++ b/assets/icons/anicraft-panel-output.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/anicraft-panel-properties.svg b/assets/icons/anicraft-panel-properties.svg new file mode 100644 index 00000000..0d6bc1a0 --- /dev/null +++ b/assets/icons/anicraft-panel-properties.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/assets/icons/anicraft-panel-swatches.svg b/assets/icons/anicraft-panel-swatches.svg new file mode 100644 index 00000000..a2211116 --- /dev/null +++ b/assets/icons/anicraft-panel-swatches.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/anicraft-warp.svg b/assets/icons/anicraft-warp.svg new file mode 100644 index 00000000..a9fe693a --- /dev/null +++ b/assets/icons/anicraft-warp.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/icons/copy.svg b/assets/icons/copy.svg new file mode 100644 index 00000000..f62ce99c --- /dev/null +++ b/assets/icons/copy.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/ellipsis.svg b/assets/icons/ellipsis.svg new file mode 100644 index 00000000..68456c39 --- /dev/null +++ b/assets/icons/ellipsis.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/assets/icons/plus.svg b/assets/icons/plus.svg new file mode 100644 index 00000000..41f92bb9 --- /dev/null +++ b/assets/icons/plus.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/trash.svg b/assets/icons/trash.svg new file mode 100644 index 00000000..e8cb0edf --- /dev/null +++ b/assets/icons/trash.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/build.rs b/build.rs index fbd5c89c..9b4047af 100644 --- a/build.rs +++ b/build.rs @@ -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}"); } } diff --git a/crates/actions/src/as3/ir.rs b/crates/actions/src/as3/ir.rs new file mode 100644 index 00000000..ec3f1978 --- /dev/null +++ b/crates/actions/src/as3/ir.rs @@ -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 { + 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), +} + +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(&self, s: S) -> Result { + 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: D) -> Result { + 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) -> 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 }, + Bin { op: BinOp, a: Box, b: Box }, + /// `a && b`, `a || b` (the operand's value, as ECMAScript gives it). + And { a: Box, b: Box }, + Or { a: Box, b: Box }, + Cond { c: Box, a: Box, b: Box }, + Math { f: MathFn, args: Vec }, + /// A call to a function of the timeline, by name. + Call { f: String, args: Vec }, + /// 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, v: Box }, + /// `++` / `--` (`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 }, +} + +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 { + 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) -> 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 { + 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, b: Vec }, + /// `while (c)`, `for (; c; next)` (`first`: the condition is tested before the body) and + /// `do … while (c)`. + Loop { + c: Option, + body: Vec, + next: Option, + first: bool, + }, + Break, + Continue, + Return { v: Option }, + /// A timeline method on an instance; `args` are the frame and the scene, when it takes them. + Act { at: Place, m: Method, args: Vec }, + Trace { args: Vec }, + /// `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, + /// 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, + pub locals: Vec, + /// `None`: `void`, or no result. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ret: Option, + pub body: Vec, + /// Functions written in place inside it (listeners). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub inner: Vec>, +} + +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 { + 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::().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, + }) +} diff --git a/crates/actions/src/as3/lower.rs b/crates/actions/src/as3/lower.rs index 6597f57a..385b682c 100644 --- a/crates/actions/src/as3/lower.rs +++ b/crates/actions/src/as3/lower.rs @@ -1,116 +1,71 @@ -//! Lowering: the syntax tree to the action IR. It accepts only what it can say exactly in the -//! IR and reports everything else where it is, so a script either runs whole or not at all. +//! Lowering: the syntax tree to the script IR ([`super::ir`]). It accepts what the IR can say +//! exactly and reports everything else where it is, so a script either compiles whole or +//! doesn't run at all. Names resolve here: a function's own variables become numbered slots, +//! the timeline's variables and functions are named (those another frame declares are listed +//! as [`Free`] names, which the timeline must have for the script to run), and instances become +//! name paths from a base. -use super::parse::{E, Expr, Func, S, Stmt}; -use super::{Compiled, Listener, MAX_INLINE_DEPTH, MAX_LISTENERS, MAX_PROBLEMS, Pos, Problem, ScriptOp}; -use crate::{Action, ButtonEvent, FrameRef, MAX_ACTIONS, MAX_FRAME, MAX_LABEL_CHARS, MAX_TRACE_CHARS, Property, Target, valid_instance_name}; -use std::collections::BTreeMap; +use super::ir::{self, Base, BinOp, Expr as X, FuncRef, Function, LValue, ListenEvent, MathFn, Method, Param as IrParam, Place, Prop, S as IS, Stmt as IStmt, Ty, UnOp, Value}; +use super::parse::{E, Expr, Func, S, Stmt, VarDecl}; +use super::{Compiled, Free, MAX_LISTENERS, MAX_PROBLEMS, Pos, Problem}; +use crate::{MAX_FRAME, MAX_LABEL_CHARS, Target, valid_instance_name}; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; -/// The timeline methods a script may call (on this timeline or on a named instance). -const METHODS: [&str; 8] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene"]; /// Names a script's own function can't take: they would hide the timeline's methods. -const BUILTINS: [&str; 11] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene", "trace", "addEventListener", "removeEventListener"]; +const BUILTINS: [&str; 12] = ["stop", "play", "gotoAndPlay", "gotoAndStop", "nextFrame", "prevFrame", "nextScene", "prevScene", "trace", "addEventListener", "removeEventListener", "getChildByName"]; /// Calls that would reach outside the movie: ignored, and noted. const OUTSIDE: [&str; 4] = ["navigateToURL", "sendToURL", "fscommand", "fsCommand"]; /// Type casts that leave an instance path as it is (`MovieClip(parent)`). const CASTS: [&str; 7] = ["MovieClip", "Object", "Sprite", "DisplayObject", "DisplayObjectContainer", "InteractiveObject", "SimpleButton"]; +/// Names that are classes, not values. +const CLASSES: [&str; 6] = ["Math", "Keyboard", "MouseEvent", "Event", "KeyboardEvent", "ExternalInterface"]; +/// Names that are always the path words. +const PATH_WORDS: [&str; 3] = ["root", "parent", "stage"]; -/// A constant value, as ActionScript computes it. -#[derive(Clone, Debug, PartialEq)] -enum Val { - Num(f64), - Str(String), - Bool(bool), - Null, - Undefined, -} - -impl Val { - fn number(&self) -> f64 { - match self { - Val::Num(n) => *n, - Val::Bool(b) => f64::from(u8::from(*b)), - Val::Null => 0.0, - Val::Undefined => f64::NAN, - Val::Str(s) => { - // ECMA-262 §9.3.1: a decimal number with optional sign and exponent (Rust would - // also read "inf" and "nan"). - let t = s.trim(); - match t.trim_start_matches(['+', '-']) { - "" if t.is_empty() => 0.0, - "Infinity" => if t.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY }, - u if u.chars().all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-')) => t.parse().unwrap_or(f64::NAN), - _ => f64::NAN, - } - } - } - } - - fn text(&self) -> String { - match self { - Val::Num(n) => number_text(*n), - Val::Str(s) => s.clone(), - Val::Bool(b) => b.to_string(), - Val::Null => "null".into(), - Val::Undefined => "undefined".into(), - } +/// A type annotation as a script variable's type, or why it can't be one. `…Event` types are +/// events (`Ok(None)`). +fn var_type(ty: &Option<(String, Pos)>) -> Result, (Pos, String)> { + match ty { + None => Ok(Some(Ty::Any)), + Some((t, _)) if t.ends_with("Event") => Ok(None), + Some((t, p)) => Ty::from_name(t).map(Some).ok_or_else(|| (*p, format!("variables of type `{t}` aren't supported yet (Number, int, uint, Boolean, String and untyped ones are)"))), } } -/// A number as ActionScript writes it (`Number.toString()`, ECMA-262 §9.8.1): integers without -/// a point, exponents outside 1e-6 … 1e21. -pub(super) 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, - } -} - -/// Where lowering is. -#[derive(Clone, Default)] -struct Cx { - /// Inside a listener's function: its event parameter and the instance it listens on (what - /// `e.currentTarget` is). - event: Option<(String, Vec)>, - /// Inside a listener (or a function it calls): listeners can't be added there yet. - in_listener: bool, - /// Inside a function body (functions can't be declared there). +/// What lowering a function's (or the script's top level's) code knows. +struct Unit { + /// The function's own variables: slot and type. + locals: BTreeMap, + types: Vec, + /// Its parameters that are the event. + events: BTreeSet, in_function: bool, - /// The parameters of the function being lowered (they can't be read). - params: Vec, - /// The script's functions being lowered, innermost last (to refuse recursion). - stack: Vec, + /// Loops it is inside (for `break` and `continue`). + loops: usize, + /// Functions written in place inside it. + inner: Vec>, +} + +impl Unit { + fn top() -> Unit { + Unit { locals: BTreeMap::new(), types: Vec::new(), events: BTreeSet::new(), in_function: false, loops: 0, inner: Vec::new() } + } } struct Lower<'a> { funcs: BTreeMap<&'a str, &'a Func>, + /// The script's top-level variables (the timeline's). + vars: BTreeMap, problems: Vec, notes: Vec, + free: Vec, listeners: usize, - /// Statements lowered so far, counting each inlined copy (calls can fan out). - work: usize, + /// Functions being lowered (inline listeners nest). + depth: usize, } -/// Most statements lowered for one script, inlined copies included. -const MAX_WORK: usize = 100_000; - -/// Whether the statement list ended in a `return`. -type Returned = bool; +type O = Option; impl<'a> Lower<'a> { fn problem(&mut self, pos: Pos, msg: impl Into) { @@ -125,444 +80,908 @@ impl<'a> Lower<'a> { } } - fn stmts(&mut self, list: &'a [Stmt], cx: &Cx, out: &mut Vec) -> Returned { - for s in list { - if self.stmt(s, cx, out) { - return true; - } + fn free(&mut self, name: &str, pos: Pos, call: bool) { + if !self.free.iter().any(|f| f.name == name && f.call == call) && self.free.len() < 1024 { + self.free.push(Free { name: name.to_string(), line: pos.line, column: pos.column, call }); } - false } - fn stmt(&mut self, s: &'a Stmt, cx: &Cx, out: &mut Vec) -> Returned { - self.work += 1; - if self.work > MAX_WORK { - if self.work == MAX_WORK + 1 { - self.problem(s.pos, format!("the script's functions call each other into more than {MAX_WORK} statements")); - } - return true; + // ----- statements ---------------------------------------------------------------------- + + fn stmts(&mut self, list: &'a [Stmt], u: &mut Unit, out: &mut Vec) { + for s in list { + self.stmt(s, u, out); } + } + + fn body(&mut self, list: &'a [Stmt], u: &mut Unit) -> Vec { + let mut out = Vec::new(); + self.stmts(list, u, &mut out); + out + } + + fn stmt(&mut self, s: &'a Stmt, u: &mut Unit, out: &mut Vec) { + let l = s.pos.line; + let push = |out: &mut Vec, s: IS| out.push(IStmt { l, s }); match &s.kind { S::Empty | S::Import => {} // Declared functions run where they are called or listened for. S::Function(_) => { - if cx.in_function { + if u.in_function { self.problem(s.pos, "functions declared inside functions aren't supported yet"); } } - S::Block(b) => return self.stmts(b, cx, out), - S::Var(w) => self.problem(s.pos, format!("variables (`{w}`) aren't supported yet")), - S::If(..) => self.problem(s.pos, "`if` statements aren't supported yet"), + S::Block(b) => self.stmts(b, u, out), + S::Var(_, list) => self.var_stmt(list, u, out, l), + S::If(c, a, b) => { + let Some(c) = self.expr(c, u) else { return }; + let a = self.body(a, u); + let b = self.body(b, u); + push(out, IS::If { c, a, b }); + } + S::For(init, c, next, body) => { + if let Some(init) = init { + self.stmt(init, u, out); + } + let c = c.as_ref().and_then(|c| self.expr(c, u)); + let next = next.as_ref().and_then(|n| self.expr(n, u)); + u.loops += 1; + let body = self.body(body, u); + u.loops -= 1; + push(out, IS::Loop { c, body, next, first: true }); + } + S::While(c, body) | S::DoWhile(body, c) => { + let first = matches!(s.kind, S::While(..)); + let c = self.expr(c, u); + u.loops += 1; + let body = self.body(body, u); + u.loops -= 1; + push(out, IS::Loop { c, body, next: None, first }); + } + S::Break | S::Continue => { + if u.loops == 0 { + let w = if matches!(s.kind, S::Break) { "break" } else { "continue" }; + return self.problem(s.pos, format!("`{w}` is only for loops here")); + } + push(out, if matches!(s.kind, S::Break) { IS::Break } else { IS::Continue }); + } S::Other(w, _) => { let what = match *w { - "for" | "while" | "do" => format!("`{w}` loops aren't supported yet"), + "for each" | "for in" => format!("`{w}` loops aren't supported yet (`for`, `while` and `do` are)"), + "labelled break" => "labels on `break` and `continue` aren't supported".to_string(), _ => format!("`{w}` statements aren't supported yet"), }; self.problem(s.pos, what); } - S::Return(None) => return true, - S::Return(Some(e)) => { - if self.constant(e, cx).is_err() { - self.problem(e.pos, "returning a value isn't supported"); - } - return true; + S::Return(e) => { + let v = match e { + Some(e) => match self.expr(e, u) { + Some(v) => Some(v), + None => return, + }, + None => None, + }; + push(out, IS::Return { v }); } - S::Expr(e) => self.expr_stmt(e, cx, out), + S::Expr(e) => self.expr_stmt(e, u, out, l), } - false } - fn expr_stmt(&mut self, e: &'a Expr, cx: &Cx, out: &mut Vec) { + fn var_stmt(&mut self, list: &'a [VarDecl], u: &mut Unit, out: &mut Vec, l: u32) { + for d in list { + let Some(init) = &d.init else { continue }; + let to = if u.in_function { + match u.locals.get(&d.name) { + Some((i, _)) => LValue::Local { i: *i }, + None => continue, + } + } else { + LValue::Var { n: d.name.clone() } + }; + let Some(v) = self.expr(init, u) else { continue }; + out.push(IStmt { l, s: IS::Do { x: X::Set { to, op: None, v: Box::new(v) } } }); + } + } + + fn expr_stmt(&mut self, e: &'a Expr, u: &mut Unit, out: &mut Vec, l: u32) { match &e.kind { - E::Call(callee, args) => self.call(e.pos, callee, args, cx, out), - E::Assign("=", lhs, rhs) => self.assign(e.pos, lhs, rhs, cx, out), - E::Assign(op, _, _) => self.problem(e.pos, format!("`{op}` reads a value first; only `=` with a value is supported")), + E::Call(callee, args) => { + if let Some(s) = self.call_stmt(e.pos, callee, args, u) { + out.push(IStmt { l, s }); + } + } E::Comma(list) => { for x in list { - self.expr_stmt(x, cx, out); + self.expr_stmt(x, u, out, l); } } // A literal alone does nothing (`"use strict"`). E::Num(_) | E::Str(_) | E::Bool(_) | E::Null => {} - E::Unary("++" | "--", _) | E::Postfix(..) => self.problem(e.pos, "`++` and `--` read a value first and aren't supported"), - _ => self.problem(e.pos, "only calls (such as `stop()`) and settings (such as `hero_mc.x = 10`) run as statements"), + E::Assign(_, lhs, _) if matches!(&lhs.kind, E::Member(_, p) if p == "buttonMode" || p == "useHandCursor") => { + let E::Member(_, p) = &lhs.kind else { return }; + self.note(e.pos, format!("`{p}` is ignored: the pointer is a hand over everything clickable here")); + } + _ => { + if let Some(x) = self.expr(e, u) { + out.push(IStmt { l, s: IS::Do { x } }); + } + } } } - fn call(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], cx: &Cx, out: &mut Vec) { + /// A call as a statement: timeline methods, `trace`, listeners, and any call with a value. + fn call_stmt(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], u: &mut Unit) -> O { match &callee.kind { - E::Name(n) => { + E::Name(n) if !u.locals.contains_key(n) => { let n = n.as_str(); - if let Some(f) = self.funcs.get(n).copied() { - return self.inline(pos, f, args, cx, out); + if self.funcs.contains_key(n) { + return self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }); } match n { - "trace" => self.trace(pos, args, cx, out), - "addEventListener" => self.listen(pos, Vec::new(), args, cx, out), - n if METHODS.contains(&n) => self.method(pos, Vec::new(), n, args, cx, out), - n if OUTSIDE.contains(&n) => self.note(pos, format!("`{n}` is ignored: a movie here can't open web pages or reach outside itself")), - "removeEventListener" => self.problem(pos, "removing listeners isn't supported yet"), - n if CASTS.contains(&n) => self.problem(pos, format!("`{n}(…)` alone does nothing; call a method on it, as in `{n}(parent).play()`")), - n => self.problem(pos, format!("`{n}` isn't declared in this frame script (functions from other frames, and the rest of the language, aren't supported yet)")), + "trace" => { + let args = self.args(args, u)?; + Some(IS::Trace { args }) + } + "addEventListener" | "removeEventListener" => self.listen(pos, Place::this(), args, n == "addEventListener", u), + n if Method::from_name(n).is_some() => self.method(pos, Place::this(), n, args, u), + n if OUTSIDE.contains(&n) => { + self.note(pos, format!("`{n}` is ignored: a movie here can't open web pages or reach outside itself")); + None + } + n if CASTS.contains(&n) => { + self.problem(pos, format!("`{n}(…)` alone does nothing; call a method on it, as in `{n}(parent).play()`")); + None + } + _ => self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }), } } E::Member(obj, m) => { let m = m.as_str(); if OUTSIDE.contains(&m) || (matches!(&obj.kind, E::Name(o) if o == "ExternalInterface") && matches!(m, "call" | "addCallback")) { - return self.note(pos, format!("`{m}` is ignored: a movie here can't open web pages or reach outside itself")); + self.note(pos, format!("`{m}` is ignored: a movie here can't open web pages or reach outside itself")); + return None; } - let known = METHODS.contains(&m) || m == "addEventListener"; - if !known { - let msg = if m == "removeEventListener" { "removing listeners isn't supported yet".to_string() } else { format!("calling `{m}` isn't supported (timeline methods such as `play()` and `gotoAndStop()`, and `addEventListener`, are)") }; - return self.problem(pos, msg); + if matches!(&obj.kind, E::Name(o) if o == "Math") { + return self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }); + } + // `field.appendText(v)` is `field.text += v` (ADR 0066). + if m == "appendText" { + let [arg] = args else { + self.problem(pos, "`appendText` takes one argument, the text to add"); + return None; + }; + let (at, v) = (self.field_place(obj, u), self.expr(arg, u)); + return Some(IS::Do { x: X::Set { to: LValue::Text { at: at? }, op: Some(BinOp::Add), v: Box::new(v?) } }); + } + if Method::from_name(m).is_none() && m != "addEventListener" && m != "removeEventListener" { + self.problem(pos, format!("calling `{m}` isn't supported (timeline methods such as `play()` and `gotoAndStop()`, `addEventListener` and `removeEventListener` are)")); + return None; + } + let at = self.place(obj, u)?; + match m { + "addEventListener" | "removeEventListener" => self.listen(pos, at, args, m == "addEventListener", u), + _ => self.method(pos, at, m, args, u), } - let Some(t) = self.target(obj, cx) else { return }; - if m == "addEventListener" { self.listen(pos, t, args, cx, out) } else { self.method(pos, t, m, args, cx, out) } } - _ => self.problem(pos, "only named functions and methods can be called"), + _ => self.call_expr(pos, callee, args, u).map(|x| IS::Do { x }), } } - /// A call to one of the script's own functions: its body runs in place. - fn inline(&mut self, pos: Pos, f: &'a Func, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - let name = f.name.clone().unwrap_or_default(); - if cx.stack.contains(&name) { - return self.problem(pos, format!("`{name}` calls itself; recursion isn't supported")); - } - if cx.stack.len() >= MAX_INLINE_DEPTH { - return self.problem(pos, format!("functions call each other more than {MAX_INLINE_DEPTH} deep")); - } - // Arguments are passed but never read (a parameter read is reported in the body). + fn args(&mut self, args: &'a [Expr], u: &mut Unit) -> O> { + let mut out = Vec::with_capacity(args.len()); + let mut ok = true; for a in args { - let passes_event = matches!((&a.kind, &cx.event), (E::Name(n), Some((e, _))) if n == e); - if !passes_event && self.constant(a, cx).is_err() { - self.problem(a.pos, "arguments are values or the event; computing them isn't supported"); + match self.expr(a, u) { + Some(x) => out.push(x), + None => ok = false, } } - if args.len() < f.params.iter().filter(|p| !p.default && !p.rest).count() { - return self.problem(pos, format!("`{name}` needs more arguments than this call passes")); - } - let mut inner = Cx { event: None, in_listener: cx.in_listener, in_function: true, params: f.params.iter().map(|p| p.name.clone()).collect(), stack: cx.stack.clone() }; - inner.stack.push(name); - self.stmts(&f.body, &inner, out); + ok.then_some(out) } - fn trace(&mut self, pos: Pos, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - let mut parts = Vec::new(); - for a in args { - match self.constant(a, cx) { - Ok(v) => parts.push(v.text()), - Err(p) => return self.problems.push(p), - } + /// A timeline method on the instance at `at`. + fn method(&mut self, pos: Pos, at: Place, m: &str, args: &'a [Expr], u: &mut Unit) -> O { + let method = Method::from_name(m)?; + let takes = matches!(method, Method::GotoAndPlay | Method::GotoAndStop); + if !takes && !args.is_empty() { + self.problem(pos, format!("`{m}()` takes no arguments")); + return None; } - let message = parts.join(" "); - if message.chars().count() > MAX_TRACE_CHARS { - return self.problem(pos, format!("a trace message is at most {MAX_TRACE_CHARS} characters")); + if matches!(method, Method::NextScene | Method::PrevScene) && (!at.path.is_this() || !at.base.is_this()) { + // Scenes belong to the main timeline; on this timeline the player checks that it is + // the main one (a movie clip has no other scenes). + self.problem(pos, format!("call `{m}()` in the main timeline's own script: scenes belong to the main timeline")); + return None; } - out.push(ScriptOp::Action(Action::Trace { message })); - } - - /// A timeline method on the instance at `path`. - fn method(&mut self, pos: Pos, path: Vec, m: &str, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - let Some(target) = self.path(pos, &path) else { return }; - let none = |l: &mut Self| { - if args.is_empty() { - true - } else { - l.problem(pos, format!("`{m}()` takes no arguments")); - false - } - }; - let action = match m { - "stop" if none(self) => Action::Stop { target }, - "play" if none(self) => Action::Play { target }, - "nextFrame" if none(self) => Action::NextFrame { target }, - "prevFrame" if none(self) => Action::PrevFrame { target }, - "nextScene" | "prevScene" => { - if !none(self) { - return; + if takes && (args.is_empty() || args.len() > 2) { + self.problem(pos, format!("`{m}` takes a frame, and optionally a scene")); + return None; + } + // Frames and scenes written out are checked now; computed ones when they run. + if let Some(f) = args.first() { + match &f.kind { + E::Num(n) if !(n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(n)) => { + self.problem(f.pos, format!("a frame number is a whole number from 1 to {}", u64::from(MAX_FRAME) + 1)); + return None; } - // Scenes belong to the main timeline; on this timeline the player checks that - // it is the main one (a movie clip has no other scenes). - if !target.is_this() { - return self.problem(pos, format!("call `{m}()` in the main timeline's own script: scenes belong to the main timeline")); + E::Str(s) if !label_ok(s) => { + self.problem(f.pos, format!("a frame label is 1 to {MAX_LABEL_CHARS} printable characters")); + return None; } - if m == "nextScene" { Action::NextScene } else { Action::PrevScene } + E::Bool(_) | E::Null => { + self.problem(f.pos, "the frame is a number or a label"); + return None; + } + _ => {} } - "gotoAndPlay" | "gotoAndStop" => { - let (Some(f), true) = (args.first(), args.len() <= 2) else { - return self.problem(pos, format!("`{m}` takes a frame, and optionally a scene")); - }; - let frame = match self.constant(f, cx) { - Ok(Val::Num(n)) if n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(&n) => FrameRef::Number(n as u32 - 1), - Ok(Val::Num(_)) => return self.problem(f.pos, format!("a frame number is a whole number from 1 to {}", u64::from(MAX_FRAME) + 1)), - Ok(Val::Str(s)) if label_ok(&s) => FrameRef::Label(s), - Ok(Val::Str(_)) => return self.problem(f.pos, format!("a frame label is 1 to {MAX_LABEL_CHARS} printable characters")), - Ok(_) => return self.problem(f.pos, "the frame is a number or a label"), - Err(p) => return self.problems.push(p), - }; - let scene = match args.get(1).map(|s| (s.pos, self.constant(s, cx))) { - None | Some((_, Ok(Val::Null | Val::Undefined))) => None, - Some((_, Ok(Val::Str(s)))) if label_ok(&s) => Some(s), - Some((p, Ok(_))) => return self.problem(p, "the scene is its name, as a string"), - Some((_, Err(p))) => return self.problems.push(p), - }; - if m == "gotoAndPlay" { Action::GotoAndPlay { target, frame, scene } } else { Action::GotoAndStop { target, frame, scene } } - } - _ => return, - }; - out.push(ScriptOp::Action(action)); - } - - /// `target.addEventListener(event, function)`. - fn listen(&mut self, pos: Pos, path: Vec, args: &'a [Expr], cx: &Cx, out: &mut Vec) { - if cx.in_listener { - return self.problem(pos, "adding a listener from inside a listener isn't supported yet"); } - let Some(target) = self.path(pos, &path) else { return }; - let (Some(ev), Some(handler), true) = (args.first(), args.get(1), args.len() <= 5) else { - return self.problem(pos, "`addEventListener` takes an event and a function"); - }; - let Some(event) = self.event(ev) else { return }; - if let Some(c) = args.get(2) - && !matches!(self.constant(c, cx), Ok(Val::Bool(false) | Val::Null | Val::Undefined)) + if let Some(s) = args.get(1) + && (matches!(&s.kind, E::Num(_) | E::Bool(_)) || matches!(&s.kind, E::Str(t) if !label_ok(t))) { - return self.problem(c.pos, "capture-phase listeners (`useCapture`) aren't supported"); + self.problem(s.pos, "the scene is its name, as a string"); + return None; + } + let args = self.args(args, u)?; + Some(IS::Act { at, m: method, args }) + } + + /// `at.addEventListener(event, function)` (or `removeEventListener`). + fn listen(&mut self, pos: Pos, at: Place, args: &'a [Expr], add: bool, u: &mut Unit) -> O { + let verb = if add { "addEventListener" } else { "removeEventListener" }; + let (Some(ev), Some(handler), true) = (args.first(), args.get(1), args.len() <= if add { 5 } else { 3 }) else { + self.problem(pos, format!("`{verb}` takes an event and a function")); + return None; + }; + let event = self.event(ev)?; + if let Some(c) = args.get(2) + && !matches!(c.kind, E::Bool(false) | E::Null) + { + self.problem(c.pos, "capture-phase listeners (`useCapture`) aren't supported"); + return None; } for extra in args.iter().skip(3) { - if self.constant(extra, cx).is_err() { - return self.problem(extra.pos, "listener priority and weak references are values"); + if !matches!(extra.kind, E::Num(_) | E::Bool(_) | E::Null) { + self.problem(extra.pos, "listener priority and weak references are values"); + return None; } } - let (f, function) = match &handler.kind { - E::Name(n) => match self.funcs.get(n.as_str()).copied() { - Some(f) => (f, n.clone()), - None => return self.problem(handler.pos, format!("`{n}` isn't a function declared in this frame script")), - }, - E::Function(f) => (&**f, format!("function at line {}", f.pos.line)), - _ => return self.problem(handler.pos, "the listener is a function declared in this frame script, or written in place"), + if event.is_key() && at.base != Base::Stage { + self.note(pos, "keys go to the stage here: listen with `stage.addEventListener(KeyboardEvent.KEY_DOWN, …)`; this listener is ignored"); + return None; + } + if at.base == Base::Stage && event.mouse().is_some() { + self.problem(pos, "mouse listeners on the stage aren't supported yet (on buttons and movie clips they are)"); + return None; + } + let f = match &handler.kind { + E::Name(n) if !u.locals.contains_key(n) => { + match self.funcs.get(n.as_str()).copied() { + Some(f) => { + if !takes_event(f) { + self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); + return None; + } + } + None if CLASSES.contains(&n.as_str()) || BUILTINS.contains(&n.as_str()) => { + self.problem(handler.pos, format!("`{n}` isn't a function declared in a frame script")); + return None; + } + None => self.free(n, handler.pos, true), + } + FuncRef::Named(n.clone()) + } + E::Function(f) if add => { + if !takes_event(f) { + self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); + return None; + } + let name = format!("function at line {}, column {}", f.pos.line, f.pos.column); + let func = self.function(f, name)?; + if u.inner.len() >= usize::from(u16::MAX) { + return None; + } + u.inner.push(func); + FuncRef::Inline((u.inner.len() - 1) as u16) + } + E::Function(_) => { + self.problem(handler.pos, "a function written in place can't be removed; give it a name and listen with that"); + return None; + } + _ => { + self.problem(handler.pos, "the listener is a function declared in a frame script, or written in place"); + return None; + } }; - // The event is passed to the function: it takes exactly one argument. - let required = f.params.iter().filter(|p| !p.default && !p.rest).count(); - let Some(first) = f.params.first().filter(|_| required <= 1) else { - return self.problem(f.pos, "a listener function takes the event as its one parameter: `function f(e:MouseEvent):void`"); - }; - if cx.stack.contains(&function) { - return self.problem(pos, format!("`{function}` adds itself as a listener; recursion isn't supported")); + if add { + if self.listeners >= MAX_LISTENERS { + self.problem(pos, format!("a frame script adds at most {MAX_LISTENERS} listeners")); + return None; + } + self.listeners += 1; } - if self.listeners >= MAX_LISTENERS { - return self.problem(pos, format!("a frame script adds at most {MAX_LISTENERS} listeners")); - } - self.listeners += 1; - let mut inner = Cx { event: Some((first.name.clone(), path)), in_listener: true, in_function: true, params: f.params.iter().map(|p| p.name.clone()).collect(), stack: cx.stack.clone() }; - inner.stack.push(function.clone()); - let mut body = Vec::new(); - self.stmts(&f.body, &inner, &mut body); - let actions: Vec = body - .into_iter() - .filter_map(|op| match op { - ScriptOp::Action(a) => Some(a), - ScriptOp::Listen(_) => None, - }) - .collect(); - if actions.len() > MAX_ACTIONS { - return self.problem(f.pos, format!("a listener runs at most {MAX_ACTIONS} actions")); - } - out.push(ScriptOp::Listen(Listener { target, event, function, actions: Arc::new(actions) })); + Some(IS::Listen { at, ev: event, f, add }) } - /// The mouse event an `addEventListener` names. - fn event(&mut self, e: &Expr) -> Option { - let (pos, name, constant) = match &e.kind { - E::Member(o, k) if matches!(&o.kind, E::Name(c) if c == "MouseEvent" || c == "Event" || c.ends_with("Event")) => { + /// The event an `addEventListener` names. + fn event(&mut self, e: &Expr) -> O { + let (name, key) = match &e.kind { + E::Member(o, k) if matches!(&o.kind, E::Name(c) if c.ends_with("Event")) => { let class = if let E::Name(c) = &o.kind { c.as_str() } else { "" }; - (e.pos, format!("{class}.{k}"), if class == "MouseEvent" { k.as_str() } else { "" }) + let ev = match (class, k.as_str()) { + ("MouseEvent", "CLICK") => Some(ListenEvent::Click), + ("MouseEvent", "MOUSE_DOWN") => Some(ListenEvent::Press), + ("MouseEvent", "MOUSE_UP") => Some(ListenEvent::Release), + ("MouseEvent", "ROLL_OVER" | "MOUSE_OVER") => Some(ListenEvent::Over), + ("MouseEvent", "ROLL_OUT" | "MOUSE_OUT") => Some(ListenEvent::Out), + ("Event", "ENTER_FRAME") => Some(ListenEvent::EnterFrame), + ("KeyboardEvent", "KEY_DOWN") => Some(ListenEvent::KeyDown), + ("KeyboardEvent", "KEY_UP") => Some(ListenEvent::KeyUp), + _ => None, + }; + (format!("{class}.{k}"), ev) } - E::Str(s) => (e.pos, format!("\"{s}\""), match s.as_str() { - "click" => "CLICK", - "mouseDown" => "MOUSE_DOWN", - "mouseUp" => "MOUSE_UP", - "rollOver" => "ROLL_OVER", - "rollOut" => "ROLL_OUT", - "mouseOver" => "MOUSE_OVER", - "mouseOut" => "MOUSE_OUT", - _ => "", - }), + E::Str(s) => ( + format!("\"{s}\""), + match s.as_str() { + "click" => Some(ListenEvent::Click), + "mouseDown" => Some(ListenEvent::Press), + "mouseUp" => Some(ListenEvent::Release), + "rollOver" | "mouseOver" => Some(ListenEvent::Over), + "rollOut" | "mouseOut" => Some(ListenEvent::Out), + "enterFrame" => Some(ListenEvent::EnterFrame), + "keyDown" => Some(ListenEvent::KeyDown), + "keyUp" => Some(ListenEvent::KeyUp), + _ => None, + }, + ), _ => { self.problem(e.pos, "the event is a constant such as `MouseEvent.CLICK`"); return None; } }; - let ev = match constant { - "CLICK" => ButtonEvent::Click, - "MOUSE_DOWN" => ButtonEvent::Press, - "MOUSE_UP" => ButtonEvent::Release, - "ROLL_OVER" | "MOUSE_OVER" => ButtonEvent::Over, - "ROLL_OUT" | "MOUSE_OUT" => ButtonEvent::Out, - _ => { - self.problem(pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT are)")); - return None; - } - }; - Some(ev) - } - - /// `x = value` on this timeline or `path.x = value`. - fn assign(&mut self, pos: Pos, lhs: &'a Expr, rhs: &'a Expr, cx: &Cx, out: &mut Vec) { - let (obj, prop) = match &lhs.kind { - E::Member(o, p) => (Some(&**o), p.as_str()), - E::Name(n) => (None, n.as_str()), - _ => return self.problem(pos, "only instance properties can be set"), - }; - let property = match prop { - "x" => Property::X, - "y" => Property::Y, - "alpha" => Property::Alpha, - "visible" => Property::Visible, - "rotation" => Property::Rotation, - "scaleX" => Property::ScaleX, - "scaleY" => Property::ScaleY, - "buttonMode" | "useHandCursor" => return self.note(pos, format!("`{prop}` is ignored: the pointer is a hand over everything clickable here")), - p if obj.is_none() => return self.problem(pos, format!("setting `{p}` isn't supported: variables don't run yet")), - p => return self.problem(pos, format!("setting `{p}` isn't supported yet (x, y, alpha, visible, rotation, scaleX and scaleY are)")), - }; - let path = match obj { - Some(o) => match self.target(o, cx) { - Some(t) => t, - None => return, - }, - None => Vec::new(), - }; - let Some(target) = self.path(pos, &path) else { return }; - let value = match self.constant(rhs, cx) { - Ok(v @ (Val::Num(_) | Val::Bool(_))) => v.number(), - Ok(_) => return self.problem(rhs.pos, format!("`{prop}` is set to a number{}", if property == Property::Visible { " or true or false" } else { "" })), - Err(p) => return self.problems.push(p), - }; - if !value.is_finite() { - return self.problem(rhs.pos, "the value must be a finite number"); + if key.is_none() { + self.problem(e.pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT, Event.ENTER_FRAME and KeyboardEvent.KEY_DOWN and KEY_UP are)")); } - out.push(ScriptOp::Action(Action::SetProperty { target, property, value })); + key } - /// An instance path as names (`root`, `parent` and instance names), relative to the - /// script's timeline; `None` after reporting why it isn't one. - fn target(&mut self, e: &Expr, cx: &Cx) -> Option> { - let mut path = match &e.kind { - E::This => Vec::new(), - E::Name(n) if n == "root" || n == "parent" => vec![n.clone()], - E::Name(n) if n == "stage" => { - self.problem(e.pos, "the stage isn't supported as a target"); + // ----- functions ----------------------------------------------------------------------- + + /// A function's IR: parameters, its own variables (hoisted, as ActionScript does) and body. + fn function(&mut self, f: &'a Func, name: String) -> O> { + if self.depth >= 8 { + self.problem(f.pos, "listeners written in place nest more than 8 deep"); + return None; + } + let before = self.problems.len(); + let mut u = Unit { in_function: true, ..Unit::top() }; + let mut params = Vec::new(); + for (i, p) in f.params.iter().enumerate() { + if p.rest { + self.problem(p.pos, "rest parameters (`...args`) aren't supported"); + continue; + } + let (t, ev) = match var_type(&p.ty) { + Ok(Some(t)) => (t, false), + Ok(None) => (Ty::Any, true), + Err((pos, m)) => { + self.problem(pos, m.replace("variables of type", "parameters of type")); + continue; + } + }; + // An untyped first parameter can be the event, too (`function f(e)`). + if ev || (i == 0 && p.ty.is_none()) { + u.events.insert(p.name.clone()); + } + let d = match &p.default { + None => None, + Some(e) => match literal(e) { + Some(v) => Some(t.coerce(v)), + None => { + self.problem(e.pos, "a parameter's default is a value written out (a number, a string, true, false or null)"); + continue; + } + }, + }; + if u.locals.insert(p.name.clone(), (u.types.len() as u16, t)).is_some() { + self.problem(p.pos, format!("the parameter `{}` is named twice", p.name)); + } + u.types.push(t); + params.push(IrParam { t, d, ev }); + } + // Every `var` in the body is the function's (hoisted). + let mut decls = Vec::new(); + collect_vars(&f.body, &mut decls); + for d in decls { + let t = match var_type(&d.ty) { + Ok(Some(t)) => t, + Ok(None) => { + self.problem(d.pos, "variables can't hold events; read `e.keyCode`, `e.target` or `e.currentTarget` from the parameter"); + continue; + } + Err((pos, m)) => { + self.problem(pos, m); + continue; + } + }; + match u.locals.get(&d.name) { + Some((_, old)) if *old != t && d.ty.is_some() => self.problem(d.pos, format!("`{}` is declared again with another type", d.name)), + Some(_) => {} + None => { + if u.types.len() >= 1024 { + self.problem(d.pos, "a function has at most 1024 variables"); + continue; + } + u.locals.insert(d.name.clone(), (u.types.len() as u16, t)); + u.types.push(t); + } + } + } + let ret = match &f.ret { + None => Some(Ty::Any), + Some((t, _)) if t == "void" => None, + Some((t, p)) => match Ty::from_name(t) { + Some(t) => Some(t), + None => { + self.problem(*p, format!("functions returning `{t}` aren't supported yet (Number, int, uint, Boolean, String, void and untyped ones are)")); + None + } + }, + }; + self.depth += 1; + let body = self.body(&f.body, &mut u); + self.depth -= 1; + if self.problems.len() > before { + return None; + } + Some(Arc::new(Function { name, line: f.pos.line, params, locals: u.types, ret, body, inner: u.inner })) + } + + // ----- names and places ---------------------------------------------------------------- + + /// An instance a script names, from the timeline or the event; `None` after reporting why + /// it isn't one. + fn place(&mut self, e: &Expr, u: &Unit) -> O { + let mut at = match &e.kind { + E::This => Place::this(), + E::Name(n) if u.locals.contains_key(n) && !u.events.contains(n) => { + self.problem(e.pos, format!("`{n}` is a variable, not an instance")); return None; } - E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => { + E::Name(n) if u.events.contains(n) => { self.problem(e.pos, format!("the event `{n}` isn't an instance; `{n}.currentTarget` is the one listened to")); return None; } - E::Name(n) if cx.params.contains(n) => { - self.problem(e.pos, format!("reading the parameter `{n}` isn't supported")); + E::Name(n) if n == "stage" => Place { base: Base::Stage, path: Target::this() }, + E::Name(n) if n == "root" || n == "parent" => Place::named(n.clone()), + E::Name(n) if self.vars.contains_key(n) => { + self.problem(e.pos, format!("`{n}` is a variable, not an instance")); return None; } - E::Name(n) => vec![n.clone()], - E::Member(o, m) if m == "currentTarget" && matches!((&o.kind, &cx.event), (E::Name(n), Some((p, _))) if n == p) => cx.event.as_ref().map(|(_, t)| t.clone()).unwrap_or_default(), - E::Member(o, m) if m == "target" && matches!((&o.kind, &cx.event), (E::Name(n), Some((p, _))) if n == p) => { - self.problem(e.pos, "`target` can be a part inside the instance; use `currentTarget`, the instance listened to"); + E::Name(n) if CLASSES.contains(&n.as_str()) => { + self.problem(e.pos, format!("`{n}` is a class, not an instance")); return None; } + E::Name(n) => Place::named(n.clone()), + E::Member(o, m) if (m == "currentTarget" || m == "target") && matches!(&o.kind, E::Name(n) if u.events.contains(n)) => Place { base: if m == "target" { Base::Target } else { Base::Current }, path: Target::this() }, E::Member(o, m) => { - let mut p = self.target(o, cx)?; - p.push(m.clone()); + let mut p = self.place(o, u)?; + if p.base == Base::Stage { + self.problem(e.pos, format!("`stage.{m}` isn't supported")); + return None; + } + let path = if p.path.is_this() { m.clone() } else { format!("{}.{m}", p.path.0.trim()) }; + p.path = Target::new(path); p } - E::Call(f, args) if matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1 => return args.first().and_then(|a| self.target(a, cx)), - E::Binary("as", x, _) => return self.target(x, cx), + E::Call(f, args) if matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1 => return args.first().and_then(|a| self.place(a, u)), + E::Binary("as", x, _) => return self.place(x, u), _ => { self.problem(e.pos, "this isn't an instance (a name path such as `hero_mc.arm_mc`, `parent` or `root`)"); return None; } }; // Every instance's `root` is the main timeline. - if let Some(i) = path.iter().rposition(|s| s == "root") { - path.drain(..i); + let segs: Vec = at.path.0.trim().split('.').filter(|s| !s.is_empty()).map(str::to_string).collect(); + if let Some(i) = segs.iter().rposition(|s| s == "root") { + at = Place { base: Base::This, path: Target::new(segs.get(i..).unwrap_or_default().join(".")) }; } - Some(path) - } - - /// The IR target for a path, checked. - fn path(&mut self, pos: Pos, path: &[String]) -> Option { - for s in path { - if !matches!(s.as_str(), "root" | "parent") && !valid_instance_name(s) { - self.problem(pos, format!("`{s}` isn't an instance name AniCraft can address (1-64 letters, digits, `_` or `$`)")); + for s in at.path.0.split('.').filter(|s| !s.is_empty()) { + if !matches!(s, "root" | "parent" | "this") && !valid_instance_name(s) { + self.problem(e.pos, format!("`{s}` isn't an instance name AniCraft can address (1-64 letters, digits, `_` or `$`)")); return None; } } - let t = Target::new(path.join(".")); - match t.segments() { - Ok(_) => Some(t), - Err(e) => { - self.problem(pos, e); + if let Err(m) = at.path.segments() { + self.problem(e.pos, m); + return None; + } + Some(at) + } + + /// The text field a script names (`score_txt`, `panel.name_txt`): an instance, not the + /// stage or a timeline (`this` is one only if it is a field, which a frame script's isn't). + fn field_place(&mut self, e: &Expr, u: &Unit) -> O { + let at = self.place(e, u)?; + if at.base == Base::Stage || (at.base == Base::This && at.path.is_this()) { + self.problem(e.pos, "this isn't a text field; name the field by its instance name, as in `score_txt.text`"); + return None; + } + Some(at) + } + + /// Whether an expression names an instance rather than a value (for `==` between instances). + fn is_instance(&self, e: &Expr, u: &Unit) -> bool { + match &e.kind { + E::This => true, + E::Name(n) => n == "stage" || n == "root" || n == "parent", + E::Member(o, m) => (m == "currentTarget" || m == "target") && matches!(&o.kind, E::Name(n) if u.events.contains(n)), + E::Call(f, args) => matches!(&f.kind, E::Name(c) if CASTS.contains(&c.as_str())) && args.len() == 1, + E::Binary("as", ..) => true, + _ => false, + } + } + + /// Where an assignment writes. + fn lvalue(&mut self, e: &'a Expr, u: &mut Unit) -> O { + match &e.kind { + E::Name(n) => { + if let Some((i, _)) = u.locals.get(n) { + return Some(LValue::Local { i: *i }); + } + if self.vars.contains_key(n) { + return Some(LValue::Var { n: n.clone() }); + } + if let Some(p) = Prop::from_name(n) { + return match p.settable() { + Some(p) => Some(LValue::Prop { at: Place::this(), p }), + None => { + self.problem(e.pos, format!("`{n}` can only be read")); + None + } + }; + } + if self.funcs.contains_key(n.as_str()) || PATH_WORDS.contains(&n.as_str()) || CLASSES.contains(&n.as_str()) || BUILTINS.contains(&n.as_str()) || matches!(n.as_str(), "undefined" | "NaN" | "Infinity") { + self.problem(e.pos, format!("`{n}` can't be assigned to")); + return None; + } + self.free(n, e.pos, false); + Some(LValue::Var { n: n.clone() }) + } + E::Member(o, m) if m == "text" => Some(LValue::Text { at: self.field_place(o, u)? }), + E::Member(o, m) => { + let Some(p) = Prop::from_member(m) else { + self.problem(e.pos, format!("setting `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY and a text field's text are)")); + return None; + }; + let Some(p) = p.settable() else { + self.problem(e.pos, format!("`{m}` can only be read")); + return None; + }; + let at = self.place(o, u)?; + if at.base == Base::Stage { + self.problem(e.pos, "the stage's properties can't be set here"); + return None; + } + Some(LValue::Prop { at, p }) + } + _ => { + self.problem(e.pos, "only variables and instance properties can be assigned to"); None } } } - /// A value computed from literals (`"Score: " + 10`, `-5`, `0.5`). - fn constant(&self, e: &Expr, cx: &Cx) -> Result { - Ok(match &e.kind { - E::Num(n) => Val::Num(*n), - E::Str(s) => Val::Str(s.clone()), - E::Bool(b) => Val::Bool(*b), - E::Null => Val::Null, - E::Name(n) if n == "undefined" => Val::Undefined, - E::Name(n) if n == "NaN" => Val::Num(f64::NAN), - E::Name(n) if n == "Infinity" => Val::Num(f64::INFINITY), - E::Unary("-", x) => Val::Num(-self.constant(x, cx)?.number()), - E::Unary("+", x) => Val::Num(self.constant(x, cx)?.number()), - E::Unary("!", x) => Val::Bool(!truthy(&self.constant(x, cx)?)), - E::Binary(op @ ("+" | "-" | "*" | "/" | "%"), a, b) => { - let (a, b) = (self.constant(a, cx)?, self.constant(b, cx)?); - match *op { - "+" if matches!(a, Val::Str(_)) || matches!(b, Val::Str(_)) => { - let s = a.text() + &b.text(); - if s.len() > MAX_TRACE_CHARS * 4 { - return Err(Problem::at(e.pos, "this text is too long")); + // ----- expressions --------------------------------------------------------------------- + + fn expr(&mut self, e: &'a Expr, u: &mut Unit) -> O { + Some(match &e.kind { + E::Num(n) => X::lit(Value::Num(*n)), + E::Str(s) => { + if ir::text_len(s) > super::run::MAX_TEXT { + self.problem(e.pos, "this text is too long"); + return None; + } + X::lit(Value::str(s)) + } + E::Bool(b) => X::lit(Value::Bool(*b)), + E::Null => X::lit(Value::Null), + E::Name(n) => return self.name(e.pos, n, u), + E::Member(o, m) => return self.member(e, o, m, u), + E::Unary(op, x) => match *op { + "-" | "+" | "!" => { + let x = self.expr(x, u)?; + let op = match *op { + "-" => UnOp::Neg, + "+" => UnOp::Plus, + _ => UnOp::Not, + }; + X::Un { op, x: Box::new(x) } + } + "++" | "--" => X::Step { to: self.lvalue(x, u)?, d: if *op == "++" { 1 } else { -1 }, post: false }, + other => { + self.problem(e.pos, format!("`{other}` isn't supported yet")); + return None; + } + }, + E::Postfix(op, x) => X::Step { to: self.lvalue(x, u)?, d: if *op == "++" { 1 } else { -1 }, post: true }, + E::Binary(op, a, b) => match *op { + "&&" | "||" => { + let (a, b) = (self.expr(a, u), self.expr(b, u)); + let (a, b) = (Box::new(a?), Box::new(b?)); + if *op == "&&" { X::And { a, b } } else { X::Or { a, b } } + } + "==" | "!=" | "===" | "!==" if self.is_instance(a, u) || self.is_instance(b, u) => { + let (pa, pb) = (self.place(a, u), self.place(b, u)); + X::Same { a: pa?, b: pb?, ne: op.starts_with('!') } + } + op => { + let Some(bop) = BinOp::from_token(op) else { + let what = match op { + "as" | "is" | "instanceof" | "in" => format!("`{op}` isn't supported here"), + _ => format!("the `{op}` operator isn't supported yet"), + }; + self.problem(e.pos, what); + return None; + }; + let (a, b) = (self.expr(a, u), self.expr(b, u)); + X::Bin { op: bop, a: Box::new(a?), b: Box::new(b?) } + } + }, + E::Assign(op, lhs, rhs) => { + let op = match *op { + "=" => None, + o => match BinOp::from_token(o.trim_end_matches('=')) { + Some(b @ (BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod)) => Some(b), + _ => { + self.problem(e.pos, format!("`{o}` isn't supported yet (`=`, `+=`, `-=`, `*=`, `/=` and `%=` are)")); + return None; } - Val::Str(s) - } - "+" => Val::Num(a.number() + b.number()), - "-" => Val::Num(a.number() - b.number()), - "*" => Val::Num(a.number() * b.number()), - "/" => Val::Num(a.number() / b.number()), - _ => Val::Num(a.number() % b.number()), - } - } - E::Name(n) => { - let msg = if cx.event.as_ref().is_some_and(|(p, _)| p == n) { format!("reading the event `{n}` isn't supported") } else { format!("reading `{n}` isn't supported: only values written out (numbers, strings, true, false) and `+` of them are") }; - return Err(Problem::at(e.pos, msg)); - } - E::Member(..) => { - let mut root = e; - while let E::Member(o, _) = &root.kind { - root = o; - } - let msg = match &root.kind { - E::Name(n) if cx.event.as_ref().is_some_and(|(p, _)| p == n) => format!("reading the event `{n}` isn't supported"), - _ => "reading properties isn't supported: only values written out (numbers, strings, true, false) and `+` of them are".into(), + }, }; - return Err(Problem::at(e.pos, msg)); + let (to, v) = (self.lvalue(lhs, u), self.expr(rhs, u)); + X::Set { to: to?, op, v: Box::new(v?) } + } + E::Cond(c, a, b) => { + let (c, a, b) = (self.expr(c, u), self.expr(a, u), self.expr(b, u)); + X::Cond { c: Box::new(c?), a: Box::new(a?), b: Box::new(b?) } + } + E::Call(callee, args) => return self.call_expr(e.pos, callee, args, u), + E::Comma(_) => { + self.problem(e.pos, "`,` between expressions isn't supported here"); + return None; + } + E::Function(_) => { + self.problem(e.pos, "a function written in place is only supported as a listener"); + return None; + } + E::This => { + self.problem(e.pos, "`this` is the timeline; read a property of it, as in `this.currentFrame`"); + return None; + } + E::Array(_) => { + self.problem(e.pos, "arrays aren't supported yet"); + return None; + } + E::Object(_) => { + self.problem(e.pos, "objects (`{…}`) aren't supported yet"); + return None; + } + E::New(..) => { + self.problem(e.pos, "`new` isn't supported yet"); + return None; + } + E::Index(..) => { + self.problem(e.pos, "`[…]` access isn't supported yet"); + return None; } - _ => return Err(Problem::at(e.pos, "only values written out (numbers, strings, true, false) and `+` of them are supported here")), }) } + + /// A bare name as a value. + fn name(&mut self, pos: Pos, n: &str, u: &mut Unit) -> O { + if let Some((i, _)) = u.locals.get(n) { + return Some(X::Local { i: *i }); + } + if self.vars.contains_key(n) { + return Some(X::Var { n: n.to_string() }); + } + match n { + "undefined" => return Some(X::lit(Value::Undefined)), + "NaN" => return Some(X::lit(Value::Num(f64::NAN))), + "Infinity" => return Some(X::lit(Value::Num(f64::INFINITY))), + _ => {} + } + if let Some(p) = Prop::from_name(n) { + return Some(X::Get { at: Place::this(), p }); + } + if self.funcs.contains_key(n) || BUILTINS.contains(&n) { + self.problem(pos, format!("`{n}` is a function; call it, as in `{n}()`")); + return None; + } + if PATH_WORDS.contains(&n) || CLASSES.contains(&n) || CASTS.contains(&n) { + self.problem(pos, format!("`{n}` isn't a value; read one of its properties")); + return None; + } + self.free(n, pos, false); + Some(X::Var { n: n.to_string() }) + } + + /// `o.m` as a value: constants, the event's key code, or a property of an instance. + fn member(&mut self, e: &'a Expr, o: &'a Expr, m: &str, u: &mut Unit) -> O { + if let E::Name(c) = &o.kind + && (!u.locals.contains_key(c) || u.events.contains(c)) + && !self.vars.contains_key(c) + { + match c.as_str() { + "Math" => { + return match m { + "PI" => Some(X::lit(Value::Num(std::f64::consts::PI))), + "E" => Some(X::lit(Value::Num(std::f64::consts::E))), + _ => { + self.problem(e.pos, format!("`Math.{m}` isn't supported yet (min, max, abs, floor, ceil, round, random and PI are)")); + None + } + }; + } + "Keyboard" => { + return match ir::key_code(m) { + Some(k) => Some(X::lit(Value::Num(f64::from(k)))), + None => { + self.problem(e.pos, format!("`Keyboard.{m}` isn't a key AniCraft knows")); + None + } + }; + } + ev if u.events.contains(ev) => { + return match m { + "keyCode" => Some(X::Key), + "currentTarget" | "target" => { + self.problem(e.pos, format!("`{ev}.{m}` is an instance; read one of its properties, as in `{ev}.{m}.name`")); + None + } + _ => { + self.problem(e.pos, format!("reading the event's `{m}` isn't supported yet (keyCode, target and currentTarget are)")); + None + } + }; + } + _ => {} + } + } + if let E::Name(n) = &o.kind + && n == "stage" + && !matches!(m, "mouseX" | "mouseY") + { + self.problem(e.pos, format!("`stage.{m}` isn't supported yet")); + return None; + } + if let E::Name(n) = &o.kind + && ((u.locals.contains_key(n) && !u.events.contains(n)) || self.vars.contains_key(n)) + { + self.problem(e.pos, format!("reading `{m}` of a value isn't supported yet")); + return None; + } + let Some(p) = Prop::from_member(m) else { + self.problem(e.pos, format!("reading `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY, currentFrame, totalFrames, currentLabel, mouseX, mouseY, name, and a text field's text and length are)")); + return None; + }; + let at = if matches!(p, Prop::Text | Prop::Length) { self.field_place(o, u)? } else { self.place(o, u)? }; + if at.base == Base::Stage && !matches!(p, Prop::MouseX | Prop::MouseY) { + self.problem(e.pos, format!("`stage.{m}` isn't supported yet")); + return None; + } + Some(X::Get { at, p }) + } + + /// A call with a value: the timeline's functions, `Math`, and casts. + fn call_expr(&mut self, pos: Pos, callee: &'a Expr, args: &'a [Expr], u: &mut Unit) -> O { + match &callee.kind { + E::Member(o, m) if matches!(&o.kind, E::Name(c) if c == "Math") => { + let Some(f) = MathFn::from_name(m) else { + self.problem(pos, format!("`Math.{m}` isn't supported yet (min, max, abs, floor, ceil, round and random are)")); + return None; + }; + if let Some(n) = f.arity() + && n != args.len() + { + self.problem(pos, format!("`Math.{m}` takes {n} argument{}", if n == 1 { "" } else { "s" })); + return None; + } + let args = self.args(args, u)?; + Some(X::Math { f, args }) + } + E::Name(n) if !u.locals.contains_key(n) => { + let n = n.as_str(); + let cast = match n { + "int" => Some(Ty::Int), + "uint" => Some(Ty::Uint), + "Number" => Some(Ty::Number), + "String" => Some(Ty::String), + "Boolean" => Some(Ty::Boolean), + _ => None, + }; + if let Some(t) = cast { + let [a] = args else { + self.problem(pos, format!("`{n}(…)` takes one value")); + return None; + }; + let x = self.expr(a, u)?; + // `String(x)` of null is "null"; as a variable type it stays null. + return Some(match t { + Ty::String => X::Bin { op: BinOp::Add, a: Box::new(X::lit(Value::str(""))), b: Box::new(x) }, + t => X::Cast { t, x: Box::new(x) }, + }); + } + if Method::from_name(n).is_some() || matches!(n, "trace" | "addEventListener" | "removeEventListener") { + self.problem(pos, format!("`{n}()` gives no value; call it as a statement")); + return None; + } + if OUTSIDE.contains(&n) || CASTS.contains(&n) || CLASSES.contains(&n) || n == "getChildByName" { + self.problem(pos, format!("`{n}(…)` isn't supported here")); + return None; + } + let local = self.funcs.get(n).copied(); + if local.is_none() { + self.free(n, callee.pos, true); + } + if let Some(f) = local { + let required = f.params.iter().filter(|p| p.default.is_none() && !p.rest).count(); + if args.len() < required || args.len() > f.params.len() { + self.problem(pos, format!("`{n}` takes {}{} argument{}, not {}", required, if required == f.params.len() { String::new() } else { format!(" to {}", f.params.len()) }, if f.params.len() == 1 { "" } else { "s" }, args.len())); + return None; + } + } + let mut out = Vec::with_capacity(args.len()); + let mut ok = true; + for a in args { + // The event a listener handles passes on to the function's event parameter. + if let E::Name(x) = &a.kind + && u.events.contains(x) + { + out.push(X::Event); + continue; + } + match self.expr(a, u) { + Some(x) => out.push(x), + None => ok = false, + } + } + ok.then_some(X::Call { f: n.to_string(), args: out }) + } + E::Member(_, m) => { + self.problem(pos, format!("calling `{m}` here isn't supported")); + None + } + _ => { + self.problem(pos, "only named functions and methods can be called"); + None + } + } + } } -fn truthy(v: &Val) -> bool { - match v { - Val::Num(n) => *n != 0.0 && !n.is_nan(), - Val::Str(s) => !s.is_empty(), - Val::Bool(b) => *b, - Val::Null | Val::Undefined => false, - } +/// Whether a declared function can be a listener: the event is its one required parameter. +fn takes_event(f: &Func) -> bool { + let required = f.params.iter().filter(|p| p.default.is_none() && !p.rest).count(); + required <= 1 && !f.params.is_empty() +} + +/// A value written out (for parameter defaults). +fn literal(e: &Expr) -> O { + Some(match &e.kind { + E::Num(n) => Value::Num(*n), + E::Str(s) => Value::str(s), + E::Bool(b) => Value::Bool(*b), + E::Null => Value::Null, + E::Name(n) if n == "undefined" => Value::Undefined, + E::Name(n) if n == "NaN" => Value::Num(f64::NAN), + E::Unary("-", x) => match &x.kind { + E::Num(n) => Value::Num(-n), + _ => return None, + }, + _ => return None, + }) } fn label_ok(s: &str) -> bool { @@ -570,6 +989,27 @@ fn label_ok(s: &str) -> bool { (1..=MAX_LABEL_CHARS).contains(&n) && !s.chars().any(char::is_control) && s.chars().any(|c| !c.is_whitespace()) } +/// Every `var` in a list of statements, into blocks and loops but not into functions. +fn collect_vars<'a>(list: &'a [Stmt], out: &mut Vec<&'a VarDecl>) { + for s in list { + match &s.kind { + S::Var(_, l) => out.extend(l.iter()), + S::Block(b) | S::While(_, b) | S::DoWhile(b, _) | S::Other(_, b) => collect_vars(b, out), + S::If(_, a, b) => { + collect_vars(a, out); + collect_vars(b, out); + } + S::For(init, _, _, b) => { + if let Some(i) = init { + collect_vars(std::slice::from_ref(&**i), out); + } + collect_vars(b, out); + } + _ => {} + } + } +} + /// The statements' top-level function declarations (also those in plain blocks, which /// ActionScript hoists too). fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, problems: &mut Vec) { @@ -577,7 +1017,7 @@ fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, proble match &s.kind { S::Function(f) => { let Some(n) = f.name.as_deref() else { continue }; - if BUILTINS.contains(&n) || CASTS.contains(&n) { + if BUILTINS.contains(&n) || CASTS.contains(&n) || CLASSES.contains(&n) || Prop::from_name(n).is_some() || matches!(n, "int" | "uint" | "Number" | "String" | "Boolean") { problems.push(Problem::at(s.pos, format!("a function named `{n}` would hide ActionScript's own `{n}`"))); } else if funcs.insert(n, f).is_some() { problems.push(Problem::at(s.pos, format!("`{n}` is declared twice"))); @@ -589,21 +1029,70 @@ fn declare<'a>(list: &'a [Stmt], funcs: &mut BTreeMap<&'a str, &'a Func>, proble } } +/// Counts statements (for "runs, N steps"). +fn count(list: &[IStmt]) -> usize { + list.iter() + .map(|s| { + 1 + match &s.s { + IS::If { a, b, .. } => count(a) + count(b), + IS::Loop { body, .. } => count(body), + _ => 0, + } + }) + .sum() +} + pub(super) fn lower(prog: &[Stmt]) -> Result> { let mut funcs = BTreeMap::new(); let mut problems = Vec::new(); declare(prog, &mut funcs, &mut problems); - let mut l = Lower { funcs, problems, notes: Vec::new(), listeners: 0, work: 0 }; - let mut ops = Vec::new(); - l.stmts(prog, &Cx::default(), &mut ops); - if ops.len() > MAX_ACTIONS { - l.problems.push(Problem::whole(format!("a frame script runs at most {MAX_ACTIONS} steps"))); + // The script's top-level `var`s are the timeline's variables. + let mut decls = Vec::new(); + collect_vars(prog, &mut decls); + let mut vars = BTreeMap::new(); + for d in decls { + let t = match var_type(&d.ty) { + Ok(Some(t)) => t, + Ok(None) => { + problems.push(Problem::at(d.pos, "variables can't hold events")); + continue; + } + Err((p, m)) => { + problems.push(Problem::at(p, m)); + continue; + } + }; + if Prop::from_name(&d.name).is_some() || PATH_WORDS.contains(&d.name.as_str()) || funcs.contains_key(d.name.as_str()) || BUILTINS.contains(&d.name.as_str()) { + problems.push(Problem::at(d.pos, format!("`{}` is already a name of the timeline; choose another name for the variable", d.name))); + continue; + } + match vars.get(&d.name) { + Some(old) if *old != t && d.ty.is_some() => problems.push(Problem::at(d.pos, format!("`{}` is declared again with another type", d.name))), + Some(_) => {} + None => { + vars.insert(d.name.clone(), t); + } + } } + let mut l = Lower { funcs, vars, problems, notes: Vec::new(), free: Vec::new(), listeners: 0, depth: 0 }; + let mut functions = Vec::new(); + let names: Vec<(&str, &Func)> = l.funcs.iter().map(|(n, f)| (*n, *f)).collect(); + for (n, f) in names { + if let Some(func) = l.function(f, n.to_string()) { + functions.push(func); + } + } + let mut top = Unit::top(); + let body = l.body(prog, &mut top); let tidy = |mut v: Vec| { v.sort(); v.dedup(); v.truncate(MAX_PROBLEMS); v }; - if l.problems.is_empty() { Ok(Compiled { ops, notes: tidy(l.notes) }) } else { Err(tidy(l.problems)) } + if !l.problems.is_empty() { + return Err(tidy(l.problems)); + } + let steps = count(&body) + functions.iter().map(|f| count(&f.body)).sum::(); + Ok(Compiled { body, inner: top.inner, functions, vars: l.vars.into_iter().collect(), free: l.free, notes: tidy(l.notes), steps }) } diff --git a/crates/actions/src/as3/mod.rs b/crates/actions/src/as3/mod.rs index 191bd386..31702d3f 100644 --- a/crates/actions/src/as3/mod.rs +++ b/crates/actions/src/as3/mod.rs @@ -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>, +/// 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::>().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, + /// The top-level statements, in order. + pub body: Vec, + /// Functions written in place at the top level (listeners). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub inner: Vec>, + /// The functions it declares (the timeline's, callable from its other frames). + pub functions: Vec>, + /// 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, /// Calls that are ignored (they would reach outside the movie, or do nothing here). pub notes: Vec, + /// 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>, + pub vars: BTreeMap, +} + +impl Decls { + /// From the timeline's compiled scripts, in frame order (top layer first within a frame). + pub fn build<'a>(scripts: impl IntoIterator) -> 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 { + 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> { 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))]); diff --git a/crates/actions/src/as3/parse.rs b/crates/actions/src/as3/parse.rs index ccdea22d..da49786f 100644 --- a/crates/actions/src/as3/parse.rs +++ b/crates/actions/src/as3/parse.rs @@ -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, pub rest: bool, } @@ -56,9 +58,20 @@ pub struct Func { pub name: Option, pub pos: Pos, pub params: Vec, + /// The result type as written (`void`, `int`), when there is one. + pub ret: Option<(String, Pos)>, pub body: Vec, } +/// 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, +} + #[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), If(Expr, Vec, Vec), + /// `for (init; cond; update) body` (`init` a `var` statement or an expression). + For(Option>, Option, Option, Vec), + While(Expr, Vec), + DoWhile(Vec, Expr), + /// `break` and `continue` (without a label). + Break, + Continue, Return(Option), Block(Vec), Empty, @@ -228,12 +248,83 @@ impl<'a> Parser<'a> { } } - /// `: Type` (read and dropped: `*`, `void`, `a.b.C`, `Vector.`). - fn annotation(&mut self) -> R<()> { + /// `: Type` (`*`, `void`, `a.b.C`, `Vector.`), as written. + fn annotation(&mut self) -> R> { 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> { + 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)>> { + 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 { + 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 { diff --git a/crates/actions/src/as3/run.rs b/crates/actions/src/as3/run.rs new file mode 100644 index 00000000..262237fe --- /dev/null +++ b/crates/actions/src/as3/run.rs @@ -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>; + /// Reads a property. + fn get(&mut self, at: &Place, p: Prop) -> Result; + /// Sets an instance property. + fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option>; + /// Sets a text field's text (ADR 0066). + fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option>; + 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; + fn write(&mut self, name: &str, v: Value) -> Result<(), String>; + /// The timeline's function by that name. + fn function(&mut self, name: &str) -> Option>; + /// 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, add: bool) -> Result<(), Option>; + /// 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; + /// The keyboard event's key code. + fn key_code(&mut self) -> Result; +} + +/// The error of a world call: `None` means the world halted (and said so). +fn lift(line: u32, e: Option) -> Stop { + match e { + Some(message) => Stop::Error { line, message }, + None => Stop::Halt, + } +} + +enum Flow { + Normal, + Break, + Continue, + Return(Value), +} + +struct Frame<'f> { + locals: Vec, + /// Each local's type (a write coerces to it). + types: &'f [Ty], + inner: &'f [Arc], +} + +struct Vm<'w> { + w: &'w mut dyn World, + fuel: u64, + depth: usize, + line: u32, +} + +type R = Result; + +/// 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], 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, 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 { + 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 = 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(&self, message: impl Into) -> R { + Err(Stop::Error { line: self.line, message: message.into() }) + } + + fn block(&mut self, list: &[Stmt], fr: &mut Frame<'_>) -> R { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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, args: &[Expr], caller: &mut Frame<'_>) -> R { + 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 = 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::()), + 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", + } +} diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs index 7ce85de8..2cc2e506 100644 --- a/crates/actions/src/as3/tests.rs +++ b/crates/actions/src/as3/tests.rs @@ -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 { - 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, + props: BTreeMap<(String, &'static str), f64>, + log: Vec, + rng: u32, + key: Option, + frame: u32, + /// Text fields' text, by name. + texts: BTreeMap, } -#[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 = 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 = 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> { + 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 { + 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> { + 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> { + 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 { + 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> { + self.decls.functions.get(name).cloned() + } + fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc, add: bool) -> Result<(), Option> { + 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 { + Ok(a == b) + } + fn key_code(&mut self) -> Result { + 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, 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 { + 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::>(), ["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::>(), [("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 = 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 = (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")); +} diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 48db7349..8381a608 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -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 diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index ab8999a5..e8c8352d 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -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 { - 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 { - 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) -> Result { - 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, -} - -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); - } } diff --git a/crates/audio/src/mix.rs b/crates/audio/src/mix.rs index 33fdb5e5..75678c41 100644 --- a/crates/audio/src/mix.rs +++ b/crates/audio/src/mix.rs @@ -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)) } diff --git a/crates/audio/src/mp3.rs b/crates/audio/src/mp3.rs deleted file mode 100644 index 63a8ece5..00000000 --- a/crates/audio/src/mp3.rs +++ /dev/null @@ -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 { - let mut r = nanomp3::SliceReader::::new(data); - let mut col: Option = None; - let mut rate = 0; - let mut buf: Vec = 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) -} diff --git a/crates/audio/src/player.rs b/crates/audio/src/player.rs index 0a2a8266..0fb87105 100644 --- a/crates/audio/src/player.rs +++ b/crates/audio/src/player.rs @@ -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, + /// Event sounds carried on after a jump or the end, on their own clock (`tail_pos`). + tails: Vec, + 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, + tail_scratch: Vec, } 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> { 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> { + 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()); + } + } + } } diff --git a/crates/audio/src/vorbis.rs b/crates/audio/src/vorbis.rs deleted file mode 100644 index 65c200a5..00000000 --- a/crates/audio/src/vorbis.rs +++ /dev/null @@ -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 { - 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::>() { - 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) -} diff --git a/crates/audio/src/wav.rs b/crates/audio/src/wav.rs index c063b34f..203fc9ab 100644 --- a/crates/audio/src/wav.rs +++ b/crates/audio/src/wav.rs @@ -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 { - Some(u16::from_le_bytes(d.get(at..at + 2)?.try_into().ok()?)) -} - -fn u32_at(d: &[u8], at: usize) -> Option { - 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 { - 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 { - 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> { @@ -166,29 +63,34 @@ pub fn append(out: &mut Vec, 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 { - 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 = vec![0, 1, -1, 32_767, -32_768, 12_345, -54, 7]; let f: Vec = 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(); diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index cbd943a9..11d6573e 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -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 diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 42a4cc5b..f0bd8dff 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -18,10 +18,26 @@ USAGE: anicraft-cli render --out [--frame N] [--scale S] anicraft-cli render-seq --out-dir [--from A] [--to B] [--scale S] anicraft-cli gif --out [--from A] [--to B] [--scale S] [--overwrite yes] + anicraft-cli apng|webp --out [--from A] [--to B] [--scale S] + [--loop forever|N] [--background yes] [--overwrite yes] + full colour with real transparency (WebP: lossless) + anicraft-cli export --format --out [--from A] [--to B] [--frame N] + [--options ''] [--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 [--save ] + a JSON array of {cmd, params}, or a saved command + (one undo step; nothing changes if a step fails) anicraft-cli exec [] [--save ] anicraft-cli new --out [--width W] [--height H] [--fps F] + anicraft-cli guide --out writes the user guide as HTML pages (open index.html) + anicraft-cli guide search [--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 { 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 { let list: Vec = 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::("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 = 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 = 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 , or search ")?; + 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 { } 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 ")?; + "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 "))?; 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 { 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::().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 ")?; @@ -199,7 +262,16 @@ pub fn run(argv: &[String]) -> Result { 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 = 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 = 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 { } } +/// `export --format `: 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 { + 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 (anicraft-cli formats lists them)")?; + let out = a.flag("out").ok_or("export needs --out ")?; + 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 )", 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 = 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(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 { 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(">()); + 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()); } } diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index f47c109f..1f75a22f 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -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 diff --git a/crates/doc/src/aids.rs b/crates/doc/src/aids.rs new file mode 100644 index 00000000..ff7913e9 --- /dev/null +++ b/crates/doc/src/aids.rs @@ -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 { + 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 { + 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) { + 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); + } +} diff --git a/crates/doc/src/armature.rs b/crates/doc/src/armature.rs index 61d9123d..fcfd4bea 100644 --- a/crates/doc/src/armature.rs +++ b/crates/doc/src/armature.rs @@ -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 { + self.sanitized_within(MAX_LIMIT) + } + + /// Finite, ordered and within `±bound`; `None` when nothing sane is left. + pub fn sanitized_within(self, bound: f32) -> Option { 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 { + (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, + /// 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, + /// The bone's spring (ADR 0084); `None`: none. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spring: Option, } 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, 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 { + 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, + /// 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, + /// 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 { + 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 { + 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 = kept.iter().map(|b| b.child).collect(); - let mut placed: HashSet = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(); + let mut placed: HashSet = 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], pose: &Pose) -> HashMap { let mut world: HashMap = 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], 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], 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 { 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], pose: &Pose) -> Vec { - let world: HashMap = 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 = 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], pose: &Pose, id: BoneId, p: Vec2) -> Option { + 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], pose: &Pose, id: BoneId, local: Vec2, target: Vec2) -> Option { 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, 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, 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], 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], 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)] diff --git a/crates/doc/src/armature_tests.rs b/crates/doc/src/armature_tests.rs index 56067e98..79df7fd1 100644 --- a/crates/doc/src/armature_tests.rs +++ b/crates/doc/src/armature_tests.rs @@ -19,14 +19,14 @@ fn instance(id: ElementId, x: f32, y: f32) -> Arc { 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>) { - 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> = { + 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}]"#); +} diff --git a/crates/doc/src/bitmap.rs b/crates/doc/src/bitmap.rs index 0ec3c6ff..47e6e65b 100644 --- a/crates/doc/src/bitmap.rs +++ b/crates/doc/src/bitmap.rs @@ -43,13 +43,25 @@ pub struct Bitmap { /// The image as PNG. #[serde(with = "base64_bytes")] pub png: Arc>, + /// 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>>>, } +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, width: u32, height: u32, rgba: Vec) -> Option { + 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> { 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 { - 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 = 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) -> Result, 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> { - 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> { @@ -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 { - 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 = (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] diff --git a/crates/doc/src/camera.rs b/crates/doc/src/camera.rs index 2b6385a7..9d54a697 100644 --- a/crates/doc/src/camera.rs +++ b/crates/doc/src/camera.rs @@ -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 { + 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 { + 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 { + let n = self.layers.len(); + let mut order: Vec = (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 = 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); diff --git a/crates/doc/src/camera_tests.rs b/crates/doc/src/camera_tests.rs index 7854e915..7b0f1a9d 100644 --- a/crates/doc/src/camera_tests.rs +++ b/crates/doc/src/camera_tests.rs @@ -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::>(); + 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)); +} diff --git a/crates/doc/src/color_effect.rs b/crates/doc/src/color_effect.rs new file mode 100644 index 00000000..ad099ad3 --- /dev/null +++ b/crates/doc/src/color_effect.rs @@ -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 = -1.0..=1.0; +pub const ADVANCED_ADD: std::ops::RangeInclusive = -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 { + (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 { + 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, brightness: Option, tint: Option<(Rgba, f32)>, advanced: Option) -> 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, + #[serde(default, skip_serializing_if = "Option::is_none")] + brightness: Option, + #[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(&self, s: S) -> Result { + 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: D) -> Result { + 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::(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)); + } +} diff --git a/crates/doc/src/easing.rs b/crates/doc/src/easing.rs index 1d538803..82bee409 100644 --- a/crates/doc/src/easing.rs +++ b/crates/doc/src/easing.rs @@ -1,9 +1,153 @@ -//! Easing curves for tweens. +//! Easing curves for tweens (ADR 0016, ADR 0081). +//! +//! An [`Easing`] maps linear tween progress `t ∈ [0, 1]` to eased progress, and every one is a +//! pure function of `t`. There are three kinds: +//! +//! * **Presets**: no ease (linear), the Classic Ease slider (strength −100 … +100), and nine +//! families, each In, Out and In Out: Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and +//! Elastic. The formulas are the classic public easing equations (Robert Penner's, as widely +//! published; credited in `ATTRIBUTION.md`): `In(t)` per family, `Out(t) = 1 − In(1 − t)` and +//! `InOut` as In over the first half and Out over the second. +//! * **One cubic Bézier** (`CubicBezier`, CSS-style handles relative to the segment's box), as +//! the Motion Editor's handles and older files make. +//! * **A custom ease** ([`CustomEase`]): a curve of several Bézier segments from (0, 0) to +//! (1, 1), as the graph editor draws it. Time never runs backwards (x is monotonic along the +//! whole curve); values may overshoot 0..1. +//! * **A sampled ease** ([`SampledEase`], ADR 0088): a table of values an ease plug-in's +//! function gave when it loaded, read back by linear interpolation. The document keeps the +//! table, so it plays the same on a computer without the plug-in. +use anicraft_geom::Vec2; use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +/// Most points (anchors) a custom ease keeps; longer curves are thinned evenly. +pub const MAX_EASE_POINTS: usize = 64; +/// Values a custom ease (and its handles) may reach: overshoot well past 0..1, never unbounded. +pub const MAX_EASE_Y: f32 = 10.0; +/// Most points read from a file or a command before thinning (bounds the sort). +const MAX_EASE_INPUT: usize = 65_536; +/// The Back family's overshoot (about 10 %). +const BACK: f64 = 1.701_58; + +/// The families of named eases. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EaseFamily { + Quad, + Cubic, + Quart, + Quint, + Sine, + Back, + Circ, + Bounce, + Elastic, +} + +impl EaseFamily { + pub const ALL: [EaseFamily; 9] = [EaseFamily::Quad, EaseFamily::Cubic, EaseFamily::Quart, EaseFamily::Quint, EaseFamily::Sine, EaseFamily::Back, EaseFamily::Circ, EaseFamily::Bounce, EaseFamily::Elastic]; + + /// The family's name as the ease menus show it. + pub fn label(self) -> &'static str { + match self { + EaseFamily::Quad => "Quad", + EaseFamily::Cubic => "Cubic", + EaseFamily::Quart => "Quart", + EaseFamily::Quint => "Quint", + EaseFamily::Sine => "Sine", + EaseFamily::Back => "Back", + EaseFamily::Circ => "Circ", + EaseFamily::Bounce => "Bounce", + EaseFamily::Elastic => "Elastic", + } + } + + /// The ease in, `In(t)`, in double precision. + fn ease_in(self, t: f64) -> f64 { + use std::f64::consts::PI; + match self { + EaseFamily::Quad => t * t, + EaseFamily::Cubic => t * t * t, + EaseFamily::Quart => t * t * t * t, + EaseFamily::Quint => t * t * t * t * t, + EaseFamily::Sine => 1.0 - (t * PI * 0.5).cos(), + EaseFamily::Back => (BACK + 1.0) * t * t * t - BACK * t * t, + EaseFamily::Circ => 1.0 - (1.0 - t * t).max(0.0).sqrt(), + EaseFamily::Bounce => 1.0 - bounce_out(1.0 - t), + EaseFamily::Elastic => { + if t <= 0.0 { + 0.0 + } else if t >= 1.0 { + 1.0 + } else { + -(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 10.75) * (2.0 * PI / 3.0)).sin() + } + } + } + } + + /// Where the ease in changes formula (other than 0 and 1): Bounce is four parabolas. + fn breaks_in(self) -> &'static [f64] { + match self { + // 1 − the Out breakpoints (1/2.75, 2/2.75, 2.5/2.75), in order. + EaseFamily::Bounce => &[0.25 / 2.75, 0.75 / 2.75, 1.75 / 2.75], + _ => &[], + } + } + + /// Bézier segments per ease in that draw it to within a hair (see [`Easing::to_custom`]); + /// cubic polynomials (Quad, Cubic, Back) and the parabolas of Bounce are exact with one. + fn pieces_in(self) -> usize { + match self { + EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce | EaseFamily::Circ => 1, + EaseFamily::Quart | EaseFamily::Quint | EaseFamily::Sine => 4, + EaseFamily::Elastic => 24, + } + } +} + +fn bounce_out(t: f64) -> f64 { + const N: f64 = 7.5625; + const D: f64 = 2.75; + if t < 1.0 / D { + N * t * t + } else if t < 2.0 / D { + let u = t - 1.5 / D; + N * u * u + 0.75 + } else if t < 2.5 / D { + let u = t - 2.25 / D; + N * u * u + 0.9375 + } else { + let u = t - 2.625 / D; + N * u * u + 0.984_375 + } +} + +/// Which way a named ease eases. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EaseDir { + In, + Out, + InOut, +} + +impl EaseDir { + pub const ALL: [EaseDir; 3] = [EaseDir::In, EaseDir::Out, EaseDir::InOut]; + + pub fn label(self) -> &'static str { + match self { + EaseDir::In => "In", + EaseDir::Out => "Out", + EaseDir::InOut => "In Out", + } + } +} /// Maps linear tween progress `t ∈ [0, 1]` to eased progress. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +/// +/// The unit variants are the named presets (their names are the file format and the +/// commands' preset names); older files hold the first seven and `Classic`/`CubicBezier`. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub enum Easing { #[default] Linear, @@ -17,90 +161,383 @@ pub enum Easing { Classic(f32), /// CSS-style cubic Bézier through (0,0), (x1,y1), (x2,y2), (1,1). CubicBezier(f32, f32, f32, f32), + QuartIn, + QuartOut, + QuartInOut, + QuintIn, + QuintOut, + QuintInOut, + SineIn, + SineOut, + SineInOut, + BackIn, + BackOut, + BackInOut, + CircIn, + CircOut, + CircInOut, + BounceIn, + BounceOut, + BounceInOut, + ElasticIn, + ElasticOut, + ElasticInOut, + /// A curve of several Bézier segments (the graph editor's), shared when copied. + Custom(Arc), + /// An ease plug-in's curve, sampled into a table when the plug-in loaded (ADR 0088). + Sampled(Arc), +} + +/// A named ease the artist saved in the document (ADR 0081): any ease, usually a custom +/// curve, offered with the presets to every classic tween and motion-tween property. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SavedEase { + pub name: String, + pub ease: Easing, +} + +/// Most saved eases a document keeps, and the longest name. +pub const MAX_SAVED_EASES: usize = 256; +pub const MAX_EASE_NAME: usize = 64; + +/// A saved ease's name as kept: trimmed, at most [`MAX_EASE_NAME`] characters; `None` when +/// nothing is left. +pub fn ease_name(name: &str) -> Option { + let n: String = name.trim().chars().filter(|c| !c.is_control()).take(MAX_EASE_NAME).collect(); + let n = n.trim().to_string(); + (!n.is_empty()).then_some(n) +} + +/// Saved eases as a document keeps them: named, each name once (the first wins, ignoring +/// case), at most [`MAX_SAVED_EASES`]. +pub fn sanitized_eases(eases: &[SavedEase]) -> Vec { + let mut out: Vec = Vec::new(); + for e in eases { + let Some(name) = ease_name(&e.name) else { continue }; + if out.len() >= MAX_SAVED_EASES || out.iter().any(|o| o.name.to_lowercase() == name.to_lowercase()) { + continue; + } + out.push(SavedEase { name, ease: e.ease.clone() }); + } + out } impl Easing { - /// Presets shown in the UI, in menu order. - pub const PRESETS: [(&'static str, Easing); 8] = [ - ("Linear", Easing::Linear), - ("Ease in (quad)", Easing::QuadIn), - ("Ease out (quad)", Easing::QuadOut), - ("Ease in-out (quad)", Easing::QuadInOut), - ("Ease in (cubic)", Easing::CubicIn), - ("Ease out (cubic)", Easing::CubicOut), - ("Ease in-out (cubic)", Easing::CubicInOut), - ("Smooth (bezier)", Easing::CubicBezier(0.25, 0.1, 0.25, 1.0)), - ]; + /// Named eases with fixed shapes, for labels and the `smooth` command name (the menus list + /// [`Easing::LINEAR_LABEL`], Classic Ease and the families instead). + pub const PRESETS: [(&'static str, Easing); 2] = [("Linear", Easing::Linear), ("Smooth (bezier)", Easing::CubicBezier(0.25, 0.1, 0.25, 1.0))]; + pub const LINEAR_LABEL: &'static str = "Linear"; + /// The named ease of `family` easing `dir`. + pub fn preset(family: EaseFamily, dir: EaseDir) -> Easing { + use EaseDir::*; + use EaseFamily::*; + match (family, dir) { + (Quad, In) => Easing::QuadIn, + (Quad, Out) => Easing::QuadOut, + (Quad, InOut) => Easing::QuadInOut, + (Cubic, In) => Easing::CubicIn, + (Cubic, Out) => Easing::CubicOut, + (Cubic, InOut) => Easing::CubicInOut, + (Quart, In) => Easing::QuartIn, + (Quart, Out) => Easing::QuartOut, + (Quart, InOut) => Easing::QuartInOut, + (Quint, In) => Easing::QuintIn, + (Quint, Out) => Easing::QuintOut, + (Quint, InOut) => Easing::QuintInOut, + (Sine, In) => Easing::SineIn, + (Sine, Out) => Easing::SineOut, + (Sine, InOut) => Easing::SineInOut, + (Back, In) => Easing::BackIn, + (Back, Out) => Easing::BackOut, + (Back, InOut) => Easing::BackInOut, + (Circ, In) => Easing::CircIn, + (Circ, Out) => Easing::CircOut, + (Circ, InOut) => Easing::CircInOut, + (Bounce, In) => Easing::BounceIn, + (Bounce, Out) => Easing::BounceOut, + (Bounce, InOut) => Easing::BounceInOut, + (Elastic, In) => Easing::ElasticIn, + (Elastic, Out) => Easing::ElasticOut, + (Elastic, InOut) => Easing::ElasticInOut, + } + } + + /// The family and direction of a named ease. + pub fn family(&self) -> Option<(EaseFamily, EaseDir)> { + use EaseDir::*; + use EaseFamily::*; + Some(match self { + Easing::QuadIn => (Quad, In), + Easing::QuadOut => (Quad, Out), + Easing::QuadInOut => (Quad, InOut), + Easing::CubicIn => (Cubic, In), + Easing::CubicOut => (Cubic, Out), + Easing::CubicInOut => (Cubic, InOut), + Easing::QuartIn => (Quart, In), + Easing::QuartOut => (Quart, Out), + Easing::QuartInOut => (Quart, InOut), + Easing::QuintIn => (Quint, In), + Easing::QuintOut => (Quint, Out), + Easing::QuintInOut => (Quint, InOut), + Easing::SineIn => (Sine, In), + Easing::SineOut => (Sine, Out), + Easing::SineInOut => (Sine, InOut), + Easing::BackIn => (Back, In), + Easing::BackOut => (Back, Out), + Easing::BackInOut => (Back, InOut), + Easing::CircIn => (Circ, In), + Easing::CircOut => (Circ, Out), + Easing::CircInOut => (Circ, InOut), + Easing::BounceIn => (Bounce, In), + Easing::BounceOut => (Bounce, Out), + Easing::BounceInOut => (Bounce, InOut), + Easing::ElasticIn => (Elastic, In), + Easing::ElasticOut => (Elastic, Out), + Easing::ElasticInOut => (Elastic, InOut), + Easing::Linear | Easing::Classic(_) | Easing::CubicBezier(..) | Easing::Custom(_) | Easing::Sampled(_) => return None, + }) + } + + /// Every named preset: no ease, then each family In, Out, In Out. + pub fn named() -> impl Iterator { + std::iter::once(Easing::Linear).chain(EaseFamily::ALL.into_iter().flat_map(|f| EaseDir::ALL.into_iter().map(move |d| Easing::preset(f, d)))) + } + + /// The preset's name in commands and files (`"QuadIn"`, `"ElasticInOut"`), `None` for + /// eases with values. + pub fn name(&self) -> Option { + match self { + Easing::Linear => Some("Linear".into()), + _ => self.family().map(|(f, d)| format!("{}{}", f.label(), d.label().replace(' ', ""))), + } + } + + /// The preset named `name`, ignoring case, spaces, `-` and `_` (`"back in out"`), with + /// the older aliases (`none`, `easein`, `easeout`, `easeinout`, `smooth`). + pub fn from_name(name: &str) -> Option { + let key: String = name.chars().filter(|c| !matches!(c, '-' | '_' | ' ')).flat_map(char::to_lowercase).collect(); + match key.as_str() { + "none" | "noease" => return Some(Easing::Linear), + "easein" => return Some(Easing::QuadIn), + "easeout" => return Some(Easing::QuadOut), + "easeinout" => return Some(Easing::QuadInOut), + "smooth" => return Some(Easing::CubicBezier(0.25, 0.1, 0.25, 1.0)), + _ => {} + } + Easing::named().find(|e| e.name().is_some_and(|n| n.to_lowercase() == key)) + } + + /// The English label menus and reports show. pub fn label(&self) -> String { match self { + Easing::Linear => Easing::LINEAR_LABEL.to_string(), Easing::Classic(s) => format!("Classic {s:+.0}"), Easing::CubicBezier(a, b, c, d) => { Easing::PRESETS.iter().find(|(_, e)| e == self).map_or_else(|| format!("Bezier({a:.2}, {b:.2}, {c:.2}, {d:.2})"), |(n, _)| (*n).to_string()) } - other => Easing::PRESETS.iter().find(|(_, e)| e == other).map_or("Custom", |(n, _)| n).to_string(), + Easing::Custom(_) => "Custom".to_string(), + Easing::Sampled(s) => s.name().to_string(), + other => other.family().map_or_else(|| "Custom".to_string(), |(f, d)| format!("{} {}", f.label(), d.label())), } } - /// The cubic Bézier `(x1, y1, x2, y2)` that draws this ease, as the Motion Editor's handles: - /// exact for linear, the quad and cubic in/out eases and the classic slider; the two in-out - /// polynomials (two curves joined at the middle) get their usual one-curve approximations. - pub fn as_bezier(&self) -> (f32, f32, f32, f32) { + /// The single cubic Bézier `(x1, y1, x2, y2)` that draws this ease, as the Motion Editor's + /// handles: exact for linear, the classic slider, the Quad, Cubic and Back eases in and + /// out, and a custom ease of one segment; the Quad and Cubic in-outs get their usual + /// one-curve approximations. `None` for eases one curve can't draw (Bounce, Elastic, the + /// other families, and custom eases of several segments): they are edited in the graph. + pub fn as_bezier(&self) -> Option<(f32, f32, f32, f32)> { const THIRD: f32 = 1.0 / 3.0; - match *self { + const B: f32 = BACK as f32; + Some(match self { Easing::Linear => (THIRD, THIRD, 2.0 * THIRD, 2.0 * THIRD), - // t² and t³ and their mirrors, with x(s) = s. + // t², t³ and (c+1)t³ − ct² and their mirrors, with x(s) = s. Easing::QuadIn => (THIRD, 0.0, 2.0 * THIRD, THIRD), Easing::QuadOut => (THIRD, 2.0 * THIRD, 2.0 * THIRD, 1.0), Easing::CubicIn => (THIRD, 0.0, 2.0 * THIRD, 0.0), Easing::CubicOut => (THIRD, 1.0, 2.0 * THIRD, 1.0), + Easing::BackIn => (THIRD, 0.0, 2.0 * THIRD, -B * THIRD), + Easing::BackOut => (THIRD, 1.0 + B * THIRD, 2.0 * THIRD, 1.0), Easing::QuadInOut => (0.45, 0.0, 0.55, 1.0), Easing::CubicInOut => (0.65, 0.0, 0.35, 1.0), Easing::Classic(strength) => { // The quadratic 2(1 − t)t·c + t², raised to a cubic. - let s = if strength.is_finite() { strength.clamp(-100.0, 100.0) / 100.0 } else { 0.0 }; - let c = 0.5 + 0.5 * s; + let c = 0.5 + 0.5 * classic_strength(*strength); (THIRD, 2.0 * c * THIRD, 2.0 * THIRD, (2.0 * c + 1.0) * THIRD) } - Easing::CubicBezier(a, b, c, d) => (a, b, c, d), - } + Easing::CubicBezier(a, b, c, d) => (*a, *b, *c, *d), + Easing::Custom(c) => match c.points() { + [a, b] => (a.out.x, a.out.y, b.at.x + b.h_in.x, b.at.y + b.h_in.y), + _ => return None, + }, + _ => return None, + }) } pub fn apply(&self, t: f32) -> f32 { let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; - match *self { + match self { Easing::Linear => t, - Easing::QuadIn => t * t, - Easing::QuadOut => t * (2.0 - t), - Easing::QuadInOut => { - if t < 0.5 { - 2.0 * t * t - } else { - -1.0 + (4.0 - 2.0 * t) * t - } - } - Easing::CubicIn => t * t * t, - Easing::CubicOut => { - let u = t - 1.0; - u * u * u + 1.0 - } - Easing::CubicInOut => { - if t < 0.5 { - 4.0 * t * t * t - } else { - let u = 2.0 * t - 2.0; - 0.5 * u * u * u + 1.0 - } - } Easing::Classic(strength) => { // Quadratic Bézier with the middle control point moved by `strength`. - let s = if strength.is_finite() { strength.clamp(-100.0, 100.0) / 100.0 } else { 0.0 }; - let c = 0.5 + 0.5 * s; // y of control point at x = 0.5 + let c = 0.5 + 0.5 * classic_strength(*strength); // y of control point at x = 0.5 2.0 * (1.0 - t) * t * c + t * t } - Easing::CubicBezier(x1, y1, x2, y2) => cubic_bezier(t, x1, y1, x2, y2), + Easing::CubicBezier(x1, y1, x2, y2) => cubic_bezier(t, *x1, *y1, *x2, *y2), + Easing::Custom(c) => c.apply(t), + Easing::Sampled(s) => s.apply(t), + named => match named.family() { + Some((f, d)) => eval_named(f, d, f64::from(t)) as f32, + None => t, + }, } } + + /// This ease as a custom curve for the graph editor: exact for linear, Classic, a Bézier, + /// the Quad, Cubic, Back and Bounce families and custom eases; Circ is two circular arcs, + /// and Quart, Quint, Sine and Elastic are fitted by matching values and slopes at a few + /// points (all within 0.5 % of the range everywhere, see the tests). A sampled ease becomes + /// the straight segments through 48 of its samples. + pub fn to_custom(&self) -> CustomEase { + match self { + Easing::Custom(c) => (**c).clone(), + Easing::Sampled(s) => s.to_polyline(), + Easing::Linear => CustomEase::linear(), + Easing::Classic(_) | Easing::CubicBezier(..) => { + let Some((x1, y1, x2, y2)) = self.as_bezier() else { return CustomEase::linear() }; + CustomEase::from_bezier(x1, y1, x2, y2) + } + named => match named.family() { + Some((f, d)) => fit_named(f, d), + None => CustomEase::linear(), + }, + } + } + + /// The custom curve, when this is one. + pub fn custom(&self) -> Option<&CustomEase> { + match self { + Easing::Custom(c) => Some(c), + _ => None, + } + } + + /// The sampled curve, when this is a plug-in's ease. + pub fn sampled(&self) -> Option<&SampledEase> { + match self { + Easing::Sampled(s) => Some(s), + _ => None, + } + } +} + +fn classic_strength(s: f32) -> f32 { + if s.is_finite() { s.clamp(-100.0, 100.0) / 100.0 } else { 0.0 } +} + +fn eval_named(f: EaseFamily, d: EaseDir, t: f64) -> f64 { + match d { + EaseDir::In => f.ease_in(t), + EaseDir::Out => 1.0 - f.ease_in(1.0 - t), + EaseDir::InOut => { + if t < 0.5 { + 0.5 * f.ease_in(2.0 * t) + } else { + 1.0 - 0.5 * f.ease_in(2.0 - 2.0 * t) + } + } + } +} + +/// The slope of `y` at `x`, from inside `[lo, hi]`: one-sided, a step in from `x` (so a +/// value pinned at an end, as Elastic's are, doesn't count), exact for parabolas but for that +/// step. +fn slope(y: &dyn Fn(f64) -> f64, x: f64, lo: f64, hi: f64) -> f64 { + const H: f64 = 1e-6; + let s = if x + 3.0 * H <= hi { + let d = (-3.0 * y(x + H) + 4.0 * y(x + 2.0 * H) - y(x + 3.0 * H)) / (2.0 * H); + let d2 = (y(x + H) - 2.0 * y(x + 2.0 * H) + y(x + 3.0 * H)) / (H * H); + d - d2 * H + } else if x - 3.0 * H >= lo { + let d = (3.0 * y(x - H) - 4.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (2.0 * H); + let d2 = (y(x - H) - 2.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (H * H); + d + d2 * H + } else { + 0.0 + }; + if s.is_finite() { s } else { 0.0 } +} + +/// The ease in of `f` as Bézier points: Hermite segments (value and slope matched at each +/// end, so exact for cubic polynomials and for each parabola of Bounce), except Circ, whose +/// quarter circle is two 45° arcs (within 4·10⁻⁶ of the circle). +fn fit_in(f: EaseFamily) -> Vec { + let pt = |x: f64, y: f64, i: (f64, f64), o: (f64, f64)| EasePoint { at: Vec2::new(x as f32, y as f32), h_in: Vec2::new(i.0 as f32, i.1 as f32), out: Vec2::new(o.0 as f32, o.1 as f32), smooth: false }; + if f == EaseFamily::Circ { + // The circle about (0, 1) from (0, 0) to (1, 1); each arc's handles are k = 4/3·tan(φ/4) + // long along the tangents. + let k = 4.0 / 3.0 * (std::f64::consts::PI / 16.0).tan(); + let c = std::f64::consts::FRAC_1_SQRT_2; + return vec![pt(0.0, 0.0, (0.0, 0.0), (k, 0.0)), pt(c, 1.0 - c, (-k * c, -k * c), (k * c, k * c)), pt(1.0, 1.0, (0.0, -k), (0.0, 0.0))]; + } + let y = move |t: f64| f.ease_in(t); + let mut xs: Vec = Vec::new(); + let pieces = f.pieces_in(); + let bounds: Vec = std::iter::once(0.0).chain(f.breaks_in().iter().copied()).chain(std::iter::once(1.0)).collect(); + for w in bounds.windows(2) { + if let [a, c] = w { + xs.extend((0..pieces).map(|k| a + (c - a) * k as f64 / pieces as f64)); + } + } + xs.push(1.0); + let mut pts: Vec = xs.iter().map(|&x| pt(x, y(x), (0.0, 0.0), (0.0, 0.0))).collect(); + for i in 0..xs.len().saturating_sub(1) { + let (Some(&a), Some(&b)) = (xs.get(i), xs.get(i + 1)) else { continue }; + let h = (b - a) / 3.0; + let (sa, sb) = (slope(&y, a, a, b), slope(&y, b, a, b)); + if let Some(p) = pts.get_mut(i) { + p.out = Vec2::new(h as f32, (sa * h) as f32); + } + if let Some(p) = pts.get_mut(i + 1) { + p.h_in = Vec2::new(-h as f32, (-sb * h) as f32); + } + } + pts +} + +/// The curve turned half a turn about (½, ½): an ease in becomes the ease out. +fn mirrored(pts: &[EasePoint]) -> Vec { + pts.iter().rev().map(|p| EasePoint { at: Vec2::new(1.0 - p.at.x, 1.0 - p.at.y), h_in: -p.out, out: -p.h_in, smooth: p.smooth }).collect() +} + +fn scaled(pts: &[EasePoint], by: f32, from: Vec2) -> Vec { + pts.iter().map(|p| EasePoint { at: from + p.at * by, h_in: p.h_in * by, out: p.out * by, smooth: p.smooth }).collect() +} + +/// A named ease as a custom curve (see [`Easing::to_custom`]). +fn fit_named(f: EaseFamily, d: EaseDir) -> CustomEase { + let ease_in = fit_in(f); + let mut pts = match d { + EaseDir::In => ease_in, + EaseDir::Out => mirrored(&ease_in), + EaseDir::InOut => { + let mut a = scaled(&ease_in, 0.5, Vec2::ZERO); + let b = scaled(&mirrored(&ease_in), 0.5, Vec2::new(0.5, 0.5)); + // The two halves meet at (½, ½): one point, the first half's in, the second's out. + if let (Some(last), Some(first)) = (a.last_mut(), b.first()) { + last.out = first.out; + } + a.extend(b.into_iter().skip(1)); + a + } + }; + // Points where the slope carries on are smooth (Bounce's floor hits are corners). + let n = pts.len(); + for (i, p) in pts.iter_mut().enumerate() { + p.smooth = i > 0 && i + 1 < n && p.h_in.length() > 1e-9 && p.out.length() > 1e-9 && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-3; + } + CustomEase::new(pts) } fn cubic_bezier(x: f32, x1: f32, y1: f32, x2: f32, y2: f32) -> f32 { @@ -109,112 +546,459 @@ fn cubic_bezier(x: f32, x1: f32, y1: f32, x2: f32, y2: f32) -> f32 { } // x control points must stay in [0, 1] so x(t) is monotonic. let (x1, x2) = (x1.clamp(0.0, 1.0), x2.clamp(0.0, 1.0)); - let bez = |t: f32, p1: f32, p2: f32| { - let mt = 1.0 - t; - 3.0 * mt * mt * t * p1 + 3.0 * mt * t * t * p2 + t * t * t - }; - let dbez = |t: f32, p1: f32, p2: f32| { - let mt = 1.0 - t; - 3.0 * mt * mt * p1 + 6.0 * mt * t * (p2 - p1) + 3.0 * t * t * (1.0 - p2) - }; - // Newton, then bisection as a fallback. - let mut t = x; - for _ in 0..8 { - let err = bez(t, x1, x2) - x; - if err.abs() < 1e-6 { - return bez(t, y1, y2); - } - let d = dbez(t, x1, x2); - if d.abs() < 1e-6 { + let s = solve_monotonic(f64::from(x), [0.0, f64::from(x1), f64::from(x2), 1.0]); + bez(s, [0.0, f64::from(y1), f64::from(y2), 1.0]) as f32 +} + +fn bez(t: f64, p: [f64; 4]) -> f64 { + let mt = 1.0 - t; + mt * mt * mt * p[0] + 3.0 * mt * mt * t * p[1] + 3.0 * mt * t * t * p[2] + t * t * t * p[3] +} + +fn dbez(t: f64, p: [f64; 4]) -> f64 { + let mt = 1.0 - t; + 3.0 * mt * mt * (p[1] - p[0]) + 6.0 * mt * t * (p[2] - p[1]) + 3.0 * t * t * (p[3] - p[2]) +} + +/// The parameter where the Bézier `p` (non-decreasing: its inner points lie between its ends) +/// reaches `x`: Newton steps kept inside a shrinking bracket, halving when a step leaves it. +fn solve_monotonic(x: f64, p: [f64; 4]) -> f64 { + let (mut lo, mut hi) = (0.0f64, 1.0f64); + let span = p[3] - p[0]; + let mut s = if span > 1e-12 { ((x - p[0]) / span).clamp(0.0, 1.0) } else { 0.5 }; + for _ in 0..48 { + let err = bez(s, p) - x; + if err.abs() < 1e-10 { break; } - t = (t - err / d).clamp(0.0, 1.0); - } - let (mut lo, mut hi) = (0.0f32, 1.0f32); - t = x; - for _ in 0..40 { - let v = bez(t, x1, x2); - if (v - x).abs() < 1e-6 { - break; - } - if v < x { - lo = t; + if err < 0.0 { + lo = s; } else { - hi = t; + hi = s; } - t = 0.5 * (lo + hi); + let d = dbez(s, p); + let next = if d.abs() > 1e-12 { s - err / d } else { f64::NAN }; + s = if next > lo && next < hi { next } else { 0.5 * (lo + hi) }; + } + s +} + +/// A point of a custom ease: where it is (x = time, y = progress), its handles as offsets +/// from it (in towards the previous point, out towards the next), and whether it is smooth +/// (handles in line, moved together) or a corner. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct EasePoint { + pub at: Vec2, + #[serde(rename = "in", default)] + pub h_in: Vec2, + #[serde(default)] + pub out: Vec2, + #[serde(default, skip_serializing_if = "is_false")] + pub smooth: bool, +} + +fn is_false(b: &bool) -> bool { + !*b +} + +/// Which handle of a point. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Handle { + In, + Out, +} + +/// A custom ease: Bézier segments through its points, from (0, 0) to (1, 1). +/// +/// Always valid, however it was made (a file, a command, an edit): 2 to [`MAX_EASE_POINTS`] +/// finite points sorted by x, the ends fixed at (0, 0) and (1, 1), every handle's x between +/// its point and the neighbour it reaches towards (so each segment's x runs forwards, and time +/// never runs backwards), and every value within ±[`MAX_EASE_Y`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(from = "CustomEaseFile")] +pub struct CustomEase { + points: Vec, +} + +#[derive(Deserialize)] +struct CustomEaseFile { + #[serde(default)] + points: Vec, +} + +impl From for CustomEase { + fn from(f: CustomEaseFile) -> CustomEase { + CustomEase::new(f.points) + } +} + +impl Default for CustomEase { + fn default() -> CustomEase { + CustomEase::linear() + } +} + +impl CustomEase { + /// The straight line, its handles a third of the way along. + pub fn linear() -> CustomEase { + CustomEase::from_bezier(1.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0) + } + + /// One segment with CSS-style handles. + pub fn from_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> CustomEase { + CustomEase::new(vec![EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(x1, y1), smooth: false }, EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(x2 - 1.0, y2 - 1.0), out: Vec2::ZERO, smooth: false }]) + } + + /// The curve of absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them, as XFL + /// writes a custom ease): `None` when the count is wrong. + pub fn from_flat(pts: &[Vec2]) -> Option { + if pts.len() < 4 || pts.len() % 3 != 1 || pts.len() > MAX_EASE_INPUT { + return None; + } + let mut out: Vec = Vec::with_capacity(pts.len() / 3 + 1); + for (i, at) in pts.iter().enumerate().step_by(3) { + let h_in = if i == 0 { Vec2::ZERO } else { pts.get(i - 1).map_or(Vec2::ZERO, |c| *c - *at) }; + let h_out = pts.get(i + 1).map_or(Vec2::ZERO, |c| *c - *at); + // Handles in line (opposite ways) make a smooth point, as the editor would draw it. + let smooth = h_in.length() > 1e-6 && h_out.length() > 1e-6 && (h_in.normalized().dot(h_out.normalized()) + 1.0).abs() < 1e-3; + out.push(EasePoint { at: *at, h_in, out: h_out, smooth }); + } + Some(CustomEase::new(out)) + } + + /// A valid curve from any points (see the type's docs): non-finite points are dropped, the + /// rest sorted by x, a curve longer than [`MAX_EASE_POINTS`] thinned evenly, the ends + /// pinned and every handle brought within reach. + pub fn new(mut pts: Vec) -> CustomEase { + pts.truncate(MAX_EASE_INPUT); + pts.retain(|p| p.at.is_finite()); + for p in pts.iter_mut() { + p.at = Vec2::new(p.at.x.clamp(0.0, 1.0), p.at.y.clamp(-MAX_EASE_Y, MAX_EASE_Y)); + if !p.h_in.is_finite() { + p.h_in = Vec2::ZERO; + } + if !p.out.is_finite() { + p.out = Vec2::ZERO; + } + } + pts.sort_by(|a, b| a.at.x.total_cmp(&b.at.x)); + if pts.len() > MAX_EASE_POINTS { + let n = pts.len(); + let keep: Vec = (0..MAX_EASE_POINTS).map(|k| k * (n - 1) / (MAX_EASE_POINTS - 1)).collect(); + pts = keep.into_iter().filter_map(|i| pts.get(i).copied()).collect(); + } + if pts.len() < 2 { + return CustomEase::linear(); + } + if let Some(p) = pts.first_mut() { + p.at = Vec2::ZERO; + } + if let Some(p) = pts.last_mut() { + p.at = Vec2::new(1.0, 1.0); + } + let mut c = CustomEase { points: pts }; + c.clamp_handles(); + c + } + + /// Brings every handle within reach (see the type's docs). + fn clamp_handles(&mut self) { + let xs: Vec = self.points.iter().map(|p| p.at.x).collect(); + let n = self.points.len(); + for (i, p) in self.points.iter_mut().enumerate() { + let prev = if i == 0 { p.at.x } else { xs.get(i - 1).copied().unwrap_or(p.at.x) }; + let next = xs.get(i + 1).copied().unwrap_or(p.at.x); + let y = |h: f32, at: f32| h.clamp(-MAX_EASE_Y - at, MAX_EASE_Y - at); + p.h_in = if i == 0 { Vec2::ZERO } else { Vec2::new(p.h_in.x.clamp(prev - p.at.x, 0.0), y(p.h_in.y, p.at.y)) }; + p.out = if i + 1 == n { Vec2::ZERO } else { Vec2::new(p.out.x.clamp(0.0, next - p.at.x), y(p.out.y, p.at.y)) }; + } + } + + pub fn points(&self) -> &[EasePoint] { + &self.points + } + + /// The control points of segment `i` (from point `i` to point `i + 1`), absolute; the + /// inner points' x always between the ends' (so x runs forwards along it). + pub fn segment(&self, i: usize) -> Option<[Vec2; 4]> { + let (a, b) = (self.points.get(i)?, self.points.get(i + 1)?); + let inner = |p: Vec2| Vec2::new(p.x.clamp(a.at.x, b.at.x.max(a.at.x)), p.y); + Some([a.at, inner(a.at + a.out), inner(b.at + b.h_in), b.at]) + } + + /// The segment that time `t` falls in. + fn segment_at(&self, t: f32) -> usize { + self.points.partition_point(|p| p.at.x <= t).saturating_sub(1).min(self.points.len().saturating_sub(2)) + } + + /// The eased value at time `t` (0 at the start, 1 at the end, anything between, overshoot + /// included). + pub fn apply(&self, t: f32) -> f32 { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + if t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let Some([p0, p1, p2, p3]) = self.segment(self.segment_at(t)) else { return t }; + if p3.x - p0.x <= 1e-9 { + return p3.y; + } + let s = solve_monotonic(f64::from(t), [p0.x, p1.x, p2.x, p3.x].map(f64::from)); + bez(s, [p0.y, p1.y, p2.y, p3.y].map(f64::from)) as f32 + } + + /// Adds a point on the curve at time `t`, leaving its shape exactly as it was (the segment + /// is split in two): the new curve and the point's index. `None` at the ends, on an + /// existing point, or when the curve is full. + pub fn insert_at(&self, t: f32) -> Option<(CustomEase, usize)> { + if !t.is_finite() || t <= 1e-4 || t >= 1.0 - 1e-4 || self.points.len() >= MAX_EASE_POINTS || self.points.iter().any(|p| (p.at.x - t).abs() < 1e-4) { + return None; + } + let i = self.segment_at(t); + let [p0, p1, p2, p3] = self.segment(i)?; + let s = solve_monotonic(f64::from(t), [p0.x, p1.x, p2.x, p3.x].map(f64::from)) as f32; + // de Casteljau at s. + let (a, b, c) = (p0.lerp(p1, s), p1.lerp(p2, s), p2.lerp(p3, s)); + let (d, e) = (a.lerp(b, s), b.lerp(c, s)); + let m = d.lerp(e, s); + let mut pts = self.points.clone(); + if let Some(q) = pts.get_mut(i) { + q.out = a - p0; + } + if let Some(q) = pts.get_mut(i + 1) { + q.h_in = c - p3; + } + pts.insert(i + 1, EasePoint { at: m, h_in: d - m, out: e - m, smooth: true }); + Some((CustomEase::new(pts), i + 1)) + } + + /// Moves point `i` (not an end) to `to`, its handles with it; its x stays between its + /// neighbours' so time keeps running forwards. `None` for an end or a missing point. + pub fn move_point(&self, i: usize, to: Vec2) -> Option { + if i == 0 || i + 1 >= self.points.len() || !to.is_finite() { + return None; + } + let (lo, hi) = (self.points.get(i - 1)?.at.x, self.points.get(i + 1)?.at.x); + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + p.at = Vec2::new(to.x.clamp(lo, hi), to.y.clamp(-MAX_EASE_Y, MAX_EASE_Y)); + c.clamp_handles(); + Some(c) + } + + /// Moves handle `which` of point `i` to `to` (absolute); a smooth point's other handle + /// turns to stay in line, keeping its length. `None` for a handle the point doesn't have + /// (the first point's in, the last's out). + pub fn move_handle(&self, i: usize, which: Handle, to: Vec2) -> Option { + let n = self.points.len(); + if !to.is_finite() || i >= n || (which == Handle::In && i == 0) || (which == Handle::Out && i + 1 == n) { + return None; + } + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + let off = to - p.at; + match which { + Handle::In => p.h_in = off, + Handle::Out => p.out = off, + } + c.clamp_handles(); + if let Some(p) = c.points.get_mut(i).filter(|p| p.smooth && i > 0 && i + 1 < n) { + let (moved, other) = match which { + Handle::In => (p.h_in, &mut p.out), + Handle::Out => (p.out, &mut p.h_in), + }; + let dir = moved.normalized(); + if dir != Vec2::ZERO { + *other = -dir * other.length().max(1e-3); + } + } + c.clamp_handles(); + Some(c) + } + + /// Removes point `i` (not an end). `None` for an end or a missing point. + pub fn remove(&self, i: usize) -> Option { + if i == 0 || i + 1 >= self.points.len() { + return None; + } + let mut pts = self.points.clone(); + pts.remove(i); + Some(CustomEase::new(pts)) + } + + /// Makes point `i` smooth (its handles in line with its neighbours' chord, a third of the + /// way to each) or a corner (its handles on the point, so the curve turns sharply there). + pub fn set_smooth(&self, i: usize, smooth: bool) -> Option { + let n = self.points.len(); + let prev = if i == 0 { None } else { self.points.get(i - 1).map(|p| p.at) }; + let next = self.points.get(i + 1).map(|p| p.at); + let mut c = self.clone(); + let p = c.points.get_mut(i)?; + p.smooth = smooth && i > 0 && i + 1 < n; + if smooth { + let (a, b) = (prev.unwrap_or(p.at), next.unwrap_or(p.at)); + let chord = b - a; + let dir = if chord.x > 1e-6 { chord * (1.0 / chord.x) } else { Vec2::new(1.0, 0.0) }; + if prev.is_some() { + p.h_in = -dir * ((p.at.x - a.x) / 3.0); + } + if next.is_some() { + p.out = dir * ((b.x - p.at.x) / 3.0); + } + } else { + p.h_in = Vec2::ZERO; + p.out = Vec2::ZERO; + } + c.clamp_handles(); + Some(c) + } + + /// The flat list of absolute points XFL writes (`[p0, c1, c2, p1, …]`). + pub fn to_flat(&self) -> Vec { + let mut out = Vec::with_capacity(self.points.len() * 3); + for (i, p) in self.points.iter().enumerate() { + if i > 0 { + out.push(p.at + p.h_in); + } + out.push(p.at); + if i + 1 < self.points.len() { + out.push(p.at + p.out); + } + } + out + } +} + +/// Most samples a sampled ease keeps (longer tables are thinned evenly); plug-in eases are +/// sampled at 257 points. +pub const MAX_EASE_SAMPLES: usize = 1025; +/// Points of the custom curve a sampled ease becomes when edited (of [`MAX_EASE_POINTS`]). +pub const POLYLINE_POINTS: usize = 48; +/// Longest plug-in or ease id a sampled ease keeps. +const MAX_EASE_ID: usize = 64; + +/// An ease plug-in's curve as a table (ADR 0088): `values[i]` is the eased progress at +/// `t = i / (n - 1)`, read between samples by linear interpolation, so evaluation is a pure, +/// constant-time function of `t` that needs no plug-in. It remembers its name and where it came +/// from (the plug-in's id and the ease's id), for the ease menu. +/// +/// Always valid, however it was made (a plug-in, a file, a command): 2 to +/// [`MAX_EASE_SAMPLES`] finite values within ±[`MAX_EASE_Y`], starting at exactly 0 and ending +/// at exactly 1. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(from = "SampledEaseFile")] +pub struct SampledEase { + name: String, + plugin: String, + ease: String, + values: Vec, +} + +#[derive(Deserialize)] +struct SampledEaseFile { + #[serde(default)] + name: String, + #[serde(default)] + plugin: String, + #[serde(default)] + ease: String, + #[serde(default)] + values: Vec, +} + +impl From for SampledEase { + fn from(f: SampledEaseFile) -> SampledEase { + SampledEase::new(&f.name, &f.plugin, &f.ease, f.values) + } +} + +/// An id as a sampled ease keeps it: `[A-Za-z0-9._-]`, at most [`MAX_EASE_ID`] characters. +fn ease_id(s: &str) -> String { + s.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')).take(MAX_EASE_ID).collect() +} + +impl SampledEase { + /// A valid table from any values (see the type's docs): a longer table is thinned evenly, + /// a value that isn't finite becomes the straight line's, values are clamped, the ends + /// pinned; fewer than two values make the straight line. + pub fn new(name: &str, plugin: &str, ease: &str, mut values: Vec) -> SampledEase { + if values.len() > MAX_EASE_SAMPLES { + let n = values.len(); + values = (0..MAX_EASE_SAMPLES).filter_map(|k| values.get(k * (n - 1) / (MAX_EASE_SAMPLES - 1)).copied()).collect(); + } + if values.len() < 2 { + values = vec![0.0, 1.0]; + } + let last = (values.len() - 1) as f32; + for (i, v) in values.iter_mut().enumerate() { + *v = if v.is_finite() { v.clamp(-MAX_EASE_Y, MAX_EASE_Y) } else { i as f32 / last }; + } + if let Some(v) = values.first_mut() { + *v = 0.0; + } + if let Some(v) = values.last_mut() { + *v = 1.0; + } + SampledEase { name: ease_name(name).unwrap_or_else(|| "Plug-in ease".to_string()), plugin: ease_id(plugin), ease: ease_id(ease), values } + } + + /// The name the ease menus show. + pub fn name(&self) -> &str { + &self.name + } + /// The id of the plug-in it came from. + pub fn plugin(&self) -> &str { + &self.plugin + } + /// Its id within that plug-in. + pub fn ease(&self) -> &str { + &self.ease + } + pub fn values(&self) -> &[f32] { + &self.values + } + + /// The eased value at time `t`, between the two nearest samples. + pub fn apply(&self, t: f32) -> f32 { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + let last = self.values.len().saturating_sub(1); + if last == 0 { + return t; + } + let x = t * last as f32; + let i = (x.floor() as usize).min(last - 1); + let f = x - i as f32; + let (a, b) = (self.values.get(i).copied().unwrap_or(0.0), self.values.get(i + 1).copied().unwrap_or(1.0)); + a + (b - a) * f + } + + /// The custom curve of straight segments through [`POLYLINE_POINTS`] of its samples, for + /// the graph editor: editing a plug-in's ease makes it a custom ease drawn like it, with + /// room left to add points. + pub fn to_polyline(&self) -> CustomEase { + let n = self.values.len(); + let m = POLYLINE_POINTS.min(n).max(2); + let at: Vec = (0..m) + .map(|k| { + let i = k * (n - 1) / (m - 1); + Vec2::new(i as f32 / (n - 1).max(1) as f32, self.values.get(i).copied().unwrap_or(0.0)) + }) + .collect(); + let pts = at + .iter() + .enumerate() + .map(|(k, p)| { + let prev = if k == 0 { *p } else { at.get(k - 1).copied().unwrap_or(*p) }; + let next = at.get(k + 1).copied().unwrap_or(*p); + EasePoint { at: *p, h_in: (prev - *p) * (1.0 / 3.0), out: (next - *p) * (1.0 / 3.0), smooth: false } + }) + .collect(); + CustomEase::new(pts) } - bez(t, y1, y2) } #[cfg(test)] -mod tests { - use super::*; - - const ALL: [Easing; 10] = [ - Easing::Linear, - Easing::QuadIn, - Easing::QuadOut, - Easing::QuadInOut, - Easing::CubicIn, - Easing::CubicOut, - Easing::CubicInOut, - Easing::Classic(-60.0), - Easing::Classic(100.0), - Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), - ]; - - #[test] - fn endpoints_fixed() { - for e in ALL { - assert!(e.apply(0.0).abs() < 1e-4, "{e:?}"); - assert!((e.apply(1.0) - 1.0).abs() < 1e-4, "{e:?}"); - } - } - - #[test] - fn monotonic() { - for e in ALL { - let mut prev = -1e-6; - for i in 0..=100 { - let v = e.apply(i as f32 / 100.0); - assert!(v >= prev - 1e-4, "{e:?} at {i}"); - prev = v; - } - } - } - - #[test] - fn hostile_input_is_clamped() { - assert_eq!(Easing::Linear.apply(f32::NAN), 0.0); - assert_eq!(Easing::QuadIn.apply(5.0), 1.0); - assert!(Easing::CubicBezier(f32::NAN, 0.0, 1.0, 1.0).apply(0.5).is_finite()); - assert!(Easing::Classic(f32::INFINITY).apply(0.5).is_finite()); - } - - #[test] - fn bezier_forms_draw_the_same_curves() { - // Exact for everything but the two in-out polynomials. - for e in [Easing::Linear, Easing::QuadIn, Easing::QuadOut, Easing::CubicIn, Easing::CubicOut, 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(); - 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(); - 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:?}"); - } - } - - #[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); - } -} +#[path = "easing_tests.rs"] +mod tests; diff --git a/crates/doc/src/easing_tests.rs b/crates/doc/src/easing_tests.rs new file mode 100644 index 00000000..7efb60c0 --- /dev/null +++ b/crates/doc/src/easing_tests.rs @@ -0,0 +1,365 @@ +use super::*; + +fn all() -> Vec { + let mut v: Vec = 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 = 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 = (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::(&text).unwrap(), e); + // A hand-edited table is made valid on load. + assert!(serde_json::from_str::(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); +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 501f104a..489372f4 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -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, pub stroke: Option, 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, /// Drawn only inside this clip (an index into [`DisplayList::clip_parents`]). pub clip: Option, - /// 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, /// 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, /// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied). pub image: Option>, + /// 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>, } /// 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>, + /// 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, /// 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| 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]>)> { +/// [`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]>)> { + 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]>)> { 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 { +fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option { + 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> = 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, + /// 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, /// 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, + /// 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, } 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) -> 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::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, + masks: Option, + guide: bool, + outline: Option, + /// 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, transform: Affine, fill: Option, stroke: Option, clip: Option, masks: Option| 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, out: &mut DisplayList, item: impl Fn(Arc, Affine, Option, Option, Option, Option) -> 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, Affine, Option, Option) { + 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; diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index e2d27250..d79aca05 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -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::(&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::>(), [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| 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 }]); +} diff --git a/crates/doc/src/field.rs b/crates/doc/src/field.rs new file mode 100644 index 00000000..b3eb7685 --- /dev/null +++ b/crates/doc/src/field.rs @@ -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, + /// 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, + /// The text laid out (the host's work); `None` while it shows the authored outline. + pub look: Option>, + /// 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 { + 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) -> 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; diff --git a/crates/doc/src/field_tests.rs b/crates/doc/src/field_tests.rs new file mode 100644 index 00000000..a1d8e5c4 --- /dev/null +++ b/crates/doc/src/field_tests.rs @@ -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>) { + 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); +} diff --git a/crates/doc/src/filter.rs b/crates/doc/src/filter.rs index 6221a060..635c6988 100644 --- a/crates/doc/src/filter.rs +++ b/crates/doc/src/filter.rs @@ -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 { + 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 { + 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 { + 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 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 { + 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> { + 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 { + 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 { + 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::*; diff --git a/crates/doc/src/gradient_tests.rs b/crates/doc/src/gradient_tests.rs new file mode 100644 index 00000000..5ed9bbf2 --- /dev/null +++ b/crates/doc/src/gradient_tests.rs @@ -0,0 +1,131 @@ +//! Gradient options, fill frames and fitting (ADR 0074). + +use super::*; + +fn stops() -> Vec { + 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::(&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:?}"); +} diff --git a/crates/doc/src/hints.rs b/crates/doc/src/hints.rs index 799b0222..f60a2ada 100644 --- a/crates/doc/src/hints.rs +++ b/crates/doc/src/hints.rs @@ -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 diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 97f0d8e4..920e2919 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -7,32 +7,49 @@ pub use anicraft_audio as audio; pub use anicraft_actions as actions; +pub mod aids; pub mod armature; +pub mod spring; +pub mod skin; +pub mod weights; +pub mod warp; mod bitmap; +mod color_effect; pub mod camera; mod filter; mod easing; mod eval; +pub mod field; mod hints; +pub mod nine_slice; +pub mod library; pub mod motion; pub mod path_table; pub mod width; pub mod stroke_style; pub mod player; +pub mod publish; pub mod sample; +pub mod templates; pub mod sound; +pub mod swatch; -pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; -pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; -pub use easing::Easing; +pub use filter::{FILTER_PARAMS, Filter, FilterEntry, FilterParam, FilterProp, FilterSide, MAX_FILTER_SLOTS, active as active_filters, any_active as any_active_filter, pairs_up as filters_pair_up, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; +pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png}; +pub use easing::{CustomEase, EaseDir, EaseFamily, EasePoint, Easing, Handle, MAX_EASE_NAME, MAX_EASE_POINTS, MAX_EASE_SAMPLES, MAX_EASE_Y, MAX_SAVED_EASES, SampledEase, SavedEase, ease_name}; +pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform}; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; -pub use motion::{MotionTween, OnPath, Property, PropertyKey, Props, Track, motion_path}; +pub use library::{FolderId, LibraryEntry, LibraryFolder, LibraryItem, LibraryTree, NameError}; +pub use motion::{KeyRef, MotionTween, OnPath, PROPERTIES, Pin, PinError, Property, PropertyKey, Props, Track, filter_properties, motion_path, own_value}; pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync}; pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle}; -pub use camera::Camera; +pub use camera::{Camera, DepthKey}; +pub use swatch::{MAX_SWATCHES, Swatch, SwatchPaint}; +pub use aids::{Aids, GUIDE_REACH, Grid, Guide, GuideAxis, MAX_GUIDES}; +pub use nine_slice::symbol_box; pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose}; -pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, guide_walk, instance_start}; +pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_shown, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; @@ -96,12 +113,103 @@ pub struct GradientStop { pub color: Rgba, } +/// What a gradient shows past its ends (Animate's Overflow / Flow, SVG's `spreadMethod`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Spread { + /// The end colours carry on (Animate's Extend, SVG's `pad`). + #[default] + Pad, + /// The ramp mirrors back and forth. + Reflect, + /// The ramp starts again. + Repeat, +} + +impl Spread { + pub const ALL: [Spread; 3] = [Spread::Pad, Spread::Reflect, Spread::Repeat]; + pub fn is_pad(&self) -> bool { + *self == Spread::Pad + } + /// The key commands and files use (`extend` is Animate's name for `pad`). + pub fn key(self) -> &'static str { + match self { + Spread::Pad => "extend", + Spread::Reflect => "reflect", + Spread::Repeat => "repeat", + } + } + pub fn from_key(s: &str) -> Option { + match s { + "extend" | "pad" => Some(Spread::Pad), + "reflect" => Some(Spread::Reflect), + "repeat" => Some(Spread::Repeat), + _ => None, + } + } + /// Gradient position `t` (0 at the start, 1 at the end) → where on the ramp, in `0..=1`. + /// Non-finite positions read the start. + pub fn apply(self, t: f32) -> f32 { + if !t.is_finite() { + return 0.0; + } + match self { + Spread::Pad => t.clamp(0.0, 1.0), + Spread::Repeat => { + let f = t.rem_euclid(1.0); + // `rem_euclid` can round up to exactly 1 for tiny negative values. + if f >= 1.0 { 0.0 } else { f } + } + Spread::Reflect => { + let m = t.rem_euclid(2.0); + (if m > 1.0 { 2.0 - m } else { m }).clamp(0.0, 1.0) + } + } + } +} + +/// Most stops a fill gradient may have (Animate allows 15). +pub const MAX_GRADIENT_STOPS: usize = 15; +/// How far the focal point may sit from the centre, as a share of the radius (a focal point on +/// the ring itself is undefined; Animate's focal ratio runs to ±1 too). +pub const MAX_FOCAL: f32 = 0.98; + /// How a region is painted. Gradient geometry is in the element's local space. +/// +/// Gradients may carry options that older files don't have (ADR 0074): what shows past the ends +/// (`spread`), interpolation in linear light (`linear_rgb`), and for a radial gradient a focal +/// point and a `matrix` that turns its circle into any ellipse. Each is written only when set, +/// so a plain gradient is stored as before. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Paint { Solid(Rgba), - Linear { start: Vec2, end: Vec2, stops: Vec }, - Radial { center: Vec2, radius: f32, stops: Vec }, + Linear { + start: Vec2, + end: Vec2, + stops: Vec, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + /// Mix the stops in linear light (Animate's "Linear RGB"), not in sRGB. + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + }, + /// The circle of `radius` round `center`, carried by `matrix` (an ellipse at any angle). + Radial { + center: Vec2, + radius: f32, + stops: Vec, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + /// Where the ramp starts, along the gradient's own x axis from the centre, as a share + /// of the radius in `-MAX_FOCAL..=MAX_FOCAL` (Animate's focal point ratio). + #[serde(default, skip_serializing_if = "is_zero")] + focal: f32, + /// Gradient space → shape space (identity: the plain circle). + #[serde(default, skip_serializing_if = "is_identity")] + matrix: Affine, + }, /// A bitmap, its pixel (x, y) at local `matrix · (x, y)`; `repeat` tiles it, otherwise it /// shows once (an imported image is a rectangle of exactly its size, with no matrix). Bitmap { @@ -118,7 +226,19 @@ fn is_identity(m: &Affine) -> bool { *m == Affine::IDENTITY } +/// The canonical box a fill's frame maps: `-1..=1` on both axes (Animate's gradient square). +pub const FRAME_BOX: Rect = Rect { min: Vec2 { x: -1.0, y: -1.0 }, max: Vec2 { x: 1.0, y: 1.0 } }; + impl Paint { + /// A linear gradient from `start` to `end`, with no options. + pub fn linear(start: Vec2, end: Vec2, stops: Vec) -> Paint { + Paint::Linear { start, end, stops, spread: Spread::Pad, linear_rgb: false } + } + /// A radial gradient: the circle of `radius` round `center`, with no options. + pub fn radial(center: Vec2, radius: f32, stops: Vec) -> Paint { + Paint::Radial { center, radius, stops, spread: Spread::Pad, linear_rgb: false, focal: 0.0, matrix: Affine::IDENTITY } + } + /// A representative colour (first stop for gradients) for swatches and the properties panel. pub fn primary_color(&self) -> Rgba { match self { @@ -128,18 +248,119 @@ impl Paint { } } + /// A gradient's colour stops. + pub fn stops(&self) -> Option<&[GradientStop]> { + match self { + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => Some(stops), + _ => None, + } + } + pub fn stops_mut(&mut self) -> Option<&mut Vec> { + match self { + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => Some(stops), + _ => None, + } + } + pub fn is_gradient(&self) -> bool { + matches!(self, Paint::Linear { .. } | Paint::Radial { .. }) + } + /// The paint carried by `m` (its geometry moved from one space to another), so a shape in - /// the new space shows it where it was: gradient ends and centre are mapped, a radial - /// gradient's radius scales by the mean scale, a bitmap's matrix is composed. + /// the new space shows it where it was: gradient ends are mapped, a radial gradient's and a + /// bitmap's matrix is composed (exact under any transform). pub fn transformed(&self, m: &Affine) -> Paint { match self { Paint::Solid(_) => self.clone(), - Paint::Linear { start, end, stops } => Paint::Linear { start: m.apply(*start), end: m.apply(*end), stops: stops.clone() }, - Paint::Radial { center, radius, stops } => Paint::Radial { center: m.apply(*center), radius: radius * m.mean_scale(), stops: stops.clone() }, + Paint::Linear { start, end, stops, spread, linear_rgb } => Paint::Linear { start: m.apply(*start), end: m.apply(*end), stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb }, + Paint::Radial { .. } => match self.frame(None) { + Some(f) => self.with_frame(&m.mul(&f), None), + None => self.clone(), + }, Paint::Bitmap { bitmap, repeat, matrix } => Paint::Bitmap { bitmap: *bitmap, repeat: *repeat, matrix: m.mul(matrix) }, } } + /// The fill's frame: the map from [`FRAME_BOX`] to the paint's space, which the Gradient + /// Transform tool edits (ADR 0074). + /// + /// * Linear: x from −1 at the start to 1 at the end, y square to it at the same scale. + /// * Radial: the unit circle onto the gradient's ring (x is its own axis, where the focal + /// point sits). + /// * Bitmap: the box onto one copy of the image (`image` is its size in pixels). + /// + /// `None` for solid colours and a bitmap of unknown size. + pub fn frame(&self, image: Option<(f32, f32)>) -> Option { + match self { + Paint::Solid(_) => None, + Paint::Linear { start, end, .. } => { + let mid = start.lerp(*end, 0.5); + let h = (*end - *start) * 0.5; + Some(Affine { m: [h.x, h.y, -h.y, h.x, mid.x, mid.y] }) + } + Paint::Radial { center, radius, matrix, .. } => Some(matrix.mul(&Affine::translate(center.x, center.y)).mul(&Affine::scale(*radius, *radius))), + Paint::Bitmap { matrix, .. } => { + let (w, h) = image?; + Some(matrix.mul(&Affine::translate(w * 0.5, h * 0.5)).mul(&Affine::scale(w * 0.5, h * 0.5))) + } + } + } + + /// This paint with its frame set to `f` (see [`Paint::frame`]); the stops and options stay. + /// A linear gradient keeps only the frame's x axis. A radial gradient is stored as a + /// circle when `f` is one, else with a matrix about its centre. Solid colours (and bitmaps + /// without a size) are returned unchanged. + pub fn with_frame(&self, f: &Affine, image: Option<(f32, f32)>) -> Paint { + let finite = f.m.iter().all(|v| v.is_finite()); + if !finite { + return self.clone(); + } + match self { + Paint::Solid(_) => self.clone(), + Paint::Linear { stops, spread, linear_rgb, .. } => Paint::Linear { start: f.apply(Vec2::new(-1.0, 0.0)), end: f.apply(Vec2::new(1.0, 0.0)), stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb }, + Paint::Radial { stops, spread, linear_rgb, focal, .. } => { + let center = f.apply(Vec2::ZERO); + let [a, b, c, d, ..] = f.m; + let radius = Vec2::new(a, b).length(); + let (matrix, radius) = if radius > 1e-9 { + // The linear part with the x axis's length taken out, about the centre. + let l = Affine { m: [a / radius, b / radius, c / radius, d / radius, 0.0, 0.0] }; + let plain = (l.m[0] - 1.0).abs() < 1e-6 && l.m[1].abs() < 1e-6 && l.m[2].abs() < 1e-6 && (l.m[3] - 1.0).abs() < 1e-6; + if plain { (Affine::IDENTITY, radius) } else { (Affine::translate(center.x, center.y).mul(&l).mul(&Affine::translate(-center.x, -center.y)), radius) } + } else { + (Affine::IDENTITY, 0.0) + }; + Paint::Radial { center, radius, stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb, focal: *focal, matrix } + } + Paint::Bitmap { bitmap, repeat, .. } => match image { + Some((w, h)) if w > 0.0 && h > 0.0 => Paint::Bitmap { bitmap: *bitmap, repeat: *repeat, matrix: f.mul(&Affine::scale(2.0 / w, 2.0 / h)).mul(&Affine::translate(-w * 0.5, -h * 0.5)) }, + _ => self.clone(), + }, + } + } + + /// This gradient or bitmap placed on `bounds` (shape space), as Animate pours an unlocked + /// fill: a linear gradient across the width, left to right; a radial one centred, its + /// ring touching the longer side; a bitmap tiled from the top-left at its own size. + /// The stops and options stay. + pub fn fitted(&self, bounds: &Rect) -> Paint { + if bounds.is_empty() || !(bounds.min.is_finite() && bounds.max.is_finite()) { + return self.clone(); + } + let c = bounds.center(); + match self { + Paint::Solid(_) => self.clone(), + Paint::Linear { .. } => { + let hw = (bounds.width() * 0.5).max(0.5); + self.with_frame(&Affine { m: [hw, 0.0, 0.0, hw, c.x, c.y] }, None) + } + Paint::Radial { .. } => { + let r = (bounds.width().max(bounds.height()) * 0.5).max(0.5); + self.with_frame(&Affine { m: [r, 0.0, 0.0, r, c.x, c.y] }, None) + } + Paint::Bitmap { bitmap, .. } => Paint::Bitmap { bitmap: *bitmap, repeat: true, matrix: Affine::translate(bounds.min.x, bounds.min.y) }, + } + } + pub fn lerp(&self, o: &Paint, t: f32) -> Paint { let lerp_stops = |a: &[GradientStop], b: &[GradientStop]| -> Option> { (a.len() == b.len()).then(|| { @@ -148,13 +369,24 @@ impl Paint { }; match (self, o) { (Paint::Solid(a), Paint::Solid(b)) => Paint::Solid(a.lerp(*b, t)), - (Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => match lerp_stops(a, b) { - Some(stops) => Paint::Linear { start: s0.lerp(*s1, t), end: e0.lerp(*e1, t), stops }, + (Paint::Linear { start: s0, end: e0, stops: a, spread, linear_rgb }, Paint::Linear { start: s1, end: e1, stops: b, .. }) => match lerp_stops(a, b) { + Some(stops) => Paint::Linear { start: s0.lerp(*s1, t), end: e0.lerp(*e1, t), stops, spread: *spread, linear_rgb: *linear_rgb }, None => self.clone(), }, - (Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => match lerp_stops(a, b) { - Some(stops) => Paint::Radial { center: c0.lerp(*c1, t), radius: anicraft_geom::lerp(*r0, *r1, t), stops }, - None => self.clone(), + (Paint::Radial { stops: a, .. }, Paint::Radial { stops: b, focal: f1, .. }) => match (lerp_stops(a, b), self.frame(None), o.frame(None)) { + (Some(stops), Some(fa), Some(fb)) => { + let mut m = [0.0; 6]; + for (k, v) in m.iter_mut().enumerate() { + *v = anicraft_geom::lerp(fa.m[k], fb.m[k], t); + } + let mut p = self.with_frame(&Affine { m }, None); + if let Paint::Radial { stops: s, focal, .. } = &mut p { + *s = stops; + *focal = anicraft_geom::lerp(*focal, *f1, t); + } + p + } + _ => self.clone(), }, _ => self.clone(), } @@ -255,17 +487,30 @@ pub struct Shape { /// Otherwise a drawing object, which keeps to itself. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub merge: bool, + /// Asset Warp (ADR 0079): the mesh and pins that bend the outline (and a bitmap fill). The + /// path is the bent outline; the warp keeps the outline as drawn. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub warp: Option>, } impl PartialEq for Shape { fn eq(&self, o: &Shape) -> bool { - arc_eq(&self.path, &o.path) && self.fill == o.fill && self.stroke == o.stroke && self.fill_rule == o.fill_rule && self.merge == o.merge + arc_eq(&self.path, &o.path) + && self.fill == o.fill + && self.stroke == o.stroke + && self.fill_rule == o.fill_rule + && self.merge == o.merge + && match (&self.warp, &o.warp) { + (Some(a), Some(b)) => arc_eq(a, b), + (None, None) => true, + _ => false, + } } } impl Shape { pub fn filled(path: Path, fill: Paint) -> Shape { - Shape { path: Arc::new(path), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, merge: false } + Shape { path: Arc::new(path), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, merge: false, warp: None } } pub fn with_stroke(mut self, color: Rgba, width: f32) -> Shape { self.stroke = Some(Stroke::new(color, width)); @@ -319,9 +564,10 @@ pub enum ElementKind { /// How the instance blends with what is below it (movie clips and buttons). #[serde(default, skip_serializing_if = "BlendMode::is_normal")] blend: BlendMode, - /// Filters, applied in order (movie clips and buttons). + /// Filters, applied in order (movie clips and buttons); each may be switched off + /// (ADR 0091). #[serde(default, skip_serializing_if = "Vec::is_empty")] - filters: Vec, + filters: Vec, /// What the instance does on pointer events in the player (buttons and movie clips; /// ADR 0024), one handler per event. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -332,6 +578,71 @@ pub enum ElementKind { /// The camera, on a camera layer (ADR 0027): the element's transform is the camera on the /// stage and its tint colours the view. It draws nothing itself. Camera, + /// A group (Modify › Group, ADR 0073): elements kept together without a Library symbol. Its + /// members are a one-layer, one-frame timeline, so double-clicking it edits them in place + /// with every tool, and raw shapes inside merge only with each other. The group's transform + /// and colour effect apply to its members; it is always drawn at its members' frame 0. + Group { + #[serde(default)] + members: Timeline, + }, +} + +impl ElementKind { + /// A group of `elements` (ADR 0073), on one layer with id `layer`. + pub fn group(layer: LayerId, elements: Vec>) -> ElementKind { + let mut l = Layer::new(layer, "Layer 1"); + if let Some(k) = l.keyframe_mut(0) { + k.elements = elements; + } + ElementKind::Group { members: Timeline { layers: vec![Arc::new(l)] } } + } + + /// A group's members as they are drawn: every layer's elements at frame 0, bottom layer + /// first (back to front). Empty for anything else. + pub fn group_members(&self) -> Vec> { + match self { + ElementKind::Group { members } => members.layers.iter().rev().filter_map(|l| l.keyframe_at(0)).flat_map(|k| k.elements.iter().cloned()).collect(), + _ => Vec::new(), + } + } +} + +/// Groups nested deeper than this are not drawn, walked or kept (guards hostile files). +pub const MAX_GROUP_DEPTH: usize = 32; + +/// `elements` with every group replaced by its members, however deep (ADR 0073), in drawing +/// order, each placed and coloured as the group shows it (the group's transform and colour +/// effect composed into it); borrowed when there is no group. For walkers that look for what is +/// placed (symbol instances, sounds, the player's instances): members keep their own ids. +pub fn expand_groups(elements: &[Arc]) -> std::borrow::Cow<'_, [Arc]> { + if !elements.iter().any(|e| matches!(e.kind, ElementKind::Group { .. })) { + return std::borrow::Cow::Borrowed(elements); + } + fn walk(els: &[Arc], at: Option<(&Affine, &ColorEffect)>, depth: usize, out: &mut Vec>) { + for e in els { + let placed = |e: &Arc| match at { + None => e.clone(), + Some((xf, fx)) => { + let mut c = (**e).clone(); + c.transform = xf.mul(&e.transform); + c.color = fx.nested(&e.color); + Arc::new(c) + } + }; + match &e.kind { + ElementKind::Group { .. } if depth < MAX_GROUP_DEPTH => { + let g = placed(e); + walk(&e.kind.group_members(), Some((&g.transform, &g.color)), depth + 1, out); + } + ElementKind::Group { .. } => {} + _ => out.push(placed(e)), + } + } + } + let mut out = Vec::new(); + walk(elements, None, 0, &mut out); + std::borrow::Cow::Owned(out) } /// How an instance's pixels combine with what is below it, as Animate's Blending menu. Every @@ -459,43 +770,169 @@ pub struct TextBlock { /// The layout box. pub box_width: f32, pub box_height: f32, + /// A dynamic or input text field (ADR 0066); `None`: static text. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub field: Option, + /// Text on a path (ADR 0070): its baseline follows this path instead of running in lines; + /// `outline` holds the glyphs set along it. Static text only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub on_path: Option, } -/// Colour effect applied to an element and everything inside it. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct ColorEffect { - /// Alpha multiplier `0..=1`. - pub alpha: f32, - /// Tint colour mixed in by `tint_amount`. - pub tint: Rgba, - pub tint_amount: f32, +/// The path a text block follows (ADR 0070), and where along it the text sits. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextPath { + /// The baseline's path, in the block's own space (its first subpath counts). + pub path: Path, + /// Where the text is anchored along the path (pixels from its start): the block's + /// alignment says how (left: starts there, centre: centred on it, right: ends there). + #[serde(default)] + pub offset: f32, + /// The text runs along the path backwards, on its other side. + #[serde(default, skip_serializing_if = "is_false")] + pub flip: bool, } -impl Default for ColorEffect { - fn default() -> Self { - ColorEffect { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0 } +/// Longest stretch along a path a text's offset may be (pixels either way). +pub const MAX_PATH_OFFSET: f32 = 1_000_000.0; + +impl TextBlock { + /// What kind of text it is: static, dynamic or input. + pub fn kind(&self) -> TextKind { + self.field.as_ref().map_or(TextKind::Static, |f| f.kind) } } -impl ColorEffect { - /// Effect of `inner` nested inside `self`. - pub fn concat(&self, inner: &ColorEffect) -> ColorEffect { - // Tints compose by keeping the stronger one; alpha multiplies. - let (tint, amount) = if inner.tint_amount >= self.tint_amount { (inner.tint, inner.tint_amount) } else { (self.tint, self.tint_amount) }; - ColorEffect { alpha: self.alpha * inner.alpha, tint, tint_amount: amount } - } - pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect { - ColorEffect { - alpha: anicraft_geom::lerp(self.alpha, o.alpha, t), - tint: self.tint.lerp(o.tint, t), - tint_amount: anicraft_geom::lerp(self.tint_amount, o.tint_amount, t), +/// Animate's three text types (ADR 0066). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TextKind { + /// Drawn as laid out; scripts can't reach it. + #[default] + Static, + /// Scripts set and read its text (`field.text`) while the movie plays. + Dynamic, + /// The viewer types into it while the movie plays; scripts read what was typed. + Input, +} + +impl TextKind { + pub const ALL: [TextKind; 3] = [TextKind::Static, TextKind::Dynamic, TextKind::Input]; + pub fn key(self) -> &'static str { + match self { + TextKind::Static => "static", + TextKind::Dynamic => "dynamic", + TextKind::Input => "input", } } - pub fn apply(&self, c: Rgba) -> Rgba { - let k = self.tint_amount.clamp(0.0, 1.0); - let mut out = c.lerp(self.tint.with_alpha(c.a), k); - out.a = c.a * self.alpha.clamp(0.0, 1.0); - out + pub fn from_key(s: &str) -> Option { + TextKind::ALL.into_iter().find(|k| k.key() == s.trim().to_ascii_lowercase()) + } +} + +/// A field's line type, as Animate's Properties name them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LineType { + /// One line: Enter types nothing, the text scrolls sideways to keep the caret in view. + #[default] + Single, + /// Lines wrap at the field's width. + Multiline, + /// Lines break only where the text does. + MultilineNoWrap, + /// One line, drawn as `*` (input fields). + Password, +} + +impl LineType { + pub const ALL: [LineType; 4] = [LineType::Single, LineType::Multiline, LineType::MultilineNoWrap, LineType::Password]; + pub fn key(self) -> &'static str { + match self { + LineType::Single => "single", + LineType::Multiline => "multiline", + LineType::MultilineNoWrap => "multiline_no_wrap", + LineType::Password => "password", + } + } + pub fn from_key(s: &str) -> Option { + let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_"); + LineType::ALL.into_iter().find(|k| k.key() == s) + } + /// More than one line (Enter starts a new one). + pub fn multiline(self) -> bool { + matches!(self, LineType::Multiline | LineType::MultilineNoWrap) + } +} + +/// The inset of text in a field's box, on every side, in pixels (as Animate's fields have). +pub const FIELD_GUTTER: f32 = 2.0; +/// Longest text a field holds (characters). +pub const MAX_FIELD_CHARS: usize = 16_384; +/// Longest instance or variable name (characters). +pub const MAX_FIELD_NAME: usize = 256; + +/// A dynamic or input text field (ADR 0066): how it is drawn and how the viewer may use it. The +/// element's name is its instance name; the block's text is what it shows before a script or the +/// viewer changes it. Its box is the block's `box_width` × `box_height` (fixed, not the text's +/// size), and its outline is the shown text laid out [`FIELD_GUTTER`] inside the box, so +/// everything that draws or measures text works on fields unchanged. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextField { + pub kind: TextKind, + #[serde(default)] + pub lines: LineType, + /// The viewer can select its text (dynamic fields; input fields always can). + #[serde(default = "yes")] + pub selectable: bool, + /// A line around the box, and a fill behind the text. + #[serde(default)] + pub border: bool, + #[serde(default = "black")] + pub border_color: Rgba, + #[serde(default)] + pub background: bool, + #[serde(default = "white")] + pub background_color: Rgba, + /// Most characters the viewer may type (0: no limit). + #[serde(default)] + pub max_chars: u32, + /// The ActionScript 1/2 variable the field shows (kept from Animate documents, not run). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub variable: String, +} + +fn black() -> Rgba { + Rgba::BLACK +} +fn white() -> Rgba { + Rgba::WHITE +} + +impl TextField { + /// A single-line field of `kind`. + pub fn new(kind: TextKind) -> TextField { + TextField { kind, lines: LineType::Single, selectable: true, border: false, border_color: Rgba::BLACK, background: false, background_color: Rgba::WHITE, max_chars: 0, variable: String::new() } + } + + /// The width text wraps at in a box `box_width` wide, if its lines wrap. + pub fn wrap_width(&self, box_width: f32) -> Option { + (self.lines == LineType::Multiline).then(|| (box_width - 2.0 * FIELD_GUTTER).max(1.0)) + } + + /// What a field shows for `text`: `*` for each character of a password. + pub fn shown(&self, text: &str) -> String { + if self.lines == LineType::Password && self.kind == TextKind::Input { text.chars().map(|_| '*').collect() } else { text.to_string() } + } + + /// The viewer can focus it: an input field, or a selectable dynamic one. + pub fn focusable(&self) -> bool { + self.kind == TextKind::Input || (self.kind == TextKind::Dynamic && self.selectable) + } + + /// Values in range: names cut to length, at most [`MAX_FIELD_CHARS`] typed. + pub fn sanitized(&self) -> TextField { + TextField { max_chars: self.max_chars.min(MAX_FIELD_CHARS as u32), variable: self.variable.chars().take(MAX_FIELD_NAME).collect(), ..self.clone() } } } @@ -534,6 +971,13 @@ fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize) -> Re } ElementKind::Text(t) => Rect::new(0.0, 0.0, t.box_width.max(0.0), t.box_height.max(0.0)).transformed(xf), ElementKind::Camera => Rect::EMPTY, + ElementKind::Group { .. } => { + let mut r = Rect::EMPTY; + for child in el.kind.group_members() { + r = r.union(&element_bounds(doc, &child, &xf.mul(&child.transform), depth + 1)); + } + r + } ElementKind::Symbol { symbol, .. } => { let Some(sym) = doc.symbol(*symbol) else { return Rect::EMPTY }; let mut r = Rect::EMPTY; @@ -560,9 +1004,56 @@ pub enum TweenKind { Shape, } +/// The property groups a classic tween may ease separately (ADR 0081), as Animate's custom +/// ease offers them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EaseGroup { + /// Where the object is (and how far along a motion guide). + Position, + /// Its rotation and skew. + Rotation, + Scale, + /// Its colour effect. + Color, + Filters, +} + +impl EaseGroup { + pub const ALL: [EaseGroup; 5] = [EaseGroup::Position, EaseGroup::Rotation, EaseGroup::Scale, EaseGroup::Color, EaseGroup::Filters]; + + /// The name commands use (`position`, `rotation`, `scale`, `color`, `filters`). + pub fn key(self) -> &'static str { + match self { + EaseGroup::Position => "position", + EaseGroup::Rotation => "rotation", + EaseGroup::Scale => "scale", + EaseGroup::Color => "color", + EaseGroup::Filters => "filters", + } + } + + pub fn from_key(k: &str) -> Option { + let k = k.trim().to_ascii_lowercase(); + let k = if k == "colour" { "color" } else { k.as_str() }; + EaseGroup::ALL.into_iter().find(|g| g.key() == k) + } + + pub fn label(self) -> &'static str { + match self { + EaseGroup::Position => "Position", + EaseGroup::Rotation => "Rotation", + EaseGroup::Scale => "Scale", + EaseGroup::Color => "Colour", + EaseGroup::Filters => "Filters", + } + } +} + /// A tween from a keyframe to the next one. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Tween { + /// The ease of everything, and of each property group without its own. #[serde(default)] pub easing: Easing, #[serde(default, skip_serializing_if = "is_classic")] @@ -570,6 +1061,37 @@ pub struct Tween { /// On a guided layer: turn with the motion guide as it bends. #[serde(default, skip_serializing_if = "is_false")] pub orient: bool, + /// Property groups eased their own way (classic tweens; ADR 0081). Empty: one ease for all + /// properties. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub groups: Vec<(EaseGroup, Easing)>, +} + +impl Tween { + /// A tween of `kind` eased by `easing`. + pub fn new(easing: Easing, kind: TweenKind) -> Tween { + Tween { easing, kind, ..Tween::default() } + } + + /// The ease of group `g`: its own, else the tween's. + pub fn ease(&self, g: EaseGroup) -> &Easing { + self.groups.iter().find(|(x, _)| *x == g).map_or(&self.easing, |(_, e)| e) + } + + /// Whether group `g` has its own ease. + pub fn has_own(&self, g: EaseGroup) -> bool { + self.groups.iter().any(|(x, _)| *x == g) + } + + /// Gives group `g` its own ease, or (with `None`) the tween's again. Groups are kept in + /// their fixed order, once each. + pub fn set_ease(&mut self, g: EaseGroup, e: Option) { + self.groups.retain(|(x, _)| *x != g); + if let Some(e) = e { + self.groups.push((g, e)); + } + self.groups.sort_by_key(|(x, _)| EaseGroup::ALL.iter().position(|y| y == x)); + } } fn is_false(b: &bool) -> bool { @@ -677,16 +1199,34 @@ pub struct Layer { pub visible: bool, #[serde(default)] pub locked: bool, + /// View as Outlines (ADR 0061): the stage draws the layer's artwork as hairlines in + /// [`Layer::color`]. Never in the movie or an export. #[serde(default)] pub outline: bool, #[serde(default = "default_layer_color")] pub color: Rgba, + /// Onion skin draws this layer's frames around the playhead (ADR 0061); off, only its + /// playhead frame shows. + #[serde(default = "yes", skip_serializing_if = "is_true")] + pub onion: bool, + /// Row height on the timeline as a multiple of a normal row (ADR 0061): 1, 2 or 3 (100, + /// 200 or 300 %), as Animate's Layer Properties offer. Read through [`Layer::height`]. + #[serde(default = "one", skip_serializing_if = "is_one", rename = "height")] + pub height_rows: u8, #[serde(default)] pub keyframes: Vec>, /// Layer depth (ADR 0027), pixels behind the stage (negative: in front): the camera's pans /// move a deeper layer less (parallax). Not the nesting depth ([`Timeline::depth`]). #[serde(default, skip_serializing_if = "is_zero")] pub depth: f32, + /// Depth over time (ADR 0082): with keys, the depth at a frame is theirs + /// ([`Layer::depth_at`]) and `depth` plays no part. Sorted by frame, one per frame. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub depth_keys: Vec, + /// Attached to the camera (ADR 0082): the camera's moves leave the layer where it is on + /// screen (titles, HUDs); its coordinates are the output's. + #[serde(default, skip_serializing_if = "is_false")] + pub attached: bool, /// Volume of the sounds on this layer (and in the symbols on it), `0..=1` (ADR 0039). #[serde(default = "full", skip_serializing_if = "is_full")] pub volume: f32, @@ -696,8 +1236,59 @@ pub struct Layer { /// An armature layer's bones (ADR 0043); `None` on every other kind of layer. #[serde(default, skip_serializing_if = "Option::is_none")] pub armature: Option>, + /// How a mask layer's artwork reveals what it masks (ADR 0070): its fill area (Animate's + /// masks), or its opacity or brightness (soft masks). Ignored on other kinds of layer. + #[serde(default, skip_serializing_if = "MaskMode::is_coverage")] + pub mask_mode: MaskMode, } +/// How a mask layer's artwork reveals the layers it masks (ADR 0070). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MaskMode { + /// Its fills' area, fully opaque: colours, opacity and strokes don't matter (as in Animate). + #[default] + Coverage, + /// Its artwork as drawn (fills, strokes, gradients, bitmaps, opacity): the artwork's + /// opacity reveals (Animate users get this with alpha-gradient masks; SVG `mask-type: alpha`). + Alpha, + /// Its artwork's brightness times its opacity reveals: white shows, black hides (SVG's + /// default `mask`). Luminance uses the sRGB coefficients 0.2125, 0.7154, 0.0721. + Luminance, +} + +impl MaskMode { + pub const ALL: [MaskMode; 3] = [MaskMode::Coverage, MaskMode::Alpha, MaskMode::Luminance]; + pub fn is_coverage(&self) -> bool { + *self == MaskMode::Coverage + } + /// Whether the artwork's colours and opacity count (not just its area). + pub fn is_soft(self) -> bool { + self != MaskMode::Coverage + } + pub fn key(self) -> &'static str { + match self { + MaskMode::Coverage => "coverage", + MaskMode::Alpha => "alpha", + MaskMode::Luminance => "luminance", + } + } + pub fn from_key(k: &str) -> Option { + MaskMode::ALL.into_iter().find(|m| m.key() == k) + } + /// How much a premultiplied colour reveals in this mode, `0..=1`. + pub fn reveal(self, premul: [f32; 4]) -> f32 { + let v = match self { + MaskMode::Coverage | MaskMode::Alpha => premul[3], + MaskMode::Luminance => LUMA[0] * premul[0] + LUMA[1] * premul[1] + LUMA[2] * premul[2], + }; + if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } + } +} + +/// The luminance coefficients of a luminance mask (SVG's `luminanceToAlpha`, on sRGB values). +pub const LUMA: [f32; 3] = [0.2125, 0.7154, 0.0721]; + fn is_zero(v: &f32) -> bool { *v == 0.0 } @@ -707,6 +1298,18 @@ fn full() -> f32 { fn is_full(v: &f32) -> bool { *v == 1.0 } +fn is_true(v: &bool) -> bool { + *v +} +fn one() -> u8 { + 1 +} +fn is_one(v: &u8) -> bool { + *v == 1 +} + +/// Tallest a layer's timeline row gets, in normal rows (300 %). +pub const MAX_LAYER_HEIGHT: u8 = 3; impl PartialEq for Layer { fn eq(&self, o: &Layer) -> bool { @@ -718,9 +1321,14 @@ impl PartialEq for Layer { && self.locked == o.locked && self.outline == o.outline && self.color == o.color + && self.onion == o.onion + && self.height_rows == o.height_rows && self.depth.to_bits() == o.depth.to_bits() + && self.depth_keys == o.depth_keys + && self.attached == o.attached && self.volume.to_bits() == o.volume.to_bits() && self.muted == o.muted + && self.mask_mode == o.mask_mode && match (&self.armature, &o.armature) { (Some(a), Some(b)) => arc_eq(a, b), (a, b) => a.is_none() && b.is_none(), @@ -747,13 +1355,22 @@ impl Layer { locked: false, outline: false, color: default_layer_color(), + onion: true, + height_rows: 1, keyframes: vec![Arc::new(Keyframe::new(0, 1))], depth: 0.0, + depth_keys: Vec::new(), + attached: false, volume: 1.0, muted: false, armature: None, + mask_mode: MaskMode::Coverage, } } + /// The row height in normal rows, `1..=MAX_LAYER_HEIGHT` whatever a file says. + pub fn height(&self) -> u8 { + self.height_rows.clamp(1, MAX_LAYER_HEIGHT) + } /// The gain this layer gives its sounds: its volume, or silence when muted. pub fn sound_gain(&self) -> f32 { if self.muted { @@ -1017,9 +1634,53 @@ pub struct Symbol { /// The class scripts know the symbol by (Animate's "linkage"), kept as text (ADR 0013). #[serde(default, skip_serializing_if = "Option::is_none")] pub linkage: Option, + /// Guides for 9-slice scaling (ADR 0055): an instance scaled keeps the corners outside them + /// unscaled. `None`: the symbol scales as a whole. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_grid: Option, + /// The guides as they were when 9-slice scaling was switched off (ADR 0057): switching it on + /// again brings them back where they were. Only kept, never drawn or applied. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_grid_kept: Option, pub timeline: Timeline, } +/// The four 9-slice guides of a symbol (ADR 0055), in the symbol's own space: two vertical +/// lines at `x = left` and `x = right`, two horizontal ones at `y = top` and `y = bottom`. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ScaleGrid { + pub left: f32, + pub right: f32, + pub top: f32, + pub bottom: f32, +} + +impl ScaleGrid { + /// Guides a quarter of the way in from each edge of `bounds` (what turning guides on gives). + pub fn inset(bounds: &Rect) -> ScaleGrid { + let (w, h) = (bounds.width() * 0.25, bounds.height() * 0.25); + ScaleGrid { left: bounds.min.x + w, right: bounds.max.x - w, top: bounds.min.y + h, bottom: bounds.max.y - h } + } + + /// Whether the guides are usable: finite, within the format's range, and in order. + pub fn check(&self) -> Result<(), String> { + let v = [self.left, self.right, self.top, self.bottom]; + if !v.iter().all(|x| x.is_finite() && x.abs() <= MAX_GRID_COORD) { + return Err(format!("9-slice guides must be numbers within ±{MAX_GRID_COORD}")); + } + if self.left > self.right { + return Err("the left 9-slice guide must not be right of the right one".into()); + } + if self.top > self.bottom { + return Err("the top 9-slice guide must not be below the bottom one".into()); + } + Ok(()) + } +} + +/// Largest 9-slice guide coordinate accepted from files and commands. +pub const MAX_GRID_COORD: f32 = 1_000_000.0; + /// A symbol's script class: what scripts create it by, and the class it extends. Kept with /// the document and shown, never run (ADR 0013 tier 1). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -1067,11 +1728,15 @@ pub struct Scene { pub name: String, #[serde(default)] pub timeline: Timeline, + /// The scene's guides (View › Guides, ADR 0076), in stage pixels. Animate keeps guides per + /// scene too; they show on the stage only, never in a picture or an export. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub guides: Vec, } impl Scene { pub fn new(name: impl Into) -> Scene { - Scene { name: name.into(), timeline: Timeline::default() } + Scene { name: name.into(), timeline: Timeline::default(), guides: Vec::new() } } } @@ -1095,14 +1760,38 @@ pub struct Document { /// Sounds in the library, placed on keyframes through [`FrameSound`]. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sounds: Vec>, + /// The Library's folders and which folder each item is in (ADR 0050). + #[serde(default, skip_serializing_if = "library_tree_is_empty")] + pub library_tree: Arc, /// The class scripts run the main timeline as (Animate's "document class"), kept as text /// (ADR 0013 tier 1); empty when there is none. #[serde(default, skip_serializing_if = "String::is_empty")] pub document_class: String, + /// File › Publish Settings: the formats Publish writes and their options (ADR 0060). + #[serde(default, skip_serializing_if = "publish_is_default")] + pub publish: Arc, + /// The Swatches panel's colours and gradients (ADR 0078). A file without them opens with + /// the default set, which is written only once changed. + #[serde(default = "default_swatches", skip_serializing_if = "swatches_are_default")] + pub swatches: Arc>, + /// How the grid and the guides look (ADR 0076). + #[serde(default, skip_serializing_if = "aids_is_default")] + pub aids: Arc, + /// Eases the artist saved by name (ADR 0081), offered with the presets. + #[serde(default, skip_serializing_if = "eases_is_empty")] + pub eases: Arc>, /// Next free id for layers, elements and symbols. pub next_id: u64, } +fn default_swatches() -> Arc> { + Arc::new(swatch::default_set()) +} + +fn swatches_are_default(v: &Arc>) -> bool { + swatch::is_default_set(v) +} + /// What a document file may hold: `scenes`, or (files before scenes) a single `timeline`. #[derive(Deserialize)] struct DocumentFile { @@ -1119,7 +1808,17 @@ struct DocumentFile { #[serde(default)] sounds: Vec>, #[serde(default)] + library_tree: Arc, + #[serde(default)] document_class: String, + #[serde(default)] + publish: Arc, + #[serde(default = "default_swatches")] + swatches: Arc>, + #[serde(default)] + aids: Arc, + #[serde(default)] + eases: Arc>, #[serde(default = "first_id")] next_id: u64, } @@ -1128,9 +1827,9 @@ impl From for Document { fn from(f: DocumentFile) -> Document { let mut scenes = f.scenes; if let Some(tl) = f.timeline { - scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl })); + scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl, guides: Vec::new() })); } - Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, document_class: f.document_class, next_id: f.next_id } + Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, aids: f.aids, swatches: f.swatches, eases: f.eases, next_id: f.next_id } } } @@ -1138,18 +1837,34 @@ fn first_id() -> u64 { 1 } +fn library_tree_is_empty(t: &Arc) -> bool { + t.is_empty() +} + +fn eases_is_empty(e: &Arc>) -> bool { + e.is_empty() +} + +fn aids_is_default(a: &Arc) -> bool { + a.is_default() +} + +fn publish_is_default(p: &Arc) -> bool { + p.is_default() +} + /// What `timeline(i)` returns for a scene that does not exist (never for a sanitized document). static NO_TIMELINE: Timeline = Timeline { layers: Vec::new() }; impl PartialEq for Document { fn eq(&self, o: &Document) -> bool { - self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) + self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) && arc_eq(&self.aids, &o.aids) && arc_eq(&self.swatches, &o.swatches) && arc_eq(&self.eases, &o.eases) } } impl Default for Document { fn default() -> Self { - let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(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::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), aids: Arc::default(), swatches: default_swatches(), eases: Arc::default(), next_id: 1 }; let id = LayerId(d.alloc_id()); d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1"))); d @@ -1207,9 +1922,15 @@ impl Document { pub fn scene_start(&self, i: usize) -> u32 { self.scenes.iter().take(i).map(|s| s.timeline.frame_count()).fold(0u32, u32::saturating_add) } - /// Every timeline: the scenes', then the library symbols'. + /// Every timeline: the scenes', then the library symbols', then the groups' inside them (ADR + /// 0073), so whatever walks every timeline (Library uses, sounds, paths) sees inside groups. pub fn timelines(&self) -> impl Iterator { - self.scenes.iter().map(|s| &s.timeline).chain(self.library.iter().map(|s| &s.timeline)) + let top: Vec<&Timeline> = self.scenes.iter().map(|s| &s.timeline).chain(self.library.iter().map(|s| &s.timeline)).collect(); + let mut all = top.clone(); + for tl in top { + group_timelines(tl, 0, &mut all); + } + all.into_iter() } /// Repairs a loaded document: ids, sizes and keyframe order. pub fn sanitize(&mut self) { @@ -1221,15 +1942,30 @@ impl Document { } s.fps = s.fps.clamp(1.0, 240.0); s.background = s.background.sanitized(); + let aids = self.aids.sanitized(); + if aids != *self.aids { + self.aids = Arc::new(aids); + } + let eases = easing::sanitized_eases(&self.eases); + if eases != *self.eases { + self.eases = Arc::new(eases); + } let mut max_id = 0u64; let scan = |l: &Layer, max_id: &mut u64| { *max_id = (*max_id).max(l.id.0); for b in l.armature.iter().flat_map(|a| &a.bones) { - *max_id = (*max_id).max(b.id.0); + // A shape armature's joint nodes take ids from the same counter (ADR 0071). + *max_id = (*max_id).max(b.id.0).max(b.child.0).max(b.parent.0); } for k in &l.keyframes { for e in &k.elements { *max_id = (*max_id).max(e.id.0); + // Warp pins take ids from the same counter (ADR 0079). + if let ElementKind::Shape(s) = &e.kind { + for p in s.warp.iter().flat_map(|w| &w.pins) { + *max_id = (*max_id).max(p.id.0); + } + } } } }; @@ -1241,13 +1977,18 @@ impl Document { if scene.name.trim().is_empty() || scene.name.len() > 256 { Arc::make_mut(scene).name = format!("Scene {}", i + 1); } + if scene.guides.len() > MAX_GUIDES || scene.guides.iter().any(|g| !(g.at.is_finite() && g.at.abs() <= GUIDE_REACH)) { + aids::sanitize_guides(&mut Arc::make_mut(scene).guides); + } let tl = &mut Arc::make_mut(scene).timeline; for l in &mut tl.layers { Arc::make_mut(l).normalize(); sanitize_scripts(l); sanitize_depth(l); sanitize_armature(l); + sanitize_warps(l); scan(l, &mut max_id); + sanitize_groups(l, 0, &mut max_id); } tl.repair_masks(); } @@ -1255,11 +1996,29 @@ impl Document { if !self.document_class.is_empty() && !actions::valid_class_name(&self.document_class) { self.document_class.clear(); } + // Swatches that can't be repaired are dropped; at most MAX_SWATCHES are kept. + let swatches: Vec = self.swatches.iter().filter_map(Swatch::sanitized).take(MAX_SWATCHES).collect(); + if swatches != *self.swatches { + self.swatches = Arc::new(swatches); + } + let mut publish = (*self.publish).clone(); + publish.sanitize(); + if publish != *self.publish { + self.publish = Arc::new(publish); + } for sym in &mut self.library { max_id = max_id.max(sym.id.0); if sym.linkage.as_ref().is_some_and(|l| l.check().is_err()) { Arc::make_mut(sym).linkage = None; } + // 9-slice guides that aren't usable are dropped: the symbol scales as a whole. + if sym.scale_grid.as_ref().is_some_and(|g| g.check().is_err()) { + Arc::make_mut(sym).scale_grid = None; + } + // Kept guides (ADR 0057) only while 9-slice is off, and only usable ones. + if sym.scale_grid_kept.as_ref().is_some_and(|g| sym.scale_grid.is_some() || g.check().is_err()) { + Arc::make_mut(sym).scale_grid_kept = None; + } let tl = &mut Arc::make_mut(sym).timeline; for l in &mut tl.layers { Arc::make_mut(l).normalize(); @@ -1270,7 +2029,9 @@ impl Document { } sanitize_depth(l); sanitize_armature(l); + sanitize_warps(l); scan(l, &mut max_id); + sanitize_groups(l, 0, &mut max_id); } tl.repair_masks(); } @@ -1280,16 +2041,120 @@ impl Document { for s in &self.sounds { max_id = max_id.max(s.id.0); } + self.sanitize_library_tree(&mut max_id); self.next_id = self.next_id.max(max_id.saturating_add(1)); } } -/// Keeps a loaded layer's depth finite and in range (touching it only if it isn't). +/// The members' timelines of every group on `tl`'s keyframes, and of the groups inside them, in +/// order, up to [`MAX_GROUP_DEPTH`] deep. +fn group_timelines<'a>(tl: &'a Timeline, depth: usize, out: &mut Vec<&'a Timeline>) { + if depth >= MAX_GROUP_DEPTH { + return; + } + for e in tl.layers.iter().flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()) { + if let ElementKind::Group { members } = &e.kind { + out.push(members); + group_timelines(members, depth + 1, out); + } + } +} + +/// Repairs the groups on a loaded layer (ADR 0073), however deep: each group's members are one +/// frame of normal layers (a camera or armature layer inside one becomes a normal layer), every +/// layer at least one keyframe at frame 0, and groups past [`MAX_GROUP_DEPTH`] are dropped. Ids +/// inside count towards `max_id`. Touches only what needs it. +fn sanitize_groups(layer: &mut Arc, depth: usize, max_id: &mut u64) { + let has_groups = layer.keyframes.iter().any(|k| k.elements.iter().any(|e| matches!(e.kind, ElementKind::Group { .. }))); + if !has_groups { + return; + } + let l = Arc::make_mut(layer); + for k in &mut l.keyframes { + if !k.elements.iter().any(|e| matches!(e.kind, ElementKind::Group { .. })) { + continue; + } + let k = Arc::make_mut(k); + if depth >= MAX_GROUP_DEPTH { + k.elements.retain(|e| !matches!(e.kind, ElementKind::Group { .. })); + continue; + } + for e in &mut k.elements { + if !matches!(e.kind, ElementKind::Group { .. }) { + continue; + } + let ElementKind::Group { members } = &mut Arc::make_mut(e).kind else { continue }; + for gl in &mut members.layers { + *max_id = (*max_id).max(gl.id.0); + let bad_kind = matches!(gl.kind, LayerKind::Camera | LayerKind::Armature | LayerKind::Folder); + let bad_frames = gl.keyframes.len() != 1 || gl.keyframes.first().is_some_and(|k| k.start != 0 || k.duration != 1 || k.tween.is_some() || k.motion.is_some()); + if bad_kind || bad_frames { + let g = Arc::make_mut(gl); + if bad_kind { + g.kind = LayerKind::Normal; + g.armature = None; + } + if bad_frames { + // The frame a group shows (its first), as its only one. + let mut first = g.keyframes.iter().find(|k| k.start == 0).map_or_else(|| Keyframe::new(0, 1), |k| (**k).clone()); + first.duration = 1; + first.tween = None; + first.motion = None; + g.keyframes = vec![Arc::new(first)]; + } + } + for ge in gl.keyframes.iter().flat_map(|k| k.elements.iter()) { + *max_id = (*max_id).max(ge.id.0); + } + sanitize_groups(gl, depth + 1, max_id); + } + members.repair_masks(); + } + } +} + +/// Repairs the warps on a loaded layer's shapes (ADR 0079): a warp with nothing usable left +/// goes (the shape keeps the outline it shows), and hostile pins are dropped. Touches only what +/// needs it. +fn sanitize_warps(layer: &mut Arc) { + let bad = |e: &Element| match &e.kind { + ElementKind::Shape(Shape { warp: Some(w), .. }) => { + let mut x = (**w).clone(); + !x.sanitize() || x != **w + } + _ => false, + }; + if !layer.keyframes.iter().any(|k| k.elements.iter().any(|e| bad(e))) { + return; + } + for k in &mut Arc::make_mut(layer).keyframes { + if !k.elements.iter().any(|e| bad(e)) { + continue; + } + for e in &mut Arc::make_mut(k).elements { + if !bad(e) { + continue; + } + if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind + && let Some(w) = &s.warp + { + let mut x = (**w).clone(); + s.warp = x.sanitize().then(|| Arc::new(x)); + } + } + } +} + +/// Keeps a loaded layer's depth and depth keys finite and in range (touching it only if they +/// aren't). fn sanitize_depth(layer: &mut Arc) { let d = camera::clamp_depth(layer.depth); if d.to_bits() != layer.depth.to_bits() { Arc::make_mut(layer).depth = d; } + if !layer.depth_keys_clean() { + Arc::make_mut(layer).sanitize_depth_keys(); + } } /// Repairs a loaded layer's armature (ADR 0043): only an armature layer has one, its bones are @@ -1352,6 +2217,10 @@ fn sanitize_scripts(layer: &mut Arc) { } } +#[cfg(test)] +#[path = "gradient_tests.rs"] +mod gradient_tests; + #[cfg(test)] #[path = "camera_tests.rs"] mod camera_tests; diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs new file mode 100644 index 00000000..d088d096 --- /dev/null +++ b/crates/doc/src/library.rs @@ -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, +} + +/// 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, + /// 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, +} + +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(m: &BTreeMap, s: S) -> Result { + s.collect_seq(m.iter().map(|(item, folder)| Placed { item: *item, folder: *folder })) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let v: Vec = 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 { + 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 + '_ { + 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 { + 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 { + 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) -> Vec { + 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 { + let inside: Vec = 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, name: &str, except: Option) -> 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, name: &str, except: Option) -> Result { + 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, 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, 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) { + 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 { + let mut parent: Option = 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 { + let mut uses: HashMap = 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 { + let mut reached: HashSet = HashSet::new(); + let mut stack: Vec = 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, stack: &mut Vec| { + 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 = 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 { + 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 = 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 = 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 = HashMap::new(); + let mut elements: HashMap = 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; diff --git a/crates/doc/src/library_tests.rs b/crates/doc/src/library_tests.rs new file mode 100644 index 00000000..d737b7ab --- /dev/null +++ b/crates/doc/src/library_tests.rs @@ -0,0 +1,195 @@ +use super::*; +use crate::{Element, Layer, Linkage, Symbol, SymbolKind, sample}; + +fn instance(d: &mut Document, symbol: SymbolId) -> Arc { + 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| 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 { 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 = 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::>().len() == 1 { + assert!(first.windows(2).all(|w| w[0] == w[1])); + } + } + let order: Vec = 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))); +} diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index 60123b4b..02dbdd76 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -2,7 +2,7 @@ //! //! A classic tween interpolates a whole keyframe into the next one. A motion tween instead //! belongs to one keyframe span and one object in it (its *target*). Each property (x, y, -//! scale, rotation, skew, alpha, tint) may have a [`Track`] of property keyframes anywhere in +//! scale, rotation, skew, and the colour effect's alpha, brightness, tint and advanced values) may have a [`Track`] of property keyframes anywhere in //! the span; between two keys the value follows the segment's [`Easing`], which may be a custom //! cubic Bézier. A property without a track keeps the target's own value (its *base*: how it //! looks on the span's first frame). Evaluation is pure: [`MotionTween::apply`] maps the base @@ -13,13 +13,25 @@ //! *when* it gets where: the share of the way along the path at a frame is the share of the //! distance the X/Y curves have covered by then. With *orient to path* the object also turns //! as the path turns. Without a path the X/Y curves place the object, as before. +//! +//! Anchors of the path may be *pinned* to frames (ADR 0049): the object passes a pinned anchor +//! exactly on its frame, and the X/Y keys there hold the anchor's place. The ends are always +//! pinned, to the first and last position keys. Pins cut the motion into legs; on each leg the +//! X/Y curves time the object along the stretch of path between its two pinned anchors, as they +//! time the whole path when only the ends are pinned. Anchors that aren't pinned shape the path +//! only. -use crate::{Element, ElementId, Easing}; +use crate::{ColorEffect, ColorStyle, ColorTransform, Element, ElementId, ElementKind, Easing, FilterParam, FilterProp, MAX_FILTER_SLOTS, Rgba}; +use std::borrow::Cow; +use anicraft_geom::edit::ANCHOR; use anicraft_geom::walk::CurveWalk; use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2}; use serde::{Deserialize, Serialize}; use std::sync::Arc; +mod retime; +pub use retime::KeyRef; + /// Most keys one track keeps (files and commands alike). pub const MAX_KEYS: usize = 10_000; @@ -27,9 +39,10 @@ pub const MAX_KEYS: usize = 10_000; pub const MAX_PATH_SEGMENTS: usize = 1_000; /// A property a motion tween animates. Values are in the units the Motion Editor shows: -/// pixels, percent and degrees. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] +/// pixels, percent, degrees, and 0–255 for colour channels and offsets (as Animate shows them). +/// In files and commands a property is its [`Property::key`]: `x`, `scale_x`, `alpha`…, and a +/// filter's number `filter..` (`filter.0.blur_x`, ADR 0092). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Property { /// Registration point, stage pixels. X, @@ -41,17 +54,83 @@ pub enum Property { Rotation, /// Degrees of horizontal skew, within ±89. Skew, - /// Colour effect: opacity and tint amount, percent. + /// Colour effect (ADR 0056), by style. Alpha: opacity, percent. Alpha, + /// Brightness, −100..=100 %. + Brightness, + /// Tint amount, percent, and the tint colour's channels, 0–255. Tint, + TintRed, + TintGreen, + TintBlue, + /// Advanced: each channel's multiplier, −100..=100 %, and offset, −255..=255. + RedMultiplier, + GreenMultiplier, + BlueMultiplier, + AlphaMultiplier, + RedOffset, + GreenOffset, + BlueOffset, + AlphaOffset, + /// A number of a filter on the target (ADR 0092), by the filter's place in its list. + Filter(FilterProp), } -impl Property { - pub const ALL: [Property; 8] = [Property::X, Property::Y, Property::ScaleX, Property::ScaleY, Property::Rotation, Property::Skew, Property::Alpha, Property::Tint]; +impl Serialize for Property { + fn serialize(&self, s: S) -> Result { + s.serialize_str(&self.key()) + } +} - /// The name used in files and commands (`x`, `scale_x`, `alpha`…). - pub fn key(self) -> &'static str { - match self { +impl<'de> Deserialize<'de> for Property { + fn deserialize>(d: D) -> Result { + let k = Cow::::deserialize(d)?; + Property::from_key(&k).ok_or_else(|| serde::de::Error::custom(format!("unknown motion tween property '{k}'"))) + } +} + +/// How many properties there are (besides the filters' numbers). +pub const PROPERTIES: usize = 20; + +impl Property { + pub const ALL: [Property; PROPERTIES] = [ + Property::X, + Property::Y, + Property::ScaleX, + Property::ScaleY, + Property::Rotation, + Property::Skew, + Property::Alpha, + Property::Brightness, + Property::Tint, + Property::TintRed, + Property::TintGreen, + Property::TintBlue, + Property::RedMultiplier, + Property::GreenMultiplier, + Property::BlueMultiplier, + Property::AlphaMultiplier, + Property::RedOffset, + Property::GreenOffset, + Property::BlueOffset, + Property::AlphaOffset, + ]; + + /// The Advanced properties: multipliers then offsets, red first. + pub const ADVANCED: [Property; 8] = [ + Property::RedMultiplier, + Property::GreenMultiplier, + Property::BlueMultiplier, + Property::AlphaMultiplier, + Property::RedOffset, + Property::GreenOffset, + Property::BlueOffset, + Property::AlphaOffset, + ]; + + /// The name used in files and commands (`x`, `scale_x`, `alpha`…, `filter.0.blur_x`). + pub fn key(self) -> Cow<'static, str> { + Cow::Borrowed(match self { Property::X => "x", Property::Y => "y", Property::ScaleX => "scale_x", @@ -59,10 +138,36 @@ impl Property { Property::Rotation => "rotation", Property::Skew => "skew", Property::Alpha => "alpha", + Property::Brightness => "brightness", Property::Tint => "tint", + Property::TintRed => "tint_red", + Property::TintGreen => "tint_green", + Property::TintBlue => "tint_blue", + Property::RedMultiplier => "red_multiplier", + Property::GreenMultiplier => "green_multiplier", + Property::BlueMultiplier => "blue_multiplier", + Property::AlphaMultiplier => "alpha_multiplier", + Property::RedOffset => "red_offset", + Property::GreenOffset => "green_offset", + Property::BlueOffset => "blue_offset", + Property::AlphaOffset => "alpha_offset", + Property::Filter(f) => return Cow::Owned(format!("filter.{}.{}", f.slot, f.param.key())), + }) + } + + /// The filter number this is, if it is one. + pub fn filter(self) -> Option { + match self { + Property::Filter(f) => Some(f), + _ => None, } } + pub fn is_filter(self) -> bool { + self.filter().is_some() + } + + /// The label (for a filter's number, the number's: the Motion Editor shows the filter above). pub fn label(self) -> &'static str { match self { Property::X => "X", @@ -72,34 +177,73 @@ impl Property { Property::Rotation => "Rotation", Property::Skew => "Skew", Property::Alpha => "Alpha", + Property::Brightness => "Brightness", Property::Tint => "Tint", + Property::TintRed => "Tint red", + Property::TintGreen => "Tint green", + Property::TintBlue => "Tint blue", + Property::RedMultiplier => "Red multiplier", + Property::GreenMultiplier => "Green multiplier", + Property::BlueMultiplier => "Blue multiplier", + Property::AlphaMultiplier => "Alpha multiplier", + Property::RedOffset => "Red offset", + Property::GreenOffset => "Green offset", + Property::BlueOffset => "Blue offset", + Property::AlphaOffset => "Alpha offset", + Property::Filter(f) => f.param.label(), } } pub fn unit(self) -> &'static str { match self { + Property::Filter(f) => f.param.unit(), Property::X | Property::Y => "px", - Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Tint => "%", + Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Brightness | Property::Tint => "%", + Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => "%", Property::Rotation | Property::Skew => "°", + Property::TintRed | Property::TintGreen | Property::TintBlue | Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => "", } } - /// The Motion Editor's groups: Position, Transform, Colour effect. + /// The Motion Editor's groups: Position, Transform, Colour effect, Filters. pub fn group(self) -> &'static str { + if self.is_filter() { + return "Filters"; + } + match self.style() { + None if matches!(self, Property::X | Property::Y) => "Position", + None => "Transform", + Some(_) => "Colour effect", + } + } + + /// The colour effect style a colour property belongs to (`None` for position, transform + /// and filters). + pub fn style(self) -> Option { match self { - Property::X | Property::Y => "Position", - Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => "Transform", - Property::Alpha | Property::Tint => "Colour effect", + Property::Filter(_) => None, + Property::X | Property::Y | Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => None, + Property::Alpha => Some(ColorStyle::Alpha), + Property::Brightness => Some(ColorStyle::Brightness), + Property::Tint | Property::TintRed | Property::TintGreen | Property::TintBlue => Some(ColorStyle::Tint), + Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier | Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => Some(ColorStyle::Advanced), } } pub fn from_key(s: &str) -> Option { + // `filter..`: a filter's number, by the filter's place in the list. + if let Some(rest) = s.trim().strip_prefix("filter.") { + let (slot, param) = rest.split_once('.')?; + let slot = slot.trim().parse::().ok().filter(|n| *n < MAX_FILTER_SLOTS)?; + return Some(Property::Filter(FilterProp { slot, param: FilterParam::from_key(param)? })); + } let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_"); let s = match s.as_str() { "scalex" => "scale_x", "scaley" => "scale_y", "rotate" => "rotation", "opacity" => "alpha", + "tint_amount" => "tint", other => other, }; Property::ALL.into_iter().find(|p| p.key() == s) @@ -108,20 +252,30 @@ impl Property { /// Values a key may hold (commands reject others; files are clamped into it). pub fn range(self) -> std::ops::RangeInclusive { match self { + Property::Filter(f) => f.param.range(), Property::X | Property::Y => -1_000_000.0..=1_000_000.0, Property::ScaleX | Property::ScaleY => -1_000_000.0..=1_000_000.0, Property::Rotation => -100_000.0..=100_000.0, Property::Skew => -89.0..=89.0, Property::Alpha | Property::Tint => 0.0..=100.0, + Property::Brightness | Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => -100.0..=100.0, + Property::TintRed | Property::TintGreen | Property::TintBlue => 0.0..=255.0, + Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => -255.0..=255.0, } } - fn index(self) -> usize { - Property::ALL.iter().position(|p| *p == self).unwrap_or(0) + /// Its place in a tween's track list: [`Property::ALL`]'s order, then the filters' numbers + /// by slot. Only the first [`PROPERTIES`] index into [`Props`]. + pub(crate) fn index(self) -> usize { + match self { + Property::Filter(f) => PROPERTIES + f.index(), + p => Property::ALL.iter().position(|q| *q == p).unwrap_or(0), + } } - fn is_transform(self) -> bool { - !matches!(self, Property::Alpha | Property::Tint) + /// Position and transform (the properties the element's matrix holds). + pub fn is_transform(self) -> bool { + self.style().is_none() && !self.is_filter() } fn clamp(self, v: f32) -> f32 { @@ -132,13 +286,57 @@ impl Property { /// Every property's value, indexed like [`Property::ALL`]. #[derive(Clone, Copy, Debug, PartialEq)] -pub struct Props(pub [f32; 8]); +pub struct Props(pub [f32; PROPERTIES]); impl Props { - /// An element's own values. + /// An element's own values. Colour properties come from its colour effect's style; the + /// other styles' properties hold their rest values (alpha 100 %, brightness 0, tint 0 % of + /// white, Advanced 100 % and 0). pub fn of(el: &Element) -> Props { let d = el.transform.decompose(); - Props([d.tx, d.ty, d.sx * 100.0, d.sy * 100.0, d.rotation.to_degrees(), d.skew.atan().to_degrees(), el.color.alpha * 100.0, el.color.tint_amount * 100.0]) + let mut p = Props([0.0; PROPERTIES]); + for (q, v) in [(Property::X, d.tx), (Property::Y, d.ty), (Property::ScaleX, d.sx * 100.0), (Property::ScaleY, d.sy * 100.0), (Property::Rotation, d.rotation.to_degrees()), (Property::Skew, d.skew.atan().to_degrees())] { + p.set(q, v); + } + p.set_colour(&el.color); + p + } + + /// Sets the colour properties from `fx`, as [`Props::of`] does. + fn set_colour(&mut self, fx: &ColorEffect) { + let (mut alpha, mut bright, mut tint, mut rgb, mut adv) = (1.0, 0.0, 0.0, Rgba::WHITE, ColorTransform::IDENTITY); + match *fx { + ColorEffect::None => {} + ColorEffect::Alpha(a) => alpha = a, + ColorEffect::Brightness(b) => bright = b, + ColorEffect::Tint { color, amount } => (tint, rgb) = (amount, color), + ColorEffect::Advanced(t) => adv = t, + } + self.set(Property::Alpha, alpha * 100.0); + self.set(Property::Brightness, bright * 100.0); + self.set(Property::Tint, tint * 100.0); + self.set(Property::TintRed, rgb.r * 255.0); + self.set(Property::TintGreen, rgb.g * 255.0); + self.set(Property::TintBlue, rgb.b * 255.0); + let values = adv.mul.iter().map(|m| m * 100.0).chain(adv.add.iter().map(|a| a * 255.0)); + for (q, v) in Property::ADVANCED.into_iter().zip(values) { + self.set(q, v); + } + } + + /// The colour effect of the styles in `styles` from these values (the other styles' values + /// are left out): one style alone is that style; several compose into Advanced (ADR 0056). + pub fn color_effect(&self, styles: &[ColorStyle]) -> ColorEffect { + let v = |p: Property| p.clamp(self.get(p)); + let on = |s: ColorStyle| styles.contains(&s); + let alpha = on(ColorStyle::Alpha).then(|| v(Property::Alpha) / 100.0); + let bright = on(ColorStyle::Brightness).then(|| v(Property::Brightness) / 100.0); + let tint = on(ColorStyle::Tint).then(|| (Rgba::new(v(Property::TintRed) / 255.0, v(Property::TintGreen) / 255.0, v(Property::TintBlue) / 255.0, 1.0), v(Property::Tint) / 100.0)); + let adv = on(ColorStyle::Advanced).then(|| { + let [rm, gm, bm, am, ro, go, bo, ao] = Property::ADVANCED.map(v); + ColorTransform { mul: [rm, gm, bm, am].map(|m| m / 100.0), add: [ro, go, bo, ao].map(|a| a / 255.0) } + }); + ColorEffect::compose(alpha, bright, tint, adv).sanitized() } pub fn get(&self, p: Property) -> f32 { self.0.get(p.index()).copied().unwrap_or(0.0) @@ -167,8 +365,35 @@ impl Props { } } +/// The object's own value of `p`: its transform's and colour effect's, or a filter's number +/// (`None` when it has no filter there with that number, ADR 0092). +pub fn own_value(el: &Element, p: Property) -> Option { + match p { + Property::Filter(f) => filter_entry(el, f.slot).and_then(|e| e.filter.param(f.param)), + p => Some(Props::of(el).get(p)), + } +} + +fn filter_entry(el: &Element, slot: u8) -> Option<&crate::FilterEntry> { + match &el.kind { + ElementKind::Symbol { filters, .. } => filters.get(usize::from(slot)), + _ => None, + } +} + +/// Every filter number the object has, in its list's order (the Motion Editor's filter rows). +pub fn filter_properties(el: &Element) -> Vec { + let ElementKind::Symbol { filters, .. } = &el.kind else { return Vec::new() }; + filters + .iter() + .take(usize::from(MAX_FILTER_SLOTS)) + .enumerate() + .flat_map(|(slot, e)| e.filter.params().iter().map(move |¶m| Property::Filter(FilterProp { slot: slot as u8, param }))) + .collect() +} + /// A property keyframe. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PropertyKey { /// Frames from the span's first frame. pub frame: u32, @@ -233,7 +458,7 @@ impl Track { } } Err(i) => { - let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or(Easing::Linear, |k| k.ease); + let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or(Easing::Linear, |k| k.ease.clone()); if self.keys.len() < MAX_KEYS { self.keys.insert(i, PropertyKey { frame, value, ease }); } @@ -258,23 +483,89 @@ impl Track { } } +/// A motion path anchor pinned to a frame (ADR 0049): the object passes the anchor exactly +/// then. Only anchors between the ends are stored; the ends are pinned to the first and last +/// position keys. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Pin { + /// Frames from the span's first frame. + pub frame: u32, + /// The anchor: path command `anchor` (0 is the start). + pub anchor: u32, +} + +/// Why an anchor can't be pinned (or a pin added) where asked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PinError { + /// The tween has no motion path. + NoPath, + /// No such anchor on the path. + NoAnchor, + /// An end: always pinned to the first or last position key. + End, + /// The frame isn't strictly between the first and last position keys (these frames). + Outside(u32, u32), + /// Pins keep the path's order (a later frame on a later anchor); this one is in the way. + Order(Pin), + /// The object is off the path at that frame (an ease overshooting an end). + OffPath, + /// The path holds as many segments as it may. + Full, +} + /// A motion tween on a keyframe span (see the module docs). +/// +/// In files the filters' tracks are kept apart, under `filter_tracks` (ADR 0092): a build from +/// before them ignores that key and opens the file, the filters then holding still. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(from = "TweenFile", into = "TweenFile")] pub struct MotionTween { /// The object it animates. When no element has this id but the keyframe holds exactly one /// element, that one is the target (so edits that replace the object keep its motion). pub target: ElementId, - /// At most one per property, in [`Property::ALL`] order. - #[serde(default, skip_serializing_if = "Vec::is_empty")] + /// At most one per property, in [`Property::ALL`] order, then the filters' numbers by slot. pub tracks: Vec, /// The motion path (ADR 0030), in the layer's space: a move and cubics (see /// [`motion_path`]). Its ends are the start and end positions; the X/Y curves give the /// timing along it. - #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option, /// Orient to path: the object turns as the path turns (relative to its turn at the start). - #[serde(default, skip_serializing_if = "is_false")] pub orient: bool, + /// Anchors between the ends pinned to frames (ADR 0049), by frame; both frames and anchors + /// increase. Files from before pins have none: only the ends are pinned. + pub pins: Vec, +} + +/// A [`MotionTween`] as files hold it. +#[derive(Clone, Serialize, Deserialize)] +struct TweenFile { + target: ElementId, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + tracks: Vec, + /// The filters' tracks (ADR 0092). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + filter_tracks: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + path: Option, + #[serde(default, skip_serializing_if = "is_false")] + orient: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pins: Vec, +} + +impl From for MotionTween { + fn from(f: TweenFile) -> MotionTween { + let mut tracks = f.tracks; + tracks.extend(f.filter_tracks); + MotionTween { target: f.target, tracks, path: f.path, orient: f.orient, pins: f.pins } + } +} + +impl From for TweenFile { + fn from(m: MotionTween) -> TweenFile { + let (filter_tracks, tracks) = m.tracks.into_iter().partition(|t| t.property.is_filter()); + TweenFile { target: m.target, tracks, filter_tracks, path: m.path, orient: m.orient, pins: m.pins } + } } fn is_false(b: &bool) -> bool { @@ -350,6 +641,9 @@ pub struct OnPath<'a> { keys: Vec<(f32, Vec2)>, /// `cum[i]`: chord length from the first position key to key `i`. cum: Vec, + /// Where the legs start and end: the first position key, each pin and the last position key, + /// as an index into `keys` and the distance along the path of the anchor pinned there. + stations: Vec<(usize, f32)>, /// Direction of travel at the start, radians. start_angle: f32, } @@ -359,34 +653,46 @@ impl OnPath<'_> { &self.walk } - /// The share of the path covered `frame` frames into the span: 0 up to the first position - /// key (and without two), 1 from the last; an overshooting ease may leave 0..1 in between. - /// Where the chords add up to nothing (a path back to its start) the object keeps an even - /// pace between the first and last position keys. + /// The share of the path covered `frame` frames into the span (see [`OnPath::distance`]). pub fn progress(&self, frame: f32) -> f32 { + let l = self.walk.length(); + if l > 0.0 { self.distance(frame) / l } else { 0.0 } + } + + /// Distance along the path at `frame`: 0 up to the first position key (and without two), the + /// whole length from the last; an overshooting ease may go beyond in between. + /// + /// The pins cut the span into legs, each from one pinned anchor to the next. On a leg, the + /// position keys inside it split it again; on each of those pieces the X/Y curves run from + /// one key's position to the next, and how far along that chord they are (signed) is how far + /// along the piece's share of the leg's stretch of path the object is, the shares being the + /// chords' lengths. Where a leg's chords add up to nothing (a loop) the object keeps an even + /// pace across it. With only the ends pinned this is ADR 0030's timing, number for number. + pub fn distance(&self, frame: f32) -> f32 { + let l = self.walk.length(); let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else { return 0.0 }; if !frame.is_finite() || frame <= first.0 || last.0 <= first.0 { return 0.0; } if frame >= last.0 { - return 1.0; - } - let total = self.cum.last().copied().unwrap_or(0.0); - if total <= 1e-4 { - return (frame - first.0) / (last.0 - first.0); + return l; } let i = self.keys.partition_point(|k| k.0 <= frame).saturating_sub(1); - let (Some(a), Some(b)) = (self.keys.get(i), self.keys.get(i + 1)) else { return 1.0 }; - let chord = b.1 - a.1; - let len = chord.length(); - let along = if len > 1e-6 { (self.tween.trace_at(&self.base, frame) - a.1).dot(chord) / len } else { 0.0 }; - let p = (self.cum.get(i).copied().unwrap_or(0.0) + along) / total; - if p.is_finite() { p } else { 0.0 } - } - - /// Distance along the path at `frame` (beyond the ends while an ease overshoots them). - pub fn distance(&self, frame: f32) -> f32 { - self.progress(frame) * self.walk.length() + let leg = self.stations.partition_point(|st| st.0 <= i).saturating_sub(1); + let (Some(&(ka, sa)), Some(&(kb, sb))) = (self.stations.get(leg), self.stations.get(leg + 1)) else { return l }; + let (Some(a), Some(b), Some(fa), Some(fb)) = (self.keys.get(i), self.keys.get(i + 1), self.keys.get(ka), self.keys.get(kb)) else { return l }; + let c0 = self.cum.get(ka).copied().unwrap_or(0.0); + let total = self.cum.get(kb).copied().unwrap_or(0.0) - c0; + let p = if total <= 1e-4 { + (frame - fa.0) / (fb.0 - fa.0) + } else { + let chord = b.1 - a.1; + let len = chord.length(); + let along = if len > 1e-6 { (self.tween.trace_at(&self.base, frame) - a.1).dot(chord) / len } else { 0.0 }; + (self.cum.get(i).copied().unwrap_or(0.0) - c0 + along) / total + }; + let p = if p.is_finite() { p } else { 0.0 }; + sa + p * (sb - sa) } /// The registration point at `frame`. Overshooting an end carries on along the path's @@ -414,7 +720,7 @@ impl OnPath<'_> { impl MotionTween { pub fn new(target: ElementId) -> MotionTween { - MotionTween { target, tracks: Vec::new(), path: None, orient: false } + MotionTween { target, tracks: Vec::new(), path: None, orient: false, pins: Vec::new() } } /// The first and last frames holding an X or Y key. @@ -433,18 +739,32 @@ impl MotionTween { /// path. pub fn on_path(&self, base: &Props) -> Option> { let walk = CurveWalk::new(self.path.as_ref()?)?; + let pins = self.live_pins(); let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| self.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); + // A pin's frame holds X/Y keys (commands see to it); a leg ends there all the same. + frames.extend(pins.iter().map(|p| p.frame)); frames.sort_unstable(); frames.dedup(); - let keys: Vec<(f32, Vec2)> = frames.into_iter().map(|f| (f as f32, self.trace_at(base, f as f32))).collect(); + let keys: Vec<(f32, Vec2)> = frames.iter().map(|&f| (f as f32, self.trace_at(base, f as f32))).collect(); let mut cum = Vec::with_capacity(keys.len()); let mut d = 0.0f32; for (i, k) in keys.iter().enumerate() { d += i.checked_sub(1).and_then(|p| keys.get(p)).map_or(0.0, |p| p.1.distance(k.1)); cum.push(d); } + let mut stations = vec![(0usize, 0.0f32)]; + for pin in &pins { + if let (Ok(i), Some(s)) = (frames.binary_search(&pin.frame), walk.anchor_distance(pin.anchor as usize)) + && stations.last().is_some_and(|l| l.0 < i) + { + stations.push((i, s)); + } + } + if keys.len() > 1 { + stations.push((keys.len() - 1, walk.length())); + } let t = walk.tangent(0.0); - Some(OnPath { tween: self, base: *base, start_angle: t.y.atan2(t.x), walk, keys, cum }) + Some(OnPath { tween: self, base: *base, start_angle: t.y.atan2(t.x), walk, keys, cum, stations }) } /// The registration point on each of the span's first `frames` frames (at most a day of @@ -460,13 +780,21 @@ impl MotionTween { /// A motion path through the X/Y curves' positions at their keys, as straight segments: /// the path a tween without one shows, made editable. `None` when the object doesn't move. pub fn path_from_tracks(&self, base: &Props) -> Option { + self.path_and_pins_from_tracks(base).map(|(p, _)| p) + } + + /// [`MotionTween::path_from_tracks`] with the position keys between the ends pinned to the + /// anchors they made (the first key at a place, where the object holds still a while). + pub fn path_and_pins_from_tracks(&self, base: &Props) -> Option<(Path, Vec)> { let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| self.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); frames.sort_unstable(); frames.dedup(); let mut pts: Vec = Vec::new(); + let mut pins = Vec::new(); for f in frames.into_iter().take(MAX_PATH_SEGMENTS + 1) { let q = self.trace_at(base, f as f32); if pts.last().is_none_or(|l| l.distance(q) > 1e-3) { + pins.push(Pin { frame: f, anchor: pts.len() as u32 }); pts.push(q); } } @@ -476,16 +804,64 @@ impl MotionTween { for q in rest { p.line_to(*q); } - motion_path(&p) + let path = motion_path(&p)?; + let n = path.cmds.len(); + pins.retain(|p| p.anchor > 0 && (p.anchor as usize) + 1 < n); + Some((path, pins)) + } + + /// The pins in force: between the ends in both frame and anchor, frames and anchors + /// increasing. Others are ignored (and dropped when a file is loaded). + pub fn live_pins(&self) -> Vec { + let (Some(path), Some((f0, f1))) = (&self.path, self.position_range()) else { return Vec::new() }; + let n = path.cmds.len(); + let mut out: Vec = Vec::new(); + for p in &self.pins { + let inside = p.frame > f0 && p.frame < f1 && p.anchor > 0 && (p.anchor as usize).saturating_add(1) < n; + if inside && out.last().is_none_or(|q| q.frame < p.frame && q.anchor < p.anchor) { + out.push(*p); + } + } + out + } + + /// Every anchor tied to a frame, in order: the start at the first position key, the pins, + /// and the end at the last. A tween without a path of its own gives those of the straight + /// path its X/Y curves trace. Empty while the object doesn't move. + pub fn pinned_anchors(&self, base: &Props) -> Vec { + let Some((f0, f1)) = self.position_range().filter(|(a, b)| b > a) else { return Vec::new() }; + let (n, pins) = match &self.path { + Some(p) => (p.cmds.len(), self.live_pins()), + None => match self.path_and_pins_from_tracks(base) { + Some((p, pins)) => (p.cmds.len(), pins), + None => return Vec::new(), + }, + }; + let mut v = Vec::with_capacity(pins.len() + 2); + v.push(Pin { frame: f0, anchor: 0 }); + v.extend(pins); + v.push(Pin { frame: f1, anchor: n.saturating_sub(1) as u32 }); + v } /// Gives the tween motion path `path` (made a [`motion_path`]; false when nothing usable /// is left). Its ends become the X/Y keys at the first and last position keys, or at the /// span's first frame and frame `last` when there are none, so the curves start and end - /// where the path does. + /// where the path does; each pinned anchor's place becomes the X/Y keys on its frame. + /// + /// A tween without a path of its own shows the straight one through its position keys, + /// which are pinned to its anchors: a path with as many anchors is that one edited, and + /// keeps them pinned. Pins on anchors the new path doesn't have are let go, with their keys. pub fn set_path(&mut self, path: &Path, base: &Props, last: u32) -> bool { let Some(p) = motion_path(path) else { return false }; let Some((a, b)) = path_ends(&p) else { return false }; + if self.path.is_none() + && self.pins.is_empty() + && let Some((implied, pins)) = self.path_and_pins_from_tracks(base) + && implied.cmds.len() == p.cmds.len() + { + self.pins = pins; + } let (f0, f1) = match self.position_range() { Some((f0, f1)) if f1 > f0 => (f0, f1), _ if last > 0 => (0, last), @@ -501,7 +877,184 @@ impl MotionTween { self.set_key(prop, f1, v1, base.get(prop)); } } + let n = p.cmds.len(); self.path = Some(p); + let (keep, gone): (Vec, Vec) = self.pins.iter().partition(|q| q.anchor > 0 && (q.anchor as usize).saturating_add(1) < n); + self.pins = keep; + for q in gone { + self.remove_pin_keys(q.frame); + } + self.sync_pins(base); + true + } + + /// Writes each pinned anchor's place as the X/Y keys on its frame (leaving keys alone that + /// already hold it, so editing elsewhere keeps the timing exactly). + fn sync_pins(&mut self, base: &Props) { + let Some(path) = self.path.clone() else { return }; + for pin in self.live_pins() { + let Some(q) = path.point(pin.anchor as usize, ANCHOR) else { continue }; + for (prop, v) in [(Property::X, q.x), (Property::Y, q.y)] { + let holds = self.track(prop).and_then(|t| t.key_at(pin.frame).and_then(|i| t.keys.get(i))).is_some_and(|k| k.value == v); + if !holds { + self.set_key(prop, pin.frame, v, base.get(prop)); + } + } + } + } + + /// Removes the X/Y keys a pin held on `frame`, unless that frame is an end's. + fn remove_pin_keys(&mut self, frame: u32) { + if self.position_range().is_some_and(|(f0, f1)| f0 < frame && frame < f1) { + self.remove_track_key(Property::X, frame); + self.remove_track_key(Property::Y, frame); + } + } + + /// Pins anchor `anchor` to `frame`: the object passes it exactly then, and the X/Y keys on + /// that frame hold its place. A pin already on that frame, or that anchor's pin on another + /// frame, gives way. + pub fn pin(&mut self, anchor: usize, frame: u32, base: &Props) -> Result<(), PinError> { + let Some(path) = &self.path else { return Err(PinError::NoPath) }; + let n = path.cmds.len(); + if anchor >= n { + return Err(PinError::NoAnchor); + } + if anchor == 0 || anchor + 1 == n { + return Err(PinError::End); + } + let (f0, f1) = self.position_range().unwrap_or((0, 0)); + if !(f0 < frame && frame < f1) { + return Err(PinError::Outside(f0, f1)); + } + let Some(q) = path.point(anchor, ANCHOR) else { return Err(PinError::NoAnchor) }; + let a = anchor as u32; + let live = self.live_pins(); + if let Some(p) = live.iter().find(|p| p.frame != frame && p.anchor != a && (p.frame < frame) != (p.anchor < a)) { + return Err(PinError::Order(*p)); + } + self.pins = live; + if let Some(old) = self.pins.iter().find(|p| p.anchor == a && p.frame != frame).copied() { + self.unpin(old.frame); + } + self.pins.retain(|p| p.frame != frame); + let i = self.pins.partition_point(|p| p.frame < frame); + self.pins.insert(i, Pin { frame, anchor: a }); + for (prop, v) in [(Property::X, q.x), (Property::Y, q.y)] { + self.set_key(prop, frame, v, base.get(prop)); + } + Ok(()) + } + + /// Pins the path where the object is on `frame`: on the anchor there, or on a new one (the + /// path's shape unchanged). The anchor pinned. + pub fn pin_here(&mut self, frame: u32, base: &Props) -> Result { + if self.path.is_none() { + return Err(PinError::NoPath); + } + let (f0, f1) = self.position_range().unwrap_or((0, 0)); + if !(f0 < frame && frame < f1) { + return Err(PinError::Outside(f0, f1)); + } + if let Some(p) = self.live_pins().into_iter().find(|p| p.frame == frame) { + return Ok(p.anchor as usize); + } + let (s, l, (cmd, t)) = { + let op = self.on_path(base).ok_or(PinError::NoPath)?; + let s = op.distance(frame as f32); + (s, op.walk().length(), op.walk().locate(s)) + }; + if !(0.0..=l).contains(&s) { + return Err(PinError::OffPath); + } + let mut trial = self.clone(); + let anchor = if t <= 1e-3 { + cmd.saturating_sub(1) + } else if t >= 1.0 - 1e-3 { + cmd + } else { + if self.path.as_ref().is_some_and(|p| p.cmds.len() > MAX_PATH_SEGMENTS) { + return Err(PinError::Full); + } + if !trial.split_path(cmd, t) { + return Err(PinError::OffPath); + } + cmd + }; + trial.pin(anchor, frame, base)?; + *self = trial; + Ok(anchor) + } + + /// Splits the path's segment `cmd` at curve parameter `t` (the curve unchanged; the new + /// anchor is `cmd`). Pins after it stay on their anchors. False when there is no such + /// segment. + pub fn split_path(&mut self, cmd: usize, t: f32) -> bool { + let Some(path) = self.path.as_mut() else { return false }; + if !path.split_segment(cmd, t) { + return false; + } + for p in &mut self.pins { + if p.anchor as usize >= cmd { + p.anchor = p.anchor.saturating_add(1); + } + } + true + } + + /// Deletes anchor `i` between the ends, refitting the two segments around it as one + /// ([`Path::merge_at`]). A pin on it goes, with its keys; later pins stay on their anchors. + /// False when it can't be deleted (an end, or no such anchor). + pub fn delete_anchor(&mut self, i: usize) -> bool { + let Some(path) = self.path.as_mut() else { return false }; + if !path.merge_at(i) { + return false; + } + if let Some(frame) = self.pins.iter().find(|p| p.anchor as usize == i).map(|p| p.frame) { + self.unpin(frame); + } + for p in &mut self.pins { + if p.anchor as usize > i { + p.anchor -= 1; + } + } + true + } + + /// Lets the pin on `frame` go: its X/Y keys go with it and its anchor shapes the path only + /// (ADR 0038's behaviour). The pin, if there was one. + pub fn unpin(&mut self, frame: u32) -> Option { + let i = self.pins.iter().position(|p| p.frame == frame)?; + let pin = self.pins.remove(i); + self.remove_pin_keys(frame); + Some(pin) + } + + /// Moves anchor `anchor` (its handles with it) by `d`; an end or a pin takes its keys along. + pub fn move_anchor(&mut self, anchor: usize, d: Vec2, base: &Props, last: u32) -> bool { + let Some(mut path) = self.path.clone() else { return false }; + path.move_anchor(anchor, d) && self.set_path(&path, base, last) + } + + /// Carries the path on from its end to `to`, reached on `frame` after the last position key: + /// the old end stays pinned to its frame and the new straight stretch ends the motion. False + /// (nothing changed) when the path is full or `frame` isn't after the last position key. + pub fn extend_to(&mut self, frame: u32, to: Vec2, base: &Props) -> bool { + let (Some(path), Some((f0, f1))) = (&self.path, self.position_range()) else { return false }; + if frame <= f1 || f1 <= f0 || path.cmds.len() > MAX_PATH_SEGMENTS { + return false; + } + let n = path.cmds.len(); + let mut longer = path.clone(); + longer.line_to(to); + let Some(longer) = motion_path(&longer).filter(|p| p.cmds.len() == n + 1) else { return false }; + let mut pins = self.live_pins(); + pins.push(Pin { frame: f1, anchor: (n - 1) as u32 }); + self.set_key(Property::X, frame, to.x, base.get(Property::X)); + self.set_key(Property::Y, frame, to.y, base.get(Property::Y)); + self.path = Some(longer); + self.pins = pins; + self.sync_pins(base); true } @@ -570,6 +1123,17 @@ impl MotionTween { if self.tracks.is_empty() && self.path.is_none() { return el; } + // The filters' numbers (ADR 0092): a track whose filter isn't there, or has no such + // number, does nothing (its filter was replaced by another kind). + if let ElementKind::Symbol { filters, .. } = &mut el.kind { + for t in self.tracks.iter().filter(|t| t.property.is_filter()) { + if let (Some(f), Some(v)) = (t.property.filter(), t.value_at(frame)) + && let Some(e) = filters.get_mut(usize::from(f.slot)) + { + e.filter.set_param(f.param, v); + } + } + } let base_props = Props::of(base); let mut props = self.props_at(&base_props, frame); let on_path = self.on_path(&base_props); @@ -587,15 +1151,29 @@ impl MotionTween { el.transform = m; } } - if let Some(t) = self.track(Property::Alpha).and_then(|t| t.value_at(frame)) { - el.color.alpha = (t / 100.0).clamp(0.0, 1.0); - } - if let Some(t) = self.track(Property::Tint).and_then(|t| t.value_at(frame)) { - el.color.tint_amount = (t / 100.0).clamp(0.0, 1.0); + // Colour: the styles keyed here and the target's own, composed (ADR 0056). + if self.tracks.iter().any(|t| t.property.style().is_some()) { + el.color = props.color_effect(&self.colour_styles(&base.color)); } el } + /// The colour effect styles the target shows over the span. As in Animate, a motion tween + /// has one colour effect: the style its colour properties are keyed in, replacing the + /// target's own (which shows while none are keyed). Keys in several styles (older files + /// keyed alpha and tint together) compose into Advanced. + pub fn colour_styles(&self, own: &ColorEffect) -> Vec { + let mut out: Vec = Vec::new(); + let keyed = self.tracks.iter().filter_map(|t| t.property.style()); + let own = (own.style() != ColorStyle::None && !self.tracks.iter().any(|t| t.property.style().is_some())).then_some(own.style()); + for s in keyed.chain(own) { + if !out.contains(&s) { + out.push(s); + } + } + out + } + /// Sets property `p`'s key at `frame`. A property's first key also gets a key on the span's /// first frame holding `base` (its value until now), so the rest of the span is unchanged. pub fn set_key(&mut self, p: Property, frame: u32, value: f32, base: f32) { @@ -604,8 +1182,8 @@ impl MotionTween { if frame > 0 { keys.push(PropertyKey { frame: 0, value: p.clamp(base), ease: Easing::Linear }); } - let at = Property::ALL.iter().position(|x| *x == p).unwrap_or(0); - let pos = self.tracks.partition_point(|t| Property::ALL.iter().position(|x| *x == t.property).unwrap_or(0) < at); + let at = p.index(); + let pos = self.tracks.partition_point(|t| t.property.index() < at); self.tracks.insert(pos, Track { property: p, keys }); } if let Some(t) = self.track_mut(p) { @@ -614,8 +1192,25 @@ impl MotionTween { } /// Removes property `p`'s key at `frame`; a track left with no keys goes. Whether a key was - /// there. + /// there. Removing the X or Y key of a pinned frame lets the pin go (with both keys). pub fn remove_key(&mut self, p: Property, frame: u32) -> bool { + if !matches!(p, Property::X | Property::Y) { + return self.remove_track_key(p, frame); + } + // Only pins in force count (removing an end's keys can leave one outside the motion). + self.pins = self.live_pins(); + if self.pins.iter().any(|q| q.frame == frame) { + let had = self.track(p).is_some_and(|t| t.key_at(frame).is_some()); + self.unpin(frame); + return had; + } + let had = self.remove_track_key(p, frame); + // An end's key gone may leave pins outside the motion: they go, never to come back. + self.pins = self.live_pins(); + had + } + + fn remove_track_key(&mut self, p: Property, frame: u32) -> bool { let Some(t) = self.track_mut(p) else { return false }; let Some(i) = t.key_at(frame) else { return false }; t.keys.remove(i); @@ -641,18 +1236,23 @@ impl MotionTween { .iter() .filter_map(|t| { let v = t.value_at(frame as f32)?; - let ease = t.segment_at(frame).and_then(|i| t.keys.get(i)).map_or(Easing::Linear, |k| k.ease); + let ease = t.segment_at(frame).and_then(|i| t.keys.get(i)).map_or(Easing::Linear, |k| k.ease.clone()); let mut keys = vec![PropertyKey { frame: 0, value: v, ease }]; - keys.extend(t.keys.iter().filter(|k| k.frame > frame).map(|k| PropertyKey { frame: k.frame - frame, ..*k })); + keys.extend(t.keys.iter().filter(|k| k.frame > frame).map(|k| PropertyKey { frame: k.frame - frame, ..k.clone() })); Some(Track { property: t.property, keys }) }) .collect(); - let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient }; + let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new() }; let Some(op) = self.on_path(base) else { return tail }; let f = frame as f32; match op.walk().tail(op.distance(f)) { - // The cut path starts where the object is; the X/Y keys go on timing it. - Some(p) => tail.path = Some(p), + // The cut path starts where the object is; the X/Y keys go on timing it, and the + // pins after the cut stay on their anchors (the cut segment's end is anchor 1). + Some(p) => { + let (cmd, _) = op.walk().locate(op.distance(f)); + tail.pins = self.live_pins().into_iter().filter(|q| q.frame > frame && q.anchor as usize >= cmd).map(|q| Pin { frame: q.frame - frame, anchor: q.anchor + 1 - cmd as u32 }).collect(); + tail.path = Some(p); + } // Past the path's end: the object holds where the path ended. None => { let p = op.point(f); @@ -673,10 +1273,29 @@ impl MotionTween { tail } + /// The target's filter list changed shape (ADR 0092): `map[old]` is where the filter that + /// was at slot `old` is now (`None`: it went). Its tracks follow it; the tracks of filters + /// that went go too. + pub fn remap_filters(&mut self, map: &[Option]) { + self.tracks.retain_mut(|t| { + let Some(f) = t.property.filter() else { return true }; + match map.get(usize::from(f.slot)).copied().flatten().and_then(|n| u8::try_from(n).ok()).filter(|n| *n < MAX_FILTER_SLOTS) { + Some(slot) => { + t.property = Property::Filter(FilterProp { slot, ..f }); + true + } + None => false, + } + }); + self.tracks.sort_by_key(|t| t.property.index()); + self.tracks.dedup_by_key(|t| t.property); + } + /// Whether loading must repair it (unsorted or duplicate keys, values out of range, /// duplicate or empty tracks). pub fn is_sane(&self) -> bool { self.path.as_ref().is_none_or(|p| motion_path(p).as_ref() == Some(p)) + && self.pins == self.live_pins() && self.tracks.iter().all(|t| !t.keys.is_empty() && t.is_sane()) && self.tracks.windows(2).all(|w| matches!(w, [a, b] if a.property.index() < b.property.index())) } @@ -689,6 +1308,10 @@ impl MotionTween { self.tracks.retain(|t| !t.keys.is_empty()); self.tracks.sort_by_key(|t| t.property.index()); self.tracks.dedup_by_key(|t| t.property); + self.pins.truncate(MAX_PATH_SEGMENTS); + self.pins.sort_by_key(|p| p.frame); + self.pins.dedup_by_key(|p| p.frame); + self.pins = self.live_pins(); } } @@ -709,7 +1332,7 @@ mod tests { } fn track(p: Property, keys: &[(u32, f32, Easing)]) -> Track { - Track { property: p, keys: keys.iter().map(|&(frame, value, ease)| PropertyKey { frame, value, ease }).collect() } + Track { property: p, keys: keys.iter().map(|(frame, value, ease)| PropertyKey { frame: *frame, value: *value, ease: ease.clone() }).collect() } } #[test] @@ -752,7 +1375,7 @@ mod tests { m.set_key(Property::Alpha, 10, 0.0, 100.0); let at5 = m.apply(&base, 5.0); assert_eq!(at5.transform, base.transform, "colour-only tween keeps the transform bit for bit"); - assert!((at5.color.alpha - 0.5).abs() < 1e-6); + assert!((at5.color.alpha() - 0.5).abs() < 1e-6 && at5.color.style() == ColorStyle::Alpha); } #[test] @@ -769,7 +1392,7 @@ mod tests { t.keys[0].ease = Easing::CubicOut; } m.set_key(Property::X, 4, 70.0, 50.0); - assert_eq!(m.track(Property::X).map(|t| t.keys[1].ease), Some(Easing::CubicOut)); + assert_eq!(m.track(Property::X).map(|t| t.keys[1].ease.clone()), Some(Easing::CubicOut)); assert!(m.remove_key(Property::X, 4) && !m.remove_key(Property::X, 4)); assert!(m.remove_key(Property::X, 0) && m.remove_key(Property::X, 10)); assert!(m.tracks.is_empty(), "an emptied track goes"); @@ -835,8 +1458,8 @@ mod tests { #[test] fn property_keys_round_trip() { for p in Property::ALL { - assert_eq!(Property::from_key(p.key()), Some(p)); - assert!(!p.label().is_empty() && !p.unit().is_empty() && !p.group().is_empty()); + assert_eq!(Property::from_key(&p.key()), Some(p)); + assert!(!p.label().is_empty() && (!p.unit().is_empty() || p.range() == (0.0..=255.0) || p.range() == (-255.0..=255.0)) && !p.group().is_empty()); } assert_eq!(Property::from_key("Scale X"), Some(Property::ScaleX)); assert_eq!(Property::from_key("nope"), None); @@ -866,7 +1489,7 @@ mod tests { /// X 0 → 100 and Y 0 → 100 over frames 0..20 with `ease` on both. fn diagonal(ease: Easing) -> MotionTween { let mut m = MotionTween::new(ElementId(1)); - m.tracks = vec![track(Property::X, &[(0, 0.0, ease), (20, 100.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, ease), (20, 100.0, Easing::Linear)])]; + m.tracks = vec![track(Property::X, &[(0, 0.0, ease.clone()), (20, 100.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, ease), (20, 100.0, Easing::Linear)])]; m } @@ -874,7 +1497,7 @@ mod tests { fn a_straight_path_reproduces_linear_and_eased_xy() { let base = el(1, 0.0, 0.0); for ease in [Easing::Linear, Easing::QuadIn, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3)] { - let plain = diagonal(ease); + let plain = diagonal(ease.clone()); let mut m = plain.clone(); assert!(m.set_path(&line((0.0, 0.0), (100.0, 100.0)), &Props::of(&base), 20)); assert_eq!(m.tracks, plain.tracks, "ends already in place: the keys stay as they were"); @@ -1051,4 +1674,408 @@ mod tests { m.sanitize(); assert!(m.path.is_none()); } + + // ----- anchors pinned to frames (ADR 0049) ---------------------------------------------- + + /// An S through three anchors: (0, 0), (100, 0) and (200, 0), over a hump and under a dip. + fn s_path() -> Path { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(40.0, -60.0), Vec2::new(60.0, -60.0), Vec2::new(100.0, 0.0)).cubic_to(Vec2::new(140.0, 60.0), Vec2::new(160.0, 60.0), Vec2::new(200.0, 0.0)); + p + } + + /// X 0 → 200 over frames 0..20 with `ease`, Y still: the S travelled left to right. + fn along_s(ease: Easing) -> (MotionTween, Element) { + let base = el(1, 0.0, 0.0); + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, ease), (20, 200.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, Easing::Linear), (20, 0.0, Easing::Linear)])]; + assert!(m.set_path(&s_path(), &Props::of(&base), 20)); + (m, base) + } + + fn anchor_at(m: &MotionTween, i: usize) -> Vec2 { + m.path.as_ref().and_then(|p| p.point(i, ANCHOR)).unwrap() + } + + #[test] + fn the_object_passes_each_pinned_anchor_on_its_frame() { + let (mut m, base) = along_s(Easing::QuadIn); + let props = Props::of(&base); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) > 10.0, "unpinned, the middle anchor is passed when the timing says"); + assert_eq!(m.pin(1, 6, &props), Ok(())); + assert_eq!(m.pins, vec![Pin { frame: 6, anchor: 1 }]); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) < 1e-3, "{:?}", at(&m, &base, 6.0)); + assert!(at(&m, &base, 0.0).distance(Vec2::ZERO) < 1e-3 && at(&m, &base, 20.0).distance(Vec2::new(200.0, 0.0)) < 1e-3, "the ends stay pinned"); + // Pinning where the object is adds an anchor there and moves nothing on that frame. + let was = at(&m, &base, 14.0); + assert_eq!(m.pin_here(14, &props), Ok(2)); + assert_eq!(m.path.as_ref().map(|p| p.cmds.len()), Some(4)); + assert_eq!(m.pins, vec![Pin { frame: 6, anchor: 1 }, Pin { frame: 14, anchor: 2 }]); + assert!(at(&m, &base, 14.0).distance(was) < 0.01, "{:?} vs {was:?}", at(&m, &base, 14.0)); + assert_eq!(m.pin_here(14, &props), Ok(2), "already pinned there"); + // Moving a pinned anchor takes the object with it on that frame, and its keys follow. + assert!(m.move_anchor(2, Vec2::new(0.0, 50.0), &props, 20)); + let a2 = anchor_at(&m, 2); + assert!(at(&m, &base, 14.0).distance(a2) < 1e-3); + assert_eq!(m.track(Property::Y).and_then(|t| t.key_at(14).map(|i| t.keys[i].value)), Some(a2.y)); + assert!(at(&m, &base, 6.0).distance(Vec2::new(100.0, 0.0)) < 1e-3, "the other pin holds"); + // What can't be pinned says why, and changes nothing. + let before = m.clone(); + assert_eq!(m.pin(1, 16, &props), Err(PinError::Order(Pin { frame: 14, anchor: 2 }))); + assert_eq!(m.pin(0, 5, &props), Err(PinError::End)); + assert_eq!(m.pin(3, 5, &props), Err(PinError::End)); + assert_eq!(m.pin(9, 5, &props), Err(PinError::NoAnchor)); + assert_eq!(m.pin(1, 25, &props), Err(PinError::Outside(0, 20))); + assert_eq!(m.pin_here(0, &props), Err(PinError::Outside(0, 20))); + assert_eq!(m, before); + // Re-pinning an anchor to another frame retimes it. + assert_eq!(m.pin(1, 4, &props), Ok(())); + assert_eq!(m.pins, vec![Pin { frame: 4, anchor: 1 }, Pin { frame: 14, anchor: 2 }]); + assert!(at(&m, &base, 4.0).distance(Vec2::new(100.0, 0.0)) < 1e-3); + assert!(m.track(Property::X).is_some_and(|t| t.key_at(6).is_none()), "the old frame's keys went with the pin"); + assert!(m.is_sane()); + } + + #[test] + fn between_pins_the_eases_time_the_object_as_before() { + // A straight path with an anchor at x = 30 pinned to frame 10: it reproduces the X curve + // exactly, eases and overshoot included, on both legs. + let base = el(1, 0.0, 0.0); + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(30.0, 0.0)).line_to(Vec2::new(100.0, 0.0)); + for second in [Easing::QuadIn, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3)] { + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, Easing::QuadIn), (20, 100.0, Easing::Linear)])]; + assert!(m.set_path(&p, &Props::of(&base), 20)); + assert_eq!(m.pin(1, 10, &Props::of(&base)), Ok(())); + if let Some(t) = m.track_mut(Property::X) { + t.keys[1].ease = second.clone(); + } + let x = m.track(Property::X).cloned().unwrap(); + for i in 0..=80 { + let f = i as f32 / 4.0; + let q = at(&m, &base, f); + assert!((q.x - x.value_at(f).unwrap()).abs() < 2e-3 && q.y.abs() < 1e-3, "{second:?} frame {f}: {q:?} vs {:?}", x.value_at(f)); + } + } + } + + #[test] + fn unpinning_gives_back_the_unpinned_motion() { + let (m, base) = along_s(Easing::CubicOut); + let props = Props::of(&base); + let mut pinned = m.clone(); + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(at(&pinned, &base, 5.0).distance(at(&m, &base, 5.0)) > 1.0, "pinning retimes"); + assert_eq!(pinned.unpin(8), Some(Pin { frame: 8, anchor: 1 })); + assert_eq!(pinned, m, "pin then unpin: the same tween, keys and all"); + assert_eq!(pinned.unpin(8), None); + // A pin added where the object was leaves its anchor behind, shaping only: the motion + // is ADR 0038's again (the split curve is the same curve). + let mut here = m.clone(); + assert!(here.pin_here(12, &props).is_ok()); + assert!(here.unpin(12).is_some()); + assert_eq!(here.path.as_ref().map(|p| p.cmds.len()), Some(4)); + for f in 0..=20 { + assert!(at(&here, &base, f as f32).distance(at(&m, &base, f as f32)) < 0.01, "frame {f}"); + } + // Removing the X (or Y) key of a pinned frame lets the pin go, with both keys. + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(pinned.remove_key(Property::X, 8)); + assert!(pinned.pins.is_empty() && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_none())); + assert_eq!(pinned, m); + // Removing the end's keys lets a pin that is no longer between the ends go; its keys + // stay as plain keys, removed one by one. + assert_eq!(pinned.pin(1, 8, &props), Ok(())); + assert!(pinned.remove_key(Property::X, 20) && pinned.remove_key(Property::Y, 20)); + assert!(pinned.pins.is_empty(), "frame 8 is the last position key now: an end"); + assert!(pinned.remove_key(Property::X, 8)); + assert!(pinned.track(Property::X).is_some_and(|t| t.key_at(8).is_none()) && pinned.track(Property::Y).is_some_and(|t| t.key_at(8).is_some())); + assert!(pinned.is_sane()); + } + + /// ADR 0030's timing as it was before pins: what files without pins must still give. + fn legacy_point(m: &MotionTween, base: &Props, frame: f32) -> Vec2 { + let walk = CurveWalk::new(m.path.as_ref().unwrap()).unwrap(); + let mut frames: Vec = [Property::X, Property::Y].into_iter().filter_map(|p| m.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).collect(); + frames.sort_unstable(); + frames.dedup(); + let keys: Vec<(f32, Vec2)> = frames.into_iter().map(|f| (f as f32, m.trace_at(base, f as f32))).collect(); + let mut cum = Vec::new(); + let mut d = 0.0f32; + for (i, k) in keys.iter().enumerate() { + d += i.checked_sub(1).and_then(|p| keys.get(p)).map_or(0.0, |p| p.1.distance(k.1)); + cum.push(d); + } + let progress = (|| { + let (first, last) = (keys.first()?, keys.last()?); + if !frame.is_finite() || frame <= first.0 || last.0 <= first.0 { + return Some(0.0); + } + if frame >= last.0 { + return Some(1.0); + } + let total = *cum.last()?; + if total <= 1e-4 { + return Some((frame - first.0) / (last.0 - first.0)); + } + let i = keys.partition_point(|k| k.0 <= frame).saturating_sub(1); + let (a, b) = (keys.get(i)?, keys.get(i + 1)?); + let chord = b.1 - a.1; + let len = chord.length(); + let along = if len > 1e-6 { (m.trace_at(base, frame) - a.1).dot(chord) / len } else { 0.0 }; + let p = (cum[i] + along) / total; + Some(if p.is_finite() { p } else { 0.0 }) + })() + .unwrap_or(1.0); + let (s, l) = (progress * walk.length(), walk.length()); + if s < 0.0 { + walk.at(0.0) + walk.tangent(0.0) * s + } else if s > l { + walk.at(l) + walk.tangent(l) * (s - l) + } else { + walk.at(s) + } + } + + #[test] + fn tweens_without_pins_evaluate_exactly_as_before() { + let base = el(1, 0.0, 0.0); + let props = Props::of(&base); + let mut cases = Vec::new(); + for ease in [Easing::Linear, Easing::QuadOut, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3), Easing::CubicBezier(0.5, -0.6, 0.5, 1.6)] { + let mut m = diagonal(ease.clone()); + assert!(m.set_path(&quarter(100.0), &props, 20)); + cases.push(m.clone()); + // Position keys in the middle are timing keys, not pins, in ADR 0030 files. + m.set_key(Property::Y, 8, 30.0, 0.0); + m.set_key(Property::X, 13, 70.0, 0.0); + cases.push(m.clone()); + let mut s = along_s(ease).0; + s.set_key(Property::X, 5, 20.0, 0.0); + cases.push(s); + } + let mut ring = Path::new(); + ring.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(40.0, 0.0)).line_to(Vec2::new(40.0, 40.0)).line_to(Vec2::new(0.0, 40.0)).close(); + let mut l = MotionTween::new(ElementId(1)); + assert!(l.set_path(&ring, &props, 16)); + cases.push(l); + for m in &cases { + assert!(m.pins.is_empty() && m.is_sane()); + let op = m.on_path(&props).unwrap(); + for i in -4..=120 { + let f = i as f32 / 4.0; + assert_eq!(op.point(f), legacy_point(m, &props, f), "frame {f}"); + } + let json = serde_json::to_string(m).unwrap(); + assert!(!json.contains("pins"), "nothing new is written for them"); + } + } + + #[test] + fn a_path_made_from_the_tracks_keeps_their_keys_pinned() { + // Right 100 over 10 frames, then down 100: no path yet, but an anchor at the corner. + let base = el(1, 0.0, 0.0); + let props = Props::of(&base); + let mut m = MotionTween::new(ElementId(1)); + m.tracks = vec![track(Property::X, &[(0, 0.0, Easing::Linear), (10, 100.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, Easing::Linear), (10, 0.0, Easing::Linear), (20, 100.0, Easing::Linear)])]; + let (mut path, pins) = m.path_and_pins_from_tracks(&props).unwrap(); + assert_eq!(pins, vec![Pin { frame: 10, anchor: 1 }]); + assert_eq!(m.pinned_anchors(&props), vec![Pin { frame: 0, anchor: 0 }, Pin { frame: 10, anchor: 1 }, Pin { frame: 20, anchor: 2 }], "shown pinned before it is a path"); + // Dragging the corner up edits that path: the corner stays pinned to frame 10. + assert!(path.move_anchor(1, Vec2::new(0.0, -40.0))); + assert!(m.set_path(&path, &props, 20)); + assert_eq!(m.pins, pins); + assert!(at(&m, &base, 10.0).distance(Vec2::new(100.0, -40.0)) < 1e-3); + // A path of another shape is a new path: only its ends are pinned. + let mut fresh = m.clone(); + fresh.path = None; + fresh.pins.clear(); + assert!(fresh.set_path(&line((0.0, 0.0), (100.0, 100.0)), &props, 20)); + assert!(fresh.pins.is_empty()); + } + + #[test] + fn splitting_keeps_the_pins_after_the_cut() { + let (mut m, base) = along_s(Easing::Linear); + let props = Props::of(&base); + assert_eq!(m.pin(1, 6, &props), Ok(())); + for cut in [3u32, 6, 10] { + let tail = m.split_at(&props, cut); + let tail_base = m.apply(&base, cut as f32); + assert_eq!(tail.pins.len(), usize::from(cut < 6), "cut {cut}"); + for f in cut..=24 { + let (a, b) = (at(&m, &base, f as f32), at(&tail, &tail_base, (f - cut) as f32)); + assert!(a.distance(b) < 0.05, "cut {cut} frame {f}: {a:?} vs {b:?}"); + } + } + } + + #[test] + fn moving_on_past_the_end_carries_the_path_on() { + let (mut m, base) = along_s(Easing::Linear); + let props = Props::of(&base); + let before: Vec = (0..=20).map(|f| at(&m, &base, f as f32)).collect(); + assert!(!m.extend_to(20, Vec2::new(250.0, 50.0), &props), "only after the last position key"); + assert!(m.extend_to(28, Vec2::new(250.0, 50.0), &props)); + assert_eq!(m.position_range(), Some((0, 28))); + assert_eq!(m.pins, vec![Pin { frame: 20, anchor: 2 }], "the old end stays pinned to its frame"); + assert!(at(&m, &base, 28.0).distance(Vec2::new(250.0, 50.0)) < 1e-3); + assert!(at(&m, &base, 24.0).distance(Vec2::new(225.0, 25.0)) < 1e-2, "on to the new end in a straight line"); + for (f, b) in before.iter().enumerate() { + assert!(at(&m, &base, f as f32).distance(*b) < 1e-2, "frame {f}: as it was"); + } + } + + #[test] + fn loading_drops_pins_that_cannot_hold() { + let (mut m, _) = along_s(Easing::Linear); + m.pins = vec![Pin { frame: 5, anchor: 9 }, Pin { frame: 3, anchor: 1 }, Pin { frame: 3, anchor: 1 }, Pin { frame: 25, anchor: 1 }, Pin { frame: 0, anchor: 1 }]; + assert!(!m.is_sane()); + m.sanitize(); + assert!(m.is_sane()); + assert_eq!(m.pins, vec![Pin { frame: 3, anchor: 1 }]); + let json = serde_json::to_string(&m).unwrap(); + assert!(json.contains("\"pins\"")); + assert_eq!(serde_json::from_str::(&json).unwrap(), m); + // Without a path nothing is pinned. + m.path = None; + assert!(!m.is_sane()); + m.sanitize(); + assert!(m.pins.is_empty()); + } + + /// A movie clip instance with `filters`, at (x, 0). + fn clip(x: f32, filters: Vec) -> Element { + Element { + kind: ElementKind::Symbol { symbol: crate::SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: filters.into_iter().map(crate::FilterEntry::from).collect(), events: Vec::new() }, + ..el(1, x, 0.0) + } + } + + fn blur_x(e: &Element, slot: usize) -> Option { + match &e.kind { + ElementKind::Symbol { filters, .. } => filters.get(slot).and_then(|f| f.filter.param(FilterParam::BlurX)), + _ => None, + } + } + + fn fp(slot: u8, param: FilterParam) -> Property { + Property::Filter(FilterProp { slot, param }) + } + + /// ADR 0092: a filter's number tweens like any property, eased per segment; untracked + /// numbers and the other filters keep the object's own. + #[test] + fn a_blur_tweens_on_its_own_curve() { + let blur = crate::Filter::new("blur").unwrap(); + let shadow = crate::Filter::new("drop_shadow").unwrap(); + let base = clip(0.0, vec![shadow.clone(), blur]); + let mut m = MotionTween::new(ElementId(1)); + m.set_key(fp(1, FilterParam::BlurX), 10, 25.0, 5.0); + assert_eq!(m.track(fp(1, FilterParam::BlurX)).map(|t| t.keys.len()), Some(2), "the first key pins the span's start to the object's own value"); + assert_eq!(blur_x(&m.apply(&base, 0.0), 1), Some(5.0)); + assert_eq!(blur_x(&m.apply(&base, 4.0), 1), Some(13.0)); + assert_eq!(blur_x(&m.apply(&base, 10.0), 1), Some(25.0)); + assert_eq!(blur_x(&m.apply(&base, 4.0), 0), shadow.param(FilterParam::BlurX), "the shadow keeps its own blur"); + let at4 = m.apply(&base, 4.0); + assert_eq!((at4.transform, at4.color), (base.transform, base.color), "a filter-only tween keeps the transform and colour bit for bit"); + // Eased: CubicOut on 0..10. + if let Some(k) = m.track_mut(fp(1, FilterParam::BlurX)).and_then(|t| t.keys.first_mut()) { + k.ease = Easing::CubicOut; + } + let want = 5.0 + 20.0 * Easing::CubicOut.apply(0.4); + assert!((blur_x(&m.apply(&base, 4.0), 1).unwrap() - want).abs() < 1e-4); + // Strength is shown in percent; the filter holds a multiplier. + m.set_key(fp(0, FilterParam::Strength), 10, 300.0, 100.0); + let ElementKind::Symbol { filters, .. } = &m.apply(&base, 5.0).kind else { panic!() }; + let crate::Filter::DropShadow { strength, .. } = filters[0].filter else { panic!() }; + assert!((strength - 2.0).abs() < 1e-5, "{strength}"); + // A track whose filter isn't there (or is another kind) does nothing, and never panics. + let plain = clip(0.0, vec![crate::Filter::new("adjust_color").unwrap()]); + assert_eq!(m.apply(&plain, 5.0).kind, plain.kind); + let shape = el(1, 0.0, 0.0); + assert_eq!(m.apply(&shape, 5.0), shape); + assert_eq!(own_value(&base, fp(1, FilterParam::BlurX)), Some(5.0)); + assert_eq!(own_value(&base, fp(1, FilterParam::Angle)), None, "a blur has no angle"); + assert_eq!(own_value(&base, fp(5, FilterParam::BlurX)), None); + assert_eq!(filter_properties(&base).len(), 5 + 2); + } + + /// In files a filter's track sits under `filter_tracks`, addressed `filter..`, + /// so a build from before them still opens the file (the filters hold still there). + #[test] + fn filter_tracks_round_trip_apart_from_the_others() { + let mut m = MotionTween::new(ElementId(1)); + m.set_key(Property::X, 10, 50.0, 0.0); + m.set_key(fp(2, FilterParam::Hue), 10, 90.0, 0.0); + let v = serde_json::to_value(&m).unwrap(); + assert_eq!(v["tracks"].as_array().map(Vec::len), Some(1)); + assert_eq!(v["tracks"][0]["property"], "x"); + assert_eq!(v["filter_tracks"][0]["property"], "filter.2.hue"); + let back: MotionTween = serde_json::from_value(v).unwrap(); + assert_eq!(back, m); + // Without filter tracks the file is exactly as before. + let mut plain = MotionTween::new(ElementId(1)); + plain.set_key(Property::X, 10, 50.0, 0.0); + assert!(serde_json::to_value(&plain).unwrap().get("filter_tracks").is_none()); + // Keys parse and print the same; nonsense is refused. + for k in ["filter.0.blur_x", "filter.15.distance", "filter.3.strength"] { + assert_eq!(Property::from_key(k).map(Property::key).as_deref(), Some(k)); + } + for k in ["filter.16.blur_x", "filter.0.sparkle", "filter.x.blur_x", "filter.", "filter.0"] { + assert_eq!(Property::from_key(k), None, "{k}"); + } + assert!(serde_json::from_str::(r#"{"target":1,"tracks":[{"property":"filter.99.blur_x","keys":[]}]}"#).is_err()); + assert!(!fp(0, FilterParam::BlurX).is_transform() && fp(0, FilterParam::BlurX).style().is_none()); + // Ordered after the twenty, by slot. + assert!(fp(0, FilterParam::Hue).index() > Property::AlphaOffset.index() && fp(1, FilterParam::BlurX).index() > fp(0, FilterParam::Hue).index()); + } + + /// Tracks follow their filter when the list is reordered, and go with it. + #[test] + fn filter_tracks_follow_their_filter() { + let mut m = MotionTween::new(ElementId(1)); + m.set_key(fp(0, FilterParam::BlurX), 4, 10.0, 0.0); + m.set_key(fp(1, FilterParam::Strength), 4, 10.0, 0.0); + m.set_key(fp(2, FilterParam::Hue), 4, 10.0, 0.0); + // 0 → 2, 1 gone, 2 → 0. + m.remap_filters(&[Some(2), None, Some(0)]); + let props: Vec = m.tracks.iter().map(|t| t.property).collect(); + assert_eq!(props, vec![fp(0, FilterParam::Hue), fp(2, FilterParam::BlurX)]); + assert!(m.is_sane()); + } + + /// Retiming and splitting treat filter keys as any other. + #[test] + fn filter_keys_retime_split_and_join() { + let base = clip(0.0, vec![crate::Filter::new("blur").unwrap()]); + let mut m = MotionTween::new(ElementId(1)); + m.set_key(fp(0, FilterParam::BlurX), 10, 45.0, 5.0); + m.set_key(Property::X, 20, 100.0, 0.0); + let (by, now) = m.move_keys(&[(fp(0, FilterParam::BlurX), 10)], 4, 20); + assert_eq!((by, now), (4, vec![(fp(0, FilterParam::BlurX), 14)])); + let mut s = m.clone(); + s.stretch(21, 41); + assert_eq!(s.track(fp(0, FilterParam::BlurX)).map(|t| t.keys.iter().map(|k| k.frame).collect::>()), Some(vec![0, 28])); + // Split, then join: the same motion on every frame. + let props = Props::of(&base); + let tail = m.split_at(&props, 7); + let tail_base = m.apply(&base, 7.0); + let j = m.join(&base, 7, &tail, &tail_base).expect("joins"); + for f in 0..=20 { + assert_eq!(blur_x(&j.apply(&base, f as f32), 0), blur_x(&m.apply(&base, f as f32), 0), "frame {f}"); + } + // Two tweens joined anew (not one split): each frame keeps its blur. + let mut a = MotionTween::new(ElementId(1)); + a.set_key(fp(0, FilterParam::BlurX), 9, 30.0, 5.0); + let b_base = clip(0.0, vec![crate::Filter::Blur { blur_x: 2.0, blur_y: 5.0, quality: 1 }]); + let b = MotionTween::new(ElementId(1)); + let j = a.join(&base, 10, &b, &b_base).expect("joins"); + for f in 0..10 { + assert!((blur_x(&j.apply(&base, f as f32), 0).unwrap() - blur_x(&a.apply(&base, f as f32), 0).unwrap()).abs() < 1e-4, "frame {f}"); + } + assert_eq!(blur_x(&j.apply(&base, 12.0), 0), Some(2.0), "the next span's own blur"); + assert!(j.is_sane()); + } } diff --git a/crates/doc/src/motion/retime.rs b/crates/doc/src/motion/retime.rs new file mode 100644 index 00000000..d5f0dd7c --- /dev/null +++ b/crates/doc/src/motion/retime.rs @@ -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 { + let pins = self.live_pins(); + let mut out: Vec = Vec::with_capacity(keys.len()); + let add = |out: &mut Vec, 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) { + 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 = 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 = 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 = 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 = 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 { + 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::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 = match ta { + Some(t) => { + let mut v: Vec = 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 = 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 { + 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 = (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![(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); + } +} diff --git a/crates/doc/src/nine_slice.rs b/crates/doc/src/nine_slice.rs new file mode 100644 index 00000000..e9e3d7be --- /dev/null +++ b/crates/doc/src/nine_slice.rs @@ -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 { + 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 { + 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; diff --git a/crates/doc/src/nine_slice_tests.rs b/crates/doc/src/nine_slice_tests.rs new file mode 100644 index 00000000..79029bc3 --- /dev/null +++ b/crates/doc/src/nine_slice_tests.rs @@ -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, extra: Vec) -> 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 { + 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); + } + } + } +} diff --git a/crates/doc/src/path_table.rs b/crates/doc/src/path_table.rs index 8ea7105a..5ce8d324 100644 --- a/crates/doc/src/path_table.rs +++ b/crates/doc/src/path_table.rs @@ -41,10 +41,17 @@ pub fn build_table(doc: &Document) -> Vec> { 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()); diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index e3170648..00f04fc9 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -14,11 +14,14 @@ //! frames entered, instances walked, output lines), so a `goto` loop ends in a message instead //! of a hang. -use crate::actions::as3::{Listener, ScriptOp}; +use crate::actions::as3::ir::{Base, Function, ListenEvent, Place, Prop, Value}; +use crate::actions::as3::run::{self, Stop, World}; +use crate::actions::as3::{Compiled, Decls, Problem}; use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target}; -use crate::eval::{Play, evaluate_guided, evaluate_symbol, guide_walk}; +use crate::eval::{Play, evaluate_shown, evaluate_symbol, guide_walk}; +use crate::field::{Changed, Edit, Editor, FieldLook, FieldState, chars, fit, scroll_to_caret}; use crate::sound::Started; -use crate::{Document, Element, ElementId, ElementKind, LayerKind, MAX_SYMBOL_DEPTH, SymbolId, SymbolKind, Timeline}; +use crate::{BlendMode, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, FIELD_GUTTER, Group, LayerKind, MAX_SYMBOL_DEPTH, Rgba, SoundSync, SymbolId, SymbolKind, TextBlock, TextField, TextKind, Timeline}; use anicraft_geom::{Affine, Vec2}; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; @@ -40,6 +43,13 @@ pub const MAX_OUTPUT_PER_STEP: usize = 1_000; pub const MAX_EVENTS_PER_STEP: usize = 256; /// Most listeners scripts add to one instance. pub const MAX_LISTENERS_PER_INSTANCE: usize = 16; +/// Most listeners scripts add to the stage. +pub const MAX_STAGE_LISTENERS: usize = 64; +/// Script fuel one step may use, all scripts and listeners together (each run has at most +/// [`run::FUEL_PER_RUN`]). +pub const MAX_FUEL_PER_STEP: u64 = 1_000_000; +/// The random generator's seed when none is given. +pub const DEFAULT_SEED: u64 = 0; /// A timeline's playhead. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -102,22 +112,60 @@ impl Overrides { } } if let Some(a) = self.alpha { - e.color.alpha = a; + e.color = e.color.with_alpha(a); } e } } -/// A mouse listener a script added to an instance (ADR 0013 tier 2): it lives while the -/// instance (and the script's timeline) stay on the stage. +/// A listener a script added to an instance or the stage (ADR 0013 tiers 2 and 2.5): it lives +/// while the instance (and the script's timeline) stay on the stage. #[derive(Clone, Debug, PartialEq)] pub struct Listening { - pub event: ButtonEvent, - /// The timeline whose script added it: the actions run there. + pub event: ListenEvent, + /// The timeline whose script added it: the function runs there. pub owner: InstancePath, /// The function's name: the same function for the same event is added once. pub function: String, - pub actions: Arc>, + pub func: Arc, + /// When it was added (enter-frame listeners run in this order). + pub seq: u64, +} + +/// The movie's random numbers (`Math.random()`): Marsaglia's xorshift128, seeded, so a movie +/// with the same seed and input always plays the same. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rng(pub [u32; 4]); + +impl Rng { + pub fn seeded(seed: u64) -> Rng { + let lo = (seed & 0xffff_ffff) as u32; + let hi = (seed >> 32) as u32; + let mut s = [lo ^ 0x9e37_79b9, hi ^ 0x243f_6a88, 0xb7e1_5162, 0x3c6e_f372]; + if s == [0; 4] { + s[0] = 1; + } + Rng(s) + } + fn next_u32(&mut self) -> u32 { + let [x, y, z, w] = self.0; + let t = x ^ (x << 11); + let w2 = w ^ (w >> 19) ^ (t ^ (t >> 8)); + self.0 = [y, z, w, w2]; + w2 + } + /// The next number in [0, 1), from 53 random bits. + pub fn next_f64(&mut self) -> f64 { + let a = f64::from(self.next_u32() >> 5); + let b = f64::from(self.next_u32() >> 6); + (a * 67_108_864.0 + b) / 9_007_199_254_740_992.0 + } +} + +impl Default for Rng { + fn default() -> Self { + Rng::seeded(DEFAULT_SEED) + } } /// Everything that changes while a movie plays. @@ -130,8 +178,18 @@ pub struct PlayerState { pub clips: BTreeMap, /// Properties actions have set, per instance. pub props: BTreeMap, - /// Mouse listeners scripts added, per instance, in the order added. + /// Listeners scripts added, per instance, in the order added. pub listeners: BTreeMap>, + /// Listeners on the stage (keyboard and enter-frame), in the order added. + pub stage: Vec, + /// Each timeline instance's variables (ADR 0052), by name. + pub vars: BTreeMap>, + /// The random generator. + pub rng: Rng, + /// The last pointer position seen (`mouseX`/`mouseY` keep it when the pointer leaves). + pub mouse: Vec2, + /// Listeners added so far (each one's `seq`). + pub seq: u64, /// The pointer in stage space (`None` when it is outside the movie), and whether it is down. pub pointer: Option, pub down: bool, @@ -141,9 +199,22 @@ pub struct PlayerState { pub pressed: Option, /// Steps taken since the start. pub tick: u64, + /// Each text field a script or the viewer has touched (ADR 0066), by instance path. + pub fields: BTreeMap, + /// The field that has the keyboard (an input field, or a selectable dynamic one). + pub focus: Option, + /// Shift is held (key code 16 down): caret moves extend the selection. + pub shift: bool, + /// The pointer went down in the focused field and is selecting as it drags. + pub selecting: bool, } impl PlayerState { + /// A state before the first frame, with the random generator seeded. + pub fn seeded(seed: u64) -> PlayerState { + PlayerState { rng: Rng::seeded(seed), ..PlayerState::default() } + } + /// The frame a movie clip instance shows (`len` frames long). pub fn clip_frame(&self, path: &[ElementId], len: u32) -> u32 { self.clips.get(path).map_or(0, |c| c.frame).min(len.max(1) - 1) @@ -152,21 +223,63 @@ impl PlayerState { /// The frame a button shows: Up (0), Over (1) under the pointer, Down (2) while pressed on /// it; a button whose timeline is shorter shows its last frame. pub fn button_frame(&self, path: &[ElementId], len: u32) -> u32 { - let over = self.hover.as_deref() == Some(path); - let f = match (over, self.down && self.pressed.as_deref() == Some(path)) { - (true, true) => 2, - (true, false) => 1, - (false, _) => 0, + let f = match self.button_state(path) { + ButtonState::Down => 2, + ButtonState::Over => 1, + ButtonState::Up | ButtonState::OutDown => 0, }; f.min(len.max(1) - 1) } + /// Where the pointer leaves a button: [`ButtonState`]. + pub fn button_state(&self, path: &[ElementId]) -> ButtonState { + ButtonState::of(self.hover.as_deref(), self.pressed.as_deref(), self.down, path) + } + /// A timeline's playhead: the main timeline's for the empty path. pub fn playhead(&self, path: &[ElementId]) -> Option { if path.is_empty() { Some(self.root) } else { self.clips.get(path).copied() } } } +/// Where the pointer is for one button, as the SWF file format names a button's states: away +/// (Up), over it (Over), pressed on it (Down), or pressed on it and dragged off (shown Up). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ButtonState { + Up, + Over, + Down, + OutDown, +} + +impl ButtonState { + /// The state of the button at `path` with the pointer over `hover`, pressed on `pressed`, + /// and down or not. + pub fn of(hover: Option<&[ElementId]>, pressed: Option<&[ElementId]>, down: bool, path: &[ElementId]) -> ButtonState { + match (hover == Some(path), down && pressed == Some(path)) { + (true, true) => ButtonState::Down, + (true, false) => ButtonState::Over, + (false, true) => ButtonState::OutDown, + (false, false) => ButtonState::Up, + } + } +} + +/// The frame of a button whose sound plays when the button goes from state `from` to `to` +/// (ADR 0057), as the SWF format's button sounds are kept: the Over frame's going over it, the +/// Up frame's leaving it, the Down frame's pressing it, and the Hit frame's letting go over it. +/// Dragging off a pressed button and back plays nothing. +pub fn button_sound_frame(from: ButtonState, to: ButtonState) -> Option { + use ButtonState::*; + match (from, to) { + (Up, Over) => Some(1), + (Over, Up) => Some(0), + (Over, Down) => Some(2), + (Down, Over) => Some(3), + _ => None, + } +} + /// A pointer event, in stage coordinates. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Event { @@ -175,6 +288,13 @@ pub enum Event { Up(Vec2), /// The pointer left the movie. Leave, + /// A key went down (or repeats) and came up, by its ActionScript key code. + KeyDown(u32), + KeyUp(u32), + /// A character typed (or pasted) into the focused input field (ADR 0066). + Char(char), + /// Select All in the focused field. + SelectAll, } /// The state after a step, what the movie wrote to the Output panel (traces, and why an @@ -196,6 +316,8 @@ pub enum NodeKind { Graphic, MovieClip, Button, + /// A dynamic or input text field (ADR 0066). + Text, } /// One symbol instance on the stage (or the main timeline), as the player sees it at a state. @@ -215,11 +337,25 @@ pub struct Node { pub frames: u32, /// Local → stage. pub xf: Affine, + /// The instance's own transform and alpha in its parent, as the timeline gives them (before + /// properties scripts set). + pub local: Affine, + pub alpha: f32, /// Pointer events can reach it (visible, not mask artwork). pub hittable: bool, pub events: Vec, /// The volume its sounds get: the layers holding it, from the main timeline down. pub gain: f32, + /// A text field's block (its style, box and authored text). + pub text: Option>, +} + +impl Node { + /// A text field's block and field settings. + pub fn field(&self) -> Option<(&TextBlock, &TextField)> { + let t = self.text.as_deref()?; + Some((t, t.field.as_ref()?)) + } } /// Runs plug-in frame scripts for the player (the engine implements it over the plug-in host). @@ -228,6 +364,13 @@ pub trait ScriptHost { fn begin_step(&mut self) {} /// Runs `script` for the timeline described by `cx`; returns the actions it emitted. fn run(&mut self, script: &PluginScript, cx: &ScriptContext<'_>) -> ScriptRun; + /// Lays out `shown` (a field's text as it is drawn) in `block`'s style and box (ADR 0066): + /// the fonts live above this crate. `None`: it can't, and the field keeps its authored + /// outline until its text changes (then it draws only its box). + fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { + let _ = (block, shown); + None + } } /// What a frame script sees. @@ -261,8 +404,13 @@ impl ScriptHost for NoScripts { /// The movie at its first frame, with the first frame's actions run. pub fn start(doc: &Document, host: &mut dyn ScriptHost) -> Step { + start_seeded(doc, DEFAULT_SEED, host) +} + +/// [`start`], with `Math.random()` seeded by `seed`. +pub fn start_seeded(doc: &Document, seed: u64, host: &mut dyn ScriptHost) -> Step { host.begin_step(); - let mut r = Run::new(doc, PlayerState::default(), host); + let mut r = Run::new(doc, PlayerState::seeded(seed), host); r.refresh(); r.pending.push_front(Vec::new()); r.settle(); @@ -278,6 +426,9 @@ pub fn step(doc: &Document, state: &PlayerState, events: &[Event], host: &mut dy r.refresh(); r.remember_graphics(); r.advance(); + // Enter-frame listeners hear the new frame before its frame scripts run (as ActionScript + // dispatches `enterFrame` before frame scripts). + r.enter_frame(); r.settle(); for e in events.iter().take(MAX_EVENTS_PER_STEP) { r.event(*e); @@ -303,7 +454,7 @@ pub fn input(doc: &Document, state: &PlayerState, events: &[Event], host: &mut d /// drawing order (parents before their contents). pub fn tree(doc: &Document, st: &PlayerState) -> Vec { let tl = doc.timeline(st.scene); - let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, hittable: true, events: Vec::new(), gain: 1.0 }]; + let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, local: Affine::IDENTITY, alpha: 1.0, hittable: true, events: Vec::new(), gain: 1.0, text: None }]; // The main timeline is seen through its camera (ADR 0027): instances are where the pointer // sees them. let camera = tl.camera_at(st.root.frame, &doc.stage); @@ -316,6 +467,86 @@ pub fn hit(doc: &Document, st: &PlayerState, p: Vec2) -> Option { hit_in(doc, st, &tree(doc, st), p) } +/// The text field at stage point `p` the viewer can click into, topmost first (ADR 0066): what +/// a window shows a text cursor over. +pub fn field_at(doc: &Document, st: &PlayerState, p: Vec2) -> Option { + field_hit(&tree(doc, st), p).map(|(_, path)| path) +} + +/// The topmost focusable field node at `p`, with its index. +fn field_hit(nodes: &[Node], p: Vec2) -> Option<(usize, InstancePath)> { + for (i, n) in nodes.iter().enumerate().rev() { + if n.kind != NodeKind::Text || !n.hittable { + continue; + } + let Some((t, f)) = n.field() else { continue }; + if !f.focusable() { + continue; + } + let Some(q) = n.xf.inverse().map(|m| m.apply(p)) else { continue }; + if q.x >= 0.0 && q.y >= 0.0 && q.x <= t.box_width && q.y <= t.box_height { + return Some((i, n.path.clone())); + } + } + None +} + +/// The frame of a button's timeline, `len` frames long, that answers the pointer: the Hit +/// frame (the fourth) when it has one, otherwise the Up frame. +pub fn hit_frame(len: u32) -> u32 { + if len > 3 { 3 } else { 0 } +} + +/// The area of a button with timeline `tl` that answers the pointer, placed by `xf`: its +/// [`hit_frame`]'s artwork without guides and mask artwork (masks don't cut hit areas, and +/// shapes count however faint they are drawn). The hit test and Test Movie's hit-area overlay +/// both use it. +pub fn hit_area(doc: &Document, tl: &Timeline, xf: Affine) -> DisplayList { + let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None); + dl.items.retain(|i| !i.guide && i.masks.is_none()); + for i in &mut dl.items { + i.clip = None; + } + for g in &mut dl.groups { + g.clip = None; + } + dl +} + +/// `dl` drawn as one translucent area: every item filled and stroked in `tint` at full +/// strength, composited together and laid over what is below at `alpha`, so overlapping shapes +/// don't darken each other. +pub fn tinted(dl: DisplayList, tint: Rgba, alpha: f32) -> DisplayList { + let mut out = DisplayList::default(); + let alpha = if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 }; + out.groups.push(Group { parent: None, alpha, blend: BlendMode::default(), filters: Arc::from(Vec::new()), clip: None }); + out.append(dl); + for g in out.groups.iter_mut().skip(1) { + g.alpha = 1.0; + g.blend = BlendMode::default(); + g.filters = Arc::from(Vec::new()); + g.parent = Some(g.parent.unwrap_or(0)); + } + for it in &mut out.items { + it.color = ColorTransform::tint(tint, 1.0); + it.outline = None; + it.group = Some(it.group.unwrap_or(0)); + } + out +} + +/// Every button's hit area at `st`, each a translucent area in `tint` (Test Movie's Show Hit +/// Areas): where the pointer finds the buttons, drawn over the movie. +pub fn hit_overlay(doc: &Document, st: &PlayerState, tint: Rgba, alpha: f32) -> DisplayList { + let mut out = DisplayList::default(); + for n in tree(doc, st).iter().filter(|n| n.kind == NodeKind::Button && n.hittable) { + if let Some(sym) = n.symbol.and_then(|s| doc.symbol(s)) { + out.append(tinted(hit_area(doc, &sym.timeline, n.xf), tint, alpha)); + } + } + out +} + /// Whether timeline layer `index` takes part in playback: shown, not a folder or guide, not in /// a hidden folder (what is drawn is what plays). fn plays(tl: &Timeline, index: usize) -> bool { @@ -329,19 +560,46 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi } let base: InstancePath = out.get(parent).map(|n| n.path.clone()).unwrap_or_default(); let parent_gain = out.get(parent).map_or(1.0, |n| n.gain); - for (index, layer) in tl.layers.iter().enumerate().rev() { + // Drawn deepest first (ADR 0082), so the topmost hit is the one drawn last. + // (Only sorted when some layer has a depth: nested timelines allocate nothing.) + let sorted = (depth == 1 && 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 }; if !plays(tl, index) { continue; } let gain = parent_gain * layer.sound_gain(); let hit = hittable && layer.kind != LayerKind::Mask; let path_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, els)) = evaluate_guided(layer, frame, path_walk.as_ref()) else { continue }; - let layer_xf = camera.map_or(xf, |c| c.view(&doc.stage, layer.depth)); + let Some((kf_start, els)) = evaluate_shown(layer, frame, path_walk.as_ref(), doc.stage.fps) else { continue }; + let layer_xf = match camera { + Some(c) => match c.layer_view(&doc.stage, layer, frame) { + Some(v) => v, + None => continue, + }, + None => xf, + }; + // Instances inside a group belong to the group's timeline (ADR 0073). + let els = crate::expand_groups(&els).into_owned(); for el in els.iter() { if out.len() >= MAX_NODES { return; } + // Dynamic and input text fields are instances scripts can name (static text isn't). + if let ElementKind::Text(t) = &el.kind + && t.field.is_some() + { + let mut path = base.clone(); + path.push(el.id); + let ov = st.props.get(&path); + let shown = ov.is_none_or(Overrides::shown); + let set = ov.map(|o| o.apply(el)); + let e: &Element = set.as_ref().unwrap_or(el); + out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: None, kind: NodeKind::Text, frame: 0, frames: 0, xf: layer_xf.mul(&e.transform), local: el.transform, alpha: el.color.alpha(), hittable: hit && shown, events: Vec::new(), gain, text: Some(t.clone()) }); + continue; + } let ElementKind::Symbol { symbol, loop_mode, first_frame, events, .. } = &el.kind else { continue }; let Some(sym) = doc.symbol(*symbol) else { continue }; let mut path = base.clone(); @@ -358,7 +616,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi }; let idx = out.len(); let node_xf = layer_xf.mul(&e.transform); - out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, hittable: hit && shown, events: events.clone(), gain }); + out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, local: el.transform, alpha: el.color.alpha(), hittable: hit && shown, events: events.clone(), gain, text: None }); // Names inside a movie clip (or a button's states) are its own; a graphic's // contents belong to the timeline the graphic is on. let inner_owner = if kind == NodeKind::Graphic { owner } else { idx }; @@ -375,9 +633,7 @@ fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2) -> Option 3 { 3 } else { 0 }; - evaluate_symbol(doc, &sym.timeline, f, n.xf, None) + hit_area(doc, &sym.timeline, n.xf) } else { evaluate_symbol(doc, &sym.timeline, n.frame, n.xf, Some(&Play { state: st, path: n.path.clone() })) }; @@ -423,11 +679,16 @@ struct Run<'a, 'h> { /// The frame each graphic showed when the step began: one that shows another frame at /// its end has entered it (and starts its sounds). graphics: BTreeMap, + /// Each timeline's declarations (ADR 0052), made the first time a script there + /// needs them. + decls: BTreeMap>, + /// Script fuel left this step. + fuel: u64, } impl<'a, 'h> Run<'a, 'h> { fn new(doc: &'a Document, st: PlayerState, host: &'h mut dyn ScriptHost) -> Self { - Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new() } + Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new(), decls: BTreeMap::new(), fuel: MAX_FUEL_PER_STEP } } fn remember_graphics(&mut self) { @@ -437,12 +698,55 @@ impl<'a, 'h> Run<'a, 'h> { /// The sounds on keyframes of `tl` starting at `frame` (every layer but guides, as the /// soundtrack has them), at volume `gain` times their layer's. fn sounds_at(&mut self, tl: &Timeline, frame: u32, gain: f32) { + self.sounds_on(tl, frame, gain, false); + } + + /// [`Run::sounds_at`]; on a button's frame (`button`) a stream sound plays as an event, + /// since a button's frame has no span to stream over (ADR 0057). + fn sounds_on(&mut self, tl: &Timeline, frame: u32, gain: f32, button: bool) { for layer in tl.layers.iter().filter(|l| !matches!(l.kind, LayerKind::Guide | LayerKind::Folder | LayerKind::Camera)) { let Some(k) = layer.keyframe_starting_at(frame).and_then(|i| layer.keyframes.get(i)) else { continue }; if let Some(fs) = &k.sound && self.sounds.len() < MAX_SOUNDS_PER_STEP { - self.sounds.push(Started { sound: fs.clone(), gain: gain * layer.sound_gain(), span: k.duration }); + let mut sound = fs.clone(); + if button && sound.sync == SoundSync::Stream { + sound.sync = SoundSync::Event; + } + self.sounds.push(Started { sound, gain: gain * layer.sound_gain(), span: k.duration }); + } + } + } + + /// Where the pointer is, for [`Run::button_sounds`]: what it is over, what it went down + /// on, and whether it is down. + fn pointer_now(&self) -> (Option, Option, bool) { + (self.st.hover.clone(), self.st.pressed.clone(), self.st.down) + } + + /// Starts the sounds of the buttons whose state changed since `before` ([`pointer_now`] + /// then): the frame [`button_sound_frame`] gives for each change. + /// + /// [`pointer_now`]: Run::pointer_now + fn button_sounds(&mut self, before: (Option, Option, bool)) { + if before == self.pointer_now() { + return; + } + self.refresh(); + let (h, p, d) = &before; + let mut paths: Vec = Vec::new(); + for path in [h, p, &self.st.hover, &self.st.pressed].into_iter().flatten() { + if !paths.contains(path) { + paths.push(path.clone()); + } + } + for path in paths { + let from = ButtonState::of(h.as_deref(), p.as_deref(), *d, &path); + let Some(frame) = button_sound_frame(from, self.st.button_state(&path)) else { continue }; + let Some(n) = self.index_of(&path).and_then(|i| self.nodes.get(i)).filter(|n| n.kind == NodeKind::Button) else { continue }; + let (gain, symbol) = (n.gain, n.symbol); + if let Some(sym) = symbol.and_then(|s| self.doc.symbol(s)) { + self.sounds_on(&sym.timeline, frame, gain, true); } } } @@ -492,6 +796,14 @@ impl<'a, 'h> Run<'a, 'h> { list.retain(|l| all.contains(&l.owner)); all.contains(p) && !list.is_empty() }); + self.st.stage.retain(|l| all.contains(&l.owner)); + // A timeline's variables go with its instance, and a field's text with the field. + self.st.vars.retain(|p, _| all.contains(p)); + self.st.fields.retain(|p, _| all.contains(p)); + if self.st.focus.as_ref().is_some_and(|p| !all.contains(p)) { + self.st.focus = None; + self.st.selecting = false; + } for slot in [&mut self.st.hover, &mut self.st.pressed] { if slot.as_ref().is_some_and(|p| !all.contains(p)) { *slot = None; @@ -568,7 +880,7 @@ impl<'a, 'h> Run<'a, 'h> { match n.kind { NodeKind::Root => Some(self.doc.timeline(self.st.scene)), NodeKind::MovieClip => n.symbol.and_then(|s| self.doc.symbol(s)).map(|s| &s.timeline), - NodeKind::Graphic | NodeKind::Button => None, + NodeKind::Graphic | NodeKind::Button | NodeKind::Text => None, } } @@ -600,7 +912,7 @@ impl<'a, 'h> Run<'a, 'h> { // than a line every time the playhead passes. FrameScript::Source(src) => { if let Ok(c) = src.compiled() { - self.run_ops(path, &c.ops); + self.run_script(path, frame, c); } } } @@ -630,43 +942,260 @@ impl<'a, 'h> Run<'a, 'h> { } } - /// Runs a compiled script's steps (ADR 0013 tier 2), each one action of the budget. - fn run_ops(&mut self, owner: &[ElementId], ops: &[ScriptOp]) { - for op in ops { - if !self.budget() { + /// The declarations of the timeline node `i` is (the main timeline's span every scene). + fn decls_of(&mut self, i: usize) -> Arc { + let key = match self.nodes.get(i) { + Some(Node { kind: NodeKind::MovieClip, symbol: Some(s), .. }) => TimelineRef::Symbol(*s), + _ => TimelineRef::Root, + }; + let doc = self.doc; + self.decls.entry(key).or_insert_with(|| Arc::new(decls(doc, key))).clone() + } + + /// Runs a compiled frame script on timeline `owner` (ADR 0052): when every name + /// it takes from other frames is there, its statements run with the fuel the step has left. + fn run_script(&mut self, owner: &[ElementId], frame: u32, c: &'a Compiled) { + let Some(i) = self.index_of(owner) else { return }; + let d = self.decls_of(i); + // A script whose names don't link doesn't run (Test Movie lists why at the start). + if !d.problems(c).is_empty() { + return; + } + let where_ = format!("Script on frame {} of {}", u64::from(frame) + 1, self.timeline_name(i)); + self.run_code(owner, d, None, &where_, |w, fuel| run::run_script(w, &c.body, &c.inner, fuel)); + } + + /// Runs code on timeline `owner` with this step's fuel; writes why it stopped early. + fn run_code(&mut self, owner: &[ElementId], decls: Arc, ev: Option, where_: &str, go: impl FnOnce(&mut dyn World, u64) -> (u64, Result<(), Stop>)) { + if self.halted { + return; + } + if self.fuel == 0 { + self.halt(&format!("scripts ran more than {MAX_FUEL_PER_STEP} steps")); + return; + } + let fuel = self.fuel.min(run::FUEL_PER_RUN); + let mut w = Script { r: self, owner: owner.to_vec(), decls, ev }; + let (used, r) = go(&mut w, fuel); + self.fuel = self.fuel.saturating_sub(used); + match r { + Ok(()) | Err(Stop::Halt) => {} + Err(e) => self.out(format!("{where_} stopped: {}", e.describe())), + } + } + + /// How Output names a timeline: the main timeline, or the instance-name path of a clip. + fn timeline_name(&self, i: usize) -> String { + if i == 0 { + return "the main timeline".into(); + } + let mut names = Vec::new(); + let mut cur = i; + for _ in 0..=MAX_SYMBOL_DEPTH { + let Some(n) = self.nodes.get(cur) else { break }; + if n.kind == NodeKind::Root { + break; + } + names.push(if n.name.is_empty() { "?" } else { n.name.as_str() }); + cur = n.owner; + } + names.reverse(); + names.join(".") + } + + /// Calls listener `l` with the event. + fn call_listener(&mut self, l: &Listening, ev: EventInfo) { + self.refresh(); + let Some(i) = self.index_of(&l.owner) else { return }; + let d = self.decls_of(i); + let f = l.func.clone(); + let where_ = format!("Listener {}", l.function); + self.run_code(&l.owner, d, Some(ev), &where_, |w, fuel| run::run_listener(w, &f, fuel)); + } + + /// Every enter-frame listener, in the order they were added. + fn enter_frame(&mut self) { + self.refresh(); + let mut all: Vec<(Option, Listening)> = self.st.listeners.iter().flat_map(|(p, list)| list.iter().filter(|l| l.event == ListenEvent::EnterFrame).map(|l| (Some(p.clone()), l.clone()))).collect(); + all.extend(self.st.stage.iter().filter(|l| l.event == ListenEvent::EnterFrame).map(|l| (None, l.clone()))); + all.sort_by_key(|(_, l)| l.seq); + for (at, l) in all { + if self.halted { return; } - match op { - ScriptOp::Action(a) => self.exec(owner, a, true), - ScriptOp::Listen(l) => self.listen(owner, l), + self.call_listener(&l, EventInfo { key: None, target: at.clone(), current: at }); + self.settle(); + } + } + + /// A key event: the stage's listeners for it, in the order added. + fn key(&mut self, event: ListenEvent, code: u32) { + let list: Vec = self.st.stage.iter().filter(|l| l.event == event).cloned().collect(); + for l in list { + if self.halted { + return; + } + self.call_listener(&l, EventInfo { key: Some(code), target: None, current: None }); + self.settle(); + } + } + + /// The node an instance name stands for, from timeline node `from` (`Ok(None)`: the stage). + fn place(&self, from: usize, ev: Option<&EventInfo>, at: &Place) -> Result, String> { + let base = match at.base { + Base::This => from, + Base::Stage => { + return if at.path.is_this() { Ok(None) } else { Err("instances on the stage are named from the main timeline (root)".into()) }; + } + Base::Target | Base::Current => { + let Some(ev) = ev else { return Err("there's no event here".into()) }; + let p = if at.base == Base::Target { &ev.target } else { &ev.current }; + match p { + None if at.path.is_this() => return Ok(None), + None => return Err("the event's target is the stage".into()), + Some(p) => self.index_of(p).ok_or("the event's target has left the stage")?, + } + } + }; + self.resolve(base, &at.path).map(Some) + } + + /// The path of the node `base` starts from (for actions on the event's target). + fn base_path(&self, owner: &[ElementId], ev: Option<&EventInfo>, base: Base) -> Result { + match base { + Base::This => Ok(owner.to_vec()), + Base::Stage => Err("the stage has no playhead".into()), + Base::Target | Base::Current => { + let Some(ev) = ev else { return Err("there's no event here".into()) }; + let p = if base == Base::Target { &ev.target } else { &ev.current }; + p.clone().ok_or_else(|| "the event's target is the stage".into()) } } } - /// `addEventListener`: the instance the listener's target names gets it (once per - /// function and event). - fn listen(&mut self, owner: &[ElementId], l: &Listener) { + /// A property of node `i` (`None`: the stage). + fn property(&self, i: Option, p: Prop) -> Result { + let num = |v: f64| Ok(Value::Num(v)); + let Some(i) = i else { + return match p { + Prop::MouseX => num(short(self.st.mouse.x)), + Prop::MouseY => num(short(self.st.mouse.y)), + _ => Err(format!("the stage's `{}` isn't supported here", p.name())), + }; + }; + let Some(n) = self.nodes.get(i) else { return Err("the instance is gone".into()) }; + if n.kind == NodeKind::Root { + return match p { + Prop::X | Prop::Y | Prop::Rotation => num(0.0), + Prop::Alpha | Prop::ScaleX | Prop::ScaleY => num(1.0), + Prop::Visible => Ok(Value::Bool(true)), + Prop::CurrentFrame => num(f64::from(self.st.root.frame) + 1.0), + Prop::TotalFrames => num(self.doc.scenes.iter().map(|s| f64::from(s.timeline.frame_count())).sum()), + Prop::CurrentLabel => Ok(current_label(self.doc.timeline(self.st.scene), self.st.root.frame)), + Prop::MouseX => num(short(self.st.mouse.x)), + Prop::MouseY => num(short(self.st.mouse.y)), + Prop::Name => Ok(Value::str("root1")), + Prop::Text | Prop::Length => Err("the main timeline isn't a text field".into()), + }; + } + if matches!(p, Prop::Text | Prop::Length) { + let Some((t, _)) = n.field() else { return Err(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind))) }; + let v = self.st.fields.get(&n.path).map_or(t.text.as_str(), |f| f.value(t)); + return Ok(if p == Prop::Text { Value::str(v) } else { Value::Num(crate::actions::as3::ir::text_len(v) as f64) }); + } + let ov = self.st.props.get(&n.path).copied().unwrap_or_default(); + let d = decompose64(&n.local); + let deg = 180.0 / std::f64::consts::PI; + let pick = |o: Option, v: f64| num(o.map_or(fround_short(v), short)); + match p { + Prop::X => pick(ov.x, d[0]), + Prop::Y => pick(ov.y, d[1]), + Prop::ScaleX => pick(ov.scale_x, d[2]), + Prop::ScaleY => pick(ov.scale_y, d[3]), + Prop::Rotation => pick(ov.rotation, d[4] * deg), + Prop::Alpha => num(short(ov.alpha.unwrap_or(n.alpha))), + Prop::Visible => Ok(Value::Bool(ov.visible != Some(false))), + Prop::Name => Ok(Value::str(&n.name)), + Prop::MouseX | Prop::MouseY => { + let m = n.xf.m.map(f64::from); + let det = m[0] * m[3] - m[1] * m[2]; + if det == 0.0 || !det.is_finite() { + return num(0.0); + } + let (x, y) = (f64::from(self.st.mouse.x) - m[4], f64::from(self.st.mouse.y) - m[5]); + let v = if p == Prop::MouseX { (m[3] * x - m[2] * y) / det } else { (m[0] * y - m[1] * x) / det }; + num(fround_short(v)) + } + Prop::Text | Prop::Length => Err("not a text field".into()), + Prop::CurrentFrame | Prop::TotalFrames | Prop::CurrentLabel => { + if n.kind != NodeKind::MovieClip { + return Err(format!("“{}” is {}; only movie clips and the main timeline have frames", n.name, kind_name(n.kind))); + } + match p { + Prop::CurrentFrame => num(f64::from(n.frame) + 1.0), + Prop::TotalFrames => num(f64::from(n.frames)), + _ => Ok(n.symbol.and_then(|s| self.doc.symbol(s)).map_or(Value::Null, |s| current_label(&s.timeline, n.frame))), + } + } + } + } + + /// `addEventListener` / `removeEventListener` from timeline `owner`. + fn listen(&mut self, owner: &[ElementId], ev: Option<&EventInfo>, at: &Place, event: ListenEvent, f: &Arc, add: bool) { self.refresh(); let Some(from) = self.index_of(owner) else { return }; - let what = format!("Listen for {} ({})", l.event.key(), l.target); - let i = match self.resolve(from, &l.target) { + let what = format!("{} for {} ({at})", if add { "Listen" } else { "Stop listening" }, event.key()); + let i = match self.place(from, ev, at) { Ok(i) => i, Err(e) => return self.out(format!("{what}: {e}")), }; + let seq = self.st.seq; + let item = Listening { event, owner: owner.to_vec(), function: f.name.clone(), func: f.clone(), seq }; + let same = |x: &Listening| x.event == event && x.owner == owner && x.function == f.name; + let Some(i) = i else { + // The stage: keyboard and enter-frame listeners. + if add { + if self.st.stage.iter().any(same) { + return; + } + if self.st.stage.len() >= MAX_STAGE_LISTENERS { + return self.out(format!("{what}: the stage already has {MAX_STAGE_LISTENERS} listeners")); + } + self.st.seq += 1; + self.st.stage.push(item); + } else { + self.st.stage.retain(|x| !same(x)); + } + return; + }; let Some(node) = self.nodes.get(i) else { return }; - if !matches!(node.kind, NodeKind::Button | NodeKind::MovieClip) { - let why = if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is a graphic; only buttons and movie clips get pointer events", node.name) }; + let ok = match event { + ListenEvent::EnterFrame => node.kind != NodeKind::Graphic, + _ => matches!(node.kind, NodeKind::Button | NodeKind::MovieClip), + }; + if !ok { + let why = if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is {}; only buttons and movie clips get pointer events", node.name, kind_name(node.kind)) }; return self.out(format!("{what}: {why}")); } let (path, name) = (node.path.clone(), node.name.clone()); + if !add { + if let Some(list) = self.st.listeners.get_mut(&path) { + list.retain(|x| !same(x)); + if list.is_empty() { + self.st.listeners.remove(&path); + } + } + return; + } let list = self.st.listeners.entry(path).or_default(); - if list.iter().any(|x| x.event == l.event && x.owner == owner && x.function == l.function) { + if list.iter().any(same) { return; } if list.len() >= MAX_LISTENERS_PER_INSTANCE { return self.out(format!("{what}: “{name}” already has {MAX_LISTENERS_PER_INSTANCE} listeners")); } - list.push(Listening { event: l.event, owner: owner.to_vec(), function: l.function.clone(), actions: l.actions.clone() }); + list.push(item); + self.st.seq += 1; } /// The node `target` names, seen from timeline node `from`. @@ -719,8 +1248,7 @@ impl<'a, 'h> Run<'a, 'h> { }; let Some(node) = self.nodes.get(i) else { return }; if !matches!(node.kind, NodeKind::Root | NodeKind::MovieClip) { - let what = if node.kind == NodeKind::Button { "a button" } else { "a graphic" }; - return self.out(format!("{}: “{}” is {what}; only movie clips and the main timeline have a playhead", a.describe(), node.name)); + return self.out(format!("{}: “{}” is {}; only movie clips and the main timeline have a playhead", a.describe(), node.name, kind_name(node.kind))); } let (path, frame, frames) = (node.path.clone(), node.frame, node.frames.max(1)); match a { @@ -813,21 +1341,54 @@ impl<'a, 'h> Run<'a, 'h> { fn event(&mut self, e: Event) { self.refresh(); match e { - Event::Move(p) => self.pointer(Some(p)), + Event::Move(p) => { + self.pointer(Some(p)); + // Dragging in the focused field selects. + if self.st.selecting && self.st.down { + self.point_field(p, true); + } + } Event::Down(p) => { self.pointer(Some(p)); + // A field the viewer can use takes the press (unless a button is above it): it + // gets the keyboard and the caret goes where it was clicked. Anywhere else the + // focused field loses the keyboard. + let hover_at = self.st.hover.as_ref().and_then(|h| self.index_of(h)); + match self.field_at(p).filter(|(i, _)| hover_at.is_none_or(|h| *i > h)) { + Some((_, path)) => { + self.st.focus = Some(path); + self.st.down = true; + self.st.selecting = true; + self.point_field(p, false); + return; + } + None => { + self.st.focus = None; + self.st.selecting = false; + } + } + let before = self.pointer_now(); self.st.down = true; self.st.pressed = self.st.hover.clone(); self.dirty = true; + self.button_sounds(before); if let Some(h) = self.st.hover.clone() { self.fire(&h, ButtonEvent::Press); } } Event::Up(p) => { + if self.st.selecting { + self.st.selecting = false; + self.st.down = false; + self.pointer(Some(p)); + return; + } self.pointer(Some(p)); + let before = self.pointer_now(); self.st.down = false; let pressed = self.st.pressed.take(); self.dirty = true; + self.button_sounds(before); if let Some(h) = self.st.hover.clone() { self.fire(&h, ButtonEvent::Release); if pressed.as_ref() == Some(&h) { @@ -836,17 +1397,130 @@ impl<'a, 'h> Run<'a, 'h> { } } Event::Leave => self.pointer(None), + // Keys edit the focused field, then go to the stage's listeners as well (as they + // reach the stage from a focused field in ActionScript). + Event::KeyDown(k) => { + if k == SHIFT { + self.st.shift = true; + } + self.field_key(k); + self.key(ListenEvent::KeyDown, k); + } + Event::KeyUp(k) => { + if k == SHIFT { + self.st.shift = false; + } + self.key(ListenEvent::KeyUp, k); + } + Event::Char(c) => { + let mut b = [0u8; 4]; + let s: &str = c.encode_utf8(&mut b); + self.edit_field(|ed, _| ed.insert(s)); + } + Event::SelectAll => self.edit_field(|ed, look| ed.key(Edit::SelectAll, false, look)), } } + /// The topmost field at stage point `p` the viewer can use, with its node's index. + fn field_at(&self, p: Vec2) -> Option<(usize, InstancePath)> { + field_hit(&self.nodes, p) + } + + /// Field `path`'s block and its place on the stage. + fn field_node(&self, path: &[ElementId]) -> Option<(Arc, Affine)> { + let n = self.index_of(path).and_then(|i| self.nodes.get(i))?; + let t = n.text.clone().filter(|t| t.field.is_some())?; + Some((t, n.xf)) + } + + /// Lays field `path`'s text out as it is now (with the host's fonts) and keeps the caret + /// in the text and in view. + fn relayout(&mut self, path: &[ElementId]) { + let Some((t, _)) = self.field_node(path) else { return }; + let Some(f) = t.field.as_ref() else { return }; + let st = self.st.fields.entry(path.to_vec()).or_default(); + let shown = f.shown(st.value(&t)); + st.look = self.host.lay_out_field(&t, &shown).map(Arc::new); + let len = chars(st.value(&t)); + st.caret = st.caret.min(len); + st.anchor = st.anchor.min(len); + scroll_to_caret(&t, f, st); + } + + /// A script sets field `path`'s text. + fn set_field_text(&mut self, path: &[ElementId], text: &str) { + let Some((t, _)) = self.field_node(path) else { return }; + let Some(f) = t.field.as_ref() else { return }; + self.st.fields.entry(path.to_vec()).or_default().text = Some(fit(f, text)); + self.relayout(path); + } + + /// Runs an edit on the focused field (laying it out first if it never was). + fn edit_field(&mut self, go: impl FnOnce(&mut Editor<'_>, Option<&FieldLook>) -> Changed) { + let Some(path) = self.st.focus.clone() else { return }; + let Some((t, _)) = self.field_node(&path) else { return }; + let Some(f) = t.field.clone() else { return }; + if self.st.fields.get(&path).is_none_or(|s| s.look.is_none()) { + self.relayout(&path); + } + let st = self.st.fields.entry(path.clone()).or_default(); + let look = st.look.clone(); + let changed = go(&mut Editor { block: &t, field: &f, st }, look.as_deref()); + if changed.text { + self.relayout(&path); + } else if changed.caret { + scroll_to_caret(&t, &f, self.st.fields.entry(path).or_default()); + } + } + + /// The pointer at stage point `p` in the focused field: places the caret (`extend`: moves + /// it, keeping the selection's other end). + fn point_field(&mut self, p: Vec2, extend: bool) { + let Some(path) = self.st.focus.clone() else { return }; + let Some((_, xf)) = self.field_node(&path) else { return }; + let Some(q) = xf.inverse().map(|m| m.apply(p)) else { return }; + let q = Vec2::new(q.x - FIELD_GUTTER, q.y - FIELD_GUTTER); + self.edit_field(|ed, look| ed.point(q, extend, look)); + } + + /// A key down for the focused field: an edit, or Tab to the next input field. + fn field_key(&mut self, code: u32) { + if self.st.focus.is_none() { + return; + } + if code == TAB { + let inputs: Vec = self.nodes.iter().filter(|n| n.hittable && n.field().is_some_and(|(_, f)| f.kind == TextKind::Input)).map(|n| n.path.clone()).collect(); + let at = inputs.iter().position(|p| Some(p) == self.st.focus.as_ref()); + let n = inputs.len(); + if n > 0 { + let next = match at { + Some(i) if self.st.shift => (i + n - 1) % n, + Some(i) => (i + 1) % n, + None => 0, + }; + self.st.focus = inputs.get(next).cloned(); + self.edit_field(|ed, look| ed.key(Edit::SelectAll, false, look)); + } + return; + } + let Some(e) = Edit::from_key(code) else { return }; + let shift = self.st.shift; + self.edit_field(|ed, look| ed.key(e, shift, look)); + } + /// Moves the pointer: what it leaves gets Out, what it reaches gets Over. fn pointer(&mut self, p: Option) { self.refresh(); self.st.pointer = p; + if let Some(p) = p { + self.st.mouse = p; + } let now = p.and_then(|p| hit_in(self.doc, &self.st, &self.nodes, p)); if now != self.st.hover { + let before = self.pointer_now(); let old = std::mem::replace(&mut self.st.hover, now.clone()); self.dirty = true; + self.button_sounds(before); if let Some(o) = old { self.fire(&o, ButtonEvent::Out); } @@ -863,15 +1537,16 @@ impl<'a, 'h> Run<'a, 'h> { let Some(n) = self.index_of(path).and_then(|i| self.nodes.get(i)) else { return }; let handler = n.events.iter().find(|h| h.event == event).map(|h| h.actions.clone()); let owner_path = self.nodes.get(n.owner).map(|o| o.path.clone()); - let listeners: Vec<(InstancePath, Arc>)> = self.st.listeners.get(path).map(|l| l.iter().filter(|l| l.event == event).map(|l| (l.owner.clone(), l.actions.clone())).collect()).unwrap_or_default(); + let le = ListenEvent::from_mouse(event); + let listeners: Vec = self.st.listeners.get(path).map(|l| l.iter().filter(|l| l.event == le).cloned().collect()).unwrap_or_default(); if handler.is_none() && listeners.is_empty() { return; } if let (Some(actions), Some(owner)) = (handler, owner_path) { self.run_list(&owner, &actions, false); } - for (owner, actions) in listeners { - self.run_list(&owner, &actions, true); + for l in listeners { + self.call_listener(&l, EventInfo { key: None, target: Some(path.to_vec()), current: Some(path.to_vec()) }); } self.settle(); } @@ -899,6 +1574,223 @@ impl<'a, 'h> Run<'a, 'h> { } } +/// The key codes of Shift and Tab. +const SHIFT: u32 = 16; +const TAB: u32 = 9; + +/// How messages name a kind of instance. +fn kind_name(k: NodeKind) -> &'static str { + match k { + NodeKind::Root => "the main timeline", + NodeKind::Graphic => "a graphic", + NodeKind::MovieClip => "a movie clip", + NodeKind::Button => "a button", + NodeKind::Text => "a text field", + } +} + +/// The event a listener is handling: the key code of a keyboard event, and its target and +/// current target (`None`: the stage). +#[derive(Clone, Debug, PartialEq)] +struct EventInfo { + key: Option, + target: Option, + current: Option, +} + +/// A timeline whose scripts share declarations: the main timeline (every scene) or a movie +/// clip symbol's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum TimelineRef { + Root, + Symbol(SymbolId), +} + +/// The compiled frame scripts of a timeline that plays them, in frame order (top layer first +/// within a frame). +pub fn timeline_scripts(tl: &Timeline) -> Vec<(u32, usize, &Compiled)> { + let mut out = Vec::new(); + for (index, layer) in tl.layers.iter().enumerate() { + if !plays(tl, index) { + continue; + } + for k in &layer.keyframes { + if let Some(FrameScript::Source(src)) = &k.script + && let Ok(c) = src.compiled() + { + out.push((k.start, index, c)); + } + } + } + out.sort_by_key(|(f, l, _)| (*f, *l)); + out +} + +/// A timeline's declarations: every function and variable its frame scripts declare (the main +/// timeline's from every scene, in scene order). +pub fn decls(doc: &Document, which: TimelineRef) -> Decls { + match which { + TimelineRef::Root => Decls::build(doc.scenes.iter().flat_map(|s| timeline_scripts(&s.timeline)).map(|(_, _, c)| c)), + TimelineRef::Symbol(id) => match doc.symbol(id) { + Some(s) if s.kind == SymbolKind::MovieClip => Decls::build(timeline_scripts(&s.timeline).into_iter().map(|(_, _, c)| c)), + _ => Decls::default(), + }, + } +} + +/// Why a compiled script on timeline `which` doesn't run there: names it takes from other +/// frames that the timeline doesn't declare, and declarations that clash. +pub fn link_problems(doc: &Document, which: TimelineRef, c: &Compiled) -> Vec { + decls(doc, which).problems(c) +} + +/// The label at or before `frame` (ActionScript's `currentLabel`), or `null`. +fn current_label(tl: &Timeline, frame: u32) -> Value { + let mut firsts: BTreeMap<&str, u32> = BTreeMap::new(); + for k in tl.layers.iter().flat_map(|l| l.keyframes.iter()).filter(|k| !k.label.is_empty()) { + let e = firsts.entry(k.label.as_str()).or_insert(k.start); + *e = (*e).min(k.start); + } + let mut best: Option<(&str, u32)> = None; + for (l, f) in firsts { + if f <= frame && best.is_none_or(|(_, b)| f > b) { + best = Some((l, f)); + } + } + best.map_or(Value::Null, |(l, _)| Value::str(l)) +} + +/// An `f32` as the shortest decimal that reads back as it (what the HTML player sees after +/// the export writes it as JSON): reads give `0.1`, not `0.10000000149011612`. +fn short(v: f32) -> f64 { + if !v.is_finite() { + return f64::from(v); + } + format!("{v}").parse().unwrap_or(f64::from(v)) +} + +/// A computed value at `f32` precision, written shortest. +fn fround_short(v: f64) -> f64 { + short(v as f32) +} + +/// `[tx, ty, sx, sy, rotation]` of a transform in `f64` (the same steps as `Affine::decompose` +/// and the HTML player's `decompose`), from its components written shortest. +fn decompose64(m: &Affine) -> [f64; 5] { + let [a, b, c, d, e, f] = m.m.map(short); + let sx = (a * a + b * b).sqrt(); + let r = b.atan2(a); + let det = a * d - b * c; + let sy = if sx > 1e-12 { det / sx } else { (c * c + d * d).sqrt() }; + [e, f, sx, sy, r] +} + +/// A running script's view of the movie (ADR 0052). +struct Script<'r, 'a, 'h> { + r: &'r mut Run<'a, 'h>, + /// The timeline the script belongs to. + owner: InstancePath, + decls: Arc, + ev: Option, +} + +impl Script<'_, '_, '_> { + fn from(&mut self) -> Result { + self.r.refresh(); + self.r.index_of(&self.owner).ok_or_else(|| "the script's timeline has left the stage".into()) + } +} + +impl World for Script<'_, '_, '_> { + fn act(&mut self, base: Base, action: &Action) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let path = self.r.base_path(&self.owner, self.ev.as_ref(), base).map_err(Some)?; + self.r.exec(&path, action, true); + if self.r.halted { Err(None) } else { Ok(()) } + } + + fn get(&mut self, at: &Place, p: Prop) -> Result { + let from = self.from()?; + let i = self.r.place(from, self.ev.as_ref(), at)?; + self.r.property(i, p) + } + + fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option> { + if at.base == Base::Stage { + return Err(Some("the stage's properties can't be set here".into())); + } + // In range (as the property keeps it), and never -0, so messages read the same here + // and in the HTML player. + let (lo, hi) = p.range(); + let v = v.clamp(lo, hi) + 0.0; + self.act(at.base, &Action::SetProperty { target: at.path.clone(), property: p, value: v }) + } + + fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let from = self.from().map_err(Some)?; + let i = self.r.place(from, self.ev.as_ref(), at).map_err(Some)?; + let Some(n) = i.and_then(|i| self.r.nodes.get(i)) else { return Err(Some("the stage isn't a text field".into())) }; + if n.field().is_none() { + return Err(Some(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind)))); + } + let path = n.path.clone(); + self.r.set_field_text(&path, &text); + Ok(()) + } + + fn trace(&mut self, line: String) { + if self.r.budget() { + self.r.out(line); + } + } + + fn read(&mut self, name: &str) -> Result { + if let Some(v) = self.r.st.vars.get(&self.owner).and_then(|m| m.get(name)) { + return Ok(v.clone()); + } + self.decls.vars.get(name).map(|t| t.default_value()).ok_or_else(|| format!("`{name}` isn't a variable of this timeline")) + } + + fn write(&mut self, name: &str, v: Value) -> Result<(), String> { + let t = *self.decls.vars.get(name).ok_or_else(|| format!("`{name}` isn't a variable of this timeline"))?; + self.r.st.vars.entry(self.owner.clone()).or_default().insert(name.to_string(), t.coerce(v)); + Ok(()) + } + + fn function(&mut self, name: &str) -> Option> { + self.decls.functions.get(name).cloned() + } + + fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc, add: bool) -> Result<(), Option> { + if !self.r.budget() { + return Err(None); + } + let owner = self.owner.clone(); + self.r.listen(&owner, self.ev.as_ref(), at, ev, f, add); + Ok(()) + } + + fn random(&mut self) -> f64 { + self.r.st.rng.next_f64() + } + + fn same(&mut self, a: &Place, b: &Place) -> Result { + let from = self.from()?; + let x = self.r.place(from, self.ev.as_ref(), a)?; + let y = self.r.place(from, self.ev.as_ref(), b)?; + Ok(x == y) + } + + fn key_code(&mut self) -> Result { + self.ev.as_ref().and_then(|e| e.key).map(f64::from).ok_or_else(|| "this isn't a keyboard event".into()) + } +} + #[cfg(test)] #[path = "player_tests.rs"] mod tests; diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 6720e447..2114efba 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -33,7 +33,7 @@ fn layer(id: u64, keys: Vec>) -> Arc { } fn symbol(id: u64, kind: SymbolKind, layers: Vec>) -> Arc { - 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>, library: Vec>) -> 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 = (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, src: &str) -> Arc { /// 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>, library: Vec>) -> Document { + let mut keys = Vec::new(); + let mut starts: Vec = 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 { + 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 = (0..10_000).map(|_| r.next_f64()).collect(); + assert!(v.iter().all(|x| (0.0..1.0).contains(x))); + let mean = v.iter().sum::() / 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 { + 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 { + 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 { + 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::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")); +} diff --git a/crates/doc/src/publish.rs b/crates/doc/src/publish.rs new file mode 100644 index 00000000..701ee881 --- /dev/null +++ b/crates/doc/src/publish.rs @@ -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::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, + #[serde(skip_serializing_if = "Option::is_none")] + pub to: Option, +} + +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::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::(&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) }); + } +} diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 2d94e4c7..f7c26fb4 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -41,19 +41,19 @@ fn key(start: u32, duration: u32, elements: Vec>, tween: Option 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` 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(); diff --git a/crates/doc/src/skin.rs b/crates/doc/src/skin.rs new file mode 100644 index 00000000..b2c33f82 --- /dev/null +++ b/crates/doc/src/skin.rs @@ -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, + /// 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, + /// One per anchor of `rest`, in path order. + #[serde(default)] + pub points: Vec, +} + +impl Skin { + /// A skin for `shape` drawn as `rest`, its anchors not yet bound. + pub fn new(shape: ElementId, rest: Arc) -> 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 { + 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 = 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 = 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 = 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 { + let Some(skin) = &arm.skin else { return HashMap::new() }; + let mut node: HashMap = 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) -> Option { + 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, b: Option) -> Option { + 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> { + 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, p: Vec2| x.map_or(p, |x| x.apply(p)); + let mut prev: Option = 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], 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]) -> Vec { + 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 = 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; diff --git a/crates/doc/src/skin_tests.rs b/crates/doc/src/skin_tests.rs new file mode 100644 index 00000000..1a7a73d9 --- /dev/null +++ b/crates/doc/src/skin_tests.rs @@ -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>) { + 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]) -> Arc { + 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:?}"); +} diff --git a/crates/doc/src/sound.rs b/crates/doc/src/sound.rs index da00a9c4..ec7adf7f 100644 --- a/crates/doc/src/sound.rs +++ b/crates/doc/src/sound.rs @@ -445,7 +445,7 @@ fn sounding_symbols(doc: &Document) -> HashSet { 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, _) => {} } } diff --git a/crates/doc/src/sound_tests.rs b/crates/doc/src/sound_tests.rs index 8e31c35b..8cd0c68a 100644 --- a/crates/doc/src/sound_tests.rs +++ b/crates/doc/src/sound_tests.rs @@ -194,7 +194,7 @@ fn nested(kind: SymbolKind, len: u32, inner: &[(u32, u32, Option)], // 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"); diff --git a/crates/doc/src/spring.rs b/crates/doc/src/spring.rs new file mode 100644 index 00000000..669e53c3 --- /dev/null +++ b/crates/doc/src/spring.rs @@ -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 { + 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 { + 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 = 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, 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; diff --git a/crates/doc/src/spring_tests.rs b/crates/doc/src/spring_tests.rs new file mode 100644 index 00000000..9bd6b4a4 --- /dev/null +++ b/crates/doc/src/spring_tests.rs @@ -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 { + 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) -> 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 = (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 = (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:?}"); +} diff --git a/crates/doc/src/swatch.rs b/crates/doc/src/swatch.rs new file mode 100644 index 00000000..53521829 --- /dev/null +++ b/crates/doc/src/swatch.rs @@ -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, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + }, + Radial { + stops: Vec, + #[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 { + 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 { + let stops = |s: &[GradientStop]| -> Option> { + if s.len() < 2 { + return None; + } + let mut v: Vec = 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 { + 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::().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 { + let colours = [0x000000, 0x333333, 0x666666, 0x999999, 0xcccccc, 0xffffff, 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0x00ffff, 0xff00ff]; + let mut v: Vec = 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), 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::().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()); + } +} diff --git a/crates/doc/src/templates.rs b/crates/doc/src/templates.rs new file mode 100644 index 00000000..988308f2 --- /dev/null +++ b/crates/doc/src/templates.rs @@ -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 { + 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 { + 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(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 { + 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> { + 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::>()); + 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 = 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()); + } +} diff --git a/crates/doc/src/warp.rs b/crates/doc/src/warp.rs new file mode 100644 index 00000000..61a11805 --- /dev/null +++ b/crates/doc/src/warp.rs @@ -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, + /// 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, + /// 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, + pub shown: Vec, + 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 { + 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 { + 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) { + 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; 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, + shown: Vec, +} + +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, 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::of(&self.rest, self.resolution) + } + + fn bent(&self) -> Option { + 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 { + 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 { + 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 { + 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) -> 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 { + 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 = 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, a: Vec2, p: Vec2, ts: &mut Vec| { + 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; diff --git a/crates/doc/src/warp_tests.rs b/crates/doc/src/warp_tests.rs new file mode 100644 index 00000000..59578c45 --- /dev/null +++ b/crates/doc/src/warp_tests.rs @@ -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 { + Arc::new(Path::ellipse(100.0, 50.0, 100.0, 50.0)) +} + +fn anchors(p: &Path) -> Vec { + 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 = (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))); +} diff --git a/crates/doc/src/weights.rs b/crates/doc/src/weights.rs new file mode 100644 index 00000000..ec47f7f4 --- /dev/null +++ b/crates/doc/src/weights.rs @@ -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 { + 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) -> Binding { + let w = if w.is_finite() { w.clamp(0.0, 1.0) } else { b.weight(bone) }; + let mut others: Vec = 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 { + 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, 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 { + 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> = HashMap::with_capacity(old.len()); + for (i, p) in old.iter().enumerate() { + at.entry(key(*p)).or_default().push(i); + } + let mut matched: Vec> = 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 = 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, 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; diff --git a/crates/doc/src/weights_tests.rs b/crates/doc/src/weights_tests.rs new file mode 100644 index 00000000..1ea3ff22 --- /dev/null +++ b/crates/doc/src/weights_tests.rs @@ -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::() - 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 = (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 = 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 = (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 = (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); +} diff --git a/crates/doc/src/width.rs b/crates/doc/src/width.rs index 4e433794..bacb457c 100644 --- a/crates/doc/src/width.rs +++ b/crates/doc/src/width.rs @@ -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 { + 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 = 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| { + 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> = 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, +} + +impl Measure { + fn new(path: &Path) -> Measure { + use anicraft_geom::PathCmd; + let mut segs = Vec::new(); + let mut sub_len: Vec = 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::() * 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()); + } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 5fce8c7e..b06903ea 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -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" diff --git a/crates/engine/src/anim.rs b/crates/engine/src/anim.rs new file mode 100644 index 00000000..60d0cce5 --- /dev/null +++ b/crates/engine/src/anim.rs @@ -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, +} + +/// 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 { + 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 { + 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 { + 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) { + 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> { + 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> { + 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 { + 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 { + 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> { + 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> { + 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 { + 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 { + 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 = Vec::new(); + let mut prev: Option> = None; + let frames: Vec = (from..=to).collect(); + for (b, chunk) in frames.chunks(batch).enumerate() { + let images: Vec> = chunk + .par_iter() + .map(|&f| { + let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + crate::publish::tick(job, 1)?; + Ok(pm.to_rgba8()) + }) + .collect::>()?; + // A frame like the one before it only lengthens that frame's delay. + let mut fresh: Vec = 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::>>()?; + 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; diff --git a/crates/engine/src/anim_tests.rs b/crates/engine/src/anim_tests.rs new file mode 100644 index 00000000..6be0a5f9 --- /dev/null +++ b/crates/engine/src/anim_tests.rs @@ -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> { + 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, + delay: (u16, u16), + rect: Rect, + over: bool, +} + +struct Apng { + frames: Vec, + 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, + } + let mut raw_frames: Vec = 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, 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> { + 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, 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, u32)], n: u64, ratio: (u64, u64)) -> Vec> { + 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], want: &[Vec], 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::(), 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, 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> { + 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()); +} diff --git a/crates/engine/src/brush_library.rs b/crates/engine/src/brush_library.rs new file mode 100644 index 00000000..ba1bb6d5 --- /dev/null +++ b/crates/engine/src/brush_library.rs @@ -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 { + 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 { + 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> { + 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::>>()?; + 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 { + 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, +} + +/// A brush set file. +#[derive(Serialize, Deserialize)] +struct BrushFile { + format: String, + version: u32, + brushes: Vec, +} + +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) -> 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::(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 { + 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 { + 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 { + 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 { + 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::().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 { + 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 { + 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> { + 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::()))); + } + 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::(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::>(&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); + } +} diff --git a/crates/engine/src/brush_library_tests.rs b/crates/engine/src/brush_library_tests.rs new file mode 100644 index 00000000..c26054e2 --- /dev/null +++ b/crates/engine/src/brush_library_tests.rs @@ -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 { + 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::() * 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 = (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); +} diff --git a/crates/engine/src/brush_tests.rs b/crates/engine/src/brush_tests.rs index dcd3d2b3..a75f16c1 100644 --- a/crates/engine/src/brush_tests.rs +++ b/crates/engine/src/brush_tests.rs @@ -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 = 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())); +} diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index ce9540f1..fe106894 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -17,11 +17,11 @@ use std::sync::Arc; pub fn specs() -> Vec { 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, 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 { 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 { /// 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 { let fps = s.doc.stage.fps.max(1.0); @@ -259,16 +268,34 @@ fn test_movie(s: &mut Session, p: &Value) -> Result { } 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 = 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::>(), + "sounds": sounds, + "more_sounds": more, "state": state_view(&s.doc, &movie.state, &nodes, None), "script_runs": runner.runs, "script_fuel": runner.fuel_used, diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs index a2d67fd8..d9e7a587 100644 --- a/crates/engine/src/cmds_bone.rs +++ b/crates/engine/src/cmds_bone.rs @@ -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 { 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 { - 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 { /// The armature layer holding bone `id`, and its armature. fn find_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc)> { - 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> { } 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>, arm: Armature) -> Result { + 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 { 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 { } 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 { 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 { 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 { let mut left = (*arm).clone(); left.bones.retain(|b| !gone.contains(&b.id)); let dissolve = left.is_empty(); - let freed: Vec = 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 = 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 { 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 { } 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::>(), "freed": freed.iter().map(|e| e.0).collect::>(), "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::>(), "freed": freed.iter().map(|e| e.0).collect::>(), "layer": layer.0, "armature_removed": dissolve})) } fn set_limits(s: &mut Session, p: &Value) -> Result { @@ -308,6 +337,108 @@ fn set_limits(s: &mut Session, p: &Value) -> Result { 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 { + 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 { + 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 { + 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 { 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(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(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Ar fn pose(s: &mut Session, p: &Value) -> Result { 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 { 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 { fn info(s: &mut Session, p: &Value) -> Result { 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 = tl @@ -421,8 +566,10 @@ fn info(s: &mut Session, p: &Value) -> Result { .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| l.map(|l| json!({"min": l.min, "max": l.max, "constrain": l != FREE})); let bones: Vec = arm .bones .iter() @@ -435,11 +582,327 @@ fn info(s: &mut Session, p: &Value) -> Result { "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::>(), "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::>(), "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::>(), "manual": b.manual})).collect::>()); + } + Some(out) }) .collect(); Ok(json!({"frame": frame, "armatures": list})) } + +fn add_in_shape(s: &mut Session, p: &Value) -> Result { + 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 { + 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 = 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::>()?, + 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> { + 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)> { + 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 { + 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 = 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::>()?; + 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 { + 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 = 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::>()).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(s: &mut Session, id: ElementId, edit: impl FnOnce(&mut Shape, Affine) -> Result) -> Result { + 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) +} diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index df6e1423..0eb593e3 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -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 { - 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 { + 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> { - 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> { } 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> { 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 { 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 { + 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::() / pts.len() as f32).clamp(0.05, 1.0) +} + fn draw_brush(s: &mut Session, p: &Value) -> Result { 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 = 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 = 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 = s.selection.id_list(); + let merged = merge::merge_in_order(s, vec![el], order)?; + let ids: Vec = 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 { + 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 { + 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 { + let mut list: Vec = 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 { + 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 { + 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 { + 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 { + let path = std::path::PathBuf::from(str_req(p, "path")?); + let chosen: Vec = 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::>()?, + 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 { + 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 { + 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", ¶ms)?; + 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) +} diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index e8fd10a3..579fe605 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -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 { "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 { - 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 { + // 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 { 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 { fn remove(s: &mut Session, _: &Value) -> Result { 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 { 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 { 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 { 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::>(), }) } @@ -187,25 +199,95 @@ fn camera_json(c: &Camera, stage: &anicraft_doc::Stage) -> Value { fn info(s: &mut Session, p: &Value) -> Result { 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 { 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 { + 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 { + 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 { + 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 = 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})) } diff --git a/crates/engine/src/cmds_desktop.rs b/crates/engine/src/cmds_desktop.rs new file mode 100644 index 00000000..c8b95fda --- /dev/null +++ b/crates/engine/src/cmds_desktop.rs @@ -0,0 +1,351 @@ +//! AppImage desktop integration (ADR 0094): `desktop.integrate / remove / status`. +//! +//! An AppImage is one file the user downloaded: nothing installs its launcher, icons or file +//! types. With the user's yes, `desktop.integrate` writes them into the user's XDG data folder +//! (`$XDG_DATA_HOME`, default `~/.local/share`), as a package would into `/usr/share`: +//! +//! * `applications/ai.storyteller.anicraft.desktop`: the packaged entry (`packaging/linux`) with +//! `Exec` and `TryExec` pointing at the `.AppImage`, quoted as the Desktop Entry spec says, and +//! an `X-AniCraft-AppImage` key that marks it as ours; +//! * `mime/packages/ai.storyteller.anicraft.xml`: the packaged MIME types (`.anicraft`, `.fla`, +//! `.xfl`); +//! * `icons/hicolor//apps/ai.storyteller.anicraft.{png,svg}`: the packaged icons. +//! +//! Then it refreshes the user's MIME and desktop databases (`update-mime-database`, +//! `update-desktop-database`) where those tools are installed. It never writes outside the data +//! folder it is given, refuses system folders, and is idempotent: writing again changes only +//! what differs. `desktop.remove` deletes exactly these files, and only when the entry is ours. +//! The paths are parameters, so tests, the CLI and MCP name them; the desktop app passes its +//! own (`platform::appimage`, `platform::data_home`). + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +pub fn specs() -> Vec { + let c = |id, label, params, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates: false, run }; + vec![ + c( + "desktop.integrate", + "Add to Applications Menu", + "{appimage: absolute path to the .AppImage, data_home: absolute path (the user's $XDG_DATA_HOME, e.g. ~/.local/share), refresh? (default true: run update-mime-database and update-desktop-database)} writes the launcher, icons and file types there; again only rewrites what changed", + integrate as crate::RunFn, + ), + c("desktop.remove", "Remove from Applications Menu", "{data_home, refresh? (default true)} deletes the launcher, icons and file types desktop.integrate wrote; nothing when the entry there isn't AniCraft's", remove), + c("desktop.status", "Applications Menu Status", "{data_home, appimage? (to say whether the entry starts this copy)} whether AniCraft is in the applications menu, and which AppImage it starts", status), + ] +} + +/// The app id (ADR 0026), which names every file written. +pub const APP_ID: &str = "ai.storyteller.anicraft"; +/// The key that marks a desktop entry as written by `desktop.integrate`; its value is the +/// AppImage it starts. +pub const MARKER_KEY: &str = "X-AniCraft-AppImage"; + +const DESKTOP_TEMPLATE: &str = include_str!("../../../packaging/linux/ai.storyteller.anicraft.desktop"); +const MIME_XML: &str = include_str!("../../../packaging/linux/ai.storyteller.anicraft.mime.xml"); + +/// The packaged icons: `(hicolor size folder, file extension, contents)`. The 512 px one is left +/// out (desktops scale the SVG), which keeps the programs small. +const ICONS: [(&str, &str, &[u8]); 8] = [ + ("16x16", "png", include_bytes!("../../../assets/app-icon/hicolor/16x16/apps/ai.storyteller.anicraft.png")), + ("24x24", "png", include_bytes!("../../../assets/app-icon/hicolor/24x24/apps/ai.storyteller.anicraft.png")), + ("32x32", "png", include_bytes!("../../../assets/app-icon/hicolor/32x32/apps/ai.storyteller.anicraft.png")), + ("48x48", "png", include_bytes!("../../../assets/app-icon/hicolor/48x48/apps/ai.storyteller.anicraft.png")), + ("64x64", "png", include_bytes!("../../../assets/app-icon/hicolor/64x64/apps/ai.storyteller.anicraft.png")), + ("128x128", "png", include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png")), + ("256x256", "png", include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.anicraft.png")), + ("scalable", "svg", include_bytes!("../../../assets/app-icon/hicolor/scalable/apps/ai.storyteller.anicraft.svg")), +]; + +/// Longest path accepted (anything longer is not a path a user has). +const MAX_PATH_BYTES: usize = 4096; + +/// System folders desktop integration never writes into, whatever it is told: packages own them. +const SYSTEM: [&str; 10] = ["/usr", "/etc", "/opt", "/var/lib", "/bin", "/sbin", "/lib", "/lib64", "/boot", "/snap"]; + +/// `path` as text a desktop entry can hold: UTF-8, absolute, no control characters, bounded. +fn entry_text<'a>(path: &'a Path, what: &str) -> Result<&'a str> { + let text = path.to_str().ok_or_else(|| EngineError::Param(format!("the {what} path is not valid UTF-8, which a desktop entry can't hold")))?; + if text.is_empty() || text.len() > MAX_PATH_BYTES { + return Err(EngineError::Param(format!("the {what} path is empty or too long"))); + } + if text.chars().any(char::is_control) { + return Err(EngineError::Param(format!("the {what} path has a line break or control character, which a desktop entry can't hold"))); + } + // `/…` counts on every system, so the Linux layouts are tested on any OS. + if !path.is_absolute() && !text.starts_with('/') { + return Err(EngineError::Param(format!("the {what} path must be absolute: {text}"))); + } + Ok(text) +} + +/// A desktop entry string value: backslashes doubled (the spec's only escape we need, since +/// control characters were refused). +fn escape_value(s: &str) -> String { + s.replace('\\', "\\\\") +} + +/// Reads a string value back ([`escape_value`] and the spec's `\s \n \t \r`). +fn unescape_value(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('s') => out.push(' '), + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some(other) => out.push(other), + None => out.push('\\'), + } + } + out +} + +/// The program argument of an `Exec` line for `path`: always in double quotes, with `"`, `` ` ``, +/// `$` and `\` escaped inside them and `%` doubled (it starts field codes), then escaped as a +/// string value. So spaces, quotes and dollar signs in folder names start the right file. +pub fn exec_argument(path: &str) -> String { + let mut quoted = String::with_capacity(path.len() + 2); + quoted.push('"'); + for c in path.chars() { + match c { + '"' | '`' | '$' | '\\' => { + quoted.push('\\'); + quoted.push(c); + } + '%' => quoted.push_str("%%"), + _ => quoted.push(c), + } + } + quoted.push('"'); + escape_value("ed) +} + +/// The desktop entry that starts the AppImage at `appimage`: the packaged one with `Exec`, +/// `TryExec` (so the entry hides itself if the file is moved or deleted) and the marker key. +pub fn desktop_entry(appimage: &Path) -> Result { + let text = entry_text(appimage, "AppImage")?; + let mut out = String::from("# Added by AniCraft for the AppImage named in X-AniCraft-AppImage.\n# AniCraft's Preferences › About › Remove takes it away again.\n"); + for line in DESKTOP_TEMPLATE.lines() { + let line = line.trim_end_matches('\r'); + if line.starts_with("Exec=") { + out.push_str(&format!("Exec={} %f\n", exec_argument(text))); + } else if line.starts_with("TryExec=") { + out.push_str(&format!("TryExec={}\n", escape_value(text))); + } else { + out.push_str(line); + out.push('\n'); + } + } + out.push_str(&format!("{MARKER_KEY}={}\n", escape_value(text))); + Ok(out) +} + +/// The AppImage a desktop entry written by [`desktop_entry`] starts, or `None` if the entry is +/// not ours. +pub fn entry_appimage(entry: &str) -> Option { + let prefix = format!("{MARKER_KEY}="); + entry.lines().find_map(|l| l.trim_end_matches('\r').strip_prefix(&prefix)).map(|v| PathBuf::from(unescape_value(v))) +} + +/// Checks the data folder: absolute, valid, and not a system folder. +fn check_data_home(data_home: &Path) -> Result<()> { + let text = entry_text(data_home, "data folder")?; + let norm = text.trim_end_matches('/'); + if norm.is_empty() || SYSTEM.iter().any(|s| norm == *s || norm.starts_with(&format!("{s}/"))) { + return Err(EngineError::Param(format!("{text} is a system folder; AniCraft adds itself only to your own data folder (~/.local/share)"))); + } + Ok(()) +} + +/// Every file desktop integration owns under `data_home`, relative to it. +pub fn owned_files() -> Vec { + let mut v = vec![PathBuf::from("applications").join(format!("{APP_ID}.desktop")), PathBuf::from("mime").join("packages").join(format!("{APP_ID}.xml"))]; + v.extend(ICONS.iter().map(|(size, ext, _)| PathBuf::from("icons").join("hicolor").join(size).join("apps").join(format!("{APP_ID}.{ext}")))); + v +} + +/// The files to write for `appimage`: `(path under data_home, contents)`, in [`owned_files`] order. +fn planned(appimage: &Path) -> Result)>> { + let mut contents: Vec> = vec![desktop_entry(appimage)?.into_bytes(), MIME_XML.as_bytes().to_vec()]; + contents.extend(ICONS.iter().map(|(_, _, b)| b.to_vec())); + Ok(owned_files().into_iter().zip(contents).collect()) +} + +/// Writes `data` to `path` through a temporary file and a rename, so a crash never leaves half a +/// launcher; leaves the file alone when it already holds `data`. Whether it wrote. +fn write_if_changed(path: &Path, data: &[u8]) -> Result { + if std::fs::read(path).is_ok_and(|old| old == data) { + return Ok(false); + } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let mut tmp = path.as_os_str().to_owned(); + tmp.push(".anicraft-tmp"); + let tmp = PathBuf::from(tmp); + std::fs::write(&tmp, data)?; + if let Err(e) = std::fs::rename(&tmp, path) { + let _ = std::fs::remove_file(&tmp); + return Err(e.into()); + } + Ok(true) +} + +/// What [`install`] did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Report { + /// Files written (new or changed), and files already as they should be. + pub written: Vec, + pub unchanged: Vec, +} + +/// The desktop entry under `data_home`, and whether it is ours. +fn entry_path(data_home: &Path) -> PathBuf { + data_home.join("applications").join(format!("{APP_ID}.desktop")) +} + +/// Adds AniCraft (the AppImage at `appimage`) to the menu under `data_home`. Refuses to replace an +/// entry of the same name that it didn't write (a hand-made one, say). +pub fn install(appimage: &Path, data_home: &Path) -> Result { + check_data_home(data_home)?; + entry_text(appimage, "AppImage")?; + if !appimage.is_file() { + return Err(EngineError::Param(format!("there is no AppImage at {}", appimage.display()))); + } + let entry = entry_path(data_home); + if let Ok(old) = std::fs::read_to_string(&entry) + && entry_appimage(&old).is_none() + { + return Err(EngineError::State(format!("{} was not written by AniCraft, so it is left as it is", entry.display()))); + } + let mut r = Report::default(); + for (rel, data) in planned(appimage)? { + let path = data_home.join(&rel); + if write_if_changed(&path, &data)? { r.written.push(path) } else { r.unchanged.push(path) } + } + Ok(r) +} + +/// Removes what [`install`] wrote under `data_home`: the files that are there. Nothing when the +/// entry there isn't ours (an error then), so it never deletes someone else's launcher. +pub fn uninstall(data_home: &Path) -> Result> { + check_data_home(data_home)?; + let entry = entry_path(data_home); + if let Ok(old) = std::fs::read_to_string(&entry) + && entry_appimage(&old).is_none() + { + return Err(EngineError::State(format!("{} was not written by AniCraft, so it is left as it is", entry.display()))); + } + let mut removed = Vec::new(); + for rel in owned_files() { + let path = data_home.join(rel); + if path.is_file() { + std::fs::remove_file(&path)?; + removed.push(path); + } + } + Ok(removed) +} + +/// Whether AniCraft is in the menu under `data_home`. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Status { + /// The AppImage our entry starts, when there is one. + pub appimage: Option, + /// An entry of our name is there that AniCraft didn't write. + pub foreign: bool, +} + +pub fn read_status(data_home: &Path) -> Status { + match std::fs::read_to_string(entry_path(data_home)) { + Ok(text) => match entry_appimage(&text) { + Some(a) => Status { appimage: Some(a), foreign: false }, + None => Status { appimage: None, foreign: true }, + }, + Err(_) => Status::default(), + } +} + +/// Runs `program args…` if it is installed, for at most a few seconds, ignoring what it says: +/// the caches it refreshes speed things up, and desktops rescan without them. +fn run_quietly(program: &str, args: &[&std::ffi::OsStr]) { + use std::process::{Command, Stdio}; + let Ok(mut child) = Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else { return }; + for _ in 0..250 { + match child.try_wait() { + Ok(Some(_)) | Err(_) => return, + Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)), + } + } + let _ = child.kill(); + let _ = child.wait(); +} + +/// Refreshes the user's MIME and desktop databases under `data_home` (best effort). +fn refresh(data_home: &Path) { + let mime = data_home.join("mime"); + if mime.join("packages").is_dir() { + run_quietly("update-mime-database", &[mime.as_os_str()]); + } + let apps = data_home.join("applications"); + if apps.is_dir() { + run_quietly("update-desktop-database", &[std::ffi::OsStr::new("-q"), apps.as_os_str()]); + } +} + +fn path_req(p: &Value, key: &str) -> Result { + let s = str_req(p, key)?; + if s.trim().is_empty() { + return Err(EngineError::Param(format!("'{key}' is empty"))); + } + Ok(PathBuf::from(s)) +} + +fn shown(paths: &[PathBuf]) -> Vec { + paths.iter().map(|p| p.display().to_string()).collect() +} + +fn integrate(_: &mut Session, p: &Value) -> Result { + let (appimage, data_home) = (path_req(p, "appimage")?, path_req(p, "data_home")?); + let refresh_after = opt_bool(p, "refresh")?.unwrap_or(true); + let r = install(&appimage, &data_home)?; + if refresh_after && !r.written.is_empty() { + refresh(&data_home); + } + Ok(json!({"added": true, "appimage": appimage.display().to_string(), "written": shown(&r.written), "unchanged": r.unchanged.len()})) +} + +fn remove(_: &mut Session, p: &Value) -> Result { + let data_home = path_req(p, "data_home")?; + let refresh_after = opt_bool(p, "refresh")?.unwrap_or(true); + let removed = uninstall(&data_home)?; + if refresh_after && !removed.is_empty() { + refresh(&data_home); + } + Ok(json!({"removed": shown(&removed)})) +} + +fn status(_: &mut Session, p: &Value) -> Result { + let data_home = path_req(p, "data_home")?; + check_data_home(&data_home)?; + let st = read_status(&data_home); + let current = match opt_str(p, "appimage")? { + Some(a) => st.appimage.as_deref().is_some_and(|x| x == Path::new(a)), + None => false, + }; + Ok(json!({ + "added": st.appimage.is_some(), + "appimage": st.appimage.as_ref().map(|a| a.display().to_string()), + "this_copy": current, + "target_exists": st.appimage.as_deref().is_some_and(Path::is_file), + "foreign": st.foreign, + })) +} diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 494f55f6..74095142 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -2,7 +2,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Selection, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_doc::{ColorEffect, ColorStyle, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, ScaleGrid, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Decomposed, Path, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -12,10 +12,10 @@ pub fn specs() -> Vec { vec![ c("draw.rect", "Rectangle", "", None, "{x, y, w, h, radius?, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}", true, draw_rect as crate::RunFn), c("draw.ellipse", "Oval", "", None, "{x, y, w, h, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}", true, draw_ellipse), - c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, cap?, join?, style?, dash?, object?}", true, draw_star), + c("draw.star", "PolyStar", "", None, "{cx, cy, outer (the corners' radius), shape?: star|polygon (default star; the PolyStar Tool Settings, ADR 0080), sides? (or points; 3..64, default 5), point_size? (0..1, default 0.5: how deep a star's points are, 1 is the polygon through its tips), inner? (an exact inner radius instead of point_size), fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash? (the line style), object?}", true, draw_star), c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (the line style, as stroke.set_style; default: the tool's), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line), c("draw.object_drawing", "Object Drawing", "", Some("J"), "{on?: bool} (default: toggle)", false, object_drawing), - c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", None, "{on?: bool} (default: toggle) dragged points and selections snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point and raw.move_handle do nothing while it is off)", false, snap_to_objects), + c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", Some("Ctrl+Shift+/"), "{on?: bool} (default: toggle) dragged points and selections, and the points the Line, Rectangle, Oval, PolyStar and Pen tools draw, snap to points, lines and fill edges (while it is off, the `snap` params of element.translate, raw.move_point and draw.snap only snap to guides, the grid and pixels, as View › Guides, Grid and Snapping say)", false, snap_to_objects), c("edit.select_all", "Select All", "Edit", Some("Ctrl+A"), "{}", false, select_all), c("edit.deselect", "Deselect All", "Edit", Some("Ctrl+Shift+A"), "{}", false, |s, _| { s.selection.clear(); @@ -23,25 +23,35 @@ pub fn specs() -> Vec { }), c("edit.delete", "Clear", "Edit", Some("Delete"), "{} (on every layer with selected items)", true, delete_selection), c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?} (each copy on its original's layer)", true, |s, p| s.each_layer(true, |s| duplicate(s, p))), - c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); the active layer becomes the first one's unless it has some of them", false, select), - c("element.pick", "Select at Point", "", None, "{x, y, add?: bool} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer", false, pick), - c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends (the nearest to `from`) then snaps onto a point, line or fill edge of the rest within that distance", true, translate), + c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, toggle?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); `toggle` takes each one that is selected out of the selection and adds the others (Shift+Space on a stage element); the active layer becomes the first one's unless it has some of them", false, select), + c("element.pick", "Select at Point", "", None, "{x, y, add?: bool, view?: stage|camera} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer; with `view: camera` the point is on the movie's picture as the camera shows it (each layer through its depth)", false, pick), + c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends, or its box's corners or centre (the nearest to `from`), then snaps within that distance by the snap engine's priority (ADR 0076): a point, guide, line or fill edge of the rest, the grid, a whole pixel", true, translate), c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), - c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), + c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), + c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera has no opacity (no Alpha style, alpha multiplier or offset)", true, |s, p| s.each_layer(true, |s| set_color_effect(s, p))), c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))), - c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))), + c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values, enabled?: bool (default true; false switches it off, keeping its settings)}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| crate::cmds_filter::set_filters(s, p))), c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))), - c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the selected instance's)}", true, set_symbol_kind), + c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the symbols of every selected instance)}", true, set_symbol_kind), + c( + "symbol.set_scale_grid", + "9-Slice Scaling", + "", + None, + "{symbol?: id (default: the symbol open for editing, else the selected instance's), on?: bool, left?, right?, top?, bottom? (guide positions in the symbol's space)} turns a symbol's guides for 9-slice scaling on or off, or moves them (ADR 0055). Turning them on brings back the guides it had when they were turned off (ADR 0057), else puts them a quarter of the way in from each edge of the symbol's artwork; moving one turns them on. Scaled instances then keep the corners outside the guides unscaled, stretch the edges one way and the centre both ways → {symbol, scale_grid: {left, right, top, bottom} | null}", + true, + set_scale_grid, + ), c("element.rename", "Instance Name", "", None, "{name}", true, |s, p| s.each_layer(true, |s| rename(s, p))), c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, true))), c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, true))), c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, false))), c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, false))), - c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol), - c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))), - c("library.place", "Place Instance", "", None, "{symbol | bitmap, x?, y?}", true, place), + c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name? (default: the next free “Symbol n”; a name the folder holds gets a number), kind?: graphic|movie_clip|button (default: graphic), folder?: Library folder id (default: the top level)} → {symbol, instance, name, layer, folder} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol), + c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{} the selected symbol instances become their contents, text becomes shapes, and drawing objects become raw shapes that merge with the raw shapes they touch", true, |s, p| s.each_layer(false, |s| break_apart(s, p))), + c("library.place", "Place on Stage", "", None, "{symbol | bitmap | sound: id, x?, y?} or {items: [{symbol | bitmap | sound: id}, ..], x?, y?} → {element, elements, sound?}: symbols and bitmaps centred on x, y (default: the stage centre; inside an open symbol, in its space) in the active layer's keyframe at the playhead, selected; a sound goes onto that keyframe, its span grown to fit (one sound per keyframe). One undo step", true, place), ] } @@ -98,17 +108,17 @@ fn rect_params(p: &Value) -> Result<(f32, f32, f32, f32)> { /// (Object Drawing), it merges with the raw shapes it touches (ADR 0031), and the pieces of it /// that come out are selected. pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, fill: Option, stroke: Option, object: bool) -> Result { - // A gradient or bitmap from the fill swatch is in stage space: it stays where it is on the - // stage (Animate's Lock Fill after the Eyedropper). - let fill = fill.map(|f| f.transformed(&Affine::translate(-origin.x, -origin.y))); - let merge = !object && crate::merge::can_merge(stroke.as_ref()); + // A gradient or bitmap from the fill swatch is in stage space: with Lock Fill it stays where + // it is on the stage, else it is fitted to the new shape (ADR 0074). + let fill = fill.map(|f| if s.style.lock_fill || matches!(f, Paint::Solid(_)) { f.transformed(&Affine::translate(-origin.x, -origin.y)) } else { f.fitted(&local.bounds()) }); + let merge = !object; let id = ElementId(s.doc.alloc_id()); let el = Element { id, name: String::new(), transform: Affine::translate(origin.x, origin.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge }), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge, warp: None }), }; if merge { let merged = crate::merge::merge_in(s, vec![el])?; @@ -148,13 +158,36 @@ fn draw_star(s: &mut Session, p: &Value) -> Result { if !(0.5..=MAX_EXTENT).contains(&outer) { return Err(EngineError::Param("param 'outer' must be between 0.5 and 1,000,000".into())); } - let inner = opt_f32(p, "inner")?.unwrap_or(outer * 0.5).clamp(0.0, MAX_EXTENT); - let points = opt_u32(p, "points")?.unwrap_or(5); + // PolyStar's Tool Settings (ADR 0080): a polygon or a star, its sides (or points) and the + // star's point size. + let polygon = match opt_str(p, "shape")?.unwrap_or("star") { + "star" => false, + "polygon" => true, + other => return Err(EngineError::Param(format!("unknown PolyStar style '{other}' (polygon or star)"))), + }; + let points = match (opt_u32(p, "sides")?, opt_u32(p, "points")?) { + (Some(n), _) | (None, Some(n)) => n, + (None, None) => 5, + }; if !(3..=64).contains(&points) { - return Err(EngineError::Param("param 'points' must be between 3 and 64".into())); + return Err(EngineError::Param("param 'sides' (or 'points') must be between 3 and 64".into())); } + let point_size = match opt_f32(p, "point_size")? { + None => 0.5, + Some(v) if (0.0..=1.0).contains(&v) => v, + Some(_) => return Err(EngineError::Param("param 'point_size' must be between 0 and 1".into())), + }; let (fill, stroke) = style(s, p, true)?; - add_shape(s, "star", Path::star(0.0, 0.0, outer, inner, points), Vec2::new(cx, cy), fill, stroke, object_param(s, p)?) + let object = object_param(s, p)?; + if polygon { + return add_shape(s, "polygon", Path::polystar(0.0, 0.0, outer, points, false, point_size), Vec2::new(cx, cy), fill, stroke, object); + } + // An explicit inner radius (scripts written before the point size) still wins. + let path = match opt_f32(p, "inner")? { + Some(inner) => Path::star(0.0, 0.0, outer, inner.clamp(0.0, MAX_EXTENT), points), + None => Path::polystar(0.0, 0.0, outer, points, true, point_size), + }; + add_shape(s, "star", path, Vec2::new(cx, cy), fill, stroke, object) } fn draw_line(s: &mut Session, p: &Value) -> Result { @@ -182,7 +215,7 @@ fn object_drawing(s: &mut Session, p: &Value) -> Result { /// Everything on every visible, unlocked layer at the playhead, as Animate's Select All. fn select_all(s: &mut Session, _: &Value) -> Result { - let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let layers: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); let mut sel = Selection::default(); for l in layers.into_iter().filter(|l| s.gathers(*l)) { sel.extend_on(l, s.elements_on(l).iter().map(|e| e.id)); @@ -200,12 +233,13 @@ fn select(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param(format!("param 'ids' has more than {MAX_SELECT} ids"))); } let add = opt_bool(p, "add")?.unwrap_or(false); + let toggle = opt_bool(p, "toggle")?.unwrap_or(false); // Where each element is at the playhead: on `layer`, else the active layer first, then the // others top to bottom. let order: Vec = match opt_u64(p, "layer")?.map(LayerId) { - Some(l) if s.doc.timeline(s.scene).layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))), + Some(l) if s.timeline().layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))), Some(l) => vec![l], - None => std::iter::once(s.layer).chain(s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(), + None => std::iter::once(s.layer).chain(s.timeline().layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(), }; let mut at: std::collections::HashMap = std::collections::HashMap::new(); for l in order { @@ -219,16 +253,22 @@ fn select(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State(format!("element {} is not on the active layer, or any layer, at this frame", id.0))); }; if !s.selectable(l) { - let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); return Err(EngineError::State(format!("element {} is on layer '{name}', which is locked or hidden", id.0))); } picked.push((l, id)); } - if !add { - s.selection.clear(); - } - for &(l, id) in &picked { - s.selection.insert(l, id); + if toggle { + for &(l, id) in &picked { + s.selection.toggle(l, id); + } + } else { + if !add { + s.selection.clear(); + } + for &(l, id) in &picked { + s.selection.insert(l, id); + } } // As a click does: the active layer is where the artwork is. if let Some(&(l, _)) = picked.first() @@ -242,7 +282,13 @@ fn select(s: &mut Session, p: &Value) -> Result { fn pick(s: &mut Session, p: &Value) -> Result { let pt = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); let add = opt_bool(p, "add")?.unwrap_or(false); - match s.hit_test(pt, 2.0) { + // `view: "camera"`: the point is on the movie's picture, seen through the camera (ADR 0082). + let through = match opt_str(p, "view")? { + None | Some("stage") => false, + Some("camera") => true, + Some(v) => return Err(EngineError::Param(format!("unknown view '{v}' (stage or camera)"))), + }; + match if through { s.hit_test_camera(pt, 2.0) } else { s.hit_test(pt, 2.0) } { Some((layer, el)) => { // Shift adds it to (or takes it from) the selection, whichever layers that is on. if add { @@ -266,7 +312,7 @@ fn pick(s: &mut Session, p: &Value) -> Result { fn translate(s: &mut Session, p: &Value) -> Result { let (mut dx, mut dy) = (f32_req(p, "dx")?, f32_req(p, "dy")?); - let snap = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0)); + let snap = opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0); let from = match p.get("from").filter(|v| !v.is_null()) { None => None, Some(v) => { @@ -277,7 +323,7 @@ fn translate(s: &mut Session, p: &Value) -> Result { let n = move_by(s, Vec2::new(dx, dy))?; // Snapping while dragging (ADR 0041): a little more, onto what is near. let mut snapped = Value::Null; - if snap > 0.0 + if s.snaps(snap) && let Some((extra, at, kind)) = crate::cmds_raw::snap_selection(s, snap, from) { move_by(s, extra)?; @@ -340,7 +386,7 @@ fn shapes_mut(s: &mut Session) -> Result> { .into_iter() .filter_map(|e| match &mut e.kind { ElementKind::Shape(sh) => Some(sh), - ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => None, + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None, }) .collect(); if shapes.is_empty() { @@ -361,7 +407,7 @@ fn set_fill(s: &mut Session, p: &Value) -> Result { Ok(json!({"ok": true})) } -fn set_stroke(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_stroke(s: &mut Session, p: &Value) -> Result { let remove = p.get("color").is_some_and(Value::is_null); let color = opt_color(p, "color")?; let width = opt_f32(p, "width")?; @@ -400,65 +446,114 @@ fn set_alpha(s: &mut Session, p: &Value) -> Result { if !(0.0..=1.0).contains(&a) { return Err(EngineError::Param("param 'alpha' must be between 0 and 1".into())); } - for e in s.selected_elements_mut()? { - e.color.alpha = a; + for e in s.selected_props_mut()? { + e.color = e.color.with_alpha(a); } Ok(json!({"alpha": a})) } -/// Most filters on one instance. -const MAX_FILTERS: usize = 16; +/// Each colour effect value `element.set_color_effect` takes: its key, style, range and scale +/// (the model's value is the param's divided by it). +const EFFECT_VALUES: [(&str, ColorStyle, f32, f32, f32); 11] = [ + ("alpha", ColorStyle::Alpha, 0.0, 100.0, 100.0), + ("brightness", ColorStyle::Brightness, -100.0, 100.0, 100.0), + ("tint_amount", ColorStyle::Tint, 0.0, 100.0, 100.0), + ("red_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("green_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("blue_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("alpha_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0), + ("red_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("green_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("blue_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), + ("alpha_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0), +]; -/// Filters for the selected movie clip and button instances (Animate offers them on those only). -fn set_filters(s: &mut Session, p: &Value) -> Result { - let mut list = p.get("filters").cloned().ok_or_else(|| EngineError::Param("param 'filters' is required (a list; [] removes them)".into()))?; - // Colours may be written "#rrggbb" (or "#rrggbbaa"), as everywhere in commands: the filter's - // own and its ramp stops'. - fn hex_colors(v: &mut Value, keys: &[&str]) -> Result<()> { - for k in keys { - if v.get(*k).is_some_and(Value::is_string) { - let c = opt_color(v, k)?.unwrap_or(anicraft_doc::Rgba::BLACK); - v[*k] = json!({"r": c.r, "g": c.g, "b": c.b, "a": c.a}); +/// A colour effect change as `element.set_color_effect` and `camera.set` take it (ADR 0056): +/// a style, values in percent (or −255..255 for offsets), or both. +pub(crate) struct EffectEdit { + style: Option, + tint: Option, + values: Vec<(usize, f32)>, +} + +impl EffectEdit { + /// The change `p` asks for; `None` when it names no style and no value. + pub(crate) fn parse(p: &Value) -> Result> { + let style = match opt_str(p, "style")? { + Some(k) => Some(ColorStyle::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown style '{k}' (none, brightness, tint, advanced or alpha)")))?), + None => None, + }; + let tint = opt_color(p, "tint")?; + let mut values: Vec<(usize, f32)> = Vec::new(); + let mut families: Vec = tint.map(|_| ColorStyle::Tint).into_iter().collect(); + for (i, (key, fam, lo, hi, scale)) in EFFECT_VALUES.iter().enumerate() { + if let Some(v) = opt_f32(p, key)? { + if !(*lo..=*hi).contains(&v) { + return Err(EngineError::Param(format!("param '{key}' must be between {lo} and {hi}"))); + } + values.push((i, v / scale)); + if !families.contains(fam) { + families.push(*fam); + } } } - Ok(()) + let style = match (style, families.as_slice()) { + (Some(st), f) if f.iter().any(|x| *x != st) => return Err(EngineError::Param(format!("the {} style has none of these values: give only its own", st.key()))), + (Some(st), _) => Some(st), + (None, []) => return Ok(None), + (None, [one]) => Some(*one), + (None, _) => return Err(EngineError::Param("these values belong to different styles: give one style's values".into())), + }; + Ok(Some(EffectEdit { style, tint, values })) } - for f in list.as_array_mut().into_iter().flatten() { - hex_colors(f, &["color", "shadow_color", "highlight_color"])?; - if let Some(stops) = f.get_mut("stops").and_then(Value::as_array_mut) { - if stops.len() > anicraft_doc::MAX_RAMP_STOPS { - return Err(EngineError::Param(format!("a ramp has at most {} stops", anicraft_doc::MAX_RAMP_STOPS))); - } - for st in stops.iter_mut() { - hex_colors(st, &["color"])?; + + /// Whether it sets an alpha value (the Alpha style, or an alpha multiplier or offset). + pub(crate) fn touches_alpha(&self) -> bool { + self.style == Some(ColorStyle::Alpha) || self.values.iter().any(|(i, _)| matches!(i, 0 | 6 | 10)) + } + + /// `fx` changed: into the style (a new one starting from the look it can keep), with the + /// values given set and the rest kept. + pub(crate) fn apply(&self, fx: &ColorEffect) -> ColorEffect { + let mut fx = fx.to_style(self.style.unwrap_or(fx.style())); + if let ColorEffect::Tint { color, .. } = &mut fx + && let Some(t) = self.tint + { + *color = t.with_alpha(1.0); + } + for &(i, v) in &self.values { + match &mut fx { + ColorEffect::Alpha(a) if i == 0 => *a = v, + ColorEffect::Brightness(b) if i == 1 => *b = v, + ColorEffect::Tint { amount, .. } if i == 2 => *amount = v, + ColorEffect::Advanced(t) => { + if let Some(m) = i.checked_sub(3).and_then(|j| t.mul.get_mut(j)) { + *m = v; + } else if let Some(o) = i.checked_sub(7).and_then(|j| t.add.get_mut(j)) { + *o = v; + } + } + _ => {} } } + fx.sanitized() } - let filters: Vec = serde_json::from_value(list).map_err(|e| EngineError::Param(format!("'filters' must be a list of {{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …}}: {e}")))?; - if filters.len() > MAX_FILTERS { - return Err(EngineError::Param(format!("at most {MAX_FILTERS} filters per instance"))); - } - let filters: Vec = filters.iter().map(anicraft_doc::Filter::sanitized).collect(); - let kinds: std::collections::HashMap = s.doc.library.iter().map(|x| (x.id, x.kind)).collect(); - let (mut set, mut graphics) = (0, 0); - for e in s.selected_elements_mut()? { - if let ElementKind::Symbol { symbol, filters: f, .. } = &mut e.kind { - if kinds.get(symbol) == Some(&SymbolKind::Graphic) { - graphics += 1; - continue; - } - f.clone_from(&filters); - set += 1; +} + +fn set_color_effect(s: &mut Session, p: &Value) -> Result { + let edit = EffectEdit::parse(p)?.ok_or_else(|| EngineError::Param("give a style, or a value to set".into()))?; + let mut first = None; + for e in s.selected_props_mut()? { + if matches!(e.kind, ElementKind::Camera) && edit.touches_alpha() { + return Err(EngineError::State("the camera has no opacity: its colour effect is None, Brightness, Tint or Advanced (without alpha)".into())); } + e.color = edit.apply(&e.color); + if matches!(e.kind, ElementKind::Camera) { + e.color = anicraft_doc::camera::camera_effect(&e.color); + } + first.get_or_insert(e.color); } - if set == 0 { - return Err(EngineError::State(if graphics > 0 { - "filters apply to movie clip and button instances, as in Animate; set the symbol's Type to Movie Clip first".into() - } else { - "select a movie clip or button instance".into() - })); - } - Ok(json!({"filters": filters.len(), "set": set})) + Ok(first.map_or(Value::Null, |fx| crate::color_effect_json(&fx))) } /// Blending for the selected movie clip and button instances (Animate offers it on those only). @@ -471,7 +566,7 @@ fn set_blend(s: &mut Session, p: &Value) -> Result { let kinds: std::collections::HashMap = s.doc.library.iter().map(|x| (x.id, x.kind)).collect(); let mut set = 0; let mut graphics = 0; - for e in s.selected_elements_mut()? { + for e in s.selected_props_mut()? { if let ElementKind::Symbol { symbol, blend, .. } = &mut e.kind { if kinds.get(symbol) == Some(&SymbolKind::Graphic) { graphics += 1; @@ -483,7 +578,7 @@ fn set_blend(s: &mut Session, p: &Value) -> Result { } if set == 0 { return Err(EngineError::State(if graphics > 0 { - "blending applies to movie clip and button instances, as in Animate; set the symbol's Type to Movie Clip first".into() + "blending applies to movie clip and button instances; set the symbol's Type to Movie Clip first".into() } else { "select a movie clip or button instance".into() })); @@ -526,13 +621,38 @@ fn set_loop(s: &mut Session, p: &Value) -> Result { /// A symbol's kind, for every instance of it: a graphic keeps step with the timeline it is /// placed on, a movie clip plays its own timeline on a loop, a button shows its Up frame. fn set_symbol_kind(s: &mut Session, p: &Value) -> Result { - let kind = match str_req(p, "kind")? { - "graphic" => SymbolKind::Graphic, - "movie_clip" | "movie clip" => SymbolKind::MovieClip, - "button" => SymbolKind::Button, - other => return Err(EngineError::Param(format!("unknown symbol kind '{other}' (graphic, movie_clip or button)"))), + let kind = crate::cmds_library::kind_of(str_req(p, "kind")?)?; + let ids: Vec = match opt_u64(p, "symbol")? { + Some(id) => vec![SymbolId(id)], + None => { + // The symbols of the selected instances, on every layer (ADR 0053: a "mixed" Type + // row sets them all), in selection order. + let mut ids = Vec::new(); + for (layer, sel) in s.selection.iter() { + if let Some(ElementKind::Symbol { symbol, .. }) = s.elements_on(layer).iter().find(|e| e.id == sel).map(|e| &e.kind) + && !ids.contains(symbol) + { + ids.push(*symbol); + } + } + if ids.is_empty() { + return Err(EngineError::State(if s.selection.is_empty() { "select a symbol instance, or pass 'symbol'".into() } else { "the selection is not a symbol instance".into() })); + } + ids + } }; - let id = match opt_u64(p, "symbol")? { + for id in &ids { + 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 sym.kind != kind { + std::sync::Arc::make_mut(sym).kind = kind; + } + } + Ok(json!({"symbol": ids.first().map(|i| i.0), "symbols": ids.iter().map(|i| i.0).collect::>(), "kind": format!("{kind:?}")})) +} + +/// The symbol a command means: `symbol`, else the selected instance's. +fn selected_symbol(s: &Session, p: &Value) -> Result { + Ok(match opt_u64(p, "symbol")? { Some(id) => SymbolId(id), None => { // The symbol of the selected instance. @@ -542,14 +662,52 @@ fn set_symbol_kind(s: &mut Session, p: &Value) -> Result { .find(|e| e.id == sel) .and_then(|e| match e.kind { ElementKind::Symbol { symbol, .. } => Some(symbol), - ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera => None, + ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None, }) .ok_or_else(|| EngineError::State("the selection is not a symbol instance".into()))? } + }) +} + +/// 9-slice guides (ADR 0055): on, off or moved, on one symbol. +fn set_scale_grid(s: &mut Session, p: &Value) -> Result { + let on = opt_bool(p, "on")?; + let edges = [opt_f32(p, "left")?, opt_f32(p, "right")?, opt_f32(p, "top")?, opt_f32(p, "bottom")?]; + if on.is_none() && edges.iter().all(Option::is_none) { + return Err(EngineError::Param("pass 'on', or a guide to move: 'left', 'right', 'top' or 'bottom'".into())); + } + // The open symbol is the one being edited; otherwise the selected instance's. + let id = match (opt_u64(p, "symbol")?, s.editing_symbol()) { + (None, Some(open)) => open, + _ => selected_symbol(s, p)?, }; - let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; - std::sync::Arc::make_mut(sym).kind = kind; - Ok(json!({"symbol": id.0, "kind": format!("{kind:?}")})) + let sym = s.doc.symbol(id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + let grid = if on == Some(false) { + if edges.iter().any(Option::is_some) { + return Err(EngineError::Param("guides can't be moved while turning them off".into())); + } + None + } else { + // Switched on again, the guides come back where they were (ADR 0057). + let start = sym.scale_grid.or(sym.scale_grid_kept).unwrap_or_else(|| { + let b = anicraft_doc::symbol_box(&s.doc, sym); + ScaleGrid::inset(&if b.is_empty() { anicraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0) } else { b }) + }); + let [l, r, t, b] = edges; + let g = ScaleGrid { left: l.unwrap_or(start.left), right: r.unwrap_or(start.right), top: t.unwrap_or(start.top), bottom: b.unwrap_or(start.bottom) }; + g.check().map_err(EngineError::Param)?; + Some(g) + }; + // Off, the guides are kept (only hidden), so switching back on finds them. + let kept = if grid.is_none() { sym.scale_grid.or(sym.scale_grid_kept) } else { None }; + if let Some(sym) = s.doc.library.iter_mut().find(|x| x.id == id) + && (sym.scale_grid != grid || sym.scale_grid_kept != kept) + { + let sym = Arc::make_mut(sym); + sym.scale_grid = grid; + sym.scale_grid_kept = kept; + } + Ok(json!({"symbol": id.0, "scale_grid": grid.map(|g| json!({"left": g.left, "right": g.right, "top": g.top, "bottom": g.bottom}))})) } fn rename(s: &mut Session, p: &Value) -> Result { @@ -648,8 +806,14 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { let Some(&top) = layers.first() else { return Err(EngineError::State("select something to convert".into())); }; - let n = s.doc.library.len() + 1; - let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}")); + // Into the folder asked for (ADR 0053), else the top level; the name is free there: the + // next free “Symbol n”, or the name asked for with a number when the folder has it already. + let folder = crate::cmds_library::opt_folder(s, p, "folder")?; + let kind = opt_str(p, "kind")?.map(crate::cmds_library::kind_of).transpose()?.unwrap_or(SymbolKind::Graphic); + let name: String = match opt_str(p, "name")? { + Some(n) => s.doc.unique_name(folder, n), + None => s.doc.numbered_name(folder, "Symbol", s.doc.library.len() + 1), + }; let bounds = s.selection_bounds(); let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() }; let sym_id = SymbolId(s.doc.alloc_id()); @@ -668,7 +832,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { let mut inner: Vec> = Vec::with_capacity(layers.len()); for l in layers { let sel = s.selection.on(l); - let source = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let source = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); let picked = s.with_layer(l, |s| -> Result>> { let kf = s.editable_keyframe()?; let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len()); @@ -694,10 +858,13 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { } inner.push(Arc::new(layer)); } - s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: inner } })); + s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: inner } })); + if folder.is_some() { + s.doc.place_entry(LibraryEntry::Item(LibraryItem::Symbol(sym_id)), folder); + } s.layer = top; s.select_only([inst_id]); - Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0})) + Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0, "folder": folder.map(|f| f.0)})) } fn break_apart(s: &mut Session, _: &Value) -> Result { @@ -709,7 +876,21 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { let mut fresh_ids = Vec::new(); let kf_elements: Vec> = s.editable_keyframe()?.elements.clone(); let mut out = Vec::new(); + // Drawing objects (Object Drawing) break apart into raw shapes, which then merge with the + // raw shapes they touch, as in Animate (#253). + let mut objects = Vec::new(); for e in kf_elements { + if let ElementKind::Shape(sh) = &e.kind + && !sh.merge + && sel.contains(&e.id) + { + let mut c = (*e).clone(); + if let ElementKind::Shape(sh) = &mut c.kind { + sh.merge = true; + } + objects.push(c); + continue; + } // Text breaks apart into a shape with the same outlines. if let ElementKind::Text(t) = &e.kind && sel.contains(&e.id) @@ -721,6 +902,25 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { out.push(Arc::new(c)); continue; } + // A group breaks apart into its members (Animate's Ctrl+B on a group ungroups it). + if let ElementKind::Group { .. } = &e.kind + && sel.contains(&e.id) + { + for child in e.kind.group_members() { + let mut c = (*child).clone(); + c.id = ElementId(s.doc.alloc_id()); + c.transform = e.transform.mul(&child.transform); + c.color = e.color.nested(&child.color); + // Its raw shapes merge with the drawing they now stand in, as drawing objects do. + if crate::merge::mergeable(&c).is_some() { + objects.push(c); + continue; + } + fresh_ids.push(c.id); + out.push(Arc::new(c)); + } + continue; + } let ElementKind::Symbol { symbol, .. } = &e.kind else { out.push(e); continue; @@ -738,32 +938,103 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { let mut c = (**child).clone(); c.id = ElementId(s.doc.alloc_id()); c.transform = e.transform.mul(&child.transform); - c.color = e.color.concat(&child.color); + c.color = e.color.nested(&child.color); fresh_ids.push(c.id); out.push(Arc::new(c)); } } } - if fresh_ids.is_empty() { - return Err(EngineError::State("the selection has no symbol instances or text to break apart".into())); + if fresh_ids.is_empty() && objects.is_empty() { + return Err(EngineError::State("the selection has no symbol instances, groups, text or drawing objects to break apart".into())); } s.editable_keyframe()?.elements = out; + if !objects.is_empty() { + fresh_ids.extend(crate::merge::merge_in(s, objects)?); + } s.select_only(fresh_ids.iter().copied()); Ok(json!({"created": fresh_ids.len()})) } -/// Places a Library item centred on `x`/`y` (default: the stage centre): an instance of -/// `symbol`, or a rectangle of `bitmap`'s size showing it, in the current keyframe, selected. -fn place(s: &mut Session, p: &Value) -> Result { - if let Some(bitmap) = opt_u64(p, "bitmap")? { - return place_bitmap(s, p, anicraft_doc::BitmapId(bitmap)); +/// Most items one `library.place` takes. +const MAX_PLACE: usize = 1_000; + +/// Places Library items at `x`/`y` (default: the stage centre), as a drop from the Library +/// does (ADR 0053): an instance of each symbol, a rectangle of each bitmap's size showing it, +/// in the active layer's keyframe at the playhead, all selected; a sound goes onto that +/// keyframe. One command, so one undo step however many items. +pub(crate) fn place(s: &mut Session, p: &Value) -> Result { + let items: Vec = match p.get("items") { + Some(list) => { + let list = list.as_array().ok_or_else(|| EngineError::Param("param 'items' must be a list of {\"symbol\" | \"bitmap\" | \"sound\": id}".into()))?; + if list.len() > MAX_PLACE { + return Err(EngineError::Param(format!("at most {MAX_PLACE} items at once"))); + } + let mut out = Vec::with_capacity(list.len()); + for v in list { + match crate::cmds_library::entry_of(v)? { + LibraryEntry::Item(i) => out.push(i), + LibraryEntry::Folder(_) => return Err(EngineError::Param("a folder can't be placed; name the items in it".into())), + } + } + out + } + None => match (opt_u64(p, "symbol")?, opt_u64(p, "bitmap")?, opt_u64(p, "sound")?) { + (Some(i), None, None) => vec![LibraryItem::Symbol(SymbolId(i))], + (None, Some(i), None) => vec![LibraryItem::Bitmap(anicraft_doc::BitmapId(i))], + (None, None, Some(i)) => vec![LibraryItem::Sound(anicraft_doc::SoundId(i))], + _ => return Err(EngineError::Param("name one item ('symbol', 'bitmap' or 'sound'), or a list in 'items'".into())), + }, + }; + if items.is_empty() { + return Err(EngineError::Param("nothing to place".into())); } - let sym = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' or 'bitmap' is required".into()))?); - if s.doc.symbol(sym).is_none() { - return Err(EngineError::State(format!("no symbol with id {}", sym.0))); + let mut sound = None; + for &i in &items { + if !s.doc.has_item(i) { + return Err(EngineError::State(match i { + LibraryItem::Symbol(id) => format!("no symbol with id {}", id.0), + LibraryItem::Bitmap(id) => format!("no bitmap with id {}", id.0), + LibraryItem::Sound(id) => format!("no sound with id {} in the library", id.0), + })); + } + match i { + LibraryItem::Symbol(id) if crate::editing::would_nest(s, id) => return Err(EngineError::State("a symbol can't be placed inside itself".into())), + LibraryItem::Sound(id) => { + if sound.is_some_and(|x| x != id) { + return Err(EngineError::State("a keyframe holds one sound; place sounds one at a time, on different keyframes or layers".into())); + } + sound = Some(id); + } + _ => {} + } } let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0); let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0); + if !(x.is_finite() && y.is_finite()) || x.abs() > 1.0e6 || y.abs() > 1.0e6 { + return Err(EngineError::Param("'x' and 'y' must be within a million pixels of the origin".into())); + } + let mut placed = Vec::new(); + for &i in &items { + match i { + LibraryItem::Symbol(id) => placed.push(place_symbol(s, id, x, y)?), + LibraryItem::Bitmap(id) => placed.push(place_bitmap(s, id, x, y)?), + LibraryItem::Sound(_) => {} + } + } + let mut out = json!({"element": placed.first().map(|e| e.0), "elements": placed.iter().map(|e| e.0).collect::>()}); + if let Some(id) = sound { + if s.active_layer().is_some_and(|l| l.locked) || s.timeline().locked_by_folder(s.layer) { + return Err(EngineError::State("the active layer is locked; unlock it to put a sound on it".into())); + } + out["sound"] = crate::cmds_sound::place(s, &json!({"sound": id.0, "extend": true}))?; + } + if !placed.is_empty() { + s.select_only(placed.iter().copied()); + } + Ok(out) +} + +fn place_symbol(s: &mut Session, sym: SymbolId, x: f32, y: f32) -> Result { let id = ElementId(s.doc.alloc_id()); let el = Element { id, @@ -773,17 +1044,14 @@ fn place(s: &mut Session, p: &Value) -> Result { kind: ElementKind::Symbol { symbol: sym, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.select_only([id]); - Ok(json!({"element": id.0})) + Ok(id) } -fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> Result { +fn place_bitmap(s: &mut Session, bitmap: anicraft_doc::BitmapId, x: f32, y: f32) -> Result { let (name, w, h) = match s.doc.bitmap(bitmap) { Some(b) => (b.name.clone(), b.width as f32, b.height as f32), None => return Err(EngineError::State(format!("no bitmap with id {}", bitmap.0))), }; - let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0); - let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0); let id = ElementId(s.doc.alloc_id()); let el = Element { id, @@ -796,9 +1064,9 @@ fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> R stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, + warp: None, }), }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.select_only([id]); - Ok(json!({"element": id.0})) + Ok(id) } diff --git a/crates/engine/src/cmds_drop.rs b/crates/engine/src/cmds_drop.rs new file mode 100644 index 00000000..52823213 --- /dev/null +++ b/crates/engine/src/cmds_drop.rs @@ -0,0 +1,282 @@ +//! Files dropped onto the window (ADR 0059). What a file is, and where it was dropped, decide +//! what happens: documents open (`file.open`, which asks first over unsaved work); drawings, +//! images and sounds dropped on the stage go onto the active layer at the playhead at the drop +//! point, and dropped on the Library go into the Library (into the folder under the pointer; +//! an SVG as a graphic symbol, ADR 0065). Dropped on a layer's frame in the timeline, a sound +//! goes onto the keyframe there and a drawing or image onto that layer at that frame, in a +//! keyframe made there if there is none (ADR 0065). +//! The routing is a pure function the shell and tests share; `file.drop` does the import, so a +//! drop of several files is one undo step however many it brings in. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{FolderId, LibraryEntry, LibraryItem}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Most files one drop brings in. +pub const MAX_DROPPED: usize = 64; + +/// What a dropped file is, by its name (and, for an XFL folder, what is inside it). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropKind { + /// `.anicraft`, `.fla`, `.xfl` (or an XFL folder): opens as the document. + Document, + /// `.svg`. + Drawing, + /// `.png`, `.jpg`, `.jpeg`. + Image, + /// `.wav`, `.ogg`, `.mp3`. + Sound, + /// Anything else. + Unsupported, +} + +/// Where a file was dropped. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropTarget { + Stage, + Library, + /// A layer's frame in the timeline. + Timeline, + /// Anywhere else on the window (panels, the timeline, the menu bar). + Window, +} + +/// What a drop does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropAction { + /// Open it as the document (`file.open`). + Open, + /// `file.drop` with `to: "stage"`. + ImportToStage, + /// `file.drop` with `to: "library"`. + ImportToLibrary, + /// `file.drop` with `to: "timeline"`. + ImportToTimeline, + /// Nothing; the message (English, translated where it is shown) says why. + Refuse(&'static str), +} + +pub fn kind_of(path: &Path) -> DropKind { + if crate::cmds_file::is_animate(path) { + return DropKind::Document; + } + let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + match ext.as_deref() { + Some("anicraft") => DropKind::Document, + Some("svg") => DropKind::Drawing, + Some("png" | "jpg" | "jpeg") => DropKind::Image, + _ if crate::cmds_sound::is_sound(path) => DropKind::Sound, + _ => DropKind::Unsupported, + } +} + +/// The message for a file AniCraft can't take. +pub const UNSUPPORTED: &str = "AniCraft opens .anicraft, .fla and .xfl documents, and imports SVG drawings, PNG and JPEG images, and WAV, Ogg and MP3 sounds"; + +/// What dropping a file of `kind` on `target` does. +pub fn route(kind: DropKind, target: DropTarget) -> DropAction { + match (kind, target) { + (DropKind::Document, _) => DropAction::Open, + (DropKind::Unsupported, _) => DropAction::Refuse(UNSUPPORTED), + (_, DropTarget::Library) => DropAction::ImportToLibrary, + (_, DropTarget::Timeline) => DropAction::ImportToTimeline, + (_, DropTarget::Stage) => DropAction::ImportToStage, + // Not over the stage, the timeline or the Library: drop it on one of them. + (_, DropTarget::Window) => DropAction::Refuse(ELSEWHERE), + } +} + +/// The message for media dropped where nothing takes them. +pub const ELSEWHERE: &str = "Drop drawings, images and sounds on the stage or a layer's frame to place them, or on the Library to add them"; + +pub fn specs() -> Vec { + vec![CommandSpec { + id: "file.drop", + label: "Import Dropped Files", + menu: "", + shortcut: None, + params: "{paths: [..] (or path; SVG, PNG, JPEG, WAV, OGG, MP3; at most 64), to: stage | library | timeline, x?, y? (stage and timeline: the point in the edited space to centre on, default the stage centre), folder? (library: a folder id), layer, frame (timeline: a layer id and a frame, from 0)} → {elements, items, layers}: on the stage each drawing, image and sound goes onto the active layer's keyframe at the playhead, centred on the drop point (a drawing with several layers or masks gets its own layers, as Import to Stage); in the Library images and sounds are added, and drawings become graphic symbols, into `folder`; on the timeline the playhead goes to the frame, a sound goes onto the layer's keyframe there (one sound per drop) and drawings and images onto the layer in a keyframe starting at that frame (made if needed, keeping what the frame showed; a drawing with several layers or masks goes in as a graphic symbol). One undo step", + mutates: true, + run: drop, + }] +} + +fn paths(p: &Value) -> Result> { + let list: Vec = match (p.get("paths"), opt_str(p, "path")?) { + (Some(v), None) => { + let a = v.as_array().ok_or_else(|| EngineError::Param("param 'paths' must be a list of file paths".into()))?; + a.iter().map(|x| x.as_str().map(PathBuf::from).ok_or_else(|| EngineError::Param("param 'paths' must be a list of file paths".into()))).collect::>()? + } + (None, Some(one)) => vec![PathBuf::from(one)], + _ => return Err(EngineError::Param("name the files with 'paths' (or one with 'path')".into())), + }; + if list.is_empty() || list.len() > MAX_DROPPED { + return Err(EngineError::Param(format!("drop 1 to {MAX_DROPPED} files at once"))); + } + Ok(list) +} + +fn drop(s: &mut Session, p: &Value) -> Result { + let files = paths(p)?; + let target = match str_req(p, "to")? { + "stage" => DropTarget::Stage, + "library" => DropTarget::Library, + "timeline" => DropTarget::Timeline, + other => return Err(EngineError::Param(format!("param 'to' must be stage, library or timeline, not '{other}'"))), + }; + // Everything is checked before anything is imported (the command is atomic anyway). + for f in &files { + match route(kind_of(f), target) { + DropAction::Open => return Err(EngineError::Param(format!("{} is a document: open it with file.open", f.display()))), + DropAction::Refuse(why) => return Err(EngineError::Param(format!("{}: {why}", f.display()))), + DropAction::ImportToStage | DropAction::ImportToLibrary | DropAction::ImportToTimeline => {} + } + } + let folder = match opt_u64(p, "folder")? { + Some(f) if target == DropTarget::Library => { + let id = FolderId(f); + if s.doc.folder(id).is_none() { + return Err(EngineError::State(format!("no Library folder with id {f}"))); + } + Some(id) + } + Some(_) => return Err(EngineError::Param("'folder' is for drops on the Library".into())), + None => None, + }; + let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0); + let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0); + if !(x.is_finite() && y.is_finite()) || x.abs() > 1.0e6 || y.abs() > 1.0e6 { + return Err(EngineError::Param("'x' and 'y' must be within a million pixels of the origin".into())); + } + if target == DropTarget::Timeline { + return onto_timeline(s, p, &files, x, y); + } + let (mut elements, mut items, mut layers) = (Vec::new(), Vec::new(), 0u64); + for f in &files { + let path = f.display().to_string(); + if target == DropTarget::Library { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let item = match (v["bitmap"].as_u64(), v["sound"].as_u64(), v["symbol"].as_u64()) { + (Some(b), _, _) => LibraryItem::Bitmap(anicraft_doc::BitmapId(b)), + (None, Some(snd), _) => LibraryItem::Sound(anicraft_doc::SoundId(snd)), + (None, None, Some(sym)) => LibraryItem::Symbol(anicraft_doc::SymbolId(sym)), + _ => return Err(EngineError::State(format!("{path} added nothing to the Library"))), + }; + if let Some(folder) = folder { + // Into the folder under the pointer, numbered if it has an item of that name. + let name = s.doc.item_name(item).unwrap_or("").to_string(); + let free = s.doc.unique_name(Some(folder), &name); + s.doc.place_entry(LibraryEntry::Item(item), Some(folder)); + if free != name { + let mut params = crate::cmds_library::entry_json(LibraryEntry::Item(item)); + params["name"] = json!(free); + crate::cmds_library::rename(s, ¶ms)?; + } + } + items.push(crate::cmds_library::entry_json(LibraryEntry::Item(item))); + continue; + } + match kind_of(f) { + DropKind::Drawing => { + // A drawing's own shapes, on the active layer (or its own layers when it has + // several or masks), centred on the drop point. + let v = crate::cmds_file::import_to_stage(s, &json!({"path": path, "cx": x, "cy": y, "layer": "active"}))?; + layers += v["layers"].as_u64().unwrap_or(0); + elements.extend(s.selection.ids()); + } + _ => { + // An image or a sound: into the Library, then placed as Place on Stage does. + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let item = match (v["bitmap"].as_u64(), v["sound"].as_u64()) { + (Some(b), _) => json!({"bitmap": b}), + (None, Some(snd)) => json!({"sound": snd}), + _ => return Err(EngineError::State(format!("{path} added nothing to the Library"))), + }; + items.push(item.clone()); + let mut place = item; + place["x"] = json!(x); + place["y"] = json!(y); + let placed = crate::cmds_draw::place(s, &place)?; + if let Some(list) = placed["elements"].as_array() { + elements.extend(list.iter().filter_map(Value::as_u64).map(anicraft_doc::ElementId)); + } + } + } + } + if !elements.is_empty() { + s.select_only(elements.iter().copied()); + } + Ok(json!({"elements": elements.iter().map(|e| e.0).collect::>(), "items": items, "layers": layers, "files": files.len()})) +} + +/// A drop on a layer's frame in the timeline (ADR 0065). +fn onto_timeline(s: &mut Session, p: &Value, files: &[PathBuf], x: f32, y: f32) -> Result { + let layer = anicraft_doc::LayerId(opt_u64(p, "layer")?.ok_or_else(|| EngineError::Param("a drop on the timeline names its 'layer' (an id)".into()))?); + let frame = opt_u32(p, "frame")?.ok_or_else(|| EngineError::Param("a drop on the timeline names its 'frame' (from 0)".into()))?; + if frame > crate::MAX_FRAME { + return Err(EngineError::Param(format!("'frame' must be at most {}", crate::MAX_FRAME))); + } + let tl = s.timeline(); + let l = tl.layer(layer).ok_or_else(|| EngineError::State(format!("no layer with id {} here", layer.0)))?; + let refuse = match l.kind { + anicraft_doc::LayerKind::Folder => Some("is a folder: drop on one of its layers"), + anicraft_doc::LayerKind::Camera => Some("is the camera layer: drop on a layer below it"), + anicraft_doc::LayerKind::Armature => Some("holds an armature, posed by its bones: drop on another layer"), + _ if l.locked || tl.locked_by_folder(layer) => Some("is locked: unlock it to drop onto it"), + _ => None, + }; + if let Some(why) = refuse { + return Err(EngineError::State(format!("“{}” {why}", l.name))); + } + if files.iter().filter(|f| kind_of(f) == DropKind::Sound).count() > 1 { + return Err(EngineError::Param("a keyframe holds one sound: drop sounds one at a time, or on different layers".into())); + } + s.layer = layer; + s.frame = frame; + // Artwork goes into a keyframe starting at the frame: made there when the frame is inside + // another's span (keeping what it showed, as Insert Keyframe does). + let artwork = files.iter().any(|f| kind_of(f) != DropKind::Sound); + let made = artwork && s.timeline().layer(layer).is_some_and(|l| l.keyframe_starting_at(frame).is_none()); + if made { + crate::cmds_timeline::insert_keyframe_at(s.layer_mut(Some(layer))?, frame, true)?; + } + let (mut elements, mut items) = (Vec::new(), Vec::new()); + let placed_ids = |v: &Value| -> Vec { v["elements"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(anicraft_doc::ElementId).collect() }; + for f in files { + let path = f.display().to_string(); + let nothing = || EngineError::State(format!("{path} added nothing to the Library")); + match kind_of(f) { + DropKind::Drawing if crate::cmds_file::one_layer(&crate::cmds_file::read_svg(f)?) => { + crate::cmds_file::import_to_stage(s, &json!({"path": path, "cx": x, "cy": y, "layer": "active"}))?; + elements.extend(s.selection.ids()); + } + DropKind::Drawing => { + // Its layers can't all go on one layer: a graphic symbol holding them goes there. + let v = crate::cmds_file::import_svg_symbol(s, f, None)?; + let sym = v["symbol"].as_u64().ok_or_else(nothing)?; + items.push(json!({"symbol": sym})); + elements.extend(placed_ids(&crate::cmds_draw::place(s, &json!({"symbol": sym, "x": x, "y": y}))?)); + } + DropKind::Sound => { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let snd = v["sound"].as_u64().ok_or_else(nothing)?; + items.push(json!({"sound": snd})); + // Onto the keyframe the frame is in (one is made past the layer's end), as long + // as the sound when it is the layer's last. + crate::cmds_sound::place(s, &json!({"sound": snd, "layer": layer.0, "frame": frame, "extend": true}))?; + } + _ => { + let v = crate::cmds_sound::import_to_library(s, &json!({"path": path}))?; + let b = v["bitmap"].as_u64().ok_or_else(nothing)?; + items.push(json!({"bitmap": b})); + elements.extend(placed_ids(&crate::cmds_draw::place(s, &json!({"bitmap": b, "x": x, "y": y}))?)); + } + } + } + if !elements.is_empty() { + s.select_only(elements.iter().copied()); + } + Ok(json!({"elements": elements.iter().map(|e| e.0).collect::>(), "items": items, "layers": 0, "files": files.len(), "layer": layer.0, "frame": frame, "keyframe_made": made})) +} diff --git a/crates/engine/src/cmds_ease.rs b/crates/engine/src/cmds_ease.rs new file mode 100644 index 00000000..eea07a7c --- /dev/null +++ b/crates/engine/src/cmds_ease.rs @@ -0,0 +1,346 @@ +//! Eases (ADR 0081): the preset library, custom eases edited point by point, eases saved in +//! the document, and copy and paste of an ease between tweens. +//! +//! Every command addresses one ease, the *target*: +//! +//! * a classic or shape tween's (the span at `layer?`/`frame?`), or with `group` one property +//! group's (`position`, `rotation`, `scale`, `color`, `filters`; ADR 0081 §3); +//! * a motion tween's property segment (the span at `layer?`/`frame?`, the segment the frame is +//! in, of `property`, or every property when it is left out); +//! * a saved ease (`saved: name`). +//! +//! Point edits turn a preset into the custom curve that draws it ([`Easing::to_custom`]) and +//! edit that. The curve stays valid whatever is asked (time never runs backwards; values stay +//! within bounds; see [`CustomEase`]); an edit that can't apply (moving an end, deleting the +//! last point between them) is an error that changes nothing. + +use crate::cmds_timeline::target; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{CustomEase, EaseGroup, Easing, Handle, LayerId, MAX_SAVED_EASES, Property, SavedEase, Tween, TweenKind, ease_name}; +use anicraft_geom::Vec2; +use serde_json::{Value, json}; +use std::sync::Arc; + + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("ease.info", "Ease", "", None, "{target: layer?, frame?, group? | property? | saved?} → the ease (as easing params take it), its label, and its curve as points (exact unless the preset is fitted)", false, info as crate::RunFn), + c("ease.set", "Set Ease", "", None, "{easing: a preset name | {classic: n} | {bezier: [..]} | {custom: ..} | {saved: name} | {plugin: id, ease: id} (the tween keeps the sampled curve) | {sampled: ..}, layer?, frame?, group? | property? | saved?}", true, set), + c("ease.add_point", "Add Ease Point", "", None, "{t: time 0..1 on the curve (its shape stays), layer?, frame?, group? | property? | saved?} → {index}", true, add_point), + c("ease.move_point", "Move Ease Point", "", None, "{index, x (time, kept between its neighbours), y (value, may overshoot), layer?, frame?, group? | property? | saved?} (the ends stay at (0, 0) and (1, 1))", true, move_point), + c("ease.move_handle", "Move Ease Handle", "", None, "{index, handle: in|out, x, y (absolute; x stays between the point and its neighbour), layer?, frame?, group? | property? | saved?} (a smooth point's other handle turns with it)", true, move_handle), + c("ease.delete_point", "Delete Ease Point", "", None, "{index (not an end), layer?, frame?, group? | property? | saved?}", true, delete_point), + c("ease.convert_point", "Convert Ease Point", "", None, "{index, smooth: bool (handles in line) or corner (handles on the point), layer?, frame?, group? | property? | saved?}", true, convert_point), + c("ease.separate", "Ease Properties Separately", "", None, "{separate: bool, layer?, frame?}: a classic tween with one ease per property group (each starting from the tween's), or one ease for all (the groups' own go)", true, separate), + c("ease.save", "Save Ease", "", None, "{name, easing? (default: the target's ease), replace?: bool, layer?, frame?, group? | property?} → saved in the document, offered with the presets", true, save), + c("ease.delete", "Delete Saved Ease", "", None, "{name} (tweens using it keep their curves)", true, delete), + c("ease.rename", "Rename Saved Ease", "", None, "{name, to}", true, rename), + c("ease.list", "Eases", "", None, "{} → the presets (name, label, family, direction), the eases saved in the document, and the installed ease plug-ins' eases ({plugin, ease} as easing params take them)", false, list), + c("ease.copy", "Copy Ease", "", None, "{layer?, frame?, group? | property? | saved?}: the ease, for ease.paste", false, copy), + c("ease.paste", "Paste Ease", "", None, "{layer?, frame?, group? | property? | saved?}: the copied ease onto this target", true, paste), + ] +} + +/// The one ease a command addresses (see the module docs). +#[derive(Clone, Debug, PartialEq)] +pub enum EaseAt { + Tween { layer: LayerId, frame: u32, group: Option }, + Motion { layer: LayerId, frame: u32, property: Option }, + Saved(String), +} + +pub(crate) fn group(p: &Value) -> Result> { + match opt_str(p, "group")? { + None => Ok(None), + Some(g) if g.trim().eq_ignore_ascii_case("all") => Ok(None), + Some(g) => EaseGroup::from_key(g).map(Some).ok_or_else(|| EngineError::Param(format!("unknown group '{g}' (all, position, rotation, scale, color, filters)"))), + } +} + +fn property(p: &Value) -> Result> { + match opt_str(p, "property")? { + None => Ok(None), + Some(k) => Property::from_key(k).map(Some).ok_or_else(|| EngineError::Param(format!("unknown property '{k}'"))), + } +} + +pub fn ease_target(s: &Session, p: &Value) -> Result { + if let Some(n) = opt_str(p, "saved")? { + saved_ease(&s.doc, n)?; + return Ok(EaseAt::Saved(n.to_string())); + } + let (lid, frame) = target(s, p)?; + let layer = lid.unwrap_or(s.layer); + let l = s.timeline().layer(layer).ok_or_else(|| EngineError::State(format!("no layer with id {}", layer.0)))?; + let kf = l.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; + if kf.motion.is_some() { + if p.get("group").is_some_and(|g| !g.is_null()) { + return Err(EngineError::Param("a motion tween eases each property's segments: give 'property', not 'group'".into())); + } + return Ok(EaseAt::Motion { layer, frame, property: property(p)? }); + } + let Some(t) = &kf.tween else { return Err(EngineError::State(format!("frame {} has no tween; create one first (Insert › Create Classic Tween)", frame + 1))) }; + let group = group(p)?; + if group.is_some() && t.kind == TweenKind::Shape { + return Err(EngineError::State("a shape tween has one ease for everything; property groups ease separately in classic tweens".into())); + } + Ok(EaseAt::Tween { layer, frame, group }) +} + +pub fn read(s: &Session, at: &EaseAt) -> Result { + match at { + EaseAt::Saved(n) => saved_ease(&s.doc, n), + EaseAt::Tween { layer, frame, group } => { + let t = s.timeline().layer(*layer).and_then(|l| l.keyframe_at(*frame)).and_then(|k| k.tween.as_ref()).ok_or_else(|| EngineError::State("the tween is gone".into()))?; + Ok(group.map_or(&t.easing, |g| t.ease(g)).clone()) + } + EaseAt::Motion { layer, frame, property } => { + let kf = s.timeline().layer(*layer).and_then(|l| l.keyframe_at(*frame)).ok_or_else(|| EngineError::State("the tween is gone".into()))?; + let m = kf.motion.as_ref().ok_or_else(|| EngineError::State("the motion tween is gone".into()))?; + let off = frame.saturating_sub(kf.start); + m.tracks.iter().filter(|t| property.is_none_or(|p| p == t.property)).find_map(|t| t.segment_at(off).and_then(|i| t.keys.get(i)).map(|k| k.ease.clone())).ok_or_else(|| not_between(*frame, *property)) + } + } +} + +fn not_between(frame: u32, p: Option) -> EngineError { + EngineError::State(format!("frame {} is not between two property keyframes{}", frame + 1, p.map_or_else(String::new, |o| format!(" of {}", o.label())))) +} + +/// Puts `e` on the target; what it set, for the reply. +pub(crate) fn write(s: &mut Session, at: &EaseAt, e: Easing) -> Result { + let label = e.label(); + match at { + EaseAt::Saved(n) => { + let want = n.to_lowercase(); + let mut list = (*s.doc.eases).clone(); + let slot = list.iter_mut().find(|x| x.name.to_lowercase() == want).ok_or_else(|| EngineError::State(format!("no ease is saved as '{n}'")))?; + slot.ease = e; + let name = slot.name.clone(); + s.doc.eases = Arc::new(list); + Ok(json!({"saved": name, "easing": label})) + } + EaseAt::Tween { layer, frame, group } => { + let l = s.layer_mut(Some(*layer))?; + let i = l.keyframe_index_at(*frame).ok_or_else(|| EngineError::State("the tween is gone".into()))?; + let t = l.keyframe_mut(i).and_then(|k| k.tween.as_mut()).ok_or_else(|| EngineError::State("the tween is gone".into()))?; + match group { + Some(g) => t.set_ease(*g, Some(e)), + None => t.easing = e, + } + Ok(json!({"easing": label, "group": group.map_or("all", |g| g.key())})) + } + EaseAt::Motion { layer, frame, property } => { + let l = s.layer_mut(Some(*layer))?; + let i = l.keyframe_index_at(*frame).ok_or_else(|| EngineError::State("the tween is gone".into()))?; + let kf = l.keyframe_mut(i).ok_or_else(|| EngineError::State("the tween is gone".into()))?; + let off = frame.saturating_sub(kf.start); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("the motion tween is gone".into()))?; + let mut set = Vec::new(); + for t in m.tracks.iter_mut().filter(|t| property.is_none_or(|p| p == t.property)) { + if let Some(k) = t.segment_at(off).and_then(|i| t.keys.get_mut(i)) { + k.ease = e.clone(); + set.push(t.property.key()); + } + } + if set.is_empty() { + return Err(not_between(*frame, *property)); + } + Ok(json!({"easing": label, "properties": set})) + } + } +} + +/// An ease's curve for replies: each point and its handles (absolute), and smooth. +pub fn points_json(c: &CustomEase) -> Value { + Value::Array(c.points().iter().map(|p| json!({"x": p.at.x, "y": p.at.y, "in": [p.at.x + p.h_in.x, p.at.y + p.h_in.y], "out": [p.at.x + p.out.x, p.at.y + p.out.y], "smooth": p.smooth})).collect()) +} + +fn kind(e: &Easing) -> &'static str { + match e { + Easing::Classic(_) => "classic", + Easing::CubicBezier(..) => "bezier", + Easing::Custom(_) => "custom", + Easing::Sampled(_) => "plugin", + _ => "preset", + } +} + +/// The name a saved ease with exactly this curve goes by, if any. +pub fn saved_name<'a>(doc: &'a anicraft_doc::Document, e: &Easing) -> Option<&'a str> { + doc.eases.iter().find(|x| x.ease == *e).map(|x| x.name.as_str()) +} + +fn info(s: &mut Session, p: &Value) -> Result { + let at = ease_target(s, p)?; + let e = read(s, &at)?; + let curve = e.to_custom(); + let exact = !matches!(e.family(), Some((f, _)) if !matches!(f, anicraft_doc::EaseFamily::Quad | anicraft_doc::EaseFamily::Cubic | anicraft_doc::EaseFamily::Back | anicraft_doc::EaseFamily::Bounce)); + let mut out = json!({"easing": easing_json(&e), "label": e.label(), "kind": kind(&e), "saved_as": saved_name(&s.doc, &e), "points": points_json(&curve), "exact": exact}); + if let EaseAt::Tween { layer, frame, .. } = at + && let Some(t) = s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).and_then(|k| k.tween.as_ref()) + { + out["groups"] = Value::Array(t.groups.iter().map(|(g, e)| json!({"group": g.key(), "easing": easing_json(e), "label": e.label()})).collect()); + } + Ok(out) +} + +fn set(s: &mut Session, p: &Value) -> Result { + let e = opt_easing_in(s, p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?; + let at = ease_target(s, p)?; + write(s, &at, e) +} + +/// The target's curve, edited by `f`; `f` saying `None` is the error `why`. +fn edit(s: &mut Session, p: &Value, why: &str, f: impl FnOnce(&CustomEase) -> Option<(CustomEase, Value)>) -> Result { + let at = ease_target(s, p)?; + let curve = read(s, &at)?.to_custom(); + let (next, mut reply) = f(&curve).ok_or_else(|| EngineError::State(why.to_string()))?; + let n = next.points().len(); + write(s, &at, Easing::Custom(Arc::new(next)))?; + reply["points"] = json!(n); + Ok(reply) +} + +fn index(p: &Value) -> Result { + opt_u32(p, "index")?.map(|i| i as usize).ok_or_else(|| EngineError::Param("param 'index' is required (0 is the start, as ease.info lists the points)".into())) +} + +fn add_point(s: &mut Session, p: &Value) -> Result { + let t = f32_req(p, "t")?; + edit(s, p, "a point can't go there: inside the curve (0 < t < 1), not on a point, and at most 64 points", |c| c.insert_at(t).map(|(c, i)| (c, json!({"index": i})))) +} + +fn move_point(s: &mut Session, p: &Value) -> Result { + let (i, x, y) = (index(p)?, f32_req(p, "x")?, f32_req(p, "y")?); + edit(s, p, "that point can't move: the ends stay at (0, 0) and (1, 1)", |c| c.move_point(i, Vec2::new(x, y)).map(|d| { + let at = d.points().get(i).map_or(Vec2::ZERO, |q| q.at); + (d, json!({"index": i, "x": at.x, "y": at.y})) + })) +} + +fn move_handle(s: &mut Session, p: &Value) -> Result { + let (i, x, y) = (index(p)?, f32_req(p, "x")?, f32_req(p, "y")?); + let h = match str_req(p, "handle")?.trim() { + "in" => Handle::In, + "out" => Handle::Out, + other => return Err(EngineError::Param(format!("param 'handle' must be in or out, not '{other}'"))), + }; + edit(s, p, "that point has no such handle (the start has no in handle, the end no out handle)", |c| c.move_handle(i, h, Vec2::new(x, y)).map(|d| (d, json!({"index": i})))) +} + +fn delete_point(s: &mut Session, p: &Value) -> Result { + let i = index(p)?; + edit(s, p, "that point can't be deleted: the ends stay", |c| c.remove(i).map(|d| (d, json!({"deleted": i})))) +} + +fn convert_point(s: &mut Session, p: &Value) -> Result { + let i = index(p)?; + let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required (true: smooth, false: corner)".into()))?; + edit(s, p, "there is no such point", |c| c.set_smooth(i, smooth).map(|d| (d, json!({"index": i, "smooth": smooth})))) +} + +fn separate(s: &mut Session, p: &Value) -> Result { + let on = opt_bool(p, "separate")?.ok_or_else(|| EngineError::Param("param 'separate' is required".into()))?; + let at = ease_target(s, &json!({"layer": p.get("layer"), "frame": p.get("frame")}))?; + let EaseAt::Tween { layer, frame, .. } = at else { return Err(EngineError::State("only classic tweens ease property groups separately; a motion tween eases each property already".into())) }; + if on && s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).and_then(|k| k.tween.as_ref()).is_some_and(|t| t.kind == TweenKind::Shape) { + return Err(EngineError::State("a shape tween has one ease for everything; property groups ease separately in classic tweens".into())); + } + let l = s.layer_mut(Some(layer))?; + let i = l.keyframe_index_at(frame).ok_or_else(|| EngineError::State("the tween is gone".into()))?; + let t: &mut Tween = l.keyframe_mut(i).and_then(|k| k.tween.as_mut()).ok_or_else(|| EngineError::State("the tween is gone".into()))?; + if on { + for g in EaseGroup::ALL { + if !t.has_own(g) { + let e = t.easing.clone(); + t.set_ease(g, Some(e)); + } + } + } else { + t.groups.clear(); + } + Ok(json!({"separate": on, "groups": t.groups.iter().map(|(g, _)| g.key()).collect::>()})) +} + +fn save(s: &mut Session, p: &Value) -> Result { + let name = ease_name(str_req(p, "name")?).ok_or_else(|| EngineError::Param("param 'name' must have something in it".into()))?; + let e = match opt_easing_in(s, p, "easing")? { + Some(e) => e, + None => { + let at = ease_target(s, p)?; + read(s, &at)? + } + }; + let replace = opt_bool(p, "replace")?.unwrap_or(false); + let mut list = (*s.doc.eases).clone(); + let full = list.len() >= MAX_SAVED_EASES; + match list.iter_mut().find(|x| x.name.to_lowercase() == name.to_lowercase()) { + Some(x) if replace => x.ease = e.clone(), + Some(x) => return Err(EngineError::State(format!("an ease is already saved as '{}'; pass replace: true to replace it", x.name))), + None if full => return Err(EngineError::State(format!("a document keeps at most {MAX_SAVED_EASES} saved eases; delete one first"))), + None => list.push(SavedEase { name: name.clone(), ease: e.clone() }), + } + s.doc.eases = Arc::new(list); + Ok(json!({"saved": name, "easing": e.label(), "count": s.doc.eases.len()})) +} + +fn delete(s: &mut Session, p: &Value) -> Result { + let name = str_req(p, "name")?; + saved_ease(&s.doc, name)?; + let want = name.trim().to_lowercase(); + let mut list = (*s.doc.eases).clone(); + list.retain(|x| x.name.to_lowercase() != want); + s.doc.eases = Arc::new(list); + Ok(json!({"deleted": name.trim(), "count": s.doc.eases.len()})) +} + +fn rename(s: &mut Session, p: &Value) -> Result { + let name = str_req(p, "name")?; + let to = ease_name(str_req(p, "to")?).ok_or_else(|| EngineError::Param("param 'to' must have something in it".into()))?; + saved_ease(&s.doc, name)?; + let (from, want) = (name.trim().to_lowercase(), to.to_lowercase()); + if from != want && s.doc.eases.iter().any(|x| x.name.to_lowercase() == want) { + return Err(EngineError::State(format!("an ease is already saved as '{to}'"))); + } + let mut list = (*s.doc.eases).clone(); + if let Some(x) = list.iter_mut().find(|x| x.name.to_lowercase() == from) { + x.name = to.clone(); + } + s.doc.eases = Arc::new(list); + Ok(json!({"renamed": name.trim(), "to": to})) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let presets: Vec = Easing::named() + .map(|e| { + let (f, d) = e.family().map_or((None, None), |(f, d)| (Some(f.label()), Some(d.label()))); + json!({"name": e.name(), "label": e.label(), "family": f, "direction": d}) + }) + .chain(std::iter::once(json!({"name": "Classic", "label": "Classic Ease", "easing": {"classic": 0}, "strength": "-100 (in) … 100 (out)"}))) + .collect(); + let saved: Vec = s.doc.eases.iter().map(|x| json!({"name": x.name, "label": x.ease.label(), "kind": kind(&x.ease), "easing": easing_json(&x.ease)})).collect(); + let plugins: Vec = plugin_eases(s).into_iter().map(|(p, c)| json!({"name": c.name, "plugin": p.id(), "plugin_name": p.manifest().name, "ease": c.id, "easing": {"plugin": p.id(), "ease": c.id}})).collect(); + Ok(json!({"presets": presets, "saved": saved, "plugins": plugins})) +} + +/// The eases of every installed ease plug-in, by plug-in id then in declaration order. +pub fn plugin_eases(s: &Session) -> Vec<(Arc, anicraft_plugins::SampledCurve)> { + s.plugins.list().filter(|p| p.manifest().kind == anicraft_plugins::Kind::Ease).flat_map(|p| p.eases().iter().map(|c| (p.clone(), c.clone())).collect::>()).collect() +} + +fn copy(s: &mut Session, p: &Value) -> Result { + let at = ease_target(s, p)?; + let e = read(s, &at)?; + let label = e.label(); + s.ease_clipboard = Some(e); + Ok(json!({"copied": label})) +} + +fn paste(s: &mut Session, p: &Value) -> Result { + let e = s.ease_clipboard.clone().ok_or_else(|| EngineError::State("no ease has been copied (Copy Ease first)".into()))?; + let at = ease_target(s, p)?; + write(s, &at, e) +} diff --git a/crates/engine/src/cmds_envelope.rs b/crates/engine/src/cmds_envelope.rs new file mode 100644 index 00000000..bc71d8b3 --- /dev/null +++ b/crates/engine/src/cmds_envelope.rs @@ -0,0 +1,258 @@ +//! Envelope (ADR 0080): Modify › Transform › Envelope bends the selected shapes and drawing +//! objects by a mesh of handles around them (`anicraft_geom::envelope`, a bicubic Bézier patch). +//! +//! The envelope is open while its shapes are the ones it made: each move bends the shapes as they +//! were when it opened (so moves never compound their approximation), and is one undo step. Like +//! Animate, it is baked: the shapes stay ordinary paths, so there is nothing to delete (no Delete +//! Envelope). Undo and redo go back to the mesh that made the shapes they restore: the session +//! keeps each mesh with the shapes it made, and finds the one whose shapes are on the stage. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId, Shape}; +use anicraft_geom::envelope::{self, Mesh}; +use anicraft_geom::{Affine, Rect, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "modify.envelope", + "Envelope", + "Modify/Transform", + None, + "{} opens an envelope around the selected shapes and drawing objects on the active layer (ADR 0080): a mesh of 4 × 4 Bézier control points over their bounds, at rest → {points: [[x, y] × 16] (row by row from the top-left), bounds: [x, y, w, h], shapes}. Then modify.envelope_move bends them. Symbols, text, groups and bitmaps can't be bent: break them apart first", + false, + open as crate::RunFn, + ), + c( + "modify.envelope_move", + "Envelope", + "", + None, + "{points: [[x, y] × 16] (the whole mesh) | index: 0..15, x, y (one control point; a corner or side handle moves the inner points with it, as a Coons patch), tolerance? (stage units, default 0.05)} bends the open envelope's shapes from where they were when it opened → {points, shapes}. One undo step", + true, + move_points, + ), + c( + "modify.envelope_close", + "Close Envelope", + "", + None, + "{} closes the open envelope: bent raw shapes merge with the drawing they now touch (as after a move). Nothing to close is no error → {closed}", + true, + close, + ), + ] +} + +/// Most meshes remembered for undo and redo. +const MAX_STATES: usize = 256; +/// Most shapes one envelope bends. +const MAX_SHAPES: usize = 10_000; + +/// An open envelope. +#[derive(Clone, Debug)] +pub struct Envelope { + pub layer: LayerId, + /// The rest rectangle (keyframe space) and the shapes as they were when it opened. + pub rest: Rect, + originals: Vec>, + /// Each mesh used, with the shapes it made (the first is the rest mesh and the originals). + states: Vec<(Mesh, Vec>)>, + /// The gesture (by the state it started from) whose move made the last of `states`: a + /// drag's moves are one undo step, so only its last needs remembering. + live: Option, +} + +impl Envelope { + #[cfg(test)] + pub(crate) fn states_len(&self) -> usize { + self.states.len() + } + + /// The mesh that made the shapes now on `els`, if they are still what one of its moves made. + fn current(&self, els: &[Arc]) -> Option { + let now: Vec>> = self.originals.iter().map(|o| els.iter().find(|e| e.id == o.id)).collect(); + self.states + .iter() + .rev() + .find(|(_, made)| made.len() == now.len() && made.iter().zip(&now).all(|(m, n)| n.is_some_and(|n| Arc::ptr_eq(m, n) || **m == **n))) + .map(|(mesh, _)| *mesh) + } +} + +impl Session { + /// The open envelope's layer, rest rectangle and current mesh (keyframe space), while its + /// shapes are selected and still the ones it made (an edit to them, or a new selection, + /// ends it). + pub fn envelope(&self) -> Option<(LayerId, Rect, Mesh)> { + let env = self.envelope.as_ref()?; + if env.layer != self.layer || !env.originals.iter().all(|o| self.selection.contains(env.layer, o.id)) { + return None; + } + let mesh = env.current(&self.elements_on(env.layer))?; + Some((env.layer, env.rest, mesh)) + } +} + +fn mesh_json(m: &Mesh) -> Value { + json!(m.iter().map(|p| [p.x, p.y]).collect::>()) +} + +/// What an envelope can bend: shapes (raw and drawing objects). +fn bendable(e: &Element) -> bool { + matches!(e.kind, ElementKind::Shape(_)) +} + +/// The tight bounds of shapes' outlines in keyframe space. +fn outline_bounds(els: &[Arc]) -> Rect { + let mut r = Rect::EMPTY; + for e in els { + if let ElementKind::Shape(sh) = &e.kind { + for pl in sh.path.flatten(&e.transform, 0.05) { + pl.points.iter().for_each(|p| r.include(*p)); + } + } + } + r +} + +fn open(s: &mut Session, _: &Value) -> Result { + let here = s.layer; + let sel = s.selection.on(here); + let els = s.elements_on(here); + let picked: Vec> = els.iter().filter(|e| sel.contains(&e.id)).cloned().collect(); + if picked.is_empty() { + return Err(EngineError::State("select the shapes or drawing objects to bend with an envelope".into())); + } + if !picked.iter().all(|e| bendable(e)) { + return Err(EngineError::State("an envelope bends shapes and drawing objects only: break symbols, text, groups and bitmaps apart first (Modify › Break Apart)".into())); + } + // A warp (ADR 0079) bends the outline as drawn on every keyframe of its layer: baking an + // envelope into one of them would fight it. + if picked.iter().any(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.warp.is_some())) { + return Err(EngineError::State("an envelope can't bend warped artwork (Asset Warp): remove its warp first (Modify › Asset Warp › Remove Warp)".into())); + } + if picked.len() > MAX_SHAPES { + return Err(EngineError::State(format!("an envelope bends at most {MAX_SHAPES} shapes at once"))); + } + let mut rest = outline_bounds(&picked); + // A straight line has no height (or width): give the mesh some room. + if rest.is_empty() || !rest.min.x.is_finite() { + return Err(EngineError::State("the selection has no outline to bend".into())); + } + let pad = |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), (y0, y1)) = (pad(rest.min.x, rest.max.x), pad(rest.min.y, rest.max.y)); + rest = Rect::new(x0, y0, x1, y1); + let mesh = envelope::rest_mesh(&rest); + s.envelope = Some(Envelope { layer: here, rest, originals: picked.clone(), states: vec![(mesh, picked.clone())], live: None }); + Ok(json!({"points": mesh_json(&mesh), "bounds": [rest.min.x, rest.min.y, rest.width(), rest.height()], "shapes": picked.len()})) +} + +/// The mesh asked for: the whole of it, or the current one with one point moved. +fn asked(p: &Value, current: &Mesh) -> Result { + if let Some(list) = p.get("points") { + let bad = || EngineError::Param("param 'points' must be 16 points [x, y], row by row from the top-left".into()); + let list = list.as_array().filter(|l| l.len() == 16).ok_or_else(bad)?; + let mut m = [Vec2::ZERO; 16]; + for (slot, v) in m.iter_mut().zip(list) { + 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() && f.abs() <= crate::cmds_draw::MAX_EXTENT); + *slot = Vec2::new(n(0).ok_or_else(bad)?, n(1).ok_or_else(bad)?); + } + return Ok(m); + } + let i = opt_u32(p, "index")?.ok_or_else(|| EngineError::Param("give the whole mesh ('points') or one point ('index', 'x', 'y')".into()))? as usize; + if i >= 16 { + return Err(EngineError::Param("param 'index' must be 0 to 15".into())); + } + let to = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if !(to.x.abs() <= crate::cmds_draw::MAX_EXTENT && to.y.abs() <= crate::cmds_draw::MAX_EXTENT) { + return Err(EngineError::Param("the point is too far away".into())); + } + let mut m = *current; + if let Some(slot) = m.get_mut(i) { + *slot = to; + } + // A boundary handle bends the inside with it; an inner point moves alone. + if envelope::BOUNDARY.contains(&i) { + envelope::coons_interior(&mut m); + } + Ok(m) +} + +/// `shape` (placed by `m`) bent in keyframe space, as an element placed at its centre. +fn bent(e: &Element, sh: &Shape, mesh: &Mesh, rest: &Rect, tol: f32) -> Option { + let path = envelope::warp(&sh.path.transformed(&e.transform), mesh, rest, tol)?; + let c = path.bounds().center(); + let to_local = Affine::translate(-c.x, -c.y); + let k = e.transform.mean_scale(); + let shape = Shape { + path: Arc::new(path.transformed(&to_local)), + // Gradients and bitmaps stay where they were on the stage (they don't bend, as in Animate). + fill: sh.fill.as_ref().map(|f| f.transformed(&to_local.mul(&e.transform))), + stroke: sh.stroke.as_ref().map(|st| st.scaled(k)), + ..sh.clone() + }; + Some(Element { id: e.id, name: e.name.clone(), transform: Affine::translate(c.x, c.y), color: e.color, kind: ElementKind::Shape(shape) }) +} + +fn move_points(s: &mut Session, p: &Value) -> Result { + let none = || EngineError::State("no envelope is open: select shapes and choose Modify › Transform › Envelope".into()); + let (_, rest, current) = s.envelope().ok_or_else(none)?; + let mesh = asked(p, ¤t)?; + let tol = match opt_f32(p, "tolerance")? { + None => 0.05, + Some(t) if (0.001..=100.0).contains(&t) => t, + Some(_) => return Err(EngineError::Param("param 'tolerance' must be between 0.001 and 100".into())), + }; + let originals = s.envelope.as_ref().map(|e| e.originals.clone()).unwrap_or_default(); + let made: Vec> = originals + .iter() + .map(|o| match &o.kind { + ElementKind::Shape(sh) => bent(o, sh, &mesh, &rest, tol).map(Arc::new).ok_or_else(|| EngineError::State("the envelope bends those shapes too far to draw; move the handles back a little".into())), + _ => Ok(o.clone()), + }) + .collect::>()?; + let kf = s.editable_keyframe()?; + for m in &made { + if let Some(slot) = kf.elements.iter_mut().find(|e| e.id == m.id) { + *slot = m.clone(); + } + } + let gesture = s.gesture.as_ref().map(|g| g.state); + if let Some(env) = s.envelope.as_mut() { + // Another move of the same drag replaces the one before it. + if gesture.is_some() && env.live == gesture && env.states.len() > 1 { + env.states.pop(); + } + env.live = gesture; + if env.states.len() >= MAX_STATES { + // Keep the rest state; forget the oldest move. + env.states.remove(1); + } + env.states.push((mesh, made.clone())); + } + Ok(json!({"points": mesh_json(&mesh), "shapes": made.len()})) +} + +fn close(s: &mut Session, _: &Value) -> Result { + let Some(env) = s.envelope.take() else { return Ok(json!({"closed": false})) }; + let ids: Vec = env.originals.iter().map(|e| e.id).collect(); + // Bent raw shapes merge where they now lie, as after a move (ADR 0031). + let here = s.elements_on(env.layer); + let raw = here.iter().any(|e| ids.contains(&e.id) && crate::merge::mergeable(e).is_some()); + if raw && env.layer == s.layer { + let keep = s.selection.clone(); + s.selection = crate::Selection::only(env.layer, ids.iter().copied()); + crate::merge::drop_selected(s)?; + // What the merge selected, else what was selected. + if s.selection.is_empty() { + s.selection = keep; + } + } + Ok(json!({"closed": true})) +} diff --git a/crates/engine/src/cmds_erase.rs b/crates/engine/src/cmds_erase.rs index 3f3d22f9..f45bf51d 100644 --- a/crates/engine/src/cmds_erase.rs +++ b/crates/engine/src/cmds_erase.rs @@ -85,11 +85,22 @@ fn erase(s: &mut Session, p: &Value) -> Result { /// Erases `eraser` (keyframe space) from the active layer's raw shapes, as `mode` says. pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: Vec2) -> Result { - let nothing = |why: &str| Ok(json!({"erased": false, "mode": mode.key(), "elements": [], "reason": why})); // Nothing may change when nothing is erased (no keyframe made, no undo step). let before = s.doc.clone(); let els = s.editable_keyframe()?.elements.clone(); let area = eraser.bounds().inflate(2.0 * SNAP); + // What the eraser passes over and keeps (ADR 0093): symbols, and drawing objects, groups and + // text. Each opens for editing in place, where its raw shapes erase. + let kept = kept_under(s, &els, eraser); + let nothing = |why: &str| { + let why = match kept { + (0, 0) => why.to_string(), + (_, 0) => "the eraser keeps symbols on the stage; double-click one with the Selection tool (or select it and use Edit Symbols) to erase inside it".to_string(), + (0, _) => "the eraser keeps drawing objects; double-click one with the Selection tool to erase inside it".to_string(), + _ => "the eraser keeps symbols and drawing objects; double-click one with the Selection tool to erase inside it".to_string(), + }; + Ok(json!({"erased": false, "mode": mode.key(), "elements": [], "reason": why, "kept": {"symbols": kept.0, "objects": kept.1}})) + }; let touching: Vec = (0..els.len()).filter(|&i| els.get(i).and_then(|e| mergeable(e).map(|sh| !reach(sh, &e.transform).intersect(&area).is_empty())).unwrap_or(false)).collect(); let el = |i: &usize| els.get(*i).map(|e| e.as_ref()); let is_fill = |i: &usize| el(i).and_then(mergeable).is_some_and(|sh| sh.fill.is_some()); @@ -142,7 +153,32 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: // What stays selected: the rest of the selection, and what is left of selected shapes. s.selection.retain(|l, id| l != here || !gone.contains(&id)); s.selection.extend_on(here, picked); - Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0)})) + Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0), "kept": {"symbols": kept.0, "objects": kept.1}})) +} + +/// How many symbol instances, and how many other elements that are not raw shapes (drawing +/// objects, groups, text), the eraser's outline reaches on the keyframe: what it keeps. +fn kept_under(s: &Session, els: &[std::sync::Arc], eraser: &Path) -> (usize, usize) { + let area = eraser.bounds(); + let (mut symbols, mut objects) = (0, 0); + for e in els.iter().take(100_000) { + if mergeable(e).is_some() || matches!(e.kind, ElementKind::Camera) { + continue; + } + let b = match &e.kind { + ElementKind::Shape(sh) => reach(sh, &e.transform), + _ => s.element_bounds(e.id), + }; + if b.intersect(&area).is_empty() { + continue; + } + if matches!(e.kind, ElementKind::Symbol { .. }) { + symbols += 1; + } else { + objects += 1; + } + } + (symbols, objects) } /// Total fill area and stroke length of raw shapes, in keyframe space. Fill areas are exact @@ -247,7 +283,7 @@ fn faucet(s: &mut Session, p: &Value) -> Result { let near = sh.path.bounds().transformed(&e.transform).inflate(hw + slop).contains(at); near && ((sh.fill.is_some() && sh.path.contains(at, &e.transform, sh.fill_rule)) || (sh.stroke.is_some() && sh.path.distance_to_edge(at, &e.transform) <= hw + slop)) } - ElementKind::Symbol { .. } | ElementKind::Text(_) => s.element_bounds(e.id).contains(at), + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Group { .. } => s.element_bounds(e.id).contains(at), ElementKind::Camera => false, }); let Some(hit) = hit else { @@ -267,7 +303,7 @@ fn faucet(s: &mut Session, p: &Value) -> Result { /// The layers `draw.erase_all` clears: visible, unlocked layers that hold artwork (not folders, /// not the camera), with the number of elements at the playhead on each. pub(crate) fn erasable_layers(s: &Session) -> Vec<(anicraft_doc::LayerId, usize)> { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); tl.layers .iter() .filter(|l| l.visible && !l.locked && !tl.locked_by_folder(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera)) @@ -283,7 +319,7 @@ fn erase_all(s: &mut Session, _: &Value) -> Result { let (scene, frame) = (s.scene, s.frame); let mut erased = 0; for (id, _) in &layers { - let Some(layer) = s.doc.timeline_mut(scene).layer_mut(*id) else { continue }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).ok().and_then(|tl| tl.layer_mut(*id)) else { continue }; let Some(i) = layer.keyframe_index_at(frame) else { continue }; let Some(kf) = layer.keyframe_mut(i) else { continue }; erased += kf.elements.len(); diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index b119325e..d00a2540 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -10,7 +10,7 @@ use std::path::PathBuf; use std::sync::Arc; pub fn specs() -> Vec { - vec![ + let mut v = vec![ CommandSpec { id: "file.new", label: "New", menu: "File", shortcut: Some("Ctrl+N"), params: "{width?, height?, fps?}", mutates: false, run: new_doc }, CommandSpec { id: "file.new_sample", label: "New from Sample", menu: "File", shortcut: None, params: "{which?: demo (default) | interactive (a menu with a Play button, for Test Movie)}", mutates: false, run: new_sample }, CommandSpec { id: "file.open", label: "Open…", menu: "File", shortcut: Some("Ctrl+O"), params: "{path, unsaved? (opens it as unsaved work: a restored copy), untitled? (with no file name, so Save asks for one)}", mutates: false, run: open }, @@ -33,7 +33,7 @@ pub fn specs() -> Vec { label: "Import to Stage…", menu: "File/Import", shortcut: Some("Ctrl+R"), - params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred)}", + params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead)}", mutates: true, run: import_to_stage, }, @@ -74,6 +74,24 @@ pub fn specs() -> Vec { mutates: false, run: export_gif, }, + CommandSpec { + id: "file.export_apng", + label: "Export Animated PNG…", + menu: "File/Export", + shortcut: None, + params: "{path (.png or .apng), from?, to? (movie frames: every scene in order), scale?, loop? (true (default): forever; false: once; or how many times it plays), background? (default false: transparent), confirm?}", + mutates: false, + run: |s, p| crate::anim::export(s, p, crate::anim::Kind::Apng), + }, + CommandSpec { + id: "file.export_webp", + label: "Export Animated WebP…", + menu: "File/Export", + shortcut: None, + params: "{path (.webp; lossless), from?, to? (movie frames: every scene in order), scale?, loop? (true (default): forever; false: once; or how many times it plays), background? (default false: transparent), confirm?}", + mutates: false, + run: |s, p| crate::anim::export(s, p, crate::anim::Kind::Webp), + }, CommandSpec { id: "file.export_lottie", label: "Export Lottie Animation…", @@ -104,7 +122,19 @@ pub fn specs() -> Vec { run: set_stage, }, CommandSpec { id: "doc.info", label: "Document Info", menu: "", shortcut: None, params: "{}", mutates: false, run: |s, _| Ok(s.info()) }, - ] + ]; + // In the File menu as in Animate: New from Template under New, Save as Template under + // Save As (ADR 0065). + for t in crate::cmds_template::specs() { + let after = match t.id { + "file.new_from_template" => "file.new_sample", + "file.save_as_template" => "file.save_as", + _ => "doc.info", + }; + let at = v.iter().position(|c| c.id == after).map_or(v.len(), |i| i + 1); + v.insert(at, t); + } + v } fn stage_edge(p: &Value, key: &str, default: u32) -> Result { @@ -149,7 +179,7 @@ pub fn is_animate(path: &std::path::Path) -> bool { matches!(ext.as_deref(), Some("fla" | "xfl")) || (crate::vfs::is_dir(path) && crate::vfs::is_file(&path.join("DOMDocument.xml"))) } -fn open(s: &mut Session, p: &Value) -> Result { +pub(crate) fn open(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); let unsaved = opt_bool(p, "unsaved")?.unwrap_or(false); let untitled = opt_bool(p, "untitled")?.unwrap_or(false); @@ -173,6 +203,8 @@ fn open(s: &mut Session, p: &Value) -> Result { // as it was in Animate (ADR 0042). let merged = crate::merge::merge_document(&mut doc); s.replace_document(doc, None); + // Open Recent reopens the Animate file (ADR 0059). + s.recent.add(&path); let mut info = s.info(); info["imported"] = json!(path.display().to_string()); info["report"] = json!(report.summary()); @@ -180,13 +212,17 @@ fn open(s: &mut Session, p: &Value) -> Result { info["kept"] = json!(report.kept); info["runs"] = json!(report.runs); info["missing_fonts"] = json!(report.missing_fonts); + // The sounds and videos that didn't come across, by name and why (ADR 0086). + info["named"] = json!(report.names); info["merged_keyframes"] = json!(merged); return Ok(info); } let doc = format::load(&path)?; - s.replace_document(doc, (!untitled).then_some(path)); + s.replace_document(doc, (!untitled).then(|| path.clone())); if unsaved { s.mark_unsaved(); + } else if !untitled { + s.recent.add(&path); } Ok(s.info()) } @@ -199,10 +235,11 @@ fn save(s: &mut Session, p: &Value) -> Result { format::save(&s.doc, &path)?; s.path = Some(path.clone()); s.mark_saved(); + s.recent.add(&path); Ok(json!({"saved": path.display().to_string()})) } -fn scale_param(p: &Value) -> Result { +pub(crate) fn scale_param(p: &Value) -> Result { match opt_f32(p, "scale")? { None => Ok(1.0), Some(v) if v > 0.0 && v <= 8.0 => Ok(v), @@ -233,7 +270,7 @@ pub(crate) const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024; /// named after the file, in a keyframe at the playhead, selected, as one undo step. A drawing /// with clip paths or masks becomes a folder named after the file, with mask layers over the /// artwork they clip (ADR 0021). Centred on the stage unless `x`/`y` give its top-left corner. -fn import_to_stage(s: &mut Session, p: &Value) -> Result { +pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); if crate::cmds_sound::is_sound(&path) { return crate::cmds_sound::import_to_stage(s, &path); @@ -257,8 +294,20 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary()))); } let stage = s.doc.stage; - let x = opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5); - let y = opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5); + // `cx`/`cy` centre it on a point (a drop, ADR 0059); `x`/`y` give its top-left corner. + let x = match opt_f32(p, "cx")? { + Some(cx) => cx - drawing.width * 0.5, + None => opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5), + }; + let y = match opt_f32(p, "cy")? { + Some(cy) => cy - drawing.height * 0.5, + None => opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5), + }; + let onto_active = match opt_str(p, "layer")? { + None | Some("new") => false, + Some("active") => true, + Some(other) => return Err(EngineError::Param(format!("param 'layer' must be new or active, not '{other}'"))), + }; if !(x.is_finite() && y.is_finite()) { return Err(EngineError::Param("'x' and 'y' must be numbers".into())); } @@ -270,7 +319,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { list.into_iter() .map(|e| { let id = anicraft_doc::ElementId(s.doc.alloc_id()); - Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect { alpha: e.alpha, ..Default::default() }, kind: e.kind }) + Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect::opacity(e.alpha), kind: e.kind }) }) .collect() }; @@ -285,7 +334,13 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { let masks = drawing.layers.iter().filter(|l| l.mask.is_some()).count(); let (width, height, report) = (drawing.width, drawing.height, drawing.report); let mut layers = drawing.layers; - let (layer_id, ids, made, folder) = if layers.len() == 1 && masks == 0 { + let (layer_id, ids, made, folder) = if onto_active && layers.len() == 1 && masks == 0 { + // Onto the active layer's keyframe at the playhead, as a drop on the stage puts it. + let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default()); + let ids: Vec = els.iter().map(|e| e.id).collect(); + s.editable_keyframe()?.elements.extend(els); + (s.layer, ids, 0, None) + } else if layers.len() == 1 && masks == 0 { // One layer, named after the file, as Import to Stage always made. crate::cmds_timeline::new_layer(s, &json!({"name": name}))?; let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default()); @@ -298,7 +353,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { // Clips and masks (ADR 0021): a folder named after the file holding, top first, each // run of artwork, with a mask layer over the runs that are masked. let made = layers.len() + masks + 1; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); if tl.layers.len() + made > 1000 { return Err(EngineError::State(format!("importing {} would make {made} layers; a timeline holds at most 1000", path.display()))); } @@ -331,6 +386,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { let mut ml = new_layer(s, label, anicraft_doc::LayerKind::Mask, Some(fid)); // Mask layers are locked, as Animate keeps them: the mask shows, its edge hides. ml.locked = true; + ml.mask_mode = mask.mode; ml.keyframes = keys(elements(s, mask.elements)); inside = Some(ml.id); stack.push(ml); @@ -343,7 +399,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { cl.keyframes = keys(els); stack.push(cl); } - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; for (k, l) in stack.into_iter().enumerate() { tl.layers.insert((at + k).min(tl.layers.len()), Arc::new(l)); } @@ -369,6 +425,74 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { })) } +/// An SVG drawing read from `path` (size-checked), with at least one shape. +pub(crate) fn read_svg(path: &std::path::Path) -> Result { + if crate::vfs::len(path)? > MAX_IMPORT_BYTES { + return Err(EngineError::Format(format!("{} is too large to import", path.display()))); + } + let drawing = anicraft_svg::import(&crate::vfs::read(path)?).map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?; + if drawing.is_empty() { + return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary()))); + } + Ok(drawing) +} + +/// Whether a drawing fits on one layer (one run of artwork, nothing masked). +pub(crate) fn one_layer(d: &anicraft_svg::SvgImport) -> bool { + d.layers.len() == 1 && d.layers.iter().all(|l| l.mask.is_none()) +} + +/// Import to Library with an SVG (ADR 0065): a graphic symbol named after the file (a free +/// name at the Library's top level) holding the drawing's shapes, its registration point at +/// the drawing's centre. Clips and masks keep their mask layers inside the symbol. +pub(crate) fn import_svg_symbol(s: &mut Session, path: &std::path::Path, name: Option<&str>) -> Result { + use anicraft_doc::{Layer, LayerId, LayerKind, Symbol, SymbolId, SymbolKind, Timeline}; + let drawing = read_svg(path)?; + let stem: String = path.file_stem().map_or_else(|| "Drawing".into(), |n| n.to_string_lossy().chars().take(128).collect()); + let name = s.doc.unique_name(None, name.map_or(stem.as_str(), str::trim)); + let place = anicraft_geom::Affine::translate(-drawing.width * 0.5, -drawing.height * 0.5); + let elements = |s: &mut Session, list: Vec| -> Vec> { + list.into_iter() + .map(|e| Arc::new(anicraft_doc::Element { id: anicraft_doc::ElementId(s.doc.alloc_id()), name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect::opacity(e.alpha), kind: e.kind })) + .collect() + }; + let one_key = |els: Vec>| { + let mut k = anicraft_doc::Keyframe::new(0, 1); + k.elements = els; + vec![Arc::new(k)] + }; + let count = drawing.elements().count(); + let (width, height, report) = (drawing.width, drawing.height, drawing.report); + let runs = drawing.layers.len(); + // Top first: the drawing lists its runs in paint order (bottom first). + let mut layers: Vec> = Vec::new(); + for (n, l) in drawing.layers.into_iter().enumerate().rev() { + let mut parent = None; + if let Some(mask) = l.mask { + let mut ml = Layer::new(LayerId(s.doc.alloc_id()), if mask.name.is_empty() { "Mask".to_string() } else { mask.name.clone() }); + ml.kind = LayerKind::Mask; + ml.locked = true; + ml.mask_mode = mask.mode; + ml.keyframes = one_key(elements(s, mask.elements)); + parent = Some(ml.id); + layers.push(Arc::new(ml)); + } + let mut cl = Layer::new(LayerId(s.doc.alloc_id()), if runs == 1 { "Layer 1".to_string() } else { format!("Layer {}", n + 1) }); + cl.parent = parent; + cl.keyframes = one_key(elements(s, l.elements)); + layers.push(Arc::new(cl)); + } + let mut timeline = Timeline { layers }; + timeline.repair_masks(); + let id = SymbolId(s.doc.alloc_id()); + s.doc.library.push(Arc::new(Symbol { id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, scale_grid_kept: None, timeline })); + Ok(json!({"symbol": id.0, "name": name, "elements": count, "layers": timeline_len(s, id), "width": width, "height": height, "report": report.summary(), "skipped": report.skipped})) +} + +fn timeline_len(s: &Session, id: anicraft_doc::SymbolId) -> usize { + s.doc.library.iter().find(|x| x.id == id).map_or(0, |x| x.timeline.layers.len()) +} + /// A PNG or JPEG as a bitmap in the document, and the one shape that shows it: a rectangle of /// the image's size filled with it. JPEGs are kept as PNG (lossless, so nothing degrades). fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec) -> Result { @@ -383,6 +507,7 @@ fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec) -> Resu stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, + warp: None, }; Ok(anicraft_svg::SvgImport::single(w, h, vec![anicraft_svg::ImportedElement { name, transform: anicraft_geom::Affine::IDENTITY, alpha: 1.0, kind: anicraft_doc::ElementKind::Shape(shape) }])) } @@ -439,7 +564,16 @@ fn export_sprite_sheet(s: &mut Session, p: &Value) -> Result { } // Frames render in parallel, then go onto the sheet in order. let doc = &s.doc; - let frames: Vec = (from..=to).into_par_iter().map(|f| render(&anicraft_doc::evaluate(doc, f), &view).map(|(pm, _)| pm)).collect::>()?; + // A publish counts the frames, and stops between them when cancelled (ADR 0060). + let job = s.job.as_deref(); + let frames: Vec = (from..=to) + .into_par_iter() + .map(|f| { + let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + crate::publish::tick(job, 1)?; + Ok(pm) + }) + .collect::>()?; let mut sheet = anicraft_render::Pixmap::new(sheet_w as u32, sheet_h as u32)?; let stride = sheet_w as usize; let delays = gif_delays(n, doc.stage.fps); @@ -567,6 +701,7 @@ fn export_video(s: &mut Session, p: &Value) -> Result { text }); let doc = &s.doc; + let job = s.job.as_deref(); let mut written = 0u32; let mut failure: Option = None; if let Some(mut stdin) = child.stdin.take() { @@ -585,11 +720,22 @@ fn export_video(s: &mut Session, p: &Value) -> Result { } written += 1; } + if let Err(e) = crate::publish::tick(job, batch.len() as u64) { + failure = Some(e); + break; + } } } + if matches!(failure, Some(EngineError::Cancelled)) { + // Cancelled while publishing: ffmpeg stops, and its unfinished file goes. + let _ = child.kill(); + } let status = child.wait()?; let log = messages.join().unwrap_or_default(); if let Some(e) = failure { + if matches!(e, EngineError::Cancelled) { + let _ = crate::vfs::remove_file(&path); + } return Err(e); } if !status.success() || written != to - from + 1 { @@ -616,6 +762,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { // Output is identical to a serial export. Files are written here, on the command's thread, // where `vfs` knows whether they go to disk or to the browser (ADR 0036). let doc = &s.doc; + let job = s.job.as_deref(); let mut files = 0usize; let frames: Vec = (from..=to).collect(); for batch in frames.chunks(64) { @@ -624,6 +771,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { crate::vfs::write(&dir.join(format!("frame_{:05}.png", f + 1)), png)?; files += 1; } + crate::publish::tick(job, batch.len() as u64)?; } Ok(json!({"frames": files, "dir": dir.display().to_string()})) } @@ -644,7 +792,8 @@ pub fn gif_delays(frames: usize, fps: f32) -> Vec { .collect() } -/// The movie as a Lottie (JSON) animation, frame-accurate (see `anicraft_render::lottie`). +/// The movie as a Lottie (JSON) animation, keyed with eases and equal to `evaluate` at every +/// frame (see `anicraft_render::lottie`, ADR 0089). fn export_lottie(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); let last = s.doc.frame_count().saturating_sub(1); @@ -723,26 +872,27 @@ fn export_gif(s: &mut Session, p: &Value) -> Result { } // Render and colour-quantize frames in parallel; encode in order. let doc = &s.doc; + let job = s.job.as_deref(); let delays = gif_delays(n as usize, doc.stage.fps); - let frames: Vec> = (from..to.saturating_add(1)) + let frames: Vec<(craft_gif::write::PreparedFrame, u16)> = (from..to.saturating_add(1)) .into_par_iter() .zip(delays.into_par_iter()) .map(|(f, delay)| { let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; - let mut rgba = pm.to_rgba8(); - let mut frame = gif::Frame::from_rgba_speed(w, h, &mut rgba, 10); - frame.delay = delay; - Ok(frame) + let rgba = pm.to_rgba8(); + let frame = craft_gif::write::prepare_frame(u32::from(w), u32::from(h), rgba, 10) + .map_err(|e| EngineError::Format(e.to_string()))?; + crate::publish::tick(job, 1)?; + Ok((frame, delay)) }) .collect::>>()?; let mut bytes = Vec::new(); { - let mut enc = gif::Encoder::new(&mut bytes, w, h, &[]).map_err(|e| EngineError::Format(e.to_string()))?; - if looping { - enc.set_repeat(gif::Repeat::Infinite).map_err(|e| EngineError::Format(e.to_string()))?; - } - for fr in &frames { - enc.write_frame(fr).map_err(|e| EngineError::Format(e.to_string()))?; + let opts = craft_gif::write::Options { loop_forever: looping, ..Default::default() }; + let mut enc = craft_gif::write::AnimationWriter::new(&mut bytes, u32::from(w), u32::from(h), opts) + .map_err(|e| EngineError::Format(e.to_string()))?; + for (fr, delay) in frames { + enc.write_prepared_frame(fr, delay).map_err(|e| EngineError::Format(e.to_string()))?; } } crate::vfs::write(&path, &bytes)?; diff --git a/crates/engine/src/cmds_filter.rs b/crates/engine/src/cmds_filter.rs new file mode 100644 index 00000000..0bb56e35 --- /dev/null +++ b/crates/engine/src/cmds_filter.rs @@ -0,0 +1,296 @@ +//! The filter list of movie clip and button instances (ADR 0025, 0091): replacing it +//! (`element.set_filters`), reordering, switching filters on and off, removing them, copying +//! and pasting them between instances, and the user's filter presets. +//! +//! Every edit acts on each selected movie clip and button instance (graphics take no filters, +//! as in Animate) and is one undo step. A filter at an index acts where an instance has one; +//! the command fails only when it acts nowhere. Copied filters and presets live in the session, +//! outside the document and its undo history. + +use crate::filter_library::{FilterLibrary, MAX_FILE_BYTES, MAX_FILTERS, MAX_PRESETS}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ElementKind, FilterEntry, SymbolId, SymbolKind}; +use serde_json::{Value, json}; + +pub fn specs() -> Vec { + let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run }; + vec![ + c("filter.move", "Move Filter", "{from, to} moves the filter at index `from` (0 is the first, applied first) to index `to` in the selected movie clip and button instances' lists; the order changes how they draw", true, (|s, p| s.each_layer(false, |s| move_filter(s, p))) as crate::RunFn), + c("filter.enable", "Enable Filter", "{enabled: bool, index? (default: every filter)} switches a filter on or off; a filter switched off keeps its settings and draws nothing", true, |s, p| s.each_layer(false, |s| enable(s, p))), + c("filter.remove", "Remove Filter", "{index? (default: every filter)} removes a filter from the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| remove(s, p))), + c("filter.copy", "Copy Filters", "{index? (default: every filter)} copies the selected instance's filters (one, or all), for Paste Filters", false, copy), + c("filter.paste", "Paste Filters", "{replace? (default false: added after the instances' own)} pastes the copied filters onto the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| paste(s, p))), + c("filter.preset_list", "Filter Presets", "{} your filter presets, each a name and its filters", false, preset_list), + c("filter.preset_save", "Save Filter Preset", "{name, filters? (a list as element.set_filters takes; default: the selected instance's)} saves a filter preset of your own (kept in your preferences; a name you have already is replaced, after asking)", false, preset_save), + c("filter.preset_apply", "Apply Filter Preset", "{name} gives the selected movie clip and button instances the preset's filters, replacing theirs (as Animate does)", true, |s, p| s.each_layer(false, |s| preset_apply(s, p))), + c("filter.preset_rename", "Rename Filter Preset", "{name, to}", false, preset_rename), + c("filter.preset_delete", "Delete Filter Preset", "{name} deletes a filter preset (asks first: it can't be undone; artwork that used it keeps its filters)", false, preset_delete), + c("filter.preset_export", "Export Filter Presets", "{path, names? (default: all)} writes your filter presets to a small JSON file", false, preset_export), + c("filter.preset_import", "Import Filter Presets", "{path} adds the presets in a filter preset file to yours (a name you have already gets a number)", false, preset_import), + ] +} + +/// A filter list from command params (`element.set_filters`, `filter.preset_save`): colours may +/// be "#rrggbb" or "#rrggbbaa", values are brought into range, at most [`MAX_FILTERS`]. +pub(crate) fn parse_list(list: Option<&Value>) -> Result> { + let mut list = list.cloned().ok_or_else(|| EngineError::Param("param 'filters' is required (a list; [] removes them)".into()))?; + fn hex_colors(v: &mut Value, keys: &[&str]) -> Result<()> { + for k in keys { + if v.get(*k).is_some_and(Value::is_string) { + let c = opt_color(v, k)?.unwrap_or(anicraft_doc::Rgba::BLACK); + v[*k] = json!({"r": c.r, "g": c.g, "b": c.b, "a": c.a}); + } + } + Ok(()) + } + if list.as_array().is_some_and(|a| a.len() > MAX_FILTERS) { + return Err(EngineError::Param(format!("at most {MAX_FILTERS} filters per instance"))); + } + for f in list.as_array_mut().into_iter().flatten() { + hex_colors(f, &["color", "shadow_color", "highlight_color"])?; + if let Some(stops) = f.get_mut("stops").and_then(Value::as_array_mut) { + if stops.len() > anicraft_doc::MAX_RAMP_STOPS { + return Err(EngineError::Param(format!("a ramp has at most {} stops", anicraft_doc::MAX_RAMP_STOPS))); + } + for st in stops.iter_mut() { + hex_colors(st, &["color"])?; + } + } + } + let filters: Vec = serde_json::from_value(list).map_err(|e| EngineError::Param(format!("'filters' must be a list of {{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values, enabled?: bool}}: {e}")))?; + Ok(filters.iter().map(FilterEntry::sanitized).collect()) +} + +/// Runs `edit` on the filter list of each selected movie clip and button instance; `edit` +/// says whether it changed that list. Fails when no instance takes filters, or none changed +/// (`nothing` says why). +fn edit_lists(s: &mut Session, nothing: &str, mut edit: impl FnMut(&mut Vec) -> bool) -> Result { + let kinds: std::collections::HashMap = s.doc.library.iter().map(|x| (x.id, x.kind)).collect(); + let (mut set, mut clips, mut graphics) = (0, 0, 0); + for e in s.selected_props_mut()? { + if let ElementKind::Symbol { symbol, filters, .. } = &mut e.kind { + if kinds.get(symbol) == Some(&SymbolKind::Graphic) { + graphics += 1; + continue; + } + clips += 1; + if edit(filters) { + set += 1; + } + } + } + if clips == 0 { + return Err(EngineError::State(if graphics > 0 { + "filters apply to movie clip and button instances; set the symbol's Type to Movie Clip first".into() + } else { + "select a movie clip or button instance".into() + })); + } + if set == 0 { + return Err(EngineError::State(nothing.into())); + } + Ok(set) +} + +/// Filters for the selected movie clip and button instances (Animate offers them on those only). +pub(crate) fn set_filters(s: &mut Session, p: &Value) -> Result { + let filters = parse_list(p.get("filters"))?; + let set = edit_lists(s, "", |f| { + f.clone_from(&filters); + true + })?; + Ok(json!({"filters": filters.len(), "set": set})) +} + +fn index(p: &Value, key: &str) -> Result> { + Ok(opt_u32(p, key)?.map(|i| i as usize)) +} + +fn index_req(p: &Value, key: &str) -> Result { + index(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required (a filter's index, 0 is the first)"))) +} + +fn no_filter(i: usize) -> String { + format!("the selection has no filter {} (0 is the first)", i) +} + +fn move_filter(s: &mut Session, p: &Value) -> Result { + let (from, to) = (index_req(p, "from")?, index_req(p, "to")?); + let set = edit_lists(s, &no_filter(from), |f| { + if from >= f.len() { + return false; + } + let to = to.min(f.len() - 1); + if from == to { + return true; + } + let x = f.remove(from); + f.insert(to, x); + true + })?; + Ok(json!({"moved": set})) +} + +fn enable(s: &mut Session, p: &Value) -> Result { + let on = opt_bool(p, "enabled")?.ok_or_else(|| EngineError::Param("param 'enabled' is required (true or false)".into()))?; + let at = index(p, "index")?; + let nothing = at.map_or_else(|| "the selection has no filters".to_string(), no_filter); + let set = edit_lists(s, ¬hing, |f| match at { + Some(i) => f.get_mut(i).map(|e| e.enabled = on).is_some(), + None => { + f.iter_mut().for_each(|e| e.enabled = on); + !f.is_empty() + } + })?; + Ok(json!({"enabled": on, "set": set})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let at = index(p, "index")?; + let nothing = at.map_or_else(|| "the selection has no filters".to_string(), no_filter); + let set = edit_lists(s, ¬hing, |f| match at { + Some(i) if i < f.len() => { + f.remove(i); + true + } + Some(_) => false, + None => { + let any = !f.is_empty(); + f.clear(); + any + } + })?; + Ok(json!({"removed": set})) +} + +/// The filters of the first selected movie clip or button instance, as it shows now. +fn selected_list(s: &Session) -> Result> { + let kinds: std::collections::HashMap = s.doc.library.iter().map(|x| (x.id, x.kind)).collect(); + s.selected_elements() + .into_iter() + .find_map(|(_, e)| match &e.kind { + ElementKind::Symbol { symbol, filters, .. } if kinds.get(symbol).is_some_and(|k| *k != SymbolKind::Graphic) => Some(filters.clone()), + _ => None, + }) + .ok_or_else(|| EngineError::State("select a movie clip or button instance".into())) +} + +fn copy(s: &mut Session, p: &Value) -> Result { + let list = selected_list(s)?; + let chosen = match index(p, "index")? { + Some(i) => vec![list.get(i).cloned().ok_or_else(|| EngineError::Param(no_filter(i)))?], + None if list.is_empty() => return Err(EngineError::State("the instance has no filters to copy".into())), + None => list, + }; + let n = chosen.len(); + s.filter_clipboard = Some(chosen); + Ok(json!({"copied": n})) +} + +/// `add` after each list (or in place of it with `replace`), refused past [`MAX_FILTERS`]. +fn put(s: &mut Session, add: &[FilterEntry], replace: bool) -> Result { + let mut full = false; + let set = edit_lists(s, "", |f| { + if replace { + *f = add.to_vec(); + return true; + } + if f.len() + add.len() > MAX_FILTERS { + full = true; + return false; + } + f.extend(add.iter().cloned()); + true + }); + match set { + Err(_) if full => Err(EngineError::State(format!("an instance has at most {MAX_FILTERS} filters; remove some first"))), + other => other, + } +} + +fn paste(s: &mut Session, p: &Value) -> Result { + let add = s.filter_clipboard.clone().ok_or_else(|| EngineError::State("no filters are copied yet (Copy Filters first)".into()))?; + let replace = opt_bool(p, "replace")?.unwrap_or(false); + let set = put(s, &add, replace)?; + Ok(json!({"pasted": add.len(), "set": set})) +} + +fn preset_json(p: &crate::filter_library::FilterPreset) -> Value { + json!({"name": p.name, "filters": p.filters}) +} + +fn preset_list(s: &mut Session, _: &Value) -> Result { + Ok(json!({"presets": s.filter_presets.presets().iter().map(preset_json).collect::>()})) +} + +fn preset_save(s: &mut Session, p: &Value) -> Result { + let name = str_req(p, "name")?; + let filters = match p.get("filters") { + None | Some(Value::Null) => selected_list(s)?, + list => parse_list(list)?, + }; + let (name, replaced) = s.filter_presets.save(name, &filters)?; + Ok(json!({"name": name, "replaced": replaced, "filters": filters.len(), "presets": s.filter_presets.presets().len()})) +} + +fn preset_apply(s: &mut Session, p: &Value) -> Result { + let name = str_req(p, "name")?; + let preset = s.filter_presets.find(name).cloned().ok_or_else(|| EngineError::Param(format!("you have no filter preset named '{}'", name.chars().take(64).collect::())))?; + let set = put(s, &preset.filters, true)?; + Ok(json!({"name": preset.name, "filters": preset.filters.len(), "set": set})) +} + +fn preset_rename(s: &mut Session, p: &Value) -> Result { + let to = s.filter_presets.rename(str_req(p, "name")?, str_req(p, "to")?)?; + Ok(json!({"name": to})) +} + +fn preset_delete(s: &mut Session, p: &Value) -> Result { + let gone = s.filter_presets.delete(str_req(p, "name")?)?; + Ok(json!({"deleted": gone.name, "presets": s.filter_presets.presets().len()})) +} + +fn preset_export(s: &mut Session, p: &Value) -> Result { + let path = std::path::PathBuf::from(str_req(p, "path")?); + let bad = || EngineError::Param("param 'names' must be a list of filter preset names".into()); + let chosen: Vec<_> = match p.get("names") { + None | Some(Value::Null) => s.filter_presets.presets().to_vec(), + Some(Value::Array(names)) => names + .iter() + .take(MAX_PRESETS * 2) + .map(|n| { + let n = n.as_str().ok_or_else(bad)?; + s.filter_presets.find(n).cloned().ok_or_else(|| EngineError::Param(format!("you have no filter preset named '{}'", n.chars().take(64).collect::()))) + }) + .collect::>()?, + Some(_) => return Err(bad()), + }; + if chosen.is_empty() { + return Err(EngineError::State("there are no filter presets to export yet (save one first)".into())); + } + let text = FilterLibrary::file_json(&chosen); + crate::vfs::write(&path, text.as_bytes())?; + Ok(json!({"written": path.display().to_string(), "presets": chosen.len(), "bytes": text.len()})) +} + +fn preset_import(s: &mut Session, p: &Value) -> Result { + 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 filter preset file", path.display()))); + } + let found = FilterLibrary::parse_file(&crate::vfs::read_to_string(&path)?)?; + if found.is_empty() { + return Err(EngineError::Param("the file has no filter presets in it".into())); + } + let mut names = Vec::with_capacity(found.len()); + for f in found { + match s.filter_presets.add_unique(f) { + 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, "presets": s.filter_presets.presets().len()})) +} diff --git a/crates/engine/src/cmds_frames.rs b/crates/engine/src/cmds_frames.rs index ac52fa73..8cbc4183 100644 --- a/crates/engine/src/cmds_frames.rs +++ b/crates/engine/src/cmds_frames.rs @@ -1,7 +1,7 @@ //! Copy, cut and paste frames (Edit › Timeline). //! //! Design notes (principal engineer / senior designer review): -//! * Frames have their own clipboard, separate from copied artwork, as in Animate: copying +//! * Frames have their own clipboard, separate from copied artwork: copying //! frames never replaces copied shapes, and the reverse. //! * A copy is cut exactly at the selection edges by splitting a scratch copy of the layer with //! the same keyframe logic as F6, so a span that starts before the selection, or is @@ -83,11 +83,11 @@ fn copy_frames(s: &mut Session, p: &Value) -> Result { let count = count_param(p)?; let mut ids = target_layers(s, p)?; // Top to bottom, whatever order the params gave. - let order: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let order: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); ids.sort_by_key(|id| order.iter().position(|o| o == id)); let mut layers = Vec::with_capacity(ids.len()); for id in ids { - let l = s.doc.timeline(s.scene).layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let l = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; layers.push(FrameSlice { name: l.name.clone(), keys: slice(l, frame, count)? }); } let clip = FrameClipboard { layers, count, symbols: Vec::new(), sounds: Vec::new() }; @@ -123,7 +123,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { if frame.saturating_add(clip.count) > MAX_FRAME || s.frame_count().saturating_add(clip.count) > MAX_FRAME { return Err(EngineError::State("the timeline would grow past its maximum length".into())); } - let mut row = s.doc.timeline(s.scene).layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?; + let mut row = s.timeline().layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?; import_symbols(s, &clip.symbols); for x in &clip.sounds { if s.doc.sound(x.id).is_none() { @@ -135,8 +135,8 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { let mut pasted = Vec::new(); for sl in &clip.layers { // Missing layers below are created, named after the copied ones. - if s.doc.timeline(s.scene).layers.get(row).is_none() { - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.get(row).is_none() { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let id = LayerId(s.doc.alloc_id()); @@ -145,7 +145,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { // The pasted keys are its frames (no stray blank frame at 1). l.keyframes.clear(); } - s.doc.timeline_mut(s.scene).layers.push(Arc::new(l)); + crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?.layers.push(Arc::new(l)); } let mut keys = Vec::with_capacity(sl.keys.len()); for k in &sl.keys { @@ -161,7 +161,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { } keys.push(Arc::new(k)); } - let Some(layer) = s.doc.timeline_mut(s.scene).layers.get_mut(row).map(Arc::make_mut) else { continue }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).ok().and_then(|tl| tl.layers.get_mut(row).map(Arc::make_mut)) else { continue }; crate::cmds_camera::keys_fit(layer.kind, keys.iter().map(|k| &**k))?; if layer.keyframe_index_at(frame).is_some() { insert_keyframe_at(layer, frame, true)?; diff --git a/crates/engine/src/cmds_group.rs b/crates/engine/src/cmds_group.rs new file mode 100644 index 00000000..a77f893d --- /dev/null +++ b/crates/engine/src/cmds_group.rs @@ -0,0 +1,375 @@ +//! Groups and Combine Objects (ADR 0073): Modify › Group (Ctrl+G) and Ungroup (Ctrl+Shift+G), and +//! Modify › Combine Objects › Union, Intersect, Punch and Crop on drawing objects. +//! +//! A group is an element holding other elements without a Library symbol +//! ([`ElementKind::Group`]): its transform and colour effect apply to its members, raw shapes +//! inside merge only with each other, and double-clicking it opens it in place like a symbol +//! (`symbol.edit`, ADR 0045). Combine Objects is exact boolean geometry on the planar map of merge +//! drawing (`anicraft_geom::planar`, ADR 0031). + +use crate::merge::{Part, remerge_with}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, LayerId, MAX_GROUP_DEPTH, Shape}; +use anicraft_geom::planar::{self, Item}; +use anicraft_geom::{Affine, FillRule, Path}; +use serde_json::{Value, json}; +use std::collections::HashSet; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "modify.group", + "Group", + "Modify", + Some("Ctrl+G"), + "{} puts the selected elements on each layer into one group there (ADR 0073), where the topmost of them was, and selects it → {group, members} (one layer) or {layers: [..]}. Members keep their places exactly: the group's transform starts as the identity. Raw shapes inside merge only with each other; double-click the group (symbol.edit) to edit it in place", + true, + (|s, p| s.each_layer(true, |s| group(s, p))) as crate::RunFn, + ), + c( + "modify.ungroup", + "Ungroup", + "Modify", + Some("Ctrl+Shift+G"), + "{} puts each selected group's members back on its layer where it was, each placed and coloured as the group showed it, and selects them; raw shapes among them merge with the drawing there → {members}", + true, + |s, p| s.each_layer(true, |s| ungroup(s, p)), + ), + c( + "modify.combine", + "Combine Objects", + "", + None, + "{op: union|intersect|punch|crop} combines the selected shapes on the active layer, bottom to top as they are stacked (ADR 0073). union: one drawing object of everything (a group of the merged pieces when they have more than one colour or keep lines); intersect: the area every one covers, in the topmost's fill and stroke; punch: the topmost's area cut out of each of the others; crop: each of the others cut to the topmost's area. Punch and crop remove the topmost. A result of one fill (or one line) is a drawing object, one of several is a group of raw shapes → {op, created}", + true, + combine_cmd, + ), + c("modify.union", "Union", "Modify/Combine Objects", None, "{} combine with op union", true, |s, _| combine(s, Op::Union)), + c("modify.intersect", "Intersect", "Modify/Combine Objects", None, "{} combine with op intersect", true, |s, _| combine(s, Op::Intersect)), + c("modify.punch", "Punch", "Modify/Combine Objects", None, "{} combine with op punch", true, |s, _| combine(s, Op::Punch)), + c("modify.crop", "Crop", "Modify/Combine Objects", None, "{} combine with op crop", true, |s, _| combine(s, Op::Crop)), + ] +} + +// ----- Group and Ungroup ---------------------------------------------------------------------- + +/// How deep groups nest inside `e` (0 for anything that is not a group). +pub(crate) fn group_depth(e: &Element) -> usize { + fn depth(e: &Element, at: usize) -> usize { + if at > MAX_GROUP_DEPTH { + return at; + } + match &e.kind { + ElementKind::Group { .. } => 1 + e.kind.group_members().iter().map(|m| depth(m, at + 1)).max().unwrap_or(0), + _ => 0, + } + } + depth(e, 0) +} + +/// How many groups are open around the timeline being edited (inside the innermost open symbol). +pub(crate) fn open_groups(s: &Session) -> usize { + s.editing.iter().rev().take_while(|l| l.open.is_group()).count() +} + +fn group(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.on(s.layer); + if sel.is_empty() { + return Err(EngineError::State("select what to group".into())); + } + let layer_id = LayerId(s.doc.alloc_id()); + let id = ElementId(s.doc.alloc_id()); + let around = open_groups(s); + let kf = s.editable_keyframe()?; + let picked: Vec> = kf.elements.iter().filter(|e| sel.contains(&e.id)).cloned().collect(); + if picked.is_empty() { + return Err(EngineError::State("the selection is not on this keyframe".into())); + } + if picked.iter().any(|e| matches!(e.kind, ElementKind::Camera)) { + return Err(EngineError::State("the camera can't be grouped".into())); + } + let deepest = picked.iter().map(|e| group_depth(e)).max().unwrap_or(0); + if around + deepest + 1 > MAX_GROUP_DEPTH { + return Err(EngineError::State(format!("groups nest at most {MAX_GROUP_DEPTH} deep"))); + } + // Where the topmost member was, among what stays. + let top = kf.elements.iter().rposition(|e| sel.contains(&e.id)).unwrap_or(0); + let below = kf.elements.iter().take(top).filter(|e| !sel.contains(&e.id)).count(); + kf.elements.retain(|e| !sel.contains(&e.id)); + let n = picked.len(); + let g = Element { id, name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::group(layer_id, picked) }; + let at = below.min(kf.elements.len()); + kf.elements.insert(at, Arc::new(g)); + s.select_only([id]); + Ok(json!({"group": id.0, "members": n})) +} + +fn ungroup(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.on(s.layer); + let kf = s.editable_keyframe()?; + if !kf.elements.iter().any(|e| sel.contains(&e.id) && matches!(e.kind, ElementKind::Group { .. })) { + return Err(EngineError::State("select a group to ungroup".into())); + } + let taken: HashSet = kf.elements.iter().filter(|e| !(sel.contains(&e.id) && matches!(e.kind, ElementKind::Group { .. }))).map(|e| e.id).collect(); + let old = std::mem::take(&mut kf.elements); + let mut out = Vec::with_capacity(old.len()); + let mut members: Vec<(ElementId, bool)> = Vec::new(); + let mut clash: Vec = Vec::new(); + let mut seen = taken; + for e in old { + if !(sel.contains(&e.id) && matches!(e.kind, ElementKind::Group { .. })) { + out.push(e); + continue; + } + for m in e.kind.group_members() { + let mut m = Arc::unwrap_or_clone(m); + m.transform = e.transform.mul(&m.transform); + m.color = e.color.nested(&m.color); + // Members keep their ids, unless a copy of this group was ungrouped here already. + if !seen.insert(m.id) { + clash.push(out.len()); + } + members.push((m.id, crate::merge::mergeable(&m).is_some())); + out.push(Arc::new(m)); + } + } + for i in clash { + let fresh = ElementId(s.doc.alloc_id()); + if let Some(e) = out.get_mut(i) { + let old = e.id; + Arc::make_mut(e).id = fresh; + // (The member list follows: the first entry still named the old id is this one.) + if let Some(m) = members.iter_mut().rev().find(|m| m.0 == old) { + m.0 = fresh; + } + } + } + s.editable_keyframe()?.elements = out; + // Raw shapes merge with the drawing they now stand in (Animate: what was grouped cuts and joins + // the shapes under it once it is apart), on top, as a dropped selection does. + let raw: Vec = members.iter().filter(|m| m.1).map(|m| m.0).collect(); + let mut selected: Vec = members.iter().filter(|m| !m.1).map(|m| m.0).collect(); + if !raw.is_empty() { + let kf = s.editable_keyframe()?; + let mut moving = Vec::new(); + kf.elements.retain(|e| { + let take = raw.contains(&e.id); + if take { + moving.push((**e).clone()); + } + !take + }); + selected.extend(crate::merge::merge_in(s, moving)?); + } + let n = selected.len(); + s.select_only(selected); + Ok(json!({"members": n})) +} + +// ----- Combine Objects ------------------------------------------------------------------------ + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Op { + Union, + Intersect, + Punch, + Crop, +} + +fn combine_cmd(s: &mut Session, p: &Value) -> Result { + let op = match str_req(p, "op")?.trim().to_ascii_lowercase().as_str() { + "union" => Op::Union, + "intersect" => Op::Intersect, + "punch" => Op::Punch, + "crop" => Op::Crop, + other => return Err(EngineError::Param(format!("unknown op '{other}' (union, intersect, punch or crop)"))), + }; + combine(s, op) +} + +/// `e`'s shape, as a raw shape in keyframe space would merge it. +fn as_raw(e: &Element, sh: &Shape) -> Element { + let mut raw = e.clone(); + let mut sh = sh.clone(); + sh.merge = true; + raw.kind = ElementKind::Shape(sh); + raw +} + +/// `paths` one after another, as one path. +fn joined<'a>(paths: impl IntoIterator) -> Path { + let mut out = Path::default(); + for p in paths { + out.cmds.extend(p.cmds.iter().copied()); + } + out +} + +/// The area `path` (keyframe space) fills with `rule`, as outlines that don't overlap, so even-odd +/// and non-zero agree on it: open subpaths closed, overlaps resolved. `None` when it is too large +/// to merge, empty when it covers nothing. +fn area(path: &Path, rule: FillRule) -> Option { + let m = planar::merge(&[Item { path, fill: Some(0), fill_rule: rule, stroke: None }])?; + Some(joined(m.fills.iter().map(|p| &p.path))) +} + +/// A drawing object of `path` (keyframe space), its local origin at the centre of its bounds as the +/// drawing tools place shapes. +fn object(doc: &mut anicraft_doc::Document, path: &Path, fill: Option, stroke: Option, color: ColorEffect) -> Element { + let c = path.bounds().center(); + let to_local = Affine::translate(-c.x, -c.y); + Element { + id: ElementId(doc.alloc_id()), + name: String::new(), + transform: Affine::translate(c.x, c.y), + color, + kind: ElementKind::Shape(Shape { path: Arc::new(path.transformed(&to_local)), fill: fill.map(|f| f.transformed(&to_local)), stroke, fill_rule: FillRule::NonZero, merge: false, warp: None }), + } +} + +/// Raw pieces (from a merge) as one result: a lone piece becomes a drawing object, several a group +/// of the raw pieces (they keep merging with each other inside it). `None` for no pieces. +fn result_of(s: &mut Session, pieces: Vec>) -> Option { + match pieces.len() { + 0 => None, + 1 => pieces.into_iter().next().map(|p| { + let mut e = Arc::unwrap_or_clone(p); + if let ElementKind::Shape(sh) = &mut e.kind { + sh.merge = false; + } + e + }), + _ => { + // Fills of one look, with no line left, are one object. + let first = pieces.first().and_then(|p| match &p.kind { + ElementKind::Shape(sh) if sh.stroke.is_none() => sh.fill.clone().map(|f| (f.transformed(&p.transform), p.color)), + _ => None, + }); + let same = first.as_ref().is_some_and(|(f0, c0)| { + pieces.iter().all(|p| matches!(&p.kind, ElementKind::Shape(sh) if sh.stroke.is_none() && p.color == *c0 && sh.fill.as_ref().is_some_and(|f| crate::merge::same_paint(&f.transformed(&p.transform), f0)))) + }); + if let (true, Some((fill, color))) = (same, first) { + let outline: Vec = pieces.iter().filter_map(|p| match &p.kind { + ElementKind::Shape(sh) => Some(sh.path.transformed(&p.transform)), + _ => None, + }).collect(); + return Some(object(&mut s.doc, &joined(outline.iter()), Some(fill), None, color)); + } + let layer = LayerId(s.doc.alloc_id()); + Some(Element { id: ElementId(s.doc.alloc_id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::group(layer, pieces) }) + } + } +} + +const TOO_LARGE: &str = "the shapes are too complex to combine at once"; + +fn combine(s: &mut Session, op: Op) -> Result { + let sel = s.selection.on(s.layer); + if s.selected_layers().len() > 1 { + return Err(EngineError::State("Combine Objects works on one layer: select shapes on one layer".into())); + } + let els = s.editable_keyframe()?.elements.clone(); + // The selected shapes, bottom to top, with their index. + let mut shapes: Vec<(usize, Arc)> = Vec::new(); + for (i, e) in els.iter().enumerate().filter(|(_, e)| sel.contains(&e.id)) { + match &e.kind { + ElementKind::Shape(_) => shapes.push((i, e.clone())), + _ => return Err(EngineError::State("Combine Objects works on shapes and drawing objects: break symbols, text and groups apart first (Ctrl+B)".into())), + } + } + if shapes.len() < 2 { + return Err(EngineError::State("select two or more shapes to combine".into())); + } + let shape = |e: &Element| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }; + // (index in the keyframe, what replaces it) + let mut results: Vec<(usize, Option)> = Vec::new(); + match op { + Op::Union => { + let raw: Vec = shapes.iter().filter_map(|(_, e)| shape(e).map(|sh| as_raw(e, &sh))).collect(); + let parts: Vec = raw.iter().map(|e| Part::Shape(e, false)).collect(); + let merged = remerge_with(s, &parts, None).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + let top = shapes.last().map_or(0, |x| x.0); + let one = result_of(s, merged.out); + results.push((top, one)); + } + Op::Intersect => { + let (bottom, rest) = shapes.split_first().ok_or_else(|| EngineError::State("select two or more shapes to combine".into()))?; + let sh = shape(&bottom.1).filter(|sh| sh.fill.is_some()).ok_or_else(|| EngineError::State("Intersect needs shapes with fills".into()))?; + let mut region = area(&sh.path.transformed(&bottom.1.transform), sh.fill_rule).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + for (_, e) in rest { + let sh = shape(e).filter(|sh| sh.fill.is_some()).ok_or_else(|| EngineError::State("Intersect needs shapes with fills".into()))?; + let cutter = area(&sh.path.transformed(&e.transform), sh.fill_rule).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + let m = planar::merge_cut(&[Item { path: ®ion, fill: Some(0), fill_rule: FillRule::EvenOdd, stroke: None }], &cutter).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + region = joined(m.fills.iter().filter(|p| p.inside).map(|p| &p.path)); + } + if region.cmds.is_empty() { + return Err(EngineError::State("the shapes don't all overlap: nothing is left to intersect".into())); + } + // In the topmost's fill and stroke (Animate). + let (top_i, top) = shapes.last().map(|(i, e)| (*i, e.clone())).ok_or_else(|| EngineError::State("nothing to combine".into()))?; + let tsh = shape(&top).ok_or_else(|| EngineError::State("nothing to combine".into()))?; + let fill = tsh.fill.map(|f| f.transformed(&top.transform)); + let stroke = tsh.stroke.map(|st| st.scaled(top.transform.mean_scale())); + let made = object(&mut s.doc, ®ion, fill, stroke, top.color); + results.push((top_i, Some(made))); + } + Op::Punch | Op::Crop => { + let (top, lower) = shapes.split_last().ok_or_else(|| EngineError::State("select two or more shapes to combine".into()))?; + let tsh = shape(&top.1).filter(|sh| sh.fill.is_some()).ok_or_else(|| EngineError::State("the topmost shape cuts with its fill: give it one".into()))?; + let cutter = area(&tsh.path.transformed(&top.1.transform), tsh.fill_rule).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + results.push((top.0, None)); + for (i, e) in lower { + let Some(sh) = shape(e) else { continue }; + let raw = as_raw(e, &sh); + let merged = remerge_with(s, &[Part::Shape(&raw, false)], Some(&cutter)).ok_or_else(|| EngineError::State(TOO_LARGE.into()))?; + let keep: Vec> = merged.out.into_iter().filter(|p| merged.inside.contains(&p.id) == (op == Op::Crop)).collect(); + let one = result_of(s, keep); + results.push((*i, one)); + } + } + } + // The sources go; each result takes its source's place. + let gone: HashSet = shapes.iter().map(|x| x.0).collect(); + let mut created = Vec::new(); + let mut out = Vec::with_capacity(els.len()); + for (i, e) in els.into_iter().enumerate() { + if !gone.contains(&i) { + out.push(e); + continue; + } + if let Some(r) = results.iter_mut().find(|(at, _)| *at == i).and_then(|(_, r)| r.take()) { + created.push(r.id); + out.push(Arc::new(r)); + } + } + if created.is_empty() && op != Op::Punch { + return Err(EngineError::State("nothing would be left".into())); + } + s.editable_keyframe()?.elements = out; + s.select_only(created.iter().copied()); + Ok(json!({"op": format!("{op:?}").to_ascii_lowercase(), "created": created.iter().map(|e| e.0).collect::>()})) +} + +/// The area `path` fills even-odd, from its flattening: each loop's area, added or taken away by +/// how many other loops hold it (an analytic check for the tests). +#[cfg(test)] +pub(crate) fn even_odd_area(path: &Path, m: &Affine) -> f64 { + let loops: Vec> = path.flatten(m, 0.005).into_iter().map(|l| l.points).filter(|p| p.len() > 2).collect(); + let signed = |pts: &[anicraft_geom::Vec2]| -> f64 { pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| f64::from(a.x) * f64::from(b.y) - f64::from(b.x) * f64::from(a.y)).sum::() * 0.5 }; + let holds = |pts: &[anicraft_geom::Vec2], p: anicraft_geom::Vec2| pts.iter().zip(pts.iter().cycle().skip(1)).filter(|(a, b)| (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x)).count() % 2 == 1; + let mut total = 0.0; + for (i, l) in loops.iter().enumerate() { + // A point just inside the loop's first edge would do; its middle vertex is near enough for + // loops that don't touch (the merge's pieces never cross). + let Some(&p) = l.first() else { continue }; + let depth = loops.iter().enumerate().filter(|(j, o)| *j != i && holds(o, p)).count(); + total += signed(l).abs() * if depth % 2 == 0 { 1.0 } else { -1.0 }; + } + total +} diff --git a/crates/engine/src/cmds_hints.rs b/crates/engine/src/cmds_hints.rs index f9fce628..63f942a4 100644 --- a/crates/engine/src/cmds_hints.rs +++ b/crates/engine/src/cmds_hints.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { fn find(s: &Session, p: &Value) -> Result<(LayerId, usize, HintSide)> { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let layer = tl.layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; let (i, side) = layer.hint_tween_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is not in a shape tween; select the span and use Insert › Create Shape Tween", frame + 1)))?; Ok((lid, i, side)) @@ -36,7 +36,7 @@ fn find(s: &Session, p: &Value) -> Result<(LayerId, usize, HintSide)> { /// The same, for an edit: refuses locked layers. fn find_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Layer, usize, HintSide)> { let (lid, i, side) = find(s, p)?; - if s.doc.timeline(s.scene).locked_by_folder(lid) { + if s.timeline().locked_by_folder(lid) { return Err(EngineError::State("the layer is in a locked folder".into())); } let layer = s.layer_mut(Some(lid))?; @@ -125,7 +125,7 @@ fn clear_hints(s: &mut Session, p: &Value) -> Result { fn list_hints(s: &mut Session, p: &Value) -> Result { let (lid, i, side) = find(s, p)?; - let layer = s.doc.timeline(s.scene).layer(lid).ok_or_else(|| EngineError::State("no such layer".into()))?; + let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State("no such layer".into()))?; let (Some(a), Some(b)) = (layer.hint_keyframe(i, HintSide::Start), layer.hint_keyframe(i, HintSide::End)) else { return Err(EngineError::State("the keyframe went away".into())) }; let hints: Vec = a .hints diff --git a/crates/engine/src/cmds_layer.rs b/crates/engine/src/cmds_layer.rs new file mode 100644 index 00000000..5ce8fe43 --- /dev/null +++ b/crates/engine/src/cmds_layer.rs @@ -0,0 +1,200 @@ +//! Layer view properties saved in the document (ADR 0061): each layer's onion skin toggle, its +//! colour (outlines and the timeline bar), View as Outlines, its row height, and Layer +//! Properties, which sets several of them (and the name, type, show and lock) as one step. +//! A mask layer's mask type (ADR 0070) is set here too: by area (Animate's masks), by the +//! artwork's opacity, or by its brightness. +//! +//! Behaviour learned from Adobe's public help pages on layers and onion skinning and from +//! watching the program; nothing was copied. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Layer, LayerId, LayerKind, MAX_LAYER_HEIGHT, MaskMode}; +use serde_json::{Value, json}; +use std::sync::Arc; + +/// Layer colours offered next to the colour picker (sRGB): those new layers take in turn, +/// then a few more, all bright enough to read as outlines on a dark or a light stage. +pub const LAYER_COLORS: [u32; 12] = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65, 0xf06292, 0xaed581, 0x9575cd, 0xe0e0e0, 0x8d6e63]; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "layer.set_onion", + "Onion Skin Layer", + "", + None, + "{onion?: bool (default: the other way), solo?: bool, layer?} whether onion skin draws the layer's frames around the playhead. solo: only this layer is onion-skinned (every other layer off); solo again on the only layer on turns them all back on (Alt-click)", + true, + set_onion as crate::RunFn, + ), + c("layer.set_color", "Layer Colour", "", None, "{color: \"#rrggbb\", layer?} the layer's colour: its outlines in outline mode and its bar on the timeline", true, set_color), + c("layer.set_height", "Layer Height", "", None, "{height: 100 | 200 | 300 (percent of a normal row), layer?} the layer's row height on the timeline", true, set_height), + c( + "layer.set_mask", + "Mask Type", + "", + None, + "{mask: coverage|alpha|luminance, layer?} how a mask layer reveals the layers it masks: coverage (its fills' area), alpha (its artwork's opacity: gradients and faded shapes make soft edges) or luminance (its brightness: white shows, black hides; SVG's mask) (ADR 0070)", + true, + set_mask, + ), + c( + "layer.set_properties", + "Layer Properties", + "Modify/Timeline", + None, + "{layer?, name?, type?: normal|mask|masked|guide|guided, mask?: coverage|alpha|luminance (a mask layer's mask type), color?, outline?: bool (view as outlines), height?: 100|200|300, visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties", + true, + set_properties, + ), + c("layer.properties", "Get Layer Properties", "", None, "{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), visible, locked and onion", false, |s, p| properties(s, layer_id(s, p)?)), + ] +} + +fn layer_id(s: &Session, p: &Value) -> Result { + let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); + s.timeline().layer(id).map(|_| id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) +} + +/// Whether a layer of this kind has frames onion skin can show (folders and the camera don't). +fn onion_able(l: &Layer) -> bool { + !matches!(l.kind, LayerKind::Folder | LayerKind::Camera) +} + +fn set_onion(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + let solo = opt_bool(p, "solo")?.unwrap_or(false); + let on = opt_bool(p, "onion")?; + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; + if solo { + // Animate's Alt-click: this layer alone; again on the only one left on, every layer. + let alone = tl.layers.iter().filter(|l| onion_able(l)).all(|l| l.onion == (l.id == id)); + for l in tl.layers.iter_mut().filter(|l| onion_able(l)) { + let want = alone || l.id == id; + if l.onion != want { + Arc::make_mut(l).onion = want; + } + } + } else { + let l = tl.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + l.onion = on.unwrap_or(!l.onion); + } + let on: Vec = tl.layers.iter().filter(|l| onion_able(l) && l.onion).map(|l| l.id.0).collect(); + let onion = tl.layer(id).is_some_and(|l| l.onion); + Ok(json!({"layer": id.0, "onion": onion, "onion_layers": on})) +} + +fn set_color(s: &mut Session, p: &Value) -> Result { + let color = opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' (like \"#ff8800\") is required".into()))?; + let lid = opt_u64(p, "layer")?.map(LayerId); + let l = s.layer_mut(lid)?; + // A layer colour is opaque: it draws hairlines and a bar. + l.color = color.with_alpha(1.0); + Ok(json!({"color": l.color.to_hex()})) +} + +/// `height` in percent (100, 200 or 300) as rows. +fn height_param(p: &Value) -> Result> { + match opt_u32(p, "height")? { + None => Ok(None), + Some(h) if h > 0 && h % 100 == 0 && h / 100 <= u32::from(MAX_LAYER_HEIGHT) => Ok(u8::try_from(h / 100).ok()), + Some(_) => Err(EngineError::Param("param 'height' must be 100, 200 or 300 (percent)".into())), + } +} + +fn set_height(s: &mut Session, p: &Value) -> Result { + let rows = height_param(p)?.ok_or_else(|| EngineError::Param("param 'height' (100, 200 or 300) is required".into()))?; + let lid = opt_u64(p, "layer")?.map(LayerId); + let l = s.layer_mut(lid)?; + l.height_rows = rows; + Ok(json!({"height": u32::from(l.height()) * 100})) +} + +/// `mask`: a mask type's key. +fn mask_param(p: &Value) -> Result> { + opt_str(p, "mask")?.map(|k| MaskMode::from_key(k).ok_or_else(|| EngineError::Param(format!("'mask' is coverage, alpha or luminance, not '{k}'")))).transpose() +} + +fn set_mask(s: &mut Session, p: &Value) -> Result { + let mode = mask_param(p)?.ok_or_else(|| EngineError::Param("param 'mask' (coverage, alpha or luminance) is required".into()))?; + let id = layer_id(s, p)?; + let l = s.layer_mut(Some(id))?; + if l.kind != LayerKind::Mask { + return Err(EngineError::State("only a mask layer has a mask type".into())); + } + l.mask_mode = mode; + Ok(json!({"layer": id.0, "mask": mode.key()})) +} + +fn set_properties(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + // Every param is read (and checked) before anything changes. + let name: Option = opt_str(p, "name")?.map(|n| n.chars().take(128).collect()); + if name.as_ref().is_some_and(|n| n.trim().is_empty()) { + return Err(EngineError::Param("layer name must not be empty".into())); + } + let ty = opt_str(p, "type")?; + let color = opt_color(p, "color")?; + let outline = opt_bool(p, "outline")?; + let height = height_param(p)?; + let mask = mask_param(p)?; + let (visible, locked, onion) = (opt_bool(p, "visible")?, opt_bool(p, "locked")?, opt_bool(p, "onion")?); + if let Some(ty) = ty { + let now = crate::cmds_timeline::layer_type_json(s, id); + if now.get("type").and_then(Value::as_str) != Some(ty) { + crate::cmds_timeline::set_type(s, id, ty)?; + } + } + let l = s.layer_mut(Some(id))?; + if let Some(m) = mask { + if l.kind != LayerKind::Mask { + return Err(EngineError::State("only a mask layer has a mask type".into())); + } + l.mask_mode = m; + } + if let Some(n) = name { + l.name = n; + } + if let Some(c) = color { + l.color = c.with_alpha(1.0); + } + if let Some(o) = outline { + l.outline = o; + } + if let Some(h) = height { + l.height_rows = h; + } + if let Some(v) = visible { + l.visible = v; + } + if let Some(v) = locked { + l.locked = v; + } + if let Some(v) = onion { + l.onion = v; + } + properties(s, id) +} + +fn properties(s: &Session, id: LayerId) -> Result { + let l = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let ty = crate::cmds_timeline::layer_type_json(s, id).get("type").cloned().unwrap_or(Value::Null); + Ok(json!({ + "layer": id.0, + "name": l.name, + "type": ty, + "mask": (l.kind == LayerKind::Mask).then(|| l.mask_mode.key()), + "color": l.color.to_hex(), + "outline": l.outline, + "height": u32::from(l.height()) * 100, + "visible": l.visible, + "locked": l.locked, + "onion": l.onion, + })) +} + +#[cfg(test)] +#[path = "cmds_layer_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmds_layer_tests.rs b/crates/engine/src/cmds_layer_tests.rs new file mode 100644 index 00000000..92006344 --- /dev/null +++ b/crates/engine/src/cmds_layer_tests.rs @@ -0,0 +1,302 @@ +//! Layer view properties (ADR 0061): onion toggles and solo, colour, View as Outlines (on the +//! stage only), row height, Layer Properties as one step, the file, and onion skin of the +//! timeline around a symbol open in place. + +use crate::Session; +use crate::onion::{Markers, OnionSkin}; +use anicraft_doc::{ElementId, LayerId, Rgba}; +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} {p}: {e}")) +} + +fn rect(s: &mut Session, x: f32) -> ElementId { + ElementId(run(s, "draw.rect", json!({"x": x, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()) +} + +/// Two layers, each a square that moves 40 px right on frames 0, 2 and 4: `top` starts at x 0, +/// `bottom` at x 200. The playhead is on frame 2. +fn two_walks() -> (Session, LayerId, LayerId) { + let mut s = Session::default(); + let bottom = s.layer; + let b = rect(&mut s, 200.0); + let top = LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let t = rect(&mut s, 0.0); + for f in [2, 4] { + run(&mut s, "timeline.goto", json!({"frame": f})); + for (l, e) in [(bottom, b), (top, t)] { + run(&mut s, "layer.select", json!({"layer": l.0})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [e.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + } + run(&mut s, "timeline.goto", json!({"frame": 2})); + (s, top, bottom) +} + +fn layer(s: &Session, id: LayerId) -> &anicraft_doc::Layer { + s.timeline().layer(id).unwrap() +} + +/// What the stage shows with `skin`: the layers and left edges of the onion frames (tinted items). +fn ghosts(s: &Session, skin: &OnionSkin) -> Vec<(LayerId, f32)> { + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(skin)); + dl.items.iter().filter(|i| !i.color.is_identity()).map(|i| (i.layer, i.path.bounds().transformed(&i.transform).min.x)).collect() +} + +#[test] +fn a_layer_with_onion_off_is_not_onion_skinned() { + let (mut s, top, bottom) = two_walks(); + let skin = OnionSkin { keyframes_only: true, ..OnionSkin::default() }; + let mut both = ghosts(&s, &skin); + both.sort_by(|a, b| a.1.total_cmp(&b.1)); + assert_eq!(both, vec![(top, 0.0), (top, 80.0), (bottom, 200.0), (bottom, 280.0)], "frames 0 and 4 on both layers"); + let r = run(&mut s, "layer.set_onion", json!({"layer": bottom.0})); + assert_eq!(r["onion"], false, "toggles"); + assert!(!layer(&s, bottom).onion && layer(&s, top).onion); + assert!(ghosts(&s, &skin).iter().all(|(l, _)| *l == top), "only the top layer's frames show"); + // Its playhead frame still shows, at full strength. + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(&skin)); + assert!(dl.items.iter().any(|i| i.layer == bottom && i.color.is_identity())); + // Edit Multiple Frames isn't onion skin: it still shows and edits the layer's keyframes. + let multi = OnionSkin { edit_multiple: true, ..skin }; + assert!(s.multi_frame_items(0, 4).iter().any(|(it, _)| it.layer == bottom && it.frame == 0)); + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(&multi)); + assert_eq!(dl.items.iter().filter(|i| i.layer == bottom).count(), 3); + // Undo brings it back. + run(&mut s, "edit.undo", json!({})); + assert!(layer(&s, bottom).onion); + assert!(s.execute("layer.set_onion", &json!({"layer": 999_999})).is_err()); + assert!(s.execute("layer.set_onion", &json!({"onion": "yes"})).is_err()); +} + +#[test] +fn solo_onion_keeps_one_layer_and_again_brings_back_all() { + let (mut s, top, bottom) = two_walks(); + let folder = LayerId(run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap()); + let r = run(&mut s, "layer.set_onion", json!({"layer": top.0, "solo": true})); + assert_eq!(r["onion_layers"], json!([top.0])); + assert!(layer(&s, top).onion && !layer(&s, bottom).onion); + assert!(layer(&s, folder).onion, "a folder has no frames to onion-skin; solo leaves it"); + // Solo on another layer moves the solo there. + run(&mut s, "layer.set_onion", json!({"layer": bottom.0, "solo": true})); + assert!(!layer(&s, top).onion && layer(&s, bottom).onion); + // Again on the only layer left on: every layer is on again. + run(&mut s, "layer.set_onion", json!({"layer": bottom.0, "solo": true})); + assert!(layer(&s, top).onion && layer(&s, bottom).onion); + // Setting it outright. + run(&mut s, "layer.set_onion", json!({"layer": top.0, "onion": false})); + run(&mut s, "layer.set_onion", json!({"layer": top.0, "onion": false})); + assert!(!layer(&s, top).onion); +} + +#[test] +fn outlines_use_the_layer_colour_on_the_stage_only() { + let mut s = Session::default(); + let l = s.layer; + rect(&mut s, 10.0); + run(&mut s, "layer.set_color", json!({"color": "#ff8800"})); + run(&mut s, "layer.toggle_outline", json!({})); + let orange = Rgba::hex(0xff8800); + assert_eq!(layer(&s, l).color, orange); + // The stage: hairlines in the layer's colour. + let stage = anicraft_doc::evaluate_scene(&s.doc, 0, 0); + assert!(stage.items.iter().all(|i| i.outline == Some(orange))); + assert!(s.display_list().items.iter().all(|i| i.outline == Some(orange))); + // The movie (every export), and the player, draw the artwork as it is. + let movie = anicraft_doc::evaluate(&s.doc, 0); + assert!(!movie.items.is_empty() && movie.items.iter().all(|i| i.outline.is_none())); + let player = anicraft_doc::evaluate_player(&s.doc, &anicraft_doc::player::PlayerState::default()); + assert!(player.items.iter().all(|i| i.outline.is_none())); + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + assert!(!svg.to_ascii_lowercase().contains("ff8800"), "no outline colour in an SVG export"); + let png = |s: &Session| { + let view = anicraft_render::View { transform: anicraft_geom::Affine::IDENTITY, width: 40, height: 40, background: Some(Rgba::WHITE) }; + anicraft_render::render(&anicraft_doc::evaluate(&s.doc, 0), &view).unwrap().0.to_rgba8() + }; + let outlined = png(&s); + run(&mut s, "layer.toggle_outline", json!({})); + assert_eq!(outlined, png(&s), "an export looks the same with or without outline mode"); + // Inside a symbol on an outlined layer, the stage outlines everything in the layer's colour. + run(&mut s, "layer.toggle_outline", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let stage = anicraft_doc::evaluate_scene(&s.doc, 0, 0); + assert!(!stage.items.is_empty() && stage.items.iter().all(|i| i.outline == Some(orange))); + assert!(anicraft_doc::evaluate(&s.doc, 0).items.iter().all(|i| i.outline.is_none())); + // A colour is opaque, and a bad one is refused. + run(&mut s, "layer.set_color", json!({"color": "#00ff0080"})); + assert_eq!(layer(&s, l).color.a, 1.0); + assert!(s.execute("layer.set_color", &json!({"color": "green"})).is_err()); + assert!(s.execute("layer.set_color", &json!({})).is_err()); +} + +#[test] +fn layer_height_is_100_200_or_300_percent() { + let mut s = Session::default(); + let l = s.layer; + assert_eq!(layer(&s, l).height(), 1); + assert_eq!(run(&mut s, "layer.set_height", json!({"height": 300}))["height"], 300); + assert_eq!(layer(&s, l).height(), 3); + for bad in [json!(0), json!(150), json!(400), json!(-100), json!("tall")] { + assert!(s.execute("layer.set_height", &json!({"height": bad})).is_err(), "{bad}"); + } + assert!(s.execute("layer.set_height", &json!({})).is_err()); + assert_eq!(layer(&s, l).height(), 3); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layer(&s, l).height(), 1); +} + +#[test] +fn layer_properties_set_everything_as_one_step_or_nothing() { + let (mut s, top, bottom) = two_walks(); + let undo = s.history.undo_len(); + let r = run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "name": "Sky", "color": "#123456", "outline": true, "height": 200, "locked": true, "visible": false, "onion": false, "type": "guide"})); + assert_eq!(r, json!({"layer": bottom.0, "name": "Sky", "type": "guide", "mask": null, "color": "#123456", "outline": true, "height": 200, "visible": false, "locked": true, "onion": false})); + assert_eq!(s.history.undo_len(), undo + 1, "one undo step"); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0})), r); + // The same type again changes nothing (a masked layer stays masked by the same mask). + run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "type": "guide"})); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0}))["type"], "guide"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + let back = run(&mut s, "layer.properties", json!({"layer": bottom.0})); + assert_eq!((back["name"].as_str(), back["type"].as_str(), back["height"].as_u64()), (Some("Layer 1"), Some("normal"), Some(100))); + // A bad value anywhere changes nothing. + for bad in [json!({"name": " "}), json!({"name": "X", "height": 250}), json!({"name": "X", "color": "red"}), json!({"name": "X", "type": "masked"}), json!({"name": "X", "type": "banana"}), json!({"name": "X", "locked": 1})] { + let mut p = bad.clone(); + p["layer"] = json!(top.0); + assert!(s.execute("layer.set_properties", &p).is_err(), "{bad}"); + assert_eq!(layer(&s, top).name, "Layer 2", "{bad}"); + } + assert!(s.execute("layer.properties", &json!({"layer": 999_999})).is_err()); +} + +#[test] +fn a_mask_layer_takes_a_mask_type() { + let (mut s, top, bottom) = two_walks(); + // Only a mask layer has one. + assert!(s.execute("layer.set_mask", &json!({"layer": top.0, "mask": "alpha"})).is_err()); + assert!(s.execute("layer.set_properties", &json!({"layer": top.0, "name": "X", "mask": "alpha"})).is_err()); + assert_eq!(layer(&s, top).name, "Layer 2", "nothing changed"); + // Made a mask and soft in one step; then by itself. + let r = run(&mut s, "layer.set_properties", json!({"layer": top.0, "type": "mask", "mask": "luminance"})); + assert_eq!((r["type"].as_str(), r["mask"].as_str()), (Some("mask"), Some("luminance"))); + assert_eq!(layer(&s, top).mask_mode, anicraft_doc::MaskMode::Luminance); + assert_eq!(run(&mut s, "layer.set_mask", json!({"layer": top.0, "mask": "alpha"}))["mask"], "alpha"); + assert!(s.execute("layer.set_mask", &json!({"layer": top.0, "mask": "soft"})).is_err()); + assert!(s.execute("layer.set_mask", &json!({"layer": top.0})).is_err()); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0}))["mask"], Value::Null); + // The stage shows it at once: the masked square at its edge (art opaque → fully shown). + run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "type": "masked"})); + let dl = s.display_list(); + assert_eq!(dl.clip_mode(0), anicraft_doc::MaskMode::Alpha); + // Undo goes back to luminance, then to coverage. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layer(&s, top).mask_mode, anicraft_doc::MaskMode::Luminance); +} + +#[test] +fn onion_and_height_are_saved_and_older_files_open_with_the_defaults() { + let (mut s, top, bottom) = two_walks(); + run(&mut s, "layer.set_onion", json!({"layer": top.0})); + run(&mut s, "layer.set_height", json!({"layer": bottom.0, "height": 200})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + let tl = back.timeline(0); + assert!(!tl.layer(top).unwrap().onion && tl.layer(bottom).unwrap().onion); + assert_eq!((tl.layer(top).unwrap().height(), tl.layer(bottom).unwrap().height()), (1, 2)); + // Defaults are left out of the file, so older files and files without them read the same. + let v: Value = serde_json::from_str(&text).unwrap(); + fn find(v: &Value, id: u64) -> Option { + match v { + Value::Object(m) if m.get("id") == Some(&json!(id)) && m.contains_key("keyframes") => Some(v.clone()), + Value::Object(m) => m.values().find_map(|x| find(x, id)), + Value::Array(a) => a.iter().find_map(|x| find(x, id)), + _ => None, + } + } + let by_id = |id: LayerId| find(&v, id.0).unwrap_or_default(); + assert!(by_id(top).get("name").is_some()); + assert_eq!((by_id(top).get("onion"), by_id(top).get("height")), (Some(&json!(false)), None)); + assert_eq!((by_id(bottom).get("onion"), by_id(bottom).get("height")), (None, Some(&json!(2)))); + let old: anicraft_doc::Layer = serde_json::from_value(json!({"id": 7, "name": "Old"})).unwrap(); + assert!(old.onion && old.height() == 1); + // A height out of range in a file reads as the nearest one. + let tall: anicraft_doc::Layer = serde_json::from_value(json!({"id": 7, "name": "Tall", "height": 200})).unwrap(); + assert_eq!(tall.height(), 3); +} + +/// A scene with a square walking on a second layer (x 0, 40, 80 on frames 0, 2, 4), and an +/// instance of a symbol on the first, open in place on frame 2 of the scene. +fn parent_walk() -> (Session, LayerId) { + let mut s = Session::default(); + let host = s.layer; + rect(&mut s, 300.0); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let inst = s.selection.ids().next().unwrap(); + let walker = LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let w = rect(&mut s, 0.0); + run(&mut s, "timeline.insert_frame", json!({"layer": host.0, "frame": 0, "count": 4})); + for f in [2, 4] { + run(&mut s, "timeline.goto", json!({"frame": f})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [w.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + run(&mut s, "layer.select", json!({"layer": host.0})); + run(&mut s, "timeline.goto", json!({"frame": 2})); + run(&mut s, "symbol.edit", json!({"id": inst.0})); + assert_eq!(s.editing.len(), 1); + (s, walker) +} + +#[test] +fn onion_skin_inside_a_symbol_shows_the_parent_timeline_frames_dimmed() { + let (s, walker) = parent_walk(); + let pic = s.stage_picture(); + let front = pic.front.clone().unwrap(); + let parent = front.parent.clone().expect("the scene shows around the symbol"); + assert_eq!(parent.frame, 2); + let skin = OnionSkin { markers: Markers::Relative { before: 2, after: 2 }, keyframes_only: true, ..OnionSkin::default() }; + let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &skin); + let left = |i: &anicraft_doc::DisplayItem| i.path.bounds().transformed(&i.transform).min.x; + // The walker on the scene: frame 2 (x 40) dimmed, frames 0 and 4 (x 0, 80) tinted and fainter. + let mut walk: Vec<(f32, f32, bool)> = dl.items.iter().filter(|i| left(i) < 150.0).map(|i| (left(i), dl.effective_alpha(i), i.color.changes_colour())).collect(); + walk.sort_by(|a, b| a.0.total_cmp(&b.0)); + assert_eq!(walk.iter().map(|w| w.0).collect::>(), vec![0.0, 40.0, 80.0], "the parent's onion frames around its frame 2"); + let dim = parent.dim; + assert!((walk[1].1 - dim).abs() < 1e-4 && !walk[1].2, "the parent's own frame as dim as without onion skin"); + assert!(walk[0].2 && walk[2].2 && walk[0].1 < dim && walk[2].1 < dim, "its onion frames tinted, dimmer still"); + // The open symbol is in front at full strength. + let box_item = dl.items.iter().find(|i| left(i) >= 290.0).unwrap(); + assert!((dl.effective_alpha(box_item) - 1.0).abs() < 1e-4); + assert!(dl.items.last().is_some_and(|i| left(i) >= 290.0), "drawn over everything around it"); + // Without onion skin the picture is as before; the parent's layer toggle and Edit Multiple + // Frames (the open symbol's frames only) leave its onion frames out. + let plain = crate::render_service::display_list_with_onion(&pic.doc, pic.frame, None); + assert_eq!(plain.items.len(), 2); + let multi = OnionSkin { edit_multiple: true, ..skin }; + assert_eq!(crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi).items.len(), 2); + let mut off = s; + run(&mut off, "symbol.exit", json!({})); + let inst = off.selection.ids().next().unwrap(); + run(&mut off, "layer.set_onion", json!({"layer": walker.0})); + run(&mut off, "symbol.edit", json!({"id": inst.0})); + let pic = off.stage_picture(); + let front = pic.front.clone().unwrap(); + assert_eq!(crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &skin).items.len(), 2); +} + +#[test] +fn plug_ins_may_set_layer_properties() { + for id in ["layer.set_onion", "layer.set_color", "layer.set_height", "layer.set_properties", "layer.properties"] { + assert!(crate::find_command(id).is_some(), "{id}"); + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs new file mode 100644 index 00000000..46f2fa89 --- /dev/null +++ b/crates/engine/src/cmds_library.rs @@ -0,0 +1,474 @@ +//! Library management (ADR 0050): folders, renaming, moving, duplicating and deleting items, +//! use counts and unused items, bitmap smoothing, and Swap Symbol. +//! +//! An item or folder is named in params as `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}` +//! or `{"folder": id}`. Sorting and filtering the list are views (the shell's); `library.items` +//! gives a script everything it needs to do the same. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::library::{MAX_FOLDER_DEPTH, MAX_FOLDERS}; +use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryFolder, LibraryItem, Paint, SoundId, SymbolId, SymbolKind, Timeline}; +use serde_json::{Value, json}; +use std::collections::HashSet; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("library.items", "List Library", "", None, "{} every folder (id, name, parent, path) and item (symbol | bitmap | sound id, kind, name, folder, path, uses, unused) in Library order; `uses` counts instances, bitmap fills and keyframe sounds once per keyframe", false, items as crate::RunFn), + c("library.new_folder", "New Folder", "", None, "{name? (default: the next free “Folder n”), parent?: folder id} → {folder, name}; names are unique within a folder (case aside) and can't hold “/”", true, new_folder), + c("library.rename", "Rename", "", None, "{symbol | bitmap | sound | folder: id, name} renames a Library item or folder; the name must be free in its folder (case aside) and can't hold “/”", true, rename), + c("library.move", "Move to Folder", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..], to: folder id | null (the top level)} moves items and folders (with what they hold) into a folder; a folder can't go inside itself, and a name the folder already has stops the move", true, move_to), + c("library.duplicate", "Duplicate Symbol", "", None, "{symbol, name? (default: “ copy”)} → {symbol, name}: a copy in the same folder, with its own layers and elements and no linkage class", true, duplicate), + c("library.delete", "Delete", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..]} deletes items and folders with everything in them; instances of deleted symbols, shapes filled with deleted bitmaps and keyframes' deleted sounds go too (asks first when anything deleted is in use or a folder isn't empty)", true, delete), + c("library.unused", "Select Unused Items", "", None, "{} → {items: [..]} the items nothing in the movie reaches: not in a scene, nor inside a symbol that is; symbols with a linkage class count as used", false, unused), + c("library.delete_unused", "Delete Unused Items", "", None, "{} deletes every item `library.unused` lists (asks first)", true, delete_unused), + c("library.set_smoothing", "Allow Smoothing", "", None, "{bitmap, on?: bool (default: toggle)} whether the bitmap is filtered when scaled or turned (off: hard-edged pixels)", true, set_smoothing), + c("element.swap_bitmap", "Swap Bitmap", "", None, "{bitmap} the selected bitmaps and bitmap-filled shapes show another bitmap: a placed bitmap keeps its transform and top-left corner and takes the new bitmap's size; a bitmap fill keeps its shape and fill transform", true, |s, p| s.each_layer(false, |s| swap_bitmap(s, p))), + c("element.swap_symbol", "Swap Symbol", "", None, "{symbol} the selected instances show another symbol, keeping their transform, colour effect, blending, filters, looping, actions and instance name", true, |s, p| s.each_layer(false, |s| swap_symbol(s, p))), + ] +} + +/// Most entries one command takes. +const MAX_ENTRIES: usize = 100_000; + +/// The entry a JSON object names: `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}` or +/// `{"folder": id}`. +pub(crate) fn entry_of(v: &Value) -> Result { + let id = |k: &str| v.get(k).and_then(Value::as_u64); + match (id("symbol"), id("bitmap"), id("sound"), id("folder")) { + (Some(i), None, None, None) => Ok(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(i)))), + (None, Some(i), None, None) => Ok(LibraryEntry::Item(LibraryItem::Bitmap(BitmapId(i)))), + (None, None, Some(i), None) => Ok(LibraryEntry::Item(LibraryItem::Sound(SoundId(i)))), + (None, None, None, Some(i)) => Ok(LibraryEntry::Folder(FolderId(i))), + _ => Err(EngineError::Param("name one Library entry: {\"symbol\" | \"bitmap\" | \"sound\" | \"folder\": id}".into())), + } +} + +/// `entry` as params name it. +pub fn entry_json(e: LibraryEntry) -> Value { + match e { + LibraryEntry::Item(LibraryItem::Symbol(i)) => json!({"symbol": i.0}), + LibraryEntry::Item(LibraryItem::Bitmap(i)) => json!({"bitmap": i.0}), + LibraryEntry::Item(LibraryItem::Sound(i)) => json!({"sound": i.0}), + LibraryEntry::Folder(f) => json!({"folder": f.0}), + } +} + +/// The entries in list `key`, each checked to exist (no repeats). +pub(crate) fn entries_of(s: &Session, p: &Value, key: &str) -> Result> { + let list = p.get(key).and_then(Value::as_array).ok_or_else(|| EngineError::Param(format!("param '{key}' must be a list of Library entries")))?; + if list.len() > MAX_ENTRIES { + return Err(EngineError::Param(format!("at most {MAX_ENTRIES} entries"))); + } + let mut out = Vec::with_capacity(list.len()); + let mut seen = HashSet::new(); + for v in list { + let e = entry_of(v)?; + if !s.doc.has_entry(e) { + return Err(EngineError::State(format!("the Library has no {}", describe(e)))); + } + if seen.insert(e) { + out.push(e); + } + } + Ok(out) +} + +fn describe(e: LibraryEntry) -> String { + match e { + LibraryEntry::Item(LibraryItem::Symbol(i)) => format!("symbol {}", i.0), + LibraryEntry::Item(LibraryItem::Bitmap(i)) => format!("bitmap {}", i.0), + LibraryEntry::Item(LibraryItem::Sound(i)) => format!("sound {}", i.0), + LibraryEntry::Folder(f) => format!("folder {}", f.0), + } +} + +pub(crate) fn opt_folder(s: &Session, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let id = v.as_u64().map(FolderId).ok_or_else(|| EngineError::Param(format!("param '{key}' must be a folder id or null")))?; + if s.doc.folder(id).is_none() { + return Err(EngineError::State(format!("the Library has no folder {}", id.0))); + } + Ok(Some(id)) + } + } +} + +/// The symbol type `key` names (`graphic`, `movie_clip` or `button`). +pub(crate) fn kind_of(key: &str) -> Result { + match key { + "graphic" => Ok(SymbolKind::Graphic), + "movie_clip" | "movie clip" => Ok(SymbolKind::MovieClip), + "button" => Ok(SymbolKind::Button), + _ => Err(EngineError::Param(format!("unknown symbol type '{key}' (graphic, movie_clip or button)"))), + } +} + +pub(crate) fn kind_key(k: SymbolKind) -> &'static str { + match k { + SymbolKind::Graphic => "graphic", + SymbolKind::MovieClip => "movie_clip", + SymbolKind::Button => "button", + } +} + +fn items(s: &mut Session, _: &Value) -> Result { + let d = &s.doc; + let uses = d.library_uses(); + let unused: HashSet = d.unused_items().into_iter().collect(); + let folders: Vec = d + .library_tree + .folders + .iter() + .map(|f| json!({"folder": f.id.0, "name": f.name, "parent": f.parent.map(|p| p.0), "path": d.entry_path(LibraryEntry::Folder(f.id))})) + .collect(); + let items: Vec = d + .library_items() + .map(|i| { + let e = LibraryEntry::Item(i); + let mut v = entry_json(e); + v["name"] = json!(d.item_name(i)); + v["folder"] = json!(d.parent_of(e).map(|f| f.0)); + v["path"] = json!(d.entry_path(e)); + v["uses"] = json!(uses.get(&i).copied().unwrap_or(0)); + v["unused"] = json!(unused.contains(&i)); + match i { + LibraryItem::Symbol(id) => { + if let Some(sym) = d.symbol(id) { + v["kind"] = json!(kind_key(sym.kind)); + v["frames"] = json!(sym.timeline.frame_count()); + v["linkage"] = json!(sym.linkage.as_ref().map(|l| &l.class)); + } + } + LibraryItem::Bitmap(id) => { + if let Some(b) = d.bitmap(id) { + v["kind"] = json!("bitmap"); + v["width"] = json!(b.width); + v["height"] = json!(b.height); + v["smoothing"] = json!(b.smoothing); + } + } + LibraryItem::Sound(id) => { + if let Some(x) = d.sound(id) { + v["kind"] = json!("sound"); + v["seconds"] = json!(x.seconds()); + } + } + } + v + }) + .collect(); + Ok(json!({"folders": folders, "items": items, "unused": unused.len()})) +} + +fn new_folder(s: &mut Session, p: &Value) -> Result { + let parent = opt_folder(s, p, "parent")?; + if s.doc.library_tree.folders.len() >= MAX_FOLDERS { + return Err(EngineError::State(format!("the Library holds at most {MAX_FOLDERS} folders"))); + } + if parent.is_some_and(|f| s.doc.folder_depth(f) >= MAX_FOLDER_DEPTH) { + return Err(EngineError::State(format!("folders nest at most {MAX_FOLDER_DEPTH} deep"))); + } + let name = match opt_str(p, "name")? { + Some(n) => s.doc.check_name(parent, n, None).map_err(|e| EngineError::Param(e.to_string()))?, + None => s.doc.numbered_name(parent, "Folder", 1), + }; + let id = FolderId(s.doc.alloc_id()); + Arc::make_mut(&mut s.doc.library_tree).folders.push(LibraryFolder { id, name: name.clone(), parent }); + Ok(json!({"folder": id.0, "name": name})) +} + +pub(crate) fn rename(s: &mut Session, p: &Value) -> Result { + let e = entry_of(p)?; + if !s.doc.has_entry(e) { + return Err(EngineError::State(format!("the Library has no {}", describe(e)))); + } + let name = s.doc.check_name(s.doc.parent_of(e), str_req(p, "name")?, Some(e)).map_err(|err| EngineError::Param(err.to_string()))?; + let d = &mut s.doc; + match e { + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + if let Some(x) = d.library.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Item(LibraryItem::Bitmap(id)) => { + if let Some(x) = d.bitmaps.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Item(LibraryItem::Sound(id)) => { + if let Some(x) = d.sounds.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Folder(id) => { + if let Some(f) = Arc::make_mut(&mut d.library_tree).folders.iter_mut().find(|f| f.id == id) { + f.name = name.clone(); + } + } + } + let mut v = entry_json(e); + v["name"] = json!(name); + Ok(v) +} + +fn move_to(s: &mut Session, p: &Value) -> Result { + let list = entries_of(s, p, "items")?; + if p.get("to").is_none() { + return Err(EngineError::Param("param 'to' is required: a folder id, or null for the top level".into())); + } + let to = opt_folder(s, p, "to")?; + let mut moved = 0; + for e in list { + if s.doc.parent_of(e) == to { + continue; + } + if let LibraryEntry::Folder(f) = e { + if to.is_some_and(|t| s.doc.folder_within(t, f)) { + return Err(EngineError::State(format!("“{}” can't go inside itself", s.doc.entry_name(e).unwrap_or("")))); + } + if to.map_or(0, |t| s.doc.folder_depth(t)) + s.doc.folder_height(f) > MAX_FOLDER_DEPTH { + return Err(EngineError::State(format!("folders nest at most {MAX_FOLDER_DEPTH} deep"))); + } + } + let name = s.doc.entry_name(e).unwrap_or("").to_string(); + if s.doc.name_taken(to, &name, Some(e)) { + let place = to.and_then(|t| s.doc.folder(t)).map_or_else(|| "The top level of the Library".to_string(), |f| format!("“{}”", f.name)); + return Err(EngineError::State(format!("{place} already has an item named “{name}”; rename one of them first"))); + } + s.doc.place_entry(e, to); + moved += 1; + } + Ok(json!({"moved": moved, "to": to.map(|f| f.0)})) +} + +fn duplicate(s: &mut Session, p: &Value) -> Result { + let id = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?); + let Some(src) = s.doc.symbol(id) else { + return Err(EngineError::State(format!("no symbol with id {}", id.0))); + }; + let parent = s.doc.parent_of(LibraryEntry::Item(LibraryItem::Symbol(id))); + let name = match opt_str(p, "name")? { + Some(n) => s.doc.check_name(parent, n, None).map_err(|e| EngineError::Param(e.to_string()))?, + None => s.doc.unique_name(parent, &format!("{} copy", src.name)), + }; + let copy = s.doc.duplicate_symbol(id, name.clone()).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + Ok(json!({"symbol": copy.0, "name": name})) +} + +/// What deleting `entries` takes: the items (folders expanded into what they hold) and the +/// folders. +pub(crate) fn deletion(s: &Session, entries: &[LibraryEntry]) -> (Vec, Vec) { + let mut items: Vec = Vec::new(); + let mut folders: Vec = Vec::new(); + let add = |e: LibraryEntry, items: &mut Vec, folders: &mut Vec| match e { + LibraryEntry::Item(i) if !items.contains(&i) => items.push(i), + LibraryEntry::Folder(f) if !folders.contains(&f) => folders.push(f), + _ => {} + }; + for &e in entries { + add(e, &mut items, &mut folders); + if let LibraryEntry::Folder(f) = e { + for inner in s.doc.folder_contents(f) { + add(inner, &mut items, &mut folders); + } + } + } + (items, folders) +} + +/// Takes every reference to `gone` off `tl` (instances, bitmap-filled shapes, keyframe sounds), +/// un-sharing only the layers and keyframes that had one. How many references went. +fn strip(tl: &mut Timeline, gone: &HashSet) -> usize { + strip_in(tl, gone, 0) +} + +/// [`strip`], inside groups too (ADR 0073): a group keeps its other members. +fn strip_in(tl: &mut Timeline, gone: &HashSet, depth: usize) -> usize { + let refers = |e: &anicraft_doc::Element| match &e.kind { + ElementKind::Symbol { symbol, .. } => gone.contains(&LibraryItem::Symbol(*symbol)), + ElementKind::Shape(sh) => matches!(&sh.fill, Some(Paint::Bitmap { bitmap, .. }) if gone.contains(&LibraryItem::Bitmap(*bitmap))), + ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => false, + }; + let inside = |e: &anicraft_doc::Element| matches!(&e.kind, ElementKind::Group { members } if depth < anicraft_doc::MAX_GROUP_DEPTH && strip_needed(members, gone)); + let sounds = |k: &anicraft_doc::Keyframe| k.sound.as_ref().is_some_and(|f| gone.contains(&LibraryItem::Sound(f.sound))); + let hit = |k: &anicraft_doc::Keyframe| sounds(k) || k.elements.iter().any(|e| refers(e) || inside(e)); + let mut n = 0; + for l in tl.layers.iter_mut().filter(|l| l.keyframes.iter().any(|k| hit(k))) { + for k in Arc::make_mut(l).keyframes.iter_mut().filter(|k| hit(k)) { + let k = Arc::make_mut(k); + if sounds(k) { + k.sound = None; + n += 1; + } + let before = k.elements.len(); + k.elements.retain(|e| !refers(e)); + n += before - k.elements.len(); + for e in k.elements.iter_mut().filter(|e| inside(e)) { + if let ElementKind::Group { members } = &mut Arc::make_mut(e).kind { + n += strip_in(members, gone, depth + 1); + } + } + } + } + n +} + +/// Deletes `items` and `folders` from the Library and every use of the items from the movie. +fn remove(s: &mut Session, items: &[LibraryItem], folders: &[FolderId]) -> Value { + let gone: HashSet = items.iter().copied().collect(); + let mut uses = 0; + if !gone.is_empty() { + for scene in &mut s.doc.scenes { + if strip_needed(&scene.timeline, &gone) { + uses += strip(&mut Arc::make_mut(scene).timeline, &gone); + } + } + s.doc.library.retain(|x| !gone.contains(&LibraryItem::Symbol(x.id))); + s.doc.bitmaps.retain(|x| !gone.contains(&LibraryItem::Bitmap(x.id))); + s.doc.sounds.retain(|x| !gone.contains(&LibraryItem::Sound(x.id))); + for sym in &mut s.doc.library { + if strip_needed(&sym.timeline, &gone) { + uses += strip(&mut Arc::make_mut(sym).timeline, &gone); + } + } + // The fill swatch may hold a deleted bitmap (picked with the Eyedropper). + if let Some(Paint::Bitmap { bitmap, .. }) = &s.style.fill_paint + && gone.contains(&LibraryItem::Bitmap(*bitmap)) + { + s.style.fill_paint = None; + } + } + let dead: HashSet = folders.iter().copied().collect(); + if !dead.is_empty() || s.doc.library_tree.placed.keys().any(|i| gone.contains(i)) { + let t = Arc::make_mut(&mut s.doc.library_tree); + t.placed.retain(|i, f| !gone.contains(i) && !dead.contains(f)); + t.folders.retain(|f| !dead.contains(&f.id)); + // A folder whose parent went (it was named on its own) goes to the top level. + let ids: HashSet = t.folders.iter().map(|f| f.id).collect(); + for f in &mut t.folders { + if f.parent.is_some_and(|p| !ids.contains(&p)) { + f.parent = None; + } + } + } + json!({"deleted": items.len(), "folders": folders.len(), "uses": uses}) +} + +fn strip_needed(tl: &Timeline, gone: &HashSet) -> bool { + let mut any = false; + anicraft_doc::library::visit_refs(tl, |i| any |= gone.contains(&i)); + any +} + +fn delete(s: &mut Session, p: &Value) -> Result { + let list = entries_of(s, p, "items")?; + if list.is_empty() { + return Err(EngineError::State("nothing to delete".into())); + } + let (items, folders) = deletion(s, &list); + Ok(remove(s, &items, &folders)) +} + +fn unused(s: &mut Session, _: &Value) -> Result { + let list: Vec = s.doc.unused_items().into_iter().map(|i| entry_json(LibraryEntry::Item(i))).collect(); + Ok(json!({"items": list})) +} + +fn delete_unused(s: &mut Session, _: &Value) -> Result { + let items = s.doc.unused_items(); + Ok(remove(s, &items, &[])) +} + +fn set_smoothing(s: &mut Session, p: &Value) -> Result { + let id = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?); + let on = opt_bool(p, "on")?; + let b = s.doc.bitmaps.iter_mut().find(|b| b.id == id).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", id.0)))?; + let on = on.unwrap_or(!b.smoothing); + if b.smoothing != on { + Arc::make_mut(b).smoothing = on; + } + Ok(json!({"bitmap": id.0, "smoothing": on})) +} + +fn swap_symbol(s: &mut Session, p: &Value) -> Result { + let to = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?); + if s.doc.symbol(to).is_none() { + return Err(EngineError::State(format!("no symbol with id {}", to.0))); + } + // Inside a symbol open for editing (ADR 0045), never swap in that symbol or one that holds it. + if crate::editing::would_nest(s, to) { + return Err(EngineError::State("a symbol can't be placed inside itself".into())); + } + let mut swapped = 0; + for e in s.selected_elements_mut()? { + if let ElementKind::Symbol { symbol, .. } = &mut e.kind { + *symbol = to; + swapped += 1; + } + } + if swapped == 0 { + return Err(EngineError::State("select a symbol instance to swap".into())); + } + Ok(json!({"swapped": swapped, "symbol": to.0})) +} + +/// Swap Bitmap (ADR 0053), as Animate's Properties offer on a bitmap. A bitmap placed from the +/// Library is a rectangle of the bitmap's size filled with it: it keeps its transform (so its +/// top-left corner stays put) and becomes the new bitmap's size, and its name follows when it was +/// the old bitmap's. Any other shape filled with a bitmap keeps its outline and fill transform. +fn swap_bitmap(s: &mut Session, p: &Value) -> Result { + let to = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?); + if s.doc.bitmap(to).is_none() { + return Err(EngineError::State(format!("no bitmap with id {}", to.0))); + } + let sizes: std::collections::HashMap = s.doc.bitmaps.iter().map(|b| (b.id, (b.name.clone(), b.width as f32, b.height as f32))).collect(); + let mut swapped = 0; + for e in s.selected_elements_mut()? { + if swap_bitmap_of(e, to, &sizes) { + swapped += 1; + } + } + if swapped == 0 { + return Err(EngineError::State("select a bitmap, or a shape filled with one, to swap".into())); + } + Ok(json!({"swapped": swapped, "bitmap": to.0})) +} + +/// Makes a bitmap-filled shape show bitmap `to` (Swap Bitmap, and Find and Replace, ADR 0058): +/// a placed bitmap (a rectangle of the old bitmap's size, filled once at the origin) takes the +/// new one's size and, when it had the old one's name, its name; any other shape keeps its +/// outline and fill transform. `sizes` are every bitmap's name, width and height. False when `e` +/// isn't filled with a bitmap. +pub(crate) fn swap_bitmap_of(e: &mut anicraft_doc::Element, to: BitmapId, sizes: &std::collections::HashMap) -> bool { + let ElementKind::Shape(sh) = &mut e.kind else { return false }; + let Some(Paint::Bitmap { bitmap, repeat, matrix }) = &mut sh.fill else { return false }; + let old = *bitmap; + *bitmap = to; + if old == to { + return true; + } + if let (Some((name, w, h)), Some(new)) = (sizes.get(&old), sizes.get(&to)) + && !*repeat + && *matrix == anicraft_geom::Affine::IDENTITY + && *sh.path == anicraft_geom::Path::rect(0.0, 0.0, *w, *h) + { + sh.path = Arc::new(anicraft_geom::Path::rect(0.0, 0.0, new.1, new.2)); + if e.name == *name { + e.name.clone_from(&new.0); + } + } + true +} + +#[cfg(test)] +#[path = "library_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "place_tests.rs"] +mod place_tests; diff --git a/crates/engine/src/cmds_macro.rs b/crates/engine/src/cmds_macro.rs new file mode 100644 index 00000000..82cafb66 --- /dev/null +++ b/crates/engine/src/cmds_macro.rs @@ -0,0 +1,542 @@ +//! Saved commands (command macros, ADR 0097): steps picked in the History panel, kept as a +//! small JSON file and run again as one undo step. +//! +//! Every undo step remembers the commands it ran (`history::Recorded`). Save As Command turns +//! the picked steps into a saved command, rewriting what only makes sense in this document +//! (an element's or layer's id) to act on the current selection or active layer where the +//! command allows it, and refusing, with the step named, what can't be kept. A saved command +//! may call what a plug-in may (`plugin_may_call`) and never the `macro.*` commands, so it +//! can't recurse, touch files or the clipboard. +//! +//! A saved command is a file `/.json`: `{"format": "anicraft-command", +//! "version": 1, "steps": [{"cmd", "params", "label"}]}`. The file's name is the command's +//! name, so a shared file keeps whatever name it is given. `anicraft-cli run` scripts (a bare +//! JSON array of `{cmd, params}`) run the same way. Their order in the Commands menu is kept +//! in `/.order.json`. The shell passes the folder (its settings folder's `Commands`); +//! the engine never looks for it, as with templates. + +use crate::history::Recorded; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session, vfs}; +use serde_json::{Map, Value, json}; +use std::path::{Path, PathBuf}; + +/// The `format` a saved command's file declares. +pub const FORMAT: &str = "anicraft-command"; +/// The newest file version this build reads and the one it writes. +pub const VERSION: u64 = 1; +/// Most steps in one saved command. +pub const MAX_STEPS: usize = 1000; +/// Largest saved command file read. +pub const MAX_FILE_BYTES: u64 = 1 << 20; +/// Most saved commands listed from one folder. +pub const MAX_LISTED: usize = 500; +/// The file that keeps the order of the saved commands (a dot-name: no command is called that). +pub const ORDER_FILE: &str = ".order.json"; +/// Longest command id and step label kept from a file. +const MAX_CMD_CHARS: usize = 128; +const MAX_LABEL_CHARS: usize = 200; + +pub fn specs() -> Vec { + let c = |id, label, menu, params, mutates, run| CommandSpec { id, label, menu, shortcut: None, params, mutates, run }; + vec![ + c("macro.run", "Run Command…", "Commands", "{name + folder (a saved command) | path (a saved command's file, or a JSON array of {cmd, params}) | steps: [{cmd, params?, label?}], name? (for steps)} → {name, steps, results}: runs the steps in order as one undo step named after it. At the first step that fails nothing is changed and the error names the step. Steps may call what a plug-in may, never macro.*", true, run as crate::RunFn), + c("macro.list", "Manage Saved Commands…", "Commands", "{folder} → {commands: [{name, path, steps}], problems: [{file, error}]}: the saved commands in the folder, in their order (the app shows them in a window)", false, list), + c("macro.history", "List History Steps", "", "{} → {steps: [{index, label, undone, keep, commands?, why?, rewritten?}]}: every undo-history step as Save As Command keeps it: `keep` false says `why` it can't be kept; `rewritten` names params dropped so the step acts on the selection or active layer", false, history), + c("macro.save", "Save As Command…", "", "{folder, name, history: [index, ..] (as macro.history lists them) | steps: [{cmd, params?, label?}], confirm? (to replace a saved command of that name)} → {name, path, steps, rewritten}: keeps the steps as /.json, last in the list", false, save), + c("macro.rename", "Rename Saved Command", "", "{folder, name, to} → {name, from, path}: renames a saved command (its file); its place in the list stays", false, rename), + c("macro.delete", "Delete Saved Command", "", "{folder, name, confirm}: deletes a saved command's file (cannot be undone)", false, delete), + c("macro.move", "Move Saved Command", "", "{folder, name, index (its new place in the list, 0-based)}", false, move_to), + c("macro.import", "Add Saved Command from File", "", "{folder, path (a saved command's file), name? (default: the file's), confirm? (to replace one of that name)} → {name, path, steps}: checks it and copies it in, last in the list", false, import), + ] +} + +/// Whether a saved command may run command `id`, and if not, why: what a plug-in may, and +/// never a `macro.*` command (a saved command doesn't run, save or change saved commands). +pub fn macro_may_call(id: &str) -> std::result::Result<(), String> { + if id.split('.').next() == Some("macro") { + return Err("a saved command can't run, save or change saved commands".into()); + } + crate::cmds_plugin::plugin_may_call(id).map_err(|why| format!("{why} (a saved command may do only what a plug-in may)")) +} + +/// One step of a saved command. +#[derive(Clone, Debug, PartialEq)] +pub struct Step { + pub cmd: String, + /// Always an object. + pub params: Value, + /// What the History panel called it (may be empty: then the command's label). + pub label: String, +} + +impl Step { + /// The step's name in messages. + pub fn name(&self) -> String { + if !self.label.is_empty() { + return self.label.clone(); + } + crate::find_command(&self.cmd).map_or_else(|| self.cmd.clone(), |c| c.label.trim_end_matches('…').to_string()) + } +} + +/// A saved command: its name and steps. +#[derive(Clone, Debug, PartialEq)] +pub struct Macro { + pub name: String, + pub steps: Vec, +} + +impl Macro { + /// The file's content. + pub fn to_json(&self) -> Value { + let steps: Vec = self.steps.iter().map(|s| json!({"cmd": s.cmd, "params": s.params, "label": s.label})).collect(); + json!({"format": FORMAT, "version": VERSION, "steps": steps}) + } + + /// Reads a saved command named `name`: a file's object, or a bare array of steps (an + /// `anicraft-cli run` script). Every step is checked: a known command a saved command may + /// call, with object params. + pub fn from_json(v: &Value, name: &str) -> Result { + let steps = match v { + Value::Array(a) => a, + Value::Object(o) => { + if let Some(f) = o.get("format") + && f.as_str() != Some(FORMAT) + { + return Err(EngineError::Format(format!("not a saved command (its format is {f}, not \"{FORMAT}\")"))); + } + if let Some(v) = o.get("version") { + let v = v.as_u64().ok_or_else(|| EngineError::Format("a saved command's version is a whole number".into()))?; + if v > VERSION { + return Err(EngineError::Format(format!("this saved command was made by a newer AniCraft (version {v}); update AniCraft to run it"))); + } + } + o.get("steps").and_then(Value::as_array).ok_or_else(|| EngineError::Format("a saved command has a \"steps\" list".into()))? + } + _ => return Err(EngineError::Format("a saved command is a JSON object with \"steps\", or a list of {cmd, params}".into())), + }; + if steps.len() > MAX_STEPS { + return Err(EngineError::Format(format!("a saved command has at most {MAX_STEPS} steps (this one has {})", steps.len()))); + } + let mut out = Vec::with_capacity(steps.len()); + for (i, st) in steps.iter().enumerate() { + let n = i + 1; + let o = st.as_object().ok_or_else(|| EngineError::Format(format!("step {n} is not an object {{cmd, params}}")))?; + let cmd = o.get("cmd").or_else(|| o.get("command")).and_then(Value::as_str).ok_or_else(|| EngineError::Format(format!("step {n} has no \"cmd\"")))?; + if cmd.chars().count() > MAX_CMD_CHARS || crate::find_command(cmd).is_none() { + let shown: String = cmd.chars().take(40).collect(); + return Err(EngineError::Format(format!("step {n}: unknown command '{shown}'"))); + } + macro_may_call(cmd).map_err(|why| EngineError::Format(format!("step {n} ({cmd}) can't be in a saved command: {why}")))?; + let params = match o.get("params") { + None | Some(Value::Null) => Value::Object(Map::new()), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err(EngineError::Format(format!("step {n} ({cmd}): params are an object"))), + }; + let label: String = o.get("label").and_then(Value::as_str).unwrap_or("").chars().filter(|c| !c.is_control()).take(MAX_LABEL_CHARS).collect(); + out.push(Step { cmd: cmd.to_string(), params, label }); + } + Ok(Macro { name: name.to_string(), steps: out }) + } +} + +/// The file of the saved command called `name` in `folder`. +pub fn command_path(folder: &Path, name: &str) -> Result { + let name = crate::cmds_template::clean_name(name, "command")?; + Ok(folder.join(format!("{name}.json"))) +} + +/// Reads a saved command's file (its name is the file's). +pub fn load(path: &Path) -> Result { + let len = vfs::len(path).map_err(|e| EngineError::Io(std::io::Error::new(e.kind(), format!("{}: {e}", path.display()))))?; + if len > MAX_FILE_BYTES { + return Err(EngineError::Format(format!("{} is larger than a saved command can be ({} KiB at most)", path.display(), MAX_FILE_BYTES / 1024))); + } + let text = vfs::read_to_string(path)?; + // Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it. + let v: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| EngineError::Format(format!("{}: not JSON ({e})", path.display())))?; + let name = path.file_stem().map_or_else(|| "Command".to_string(), |n| n.to_string_lossy().into_owned()); + Macro::from_json(&v, &name) +} + +/// A saved command found in the folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Saved { + pub name: String, + pub path: PathBuf, + pub steps: usize, +} + +fn read_order(folder: &Path) -> Vec { + let path = folder.join(ORDER_FILE); + if vfs::len(&path).map_or(true, |n| n > MAX_FILE_BYTES) { + return Vec::new(); + } + let v: Value = vfs::read_to_string(&path).ok().and_then(|t| serde_json::from_str(t.trim_start_matches('\u{feff}')).ok()).unwrap_or(Value::Null); + v.as_array().into_iter().flatten().filter_map(Value::as_str).take(MAX_LISTED).map(str::to_string).collect() +} + +fn write_order(folder: &Path, names: &[String]) -> Result<()> { + let text = serde_json::to_string_pretty(names).map_err(|e| EngineError::Format(e.to_string()))?; + vfs::write(&folder.join(ORDER_FILE), text)?; + Ok(()) +} + +/// The saved commands in `folder`, in their order (then by name), and the files that aren't +/// saved commands with why: `(file name, error)`. +pub fn saved_commands(folder: &Path) -> (Vec, Vec<(String, String)>) { + let order: Vec = read_order(folder).into_iter().map(|n| n.to_lowercase()).collect(); + let mut found = Vec::new(); + let mut problems = Vec::new(); + for f in vfs::list(folder, MAX_LISTED * 2) { + let Some(stem) = f.file_stem().map(|n| n.to_string_lossy().into_owned()) else { continue }; + if stem.starts_with('.') || !f.extension().is_some_and(|e| e.eq_ignore_ascii_case("json")) || !vfs::is_file(&f) { + continue; + } + let file = f.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + match load(&f) { + Ok(m) if found.len() < MAX_LISTED => found.push(Saved { name: m.name, path: f, steps: m.steps.len() }), + Ok(_) => {} + Err(e) => problems.push((file, e.to_string())), + } + } + found.sort_by_key(|s| (order.iter().position(|o| *o == s.name.to_lowercase()).unwrap_or(usize::MAX), s.name.to_lowercase())); + problems.sort(); + (found, problems) +} + +fn folder(p: &Value) -> Result { + let f = str_req(p, "folder")?; + if f.trim().is_empty() { + return Err(EngineError::Param("name the saved commands' folder".into())); + } + Ok(PathBuf::from(f)) +} + +/// The saved command file the params name (`folder` and `name`). +pub(crate) fn target(p: &Value) -> Result { + command_path(&folder(p)?, str_req(p, "name")?) +} + +/// Where `macro.import` copies its file to. +pub(crate) fn import_target(p: &Value) -> Result { + let from = PathBuf::from(str_req(p, "path")?); + let name = match opt_str(p, "name")? { + Some(n) => n.to_string(), + None => from.file_stem().map(|n| n.to_string_lossy().into_owned()).ok_or_else(|| EngineError::Param("the file has no name".into()))?, + }; + command_path(&folder(p)?, &name) +} + +fn name_of(path: &Path) -> String { + path.file_stem().map_or_else(String::new, |n| n.to_string_lossy().into_owned()) +} + +/// The saved command the params name: by `name` in `folder`, a file's `path`, or `steps`. +fn resolve(p: &Value) -> Result { + if let Some(steps) = p.get("steps") { + let name = opt_str(p, "name")?.map_or_else(|| "Saved command".to_string(), |n| n.chars().filter(|c| !c.is_control()).take(crate::cmds_template::MAX_NAME_CHARS).collect()); + return Macro::from_json(steps, &name); + } + if let Some(path) = opt_str(p, "path")? { + return load(Path::new(path)); + } + let path = target(p).map_err(|e| EngineError::Param(format!("name a saved command (name and folder), a file (path) or steps: {e}")))?; + if !vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no saved command “{}”", name_of(&path)))); + } + load(&path) +} + +fn run(s: &mut Session, p: &Value) -> Result { + let m = resolve(p)?; + if m.steps.is_empty() { + return Err(EngineError::State(format!("“{}” has no steps to run", m.name))); + } + let n = m.steps.len(); + let mut results = Vec::with_capacity(n); + for (i, st) in m.steps.iter().enumerate() { + // (Checked when it was read; the rule is the run's, so it is checked here too.) + let r = macro_may_call(&st.cmd).map_err(EngineError::State).and_then(|()| s.execute_nested(&st.cmd, &st.params)); + match r { + Ok(v) => results.push(v), + // The session puts the document back as it was before the run. + Err(e) => return Err(EngineError::State(format!("“{}” stopped at step {} of {n} ({}): {e}. Nothing was changed.", m.name, i + 1, st.name()))), + } + } + s.step_label = Some(m.name.clone()); + // History keeps the steps, so a run can itself be saved again with other steps. + s.record_as = Some(m.steps.iter().map(|st| Recorded::new(&st.cmd, &st.params)).collect()); + Ok(json!({"name": m.name, "steps": n, "results": results})) +} + +fn list(_: &mut Session, p: &Value) -> Result { + let (found, problems) = saved_commands(&folder(p)?); + let commands: Vec = found.iter().map(|c| json!({"name": c.name, "path": c.path.display().to_string(), "steps": c.steps})).collect(); + let problems: Vec = problems.iter().map(|(f, e)| json!({"file": f, "error": e})).collect(); + Ok(json!({"commands": commands, "problems": problems})) +} + +/// Params naming who a step acts on: dropped, where the command then acts on the selection +/// (or, for layers, the active layer), so the step replays elsewhere. +const TARGETS: &[&str] = &["layer", "layers", "element", "elements", "id", "ids", "shape", "path", "symbol"]; +/// Params naming things that exist only in this document: Library items, folders and bones. +const FIXED: &[&str] = &["bitmap", "sound", "folder", "bone", "parent", "items"]; + +/// What a param names, in a sentence. +fn noun(key: &str) -> &'static str { + match key { + "layer" | "layers" => "particular layers", + "symbol" | "bitmap" | "sound" | "folder" | "items" => "particular Library items", + "bone" | "parent" | "from" | "to" => "particular bones", + _ => "particular objects", + } +} + +/// Whether the command's params doc makes `key` optional (`key?`), and, but for layers, says +/// it defaults to what is selected. +fn defaults_to_selection(doc: &str, key: &str) -> bool { + let pat = format!("{key}?"); + doc.match_indices(&pat).any(|(i, _)| { + let whole = doc.get(..i).and_then(|b| b.chars().next_back()).is_none_or(|c| !c.is_alphanumeric() && c != '_'); + let after: String = doc.get(i + pat.len()..).unwrap_or("").chars().take(90).collect(); + whole && (key.starts_with("layer") || after.contains("select")) + }) +} + +/// Whether a recorded command can be kept: the params it would drop (they name this +/// document's layers or objects and the command can act on the selection or active layer +/// instead), or why it can't be kept. Reads only: listing a long history costs no copies. +fn check(cmd: &str, params: &Value) -> std::result::Result, String> { + macro_may_call(cmd)?; + let spec = crate::find_command(cmd).ok_or_else(|| format!("'{cmd}' is not a command any more"))?; + let mut dropped = Vec::new(); + for (k, v) in params.as_object().into_iter().flatten() { + let fixed = FIXED.contains(&k.as_str()) || (cmd.starts_with("bone.") && matches!(k.as_str(), "from" | "to")) || (cmd == "library.move" && k == "to"); + let target = TARGETS.iter().find(|t| **t == k.as_str()); + match target { + _ if v.is_null() => {} + Some(t) if !fixed && defaults_to_selection(spec.params, t) => dropped.push(*t), + None if !fixed => {} + _ => return Err(format!("it works on {} of this document", noun(k))), + } + } + Ok(dropped) +} + +/// A recorded command as a saved command keeps it: its params without what names this +/// document's layers and objects (and which of those went), or why it can't be kept. +pub fn portable(cmd: &str, params: &Value) -> std::result::Result<(Value, Vec), String> { + let dropped = check(cmd, params)?; + let out: Map = params.as_object().into_iter().flatten().filter(|(k, _)| !dropped.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + Ok((Value::Object(out), dropped.into_iter().map(str::to_string).collect())) +} + +/// An undo step as a saved command keeps it: its steps and the params dropped, or why not. +fn keep_step(label: &str, cmds: Option<&[Recorded]>) -> std::result::Result<(Vec, Vec), String> { + let cmds = usable(cmds)?; + let mut steps = Vec::with_capacity(cmds.len()); + let mut dropped = Vec::new(); + for r in cmds { + let (params, gone) = portable(&r.cmd, &r.params)?; + for g in gone { + if !dropped.contains(&g) { + dropped.push(g); + } + } + steps.push(Step { cmd: r.cmd.clone(), params, label: label.to_string() }); + } + Ok((steps, dropped)) +} + +fn usable(cmds: Option<&[Recorded]>) -> std::result::Result<&[Recorded], String> { + let cmds = cmds.ok_or("it ran too many commands to keep (a very long drag?)")?; + if cmds.is_empty() { + return Err("it has nothing to run again".into()); + } + Ok(cmds) +} + +/// [`keep_step`] without building the steps: how many commands, and the params dropped. +fn check_step(cmds: Option<&[Recorded]>) -> std::result::Result<(usize, Vec), String> { + let cmds = usable(cmds)?; + let mut dropped: Vec = Vec::new(); + for r in cmds { + for g in check(&r.cmd, &r.params)? { + if !dropped.iter().any(|d| d == g) { + dropped.push(g.to_string()); + } + } + } + Ok((cmds.len(), dropped)) +} + +/// What dropped params mean for the step, in a sentence. +fn rewritten_note(dropped: &[String]) -> Option { + let layers = dropped.iter().any(|d| d.starts_with("layer")); + let objects = dropped.iter().any(|d| !d.starts_with("layer")); + match (objects, layers) { + (true, true) => Some("acts on the selection and the active layer".into()), + (true, false) => Some("acts on the selection".into()), + (false, true) => Some("acts on the active layer".into()), + (false, false) => None, + } +} + +fn history(s: &mut Session, _: &Value) -> Result { + let done = s.history().undo_len(); + let steps: Vec = s + .history() + .steps() + .enumerate() + .map(|(i, (label, cmds))| { + let mut v = json!({"index": i, "label": label, "undone": i >= done}); + match check_step(cmds) { + Ok((n, dropped)) => { + v["keep"] = json!(true); + v["commands"] = json!(n); + if let Some(note) = rewritten_note(&dropped) { + v["rewritten"] = json!(note); + } + } + Err(why) => { + v["keep"] = json!(false); + v["why"] = json!(why); + } + } + v + }) + .collect(); + Ok(json!({"steps": steps})) +} + +/// The steps the params ask to save: history steps by index, or steps given outright; and +/// what was rewritten, a sentence per step. +fn steps_to_save(s: &Session, p: &Value) -> Result<(Vec, Vec)> { + if let Some(v) = p.get("steps") { + return Ok((Macro::from_json(v, "")?.steps, Vec::new())); + } + let mut picked = opt_u64_list(p, "history")?.ok_or_else(|| EngineError::Param("pick the steps to keep: history (as macro.history lists them) or steps".into()))?; + picked.sort_unstable(); + picked.dedup(); + if picked.is_empty() { + return Err(EngineError::Param("pick at least one step to keep".into())); + } + let all: Vec<(&str, Option<&[Recorded]>)> = s.history().steps().collect(); + let mut steps = Vec::new(); + let mut notes = Vec::new(); + for i in picked { + let (label, cmds) = usize::try_from(i).ok().and_then(|i| all.get(i).copied()).ok_or_else(|| EngineError::Param(format!("there is no history step {i} (macro.history lists them)")))?; + let (kept, dropped) = keep_step(label, cmds).map_err(|why| EngineError::State(format!("step {} “{label}” can't be kept: {why}", i + 1)))?; + if let Some(note) = rewritten_note(&dropped) { + notes.push(json!({"index": i, "label": label, "note": note})); + } + steps.extend(kept); + if steps.len() > MAX_STEPS { + return Err(EngineError::State(format!("a saved command has at most {MAX_STEPS} steps"))); + } + } + Ok((steps, notes)) +} + +/// Adds `name` to the end of the folder's order (or leaves it where it is). +fn order_add(folder: &Path, name: &str) -> Result<()> { + let mut order = read_order(folder); + if !order.iter().any(|o| o.to_lowercase() == name.to_lowercase()) { + // The order holds every listed command, so a new one goes after all of them. + let (found, _) = saved_commands(folder); + let mut names: Vec = found.into_iter().map(|c| c.name).filter(|n| n.to_lowercase() != name.to_lowercase()).collect(); + names.push(name.to_string()); + order = names; + } + write_order(folder, &order) +} + +fn write_macro(path: &Path, m: &Macro) -> Result<()> { + if let Some(dir) = path.parent() { + vfs::create_dir_all(dir)?; + } + let text = serde_json::to_string_pretty(&m.to_json()).map_err(|e| EngineError::Format(e.to_string()))?; + vfs::write(path, text)?; + Ok(()) +} + +fn save(s: &mut Session, p: &Value) -> Result { + let path = target(p)?; + let (steps, rewritten) = steps_to_save(s, p)?; + if steps.is_empty() { + return Err(EngineError::Param("a saved command needs at least one step".into())); + } + let m = Macro { name: name_of(&path), steps }; + write_macro(&path, &m)?; + if let Some(dir) = path.parent() { + order_add(dir, &m.name)?; + } + Ok(json!({"name": m.name, "path": path.display().to_string(), "steps": m.steps.len(), "rewritten": rewritten})) +} + +fn import(_: &mut Session, p: &Value) -> Result { + let to = import_target(p)?; + let from = PathBuf::from(str_req(p, "path")?); + let m = Macro { name: name_of(&to), ..load(&from)? }; + write_macro(&to, &m)?; + if let Some(dir) = to.parent() { + order_add(dir, &m.name)?; + } + Ok(json!({"name": m.name, "path": to.display().to_string(), "steps": m.steps.len()})) +} + +fn existing(p: &Value) -> Result { + let path = target(p)?; + if !vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no saved command “{}”", name_of(&path)))); + } + Ok(path) +} + +fn rename(_: &mut Session, p: &Value) -> Result { + let from = existing(p)?; + let dir = folder(p)?; + let to = command_path(&dir, str_req(p, "to")?)?; + let (old, new) = (name_of(&from), name_of(&to)); + if old == new { + return Ok(json!({"name": new, "from": old})); + } + // A change of case only is the same file on Windows and macOS. + if old.to_lowercase() != new.to_lowercase() && vfs::exists(&to) { + return Err(EngineError::State(format!("there is already a saved command “{new}”"))); + } + vfs::rename(&from, &to)?; + let mut order = read_order(&dir); + for o in &mut order { + if o.to_lowercase() == old.to_lowercase() { + o.clone_from(&new); + } + } + write_order(&dir, &order)?; + Ok(json!({"name": new, "from": old, "path": to.display().to_string()})) +} + +fn delete(_: &mut Session, p: &Value) -> Result { + let path = existing(p)?; + let dir = folder(p)?; + let name = name_of(&path); + vfs::remove_file(&path)?; + let order: Vec = read_order(&dir).into_iter().filter(|o| o.to_lowercase() != name.to_lowercase()).collect(); + write_order(&dir, &order)?; + Ok(json!({"deleted": name})) +} + +fn move_to(_: &mut Session, p: &Value) -> Result { + let path = existing(p)?; + let dir = folder(p)?; + let name = name_of(&path); + let index = opt_u64(p, "index")?.ok_or_else(|| EngineError::Param("give the new place: index (0-based)".into()))?; + let (found, _) = saved_commands(&dir); + let mut names: Vec = found.into_iter().map(|c| c.name).filter(|n| n.to_lowercase() != name.to_lowercase()).collect(); + let at = usize::try_from(index).unwrap_or(usize::MAX).min(names.len()); + names.insert(at, name.clone()); + write_order(&dir, &names)?; + Ok(json!({"name": name, "index": at})) +} diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index 209bf9f7..6ee3ee81 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -50,6 +50,9 @@ pub struct ClipLayer { pub layer: LayerId, pub name: String, pub elements: Vec, + /// The keyframe (its first frame) it was copied from with Edit Multiple Frames (ADR 0051), + /// where Paste in Place on Multiple Frames puts it back; `None` for a copy on one frame. + pub frame: Option, } impl Clipboard { @@ -65,17 +68,19 @@ impl Clipboard { } } -fn symbol_refs(e: &Element) -> Option { +/// The symbols `e` places: itself, or what is inside it as a group (ADR 0073). +fn symbol_refs(e: &Element) -> Vec { match &e.kind { - ElementKind::Symbol { symbol, .. } => Some(*symbol), - ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera => None, + ElementKind::Symbol { symbol, .. } => vec![*symbol], + ElementKind::Group { .. } => anicraft_doc::expand_groups(std::slice::from_ref(&Arc::new(e.clone()))).iter().filter_map(|m| if let ElementKind::Symbol { symbol, .. } = m.kind { Some(symbol) } else { None }).collect(), + ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera => Vec::new(), } } /// Symbols reachable from `roots` (bounded walk; libraries may be cyclic). pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec> { let mut seen: HashSet = HashSet::new(); - let mut stack: Vec = roots.iter().filter_map(symbol_refs).collect(); + let mut stack: Vec = roots.iter().flat_map(symbol_refs).collect(); let mut out = Vec::new(); while let Some(id) = stack.pop() { if !seen.insert(id) || seen.len() > 10_000 { @@ -84,7 +89,7 @@ pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec let Some(sym) = s.doc.library.iter().find(|x| x.id == id) else { continue }; for l in &sym.timeline.layers { for k in &l.keyframes { - stack.extend(k.elements.iter().filter_map(|e| symbol_refs(e))); + stack.extend(k.elements.iter().flat_map(|e| symbol_refs(e))); } } out.push(sym.clone()); @@ -101,9 +106,9 @@ fn copy(s: &mut Session, _: &Value) -> Result { let mut copied = Vec::with_capacity(layers.len()); for l in layers { let elements: Vec = s.elements_on(l).iter().filter(|e| s.selection.contains(l, e.id)).map(|e| (**e).clone()).collect(); - let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); if !elements.is_empty() { - copied.push(ClipLayer { layer: l, name, elements }); + copied.push(ClipLayer { layer: l, name, elements, frame: None }); } } let all: Vec = copied.iter().flat_map(|c| c.elements.iter().cloned()).collect(); @@ -141,32 +146,46 @@ fn clip_element_bounds(s: &Session, e: &Element) -> Rect { /// layers below it, in order, with missing layers created at the bottom named after the copied /// ones, as Paste Frames does. fn paste_targets(s: &mut Session) -> Result> { - let n = s.clipboard.layers.len(); + // Each layer the artwork came from once (a copy with Edit Multiple Frames has one entry per + // keyframe, ADR 0051), in order. + let mut src: Vec<(LayerId, String)> = Vec::new(); + for c in &s.clipboard.layers { + if !src.iter().any(|(l, _)| *l == c.layer) { + src.push((c.layer, c.name.clone())); + } + } + let dst = layer_targets(s, &src)?; + Ok(s.clipboard.layers.iter().map(|c| src.iter().position(|(l, _)| *l == c.layer).and_then(|i| dst.get(i)).copied().unwrap_or(s.layer)).collect()) +} + +/// [`paste_targets`] for each source layer (its id and name). +fn layer_targets(s: &mut Session, src: &[(LayerId, String)]) -> Result> { + let n = src.len(); if n <= 1 { return Ok(vec![s.layer]); } - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let drawable = |s: &Session, l: &Layer| s.selectable(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature); - let home: Vec = s.clipboard.layers.iter().filter_map(|c| tl.layer(c.layer).filter(|l| l.name == c.name && drawable(s, l)).map(|l| l.id)).collect(); + let home: Vec = src.iter().filter_map(|(id, name)| tl.layer(*id).filter(|l| l.name == *name && drawable(s, l)).map(|l| l.id)).collect(); if home.len() == n { return Ok(home); } let at = s.active_layer_index().unwrap_or(0); let mut out = vec![s.layer]; out.extend(tl.layers.iter().skip(at + 1).filter(|l| drawable(s, l)).map(|l| l.id).take(n - 1)); - let names: Vec = s.clipboard.layers.iter().skip(out.len()).map(|c| c.name.clone()).collect(); + let names: Vec = src.iter().skip(out.len()).map(|(_, name)| name.clone()).collect(); for name in names { - 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()); - let count = s.doc.timeline(s.scene).layers.len(); + let count = s.timeline().layers.len(); let mut layer = Layer::new(id, name); if let Some(k) = layer.keyframe_mut(0) { k.duration = s.frame_count().max(1); } layer.color = crate::cmds_timeline::layer_color(count + 1); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; tl.layers.push(Arc::new(layer)); tl.repair_masks(); out.push(id); @@ -174,10 +193,19 @@ fn paste_targets(s: &mut Session) -> Result> { Ok(out) } +/// Whether pasting the clipboard would put a symbol inside itself: inside an open symbol, an +/// instance of it (or of one using it). +pub(crate) fn clipboard_nests(s: &Session) -> bool { + s.clipboard.layers.iter().flat_map(|c| &c.elements).any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { symbol, .. } if crate::editing::would_nest(s, symbol))) +} + fn paste_with(s: &mut Session, offset: Vec2) -> Result { if s.clipboard.is_empty() { return Err(EngineError::State("the clipboard is empty".into())); } + if clipboard_nests(s) { + return Err(EngineError::State("a symbol can't be pasted inside itself".into())); + } import_symbols(s, &s.clipboard.symbols.clone()); let targets = paste_targets(s)?; let copied = s.clipboard.layers.clone(); @@ -191,21 +219,27 @@ fn paste_with(s: &mut Session, offset: Vec2) -> Result { sel.extend_on(layer, fresh); } s.selection = sel; - if let Some(&first) = targets.first() - && targets.len() > 1 + let mut layers: Vec = Vec::new(); + for l in &targets { + if !layers.contains(l) { + layers.push(*l); + } + } + if let Some(&first) = layers.first() + && layers.len() > 1 { s.layer = first; } let mut v = json!({"pasted": all, "merged": merged}); - if targets.len() > 1 { - v["layers"] = json!(targets.iter().map(|l| l.0).collect::>()); + if layers.len() > 1 { + v["layers"] = json!(layers.iter().map(|l| l.0).collect::>()); } Ok(v) } /// Pastes `elements` moved by `offset` into the active layer's keyframe at the playhead; their /// new ids, and whether raw shapes merged. -fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec, bool)> { +pub(crate) fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec, bool)> { let mut fresh = Vec::new(); let mut out = Vec::new(); let mut raw = Vec::new(); diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 2f7f6cc2..0c294c86 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -6,11 +6,20 @@ //! [`begin_edit`] swaps the target for how it looks at the playhead, and after the command //! [`finish_edit`] turns whatever changed in its transform or colour effect into property keys //! and puts the base object back (with any other change, a new fill say, kept). +//! +//! Filters (ADR 0092): a filter's numbers tween as properties too, addressed by the filter's place +//! (`filter.0.blur_x`). An edit of a filter's number at the playhead keys it there; an edit that +//! reorders, removes or adds filters takes the tracks along with their filters. +//! +//! On a motion path, moving the object at a frame pins the path there (ADR 0049): the anchor +//! pinned to that frame moves (an end, at the first or last position key), or a new anchor is +//! added where the object is, pinned to the frame, and moved; after the last position key the +//! path carries on to where the object was put. use crate::cmds_timeline::target; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Property, Props}; +use anicraft_doc::{Element, ElementId, ElementKind, FilterEntry, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props, filter_properties, own_value}; use anicraft_geom::{Affine, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -18,10 +27,10 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|tint, value (px, %, °), frame?, layer?}", true, set_key as crate::RunFn), + c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255)|filter.. (a number of the object's filter at that place, 0 the first; ADR 0092), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)", true, set_key as crate::RunFn), c("motion.remove_key", "Remove Property Keyframe", "", None, "{property? (default: every property), frame?, layer?}", true, remove_key), - c("motion.set_ease", "Property Ease", "", None, "{easing, property? (default: every property), frame? (inside the segment), layer?}", true, set_ease), - c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path and where the object is", false, info), + c("motion.set_ease", "Property Ease", "", None, "{easing (as timeline.set_easing takes it, saved eases too), property? (default: every property), frame? (inside the segment), layer?}", true, set_ease), + c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is", false, info), c("motion.set_path", "Edit Motion Path", "", None, "{d: SVG path data in stage space (its first subpath; ends are the start and end positions), layer?, frame?}", true, set_path), c("motion.clear_path", "Remove Motion Path", "", None, "{layer?, frame?}: back to the straight path the X/Y curves trace", true, clear_path), c("motion.orient", "Orient to Path", "", None, "{orient: bool, layer?, frame?}: turn the object as its motion path turns", true, orient), @@ -29,6 +38,8 @@ pub fn specs() -> Vec { c("motion.delete_points", "Delete Motion Path Points", "", None, "{anchors: [index, ..] (as motion.info lists them; the ends stay), layer?, frame?}: the path refits through the rest", true, delete_points), c("motion.convert_point", "Convert Motion Path Point", "", None, "{anchor, smooth: bool, layer?, frame?}: smooth (handles in line) or corner (handles on the anchor)", true, convert_point), c("motion.move_path", "Move Motion Path", "", None, "{dx, dy, layer?, frame?}: the whole path with its object, keeping the timing", true, move_path), + c("motion.pin_point", "Pin Motion Path Point", "", None, "{anchor? (default: a new anchor where the object is), frame? (the frame to pin it to, between the first and last position keys), layer?}: the object passes the anchor exactly on that frame → {anchor, frame, pins}", true, pin_point), + c("motion.unpin_point", "Unpin Motion Path Point", "", None, "{anchor? | frame?, layer?}: the anchor shapes the path only again; the X/Y keys of its frame go → {anchor, frame, pins}", true, unpin_point), ] } @@ -68,7 +79,7 @@ pub(crate) fn begin_edit(layer: LayerId, kf: &mut Keyframe, frame: u32) -> Optio /// the base back. On the span's first frame a property without keys changes the base itself. pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { let scene = s.scene; - let Some(layer) = s.doc.timeline_mut(scene).layer_mut(e.layer) else { return }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).ok().and_then(|tl| tl.layer_mut(e.layer)) else { return }; let Some(kf) = layer.keyframe_starting_at(e.start).and_then(|i| layer.keyframe_mut(i)) else { return }; let Some(idx) = kf.elements.iter().position(|x| x.id == e.target) else { return }; let Some(after) = kf.elements.get(idx).map(|x| (**x).clone()) else { return }; @@ -104,7 +115,7 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { let v = was.get(p) + d; if e.offset == 0 && m.track(p).is_none() { new_base.set(p, v); - if matches!(p, Property::Alpha | Property::Tint) { + if p.style().is_some() { base_color = true; } else { base_xf = true; @@ -113,9 +124,13 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { m.set_key(p, e.offset, v, base_props.get(p)); } } - let tracks_xf = m.tracks.iter().any(|t| !matches!(t.property, Property::Alpha | Property::Tint)); - let tracks_color = m.tracks.iter().any(|t| matches!(t.property, Property::Alpha | Property::Tint)); + let tracks_xf = m.tracks.iter().any(|t| t.property.is_transform()); + let tracks_color = m.tracks.iter().any(|t| t.property.style().is_some()); + let filters = key_filters(m, &e, &after); let mut base = after; + if let (Some(f), ElementKind::Symbol { filters: slot, .. }) = (filters, &mut base.kind) { + *slot = f; + } // Exact where nothing is keyed on the first frame: the edited object is the new base. base.transform = match (base_xf, e.offset == 0 && !tracks_xf) { (true, true) => base.transform, @@ -124,27 +139,107 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { }; base.color = match (base_color, e.offset == 0 && !tracks_color) { (true, true) => base.color, - (true, false) => ColorEffect { alpha: (new_base.get(Property::Alpha) / 100.0).clamp(0.0, 1.0), tint: base.color.tint, tint_amount: (new_base.get(Property::Tint) / 100.0).clamp(0.0, 1.0) }, - (false, _) => ColorEffect { tint: base.color.tint, ..e.base.color }, + // The edit's style, from the new values (ADR 0056). + (true, false) => new_base.color_effect(&[base.color.style()]), + (false, _) => e.base.color, }; if let Some(slot) = kf.elements.get_mut(idx) { *slot = Arc::new(base); } } -/// Most bends [`move_on_path`] makes to land the object where it was put; each takes 15–35% -/// off the miss on typical paths (the path's length changes as it bends, sliding the object). +/// The filters of an edited target (ADR 0092). The command saw them as they look at the +/// playhead (`e.before`) and left them as `after` has them. When the list kept its shape (the +/// same kinds in the same order), each number it changed becomes a key at the playhead (on the +/// span's first frame, an untracked number changes the object's own), and the tracked numbers +/// keep the object's own values underneath. When the shape changed (filters reordered, removed +/// or added), each filter is found again by what it holds, its tracks go where it went, and +/// those of filters that went go too. The base's new list, or `None` when there are no filters +/// to look after. +fn key_filters(m: &mut MotionTween, e: &MotionEdit, after: &Element) -> Option> { + let list = |el: &Element| match &el.kind { + ElementKind::Symbol { filters, .. } => Some(filters.clone()), + _ => None, + }; + let (before, base, mut now) = (list(&e.before)?, list(&e.base)?, list(after)?); + if !anicraft_doc::filters_pair_up(&before, &now) { + // Where each filter went: the first one left that holds the same. + let mut taken = vec![false; now.len()]; + let map: Vec> = before + .iter() + .map(|b| { + let i = now.iter().enumerate().position(|(i, n)| !taken.get(i).copied().unwrap_or(true) && n.filter == b.filter)?; + if let Some(t) = taken.get_mut(i) { + *t = true; + } + Some(i) + }) + .collect(); + m.remap_filters(&map); + // A filter that moved is the base's underneath (with its switch as the edit left it), + // not the playhead's. + for (old, new) in map.iter().enumerate() { + if let (Some(n), Some(b)) = (new, base.get(old)) + && let Some(slot) = now.get_mut(*n) + { + let enabled = slot.enabled; + *slot = FilterEntry { enabled, ..b.clone() }; + } + } + return Some(now); + } + for (slot, (was, is)) in before.iter().zip(&now).enumerate().take(usize::from(anicraft_doc::MAX_FILTER_SLOTS)) { + for ¶m in is.filter.params() { + let p = Property::Filter(anicraft_doc::FilterProp { slot: slot as u8, param }); + let (Some(v0), Some(v1)) = (was.filter.param(param), is.filter.param(param)) else { continue }; + if (v1 - v0).abs() > 1e-4 && !(e.offset == 0 && m.track(p).is_none()) { + let own = base.get(slot).and_then(|b| b.filter.param(param)).unwrap_or(v0); + m.set_key(p, e.offset, v1, own); + } + } + } + // Tracked numbers: the object's own underneath (the curves give the rest). + for t in &m.tracks { + if let Some(f) = t.property.filter() + && let (Some(slot), Some(own)) = (now.get_mut(usize::from(f.slot)), base.get(usize::from(f.slot)).and_then(|b| b.filter.param(f.param))) + { + slot.filter.set_param(f.param, own); + } + } + Some(now) +} + +/// Most bends [`move_on_path`] makes to land the object where it was put off the path; each +/// takes 15–35% off the miss on typical paths (the path's length changes as it bends, sliding the +/// object). const BEND_STEPS: usize = 48; -/// The object on a motion path was moved by `d` at `offset`: at or before the first position -/// key the path's start moves, at or after the last its end, in between the path bends so it -/// passes where the object was put (a few bends, as the path's length changes with each); -/// without position keys the whole path moves. +/// The object on a motion path was moved by `d` at `offset` (ADR 0049): the anchor pinned to +/// that frame moves with it (before the first position key, the start); after the last position +/// key the path carries on to where it was put; in between, a new anchor where the object is gets +/// pinned to the frame and moved. Where the object is off the path (an overshooting ease) the +/// path bends instead (ADR 0030); without position keys the whole path moves. fn move_on_path(m: &mut MotionTween, base: &Props, offset: u32, d: Vec2, last: u32) { let Some(mut path) = m.path.clone() else { return }; - let f = offset as f32; match m.position_range() { - Some((f0, f1)) if f1 > f0 && offset > f0 && offset < f1 => { + Some((f0, f1)) if f1 > f0 => { + let pinned = m.pinned_anchors(base).into_iter().find(|p| p.frame == offset).map(|p| p.anchor as usize); + if let Some(a) = pinned.or((offset < f0).then_some(0)) { + m.move_anchor(a, d, base, last); + return; + } + if offset > f1 { + let end = anicraft_doc::motion::path_ends(&path).map(|(_, b)| b).unwrap_or_default(); + if !m.extend_to(offset, end + d, base) { + m.move_anchor(path.cmds.len().saturating_sub(1), d, base, last); + } + return; + } + if let Ok(a) = m.pin_here(offset, base) { + m.move_anchor(a, d, base, last); + return; + } + let f = offset as f32; let Some(target) = m.on_path(base).map(|op| op.point(f) + d) else { return }; let mut trial = m.clone(); for _ in 0..BEND_STEPS { @@ -160,10 +255,6 @@ fn move_on_path(m: &mut MotionTween, base: &Props, offset: u32, d: Vec2, last: u trial.path = Some(path.clone()); } } - Some((f0, f1)) if f1 > f0 => { - let anchor = if offset <= f0 { 0 } else { path.cmds.len().saturating_sub(1) }; - path.move_anchor(anchor, d); - } _ => path = path.transformed(&Affine::translate(d.x, d.y)), } m.set_path(&path, base, last); @@ -182,7 +273,7 @@ fn set_path(s: &mut Session, p: &Value) -> Result { let path = anicraft_geom::svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; if last == 0 && m.position_range().is_none_or(|(a, b)| a == b) { return Err(EngineError::State("a one-frame span has no room to move along a path: make the span longer first".into())); @@ -190,33 +281,61 @@ fn set_path(s: &mut Session, p: &Value) -> Result { if !m.set_path(&path, &base, last) { return Err(EngineError::Param("param 'd' needs a segment of some length, with finite points within ±1000000".into())); } - Ok(path_summary(m)) + Ok(path_summary(m, start, &base)) } -fn path_summary(m: &MotionTween) -> Value { - let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient}) }; +fn path_summary(m: &MotionTween, start: u32, base: &Props) -> Value { + let pins = pins_json(m, start, base); + let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient, "pins": pins}) }; let len = anicraft_geom::walk::CurveWalk::new(path).map_or(0.0, |w| w.length()); let (a, b) = anicraft_doc::motion::path_ends(path).unwrap_or_default(); // Anchor `i` is path command `i` (a motion path is a move and cubics). let anchors: Vec<[f32; 2]> = path.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect(); - json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient}) + json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient, "pins": pins}) +} + +/// The anchors tied to frames (ADR 0049), ends included: `{anchor, frame, end, at}`, frames +/// counted from the timeline's start. +fn pins_json(m: &MotionTween, start: u32, base: &Props) -> Value { + let path = m.path.clone().or_else(|| m.path_from_tracks(base)); + let pins = m.pinned_anchors(base); + let n = pins.len(); + let v: Vec = pins + .iter() + .enumerate() + .map(|(i, q)| { + let at = path.as_ref().and_then(|p| p.point(q.anchor as usize, anicraft_geom::edit::ANCHOR)).map(|v| json!([v.x, v.y])); + json!({"anchor": q.anchor, "frame": start + q.frame, "end": i == 0 || i + 1 == n, "at": at}) + }) + .collect(); + Value::Array(v) } /// Edits the motion path at the target frame with `edit`: the tween's own path, or the straight -/// one its X/Y curves trace (which the edit makes its own, as on the stage). The ends' keys stay -/// unless the edit moved an end, so the timing is kept. Returns what `edit` returned and the -/// path's summary. -fn edit_path(s: &mut Session, p: &Value, edit: impl FnOnce(&mut anicraft_geom::Path) -> Result) -> Result<(T, Value)> { +/// one its X/Y curves trace (which the edit makes its own, as on the stage, its position keys +/// pinned to their anchors). The ends' and pins' keys stay unless the edit moved their anchors, +/// so the timing is kept. Returns what `edit` returned and the path's summary. +fn edit_path(s: &mut Session, p: &Value, edit: impl FnOnce(&mut MotionTween) -> Result) -> Result<(T, Value)> { let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; - let mut path = m.path.clone().or_else(|| m.path_from_tracks(&base)).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?; - let out = edit(&mut path)?; + if m.path.is_none() { + let (path, pins) = m.path_and_pins_from_tracks(&base).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?; + m.path = Some(path); + m.pins = pins; + } + let out = edit(m)?; + let path = m.path.clone().ok_or_else(|| EngineError::State("the motion path went away".into()))?; if !m.set_path(&path, &base, last) { return Err(EngineError::State("that would leave the motion path with no length".into())); } - Ok((out, path_summary(m))) + Ok((out, path_summary(m, start, &base))) +} + +/// The motion path being edited (there is one inside [`edit_path`]). +fn path_mut(m: &mut MotionTween) -> Result<&mut anicraft_geom::Path> { + m.path.as_mut().ok_or_else(|| EngineError::State("no motion path here".into())) } /// An anchor index param, checked against the path. @@ -242,7 +361,8 @@ fn add_point(s: &mut Session, p: &Value) -> Result { if !(0.0..=1000.0).contains(&slop) { return Err(EngineError::Param("param 'slop' must be between 0 and 1000".into())); } - let (anchor, mut v) = edit_path(s, p, |path| { + let (anchor, mut v) = edit_path(s, p, |m| { + let path = path_mut(m)?; if path.cmds.len() > anicraft_doc::motion::MAX_PATH_SEGMENTS { return Err(EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS))); } @@ -268,7 +388,8 @@ fn add_point(s: &mut Session, p: &Value) -> Result { if !(1e-3..=1.0 - 1e-3).contains(&t) { return Err(EngineError::State("there is already an anchor there".into())); } - if !path.split_segment(cmd, t) { + // Pins after it stay on their anchors. + if !m.split_path(cmd, t) { return Err(EngineError::State("cannot add a point there".into())); } // The new anchor ends the first half. @@ -283,8 +404,8 @@ fn delete_points(s: &mut Session, p: &Value) -> Result { if wanted.is_empty() { return Err(EngineError::Param("param 'anchors' lists no anchor".into())); } - let ((deleted, kept_ends), mut v) = edit_path(s, p, |path| { - let n = path.cmds.len(); + let ((deleted, kept_ends, unpinned), mut v) = edit_path(s, p, |m| { + let n = path_mut(m)?.cmds.len(); let mut set = std::collections::BTreeSet::new(); for &i in wanted.iter().take(100_000) { match usize::try_from(i).ok().filter(|i| *i < n) { @@ -296,23 +417,28 @@ fn delete_points(s: &mut Session, p: &Value) -> Result { if set.is_empty() { return Err(EngineError::State("the ends of a motion path can't be deleted: they are where the motion starts and ends. Drag them to move them, or Straighten the path".into())); } - // Last first, so the indices still to go stay where they were. - let mut deleted = 0; + // Last first, so the indices still to go stay where they were. A pinned anchor's pin + // goes with it (and its X/Y keys). + let (mut deleted, mut unpinned) = (0, 0); for i in set.into_iter().rev() { - if path.merge_at(i) { + let pinned = m.live_pins().iter().any(|q| q.anchor as usize == i); + if m.delete_anchor(i) { deleted += 1; + unpinned += usize::from(pinned); } } - Ok((deleted, ends)) + Ok((deleted, ends, unpinned)) })?; v["deleted"] = json!(deleted); v["kept_ends"] = json!(kept_ends); + v["unpinned"] = json!(unpinned); Ok(v) } fn convert_point(s: &mut Session, p: &Value) -> Result { let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required (true: smooth, false: corner)".into()))?; - let (changed, mut v) = edit_path(s, p, |path| { + let (changed, mut v) = edit_path(s, p, |m| { + let path = path_mut(m)?; let a = anchor_index(p, "anchor", path)?; Ok(if smooth { path.make_smooth(a) } else { path.make_corner(a) }) })?; @@ -326,6 +452,7 @@ fn move_path(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("params 'dx' and 'dy' must be finite".into())); } let (kf, _) = motion_span(s, p)?; + let start = kf.start; let i = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; if !m.translate(d) { @@ -337,7 +464,8 @@ fn move_path(s: &mut Session, p: &Value) -> Result { el.transform = Affine::translate(d.x, d.y).mul(&el.transform); *slot = Arc::new(el); } - let mut v = kf.motion.as_ref().map_or(Value::Null, path_summary); + let base = base_of(kf)?; + let mut v = kf.motion.as_ref().map_or(Value::Null, |m| path_summary(m, start, &base)); v["moved"] = json!([d.x, d.y]); Ok(v) } @@ -349,8 +477,10 @@ fn clear_path(s: &mut Session, p: &Value) -> Result { if m.path.take().is_none() { return Err(EngineError::State(format!("the motion tween at frame {} has no motion path to remove", frame + 1))); } - // Orient to path has nothing left to turn with. + // Orient to path has nothing left to turn with, and pins nothing to pin. Their keys stay: + // the straight path runs through them. m.orient = false; + m.pins.clear(); Ok(json!({"cleared": true})) } @@ -358,7 +488,7 @@ fn orient(s: &mut Session, p: &Value) -> Result { let on = opt_bool(p, "orient")?.ok_or_else(|| EngineError::Param("param 'orient' is required (true or false)".into()))?; let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; - let last = kf.duration.saturating_sub(1); + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; // The straight path the X/Y curves trace becomes the path to turn along. let mut created = false; @@ -367,11 +497,84 @@ fn orient(s: &mut Session, p: &Value) -> Result { created = m.set_path(&path, &base, last); } m.orient = on; - let mut v = path_summary(m); + let mut v = path_summary(m, start, &base); v["path_created"] = json!(created); Ok(v) } +/// Why a pin can't be made, in words an artist (or an agent) can act on. `start` is the span's +/// first frame (messages count frames from 1, as the timeline does). +fn pin_error(e: PinError, start: u32, frame: u32) -> EngineError { + let shown = |f: u32| start + f + 1; + match e { + PinError::NoPath => EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()), + PinError::NoAnchor => EngineError::Param("no such anchor on this motion path (motion.info lists them, from 0 at the start)".into()), + PinError::End => EngineError::State("the ends of a motion path are always pinned, to the first and last position keys: move the object on those frames to move them".into()), + PinError::Outside(f0, f1) => EngineError::State(format!("frame {} is outside the motion (frames {} to {}): move the object there to carry the path on", shown(frame), shown(f0), shown(f1))), + PinError::Order(q) => EngineError::State(format!("anchor {} is pinned to frame {}: pins keep the path's order, a later frame on a later anchor", q.anchor, shown(q.frame))), + PinError::OffPath => EngineError::State(format!("at frame {} the object is beyond an end of the path (its ease overshoots): pin an anchor of the path instead", shown(frame))), + PinError::Full => EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS)), + } +} + +/// A straight motion's path becomes the tween's own, its position keys pinned to its anchors +/// (nothing moves). +fn own_path(m: &mut MotionTween, base: &Props, last: u32) -> std::result::Result<(), PinError> { + if m.path.is_none() { + let (path, pins) = m.path_and_pins_from_tracks(base).ok_or(PinError::NoPath)?; + m.path = Some(path.clone()); + m.pins = pins; + m.set_path(&path, base, last); + } + Ok(()) +} + +fn pin_point(s: &mut Session, p: &Value) -> Result { + let anchor = opt_u64(p, "anchor")?.map(|a| usize::try_from(a).unwrap_or(usize::MAX)); + let (kf, offset) = motion_span(s, p)?; + let base = base_of(kf)?; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + own_path(m, &base, last).map_err(|e| pin_error(e, start, offset))?; + let a = match anchor { + Some(a) => m.pin(a, offset, &base).map(|_| a), + None => m.pin_here(offset, &base), + } + .map_err(|e| pin_error(e, start, offset))?; + let mut v = path_summary(m, start, &base); + v["anchor"] = json!(a); + v["frame"] = json!(start + offset); + Ok(v) +} + +fn unpin_point(s: &mut Session, p: &Value) -> Result { + let anchor = opt_u64(p, "anchor")?; + let (kf, offset) = motion_span(s, p)?; + let base = base_of(kf)?; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + own_path(m, &base, last).map_err(|e| pin_error(e, start, offset))?; + let all = m.pinned_anchors(&base); + let found: Option = match anchor { + Some(a) => all.iter().find(|q| u64::from(q.anchor) == a).copied(), + None => all.iter().find(|q| q.frame == offset).copied(), + }; + let Some(pin) = found else { + return Err(EngineError::State(match anchor { + Some(a) => format!("anchor {a} isn't pinned to a frame"), + None => format!("no anchor is pinned to frame {}", start + offset + 1), + })); + }; + if all.first() == Some(&pin) || all.last() == Some(&pin) { + return Err(pin_error(PinError::End, start, pin.frame)); + } + m.unpin(pin.frame); + let mut v = path_summary(m, start, &base); + v["anchor"] = json!(pin.anchor); + v["frame"] = json!(start + pin.frame); + Ok(v) +} + /// Insert Keyframe (F6) inside a motion tween: every property gets a key at `frame` holding its /// value there; the timeline is not split. Whether `frame` was in a motion tween. pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool { @@ -382,9 +585,23 @@ pub(crate) fn key_all_at(layer: &mut Layer, frame: u32) -> bool { } let offset = frame - kf.start; let Some(m) = kf.motion.as_mut() else { return false }; - let Some(base) = m.target_index(&kf.elements).and_then(|t| kf.elements.get(t)).map(|e| Props::of(e)) else { return true }; + let Some(target) = m.target_index(&kf.elements).and_then(|t| kf.elements.get(t)).cloned() else { return true }; + let base = Props::of(&target); let now = m.props_at(&base, offset as f32); + // The filters' numbers too (ADR 0092), as they are on that frame. + let at = m.apply(&target, offset as f32); + for p in filter_properties(&target) { + if let (Some(v), Some(own)) = (own_value(&at, p), own_value(&target, p)) { + m.set_key(p, offset, v, own); + } + } + // On a motion path the frame's place is an anchor pinned to it (ADR 0049), where the + // object is: nothing moves on this frame. + let pinned = m.path.is_some() && m.pin_here(offset, &base).is_ok(); for p in Property::ALL { + if pinned && matches!(p, Property::X | Property::Y) { + continue; + } m.set_key(p, offset, now.get(p), base.get(p)); } true @@ -411,7 +628,7 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); let (start, ids) = { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let layer = tl.layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; if layer.kind == LayerKind::Folder { return Err(EngineError::State("a folder holds layers, not frames; pick a layer inside it".into())); @@ -489,8 +706,8 @@ fn property(p: &Value) -> Result> { match opt_str(p, "property")? { None => Ok(None), Some(k) => Property::from_key(k).map(Some).ok_or_else(|| { - let all: Vec<&str> = Property::ALL.iter().map(|p| p.key()).collect(); - EngineError::Param(format!("unknown property '{k}' ({})", all.join(", "))) + let all: Vec = Property::ALL.iter().map(|p| p.key().into_owned()).collect(); + EngineError::Param(format!("unknown property '{k}' ({}, or filter.., slot 0 to 15)", all.join(", "))) }), } } @@ -503,11 +720,33 @@ fn set_key(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param(format!("{} must be between {} and {} {}", prop.label(), r.start(), r.end(), prop.unit()))); } let (kf, offset) = motion_span(s, p)?; - let base = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e)); - let base = base.ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; - let start = kf.start; + let target = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).and_then(|i| kf.elements.get(i)).cloned(); + let target = target.ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; + let base = Props::of(&target); + let own = own_value(&target, prop).ok_or_else(|| match prop.filter() { + Some(f) => EngineError::State(match &target.kind { + ElementKind::Symbol { filters, .. } => match filters.get(usize::from(f.slot)) { + Some(e) => format!("filter {} of the tween's object is a {}, which has no {}", f.slot, e.filter.label(), f.param.label()), + None => format!("the tween's object has no filter {} (it has {}; 0 is the first)", f.slot, filters.len()), + }, + _ => "filters apply to movie clip and button instances: the tween's object has none".into(), + }), + None => EngineError::State("the motion tween's object has no such property".into()), + })?; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; - m.set_key(prop, offset, value, base.get(prop)); + // On a path, the X/Y keys of a pinned frame are its anchor's place: setting one moves the + // anchor (ADR 0049). + let pinned = matches!(prop, Property::X | Property::Y).then(|| m.pinned_anchors(&base).into_iter().find(|q| q.frame == offset)).flatten().filter(|_| m.path.is_some()); + if let Some(pin) = pinned { + let at = m.path.as_ref().and_then(|p| p.point(pin.anchor as usize, anicraft_geom::edit::ANCHOR)).unwrap_or_default(); + let d = if prop == Property::X { Vec2::new(value - at.x, 0.0) } else { Vec2::new(0.0, value - at.y) }; + if d != Vec2::ZERO && !m.move_anchor(pin.anchor as usize, d, &base, last) { + return Err(EngineError::Param(format!("{} must keep the motion path within ±1000000 px", prop.label()))); + } + return Ok(json!({"property": prop.key(), "frame": start + offset, "value": value, "anchor": pin.anchor})); + } + m.set_key(prop, offset, value, own); Ok(json!({"property": prop.key(), "frame": start + offset, "value": value})) } @@ -516,53 +755,85 @@ fn remove_key(s: &mut Session, p: &Value) -> Result { let (kf, offset) = motion_span(s, p)?; let start = kf.start; let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; - let removed: Vec<&str> = Property::ALL.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect(); + // Removing a pinned frame's X or Y key lets the pin go, with both keys (ADR 0049). + let pin = m.live_pins().into_iter().find(|q| q.frame == offset).filter(|_| only.is_none_or(|o| matches!(o, Property::X | Property::Y))); + let keyed: Vec = m.tracks.iter().map(|t| t.property).collect(); + let mut removed: Vec> = keyed.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect(); + if pin.is_some() { + for k in [Property::X.key(), Property::Y.key()] { + if !removed.contains(&k) { + removed.push(k); + } + } + } if removed.is_empty() { return Err(EngineError::State(format!("there is no property keyframe at frame {}", start + offset + 1))); } - Ok(json!({"removed": removed, "frame": start + offset})) + Ok(json!({"removed": removed, "frame": start + offset, "unpinned": pin.map(|q| q.anchor)})) } fn set_ease(s: &mut Session, p: &Value) -> Result { - let easing = opt_easing(p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?; + let easing = opt_easing_in(s, p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?; let only = property(p)?; + let label = easing.label(); let (kf, offset) = motion_span(s, p)?; let start = kf.start; let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; let mut set = Vec::new(); for t in m.tracks.iter_mut().filter(|t| only.is_none_or(|o| o == t.property)) { if let Some(k) = t.segment_at(offset).and_then(|i| t.keys.get_mut(i)) { - k.ease = easing; + k.ease = easing.clone(); set.push(t.property.key()); } } if set.is_empty() { return Err(EngineError::State(format!("frame {} is not between two property keyframes{}", start + offset + 1, only.map_or_else(String::new, |o| format!(" of {}", o.label()))))); } - Ok(json!({"easing": easing.label(), "properties": set})) + Ok(json!({"easing": label, "properties": set})) } fn info(s: &mut Session, p: &Value) -> Result { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); - let layer = s.doc.timeline(s.scene).layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; + let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; let kf = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; let m = kf.motion.as_ref().ok_or_else(|| EngineError::State(format!("frame {} is not in a motion tween", frame + 1)))?; - let base = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e)); + let target = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)); + let base = target.map(|e| Props::of(e)); let now = base.map(|b| m.props_at(&b, (frame - kf.start) as f32)); + let filter_of = |slot: u8| match target.map(|e| &e.kind) { + Some(ElementKind::Symbol { filters, .. }) => filters.get(usize::from(slot)).map(|e| e.filter.label()), + _ => None, + }; let tracks: Vec = m .tracks .iter() .map(|t| { - let keys: Vec = t.keys.iter().map(|k| json!({"frame": kf.start + k.frame, "value": k.value, "ease": k.ease.label(), "bezier": k.ease.as_bezier()})).collect(); - json!({"property": t.property.key(), "label": t.property.label(), "unit": t.property.unit(), "keys": keys}) + let keys: Vec = t.keys.iter().map(|k| json!({"frame": kf.start + k.frame, "value": k.value, "ease": k.ease.label(), "easing": easing_json(&k.ease), "bezier": k.ease.as_bezier()})).collect(); + let mut v = json!({"property": t.property.key(), "label": t.property.label(), "unit": t.property.unit(), "keys": keys}); + // A filter's number: which filter (ADR 0092); its kind `null` when it isn't there now. + if let Some(f) = t.property.filter() { + v["filter"] = json!({"slot": f.slot, "kind": filter_of(f.slot)}); + } + v }) .collect(); - let values: serde_json::Map = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().to_string(), json!(n.get(*p))))).collect(); + let mut values: serde_json::Map = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().into_owned(), json!(n.get(*p))))).collect(); + // And the filters' numbers at the frame. + if let Some(e) = target { + let at = m.apply(e, (frame - kf.start) as f32); + for p in filter_properties(e) { + if let Some(v) = own_value(&at, p) { + values.insert(p.key().into_owned(), json!(v)); + } + } + } // Where the object is (on a motion path the X/Y values are its timing, not its place). let position = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| m.apply(e, (frame - kf.start) as f32).transform.translation()).map(|q| json!([q.x, q.y])); - let path = path_summary(m); + let path = m.path.as_ref().map(|p| p.to_svg()); // The anchors point edits address: the path's own, or the straight path's (ADR 0038). let anchors: Vec<[f32; 2]> = m.path.clone().or_else(|| base.and_then(|b| m.path_from_tracks(&b))).map(|p| p.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect()).unwrap_or_default(); - Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path["path"], "anchors": anchors, "orient": m.orient})) + // And those tied to frames, ends included (ADR 0049). + let pins = base.map_or(Value::Array(Vec::new()), |b| pins_json(m, kf.start, &b)); + Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path, "anchors": anchors, "pins": pins, "orient": m.orient})) } diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs index d878ed7d..411447a6 100644 --- a/crates/engine/src/cmds_paint.rs +++ b/crates/engine/src/cmds_paint.rs @@ -1,4 +1,5 @@ -//! Paint Bucket, Ink Bottle and Eyedropper. +//! Paint Bucket, Ink Bottle and Eyedropper; the fill swatch's gradients and bitmaps, Lock Fill +//! and the Gradient Transform tool (ADR 0074). //! //! AniCraft shapes are independent objects (like object drawing), so a fill for an area //! enclosed by several shapes has to be found, not looked up: @@ -18,7 +19,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, DisplayItem, Element, ElementId, ElementKind, Paint, Shape, Stroke}; +use anicraft_doc::{BitmapId, ColorEffect, DisplayItem, Element, ElementId, ElementKind, GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Shape, Spread, Stroke}; use anicraft_geom::trace::contours; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2, fit_curve}; use anicraft_render::raster::{Coverage, IRect}; @@ -42,6 +43,25 @@ pub fn specs() -> Vec { c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?, profile?, cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing?} (the tool's line style unless given; see stroke.set_style)", true, ink), c("paint.pick", "Eyedropper", "", None, "{x, y, other?: bool (into the other swatch only: a fill's colour into the stroke, a line's into the fill), slop?} picks the style under the point on any visible layer into the tool settings: a fill's paint (solid, gradient or bitmap, kept where it is on the stage) into the fill swatch, a line's colour, width and profile into the stroke settings", false, pick_style), c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, |s, p| s.each_layer(false, |s| apply_style(s, p))), + c( + "paint.set_fill", + "Fill", + "", + None, + "{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid), stops?: [{offset: 0..1, color: \"#rrggbb\" | \"#rrggbbaa\"}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}", + true, + set_fill, + ), + c( + "paint.transform_fill", + "Gradient Transform", + "", + None, + "{element?: id (default: the selected shapes with a gradient or bitmap fill), frame?: [a, b, c, d, e, f] (the fill's frame in the space being edited: the box -1..1 onto a linear gradient's span, a radial gradient's ring or one copy of a bitmap), or changes made in this order: scale_x?, scale_y?, scale? (along the frame's own axes), skew_x?, skew_y? (degrees, along its axes), rotate? (degrees, about its centre), move?: [dx, dy], center?: [x, y]; focal?: -0.98..0.98 (radial)} moves, turns, scales or skews where a gradient or bitmap fill lies, as the Gradient Transform tool (F) does → {changed, frames: [[a, b, c, d, e, f], ..]}", + true, + |s, p| s.each_layer(false, |s| transform_fill(s, p)), + ), + c("paint.lock_fill", "Lock Fill", "", None, "{on?: bool (default: toggle)} Lock Fill: a gradient or bitmap from the fill swatch is poured where it lies on the stage, running on across shapes; off, each shape gets it fitted to its bounds → {on}", false, lock_fill), ] } @@ -73,13 +93,15 @@ fn element_shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> { ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances keep their own colours; break it apart (Ctrl+B) or edit the symbol to paint it".into())), ElementKind::Text(_) => Err(EngineError::State("text has its own colour (Properties); break it apart (Ctrl+B) to paint it as a shape".into())), ElementKind::Camera => Err(EngineError::State("the camera has no paint (its tint is in Properties)".into())), + ElementKind::Group { .. } => Err(EngineError::State("a group keeps its members' colours; double-click it to paint inside, or ungroup it (Ctrl+Shift+G)".into())), } } fn bucket(s: &mut Session, p: &Value) -> Result { let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); - // The fill swatch (a picked gradient or bitmap stays where it is on the stage). - let paint = opt_color(p, "color")?.map_or_else(|| s.style.fill_paint(), Paint::Solid); + // The fill swatch: a gradient or bitmap stays where it is on the stage with Lock Fill, else + // it is fitted to the shape it fills (ADR 0074). + let given = opt_color(p, "color")?.map(Paint::Solid); let gap = opt_f32(p, "gap")?.unwrap_or(0.0); if !(0.0..=1000.0).contains(&gap) { return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into())); @@ -89,8 +111,12 @@ fn bucket(s: &mut Session, p: &Value) -> Result { // 1. On a fill: recolour it. A raw fill then joins the fills of its new colour it touches. if let Some((id, true)) = pick(&items, at, 0.0) { let to_local = items.iter().find(|i| i.element == id).and_then(|i| i.transform.inverse()).unwrap_or(Affine::IDENTITY); + let style = s.style.clone(); let sh = element_shape_mut(s, id)?; - sh.fill = Some(paint.transformed(&to_local)); + sh.fill = Some(match &given { + Some(c) => c.clone(), + None => style.fill_paint_for(&to_local, &sh.path.bounds()), + }); if sh.merge { crate::cmds_raw::remerge_in_place(s, &[id])?; return Ok(json!({"recolored": id.0, "merged": true})); @@ -113,7 +139,7 @@ fn bucket(s: &mut Session, p: &Value) -> Result { name: String::new(), transform: Affine::translate(c.x, c.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(paint.transformed(&Affine::translate(-c.x, -c.y))), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }), + kind: ElementKind::Shape(Shape { fill: Some(given.unwrap_or_else(|| s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()))), path: Arc::new(local), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }), }; if !object { // Raw: behind the drawing, so it takes only what is empty and joins the fills of its @@ -375,6 +401,10 @@ fn pick_style(s: &mut Session, p: &Value) -> Result { } st.fill = color; st.fill_paint = (!matches!(paint, Paint::Solid(_))).then(|| paint.clone()); + // As in Animate, a picked gradient or bitmap is locked where it was on the stage. + if st.fill_paint.is_some() { + st.lock_fill = true; + } st.use_fill = true; Ok(json!({"picked": "fill", "into": "fill", "paint": paint_kind(&paint), "color": color.to_hex()})) } @@ -415,7 +445,6 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("apply the fill, the stroke or both".into())); } let style = s.style.clone(); - let paint = style.fill_paint(); let line = style.new_stroke(style.stroke, style.stroke_width); let mut changed = 0; for e in s.selected_elements_mut()? { @@ -426,7 +455,7 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { && sh.fill.is_some() && let Some(m) = to_local { - sh.fill = Some(paint.transformed(&m)); + sh.fill = Some(style.fill_paint_for(&m, &sh.path.bounds())); hit = true; } // Raw fills stay fill-only: the lines round them are shapes of their own (ADR 0031). @@ -441,3 +470,328 @@ fn apply_style(s: &mut Session, p: &Value) -> Result { } Ok(json!({"changed": changed})) } + +// ----- the fill swatch, Lock Fill and the Gradient Transform tool (ADR 0074) --------------- + +/// Animate's default gradient: white to black. +fn default_stops() -> Vec { + vec![GradientStop { offset: 0.0, color: Rgba::WHITE }, GradientStop { offset: 1.0, color: Rgba::BLACK }] +} + +/// The `stops` param: 2 to 15 stops, each `{offset, color}`, put in order of offset. +pub(crate) fn opt_stops(p: &Value) -> Result>> { + let bad = || EngineError::Param(format!("param 'stops' must be a list of 2 to {MAX_GRADIENT_STOPS} stops like {{\"offset\": 0.5, \"color\": \"#ff8800\"}}")); + let list = match p.get("stops") { + None | Some(Value::Null) => return Ok(None), + Some(Value::Array(a)) if (2..=MAX_GRADIENT_STOPS).contains(&a.len()) => a, + Some(_) => return Err(bad()), + }; + let mut stops = Vec::with_capacity(list.len()); + for v in list { + let offset = opt_f32(v, "offset").map_err(|_| bad())?.ok_or_else(bad)?; + if !(0.0..=1.0).contains(&offset) { + return Err(EngineError::Param("a stop's 'offset' must be between 0 and 1".into())); + } + let color = opt_color(v, "color").map_err(|_| bad())?.ok_or_else(bad)?; + stops.push(GradientStop { offset, color }); + } + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + Ok(Some(stops)) +} + +/// The kinds of fill `paint.set_fill` makes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FillKind { + Solid, + Linear, + Radial, + Bitmap, +} + +fn fill_kind(p: &Paint) -> FillKind { + match p { + Paint::Solid(_) => FillKind::Solid, + Paint::Linear { .. } => FillKind::Linear, + Paint::Radial { .. } => FillKind::Radial, + Paint::Bitmap { .. } => FillKind::Bitmap, + } +} + +/// What `paint.set_fill` asks for: a kind of fill and the parts given. +struct FillSpec { + kind: FillKind, + color: Option, + stops: Option>, + spread: Option, + linear_rgb: Option, + focal: Option, + bitmap: Option, +} + +impl FillSpec { + /// `base` with these changes. A fill of the same kind keeps its geometry; another kind + /// comes out on the unit box (to be placed); a gradient keeps the colours and options of + /// the gradient it replaces, else starts white to black. `None`: a bitmap fill with no + /// bitmap given or held. + fn apply(&self, base: &Paint) -> Option { + let mut p = match self.kind { + FillKind::Solid => return Some(Paint::Solid(self.color.unwrap_or_else(|| base.primary_color()))), + k if k == fill_kind(base) => base.clone(), + FillKind::Linear | FillKind::Radial => { + let stops = base.stops().map_or_else(default_stops, <[GradientStop]>::to_vec); + let mut q = if self.kind == FillKind::Linear { Paint::linear(Vec2::new(-1.0, 0.0), Vec2::new(1.0, 0.0), stops) } else { Paint::radial(Vec2::ZERO, 1.0, stops) }; + if let (Paint::Linear { spread: a, linear_rgb: b, .. } | Paint::Radial { spread: a, linear_rgb: b, .. }, Paint::Linear { spread, linear_rgb, .. } | Paint::Radial { spread, linear_rgb, .. }) = (&mut q, base) { + *a = *spread; + *b = *linear_rgb; + } + q + } + FillKind::Bitmap => Paint::Bitmap { bitmap: self.bitmap?, repeat: true, matrix: Affine::IDENTITY }, + }; + match &mut p { + Paint::Linear { stops, spread, linear_rgb, .. } => self.set_common(stops, spread, linear_rgb), + Paint::Radial { stops, spread, linear_rgb, focal, .. } => { + self.set_common(stops, spread, linear_rgb); + if let Some(f) = self.focal { + *focal = f; + } + } + Paint::Bitmap { bitmap, .. } => { + if let Some(b) = self.bitmap { + *bitmap = b; + } + } + Paint::Solid(_) => {} + } + Some(p) + } + + fn set_common(&self, stops: &mut Vec, spread: &mut Spread, linear_rgb: &mut bool) { + if let Some(st) = &self.stops { + stops.clone_from(st); + } + if let Some(sp) = self.spread { + *spread = sp; + } + if let Some(l) = self.linear_rgb { + *linear_rgb = l; + } + } +} + +/// `#rrggbb`, or `#rrggbbaa` when not opaque. +fn hex_alpha(c: Rgba) -> String { + let c = c.sanitized(); + if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } +} + +/// A fill as `paint.set_fill` reports it (in its own params' terms). +pub fn fill_json(p: &Paint) -> Value { + let stops = |st: &[GradientStop]| -> Vec { st.iter().map(|s| json!({"offset": s.offset, "color": hex_alpha(s.color)})).collect() }; + match p { + Paint::Solid(c) => json!({"type": "solid", "color": hex_alpha(*c)}), + Paint::Linear { stops: st, spread, linear_rgb, .. } => json!({"type": "linear", "stops": stops(st), "spread": spread.key(), "linear_rgb": linear_rgb}), + Paint::Radial { stops: st, spread, linear_rgb, focal, .. } => json!({"type": "radial", "stops": stops(st), "spread": spread.key(), "linear_rgb": linear_rgb, "focal": focal}), + Paint::Bitmap { bitmap, repeat, .. } => json!({"type": "bitmap", "bitmap": bitmap.0, "repeat": repeat}), + } +} + +pub(crate) fn opt_focal(p: &Value) -> Result> { + let f = opt_f32(p, "focal")?; + if f.is_some_and(|f| !(-MAX_FOCAL..=MAX_FOCAL).contains(&f)) { + return Err(EngineError::Param(format!("param 'focal' must be between -{MAX_FOCAL} and {MAX_FOCAL}"))); + } + Ok(f) +} + +/// `paint.set_fill`: the Colour panel's fill (type, stops, overflow, linear RGB, bitmap). +pub(crate) fn set_fill(s: &mut Session, p: &Value) -> Result { + let swatch = s.style.fill_paint(); + let kind = match opt_str(p, "type")? { + None => fill_kind(&swatch), + Some("solid") => FillKind::Solid, + Some("linear") => FillKind::Linear, + Some("radial") => FillKind::Radial, + Some("bitmap") => FillKind::Bitmap, + Some(other) => return Err(EngineError::Param(format!("unknown fill type '{other}' (solid, linear, radial or bitmap)"))), + }; + let spread = match opt_str(p, "spread")? { + None => None, + Some(k) => Some(Spread::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown spread '{k}' (extend, reflect or repeat)")))?), + }; + let bitmap = match opt_u64(p, "bitmap")? { + None => None, + Some(id) => Some(s.doc.bitmap(BitmapId(id)).ok_or_else(|| EngineError::Param(format!("there is no bitmap {id} in the Library")))?.id), + }; + let spec = FillSpec { kind, color: opt_color(p, "color")?, stops: opt_stops(p)?, spread, linear_rgb: opt_bool(p, "linear_rgb")?, focal: opt_focal(p)?, bitmap }; + let new = spec.apply(&swatch).ok_or_else(|| EngineError::Param("a bitmap fill needs 'bitmap' (a Library bitmap's id)".into()))?; + // The swatch keeps where its fill lies; a new kind lies across the stage. + let stage = Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32); + let placed = if fill_kind(&swatch) == kind { new } else { new.fitted(&stage) }; + match &placed { + Paint::Solid(c) => s.style.set_fill_color(*c), + other => { + s.style.fill = other.primary_color(); + s.style.fill_paint = Some(other.clone()); + } + } + s.style.use_fill = true; + let changed = if opt_bool(p, "selection")?.unwrap_or(true) && !s.selection.is_empty() { + // Counts from several layers are added up. + s.each_layer(false, |s| set_selected_fills(s, &spec))?.get("changed").and_then(Value::as_u64).unwrap_or(0) + } else { + 0 + }; + Ok(json!({"fill": fill_json(&placed), "changed": changed})) +} + +/// The selected shapes with a fill on the active layer get `spec`: the same kind of fill keeps +/// where it lies, another kind is fitted to the shape. +fn set_selected_fills(s: &mut Session, spec: &FillSpec) -> Result { + let sel: std::collections::HashSet = s.selection.on(s.layer).into_iter().collect(); + if sel.is_empty() { + return Ok(json!({"changed": 0})); + } + let mut changed = 0u64; + let mut merged = Vec::new(); + for e in s.editable_keyframe()?.elements_mut_where(|id| sel.contains(&id)) { + let id = e.id; + let ElementKind::Shape(sh) = &mut e.kind else { continue }; + let Some(old) = &sh.fill else { continue }; + let Some(mut new) = spec.apply(old) else { continue }; + if fill_kind(old) != spec.kind { + new = new.fitted(&sh.path.bounds()); + } + if sh.fill.as_ref() != Some(&new) { + sh.fill = Some(new); + changed += 1; + if sh.merge { + merged.push(id); + } + } + } + // A raw fill joins the fills of its new paint it touches (as the Paint Bucket's recolour). + if !merged.is_empty() { + crate::cmds_raw::remerge_in_place(s, &merged)?; + } + Ok(json!({"changed": changed})) +} + +/// The size of the image a bitmap fill shows (`None`: not a bitmap, or missing). +pub fn image_size(doc: &anicraft_doc::Document, p: &Paint) -> Option<(f32, f32)> { + match p { + Paint::Bitmap { bitmap, .. } => doc.bitmap(*bitmap).map(|b| (b.width as f32, b.height as f32)), + _ => None, + } +} + +/// Where element `e`'s gradient or bitmap fill lies: its frame (see [`Paint::frame`]) in the +/// space being edited. `None` for anything else. +pub fn fill_frame(doc: &anicraft_doc::Document, e: &Element) -> Option { + let ElementKind::Shape(sh) = &e.kind else { return None }; + let f = sh.fill.as_ref()?; + Some(e.transform.mul(&f.frame(image_size(doc, f))?)) +} + +fn opt_vec2(p: &Value, key: &str) -> Result> { + let bad = || EngineError::Param(format!("param '{key}' must be [x, y] (finite numbers)")); + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) if a.len() == 2 => { + let v = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= f64::from(crate::cmds_draw::MAX_EXTENT)).map(|x| x as f32); + match (v(0), v(1)) { + (Some(x), Some(y)) => Ok(Some(Vec2::new(x, y))), + _ => Err(bad()), + } + } + Some(_) => Err(bad()), + } +} + +/// The frame `paint.transform_fill`'s params ask for, from the current one `cur`. +fn new_frame(cur: &Affine, p: &Value) -> Result { + if let Some(v) = p.get("frame").filter(|v| !v.is_null()) { + let a = v.as_array().filter(|a| a.len() == 6).ok_or_else(|| EngineError::Param("param 'frame' must be [a, b, c, d, e, f]".into()))?; + let mut m = [0.0f32; 6]; + for (slot, x) in m.iter_mut().zip(a) { + *slot = x.as_f64().filter(|x| x.is_finite() && x.abs() <= 1e7).ok_or_else(|| EngineError::Param("param 'frame' must hold six finite numbers".into()))? as f32; + } + return Ok(Affine { m }); + } + let scale = |k: &str| -> Result { + match opt_f32(p, k)? { + None => Ok(1.0), + Some(v) if (1e-4..=1e4).contains(&v.abs()) => Ok(v), + Some(_) => Err(EngineError::Param(format!("param '{k}' must be a scale between 0.0001 and 10000 (negative flips)"))), + } + }; + let both = scale("scale")?; + let (sx, sy) = (scale("scale_x")? * both, scale("scale_y")? * both); + let skew = |k: &str| -> Result { + match opt_f32(p, k)? { + None => Ok(0.0), + Some(d) if d.abs() <= 85.0 => Ok(d.to_radians().tan()), + Some(_) => Err(EngineError::Param(format!("param '{k}' must be between -85 and 85 degrees"))), + } + }; + let own = Affine::scale(sx, sy).mul(&Affine { m: [1.0, skew("skew_y")?, skew("skew_x")?, 1.0, 0.0, 0.0] }); + let mut f = cur.mul(&own); + if let Some(deg) = opt_f32(p, "rotate")? { + let c = f.apply(Vec2::ZERO); + f = Affine::translate(c.x, c.y).mul(&Affine::rotate(deg.to_radians())).mul(&Affine::translate(-c.x, -c.y)).mul(&f); + } + if let Some(d) = opt_vec2(p, "move")? { + f = Affine::translate(d.x, d.y).mul(&f); + } + if let Some(at) = opt_vec2(p, "center")? { + let c = f.apply(Vec2::ZERO); + f = Affine::translate(at.x - c.x, at.y - c.y).mul(&f); + } + Ok(f) +} + +/// `paint.transform_fill`: the Gradient Transform tool's edit. +fn transform_fill(s: &mut Session, p: &Value) -> Result { + let focal = opt_focal(p)?; + let only = opt_u64(p, "element")?.map(ElementId); + let targets: std::collections::HashSet = match only { + Some(id) => [id].into(), + None => s.selection.on(s.layer).into_iter().collect(), + }; + if targets.is_empty() { + return Err(EngineError::State("select a shape with a gradient or bitmap fill".into())); + } + let doc = s.doc.clone(); + let mut frames = Vec::new(); + for e in s.editable_keyframe()?.elements_mut_where(|id| targets.contains(&id)) { + let (Some(cur), Some(to_local)) = (fill_frame(&doc, e), e.transform.inverse()) else { continue }; + let f = new_frame(&cur, p)?; + if !f.is_finite() || f.determinant().abs() < 1e-6 { + return Err(EngineError::Param("that would flatten the fill to nothing".into())); + } + let ElementKind::Shape(sh) = &mut e.kind else { continue }; + let Some(fill) = &sh.fill else { continue }; + let mut new = fill.with_frame(&to_local.mul(&f), image_size(&doc, fill)); + if let (Paint::Radial { focal: slot, .. }, Some(v)) = (&mut new, focal) { + *slot = v; + } + frames.push(json!(f.m)); + // Only where the fill lies changes, so a raw fill stays the shape it is (no re-merge: + // its id holds through a drag, and a moved gradient matches no neighbour's anyway). + sh.fill = Some(new); + } + if frames.is_empty() { + return Err(EngineError::State(match only { + Some(_) => "that shape has no gradient or bitmap fill on the active layer at this frame".into(), + None => "none of the selected shapes has a gradient or bitmap fill".into(), + })); + } + Ok(json!({"changed": frames.len(), "frames": frames})) +} + +/// `paint.lock_fill`. +fn lock_fill(s: &mut Session, p: &Value) -> Result { + let on = opt_bool(p, "on")?.unwrap_or(!s.style.lock_fill); + s.style.lock_fill = on; + Ok(json!({"on": on})) +} diff --git a/crates/engine/src/cmds_path.rs b/crates/engine/src/cmds_path.rs index fa223743..eeaf2714 100644 --- a/crates/engine/src/cmds_path.rs +++ b/crates/engine/src/cmds_path.rs @@ -9,7 +9,7 @@ use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param, style}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{Element, ElementId, ElementKind, Shape}; -use anicraft_geom::edit::{ANCHOR, polyline_path, simplify}; +use anicraft_geom::edit::{ANCHOR, C1, C2, polyline_path, simplify}; use anicraft_geom::{Affine, Path, PathCmd, Vec2, fit_curve}; use serde_json::{Value, json}; use std::collections::BTreeSet; @@ -28,7 +28,7 @@ pub fn specs() -> Vec { true, draw_freehand, ), - c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy}", true, move_points), + c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy, smooth?: bool} (a handle moved alone at a smooth anchor turns the other one with it, keeping its length, unless smooth is false: Alt breaks the pair)", true, move_points), c("path.add_point", "Add Anchor Point", "", None, "{id, x, y, slop?}", true, add_point), c("path.delete_points", "Delete Anchor Points", "", None, "{id, cmds: [..]}", true, delete_points), c("path.convert_point", "Convert Anchor Point", "", None, "{id, cmd, smooth: bool}", true, convert_point), @@ -116,20 +116,26 @@ fn draw_freehand(s: &mut Session, p: &Value) -> Result { // ----- point editing ---------------------------------------------------------------------- -/// The shape element `id` in the editable keyframe (copy-on-write), with its transform. -fn shape_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Shape, Affine)> { +/// Runs `edit` on shape element `id` (param `id`) in the editable keyframe (copy-on-write), with +/// its transform. The shape of a shape armature is reshaped at rest instead, keeping its binding +/// (ADR 0090). +fn edit_shape(s: &mut Session, p: &Value, edit: impl FnOnce(&mut Shape, Affine) -> Result) -> Result { let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?); if !s.visible_elements().iter().any(|e| e.id == id) { return Err(EngineError::State(format!("element {} is not on the active layer at this frame", id.0))); } + if crate::cmds_bone::is_skin_shape(s, id) { + return crate::cmds_bone::reshape(s, id, edit); + } let kf = s.editable_keyframe()?; let el: &mut Element = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?; let m = el.transform; match &mut el.kind { - ElementKind::Shape(sh) => Ok((sh, m)), + ElementKind::Shape(sh) => edit(sh, m), ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances have no points to edit (double-click to edit the symbol)".into())), ElementKind::Text(_) => Err(EngineError::State("text has no points to edit; break it apart (Ctrl+B) to edit its outlines".into())), ElementKind::Camera => Err(EngineError::State("the camera has no points to edit".into())), + ElementKind::Group { .. } => Err(EngineError::State("a group has no points of its own (double-click it to edit what is inside)".into())), } } @@ -149,77 +155,109 @@ fn move_points(s: &mut Session, p: &Value) -> Result { let slot = pair.get(1).and_then(Value::as_u64).filter(|s| *s <= 2).ok_or_else(bad)?; wanted.push((usize::try_from(cmd).unwrap_or(usize::MAX), slot as u8)); } - let (sh, m) = shape_mut(s, p)?; - let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?; - let local = inv.apply_vector(d); - if !local.is_finite() { - return Err(EngineError::Param("the move is too large".into())); - } - let path = Arc::make_mut(&mut sh.path); - // Anchors bring their handles and their twin at a closed start; each point moves once. - let mut set = BTreeSet::new(); - for (cmd, slot) in wanted { - if path.point(cmd, slot).is_none() { - return Err(EngineError::Param(format!("no point ({cmd}, {slot}) on this path"))); + let smooth = opt_bool(p, "smooth")?.unwrap_or(true); + edit_shape(s, p, |sh, m| { + let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?; + let local = inv.apply_vector(d); + if !local.is_finite() { + return Err(EngineError::Param("the move is too large".into())); } - if slot == ANCHOR { - set.extend(path.anchor_group(cmd)); - } else { - set.insert((cmd, slot)); + let path = Arc::make_mut(&mut sh.path); + // Anchors bring their handles and their twin at a closed start; each point moves once. + let mut set = BTreeSet::new(); + for (cmd, slot) in wanted { + if path.point(cmd, slot).is_none() { + return Err(EngineError::Param(format!("no point ({cmd}, {slot}) on this path"))); + } + if slot == ANCHOR { + set.extend(path.anchor_group(cmd)); + } else { + set.insert((cmd, slot)); + } } - } - for &(cmd, slot) in &set { - if let Some(q) = path.point(cmd, slot) { - path.set_point(cmd, slot, q + local); + // The other handle of a smooth anchor whose handle moves alone (ADR 0045), as it was. + let partners: Vec<(usize, u8, Vec2, Vec2)> = if smooth { set.iter().filter_map(|&(cmd, slot)| partner(path, &set, cmd, slot)).collect() } else { Vec::new() }; + for &(cmd, slot) in &set { + if let Some(q) = path.point(cmd, slot) { + path.set_point(cmd, slot, q + local); + } } + for (cmd, slot, anchor, handle) in partners { + if let Some(k) = path.point(cmd, slot) { + path.set_point(cmd, slot, anicraft_geom::raw::turned_opposite(anchor, handle + local, k)); + } + } + check_path(path)?; + Ok(json!({"moved": set.len()})) + }) +} + +/// For handle `(cmd, slot)` moving alone: the other handle of its anchor when the anchor is smooth +/// and that handle stays (`(cmd, slot)`), with the anchor and this handle where they are now. +fn partner(path: &Path, moving: &BTreeSet<(usize, u8)>, cmd: usize, slot: u8) -> Option<(usize, u8, Vec2, Vec2)> { + // Slot 2 is the in-handle of anchor `cmd`; slot 1 the out-handle of the anchor before. + let anchor = match slot { + C2 => path.canonical_anchor(cmd), + C1 => path.canonical_anchor(cmd.checked_sub(1)?), + _ => return None, + }; + let (i, o) = path.anchor_segments(anchor); + let other = if slot == C2 { (o?, C1) } else { (i?, C2) }; + if moving.contains(&other) || path.anchor_group(anchor).iter().any(|g| g.1 == ANCHOR && moving.contains(g)) { + return None; } - check_path(path)?; - Ok(json!({"moved": set.len()})) + let (a, h, k) = (path.point(anchor, ANCHOR)?, path.point(cmd, slot)?, path.point(other.0, other.1)?); + // A quadratic's control is both its ends' handle: turning it would bend the other end. + let cubic = |c: usize| matches!(path.cmds.get(c), Some(PathCmd::CubicTo(..))); + (cubic(other.0) && anicraft_geom::raw::smooth_at(a, h, k)).then_some((other.0, other.1, a, h)) } fn add_point(s: &mut Session, p: &Value) -> Result { let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 1000.0); - let (sh, m) = shape_mut(s, p)?; - let path = Arc::make_mut(&mut sh.path); - path.close_explicitly(); - let (cmd, t, dist) = path.nearest_segment(at, &m).ok_or_else(|| EngineError::State("the path has no segments".into()))?; - if dist > slop { - return Err(EngineError::State("no segment there".into())); - } - if path.cmds.len() >= MAX_CMDS || !path.split_segment(cmd, t) { - return Err(EngineError::State("cannot add a point there".into())); - } - Ok(json!({"cmd": cmd})) + edit_shape(s, p, |sh, m| { + let path = Arc::make_mut(&mut sh.path); + path.close_explicitly(); + let (cmd, t, dist) = path.nearest_segment(at, &m).ok_or_else(|| EngineError::State("the path has no segments".into()))?; + if dist > slop { + return Err(EngineError::State("no segment there".into())); + } + if path.cmds.len() >= MAX_CMDS || !path.split_segment(cmd, t) { + return Err(EngineError::State("cannot add a point there".into())); + } + Ok(json!({"cmd": cmd})) + }) } fn delete_points(s: &mut Session, p: &Value) -> Result { let cmds = index_list(p, "cmds")?; - let (sh, _) = shape_mut(s, p)?; - let path = Arc::make_mut(&mut sh.path); - // Highest first, so earlier indices stay valid; twins collapse onto one anchor. - let order: BTreeSet = cmds.iter().map(|&c| path.canonical_anchor(c)).collect(); - let mut removed = 0; - for cmd in order.into_iter().rev() { - if path.remove_anchor(cmd) { - removed += 1; + edit_shape(s, p, |sh, _| { + let path = Arc::make_mut(&mut sh.path); + // Highest first, so earlier indices stay valid; twins collapse onto one anchor. + let order: BTreeSet = cmds.iter().map(|&c| path.canonical_anchor(c)).collect(); + let mut removed = 0; + for cmd in order.into_iter().rev() { + if path.remove_anchor(cmd) { + removed += 1; + } } - } - if removed == 0 { - return Err(EngineError::State("a path keeps at least two points (delete the shape instead)".into())); - } - Ok(json!({"deleted": removed})) + if removed == 0 { + return Err(EngineError::State("a path keeps at least two points (delete the shape instead)".into())); + } + Ok(json!({"deleted": removed})) + }) } fn convert_point(s: &mut Session, p: &Value) -> Result { let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?; let cmd = usize::try_from(cmd).unwrap_or(usize::MAX); let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required".into()))?; - let (sh, _) = shape_mut(s, p)?; - let path = Arc::make_mut(&mut sh.path); - if path.point(cmd, ANCHOR).is_none() { - return Err(EngineError::Param(format!("no anchor {cmd} on this path"))); - } - let changed = if smooth { path.make_smooth(cmd) } else { path.make_corner(cmd) }; - Ok(json!({"changed": changed})) + edit_shape(s, p, |sh, _| { + let path = Arc::make_mut(&mut sh.path); + if path.point(cmd, ANCHOR).is_none() { + return Err(EngineError::Param(format!("no anchor {cmd} on this path"))); + } + let changed = if smooth { path.make_smooth(cmd) } else { path.make_corner(cmd) }; + Ok(json!({"changed": changed})) + }) } diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index dc4d70c4..4b00ff27 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -31,16 +31,40 @@ const MAX_ELEMENTS: usize = 10_000; /// a namespace this list doesn't know is refused until someone decides (a test checks that /// every registered namespace is known). pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { - const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw", "frames"]; + const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "warp", "script", "raw", "frames", "find", "explorer", "ease"]; match id { "edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"), - "edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" => { + "edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" | "frames.cut" | "frames.copy" | "frames.paste" | "ease.copy" | "ease.paste" => { Err("plug-ins don't use your clipboard") } _ => match id.split('.').next().unwrap_or("") { - "file" => Err("plug-ins can't open, save, import or export files"), + "file" => Err("plug-ins can't open, save, import, export or publish files"), + // Reading the settings is harmless; changing them changes what Publish writes where. + "publish" if id == "publish.settings_get" => Ok(()), + "publish" => Err("plug-ins can't change what Publish writes"), + "prefs" => Err("plug-ins can't read or change your preferences"), + // Listing the brushes is harmless (and painting with one is `draw.brush`); the + // user's own brushes are their preferences, and a brush set is a file. + "brush" if id == "brush.preset_list" => Ok(()), + "brush" => Err("plug-ins can't change your brushes or read and write brush sets"), + // Filter lists are the document's (ADR 0091); copied filters are the artist's + // clipboard, and the presets their preferences (listing and applying one is fine). + "filter" if matches!(id, "filter.copy" | "filter.paste") => Err("plug-ins don't use your clipboard"), + "filter" if matches!(id, "filter.preset_save" | "filter.preset_rename" | "filter.preset_delete" | "filter.preset_export" | "filter.preset_import") => Err("plug-ins can't change your filter presets or read and write preset files"), + "filter" => Ok(()), + // The document's swatches are document data; swatch files are files. + "swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"), + "swatch" => Ok(()), "plugin" => Err("plug-ins can't install, run or remove plug-ins"), + // Saved commands are files in your preferences (ADR 0097), and running one from a + // plug-in would let the two call each other. + "macro" => Err("plug-ins can't run, save or change saved commands"), + "desktop" => Err("plug-ins can't change your applications menu or which app opens your files"), "control" => Err("plug-ins can't play the movie"), + // A scene's guides are the document's (ADR 0076); whether rulers, grid and guides + // show and snap is how you work. + "view" if matches!(id, "view.aids" | "view.guide_add" | "view.guide_move" | "view.guide_delete" | "view.guides_clear") => Ok(()), + "view" => Err("plug-ins can't change how your stage shows and snaps"), ns if DOCUMENT.contains(&ns) => Ok(()), _ => Err("plug-ins can't call this command"), }, @@ -75,11 +99,10 @@ impl Host for SessionHost<'_> { fn document_view(s: &Session) -> Value { let st = &s.doc.stage; let layers: Vec = s - .doc - .timeline(s.scene) + .timeline() .layers .iter() - .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "parent": l.parent.map(|p| p.0)})) + .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "outline": l.outline, "onion": l.onion, "height": u32::from(l.height()) * 100, "parent": l.parent.map(|p| p.0)})) .collect(); json!({ "abi": anicraft_plugins::ABI_VERSION, @@ -127,7 +150,8 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result "selected": s.selection.contains(s.layer, e.id), "transform": e.transform.m, "bounds": if b.is_empty() { Value::Null } else { json!([b.min.x, b.min.y, b.max.x - b.min.x, b.max.y - b.min.y]) }, - "alpha": e.color.alpha, + "alpha": e.color.alpha(), + "color_effect": crate::color_effect_json(&e.color), }); match &e.kind { ElementKind::Shape(sh) => { @@ -147,6 +171,10 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result v["text"] = json!(t.text); } ElementKind::Camera => v["kind"] = json!("camera"), + ElementKind::Group { .. } => { + v["kind"] = json!("group"); + v["members"] = json!(e.kind.group_members().len()); + } } out.push(v); } @@ -177,6 +205,8 @@ pub fn describe(s: &Session, p: &Plugin) -> Value { "description": m.description, "kind": m.kind.key(), "entries": m.entries, + "format": m.format.as_ref().map(|f| json!({"name": f.name, "extension": f.extension})), + "eases": p.eases().iter().map(|c| json!({"id": c.id, "name": c.name})).collect::>(), "selection": if m.selection == SelectionNeed::Required { "required" } else { "optional" }, "params": m.params.iter().map(|(k, spec)| param_json(k, spec)).collect::>(), "notation": m.params_notation(), @@ -212,8 +242,11 @@ fn run(s: &mut Session, p: &Value) -> Result { let id = str_req(p, "id")?; let plugin = s.plugins.get(id).ok_or_else(|| EngineError::State(format!("no plug-in “{id}” is installed (see plugin.list)")))?; let m = plugin.manifest(); - if m.kind == anicraft_plugins::Kind::FrameScript { - return Err(EngineError::State(format!("{} is a frame script: it runs while the movie plays, from a keyframe (Window › Actions)", m.name))); + match m.kind { + anicraft_plugins::Kind::Command => {} + anicraft_plugins::Kind::FrameScript => return Err(EngineError::State(format!("{} is a frame script: it runs while the movie plays, from a keyframe (Window › Actions)", m.name))), + anicraft_plugins::Kind::Exporter => return Err(EngineError::State(format!("{} is an export format: use File › Export, or file.export_plugin {{\"format\": \"{}\", \"path\": …}}", m.name, m.id))), + anicraft_plugins::Kind::Ease => return Err(EngineError::State(format!("{} adds eases: pick one in a tween's ease menu, or ease.set {{\"easing\": {{\"plugin\": \"{}\", \"ease\": …}}}}", m.name, m.id))), } if m.selection == SelectionNeed::Required && s.selection.is_empty() { return Err(EngineError::State(format!("{} works on the selection: select some artwork first", m.name))); diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs index 7b122f1b..794a0722 100644 --- a/crates/engine/src/cmds_raw.rs +++ b/crates/engine/src/cmds_raw.rs @@ -158,7 +158,7 @@ fn hit(s: &mut Session, p: &Value) -> Result { } /// Makes the layer of what is at `at` (within `slop`) the active one, as a click does. -fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) { +pub(crate) fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) { if let Some((layer, _)) = s.hit_test(at, slop) && layer != s.layer { @@ -263,6 +263,38 @@ pub(crate) fn edit_edge(s: &mut Session, id: ElementId, cmd: usize, old: &Cubic, Ok(changed) } +/// Changes every copy of the edge `old` (stage space) into `new` (same ends): in every raw shape on +/// the editable keyframe, or only in `only` (a drawing object edits itself alone). Returns the +/// shapes that changed. +pub(crate) fn follow_edge(s: &mut Session, only: Option, old: &Cubic, new: &Cubic) -> Result> { + let area = new.iter().chain(old).fold(Rect::EMPTY, |mut r, q| { + r.include(*q); + r + }); + let kf = s.editable_keyframe()?; + let mut changed = Vec::new(); + for e in kf.elements.iter_mut() { + let take = match only { + Some(id) => e.id == id, + None => mergeable(e).is_some_and(|x| !reach(x, &e.transform).intersect(&area).is_empty()), + }; + if !take { + continue; + } + let (Some(inv), ElementKind::Shape(x)) = (e.transform.inverse(), &e.kind) else { continue }; + let mut edited = (*x.path).clone(); + if rawgeom::follow(&mut edited, &rawgeom::transform(old, &inv), &rawgeom::transform(new, &inv), SNAP / e.transform.mean_scale().max(1e-6)) == 0 { + continue; + } + check_extent(&edited)?; + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(edited); + } + changed.push(e.id); + } + Ok(changed) +} + // ----- moving shared points --------------------------------------------------------------------- fn points_param(p: &Value) -> Result>> { @@ -332,7 +364,7 @@ fn shared_points(s: &mut Session, at: Vec2) -> Result> { fn move_point(s: &mut Session, p: &Value) -> Result { let from = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); let to = Vec2::new(f32_req(p, "to_x")?, f32_req(p, "to_y")?); - let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0)); + let radius = opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0); let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0); let merge_after = opt_bool(p, "merge")?.unwrap_or(true); let points = match points_param(p)? { @@ -366,7 +398,7 @@ fn move_point(s: &mut Session, p: &Value) -> Result { _ => None, }); let cur = cur.ok_or_else(|| EngineError::Param(format!("no point ({}, {cmd0}) on the active layer", id0.0)))?; - let snapped = if radius > 0.0 { snap_point(&els, to, radius, &points) } else { None }; + let snapped = if s.snaps(radius) { snap_point(s, &els, to, radius, &points) } else { None }; let target = snapped.map_or(to, |(q, _)| q); let d = target - cur; let kf = s.editable_keyframe()?; @@ -408,23 +440,9 @@ fn move_point(s: &mut Session, p: &Value) -> Result { // ----- snapping --------------------------------------------------------------------------------- -/// What a dragged point snapped to. -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum SnapTo { - /// An anchor (corner or end). - Point, - /// A stroke or a fill's edge. - Line, -} - -impl SnapTo { - pub fn key(&self) -> &'static str { - match self { - SnapTo::Point => "point", - SnapTo::Line => "line", - } - } -} +/// What a dragged point snapped to (the snap engine's, ADR 0076). +pub use crate::snap::SnapTo; +use crate::snap::{ObjectTargets, resolve}; /// Anchors and segments to snap to, in stage space. #[derive(Default)] @@ -460,30 +478,35 @@ fn targets(els: &[Arc], skip_el: impl Fn(ElementId) -> bool, skip_point t } -/// The nearest anchor within `radius` of `p`, else the nearest point on a segment. -fn snap_to(t: &Targets, p: Vec2, radius: f32) -> Option<(Vec2, SnapTo, f32)> { - let point = t.points.iter().map(|q| (*q, q.distance(p))).filter(|(_, d)| *d <= radius).min_by(|a, b| a.1.total_cmp(&b.1)); - if let Some((q, d)) = point { - return Some((q, SnapTo::Point, d)); +impl ObjectTargets for Targets { + /// The nearest anchor within `radius` of `p`. + fn nearest_point(&self, p: Vec2, radius: f32) -> Option<(Vec2, f32)> { + self.points.iter().map(|q| (*q, q.distance(p))).filter(|(_, d)| *d <= radius).min_by(|a, b| a.1.total_cmp(&b.1)) + } + /// The nearest point on a segment within `radius` of `p`. + fn nearest_line(&self, p: Vec2, radius: f32) -> Option<(Vec2, f32)> { + let near = |c: &Cubic| { + let (lo, hi) = c.iter().fold((Vec2::new(f32::INFINITY, f32::INFINITY), Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY)), |(lo, hi), q| (Vec2::new(lo.x.min(q.x), lo.y.min(q.y)), Vec2::new(hi.x.max(q.x), hi.y.max(q.y)))); + p.x >= lo.x - radius && p.x <= hi.x + radius && p.y >= lo.y - radius && p.y <= hi.y + radius + }; + self.segs + .iter() + .filter(|c| near(c)) + .map(|c| { + let (u, d) = rawgeom::nearest(c, p); + (cubic_point(c, u), d) + }) + .filter(|(_, d)| *d <= radius) + .min_by(|a, b| a.1.total_cmp(&b.1)) } - let near = |c: &Cubic| { - let (lo, hi) = c.iter().fold((Vec2::new(f32::INFINITY, f32::INFINITY), Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY)), |(lo, hi), q| (Vec2::new(lo.x.min(q.x), lo.y.min(q.y)), Vec2::new(hi.x.max(q.x), hi.y.max(q.y)))); - p.x >= lo.x - radius && p.x <= hi.x + radius && p.y >= lo.y - radius && p.y <= hi.y + radius - }; - t.segs - .iter() - .filter(|c| near(c)) - .map(|c| { - let (u, d) = rawgeom::nearest(c, p); - (cubic_point(c, u), d) - }) - .filter(|(_, d)| *d <= radius) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(q, d)| (q, SnapTo::Line, d)) } -/// Where a point being moved (`moving`: the anchors that go with it) snaps near `to`. -fn snap_point(els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, usize)]) -> Option<(Vec2, SnapTo)> { +/// Where a point being moved (`moving`: the anchors that go with it) snaps near `to`: the +/// artwork that stays put, the guides, the grid and pixels (ADR 0076). +fn snap_point(s: &Session, els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, usize)]) -> Option<(Vec2, SnapTo)> { + if !s.style.snap_objects { + return resolve(s, to, radius, None); + } // The segments leaving the moving anchors move too. let mut segs: BTreeSet<(ElementId, usize)> = BTreeSet::new(); for e in els { @@ -494,14 +517,52 @@ fn snap_point(els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, } } let t = targets(els, |_| false, |id, c| moving.contains(&(id, c)), |id, k| segs.contains(&(id, k))); - snap_to(&t, to, radius).map(|(q, k, _)| (q, k)) + resolve(s, to, radius, Some(&t)) } -/// After the selection moved: the extra move that snaps one of its anchors (the nearest to -/// `from` when given, else whichever comes closest) onto an anchor or line of the shapes that -/// did not move, within `radius`. +/// Where a point drawn at `p` snaps (the Line, Rectangle, Oval, PolyStar and Pen tools, ADR +/// 0045; the Free Transform tool's handles): the nearest anchor within `radius`, else a guide, +/// a line or fill edge of what the stage shows near it, the grid or a pixel (ADR 0076). With +/// `moving`, the selection is what moves, so it isn't snapped to. +pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32, moving: bool) -> Option<(Vec2, SnapTo)> { + if !(radius > 0.0 && p.is_finite()) { + return None; + } + if !s.style.snap_objects { + return resolve(s, p, radius, None); + } + let dl = s.display_list(); + let mut t = Targets::default(); + for item in dl.items.iter().filter(|i| !(moving && s.selection.contains(i.layer, i.element))) { + if t.points.len() + t.segs.len() > MAX_TARGETS { + break; + } + let pad = item.stroke.as_ref().map_or(0.0, |st| st.reach() * item.transform.mean_scale()); + if !item.path.bounds().transformed(&item.transform).inflate(pad + radius).contains(p) { + continue; + } + let mut path = (*item.path).clone(); + path.close_explicitly(); + t.points.extend(path.editable_anchors().into_iter().map(|(_, q)| item.transform.apply(q))); + t.segs.extend((0..path.cmds.len().min(MAX_TARGETS)).filter_map(|k| rawgeom::segment_cubic(&path, k)).map(|c| rawgeom::transform(&c, &item.transform))); + } + resolve(s, p, radius, Some(&t)) +} + +/// After the selection moved: the extra move that snaps one of its anchors or its bounding +/// box's corners or centre (the nearest to `from` when given, else whichever snaps best) onto +/// an anchor or line of the shapes that did not move, a guide, the grid or a pixel, within +/// `radius` (ADR 0041, 0076). pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option) -> Option<(Vec2, Vec2, SnapTo)> { let mut own: Vec = Vec::new(); + // The box's corners and centre: what symbols, text and bitmaps snap by. The selection has + // just moved, so the display list is looked at again. + s.dl_cache.replace(None); + let b = s.selection_bounds(); + if !b.is_empty() { + let c = Vec2::new((b.min.x + b.max.x) * 0.5, (b.min.y + b.max.y) * 0.5); + own.extend([b.min, Vec2::new(b.max.x, b.min.y), b.max, Vec2::new(b.min.x, b.max.y), c]); + } for (_, e) in s.selected_elements() { if let ElementKind::Shape(sh) = &e.kind { own.extend(sh.path.editable_anchors().into_iter().map(|(_, q)| e.transform.apply(q))); @@ -518,12 +579,15 @@ pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option) -> Op return None; } // What stays put on the layers the selection is on (ADR 0044). - let rest: Vec> = s.selected_layers().into_iter().flat_map(|l| s.elements_on(l).into_iter().filter(move |e| !s.selection.contains(l, e.id))).collect(); - let t = targets(&rest, |_| false, |_, _| false, |_, _| false); + let t = s.style.snap_objects.then(|| { + let rest: Vec> = s.selected_layers().into_iter().flat_map(|l| s.elements_on(l).into_iter().filter(move |e| !s.selection.contains(l, e.id))).collect(); + targets(&rest, |_| false, |_, _| false, |_, _| false) + }); + let t = t.as_ref().map(|t| t as &dyn ObjectTargets); candidates .into_iter() - .filter_map(|c| snap_to(&t, c, radius).map(|(q, k, d)| (c, q, k, d))) - .min_by(|a, b| a.3.total_cmp(&b.3)) + .filter_map(|c| resolve(s, c, radius, t).map(|(q, k)| (c, q, k, q.distance(c)))) + .min_by(|a, b| a.2.rank().cmp(&b.2.rank()).then(a.3.total_cmp(&b.3))) .map(|(c, q, k, _)| (q - c, q, k)) } @@ -555,7 +619,7 @@ fn select_rect(s: &mut Session, p: &Value) -> Result { // What each layer has under the marquee, from one display list: wholly inside, or (raw // shapes) partly. let mut found: Vec<(LayerId, Vec, Vec)> = Vec::new(); - let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); + let layers: Vec = s.timeline().layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); for l in layers { let (mut picked, mut partial) = (Vec::new(), Vec::new()); for e in s.elements_on(l) { diff --git a/crates/engine/src/cmds_rawpoints.rs b/crates/engine/src/cmds_rawpoints.rs new file mode 100644 index 00000000..fb04262d --- /dev/null +++ b/crates/engine/src/cmds_rawpoints.rs @@ -0,0 +1,247 @@ +//! Adding and deleting the anchors of raw drawings, making them smooth or corners, and where a +//! point being drawn snaps (ADR 0045; issue #42 §1 and §3). +//! +//! A layer's merged drawing stores a shared point once in each shape that has it (ADR 0031), so +//! these work on positions, as the Subselection tool shows them (`raw.points`), and change every +//! copy alike: an added point is added to every shape with that edge; a deleted one is joined +//! across in every shape that has it, so the drawing stays connected. + +use crate::cmds_raw::{activate_layer_at, check_extent, follow_edge, positions_param, remerge_in_place, snap_drawn}; +use crate::merge::{mergeable, reach}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ElementId, ElementKind, Keyframe}; +use anicraft_geom::planar::SNAP; +use anicraft_geom::raw::{self as rawgeom, Seg, Sub}; +use anicraft_geom::{Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "raw.add_point", + "Add Anchor Point", + "", + None, + "{x, y, slop?} adds an anchor on the raw line or fill edge at (x, y): every raw shape with that edge gets it, and the curve keeps its shape; returns where it is", + true, + add_point as crate::RunFn, + ), + c( + "raw.delete_points", + "Delete Anchor Points", + "", + None, + "{points: [[x, y], ..]} deletes the raw anchors at those positions (as raw.points lists them): every shape that has one is joined across it, so the drawing stays connected; a free end shortens its line; a shape left with nothing is removed; a point where three or more edges meet is kept", + true, + delete_points, + ), + c( + "raw.convert_points", + "Convert Anchor Points", + "", + None, + "{points: [[x, y], ..], smooth: bool} makes the raw anchors at those positions smooth (their handles in one line) or corners (handles drawn in), in every shape that has them", + true, + convert_points, + ), + c( + "draw.snap", + "Snap Point", + "", + None, + "{x, y, snap, moving?: bool} where a point drawn at (x, y) snaps within `snap` stage units, by the snap engine's priority (ADR 0076): an anchor (Snap to Objects), a guide (Snap to Guides), a line or fill edge, the grid (Snap to Grid), a whole pixel (Snap to Pixels); `moving`: the selection is what moves (a Free Transform handle), so it isn't a target; returns {x, y, snapped: {x, y, to: point|guide|line|grid|pixel} | null}", + false, + snap_cmd, + ), + ] +} + +/// Ends of segments this near a position are at it (the copies of a shared point lie within +/// `SNAP` of each other, ADR 0042). +const ENDS: f32 = 1.5 * SNAP; + +/// The raw shapes on `kf` near `at`: index, whether filled, and stage-space subpaths. +fn near(kf: &Keyframe, at: Vec2) -> Vec<(usize, bool, Vec)> { + kf.elements + .iter() + .enumerate() + .filter_map(|(i, e)| { + let sh = mergeable(e)?; + reach(sh, &e.transform).contains(at).then(|| (i, sh.fill.is_some(), rawgeom::subpaths(&sh.path.transformed(&e.transform)))) + }) + .collect() +} + +/// The distinct edges leaving `at` among `shapes`. +fn edges(shapes: &[(usize, bool, Vec)], at: Vec2) -> Vec { + rawgeom::distinct_edges(shapes.iter().flat_map(|(_, _, subs)| rawgeom::edges_at(subs, at, ENDS)), ENDS) +} + +fn points(p: &Value) -> Result> { + let pts = positions_param(p, "points")?; + if pts.is_empty() { + return Err(EngineError::Param("param 'points' is required: the positions of the anchors, as raw.points lists them".into())); + } + Ok(pts) +} + +// ----- adding ------------------------------------------------------------------------------------ + +fn add_point(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 100.0); + activate_layer_at(s, at, slop); + // The nearest raw line or fill edge. + let mut best: Option<(f32, Vec2)> = None; + for e in s.visible_elements() { + let Some(sh) = mergeable(&e) else { continue }; + if !reach(sh, &e.transform).inflate(slop).contains(at) { + continue; + } + let mut path = (*sh.path).clone(); + path.close_explicitly(); + let half = sh.stroke.as_ref().map_or(0.0, |st| st.width * 0.5 * e.transform.mean_scale()); + if let Some((cmd, t, d)) = path.nearest_segment(at, &e.transform) + && d <= slop + half + && best.is_none_or(|b| d < b.0) + && let Some(q) = path.segment_point(cmd, t) + { + best = Some((d, e.transform.apply(q))); + } + } + let (_, q) = best.ok_or_else(|| EngineError::State("no line or fill edge of a merged drawing there".into()))?; + let kf = s.editable_keyframe()?; + if near(kf, q).iter().any(|(_, _, subs)| subs.iter().flat_map(|sb| &sb.segs).any(|g| g.c[0].distance(q) <= 2.0 * SNAP || g.c[3].distance(q) <= 2.0 * SNAP)) { + return Err(EngineError::State("there is a point there already".into())); + } + let mut changed = Vec::new(); + for e in kf.elements.iter_mut() { + let Some(sh) = mergeable(e) else { continue }; + if !reach(sh, &e.transform).contains(q) { + continue; + } + let Some(inv) = e.transform.inverse() else { continue }; + let mut path = (*sh.path).clone(); + path.close_explicitly(); + let len = path.cmds.len(); + // Splits the segment through the point (de Casteljau: the curve is unchanged). + rawgeom::anchors_at(&mut path, inv.apply(q), SNAP / e.transform.mean_scale().max(1e-6)); + if path.cmds.len() == len { + continue; + } + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(path); + } + changed.push(e.id); + } + if changed.is_empty() { + return Err(EngineError::State("cannot add a point there".into())); + } + // Nothing moved, so nothing merges: the point stays until a merge finds it on a straight + // line that it no longer bends (issue #42 §1). + Ok(json!({"x": q.x, "y": q.y, "changed": changed.iter().map(|e| e.0).collect::>()})) +} + +// ----- deleting ---------------------------------------------------------------------------------- + +fn delete_points(s: &mut Session, p: &Value) -> Result { + let pts = points(p)?; + let (mut deleted, mut kept) = (0usize, 0usize); + let mut changed: Vec = Vec::new(); + let mut removed: Vec = Vec::new(); + for at in pts { + let kf = s.editable_keyframe()?; + let shapes = near(kf, at); + let edges = edges(&shapes, at); + let joined = match edges.as_slice() { + [] => continue, + [_] => None, + [a, b] => Some(rawgeom::join(a, b).ok_or_else(|| EngineError::Param("cannot join the lines across that point".into()))?), + _ => { + kept += 1; + continue; + } + }; + let mut gone: Vec = Vec::new(); + let mut any = false; + for (i, filled, mut subs) in shapes { + if !rawgeom::delete_anchor(&mut subs, at, &edges, joined.as_ref(), ENDS) { + continue; + } + rawgeom::tidy(&mut subs, filled); + let Some(e) = kf.elements.get_mut(i) else { continue }; + any = true; + if subs.is_empty() { + gone.push(e.id); + continue; + } + let Some(inv) = e.transform.inverse() else { continue }; + let path: Path = rawgeom::from_subpaths(&subs).transformed(&inv); + check_extent(&path)?; + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(path); + } + if !changed.contains(&e.id) { + changed.push(e.id); + } + } + kf.elements.retain(|e| !gone.contains(&e.id)); + changed.retain(|id| !gone.contains(id)); + removed.extend(gone); + deleted += usize::from(any); + } + if deleted == 0 { + return Err(EngineError::State(if kept > 0 { "a point where three or more lines meet can't be deleted; delete a line there instead".into() } else { "no point of a merged drawing there".into() })); + } + let here = s.layer; + s.selection.retain(|l, id| l != here || !removed.contains(&id)); + // Joined runs and fills merge again with what they touch, as after any edit. + remerge_in_place(s, &changed)?; + Ok(json!({"deleted": deleted, "kept": kept, "removed": removed.iter().map(|e| e.0).collect::>(), "selected": s.selection.id_list()})) +} + +// ----- smooth and corner ------------------------------------------------------------------------- + +fn convert_points(s: &mut Session, p: &Value) -> Result { + let pts = points(p)?; + let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required".into()))?; + let mut changed: Vec = Vec::new(); + let mut converted = 0usize; + for at in pts { + let kf = s.editable_keyframe()?; + let edges = edges(&near(kf, at), at); + let edits: Vec<(Seg, Seg)> = if smooth { + match edges.as_slice() { + [a, b] => rawgeom::smooth_pair(a, b).map(|(na, nb)| vec![(*a, na), (*b, nb)]).unwrap_or_default(), + _ => Vec::new(), + } + } else { + edges.iter().filter_map(|e| rawgeom::corner(e).map(|n| (*e, n))).collect() + }; + converted += usize::from(!edits.is_empty()); + for (old, new) in edits { + for id in follow_edge(s, None, &old.c, &new.c)? { + if !changed.contains(&id) { + changed.push(id); + } + } + } + } + remerge_in_place(s, &changed)?; + Ok(json!({"converted": converted, "changed": changed.len()})) +} + +// ----- snapping while drawing -------------------------------------------------------------------- + +fn snap_cmd(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let radius = opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0); + let moving = opt_bool(p, "moving")?.unwrap_or(false); + Ok(match snap_drawn(s, at, radius, moving) { + Some((q, kind)) => json!({"x": q.x, "y": q.y, "snapped": {"x": q.x, "y": q.y, "to": kind.key()}}), + None => json!({"x": at.x, "y": at.y, "snapped": null}), + }) +} diff --git a/crates/engine/src/cmds_rawsub.rs b/crates/engine/src/cmds_rawsub.rs index 7187da73..93114ea8 100644 --- a/crates/engine/src/cmds_rawsub.rs +++ b/crates/engine/src/cmds_rawsub.rs @@ -10,8 +10,8 @@ //! Which anchors are selected is view state, kept by the editor (as for drawing objects): the //! commands here report anchors and handles by stage position, and take positions back. -use crate::cmds_raw::{check_extent, edit_edge, remerge_in_place}; -use crate::merge::mergeable; +use crate::cmds_raw::{check_extent, edit_edge, follow_edge, remerge_in_place}; +use crate::merge::{mergeable, reach}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{Element, ElementId, ElementKind}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Move Handle", "", None, - "{id, cmd, slot: 1|2, dx, dy, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false)", + "{id, cmd, slot: 1|2, dx, dy, smooth?: bool, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false); at a smooth anchor the other handle turns to stay opposite, keeping its length (unless smooth is false: Alt breaks the pair)", true, move_handle, ), @@ -378,7 +378,7 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { if !add { s.selection.clear(); } - let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer); + let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.timeline().locked_by_folder(s.layer); let empty = json!({"selected": s.selection.id_list(), "anchors": []}); if !usable || !(r.width() > 0.0 || r.height() > 0.0) { return Ok(empty); @@ -400,6 +400,32 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { // ----- handles ----------------------------------------------------------------------------------- +/// The other curve at the anchor of handle `slot` of `old` (stage space) when the anchor is smooth +/// there: the one edge leaving it whose handle lies opposite this one ([`rawgeom::smooth_at`]), in +/// any raw shape on the layer (or in `el` alone, a drawing object). Oriented from the anchor. +fn opposite_handle(els: &[Arc], el: &Element, raw: bool, old: &Cubic, slot: usize) -> Option { + let (a, h) = if slot == 1 { (old[0], old[1]) } else { (old[3], old[2]) }; + let dragged = rawgeom::Seg { c: if slot == 1 { *old } else { [old[3], old[2], old[1], old[0]] }, line: false }; + let tol = 1.5 * SNAP; + let mut subs = Vec::new(); + let from = |e: &Element| match &e.kind { + ElementKind::Shape(sh) => rawgeom::subpaths(&sh.path.transformed(&e.transform)), + _ => Vec::new(), + }; + if raw { + for e in els.iter().filter(|e| mergeable(e).is_some_and(|sh| reach(sh, &e.transform).contains(a))) { + subs.extend(from(e)); + } + } else { + subs = from(el); + } + let edges = rawgeom::distinct_edges(rawgeom::edges_at(&subs, a, tol), tol); + let mut found = edges.into_iter().filter(|f| !rawgeom::same_edge(f, &dragged, tol) && !f.line && rawgeom::smooth_at(a, h, f.c[1])); + let f = found.next()?; + // Two candidates: a junction, not a smooth pair. + found.next().is_none().then_some(f) +} + fn move_handle(s: &mut Session, p: &Value) -> Result { let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?); let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?; @@ -426,7 +452,18 @@ fn move_handle(s: &mut Session, p: &Value) -> Result { bounds.move_to(new[0]).cubic_to(new[1], new[2], new[3]); check_extent(&bounds)?; let raw = mergeable(el).is_some(); - let changed = edit_edge(s, id, cmd, &old, &new, raw)?; + // A smooth anchor's other handle turns with this one (ADR 0045). + let partner = if opt_bool(p, "smooth")?.unwrap_or(true) { opposite_handle(&els, el, raw, &old, slot).map(|f| (f, new[slot])) } else { None }; + let mut changed = edit_edge(s, id, cmd, &old, &new, raw)?; + if let Some((f, h)) = partner { + let a = f.c[0]; + let turned = rawgeom::Seg { c: [a, rawgeom::turned_opposite(a, h, f.c[1]), f.c[2], f.c[3]], line: false }; + for e in follow_edge(s, (!raw).then_some(id), &f.c, &turned.c)? { + if !changed.contains(&e) { + changed.push(e); + } + } + } if raw && merge_after { remerge_in_place(s, &changed)?; } diff --git a/crates/engine/src/cmds_recent.rs b/crates/engine/src/cmds_recent.rs new file mode 100644 index 00000000..c2de5508 --- /dev/null +++ b/crates/engine/src/cmds_recent.rs @@ -0,0 +1,365 @@ +//! Recent files (ADR 0059): the documents opened or saved last, most recent first, with pinned +//! favourites kept above them. The list belongs to the session (it survives New and Open) and +//! is plain data: the desktop app keeps it in its preferences and puts it back at start, so the +//! engine never reads or writes the settings folder. `file.open` and `file.save` add to it; +//! these commands open, pin, remove and clear entries for menus, the CLI and MCP alike. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Most recent (unpinned) files kept, as Animate's Open Recent shows. +pub const MAX_RECENT: usize = 10; +/// Most pinned favourites. +pub const MAX_PINNED: usize = 10; +/// Longest path kept (anything longer is not a path a user picked). +const MAX_PATH_BYTES: usize = 4096; + +/// One file in the list. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RecentFile { + pub path: PathBuf, + /// A favourite: it stays at the top, and adding or clearing recent files leaves it alone. + pub pinned: bool, +} + +/// Pinned favourites first (in the order they were pinned), then the recent files, most recent +/// first. At most [`MAX_PINNED`] + [`MAX_RECENT`] entries, never the same file twice. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct RecentFiles { + entries: Vec, +} + +/// Whether two paths name the same file as the user sees it: Windows and macOS file names +/// ignore case (by default), and Windows takes either slash. +pub fn same_file(a: &Path, b: &Path) -> bool { + if cfg!(any(windows, target_os = "macos")) { + let norm = |p: &Path| p.to_string_lossy().replace('\\', "/").to_lowercase(); + norm(a) == norm(b) + } else { + a == b + } +} + +/// Whether a recent file is still there to open (a file, or an XFL folder). +pub fn exists(path: &Path) -> bool { + crate::vfs::is_file(path) || crate::vfs::is_dir(path) +} + +/// A short, stable key for a path (64-bit FNV-1a of its normalised text, as hex): the name its +/// thumbnail is kept under. +pub fn thumb_key(path: &Path) -> String { + let text = if cfg!(any(windows, target_os = "macos")) { path.to_string_lossy().replace('\\', "/").to_lowercase() } else { path.to_string_lossy().into_owned() }; + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in text.bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{h:016x}") +} + +/// Largest edge of a recent file's thumbnail, in pixels. +pub const THUMB_W: u32 = 240; +pub const THUMB_H: u32 = 135; + +/// The document's first frame as a small PNG that fits [`THUMB_W`] × [`THUMB_H`] (the start +/// screen's picture of a recent file), rendered by the CPU oracle. +pub fn thumbnail_png(doc: &anicraft_doc::Document) -> Result> { + let (w, h) = (doc.stage.width.max(1) as f32, doc.stage.height.max(1) as f32); + let scale = (THUMB_W as f32 / w).min(THUMB_H as f32 / h).min(1.0); + crate::cmds_file::render_png(doc, 0, scale) +} + +impl RecentFiles { + pub fn entries(&self) -> &[RecentFile] { + &self.entries + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + fn position(&self, path: &Path) -> Option { + self.entries.iter().position(|e| same_file(&e.path, path)) + } + + fn pinned_count(&self) -> usize { + self.entries.iter().take_while(|e| e.pinned).count() + } + + /// A file was opened or saved: it becomes the most recent. A pinned file keeps its place; + /// the oldest recent file beyond [`MAX_RECENT`] drops off. Returns whether the list changed. + pub fn add(&mut self, path: &Path) -> bool { + if path.as_os_str().is_empty() || path.as_os_str().len() > MAX_PATH_BYTES { + return false; + } + let before = self.entries.clone(); + if let Some(i) = self.position(path) { + if self.entries.get(i).is_some_and(|e| e.pinned) { + return false; + } + self.entries.remove(i); + } + let at = self.pinned_count(); + self.entries.insert(at, RecentFile { path: path.to_path_buf(), pinned: false }); + self.entries.truncate(at + MAX_RECENT); + before != self.entries + } + + /// Takes a file off the list (pinned or not). Returns whether it was there. + pub fn remove(&mut self, path: &Path) -> bool { + match self.position(path) { + Some(i) => { + self.entries.remove(i); + true + } + None => false, + } + } + + /// Pins a file (it goes below the other pinned files) or unpins it (it becomes the most + /// recent file). A file not on the list is added pinned. + pub fn pin(&mut self, path: &Path, pinned: bool) -> std::result::Result<(), String> { + let current = self.position(path).and_then(|i| self.entries.get(i)).map(|e| e.pinned); + if current == Some(pinned) { + return Ok(()); + } + if pinned && self.pinned_count() >= MAX_PINNED { + return Err(format!("at most {MAX_PINNED} files can be pinned; unpin one first")); + } + if path.as_os_str().is_empty() || path.as_os_str().len() > MAX_PATH_BYTES { + return Err("that is not a file path".into()); + } + self.remove(path); + let at = self.pinned_count(); + self.entries.insert(at, RecentFile { path: path.to_path_buf(), pinned }); + let pins = self.pinned_count(); + self.entries.truncate(pins + MAX_RECENT); + Ok(()) + } + + /// Clears the recent files; pinned favourites stay unless `pinned` too. Returns how many + /// were taken off. + pub fn clear(&mut self, pinned: bool) -> usize { + let before = self.entries.len(); + self.entries.retain(|e| e.pinned && !pinned); + before - self.entries.len() + } + + /// The list as read from a preferences file that anyone may have edited: empty and overlong + /// paths and repeats dropped, pinned files first, each part within its limit. + pub fn sanitized(self) -> RecentFiles { + let mut out = RecentFiles::default(); + let (pins, recents): (Vec, Vec) = self.entries.into_iter().partition(|e| e.pinned); + for e in pins.into_iter().chain(recents) { + let bad = e.path.as_os_str().is_empty() || e.path.as_os_str().len() > MAX_PATH_BYTES; + if bad || out.position(&e.path).is_some() { + continue; + } + let pins = out.pinned_count(); + if (e.pinned && pins >= MAX_PINNED) || (!e.pinned && out.entries.len() - pins >= MAX_RECENT) { + continue; + } + out.entries.push(e); + } + out + } +} + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "file.open_recent", + label: "Open Recent", + // The File menu shows the files themselves (a submenu the shell draws). + menu: "", + shortcut: None, + params: "{index? (in file.recent_list order, from 0) | path?, confirm? (needed over unsaved changes)}: opens it as file.open does; a file that is no longer there stays on the list, marked missing", + mutates: false, + run: open_recent, + }, + CommandSpec { + id: "file.recent_list", + label: "Recent Files", + menu: "", + shortcut: None, + params: "{} → {files: [{index, path, name, pinned, missing, thumb}]}: pinned favourites first, then the last 10 files opened or saved, most recent first (`thumb` names the start screen's picture)", + mutates: false, + run: list, + }, + CommandSpec { + id: "prefs.recent_pin", + label: "Pin to Recent Files", + menu: "", + shortcut: None, + params: "{index? | path?, pinned? (default: toggle)}: a pinned file stays at the top of Open Recent", + mutates: false, + run: pin, + }, + CommandSpec { id: "prefs.recent_remove", label: "Remove from Recent Files", menu: "", shortcut: None, params: "{index? | path?}", mutates: false, run: remove }, + CommandSpec { + id: "prefs.recent_clear", + label: "Clear Recent Files", + menu: "", + shortcut: None, + params: "{pinned? (default false: pinned favourites stay)} → {removed}", + mutates: false, + run: clear, + }, + ] +} + +/// The entry `index` or `path` names. +fn which(s: &Session, p: &Value) -> Result { + match (opt_u64(p, "index")?, opt_str(p, "path")?) { + (Some(i), None) => usize::try_from(i).ok().and_then(|i| s.recent.entries().get(i)).map(|e| e.path.clone()).ok_or_else(|| EngineError::Param(format!("no recent file {i}; file.recent_list has {}", s.recent.len()))), + (None, Some(path)) if !path.trim().is_empty() => Ok(PathBuf::from(path)), + (None, Some(_)) => Err(EngineError::Param("param 'path' must name a file".into())), + _ => Err(EngineError::Param("name the file with 'index' or 'path' (one of them)".into())), + } +} + +fn open_recent(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + if !exists(&path) { + return Err(EngineError::State(format!("{} is no longer there (moved, renamed or deleted); remove it from Open Recent", path.display()))); + } + crate::cmds_file::open(s, &json!({"path": path.display().to_string()})) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let files: Vec = s + .recent + .entries() + .iter() + .enumerate() + .map(|(i, e)| { + let name = e.path.file_name().map_or_else(|| e.path.display().to_string(), |n| n.to_string_lossy().into_owned()); + json!({"index": i, "path": e.path.display().to_string(), "name": name, "pinned": e.pinned, "missing": !exists(&e.path), "thumb": thumb_key(&e.path)}) + }) + .collect(); + Ok(json!({"files": files})) +} + +fn pin(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + let now = s.recent.entries().iter().find(|e| same_file(&e.path, &path)).is_some_and(|e| e.pinned); + let pinned = opt_bool(p, "pinned")?.unwrap_or(!now); + s.recent.pin(&path, pinned).map_err(EngineError::State)?; + Ok(json!({"path": path.display().to_string(), "pinned": pinned})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let path = which(s, p)?; + if !s.recent.remove(&path) { + return Err(EngineError::State(format!("{} is not in the recent files", path.display()))); + } + Ok(json!({"removed": path.display().to_string()})) +} + +fn clear(s: &mut Session, p: &Value) -> Result { + let pinned = opt_bool(p, "pinned")?.unwrap_or(false); + Ok(json!({"removed": s.recent.clear(pinned)})) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn paths(r: &RecentFiles) -> Vec { + r.entries().iter().map(|e| format!("{}{}", if e.pinned { "*" } else { "" }, e.path.display())).collect() + } + + #[test] + fn most_recent_first_ten_at_most_never_twice() { + let mut r = RecentFiles::default(); + for i in 0..14 { + assert!(r.add(Path::new(&format!("f{i}.anicraft")))); + } + assert_eq!(r.len(), MAX_RECENT); + assert_eq!(paths(&r).first().map(String::as_str), Some("f13.anicraft")); + assert_eq!(paths(&r).last().map(String::as_str), Some("f4.anicraft"), "the oldest drop off"); + // Opening one again moves it to the top, without a second entry. + assert!(r.add(Path::new("f8.anicraft"))); + assert_eq!(paths(&r)[..2], ["f8.anicraft", "f13.anicraft"]); + assert_eq!(r.len(), MAX_RECENT); + assert!(!r.add(Path::new("f8.anicraft")), "already the most recent"); + assert!(!r.add(Path::new("")), "no empty paths"); + } + + #[test] + fn pinned_files_stay_on_top_and_survive_clearing() { + let mut r = RecentFiles::default(); + for f in ["a", "b", "c"] { + r.add(Path::new(f)); + } + r.pin(Path::new("a"), true).unwrap(); + assert_eq!(paths(&r), ["*a", "c", "b"]); + // New files go below the pins; opening a pinned file leaves it where it is. + r.add(Path::new("d")); + assert!(!r.add(Path::new("a"))); + assert_eq!(paths(&r), ["*a", "d", "c", "b"]); + // Pins don't count towards the ten recent files. + for i in 0..12 { + r.add(Path::new(&format!("n{i}"))); + } + assert_eq!(r.len(), 1 + MAX_RECENT); + assert_eq!(r.clear(false), MAX_RECENT); + assert_eq!(paths(&r), ["*a"]); + // Unpinning makes it the most recent file. + r.add(Path::new("z")); + r.pin(Path::new("a"), false).unwrap(); + assert_eq!(paths(&r), ["a", "z"]); + assert!(r.remove(Path::new("z"))); + assert!(!r.remove(Path::new("z"))); + assert_eq!(r.clear(true), 1); + assert!(r.is_empty()); + for i in 0..MAX_PINNED { + r.pin(Path::new(&format!("p{i}")), true).unwrap(); + } + assert!(r.pin(Path::new("one too many"), true).is_err()); + } + + #[test] + fn a_hand_edited_list_is_cleaned_up() { + let raw = r#"[{"path": "b"}, {"path": "", "pinned": true}, {"path": "a", "pinned": true}, {"path": "b"}, {"nonsense": 1}]"#; + let r: RecentFiles = serde_json::from_str::(raw).unwrap().sanitized(); + assert_eq!(paths(&r), ["*a", "b"]); + let many: Vec = (0..40).map(|i| RecentFile { path: PathBuf::from(format!("{i}")), pinned: i % 2 == 0 }).collect(); + let r = RecentFiles { entries: many }.sanitized(); + assert_eq!(r.entries().iter().filter(|e| e.pinned).count(), MAX_PINNED); + assert_eq!(r.entries().iter().filter(|e| !e.pinned).count(), MAX_RECENT); + assert!(r.entries().iter().take(MAX_PINNED).all(|e| e.pinned), "pins first"); + assert!(RecentFiles { entries: vec![RecentFile { path: PathBuf::from("x".repeat(5000)), pinned: false }] }.sanitized().is_empty()); + } + + #[test] + fn thumbnail_keys_are_stable_and_distinct() { + assert_eq!(thumb_key(Path::new("a/b.anicraft")), thumb_key(Path::new("a/b.anicraft"))); + assert_ne!(thumb_key(Path::new("a/b.anicraft")), thumb_key(Path::new("a/c.anicraft"))); + assert_eq!(thumb_key(Path::new("x")).len(), 16); + } + + #[test] + fn thumbnails_fit_the_start_screen() { + let t = std::time::Instant::now(); + let png = thumbnail_png(&anicraft_doc::sample::demo()).unwrap(); + eprintln!("thumbnail of the sample: {:.2} ms, {} bytes", t.elapsed().as_secs_f64() * 1000.0, png.len()); + let img = image_size(&png); + assert!(img.0 <= THUMB_W && img.1 <= THUMB_H && img.0 > 0 && img.1 > 0, "{img:?}"); + } + + /// Width and height from a PNG's header. + fn image_size(png: &[u8]) -> (u32, u32) { + let be = |i: usize| u32::from_be_bytes([png[i], png[i + 1], png[i + 2], png[i + 3]]); + (be(16), be(20)) + } +} diff --git a/crates/engine/src/cmds_retime.rs b/crates/engine/src/cmds_retime.rs new file mode 100644 index 00000000..83ecae69 --- /dev/null +++ b/crates/engine/src/cmds_retime.rs @@ -0,0 +1,191 @@ +//! Retiming tweens (ADR 0083): property keys dragged in time in the Motion Editor, a span's +//! length changed with its keys stretched in proportion, and Split / Join Motion. +//! +//! Moving whole spans (and Alt-drag copies) is `timeline.move_spans`, beside the other frame +//! moves in `cmds_timeline`. + +use crate::cmds_timeline::{shift_after, target}; +use crate::params::*; +use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session}; +use anicraft_doc::{Element, KeyRef, Keyframe, Layer, LayerKind, Property}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("motion.move_keys", "Move Property Keyframes", "", None, "{keys: [{property, frame}, ..] (frames as motion.info lists them), by (frames; negative = earlier), layer?, frame? (in the span; default: the first key's)}: values and eases travel with their keys; no key moves outside the span or onto or past a key of its property that isn't moving (the move stops there); a pinned path point's X and Y keys move together → {by, keys}", true, move_keys as crate::RunFn), + c("timeline.resize_span", "Span Length", "", None, "{frames (the new length), layer?, frame?, scale_keys?: false (keep a motion tween's keys where they are; default: they stretch in proportion, as dragging the span's end in Animate)}: later frames move with the end, as with F5 / Shift+F5 → {start, frames, scaled}", true, resize_span), + c("motion.split", "Split Motion", "Modify/Timeline", None, "{layer?, frame?}: the motion tween becomes two at the frame, each moving as before → {first, second}", true, split), + c("motion.join", "Join Motion", "Modify/Timeline", None, "{layer?, frame?, to? (the last frame of the spans to join; default: the span after the one at the frame)}: adjacent motion tweens of one object become one, keeping every frame as it was → {start, frames, joined}", true, join), + ] +} + +/// The most keys one `motion.move_keys` call names. +const MAX_MOVED: usize = 100_000; + +fn keys_param(p: &Value) -> Result> { + let list = p.get("keys").and_then(Value::as_array).ok_or_else(|| EngineError::Param("param 'keys' is required: a list of {property, frame}".into()))?; + if list.is_empty() { + return Err(EngineError::Param("param 'keys' lists no key".into())); + } + if list.len() > MAX_MOVED { + return Err(EngineError::Param(format!("param 'keys' lists more than {MAX_MOVED} keys"))); + } + let mut out = Vec::with_capacity(list.len()); + for k in list { + let name = opt_str(k, "property")?.ok_or_else(|| EngineError::Param("each key needs a 'property'".into()))?; + let prop = Property::from_key(name).ok_or_else(|| EngineError::Param(format!("unknown property '{name}'")))?; + let frame = opt_u32(k, "frame")?.ok_or_else(|| EngineError::Param("each key needs a 'frame'".into()))?; + if frame > MAX_FRAME { + return Err(EngineError::Param(format!("key frames must be at most {MAX_FRAME}"))); + } + out.push((prop, frame)); + } + Ok(out) +} + +fn move_keys(s: &mut Session, p: &Value) -> Result { + let keys = keys_param(p)?; + let by = p.get("by").and_then(Value::as_i64).ok_or_else(|| EngineError::Param("param 'by' must be a whole number of frames".into()))?; + if by.unsigned_abs() > u64::from(MAX_FRAME) { + return Err(EngineError::Param(format!("param 'by' must be within ±{MAX_FRAME}"))); + } + let lid = opt_u64(p, "layer")?.map(anicraft_doc::LayerId); + let at = match opt_u32(p, "frame")? { + Some(f) if f > MAX_FRAME => return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))), + Some(f) => f, + None => keys.first().map_or(s.frame, |k| k.1), + }; + let layer = s.layer_mut(lid)?; + let i = layer.keyframe_index_at(at).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", at + 1)))?; + let kf = layer.keyframe_mut(i).ok_or_else(|| EngineError::State("keyframe vanished".into()))?; + let (start, last) = (kf.start, kf.duration.saturating_sub(1)); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State(format!("frame {} is not in a motion tween", at + 1)))?; + let mut picked: Vec = Vec::with_capacity(keys.len()); + for (prop, f) in keys { + let off = f.checked_sub(start).filter(|o| m.track(prop).is_some_and(|t| t.key_at(*o).is_some())); + let Some(off) = off else { return Err(EngineError::State(format!("there is no {} keyframe at frame {}", prop.label(), f + 1))) }; + picked.push((prop, off)); + } + let (moved, now) = m.move_keys(&picked, by, last); + let keys: Vec = now.iter().map(|(p, f)| json!({"property": p.key(), "frame": start + f})).collect(); + Ok(json!({"by": moved, "keys": keys})) +} + +fn resize_span(s: &mut Session, p: &Value) -> Result { + let frames = opt_u32(p, "frames")?.ok_or_else(|| EngineError::Param("param 'frames' (the span's new length) is required".into()))?; + if !(1..=MAX_FRAME).contains(&frames) { + return Err(EngineError::Param(format!("param 'frames' must be between 1 and {MAX_FRAME}"))); + } + let scale = opt_bool(p, "scale_keys")?.unwrap_or(true); + let (lid, frame) = target(s, p)?; + let layer = s.layer_mut(lid)?; + if layer.kind == LayerKind::Folder { + return Err(EngineError::State("a folder holds layers, not frames; pick a layer inside it".into())); + } + let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; + let (start, old, end) = layer.keyframes.get(i).map(|k| (k.start, k.duration, k.end())).ok_or_else(|| EngineError::State("keyframe vanished".into()))?; + let grow = i64::from(frames) - i64::from(old); + if grow > 0 && i64::from(layer.end_frame()) + grow > i64::from(MAX_FRAME) + 1 { + return Err(EngineError::State("the timeline is at its maximum length".into())); + } + let scaled = resize(layer, i, frames, scale); + // Later frames move with the end, as with F5 / Shift+F5. + shift_after(layer, end, grow); + layer.normalize(); + Ok(json!({"start": start, "frames": frames, "scaled": scaled})) +} + +/// Sets keyframe `i`'s length to `frames`, stretching its motion tween's keys when `scale`. +/// Whether keys were stretched. +fn resize(layer: &mut Layer, i: usize, frames: u32, scale: bool) -> bool { + let Some(k) = layer.keyframe_mut(i) else { return false }; + let old = k.duration; + k.duration = frames; + match k.motion.as_mut() { + Some(m) if scale && old > 1 && frames > 1 && old != frames => { + m.stretch(old, frames); + true + } + _ => false, + } +} + +fn split(s: &mut Session, p: &Value) -> Result { + let (lid, frame) = target(s, p)?; + let layer = s.layer_mut(lid)?; + let k = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; + if k.motion.is_none() { + return Err(EngineError::State(format!("frame {} is not in a motion tween", frame + 1))); + } + let first = k.start; + if frame == first { + return Err(EngineError::State(format!("frame {} is the tween's first frame: split it at a later frame", frame + 1))); + } + // The cut a copied keyframe makes inside a span keeps the motion in both halves. + crate::cmds_timeline::insert_keyframe_at(layer, frame, true)?; + Ok(json!({"first": first, "second": frame})) +} + +fn join(s: &mut Session, p: &Value) -> Result { + let (lid, frame) = target(s, p)?; + let to = opt_u32(p, "to")?; + let layer = s.layer_mut(lid)?; + let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; + let (start, end) = layer.keyframes.get(i).filter(|k| k.motion.is_some()).map(|k| (k.start, k.end())).ok_or_else(|| EngineError::State(format!("frame {} is not in a motion tween", frame + 1)))?; + let to = to.unwrap_or(end); + if to < end { + return Err(EngineError::State("there is only one motion tween in those frames: Join Motion joins it with the ones after it".into())); + } + let mut joined = 0; + while let Some(next) = layer.keyframes.get(i + 1).filter(|n| n.start <= to) { + let next = Arc::clone(next); + let Some(kf) = layer.keyframes.get(i) else { break }; + let merged = join_pair(kf, &next)?; + layer.keyframes.remove(i + 1); + if let Some(slot) = layer.keyframes.get_mut(i) { + *slot = Arc::new(merged); + } + joined += 1; + } + if joined == 0 { + return Err(EngineError::State(format!("no motion tween starts right after frame {}", end))); + } + layer.normalize(); + let frames = layer.keyframes.get(i).map_or(0, |k| k.duration); + Ok(json!({"start": start, "frames": frames, "joined": joined + 1})) +} + +/// The span `a` and the span `b` right after it, as one motion tween span. +fn join_pair(a: &Keyframe, b: &Keyframe) -> Result { + let shown = b.start + 1; + if b.start != a.end() { + return Err(EngineError::State(format!("the span at frame {shown} doesn't start where the tween before it ends"))); + } + let (Some(ma), Some(mb)) = (&a.motion, &b.motion) else { + return Err(EngineError::State(format!("the span at frame {shown} has no motion tween: Join Motion joins motion tweens"))); + }; + if b.sound.is_some() || b.script.is_some() { + return Err(EngineError::State(format!("the keyframe at frame {shown} has a sound or actions, which joining would drop: move them first"))); + } + let lost = || EngineError::State("a motion tween's object is no longer on its keyframe".into()); + let ia = ma.target_index(&a.elements).ok_or_else(lost)?; + let ib = mb.target_index(&b.elements).ok_or_else(lost)?; + let (ta, tb) = (a.elements.get(ia).ok_or_else(lost)?, b.elements.get(ib).ok_or_else(lost)?); + if ta.kind != tb.kind { + return Err(EngineError::State(format!("the tween at frame {shown} animates another object: Join Motion joins the tweens of one object"))); + } + let others = |k: &Keyframe, t: usize| -> Vec { k.elements.iter().enumerate().filter(|(j, _)| *j != t).map(|(_, e)| (**e).clone()).collect() }; + if others(a, ia) != others(b, ib) { + return Err(EngineError::State(format!("the span at frame {shown} holds other artwork than the tween before it: Join Motion joins spans that differ only in the tweened object"))); + } + let m = ma.join(ta, a.duration, mb, tb).ok_or_else(|| EngineError::State("Join Motion can't join tweens with motion paths yet (unless one was split from the other): remove a path first".into()))?; + let mut k = a.clone(); + k.duration = a.duration.saturating_add(b.duration); + k.motion = Some(m); + if k.label.is_empty() { + k.label.clone_from(&b.label); + } + Ok(k) +} diff --git a/crates/engine/src/cmds_scene.rs b/crates/engine/src/cmds_scene.rs index 4ff21586..b619c6c8 100644 --- a/crates/engine/src/cmds_scene.rs +++ b/crates/engine/src/cmds_scene.rs @@ -31,10 +31,12 @@ pub(crate) fn target_scene(s: &Session, p: &Value) -> Result { } /// Opens scene `i` at its first frame, on its top layer. -fn open_scene(s: &mut Session, i: usize) { +pub(crate) fn open_scene(s: &mut Session, i: usize) { + // A scene is edited from its own timeline: open symbols close first (ADR 0045). + s.exit_all(); s.scene = i.min(s.doc.scenes.len().saturating_sub(1)); s.frame = 0; - 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(); } @@ -125,7 +127,7 @@ fn duplicate_scene(s: &mut Session, p: &Value) -> Result { let Some(src) = s.doc.scenes.get(i).cloned() else { return Err(EngineError::State("no such scene".into())) }; let timeline = reid(s, &src.timeline); let name = unused_name(s, &format!("{} copy", src.name)); - s.doc.scenes.insert(i + 1, Arc::new(Scene { name, timeline })); + s.doc.scenes.insert(i + 1, Arc::new(Scene { name, timeline, guides: src.guides.clone() })); open_scene(s, i + 1); Ok(scene_json(s)) } diff --git a/crates/engine/src/cmds_script.rs b/crates/engine/src/cmds_script.rs index 8ab992b3..0ddb7de1 100644 --- a/crates/engine/src/cmds_script.rs +++ b/crates/engine/src/cmds_script.rs @@ -13,8 +13,10 @@ use crate::cmds_actions::{Scope, keyframe_in}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::actions::as3::Problem; use anicraft_doc::actions::{self, CompileResult, FrameScript, Language, SourceScript}; -use anicraft_doc::{Linkage, SymbolId}; +use anicraft_doc::player::{TimelineRef, link_problems}; +use anicraft_doc::{Document, Linkage, SymbolId, SymbolKind}; use serde_json::{Value, json}; use std::sync::Arc; @@ -24,7 +26,7 @@ pub fn specs() -> Vec { c("script.set", "Set Frame Script", "", None, "{text?: the script, verbatim (\"\" clears; at most 1 MiB), language?: actionscript3|actionscript1or2|other (default: the script's, else actionscript3), symbol?: id, layer?, frame?} keeps a script on the keyframe at the frame (it replaces actions there); ActionScript 3.0 in the subset runs in Test Movie and the HTML export, the rest is kept and not run (`runs`, `problems` say which)", true, set as crate::RunFn), c("script.clear", "Clear Frame Script", "", None, "{symbol?, layer?, frame?} removes the keyframe's kept script (actions are left alone: actions.clear)", true, clear), c("script.list", "List Frame Scripts", "", None, "{text?: bool (default true)} every kept script in every scene and symbol, with its text, whether it runs and its problems, plus symbol linkage classes and the document class", false, list), - c("script.check", "Check Frame Script", "", None, "{text: the script, language?: actionscript3|actionscript1or2|other (default actionscript3)} whether it would run (the ActionScript 3.0 subset, ADR 0013), its problems with line and column, what is ignored, and the steps it runs; changes nothing", false, check), + c("script.check", "Check Frame Script", "", None, "{text: the script, language?: actionscript3|actionscript1or2|other (default actionscript3)} whether it would run (the ActionScript 3.0 subset, ADR 0013), its problems with line and column, what is ignored, the names it takes from other frames of its timeline (`uses`), and what it compiles to (`steps`, `program`); changes nothing", false, check), c("script.set_class", "Set Script Class", "", None, "{symbol?: id (default: the document), class: dotted class name (\"\" clears), base?: the class it extends} sets a symbol's linkage class, or the document class; kept as text, not run", true, set_class), ] } @@ -47,14 +49,33 @@ fn what(script: &Option) -> Value { } /// Whether a script runs, its problems and notes (each `{line, column, message}`; line 0 is -/// the whole script). -fn status(c: &CompileResult) -> Value { +/// the whole script). `links`: why it doesn't run on its timeline although it compiles (a +/// name from another frame that isn't there, ADR 0052). +fn status(c: &CompileResult, links: &[Problem]) -> Value { match c { - Ok(c) => json!({"runs": true, "problems": [], "notes": c.notes}), + Ok(c) if links.is_empty() => json!({"runs": true, "problems": [], "notes": c.notes}), + Ok(c) => json!({"runs": false, "problems": links, "notes": c.notes}), Err(p) => json!({"runs": false, "problems": p, "notes": []}), } } +/// The timeline a keyframe's script belongs to, for linking (graphic and button timelines +/// don't run scripts: `None`). +fn timeline_of(doc: &Document, symbol: Option) -> Option { + match symbol { + None => Some(TimelineRef::Root), + Some(id) => doc.symbol(id).filter(|s| s.kind == SymbolKind::MovieClip).map(|_| TimelineRef::Symbol(id)), + } +} + +/// Why a compiled script doesn't link on its timeline. +fn links(doc: &Document, which: Option, c: &CompileResult) -> Vec { + match (which, c) { + (Some(w), Ok(c)) => link_problems(doc, w, c), + _ => Vec::new(), + } +} + fn check(_: &mut Session, p: &Value) -> Result { let text = str_req(p, "text")?; if text.len() > actions::MAX_SOURCE_BYTES { @@ -62,10 +83,11 @@ fn check(_: &mut Session, p: &Value) -> Result { } let script = SourceScript::new(language(p)?.unwrap_or_default(), text); let c = script.compiled(); - let mut v = status(c); + let mut v = status(c, &[]); if let Ok(c) = c { - v["steps"] = json!(c.ops); - v["describe"] = json!(c.ops.iter().map(|o| o.describe()).collect::>()); + v["steps"] = json!(c.steps); + v["uses"] = json!(c.free); + v["program"] = json!(c); } Ok(v) } @@ -103,10 +125,12 @@ fn set(s: &mut Session, p: &Value) -> Result { let script = SourceScript::new(lang.or(old.map(|o| o.language)).unwrap_or_default(), text); script.check().map_err(EngineError::Param)?; let mut out = json!({"layer": lid.0, "keyframe": k.start, "language": script.language.key(), "lines": script.lines(), "bytes": script.text.len(), "replaced": if before == json!("script") { Value::Null } else { before }}); - if let (Some(o), Value::Object(st)) = (out.as_object_mut(), status(script.compiled())) { + let script = Arc::new(script); + k.script = Some(FrameScript::Source(script.clone())); + let which = timeline_of(&s.doc, opt_u64(p, "symbol")?.map(SymbolId)); + if let (Some(o), Value::Object(st)) = (out.as_object_mut(), status(script.compiled(), &links(&s.doc, which, script.compiled()))) { o.extend(st); } - k.script = Some(FrameScript::Source(Arc::new(script))); Ok(out) } @@ -122,13 +146,14 @@ fn clear(s: &mut Session, p: &Value) -> Result { fn list(s: &mut Session, p: &Value) -> Result { let with_text = opt_bool(p, "text")?.unwrap_or(true); let mut frames = Vec::new(); - let timelines = s.doc.scenes.iter().enumerate().map(|(i, sc)| (json!({"scene": i}), sc.name.as_str(), &sc.timeline)).chain(s.doc.library.iter().map(|sym| (json!({"symbol": sym.id.0}), sym.name.as_str(), &sym.timeline))); - for (at, name, tl) in timelines { + let doc = &s.doc; + let timelines = doc.scenes.iter().enumerate().map(|(i, sc)| (json!({"scene": i}), sc.name.as_str(), &sc.timeline, Some(TimelineRef::Root))).chain(doc.library.iter().map(|sym| (json!({"symbol": sym.id.0}), sym.name.as_str(), &sym.timeline, timeline_of(doc, Some(sym.id))))); + for (at, name, tl, which) in timelines { for l in &tl.layers { for k in &l.keyframes { let Some(src) = k.script.as_ref().and_then(FrameScript::source) else { continue }; let mut v = json!({"timeline": name, "layer": l.id.0, "layer_name": l.name, "frame": k.start, "label": k.label, "language": src.language.key(), "lines": src.lines(), "bytes": src.text.len()}); - if let (Some(o), Value::Object(st)) = (v.as_object_mut(), status(src.compiled())) { + if let (Some(o), Value::Object(st)) = (v.as_object_mut(), status(src.compiled(), &links(doc, which, src.compiled()))) { o.extend(st); } if with_text { diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index e64a24f4..e055f1fa 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Import to Library…", "File/Import", None, - "{path (.wav, .ogg or .mp3 sound; .png or .jpg image), name?}", + "{path (.wav, .ogg or .mp3 sound; .png or .jpg image; .svg drawing: a graphic symbol named after the file holding its shapes), name?}", true, import_to_library as crate::RunFn, ), @@ -99,7 +99,7 @@ fn sound_json(s: &Sound) -> Value { } /// Import to Library: a sound (or an image) goes into the library without being placed. -fn import_to_library(s: &mut Session, p: &Value) -> Result { +pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); if is_sound(&path) { let id = add_sound(s, &path, opt_str(p, "name")?)?; @@ -118,7 +118,11 @@ fn import_to_library(s: &mut Session, p: &Value) -> Result { s.doc.bitmaps.push(Arc::new(bitmap)); return Ok(json!({"bitmap": id.0, "width": w, "height": h})); } - Err(EngineError::Param("Import to Library reads WAV, Ogg Vorbis and MP3 sounds, and PNG and JPEG images".into())) + if ext.as_deref() == Some("svg") { + // A drawing becomes a graphic symbol holding its shapes (ADR 0065). + return crate::cmds_file::import_svg_symbol(s, &path, opt_str(p, "name")?); + } + Err(EngineError::Param("Import to Library reads WAV, Ogg Vorbis and MP3 sounds, PNG and JPEG images, and SVG drawings (as a graphic symbol)".into())) } /// Import to Stage with a sound: into the library, and onto a new layer named after the file, @@ -203,7 +207,7 @@ fn sound_param(s: &Session, p: &Value) -> Result { /// Place Sound: the sound goes on the keyframe covering the frame (a blank keyframe is made /// on an empty frame), Animate-style. With `extend`, the layer's last span grows to the sound's /// length so its waveform shows in full. -fn place(s: &mut Session, p: &Value) -> Result { +pub(crate) fn place(s: &mut Session, p: &Value) -> Result { let id = sound_param(s, p)?; let fps = s.doc.stage.fps; let want = s.doc.sound(id).map_or(1, |x| x.movie_frames(fps)); @@ -242,7 +246,7 @@ fn set(s: &mut Session, p: &Value) -> Result { // shaped over, which Custom starts from. let (lid, frame) = target(s, p)?; let fps = s.doc.stage.fps; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let place = tl.layer(lid.unwrap_or(s.layer)).and_then(|l| l.keyframe_at(frame)).map(|k| (k.duration, s.doc.frame_count().saturating_sub(s.doc.scene_start(s.scene).saturating_add(k.start)))); let sounds = s.doc.sounds.clone(); let heard = move |fs: &FrameSound| match (sounds.iter().find(|x| x.id == fs.sound), place) { diff --git a/crates/engine/src/cmds_swatch.rs b/crates/engine/src/cmds_swatch.rs new file mode 100644 index 00000000..01697060 --- /dev/null +++ b/crates/engine/src/cmds_swatch.rs @@ -0,0 +1,302 @@ +//! The Swatches panel's commands (ADR 0078): the document's saved colours and gradients. +//! +//! Swatches live in the document (`Document::swatches`), so every change here is an undo step +//! and is saved with the file, as Animate keeps them per document. Applying a swatch is +//! `paint.set_fill` (fill) or `element.set_stroke` (stroke) underneath, so the selection and +//! the tool colour change exactly as they do from the Colour panel. +//! +//! A swatch set moves between documents and computers as a small JSON file +//! (`swatch.export` / `swatch.import`); GIMP palettes (`.gpl`, an open plain-text format) +//! import too. Adobe's `.aco`, `.ase` and `.clr` formats are proprietary and not read. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::swatch::{MAX_PALETTE_BYTES, clean_name, default_set, parse_gpl}; +use anicraft_doc::{GradientStop, MAX_SWATCHES, Rgba, Spread, Swatch, SwatchPaint}; +use serde_json::{Value, json}; +use std::path::PathBuf; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run }; + vec![ + c("swatch.list", "Swatches", "{} the document's swatches, in the Swatches panel's order → {swatches: [{index, name, type, color | stops, ..}], count}", false, list as crate::RunFn), + c( + "swatch.add", + "Add Swatch", + "{from?: fill|stroke (default fill: the fill swatch's colour or gradient; stroke: the stroke colour), or the swatch itself: type?: solid|linear|radial, color? (\"#rrggbb\" | \"#rrggbbaa\", solid), stops?: [{offset: 0..1, color}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial); name?, at? (index; default: the end)} → {index, count}", + true, + add, + ), + c("swatch.remove", "Delete Swatch", "{index} → {count}", true, remove), + c("swatch.move", "Move Swatch", "{from, to} (indices: the swatch at `from` ends up at `to`) → {index}", true, move_swatch), + c("swatch.duplicate", "Duplicate Swatch", "{index} puts a copy right after it → {index, count}", true, duplicate), + c("swatch.rename", "Rename Swatch", "{index, name} (empty: no name, the hex shows on hover)", true, rename), + c( + "swatch.apply", + "Apply Swatch", + "{index, target?: fill|stroke (default fill), selection?: bool (default true)} sets the fill swatch (as paint.set_fill: a gradient is fitted to each shape) or the stroke colour, and unless `selection` is false the selected shapes' fills or strokes. A gradient swatch can't be a stroke (strokes are one colour) → {target, changed}", + true, + apply, + ), + c("swatch.clear", "Clear Swatches", "{} removes every swatch but black and white (Animate's Clear Colors; undoable)", true, clear), + c("swatch.reset", "Default Swatches", "{} replaces the swatches with a new document's set (undoable)", true, reset), + c("swatch.import", "Import Swatches", "{path: a swatch file (.json, from swatch.export) or a GIMP palette (.gpl), replace?: bool (default false: added at the end)} → {imported, count}", true, import), + c("swatch.export", "Export Swatches", "{path} writes the document's swatches to a swatch file (JSON) → {written, swatches}", false, export), + ] +} + +/// `#rrggbb`, or `#rrggbbaa` when not opaque. +pub fn hex(c: Rgba) -> String { + let c = c.sanitized(); + if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } +} + +fn stops_json(stops: &[GradientStop]) -> Value { + json!(stops.iter().map(|s| json!({"offset": s.offset, "color": hex(s.color)})).collect::>()) +} + +/// A swatch as commands and swatch files write it. +pub fn swatch_json(s: &Swatch) -> Value { + let mut v = match &s.paint { + SwatchPaint::Solid { color } => json!({"type": "solid", "color": hex(*color)}), + SwatchPaint::Linear { stops, spread, linear_rgb } => json!({"type": "linear", "stops": stops_json(stops), "spread": spread.key(), "linear_rgb": linear_rgb}), + SwatchPaint::Radial { stops, spread, linear_rgb, focal } => json!({"type": "radial", "stops": stops_json(stops), "spread": spread.key(), "linear_rgb": linear_rgb, "focal": focal}), + }; + if !s.name.is_empty() + && let Some(o) = v.as_object_mut() + { + o.insert("name".into(), json!(s.name)); + } + v +} + +/// A swatch from its JSON (see `swatch.add`). `None` when `v` names no paint (no type, colour +/// or stops), so the caller can fall back to the current one. +pub fn swatch_from_json(v: &Value) -> Result> { + let kind = opt_str(v, "type")?; + let color = opt_color(v, "color")?; + let stops = crate::cmds_paint::opt_stops(v)?; + let spread = match opt_str(v, "spread")? { + None => Spread::Pad, + Some(k) => Spread::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown spread '{k}' (extend, reflect or repeat)")))?, + }; + let linear_rgb = opt_bool(v, "linear_rgb")?.unwrap_or(false); + let focal = crate::cmds_paint::opt_focal(v)?.unwrap_or(0.0); + let kind = match (kind, &color, &stops) { + (None, None, None) => return Ok(None), + (Some(k), ..) => k, + (None, _, Some(_)) => "linear", + (None, Some(_), None) => "solid", + }; + let need_stops = || stops.clone().ok_or_else(|| EngineError::Param(format!("a {kind} swatch needs 'stops' (2 to 15 like {{\"offset\": 0, \"color\": \"#ff0000\"}})"))); + let paint = match kind { + "solid" => SwatchPaint::Solid { color: color.ok_or_else(|| EngineError::Param("a solid swatch needs 'color' (like \"#ff8800\")".into()))? }, + "linear" => SwatchPaint::Linear { stops: need_stops()?, spread, linear_rgb }, + "radial" => SwatchPaint::Radial { stops: need_stops()?, spread, linear_rgb, focal }, + other => return Err(EngineError::Param(format!("unknown swatch type '{other}' (solid, linear or radial)"))), + }; + let name = opt_str(v, "name")?.unwrap_or(""); + Swatch::new(name, paint).sanitized().map(Some).ok_or_else(|| EngineError::Param("that swatch can't be kept (a gradient needs two stops)".into())) +} + +fn index_param(s: &Session, p: &Value, key: &str) -> Result { + let n = s.doc.swatches.len(); + let i = opt_u64(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required (a swatch's index)")))?; + usize::try_from(i).ok().filter(|i| *i < n).ok_or_else(|| if n == 0 { EngineError::State("the document has no swatches".into()) } else { EngineError::Param(format!("param '{key}' must be a swatch index, 0 to {}", n - 1)) }) +} + +fn swatches_mut(s: &mut Session) -> &mut Vec { + Arc::make_mut(&mut s.doc.swatches) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let v: Vec = s + .doc + .swatches + .iter() + .enumerate() + .map(|(i, sw)| { + let mut j = swatch_json(sw); + if let Some(o) = j.as_object_mut() { + o.insert("index".into(), json!(i)); + } + j + }) + .collect(); + Ok(json!({"count": v.len(), "swatches": v})) +} + +/// The swatch `swatch.add` makes from the current colours: the fill swatch, or the stroke. +fn current(s: &Session, from: &str) -> Result { + match from { + "fill" => SwatchPaint::from_paint(&s.style.fill_paint()).map(|p| Swatch { name: String::new(), paint: p }).ok_or_else(|| EngineError::State("a bitmap fill can't be a swatch (swatches hold colours and gradients)".into())), + "stroke" => Ok(Swatch::solid(s.style.stroke)), + other => Err(EngineError::Param(format!("param 'from' must be fill or stroke, not '{other}'"))), + } +} + +fn add(s: &mut Session, p: &Value) -> Result { + if s.doc.swatches.len() >= MAX_SWATCHES { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let mut sw = match (opt_str(p, "from")?, swatch_from_json(p)?) { + (Some(_), Some(_)) => return Err(EngineError::Param("give either 'from' or the swatch's own type, colour or stops, not both".into())), + (None, Some(sw)) => sw, + (from, None) => current(s, from.unwrap_or("fill"))?, + }; + if let Some(n) = opt_str(p, "name")? { + sw.name = clean_name(n); + } + let n = s.doc.swatches.len(); + let at = match opt_u64(p, "at")? { + None => n, + Some(i) => usize::try_from(i).ok().filter(|i| *i <= n).ok_or_else(|| EngineError::Param(format!("param 'at' must be 0 to {n}")))?, + }; + swatches_mut(s).insert(at, sw); + Ok(json!({"index": at, "count": n + 1})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let v = swatches_mut(s); + v.remove(i); + Ok(json!({"count": v.len()})) +} + +fn move_swatch(s: &mut Session, p: &Value) -> Result { + let from = index_param(s, p, "from")?; + let to = index_param(s, p, "to")?; + if from != to { + let v = swatches_mut(s); + let sw = v.remove(from); + v.insert(to, sw); + } + Ok(json!({"index": to})) +} + +fn duplicate(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + if s.doc.swatches.len() >= MAX_SWATCHES { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let v = swatches_mut(s); + let copy = v.get(i).cloned().ok_or_else(|| EngineError::Param("no such swatch".into()))?; + v.insert(i + 1, copy); + Ok(json!({"index": i + 1, "count": v.len()})) +} + +fn rename(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let name = clean_name(str_req(p, "name")?); + if let Some(sw) = swatches_mut(s).get_mut(i) { + sw.name = name.clone(); + } + Ok(json!({"index": i, "name": name})) +} + +fn apply(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let sw = s.doc.swatches.get(i).cloned().ok_or_else(|| EngineError::Param("no such swatch".into()))?; + let selection = opt_bool(p, "selection")?.unwrap_or(true); + match opt_str(p, "target")?.unwrap_or("fill") { + "fill" => { + let mut fill = swatch_json(&sw); + if let Some(o) = fill.as_object_mut() { + o.remove("name"); + o.insert("selection".into(), json!(selection)); + } + let r = crate::cmds_paint::set_fill(s, &fill)?; + Ok(json!({"target": "fill", "changed": r.get("changed").cloned().unwrap_or(json!(0))})) + } + "stroke" => { + let SwatchPaint::Solid { color } = sw.paint else { + return Err(EngineError::State("strokes are one colour: apply a gradient swatch to the fill instead".into())); + }; + s.style.stroke = color; + s.style.use_stroke = true; + let changed = if selection && !s.selection.is_empty() { + s.each_layer(false, |s| crate::cmds_draw::set_stroke(s, &json!({"color": hex(color)})))?; + s.selection.len() + } else { + 0 + }; + Ok(json!({"target": "stroke", "changed": changed})) + } + other => Err(EngineError::Param(format!("param 'target' must be fill or stroke, not '{other}'"))), + } +} + +fn clear(s: &mut Session, _: &Value) -> Result { + s.doc.swatches = Arc::new(vec![Swatch::solid(Rgba::BLACK), Swatch::solid(Rgba::WHITE)]); + Ok(json!({"count": 2})) +} + +fn reset(s: &mut Session, _: &Value) -> Result { + s.doc.swatches = Arc::new(default_set()); + Ok(json!({"count": s.doc.swatches.len()})) +} + +/// The JSON swatch file: `{"format": "anicraft-swatches", "version": 1, "swatches": [..]}`. +pub fn file_json(swatches: &[Swatch]) -> String { + let v = json!({"format": FORMAT, "version": 1, "swatches": swatches.iter().map(swatch_json).collect::>()}); + serde_json::to_string_pretty(&v).unwrap_or_default() +} + +const FORMAT: &str = "anicraft-swatches"; + +/// The swatches in a swatch file (JSON) or a GIMP palette, told apart by their content. +pub fn parse_file(text: &str) -> Result> { + if text.len() > MAX_PALETTE_BYTES { + return Err(EngineError::Param("the swatch file is too large".into())); + } + if text.trim_start_matches('\u{feff}').trim_start().starts_with("GIMP Palette") { + return parse_gpl(text).map(|(_, v)| v).map_err(EngineError::Param); + } + let v: Value = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("this isn't a swatch file or a GIMP palette ({e})")))?; + if v.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err(EngineError::Param(format!("this JSON isn't a swatch file (its \"format\" must be \"{FORMAT}\")"))); + } + let list = v.get("swatches").and_then(Value::as_array).ok_or_else(|| EngineError::Param("the swatch file has no \"swatches\" list".into()))?; + let mut out = Vec::new(); + for item in list.iter().take(MAX_SWATCHES) { + // A swatch this version can't read is skipped, so a newer file still opens. + if let Ok(Some(sw)) = swatch_from_json(item) { + out.push(sw); + } + } + if out.is_empty() { + return Err(EngineError::Param("the swatch file has no swatches in it".into())); + } + Ok(out) +} + +fn import(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + if crate::vfs::len(&path)? > MAX_PALETTE_BYTES as u64 { + return Err(EngineError::Param(format!("{} is too large to be a swatch file", path.display()))); + } + let found = parse_file(&crate::vfs::read_to_string(&path)?)?; + let replace = opt_bool(p, "replace")?.unwrap_or(false); + let v = swatches_mut(s); + if replace { + v.clear(); + } + let room = MAX_SWATCHES.saturating_sub(v.len()); + if room == 0 { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let n = found.len().min(room); + v.extend(found.into_iter().take(n)); + Ok(json!({"imported": n, "count": v.len()})) +} + +fn export(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + if s.doc.swatches.is_empty() { + return Err(EngineError::State("the document has no swatches to export".into())); + } + let text = file_json(&s.doc.swatches); + crate::vfs::write(&path, text.as_bytes())?; + Ok(json!({"written": path.display().to_string(), "swatches": s.doc.swatches.len(), "bytes": text.len()})) +} diff --git a/crates/engine/src/cmds_template.rs b/crates/engine/src/cmds_template.rs new file mode 100644 index 00000000..17c0e2c8 --- /dev/null +++ b/crates/engine/src/cmds_template.rs @@ -0,0 +1,207 @@ +//! Templates (ADR 0065): new documents from the templates AniCraft ships with +//! (`anicraft_doc::templates`, built by code) and from the user's own, which File › Save as +//! Template keeps as plain `.anicraft` files with a picture beside them: +//! `//.anicraft` and `.png`. The shell passes the folder (its +//! settings folder's `Templates`); the engine never looks for it, as with recent files. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session, format}; +use anicraft_doc::templates::{self, TEMPLATES}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Longest template or category name, in characters. +pub const MAX_NAME_CHARS: usize = 64; +/// Most categories and templates listed (a folder with more is not one we made). +const MAX_CATEGORIES: usize = 64; +const MAX_TEMPLATES: usize = 500; +/// The category a template is saved in when none is given. +pub const DEFAULT_CATEGORY: &str = "My Templates"; + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "file.new_from_template", + label: "New from Template…", + menu: "File", + shortcut: None, + params: "{template? (a built-in template's id, from file.templates) | path? (a template file: any .anicraft opens as a new, untitled document)}", + mutates: false, + run: new_from_template, + }, + CommandSpec { + id: "file.templates", + label: "List Templates", + menu: "", + shortcut: None, + params: "{folder? (the user templates folder)} → {builtin: [{id, name, category, description, width, height, fps, frames}], user: [{name, category, path, thumbnail}]}", + mutates: false, + run: list, + }, + CommandSpec { + id: "file.save_as_template", + label: "Save as Template…", + menu: "File", + shortcut: None, + params: "{folder (the user templates folder), name, category? (default “My Templates”), confirm? (to replace a template of that name)} → {path, thumbnail}: the document as it is, kept as //.anicraft with a picture of its first frame; the open document is unchanged", + mutates: false, + run: save_as_template, + }, + CommandSpec { id: "file.delete_template", label: "Delete Template", menu: "", shortcut: None, params: "{folder, name, category?, confirm}: removes a user template and its picture (cannot be undone)", mutates: false, run: delete_template }, + ] +} + +/// A name usable as a file or folder name on every system, or why not. +pub(crate) fn clean_name(raw: &str, what: &str) -> Result { + let name = raw.trim(); + if name.is_empty() { + return Err(EngineError::Param(format!("give the {what} a name"))); + } + if name.chars().count() > MAX_NAME_CHARS { + return Err(EngineError::Param(format!("a {what} name has at most {MAX_NAME_CHARS} characters"))); + } + if name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) { + return Err(EngineError::Param(format!("a {what} name can't use / \\ : * ? \" < > |"))); + } + if name.starts_with('.') || name.ends_with('.') { + return Err(EngineError::Param(format!("a {what} name can't start or end with a dot"))); + } + // Names Windows keeps for devices, with or without an extension. + let stem = name.split('.').next().unwrap_or(name).trim().to_ascii_uppercase(); + let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || ((stem.starts_with("COM") || stem.starts_with("LPT")) && stem.len() == 4 && stem.ends_with(|c: char| c.is_ascii_digit())); + if reserved { + return Err(EngineError::Param(format!("“{name}” is a name the system keeps for itself: pick another {what} name"))); + } + Ok(name.to_string()) +} + +/// Where a user template of this category and name is kept. +pub fn template_path(folder: &Path, category: &str, name: &str) -> Result { + let category = clean_name(category, "category")?; + let name = clean_name(name, "template")?; + Ok(folder.join(category).join(format!("{name}.anicraft"))) +} + +/// The picture kept beside a template file. +pub fn thumbnail_path(template: &Path) -> PathBuf { + template.with_extension("png") +} + +/// A user template found in the folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UserTemplate { + pub name: String, + pub category: String, + pub path: PathBuf, + /// Its picture, when there is one. + pub thumbnail: Option, +} + +/// The user's templates, by category then name (ignoring case). +pub fn user_templates(folder: &Path) -> Vec { + let mut out = Vec::new(); + for dir in crate::vfs::list(folder, MAX_CATEGORIES).into_iter().filter(|d| crate::vfs::is_dir(d)) { + let Some(category) = dir.file_name().map(|n| n.to_string_lossy().into_owned()) else { continue }; + for f in crate::vfs::list(&dir, MAX_TEMPLATES) { + if out.len() >= MAX_TEMPLATES { + break; + } + let is_template = f.extension().is_some_and(|e| e.eq_ignore_ascii_case("anicraft")) && crate::vfs::is_file(&f); + let Some(name) = f.file_stem().map(|n| n.to_string_lossy().into_owned()).filter(|_| is_template) else { continue }; + let thumb = thumbnail_path(&f); + out.push(UserTemplate { name, category: category.clone(), thumbnail: crate::vfs::is_file(&thumb).then_some(thumb), path: f }); + } + } + out.sort_by_key(|t| (t.category.to_lowercase(), t.name.to_lowercase())); + out +} + +/// A template's picture: its first frame fitting the recent files' thumbnail size, guides +/// drawn, their lines widened to stay visible at that size. +pub fn picture_png(doc: &anicraft_doc::Document) -> Result> { + let (w, h) = (doc.stage.width.max(1) as f32, doc.stage.height.max(1) as f32); + let scale = (crate::cmds_recent::THUMB_W as f32 / w).min(crate::cmds_recent::THUMB_H as f32 / h).min(1.0); + crate::cmds_recent::thumbnail_png(&templates::with_guides_shown(doc, 1.5 / scale.max(1e-3))) +} + +fn new_from_template(s: &mut Session, p: &Value) -> Result { + let (doc, name) = match (opt_str(p, "template")?, opt_str(p, "path")?) { + (Some(id), None) => { + let t = templates::find(id).ok_or_else(|| EngineError::Param(format!("no template '{id}' (file.templates lists them)")))?; + ((t.build)(), t.name.to_string()) + } + (None, Some(path)) => { + let path = PathBuf::from(path); + if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("anicraft")) { + return Err(EngineError::Param("a template is an .anicraft document".into())); + } + let name = path.file_stem().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + (format::load(&path)?, name) + } + _ => return Err(EngineError::Param("name a built-in 'template' or a template file's 'path'".into())), + }; + // A new document: untitled, so Save asks for a name and never writes over the template. + s.replace_document(doc, None); + // Ready to draw: the top layer that takes artwork is active (not a locked guide). + if let Some(l) = s.timeline().layers.iter().find(|l| l.kind == anicraft_doc::LayerKind::Normal && !l.locked) { + s.layer = l.id; + } + let mut info = s.info(); + info["template"] = json!(name); + Ok(info) +} + +fn list(_: &mut Session, p: &Value) -> Result { + let builtin: Vec = TEMPLATES + .iter() + .map(|t| { + let d = (t.build)(); + json!({"id": t.id, "name": t.name, "category": t.category, "description": t.description, "width": d.stage.width, "height": d.stage.height, "fps": d.stage.fps, "frames": d.frame_count()}) + }) + .collect(); + let user: Vec = match opt_str(p, "folder")? { + Some(f) => user_templates(Path::new(f)).into_iter().map(|t| json!({"name": t.name, "category": t.category, "path": t.path.display().to_string(), "thumbnail": t.thumbnail.map(|p| p.display().to_string())})).collect(), + None => Vec::new(), + }; + Ok(json!({"builtin": builtin, "user": user})) +} + +fn category(p: &Value) -> Result<&str> { + Ok(opt_str(p, "category")?.filter(|c| !c.trim().is_empty()).unwrap_or(DEFAULT_CATEGORY)) +} + +/// The template file the params name. +pub(crate) fn target(p: &Value) -> Result { + template_path(Path::new(str_req(p, "folder")?), category(p)?, str_req(p, "name")?) +} + +fn save_as_template(s: &mut Session, p: &Value) -> Result { + let path = target(p)?; + if let Some(dir) = path.parent() { + crate::vfs::create_dir_all(dir)?; + } + format::save(&s.doc, &path)?; + // Its picture shows the guides too (they are much of what a template is). + let thumb = thumbnail_path(&path); + let picture = picture_png(&s.doc).and_then(|png| Ok(crate::vfs::write(&thumb, png)?)); + Ok(json!({"path": path.display().to_string(), "thumbnail": picture.is_ok().then(|| thumb.display().to_string())})) +} + +fn delete_template(_: &mut Session, p: &Value) -> Result { + let path = target(p)?; + if !crate::vfs::is_file(&path) { + return Err(EngineError::State(format!("there is no template “{}” in “{}”", str_req(p, "name")?.trim(), category(p)?.trim()))); + } + crate::vfs::remove_file(&path)?; + let thumb = thumbnail_path(&path); + if crate::vfs::is_file(&thumb) { + crate::vfs::remove_file(&thumb)?; + } + // An emptied category goes with its last template. + if let Some(dir) = path.parent() + && crate::vfs::list(dir, 1).is_empty() + { + let _ = std::fs::remove_dir(dir); + } + Ok(json!({"deleted": path.display().to_string()})) +} diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index a69844b7..f73a94b6 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -1,15 +1,23 @@ //! Text commands (ADR 0012): create and edit text blocks, list fonts. Laying text out happens //! here, when it changes; the document keeps the outlines, so rendering never needs fonts. +//! +//! Dynamic and input text fields (ADR 0066): `text.field` sets a block's Text type and field +//! options. A field's box is fixed and its text is laid out inside the gutter, aligned in the box; +//! [`field_layout`] does that for the commands and for the player while a movie plays. +//! +//! Text on a path (ADR 0070): `text.attach_path` sets static text along a shape's outline (a +//! copy of it, in the text's own space), `text.path` moves it along, flips it or releases it. +//! The glyphs are set by arc length and stored as outlines, as all text is. use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Rgba, TextAlign, TextBlock}; -use anicraft_geom::{Affine, Path}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, MAX_PATH_OFFSET, Rgba, TextAlign, TextBlock, TextField, TextKind, TextPath}; +use anicraft_geom::{Affine, Path, Vec2}; use anicraft_text::{Align, Fonts}; use serde_json::{Value, json}; use std::sync::Arc; -/// The text style new text gets: the last one used, as in Animate. +/// The text style new text gets: the last one used. #[derive(Clone, Debug, PartialEq)] pub struct TextStyle { pub font: String, @@ -32,9 +40,21 @@ impl Default for TextStyle { pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("text.create", "New Text", "", None, "{text, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn), + c("text.create", "New Text", "", None, "{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn), c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, |s, p| s.each_layer(false, |s| edit(s, p))), c("text.fonts", "Fonts", "", None, "{}", false, fonts), + c( + "text.attach_path", + "Attach Text to Path", + "Modify/Text", + None, + "{path?: element id of a shape (default: the other selected element, a shape), x?, y? (pick the shape at this stage point instead), offset? (px along the path; default by the text's alignment: its start, middle or end), flip?: bool} sets the selected static text along a copy of the shape's outline (its first contour); the shape stays as it is (ADR 0070)", + true, + attach_path as crate::RunFn, + ), + c("text.path", "Text on Path", "", None, "{offset? (px along the path), flip?: bool (along the path backwards, on its other side), release?: bool (back to lines of text where it starts)} on the selected text on a path (ADR 0070)", true, |s, p| s.each_layer(false, |s| set_path(s, p))), + c("text.release_path", "Release Text from Path", "Modify/Text", None, "{} the selected text on a path goes back to lines of text (ADR 0070)", true, |s, _| s.each_layer(false, |s| set_path(s, &json!({"release": true})))), + c("text.field", "Text Type", "", None, "{type?: static|dynamic|input, lines?: single|multiline|multiline_no_wrap|password (input only), width?, height? (the field's box, px), selectable?, border?, background?, border_color?, background_color?, max_chars? (input; 0: no limit), variable? (kept, not run)} on the selected text; dynamic and input fields are named with instance.set_name and scripted in Test Movie and the HTML export (ADR 0066)", true, |s, p| s.each_layer(false, |s| set_field(s, p))), ] } @@ -120,22 +140,355 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu outline: Arc::new(layout.outline), box_width: layout.width, box_height: layout.height, + field: None, + on_path: None, }; Ok((block, note)) } -fn style_of(t: &TextBlock) -> TextStyle { +/// A field's text laid out (ADR 0066): `shown` in the block's style, wrapped at the box less its +/// gutters when it is multiline, aligned in the box, with the outline moved into the gutter. +/// The carets are from the text's left edge (the alignment applied, not the gutter). +pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_width: f32, shown: &str) -> std::result::Result { + let wrap = field.wrap_width(box_width); + let mut l = fonts.layout( + shown, + &anicraft_text::Style { + family: style.font.clone(), + size: style.size, + bold: style.bold, + italic: style.italic, + align: match style.align { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: wrap, + }, + )?; + // Lines that don't wrap align against the widest; the widest aligns in the box. + let inner = (box_width - 2.0 * FIELD_GUTTER).max(0.0); + let shift = match (wrap, style.align) { + (Some(_), _) | (None, TextAlign::Left) => 0.0, + (None, TextAlign::Center) => ((inner - l.width) * 0.5).max(0.0), + (None, TextAlign::Right) => (inner - l.width).max(0.0), + }; + l.outline = l.outline.transformed(&Affine::translate(FIELD_GUTTER + shift, FIELD_GUTTER)); + if shift != 0.0 { + for line in &mut l.carets { + for s in &mut line.stops { + s.1 += shift; + } + } + l.width += shift; + } + Ok(l) +} + +/// A field block for `text`: laid out in its box (`box_width` × `box_height`). +pub(crate) fn lay_out_field(text: &str, style: &TextStyle, field: &TextField, box_width: f32, box_height: f32) -> Result<(TextBlock, Option)> { + let fonts = Fonts::get(); + let text: String = text.chars().take(MAX_FIELD_CHARS).collect(); + let l = field_layout(fonts, style, field, box_width, &field.shown(&text)).map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; + let note = (!style.font.trim().is_empty() && !l.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), l.family)); + let block = TextBlock { + text, + font: l.family, + size: style.size, + bold: style.bold, + italic: style.italic, + color: style.color, + align: style.align, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: field.wrap_width(box_width), + outline: Arc::new(l.outline), + box_width, + box_height, + field: Some(field.clone()), + on_path: None, + }; + Ok((block, note)) +} + +/// Text on a path (ADR 0070): `text` on one line (line breaks become spaces) set along `on`'s +/// path. The block's space is moved so its box (the path and the glyphs together) starts at +/// the origin, as every text box does: the second value is where that origin was, which the +/// element's transform must move by (`transform × translate(shift)`) for nothing to move. +pub(crate) fn lay_out_on_path(text: &str, style: &TextStyle, on: &TextPath) -> Result<(TextBlock, Option, Vec2)> { + let fonts = Fonts::get(); + let line: String = text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect(); + let layout = fonts + .layout_glyphs(&line, &anicraft_text::Style { family: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, align: Align::Left, letter_spacing: style.letter_spacing, line_spacing: 0.0, width: None }) + .map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; + let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + let align = match style.align { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }; + let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 }; + let set = anicraft_text::on_path_boxed(&layout.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?; + let shift = set.shift; + let block = TextBlock { + text: text.to_string(), + font: layout.family, + size: style.size, + bold: style.bold, + italic: style.italic, + color: style.color, + align: style.align, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: None, + outline: Arc::new(set.outline), + box_width: set.width, + box_height: set.height, + field: None, + on_path: Some(TextPath { path: set.path, offset, flip: on.flip }), + }; + Ok((block, note, shift)) +} + +/// The block `t` with new text or style: a field keeps its box (or takes `width` as its new +/// width); static text wraps at `width`; text on a path stays on it. With where the block's +/// origin moved to ([`lay_out_on_path`]; zero for the others). +pub(crate) fn relay(t: &TextBlock, text: &str, style: &TextStyle, width: Option) -> Result<(TextBlock, Option, Vec2)> { + match (&t.field, &t.on_path) { + (_, Some(on)) => lay_out_on_path(text, style, on), + (Some(f), None) => lay_out_field(text, style, f, width.unwrap_or(t.box_width), t.box_height).map(|(b, n)| (b, n, Vec2::ZERO)), + (None, None) => lay_out(text, style, width).map(|(b, n)| (b, n, Vec2::ZERO)), + } +} + +/// What Find and Replace lays text out with: as before (static text, its fields' boxes +/// dropped), except that text on a path stays on its path. +pub(crate) fn relay_static(t: &TextBlock, text: &str, style: &TextStyle) -> Result<(TextBlock, Option, Vec2)> { + match &t.on_path { + Some(on) => lay_out_on_path(text, style, on), + None => lay_out(text, style, t.width).map(|(b, n)| (b, n, Vec2::ZERO)), + } +} + +/// The selected static text, along a copy of a shape's outline (ADR 0070). +fn attach_path(s: &mut Session, p: &Value) -> Result { + let by_id = opt_u64(p, "path")?.map(ElementId); + let at = match (opt_f32(p, "x")?, opt_f32(p, "y")?) { + (Some(x), Some(y)) => Some(Vec2::new(x, y)), + (None, None) => None, + _ => return Err(EngineError::Param("give both 'x' and 'y', or neither".into())), + }; + let flip = opt_bool(p, "flip")?.unwrap_or(false); + let offset = opt_f32(p, "offset")?; + if offset.is_some_and(|o| !(-MAX_PATH_OFFSET..=MAX_PATH_OFFSET).contains(&o)) { + return Err(EngineError::Param(format!("'offset' must be within ±{MAX_PATH_OFFSET} px"))); + } + // The shape: by id or by point, on any layer of what is being edited; else the selection's. + let wanted = match (by_id, at) { + (Some(id), _) => Some(id), + (None, Some(pt)) => Some(s.hit_test(pt, 2.0).map(|(_, e)| e).ok_or_else(|| EngineError::State("there is no shape there to set the text along".into()))?), + (None, None) => None, + }; + let texts: Vec = s.selected_elements_mut()?.iter().filter(|e| matches!(&e.kind, ElementKind::Text(t) if t.field.is_none())).map(|e| e.id).collect(); + let [text_id] = texts.as_slice() else { + return Err(EngineError::State(if texts.is_empty() { "select a static text block to set along a path".into() } else { "select one text block to set along a path".into() })); + }; + // The shapes on the timeline being edited at this frame (in its space, as the text is): + // the one asked for, or the selected one. + let selected = s.selection.on(s.layer); + let mut candidates: Vec = Vec::new(); + for l in &s.timeline().layers { + let Some((_, els)) = anicraft_doc::evaluate_layer_elements(l, s.frame) else { continue }; + for e in els.iter() { + let ElementKind::Shape(sh) = &e.kind else { continue }; + let pick = match wanted { + Some(w) => w == e.id, + None => l.id == s.layer && selected.contains(&e.id), + }; + if pick { + candidates.push(sh.path.transformed(&e.transform)); + } + } + } + let path = match candidates.as_slice() { + [path] => path.clone(), + [] => return Err(EngineError::State("pick a shape to set the text along".into())), + _ => return Err(EngineError::State("select the text and one shape (or pick the shape)".into())), + }; + // Its first contour, in the timeline's space (the text takes the path's place). + let first: Path = Path { cmds: path.cmds.iter().enumerate().take_while(|(i, c)| *i == 0 || !matches!(c, anicraft_geom::PathCmd::MoveTo(_))).map(|(_, c)| *c).collect() }; + let length = anicraft_geom::walk::CurveWalk::new(&first).map(|w| w.length()).ok_or_else(|| EngineError::State("the shape's outline has no length to set text along".into()))?; + let mut out = Value::Null; + for e in s.selected_elements_mut()? { + if e.id != *text_id { + continue; + } + let ElementKind::Text(t) = &e.kind else { continue }; + let style = style_of(t); + let offset = offset.unwrap_or(match t.align { + TextAlign::Left => 0.0, + TextAlign::Center => length * 0.5, + TextAlign::Right => length, + }); + let (block, note, shift) = lay_out_on_path(&t.text, &style, &TextPath { path: first.clone(), offset, flip })?; + // The path is in stage space; the text's new space is the path's, moved to its box. + e.transform = Affine::translate(shift.x, shift.y); + out = json!({"element": e.id.0, "length": length, "offset": offset, "flip": flip, "note": note}); + e.kind = ElementKind::Text(Arc::new(block)); + } + s.select_only([*text_id]); + Ok(out) +} + +/// Moves, flips or releases the selected text on a path. +fn set_path(s: &mut Session, p: &Value) -> Result { + let offset = opt_f32(p, "offset")?; + if offset.is_some_and(|o| !(-MAX_PATH_OFFSET..=MAX_PATH_OFFSET).contains(&o)) { + return Err(EngineError::Param(format!("'offset' must be within ±{MAX_PATH_OFFSET} px"))); + } + let flip = opt_bool(p, "flip")?; + let release = opt_bool(p, "release")?.unwrap_or(false); + let mut changed = 0; + for e in s.selected_elements_mut()? { + let ElementKind::Text(t) = &e.kind else { continue }; + let Some(on) = &t.on_path else { continue }; + let style = style_of(t); + if release { + // Back to a line of text, its box where the text started along the path. + let start = t.outline.bounds(); + let (block, _) = lay_out(&t.text, &style, None)?; + let at = if start.min.x.is_finite() { start.min } else { Vec2::ZERO }; + e.transform = e.transform.mul(&Affine::translate(at.x, at.y)); + e.kind = ElementKind::Text(Arc::new(block)); + } else { + let on = TextPath { offset: offset.unwrap_or(on.offset), flip: flip.unwrap_or(on.flip), ..on.clone() }; + let (block, _, shift) = lay_out_on_path(&t.text, &style, &on)?; + e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); + e.kind = ElementKind::Text(Arc::new(block)); + } + changed += 1; + } + if changed == 0 { + return Err(EngineError::State("the selection has no text on a path".into())); + } + Ok(json!({"changed": changed})) +} + +/// The box a block becomes a field in: the text's own size and the gutters (at least 20 px wide). +fn field_box(t: &TextBlock) -> (f32, f32) { + ((t.width.unwrap_or(t.box_width) + 2.0 * FIELD_GUTTER).max(20.0), t.box_height + 2.0 * FIELD_GUTTER) +} + +fn kind_param(p: &Value) -> Result> { + opt_str(p, "type")?.map(|k| TextKind::from_key(k).ok_or_else(|| EngineError::Param(format!("'type' is static, dynamic or input, not '{k}'")))).transpose() +} + +fn set_field(s: &mut Session, p: &Value) -> Result { + let kind = kind_param(p)?; + let lines = opt_str(p, "lines")?.map(|k| LineType::from_key(k).ok_or_else(|| EngineError::Param(format!("'lines' is single, multiline, multiline_no_wrap or password, not '{k}'")))).transpose()?; + let size = |key: &str| -> Result> { + match opt_f32(p, key)? { + Some(v) if (1.0..=100_000.0).contains(&v) => Ok(Some(v)), + Some(_) => Err(EngineError::Param(format!("'{key}' must be between 1 and 100000 px"))), + None => Ok(None), + } + }; + let (width, height) = (size("width")?, size("height")?); + let max_chars = opt_u32(p, "max_chars")?; + if max_chars.is_some_and(|n| n as usize > MAX_FIELD_CHARS) { + return Err(EngineError::Param(format!("'max_chars' is at most {MAX_FIELD_CHARS}"))); + } + let variable = opt_str(p, "variable")?.map(|v| v.trim().chars().take(MAX_FIELD_NAME).collect::()); + let (selectable, border, background) = (opt_bool(p, "selectable")?, opt_bool(p, "border")?, opt_bool(p, "background")?); + let (border_color, background_color) = (opt_color(p, "border_color")?, opt_color(p, "background_color")?); + let mut changed = 0; + let mut notes = Vec::new(); + for e in s.selected_elements_mut()? { + let ElementKind::Text(t) = &e.kind else { continue }; + if t.on_path.is_some() && kind.is_some_and(|k| k != TextKind::Static) { + return Err(EngineError::State("text on a path is static text (release it from the path first)".into())); + } + let to = kind.unwrap_or(t.kind()); + let style = style_of(t); + let (block, note) = if to == TextKind::Static { + if t.field.is_none() { + continue; + } + // Back to static text: laid out as before fields, the words where they were. + e.transform = e.transform.mul(&Affine::translate(FIELD_GUTTER, FIELD_GUTTER)); + e.name.clear(); + lay_out(&t.text, &style, t.field.as_ref().and_then(|f| f.wrap_width(t.box_width)))? + } else { + let (bw, bh) = if t.field.is_some() { (t.box_width, t.box_height) } else { field_box(t) }; + // Wrapped text becomes a multiline field, text with line breaks a multiline one + // that doesn't wrap, the rest a single line. + let lines_of = if t.width.is_some() { + LineType::Multiline + } else if t.text.contains('\n') { + LineType::MultilineNoWrap + } else { + LineType::Single + }; + let mut f = t.field.clone().unwrap_or_else(|| TextField { lines: lines_of, ..TextField::new(to) }); + if t.field.is_none() { + // The text stays where it was; the box grows round it. + e.transform = e.transform.mul(&Affine::translate(-FIELD_GUTTER, -FIELD_GUTTER)); + } + f.kind = to; + if let Some(l) = lines { + if l == LineType::Password && to != TextKind::Input { + return Err(EngineError::Param("only input text can be a password field".into())); + } + f.lines = l; + } + if f.lines == LineType::Password && to != TextKind::Input { + f.lines = LineType::Single; + } + f.selectable = selectable.unwrap_or(f.selectable); + f.border = border.unwrap_or(f.border); + f.background = background.unwrap_or(f.background); + f.border_color = border_color.unwrap_or(f.border_color); + f.background_color = background_color.unwrap_or(f.background_color); + f.max_chars = max_chars.unwrap_or(f.max_chars); + if let Some(v) = &variable { + f.variable.clone_from(v); + } + lay_out_field(&t.text, &style, &f.sanitized(), width.unwrap_or(bw), height.unwrap_or(bh))? + }; + notes.extend(note); + e.kind = ElementKind::Text(Arc::new(block)); + changed += 1; + } + if changed == 0 { + return Err(EngineError::State("the selection has no text to change".into())); + } + notes.dedup(); + Ok(json!({"changed": changed, "note": notes.first()})) +} + +pub(crate) fn style_of(t: &TextBlock) -> TextStyle { TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing } } fn create(s: &mut Session, p: &Value) -> Result { let text: String = str_req(p, "text")?.to_string(); - if text.trim().is_empty() { + let kind = kind_param(p)?.unwrap_or_default(); + // An input field may start empty (the viewer fills it in); static text may not. + if text.trim().is_empty() && kind == TextKind::Static { return Err(EngineError::Param("'text' is empty".into())); } let style = style_param(p, &s.text_style)?; let width = width_param(p, None)?; let (block, note) = lay_out(&text, &style, width)?; + let (block, note) = if kind == TextKind::Static { + (block, note) + } else { + let (bw, bh) = field_box(&block); + let f = TextField { lines: if width.is_some() { LineType::Multiline } else if text.contains('\n') { LineType::MultilineNoWrap } else { LineType::Single }, ..TextField::new(kind) }; + lay_out_field(&text, &style, &f, bw, bh)? + }; let x = opt_f32(p, "x")?.unwrap_or((s.doc.stage.width as f32 - block.box_width) * 0.5); let y = opt_f32(p, "y")?.unwrap_or((s.doc.stage.height as f32 - block.box_height) * 0.5); let id = ElementId(s.doc.alloc_id()); @@ -148,21 +501,23 @@ fn create(s: &mut Session, p: &Value) -> Result { } fn edit(s: &mut Session, p: &Value) -> Result { - let new_text = match opt_str(p, "text")? { - Some(t) if t.trim().is_empty() => return Err(EngineError::Param("'text' is empty (delete the text instead)".into())), - t => t.map(str::to_string), - }; + let new_text = opt_str(p, "text")?.map(str::to_string); let mut notes = Vec::new(); let mut edited = 0; let mut last_style = None; for e in s.selected_elements_mut()? { let ElementKind::Text(t) = &e.kind else { continue }; let style = style_param(p, &style_of(t))?; - let width = width_param(p, t.width)?; let text = new_text.clone().unwrap_or_else(|| t.text.clone()); - let (block, note) = lay_out(&text, &style, width)?; + // Fields may be empty (a script or the viewer fills them); static text may not. + if text.trim().is_empty() && t.field.is_none() { + return Err(EngineError::Param("'text' is empty (delete the text instead)".into())); + } + let width = if t.field.is_some() { width_param(p, Some(t.box_width))?.or(Some(t.box_width)).map(|w| w.max(1.0)) } else { width_param(p, t.width)? }; + let (block, note, shift) = relay(t, &text, &style, width)?; notes.extend(note); last_style = Some(TextStyle { font: block.font.clone(), ..style }); + e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); e.kind = ElementKind::Text(Arc::new(block)); edited += 1; } @@ -184,5 +539,5 @@ fn fonts(_: &mut Session, _: &Value) -> Result { /// A text block as a plain shape with the same outlines (Break Apart). pub(crate) fn to_shape(t: &TextBlock) -> anicraft_doc::Shape { let path: Arc = t.outline.clone(); - anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(t.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false } + anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(t.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, warp: None } } diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index c452ac97..b3d29cae 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -9,17 +9,18 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("timeline.insert_frame", "Frame", "Insert/Timeline", Some("F5"), "{layer? | layers?: [..], frame?, count?}", true, insert_frame as crate::RunFn), + c("timeline.insert_frame", "Frame", "Insert/Timeline", Some("F5"), "{layer? | layers?: [..] | all_layers?: true (every layer with frames at or after the frame, as F5 with no frame selection; the active layer when none has), frame?, count?, advance?: true (the playhead moves onto the last frame inserted, as the key does in the editor)}", true, insert_frame as crate::RunFn), c("timeline.remove_frame", "Remove Frame", "Insert/Timeline", Some("Shift+F5"), "{layer? | layers?: [..], frame?, count?}", true, remove_frame), - c("timeline.insert_keyframe", "Keyframe", "Insert/Timeline", Some("F6"), "{layer? | layers?: [..], frame?}", true, insert_keyframe), - c("timeline.insert_blank_keyframe", "Blank Keyframe", "Insert/Timeline", Some("F7"), "{layer? | layers?: [..], frame?}", true, insert_blank_keyframe), + c("timeline.insert_keyframe", "Keyframe", "Insert/Timeline", Some("F6"), "{layer? | layers?: [..], frame?, advance?: true (on a keyframe the new key goes on the next frame, and the playhead moves onto it, as the key does in the editor)}", true, insert_keyframe), + c("timeline.insert_blank_keyframe", "Blank Keyframe", "Insert/Timeline", Some("F7"), "{layer? | layers?: [..], frame?, advance?: true (on a keyframe the blank key goes on the next frame instead of clearing it, and the playhead moves onto it)}", true, insert_blank_keyframe), c("timeline.clear_keyframe", "Clear Keyframe", "Insert/Timeline", Some("Shift+F6"), "{layer? | layers?: [..], frame?, count?}", true, clear_keyframe), c("timeline.move_keyframes", "Move Keyframes", "", None, "{layer? | layers?: [..], from, to?, by, layer_by? (rows down; negative = up)}", true, move_keyframes), + c("timeline.move_spans", "Move Spans", "", None, "{layer? | layers?: [..], from, to?, by, layer_by? (rows down; negative = up), copy?: true (Alt-drag: the frames stay where they were too)}: the spans starting in from..=to move whole, keeping their lengths and tweens (as dragging a tween span in Animate), replacing what they land on; the frames they leave are empty", true, move_spans), c("timeline.create_motion_tween", "Create Motion Tween", "Insert", None, "{layer?, frame?} (several objects on the key become one graphic symbol; a one-frame span grows to a second)", true, crate::cmds_motion::create), - c("timeline.create_tween", "Create Classic Tween", "Insert", None, "{layer?, frame?, easing?}", true, create_tween), - c("timeline.create_shape_tween", "Create Shape Tween", "Insert", None, "{layer?, frame?, easing?}", true, create_shape_tween), + c("timeline.create_tween", "Create Classic Tween", "Insert", None, "{layer?, frame?, easing? (as timeline.set_easing takes it)}", true, create_tween), + c("timeline.create_shape_tween", "Create Shape Tween", "Insert", None, "{layer?, frame?, easing? (as timeline.set_easing takes it)}", true, create_shape_tween), c("timeline.remove_tween", "Remove Tween", "Insert", None, "{layer?, frame?} (a motion tween leaves its object as it is on the first frame)", true, remove_tween), - c("timeline.set_easing", "Set Tween Easing", "", None, "{easing, layer?, frame?}", true, set_easing), + c("timeline.set_easing", "Set Tween Easing", "", None, "{easing: a preset name (Linear, QuadIn … ElasticInOut) | {classic: -100..100} | {bezier: [x1, y1, x2, y2]} | {custom: {points: [..]} | [[x, y], ..]} | {saved: name} | {plugin: id, ease: id} (an ease plug-in's; the tween keeps its sampled curve), group?: all|position|rotation|scale|color|filters (classic tweens: that property group's own ease), layer?, frame?}", true, set_easing), c("timeline.set_orient", "Orient to Path", "", None, "{orient: bool, layer?, frame?}", true, set_orient), c("timeline.set_label", "Frame Label", "", None, "{label, layer?, frame?}", true, set_label), c("timeline.goto", "Go to Frame", "", None, "{frame}", false, goto), @@ -54,11 +55,11 @@ pub fn specs() -> Vec { /// mask back into a normal layer (its masked layers become normal too). fn toggle_mask(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let is_mask = s.doc.timeline(s.scene).layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask; + let is_mask = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask; let ty = if is_mask { "normal" } else { "mask" }; set_type(s, id, ty)?; if !is_mask { - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; // The normal layer directly below, in the same folder, becomes masked. let mask_parent = tl.layer(id).and_then(|m| m.parent); if let Some(i) = tl.layers.iter().position(|l| l.id == id) @@ -76,7 +77,7 @@ fn toggle_mask(s: &mut Session, p: &Value) -> Result { /// Draw a line on the guide; the layer's classic tweens travel along it. fn add_motion_guide(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let Some(l) = tl.layers.get(i) else { return Err(EngineError::State("no such layer".into())) }; if l.kind != LayerKind::Normal { @@ -100,7 +101,7 @@ fn add_motion_guide(s: &mut Session, p: &Value) -> Result { if let Some(k) = guide.keyframe_mut(0) { k.duration = s.frame_count().max(1); } - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; tl.layers.insert(i, Arc::new(guide)); if let Some(l) = tl.layers.get_mut(i + 1) { Arc::make_mut(l).parent = Some(gid); @@ -126,8 +127,8 @@ fn set_layer_type(s: &mut Session, p: &Value) -> Result { Ok(layer_type_json(s, id)) } -fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { - let tl = s.doc.timeline_mut(s.scene); +pub(crate) fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder) { return Err(EngineError::State("a folder holds layers; it can't become another kind of layer".into())); @@ -161,9 +162,9 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { Ok(()) } -fn layer_type_json(s: &Session, id: LayerId) -> Value { - let Some(l) = s.doc.timeline(s.scene).layer(id) else { return json!({}) }; - let tl = s.doc.timeline(s.scene); +pub(crate) fn layer_type_json(s: &Session, id: LayerId) -> Value { + let Some(l) = s.timeline().layer(id) else { return json!({}) }; + let tl = s.timeline(); let parent_kind = l.parent.and_then(|p| tl.layer(p)).map(|x| x.kind); let masked_by = l.parent.filter(|_| parent_kind == Some(LayerKind::Mask)); let guided_by = l.parent.filter(|_| parent_kind == Some(LayerKind::Guide)); @@ -200,7 +201,7 @@ pub(crate) fn target_layers(s: &Session, p: &Value) -> Result> { let mut out: Vec = Vec::with_capacity(ids.len()); let mut folders = 0; for id in ids { - let Some(l) = s.doc.timeline(s.scene).layer(id) else { return Err(EngineError::State(format!("no layer with id {}", id.0))) }; + let Some(l) = s.timeline().layer(id) else { return Err(EngineError::State(format!("no layer with id {}", id.0))) }; // Folders have no frames: a range across a folder row acts on the layers only. if l.kind == LayerKind::Folder { folders += 1; @@ -232,19 +233,54 @@ pub(crate) fn shift_after(layer: &mut Layer, from: u32, delta: i64) { } } -/// F5 over a range: `count` frames on each target layer. +/// F5 over a range: `count` frames on each target layer. With `all_layers` (F5 with no frame +/// selection) every layer that has frames at or after `frame` grows, so the layers stay in step; +/// layers that end before it are left alone. With `advance` the playhead moves onto the last +/// frame inserted, as holding F5 walks along the timeline. fn insert_frame(s: &mut Session, p: &Value) -> Result { let (_, frame) = target(s, p)?; let count = count_param(p)?; + let all = opt_bool(p, "all_layers")?.unwrap_or(false); + let ids = if all { layers_at_or_after(s, frame) } else { target_layers(s, p)? }; let mut frames = 0; - for id in target_layers(s, p)? { + for &id in &ids { let layer = s.layer_mut(Some(id))?; for _ in 0..count { - insert_frame_at(layer, frame)?; + if all && layer.keyframe_index_at(frame).is_none() && layer.end_frame() > frame { + // A gap (or the frames before the first key) under the playhead: insert an + // empty frame there, so what follows moves along with the other layers. + insert_empty_frame_at(layer, frame)?; + } else { + insert_frame_at(layer, frame)?; + } } frames = frames.max(layer.end_frame()); } - Ok(json!({"frames": frames})) + let mut out = json!({"frames": frames, "layers": ids.iter().map(|l| l.0).collect::>()}); + if opt_bool(p, "advance")?.unwrap_or(false) { + s.set_frame(frame.saturating_add(count).min(frames.saturating_sub(1))); + out["playhead"] = json!(s.frame); + } + Ok(out) +} + +/// The layers F5 with no frame selection extends: every layer of the timeline with frames at or +/// after `frame` (folders have none). When no layer reaches that far, the active layer, so F5 +/// past the end still lengthens what you are working on. +fn layers_at_or_after(s: &Session, frame: u32) -> Vec { + let tl = s.timeline(); + let ids: Vec = tl.layers.iter().filter(|l| l.kind != LayerKind::Folder && l.end_frame() > frame).map(|l| l.id).collect(); + if ids.is_empty() { vec![s.layer] } else { ids } +} + +/// One empty frame at `frame`: everything from there on moves one frame later. +fn insert_empty_frame_at(layer: &mut Layer, frame: u32) -> Result<()> { + if layer.end_frame() >= MAX_FRAME { + return Err(EngineError::State("the timeline is at its maximum length".into())); + } + shift_after(layer, frame, 1); + layer.normalize(); + Ok(()) } pub(crate) fn insert_frame_at(layer: &mut Layer, frame: u32) -> Result<()> { @@ -349,11 +385,11 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R Some(i) => { let Some(k) = layer.keyframe_mut(i) else { return Ok(()) }; let end = k.end(); - let tween = if copy { k.tween } else { None }; + let tween = if copy { k.tween.clone() } else { None }; // A motion tween split in two keeps moving the same way in both halves. let motion = if copy { k.motion.as_ref().map(|m| { - let base = m.target_index(&k.elements).and_then(|t| k.elements.get(t)).map_or(anicraft_doc::Props([0.0; 8]), |e| anicraft_doc::Props::of(e)); + let base = m.target_index(&k.elements).and_then(|t| k.elements.get(t)).map_or(anicraft_doc::Props([0.0; anicraft_doc::PROPERTIES]), |e| anicraft_doc::Props::of(e)); m.split_at(&base, frame - k.start) }) } else { @@ -393,7 +429,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R } fn insert_keyframe(s: &mut Session, p: &Value) -> Result { - let (_, frame) = target(s, p)?; + let frame = key_frame(s, p)?; for id in target_layers(s, p)? { let layer = s.layer_mut(Some(id))?; // Inside a motion tween F6 keys every property there; the span stays whole. @@ -401,15 +437,38 @@ fn insert_keyframe(s: &mut Session, p: &Value) -> Result { insert_keyframe_at(layer, frame, true)?; } } - Ok(json!({"keyframe": frame})) + advanced(s, p, frame) } fn insert_blank_keyframe(s: &mut Session, p: &Value) -> Result { - let (_, frame) = target(s, p)?; + let frame = key_frame(s, p)?; for id in target_layers(s, p)? { insert_keyframe_at(s.layer_mut(Some(id))?, frame, false)?; } - Ok(json!({"keyframe": frame})) + advanced(s, p, frame) +} + +/// Where F6 / F7 put the key. With `advance`, a frame that is already a keyframe on every target +/// layer means "the next one": pressing F6 again after drawing makes the next drawing's key. +fn key_frame(s: &Session, p: &Value) -> Result { + let (_, frame) = target(s, p)?; + if !opt_bool(p, "advance")?.unwrap_or(false) { + return Ok(frame); + } + let ids = target_layers(s, p)?; + let tl = s.timeline(); + let on_keys = !ids.is_empty() && ids.iter().all(|id| tl.layer(*id).is_some_and(|l| l.keyframe_starting_at(frame).is_some())); + if on_keys && frame < MAX_FRAME { Ok(frame + 1) } else { Ok(frame) } +} + +/// The result of F6 / F7; with `advance` the playhead moves onto the new key. +fn advanced(s: &mut Session, p: &Value, frame: u32) -> Result { + let mut out = json!({"keyframe": frame}); + if opt_bool(p, "advance")?.unwrap_or(false) { + s.set_frame(frame); + out["playhead"] = json!(frame); + } + Ok(out) } /// Shift+F6 over a range: clears every keyframe starting in `frame..frame + count` on each @@ -448,7 +507,7 @@ fn move_keyframes(s: &mut Session, p: &Value) -> Result { Some(v) => v.as_i64().ok_or_else(|| EngineError::Param("param 'layer_by' must be a whole number of layers".into()))?, }; if layer_by != 0 { - return move_across_layers(s, p, from, to, by, layer_by); + return move_across_layers(s, p, from, to, by, layer_by, false); } let mut moved = 0; for id in target_layers(s, p)? { @@ -457,13 +516,38 @@ fn move_keyframes(s: &mut Session, p: &Value) -> Result { Ok(json!({"moved": moved})) } -/// Dragging keyframes onto other layers (`layer_by` rows down, negative = up): the frames are -/// lifted out of every source layer first (leaving blank keyframes, as in Animate), then -/// placed on the target layers, replacing what was there; frames after the landing range -/// keep their content. Lifting everything before placing anything makes overlapping row -/// ranges (dragging two rows down by one) come out right. -fn move_across_layers(s: &mut Session, p: &Value, from: u32, to: u32, by: i64, layer_by: i64) -> Result { - let order: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); +/// Moving whole spans (ADR 0083): the spans starting in `from..=to` keep their lengths, motion +/// and tweens, and land `by` frames later and `layer_by` rows down, replacing what was there. +/// `copy` (Alt-drag) leaves the originals where they were. +fn move_spans(s: &mut Session, p: &Value) -> Result { + let from = opt_u32(p, "from")?.ok_or_else(|| EngineError::Param("param 'from' is required".into()))?; + let to = opt_u32(p, "to")?.unwrap_or(from); + let by = p.get("by").and_then(Value::as_i64).ok_or_else(|| EngineError::Param("param 'by' must be a whole number of frames".into()))?; + if to < from || to > MAX_FRAME || by.unsigned_abs() > u64::from(MAX_FRAME) { + return Err(EngineError::Param(format!("frames must be in order and within {MAX_FRAME}"))); + } + let layer_by = match p.get("layer_by") { + None | Some(Value::Null) => 0, + Some(v) => v.as_i64().ok_or_else(|| EngineError::Param("param 'layer_by' must be a whole number of layers".into()))?, + }; + let copy = opt_bool(p, "copy")?.unwrap_or(false); + if by == 0 && layer_by == 0 { + if copy { + return Err(EngineError::State("the copy would land on the frames it copies: drag it somewhere else".into())); + } + return Ok(json!({"moved": 0})); + } + move_across_layers(s, p, from, to, by, layer_by, copy) +} + +/// Dragging keyframes onto other layers (`layer_by` rows down, negative = up), or whole spans +/// along their own: the frames are lifted out of every source layer first (leaving blank +/// keyframes, as in Animate; a `copy` leaves them be), then placed on the target layers, +/// replacing what was there; frames after the landing range keep their content. Lifting +/// everything before placing anything makes overlapping row ranges (dragging two rows down by +/// one) come out right. +fn move_across_layers(s: &mut Session, p: &Value, from: u32, to: u32, by: i64, layer_by: i64, copy: bool) -> Result { + let order: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); let mut rows: Vec = target_layers(s, p)?.iter().filter_map(|id| order.iter().position(|o| o == id)).collect(); rows.sort_unstable(); let mut plan = Vec::with_capacity(rows.len()); @@ -478,7 +562,9 @@ fn move_across_layers(s: &mut Session, p: &Value, from: u32, to: u32, by: i64, l for &(src, dst) in &plan { let layer = s.layer_mut(Some(src))?; let keys: Vec = layer.keyframes.iter().filter(|k| k.start >= from && k.start <= to).map(|k| (**k).clone()).collect(); - if let (Some(first), Some(last)) = (keys.first().map(|k| k.start), keys.last().map(Keyframe::end)) { + if !copy + && let (Some(first), Some(last)) = (keys.first().map(|k| k.start), keys.last().map(Keyframe::end)) + { layer.keyframes.retain(|k| !(k.start >= from && k.start <= to)); // The frames stay; their content leaves. layer.keyframes.push(Arc::new(Keyframe::new(first, last - first))); @@ -591,22 +677,23 @@ fn create_shape_tween(s: &mut Session, p: &Value) -> Result { } fn tween_of_kind(s: &mut Session, p: &Value, kind: TweenKind) -> Result { + let given = opt_easing_in(s, p, "easing")?; let k = keyframe_mut(s, p)?; - // Switching kinds keeps the easing the span already had, unless one is given. - let easing = match opt_easing(p, "easing")? { - Some(e) => e, - None => k.tween.map(|t| t.easing).unwrap_or_default(), - }; - let orient = k.tween.is_some_and(|t| t.orient); + // Switching kinds keeps the easing the span already had, unless one is given; a classic + // tween keeps its property groups' eases (a shape tween has one ease, as in Animate). + let easing = given.unwrap_or_else(|| k.tween.as_ref().map(|t| t.easing.clone()).unwrap_or_default()); + let orient = k.tween.as_ref().is_some_and(|t| t.orient); + let groups = if kind == TweenKind::Classic { k.tween.as_ref().map(|t| t.groups.clone()).unwrap_or_default() } else { Vec::new() }; // It replaces a motion tween, keeping the object as it is on the first frame. crate::cmds_motion::bake_first_frame(k); - k.tween = Some(Tween { easing, kind, orient }); + let label = easing.label(); + k.tween = Some(Tween { easing, kind, orient, groups }); // Shape hints only mean something to a shape tween. if kind != TweenKind::Shape { k.hints.clear(); } let kind = if kind == TweenKind::Shape { "shape" } else { "classic" }; - Ok(json!({"tween": k.start, "easing": easing.label(), "kind": kind})) + Ok(json!({"tween": k.start, "easing": label, "kind": kind})) } fn remove_tween(s: &mut Session, p: &Value) -> Result { @@ -618,11 +705,17 @@ fn remove_tween(s: &mut Session, p: &Value) -> Result { } fn set_easing(s: &mut Session, p: &Value) -> Result { - let easing = opt_easing(p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?; + let easing = opt_easing_in(s, p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?; + let group = crate::cmds_ease::group(p)?; let k = keyframe_mut(s, p)?; let t = k.tween.as_mut().ok_or_else(|| EngineError::State("this span has no tween; create one first".into()))?; - t.easing = easing; - Ok(json!({"easing": easing.label()})) + let label = easing.label(); + match group { + Some(_) if t.kind == TweenKind::Shape => return Err(EngineError::State("a shape tween has one ease for everything; property groups ease separately in classic tweens".into())), + Some(g) => t.set_ease(g, Some(easing)), + None => t.easing = easing, + } + Ok(json!({"easing": label, "group": group.map_or("all", |g| g.key())})) } fn set_label(s: &mut Session, p: &Value) -> Result { @@ -656,12 +749,13 @@ fn new_folder(s: &mut Session, p: &Value) -> Result { /// The colour the `n`th layer gets (its outline and timeline bar). pub(crate) fn layer_color(n: usize) -> anicraft_doc::Rgba { - const PALETTE: [u32; 7] = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; - anicraft_doc::Rgba::hex(PALETTE.get(n % PALETTE.len()).copied().unwrap_or(0x4fa3ff)) + // The first seven of the layer colours, in turn. + const TURN: usize = 7; + anicraft_doc::Rgba::hex(crate::LAYER_COLORS.get(n % TURN).copied().unwrap_or(0x4fa3ff)) } fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); if tl.layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } @@ -688,7 +782,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { k.duration = s.frame_count().max(1); } layer.color = layer_color(n); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; tl.layers.insert(at, Arc::new(layer)); tl.repair_masks(); s.layer = id; @@ -700,7 +794,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { /// stays where it is, in the mask's folder. fn delete_layer(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let is_folder = tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder); let range = if is_folder { tl.group_range(i) } else { i..i + 1 }; @@ -709,7 +803,7 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State("a document needs at least one layer to draw on".into())); } let up = tl.layers.get(i).and_then(|l| l.parent); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; if !is_folder { for l in tl.layers.iter_mut().filter(|l| l.parent == Some(id)) { Arc::make_mut(l).parent = up; @@ -718,8 +812,8 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result { let removed: Vec = tl.layers.drain(range.clone()).map(|l| l.id).collect(); tl.repair_masks(); if removed.contains(&s.layer) { - let j = range.start.min(s.doc.timeline(s.scene).layers.len().saturating_sub(1)); - s.layer = s.doc.timeline(s.scene).layers.get(j).map_or(LayerId(0), |l| l.id); + let j = range.start.min(s.timeline().layers.len().saturating_sub(1)); + s.layer = s.timeline().layers.get(j).map_or(LayerId(0), |l| l.id); s.selection.clear(); } Ok(json!({"deleted": id.0, "layers": removed.len()})) @@ -747,11 +841,11 @@ fn select_layer(s: &mut Session, p: &Value) -> Result { let id = if let Some(id) = opt_u64(p, "layer")? { LayerId(id) } else if let Some(i) = opt_u64(p, "index")? { - usize::try_from(i).ok().and_then(|i| s.doc.timeline(s.scene).layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))? + usize::try_from(i).ok().and_then(|i| s.timeline().layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))? } else { return Err(EngineError::Param("pass {\"layer\": id} or {\"index\": n}".into())); }; - if s.doc.timeline(s.scene).layer(id).is_none() { + if s.timeline().layer(id).is_none() { return Err(EngineError::State(format!("no layer with id {}", id.0))); } // A click on a layer's name in Animate: the layer becomes active with all of its artwork at @@ -774,7 +868,7 @@ fn select_layer(s: &mut Session, p: &Value) -> Result { /// where it landed: moving it in under a folder or mask puts it inside, moving it out frees it. fn move_layer(s: &mut Session, p: &Value, d: i64) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?; let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let n = tl.layers.len(); if tl.layers.get(i).is_some_and(|l| matches!(l.kind, LayerKind::Mask | LayerKind::Folder)) { diff --git a/crates/engine/src/cmds_view.rs b/crates/engine/src/cmds_view.rs new file mode 100644 index 00000000..1e088563 --- /dev/null +++ b/crates/engine/src/cmds_view.rs @@ -0,0 +1,202 @@ +//! Rulers, grid and guides (ADR 0076): View › Rulers, View › Grid, View › Guides and the pixel +//! snapping in View › Snapping. Whether each shows and snaps is the session's (`ViewAids`, no +//! undo step); the guides, the grid's spacing and colour and the guides' colour are the +//! document's, so changing them is an undoable edit saved with the file. + +use crate::params::*; +use crate::snap::{Accuracy, ViewAids}; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::aids::{GRID_MAX, GRID_MIN}; +use anicraft_doc::{Guide, GuideAxis, MAX_GUIDES}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("view.rulers", "Rulers", "View", Some("Ctrl+Alt+Shift+R"), "{on?: bool} (default: toggle) rulers along the stage's top and left edges, in stage pixels from its top-left corner; drag from one to make a guide", false, (|s, p| toggle(s, p, |a| &mut a.rulers)) as crate::RunFn), + c("view.grid_show", "Show Grid", "View/Grid", Some("Ctrl+'"), "{on?: bool} (default: toggle) the grid on the stage (never in pictures or exports)", false, |s, p| toggle(s, p, |a| &mut a.show_grid)), + c("view.grid_snap", "Snap to Grid", "View/Grid", Some("Ctrl+Shift+'"), "{on?: bool} (default: toggle) points being drawn, dragged or moved snap to the grid's lines (shown or not)", false, |s, p| toggle(s, p, |a| &mut a.snap_grid)), + c( + "view.grid_set", + "Edit Grid…", + "View/Grid", + Some("Ctrl+Alt+G"), + "{spacing?, spacing_x?, spacing_y? (stage pixels, 1..=4096), color?: \"#rrggbb[aa]\", over_objects?: bool, show?: bool, snap?: bool, accuracy?: \"close\"|\"normal\"|\"distant\"|\"always\"} sets the grid; spacing and colour are saved with the document (one undo step), the rest is the editor's; returns everything as view.aids does", + true, + grid_set, + ), + c("view.guides_show", "Show Guides", "View/Guides", Some("Ctrl+;"), "{on?: bool} (default: toggle) this scene's guides on the stage (never in pictures or exports)", false, |s, p| toggle(s, p, |a| &mut a.show_guides)), + c("view.guides_lock", "Lock Guides", "View/Guides", Some("Ctrl+Alt+;"), "{on?: bool} (default: toggle) locked guides can't be dragged, moved or deleted one by one (new ones can still be added, and Clear Guides clears them)", false, |s, p| toggle(s, p, |a| &mut a.lock_guides)), + c("view.guides_snap", "Snap to Guides", "View/Guides", Some("Ctrl+Shift+;"), "{on?: bool} (default: toggle) points being drawn, dragged or moved snap to the guides", false, |s, p| toggle(s, p, |a| &mut a.snap_guides)), + c( + "view.guides_set", + "Edit Guides…", + "View/Guides", + Some("Ctrl+Alt+Shift+G"), + "{color?: \"#rrggbb[aa]\", show?: bool, lock?: bool, snap?: bool, accuracy?: \"close\"|\"normal\"|\"distant\"} sets the guides; the colour is saved with the document (one undo step), the rest is the editor's; returns everything as view.aids does", + true, + guides_set, + ), + c("view.guide_add", "Add Guide…", "View/Guides", None, "{axis: \"horizontal\"|\"vertical\", at} adds a guide to this scene at `at` stage pixels (y for a horizontal guide, x for a vertical one); returns {index, guides}", true, guide_add), + c("view.guide_move", "Move Guide", "", None, "{index, at} moves this scene's guide `index` (as view.aids lists them) to `at`; refused while guides are locked", true, guide_move), + c("view.guide_delete", "Delete Guide", "", None, "{index} removes this scene's guide `index`; refused while guides are locked", true, guide_delete), + c("view.guides_clear", "Clear Guides", "View/Guides", None, "{} removes every guide from this scene (undoable)", true, guides_clear), + c("view.snap_pixels", "Snap to Pixels", "View/Snapping", None, "{on?: bool} (default: toggle) points being drawn, dragged or moved go to whole stage pixels where nothing else snaps them", false, |s, p| toggle(s, p, |a| &mut a.snap_pixels)), + c("view.aids", "Rulers, Grid and Guides", "", None, "{} whether the rulers, grid and guides show and snap, the grid's and guides' settings, and this scene's guides [{axis, at}, ..]", false, |s, _| Ok(aids_json(s))), + ] +} + +fn toggle(s: &mut Session, p: &Value, field: fn(&mut ViewAids) -> &mut bool) -> Result { + let f = field(&mut s.aids); + *f = opt_bool(p, "on")?.unwrap_or(!*f); + Ok(aids_json(s)) +} + +/// Everything about the rulers, grid and guides, as `view.aids` returns it. +pub(crate) fn aids_json(s: &Session) -> Value { + let a = s.aids; + let g = s.doc.aids.grid; + json!({ + "rulers": a.rulers, + "grid": {"show": a.show_grid, "snap": a.snap_grid, "accuracy": a.grid_accuracy.key(), "spacing_x": g.spacing_x, "spacing_y": g.spacing_y, "color": color_hex(g.color), "over_objects": g.over_objects}, + "guides": {"show": a.show_guides, "lock": a.lock_guides, "snap": a.snap_guides, "accuracy": a.guide_accuracy.key(), "color": color_hex(s.doc.aids.guide_color), "list": guides_json(s)}, + "snap_pixels": a.snap_pixels, + "snap_objects": s.style.snap_objects, + }) +} + +fn color_hex(c: anicraft_doc::Rgba) -> String { + let c = c.sanitized(); + if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } +} + +fn guides_json(s: &Session) -> Value { + json!(s.guides().iter().map(|g| json!({"axis": g.axis.key(), "at": g.at})).collect::>()) +} + +fn accuracy(p: &Value, grid: bool) -> Result> { + let Some(k) = opt_str(p, "accuracy")? else { return Ok(None) }; + match Accuracy::parse(k) { + Some(Accuracy::Always) if !grid => Err(EngineError::Param("guides snap 'close', 'normal' or 'distant' (only the grid can 'always' snap)".into())), + Some(a) => Ok(Some(a)), + None => Err(EngineError::Param(format!("unknown accuracy '{k}' (close, normal, distant{})", if grid { " or always" } else { "" }))), + } +} + +fn spacing(p: &Value, key: &str) -> Result> { + match opt_f32(p, key)? { + Some(v) if !(GRID_MIN..=GRID_MAX).contains(&v) => Err(EngineError::Param(format!("'{key}' must be between {GRID_MIN} and {GRID_MAX} pixels"))), + v => Ok(v), + } +} + +fn grid_set(s: &mut Session, p: &Value) -> Result { + // Everything is read (and checked) before anything changes. + let both = spacing(p, "spacing")?; + let (sx, sy) = (spacing(p, "spacing_x")?.or(both), spacing(p, "spacing_y")?.or(both)); + let color = opt_color(p, "color")?; + let over = opt_bool(p, "over_objects")?; + let (show, snap, acc) = (opt_bool(p, "show")?, opt_bool(p, "snap")?, accuracy(p, true)?); + let mut g = s.doc.aids.grid; + g.spacing_x = sx.unwrap_or(g.spacing_x); + g.spacing_y = sy.unwrap_or(g.spacing_y); + g.color = color.map_or(g.color, anicraft_doc::Rgba::sanitized); + g.over_objects = over.unwrap_or(g.over_objects); + if g != s.doc.aids.grid { + Arc::make_mut(&mut s.doc.aids).grid = g; + } + let a = &mut s.aids; + a.show_grid = show.unwrap_or(a.show_grid); + a.snap_grid = snap.unwrap_or(a.snap_grid); + a.grid_accuracy = acc.unwrap_or(a.grid_accuracy); + Ok(aids_json(s)) +} + +fn guides_set(s: &mut Session, p: &Value) -> Result { + let color = opt_color(p, "color")?; + let (show, lock, snap, acc) = (opt_bool(p, "show")?, opt_bool(p, "lock")?, opt_bool(p, "snap")?, accuracy(p, false)?); + if let Some(c) = color.map(anicraft_doc::Rgba::sanitized) + && c != s.doc.aids.guide_color + { + Arc::make_mut(&mut s.doc.aids).guide_color = c; + } + let a = &mut s.aids; + a.show_guides = show.unwrap_or(a.show_guides); + a.lock_guides = lock.unwrap_or(a.lock_guides); + a.snap_guides = snap.unwrap_or(a.snap_guides); + a.guide_accuracy = acc.unwrap_or(a.guide_accuracy); + Ok(aids_json(s)) +} + +/// This scene's guides, copy-on-write. +fn guides_mut(s: &mut Session) -> Result<&mut Vec> { + let i = s.scene; + let scene = s.doc.scenes.get_mut(i).ok_or_else(|| EngineError::State("no scene is open".into()))?; + Ok(&mut Arc::make_mut(scene).guides) +} + +fn position(p: &Value) -> Result { + let at = f32_req(p, "at")?; + if at.abs() > anicraft_doc::GUIDE_REACH { + return Err(EngineError::Param(format!("'at' must be within {} pixels of the stage's corner", anicraft_doc::GUIDE_REACH))); + } + Ok(at) +} + +fn index(s: &Session, p: &Value) -> Result { + let n = s.guides().len(); + let i = opt_u64(p, "index")?.ok_or_else(|| EngineError::Param("missing param 'index'".into()))?; + usize::try_from(i).ok().filter(|i| *i < n).ok_or_else(|| EngineError::Param(if n == 0 { "this scene has no guides".into() } else { format!("no guide {i} (this scene has {n}: 0 to {})", n - 1) })) +} + +fn unlocked(s: &Session) -> Result<()> { + if s.aids.lock_guides { + return Err(EngineError::State("guides are locked: turn off View › Guides › Lock Guides to move or delete them".into())); + } + Ok(()) +} + +fn guide_add(s: &mut Session, p: &Value) -> Result { + let axis = str_req(p, "axis")?; + let axis = GuideAxis::parse(axis).ok_or_else(|| EngineError::Param(format!("unknown axis '{axis}' (horizontal or vertical)")))?; + let at = position(p)?; + let guide = Guide::new(axis, at).ok_or_else(|| EngineError::Param("'at' must be a number".into()))?; + if s.guides().len() >= MAX_GUIDES { + return Err(EngineError::State(format!("a scene has at most {MAX_GUIDES} guides"))); + } + let guides = guides_mut(s)?; + guides.push(guide); + let index = guides.len() - 1; + Ok(json!({"index": index, "guides": guides_json(s)})) +} + +fn guide_move(s: &mut Session, p: &Value) -> Result { + unlocked(s)?; + let i = index(s, p)?; + let at = position(p)?; + if let Some(g) = guides_mut(s)?.get_mut(i) + && g.at != at + { + g.at = at; + } + Ok(json!({"index": i, "guides": guides_json(s)})) +} + +fn guide_delete(s: &mut Session, p: &Value) -> Result { + unlocked(s)?; + let i = index(s, p)?; + let guides = guides_mut(s)?; + if i < guides.len() { + guides.remove(i); + } + Ok(json!({"deleted": i, "guides": guides_json(s)})) +} + +fn guides_clear(s: &mut Session, _: &Value) -> Result { + let n = s.guides().len(); + if n > 0 { + guides_mut(s)?.clear(); + } + Ok(json!({"cleared": n})) +} diff --git a/crates/engine/src/cmds_warp.rs b/crates/engine/src/cmds_warp.rs new file mode 100644 index 00000000..3d3d923b --- /dev/null +++ b/crates/engine/src/cmds_warp.rs @@ -0,0 +1,397 @@ +//! Asset Warp commands (ADR 0079): a warp mesh on a shape or a bitmap, pins on it, and moving +//! them to bend the artwork. +//! +//! The mesh belongs to the artwork: `warp.add` (and the first `warp.pin_add`) puts it on the +//! element at the playhead and on every keyframe of its layer that holds the same artwork, so +//! keyframes made from it bend the same mesh. Pins are added to and removed from all of those +//! keyframes (where the artwork shows there, so nothing moves), while `warp.pin_move` moves a +//! pin on the keyframe at the playhead only: that is the pose, and poses tween with classic +//! tweens. Inside a tween a move keys the frame with what it shows, as editing any tweened +//! object does. A drag sends many `warp.pin_move` calls inside one gesture: one undo step. +//! +//! A shape edited since by another tool (its outline no longer the one its warp gave it) starts +//! again from how it now looks: its pins stay where they show and become its rest. + +use crate::params::*; +use crate::{CommandSpec, EngineError, KeyEdit, MAX_FRAME, Result, Session}; +use anicraft_doc::warp::{self, MAX_EXTENT, MAX_PINS, MAX_RESOLUTION, MAX_WARP_POINTS, MIN_RESOLUTION, PIN_SPACING, Pin, PinId, Warp}; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId, Paint, Shape, evaluate_layer_elements}; +use anicraft_geom::{Affine, Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, params, mutates, run| CommandSpec { id, label, menu, shortcut: None, params, mutates, run }; + vec![ + c( + "warp.add", + "Add Warp Mesh", + "Modify/Asset Warp", + "{element? (a shape or bitmap; default the one selected), resolution? (cells along the longer side, 2…48; default 12)} → {element, created, resolution, columns, rows}. Covers the artwork with a warp mesh on every keyframe of its layer that holds it (it becomes a drawing object); on artwork that has one, changes the mesh's resolution", + true, + add as crate::RunFn, + ), + c( + "warp.pin_add", + "Add Warp Pin", + "", + "{element?, x, y (stage px, on the artwork)} → {element, pin, created}. Pins the artwork there (adding the mesh first if it has none), on every keyframe that bends the same mesh; nothing moves", + true, + pin_add, + ), + c("warp.pin_move", "Move Warp Pin", "", "{element?, pin, x?, y? (stage px: where the pin goes), dx?, dy? (stage px: by how much), frame?} → {element, pin, at}. Bends the artwork at the frame (keying it inside a tween); pins tween between keyframes", true, pin_move), + c("warp.pin_remove", "Remove Warp Pin", "", "{element?, pin} removes the pin from every keyframe that bends the same mesh; the artwork follows the pins that are left", true, pin_remove), + c("warp.remove", "Remove Warp", "Modify/Asset Warp", "{element?} takes the warp mesh and its pins off the artwork on every keyframe of its layer: it shows as drawn again", true, remove), + c("warp.info", "Warp Mesh", "", "{element?, frame?} → the artwork's warp at the frame: resolution, the mesh's columns, rows, vertices and triangles, whether it is bent, and its pins (id, where they show in stage px, and where they were placed on the artwork as drawn, in its own space)", false, info), + ] +} + +/// The element a warp command acts on: `element`, or the one selected element on the active +/// layer. +fn element_param(s: &Session, p: &Value) -> Result { + if let Some(id) = opt_u64(p, "element")? { + return Ok(ElementId(id)); + } + match s.selection.on(s.layer).as_slice() { + [one] => Ok(*one), + [] => Err(EngineError::State("select a shape or a bitmap first (or give 'element')".into())), + _ => Err(EngineError::State("select just one shape or bitmap to warp".into())), + } +} + +/// Where element `id` is at `frame`, as it shows (tweened): its layer and the element. +fn find(s: &Session, id: ElementId, frame: u32) -> Result<(LayerId, Arc)> { + s.timeline() + .layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + Some((l.id, els.iter().find(|e| e.id == id)?.clone())) + }) + .ok_or_else(|| EngineError::State(format!("no element with id {} on the stage at frame {}", id.0, frame + 1))) +} + +fn shape_of(el: &Element) -> Result<&Shape> { + match &el.kind { + ElementKind::Shape(sh) => Ok(sh), + _ => Err(EngineError::State("Asset Warp bends shapes and bitmaps; break a symbol or text apart first (Modify › Break Apart)".into())), + } +} + +fn frame_param(s: &Session, p: &Value) -> Result { + let f = opt_u32(p, "frame")?.unwrap_or(s.frame); + if f > MAX_FRAME { + return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))); + } + Ok(f) +} + +/// The warp a command starts from on `sh`: its own while it shows it, rebased when the shape +/// was edited since, `None` without one. +fn current(sh: &Shape) -> Option { + let w = sh.warp.as_deref()?; + Some(if w.shows(&sh.path) { w.clone() } else { w.rebased(sh.path.clone()) }) +} + +fn check_artwork(path: &Path) -> Result<()> { + if warp::anchor_count(path) > MAX_WARP_POINTS { + return Err(EngineError::State(format!("that artwork has more than {MAX_WARP_POINTS} points: simplify it first (Modify › Shape › Optimize)"))); + } + if Warp::new(Arc::new(path.clone()), MIN_RESOLUTION).grid().is_none() { + return Err(EngineError::State("that artwork has no extent to warp".into())); + } + Ok(()) +} + +/// Runs `edit` on element `id` in the keyframe of `layer` that an edit at `frame` changes (keying +/// the frame inside a classic or shape tween), with the shape and the stage → local map. +fn edit_at(s: &mut Session, layer: LayerId, frame: u32, id: ElementId, edit: impl FnOnce(&mut Shape, &Affine) -> Result) -> Result { + let tl = s.timeline(); + let l = tl.layer(layer).ok_or_else(|| EngineError::State("the layer went away".into()))?; + if l.keyframe_at(frame).is_some_and(|k| k.motion.is_some()) { + return Err(EngineError::State("Asset Warp pins tween with classic tweens: this frame is in a motion tween".into())); + } + let (was_layer, was_frame) = (s.layer, s.frame); + s.layer = layer; + s.frame = frame; + let out = (|| { + let kf = s.editable_keyframe_in(KeyEdit::Artwork)?; + let e = kf.elements.iter_mut().find(|e| e.id == id).ok_or_else(|| EngineError::State("that element isn't on this keyframe".into()))?; + let el = Arc::make_mut(e); + let inv = el.transform.inverse().ok_or_else(|| EngineError::State("artwork scaled to nothing can't be warped".into()))?; + let ElementKind::Shape(sh) = &mut el.kind else { return Err(EngineError::State("Asset Warp bends shapes and bitmaps".into())) }; + edit(sh, &inv) + })(); + s.layer = was_layer; + s.frame = was_frame; + out +} + +/// Runs `f` on every other keyframe of `layer` (not the one starting at `skip`) whose element +/// `id` is warped on the same mesh as `rest` (it shows its warp), then bends it again. +fn each_other(s: &mut Session, layer: LayerId, skip: Option, id: ElementId, rest: &Arc, resolution: u32, mut f: impl FnMut(&mut Warp, &mut Shape)) -> Result { + let l = s.layer_mut(Some(layer))?; + let mut n = 0; + for k in &mut l.keyframes { + if Some(k.start) == skip { + continue; + } + let same = |e: &Arc| e.id == id && matches!(&e.kind, ElementKind::Shape(sh) if sh.live_warp().is_some_and(|w| anicraft_doc::arc_eq(&w.rest, rest) && w.resolution == resolution)); + if !k.elements.iter().any(same) { + continue; + } + for e in Arc::make_mut(k).elements.iter_mut().filter(|e| same(e)) { + if let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind + && let Some(mut w) = sh.warp.as_deref().cloned() + { + f(&mut w, sh); + if sh.warp.is_some() { + sh.set_warp(w); + } + n += 1; + } + } + } + Ok(n) +} + +/// The start of the keyframe of `layer` covering `frame`. +fn key_start(s: &Session, layer: LayerId, frame: u32) -> Option { + s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).map(|k| k.start) +} + +fn resolution_param(p: &Value) -> Result> { + match opt_u32(p, "resolution")? { + Some(r) if !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&r) => Err(EngineError::Param(format!("param 'resolution' must be {MIN_RESOLUTION}…{MAX_RESOLUTION}"))), + r => Ok(r), + } +} + +/// Puts a warp on element `id` at the playhead (and on every keyframe holding the same +/// artwork), or changes its resolution. Returns whether it was made, and the warp. +fn ensure(s: &mut Session, layer: LayerId, id: ElementId, resolution: Option) -> Result<(bool, Warp)> { + let frame = s.frame; + // The artwork as it is on the keyframe at the playhead (before any keying), to find copies. + let before: Option> = s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).and_then(|k| k.elements.iter().find(|e| e.id == id)).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.path.clone()), + _ => None, + }); + let (created, w, old) = edit_at(s, layer, frame, id, |sh, _| { + let old = sh.live_warp().map(|w| (w.rest.clone(), w.resolution)); + let (created, mut w) = match current(sh) { + Some(w) => (false, w), + None => { + check_artwork(&sh.path)?; + (true, Warp::new(sh.path.clone(), resolution.unwrap_or(warp::DEFAULT_RESOLUTION))) + } + }; + if let Some(r) = resolution { + w.resolution = r; + } + // A warped shape is a drawing object: drawing over it never cuts its outline. + sh.merge = false; + sh.set_warp(w.clone()); + Ok((created, w, old)) + })?; + let skip = key_start(s, layer, frame); + match old { + // A new resolution: every keyframe on the same mesh takes it. + Some((rest, r)) if !created && Some(r) != resolution && resolution.is_some() => { + each_other(s, layer, skip, id, &rest, r, |x, _| x.resolution = w.resolution)?; + } + Some(_) => {} + None => { + // A new mesh: every other keyframe holding the very artwork it covers gets it too. + let Some(path) = before else { return Ok((created, w)) }; + let l = s.layer_mut(Some(layer))?; + for k in &mut l.keyframes { + if Some(k.start) == skip { + continue; + } + let same = |e: &Arc| e.id == id && matches!(&e.kind, ElementKind::Shape(sh) if sh.warp.is_none() && (Arc::ptr_eq(&sh.path, &path) || *sh.path == *path)); + if k.elements.iter().any(same) { + for e in Arc::make_mut(k).elements.iter_mut().filter(|e| same(e)) { + if let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind { + sh.merge = false; + let mut x = w.clone(); + x.rest = sh.path.clone(); + sh.set_warp(x); + } + } + } + } + } + } + Ok((created, w)) +} + +fn add(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let resolution = resolution_param(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let (created, w) = ensure(s, layer, id, resolution)?; + let g = w.grid(); + Ok(json!({"element": id.0, "created": created, "resolution": w.resolution, "columns": g.map_or(0, |g| g.nx), "rows": g.map_or(0, |g| g.ny)})) +} + +fn stage_point(p: &Value) -> Result { + let v = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if v.x.abs() > MAX_EXTENT || v.y.abs() > MAX_EXTENT { + return Err(EngineError::Param("the point must be within ±1,000,000 px".into())); + } + Ok(v) +} + +fn pin_add(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let at = stage_point(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let (created, _) = ensure(s, layer, id, None)?; + let pin = PinId(s.doc.alloc_id()); + let frame = s.frame; + let (rest, mesh) = edit_at(s, layer, frame, id, |sh, inv| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh".into()))?; + if w.pins.len() >= MAX_PINS { + return Err(EngineError::State(format!("a warp has at most {MAX_PINS} pins"))); + } + let local = inv.apply(at); + let r = w.unmap(local).ok_or_else(|| EngineError::State("click on the artwork to pin it".into()))?; + if w.pins.iter().any(|q| q.rest.distance(r) < PIN_SPACING) { + return Err(EngineError::State("there is a pin there already".into())); + } + w.pins.push(Pin { id: pin, rest: r, at: local }); + let mesh = (w.rest.clone(), w.resolution); + sh.set_warp(w); + Ok((r, mesh)) + })?; + // The same pin on every other keyframe bending this mesh, where that point shows there. + let skip = key_start(s, layer, frame); + each_other(s, layer, skip, id, &mesh.0, mesh.1, |w, _| { + if w.pins.len() < MAX_PINS && w.pin(pin).is_none() { + let shown = w.map(rest); + w.pins.push(Pin { id: pin, rest, at: shown }); + } + })?; + Ok(json!({"element": id.0, "pin": pin.0, "created": created})) +} + +fn pin_id(p: &Value) -> Result { + opt_u64(p, "pin")?.map(PinId).ok_or_else(|| EngineError::Param("param 'pin' (a pin id; see warp.info) is required".into())) +} + +fn pin_move(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let pin = pin_id(p)?; + let frame = frame_param(s, p)?; + let to = match (opt_f32(p, "x")?, opt_f32(p, "y")?) { + (Some(x), Some(y)) => Some(Vec2::new(x, y)), + (None, None) => None, + _ => return Err(EngineError::Param("give both 'x' and 'y' (or 'dx' and 'dy')".into())), + }; + let by = Vec2::new(opt_f32(p, "dx")?.unwrap_or(0.0), opt_f32(p, "dy")?.unwrap_or(0.0)); + let (layer, el) = find(s, id, frame)?; + shape_of(&el)?; + let xf = el.transform; + let at = edit_at(s, layer, frame, id, |sh, inv| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh: add pins with the Warp tool first".into()))?; + let q = w.pins.iter_mut().find(|q| q.id == pin).ok_or_else(|| EngineError::State(format!("no pin with id {} on that artwork", pin.0)))?; + let local = match to { + Some(t) => inv.apply(t), + None => q.at + inv.apply_vector(by), + }; + if !(local.is_finite() && local.x.abs() <= MAX_EXTENT && local.y.abs() <= MAX_EXTENT) { + return Err(EngineError::Param("the pin must stay within ±1,000,000 px".into())); + } + q.at = local; + sh.set_warp(w); + Ok(local) + })?; + let shown = xf.apply(at); + Ok(json!({"element": id.0, "pin": pin.0, "at": [shown.x, shown.y]})) +} + +fn pin_remove(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let pin = pin_id(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let frame = s.frame; + let mesh = edit_at(s, layer, frame, id, |sh, _| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh".into()))?; + let before = w.pins.len(); + w.pins.retain(|q| q.id != pin); + if w.pins.len() == before { + return Err(EngineError::State(format!("no pin with id {} on that artwork", pin.0))); + } + let mesh = (w.rest.clone(), w.resolution); + sh.set_warp(w); + Ok(mesh) + })?; + let skip = key_start(s, layer, frame); + let n = each_other(s, layer, skip, id, &mesh.0, mesh.1, |w, _| w.pins.retain(|q| q.id != pin))?; + Ok(json!({"element": id.0, "pin": pin.0, "keyframes": n + 1})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let (layer, el) = find(s, id, s.frame)?; + let sh = shape_of(&el)?; + let frame = s.frame; + let Some(w) = sh.live_warp().cloned() else { + if sh.warp.is_some() { + // Edited since by another tool: the stale warp just goes; the shape stays as it is. + edit_at(s, layer, frame, id, |sh, _| { + sh.warp = None; + Ok(()) + })?; + return Ok(json!({"element": id.0, "keyframes": 1})); + } + return Err(EngineError::State("that artwork has no warp mesh".into())); + }; + edit_at(s, layer, frame, id, |sh, _| { + sh.path = w.rest.clone(); + sh.warp = None; + Ok(()) + })?; + let skip = key_start(s, layer, frame); + let n = each_other(s, layer, skip, id, &w.rest, w.resolution, |w, sh| { + sh.path = w.rest.clone(); + sh.warp = None; + })?; + Ok(json!({"element": id.0, "keyframes": n + 1})) +} + +fn info(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let frame = frame_param(s, p)?; + let (layer, el) = find(s, id, frame)?; + let sh = shape_of(&el)?; + let bitmap = matches!(sh.fill, Some(Paint::Bitmap { .. })); + let Some(w) = sh.live_warp() else { + return Ok(json!({"element": id.0, "layer": layer.0, "warped": false, "bitmap": bitmap, "stale": sh.warp.is_some()})); + }; + let g = w.grid(); + let pins: Vec = w + .pins + .iter() + .map(|q| { + let at = el.transform.apply(q.at); + json!({"pin": q.id.0, "at": [at.x, at.y], "rest": [q.rest.x, q.rest.y]}) + }) + .collect(); + Ok(json!({ + "element": id.0, + "layer": layer.0, + "warped": true, + "bitmap": bitmap, + "bent": !w.at_rest(), + "resolution": w.resolution, + "columns": g.map_or(0, |g| g.nx), + "rows": g.map_or(0, |g| g.ny), + "vertices": g.map_or(0, |g| (g.nx + 1) * (g.ny + 1)), + "triangles": g.map_or(0, |g| 2 * g.nx * g.ny), + "pins": pins, + })) +} diff --git a/crates/engine/src/cmds_width.rs b/crates/engine/src/cmds_width.rs index 38fd6d28..3bc2088a 100644 --- a/crates/engine/src/cmds_width.rs +++ b/crates/engine/src/cmds_width.rs @@ -51,7 +51,7 @@ pub(crate) fn visible_shape(s: &Session, id: ElementId) -> Result Ok(el), ElementKind::Shape(_) => Err(EngineError::State("this shape has no stroke (give it one in Properties or with the Ink Bottle)".into())), - ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => Err(EngineError::State("only shapes have strokes (break it apart with Ctrl+B to edit its lines)".into())), + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => Err(EngineError::State("only shapes have strokes (break it apart with Ctrl+B to edit its lines)".into())), } } @@ -62,7 +62,7 @@ pub(crate) fn shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> { let el = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?; match &mut el.kind { ElementKind::Shape(sh) => Ok(sh), - ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => Err(EngineError::State("only shapes have strokes".into())), + ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => Err(EngineError::State("only shapes have strokes".into())), } } diff --git a/crates/engine/src/color_tests.rs b/crates/engine/src/color_tests.rs new file mode 100644 index 00000000..0031d910 --- /dev/null +++ b/crates/engine/src/color_tests.rs @@ -0,0 +1,259 @@ +//! Colour effects through the command registry (ADR 0056): every style, switching styles, +//! values on a mixed selection, classic and motion tweens, undo, the file round trip and the +//! renders they give. + +use super::*; +use anicraft_doc::{ColorEffect, ColorStyle, ColorTransform, Property, Rgba}; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A white 20 × 20 square at the origin, selected. +fn square() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "fill": "#336699", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + s +} + +fn effect(s: &Session) -> ColorEffect { + s.visible_elements().first().map(|e| e.color).unwrap_or_default() +} + +/// The square's colour at the stage centre of its frame (CPU oracle, 1:1), 0–255. +fn pixel(s: &Session, frame: u32) -> [u8; 4] { + let pm = anicraft_render::render_frame(&s.doc, frame, 1.0).unwrap(); + let px = pm.to_rgba8(); + let i = ((10 * pm.width + 10) * 4) as usize; + [px[i], px[i + 1], px[i + 2], px[i + 3]] +} + +fn near(a: [u8; 4], b: [u8; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 1) +} + +#[test] +fn every_style_is_set_and_reported() { + let mut s = square(); + let v = run(&mut s, "element.set_color_effect", json!({"brightness": -50})); + assert_eq!(v, json!({"style": "brightness", "brightness": -50.0})); + assert_eq!(effect(&s), ColorEffect::Brightness(-0.5)); + let v = run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 25})); + assert_eq!(v, json!({"style": "tint", "tint": "#ff0000", "tint_amount": 25.0})); + let v = run(&mut s, "element.set_color_effect", json!({"alpha": 40})); + assert_eq!(v, json!({"style": "alpha", "alpha": 40.0})); + run(&mut s, "element.set_color_effect", json!({"red_multiplier": -100, "red_offset": 255, "alpha_offset": -10.5})); + assert_eq!(effect(&s), ColorEffect::Advanced(ColorTransform { mul: [-1.0, 1.0, 1.0, 0.4], add: [1.0, 0.0, 0.0, -10.5 / 255.0] }), "Advanced starts from the alpha it had"); + let v = run(&mut s, "element.set_color_effect", json!({"style": "none"})); + assert_eq!(v, json!({"style": "none"})); + assert_eq!(effect(&s), ColorEffect::None); +} + +#[test] +fn a_new_style_keeps_the_look_it_can() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#00ff00", "tint_amount": 60})); + let before = pixel(&s, 0); + run(&mut s, "element.set_color_effect", json!({"style": "advanced"})); + assert_eq!(effect(&s).style(), ColorStyle::Advanced); + assert!(near(pixel(&s, 0), before), "Advanced is exactly the tint"); + run(&mut s, "element.set_color_effect", json!({"style": "brightness"})); + assert_eq!(effect(&s), ColorEffect::Brightness(0.0)); + run(&mut s, "element.set_color_effect", json!({"style": "tint"})); + assert_eq!(effect(&s), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 }); +} + +#[test] +fn bad_params_change_nothing() { + let mut s = square(); + let before = s.doc.clone(); + for p in [ + json!({}), + json!({"style": "sepia"}), + json!({"brightness": 101}), + json!({"tint_amount": -1}), + json!({"red_offset": 300}), + json!({"alpha": 50, "brightness": 10}), + json!({"style": "tint", "alpha": 50}), + json!({"tint": "red"}), + json!({"alpha": f64::NAN}), + ] { + assert!(s.execute("element.set_color_effect", &p).is_err(), "{p}"); + } + assert_eq!(s.doc, before); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("element.set_color_effect", &json!({"style": "alpha"})).is_err(), "nothing selected"); +} + +#[test] +fn renders_follow_the_arithmetic() { + // #336699 = (51, 102, 153). + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": 50})); + assert!(near(pixel(&s, 0), [153, 179, 204, 255]), "{:?}", pixel(&s, 0)); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + assert!(near(pixel(&s, 0), [153, 51, 77, 255]), "{:?}", pixel(&s, 0)); + run(&mut s, "element.set_color_effect", json!({"style": "advanced", "red_multiplier": -100, "red_offset": 255, "green_multiplier": 50, "blue_offset": -100})); + // The tint carried over into Advanced (×50 %, +127.5 red), then these channels changed. + let fx = effect(&s).transform(); + assert_eq!((fx.mul[0], fx.add[0], fx.mul[1], fx.add[2]), (-1.0, 1.0, 0.5, -100.0 / 255.0)); + assert!(near(pixel(&s, 0), [204, 51, 0, 255]), "{:?}", pixel(&s, 0)); +} + +#[test] +fn a_change_on_a_mixed_selection_sets_only_that_value() { + let mut s = Session::default(); + let a = run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + let b = run(&mut s, "draw.rect", json!({"x": 20, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "element.select", json!({"ids": [a]})); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + run(&mut s, "element.select", json!({"ids": [b]})); + run(&mut s, "element.set_color_effect", json!({"tint": "#0000ff", "tint_amount": 10})); + run(&mut s, "element.select", json!({"ids": [a, b]})); + run(&mut s, "element.set_color_effect", json!({"tint_amount": 80})); + let fx: Vec = s.visible_elements().iter().map(|e| e.color).collect(); + assert_eq!(fx, [ColorEffect::Tint { color: Rgba::hex(0xff0000), amount: 0.8 }, ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.8 }], "each keeps its colour"); + // One undo step puts both back. + s.undo().unwrap(); + assert_eq!(s.visible_elements()[1].color, ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.1 }); +} + +#[test] +fn set_alpha_keeps_the_rest_of_the_effect() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": 20})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + assert_eq!(effect(&s).transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::brightness(0.2))); + run(&mut s, "element.set_color_effect", json!({"style": "none"})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + assert_eq!(effect(&s), ColorEffect::Alpha(0.5)); +} + +#[test] +fn a_classic_tween_between_styles_travels_in_the_advanced_space() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 100})); + 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.set_color_effect", json!({"alpha": 50})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + s.set_frame(5); + let mid = effect(&s); + assert_eq!(mid.style(), ColorStyle::Advanced); + let want = ColorTransform::tint(Rgba::hex(0xff0000), 1.0).lerp(&ColorTransform::alpha(0.5), 0.5); + let got = mid.transform(); + assert!(got.mul.iter().zip(want.mul).chain(got.add.iter().zip(want.add)).all(|(a, b)| (a - b).abs() < 1e-5), "{got:?} vs {want:?}"); + // Within one style the value itself travels: brightness −100 % to +100 % is 0 halfway. + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"brightness": -100})); + 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.set_color_effect", json!({"brightness": 100})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Brightness(0.0)); + assert!(near(pixel(&s, 5), [51, 102, 153, 255])); +} + +#[test] +fn motion_tweens_key_brightness_tint_and_advanced() { + let mut s = square(); + run(&mut s, "timeline.create_motion_tween", json!({})); + run(&mut s, "motion.set_key", json!({"property": "brightness", "frame": 10, "value": 60})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Brightness(0.3)); + // A second style composes with the first into Advanced, exactly. + run(&mut s, "motion.set_key", json!({"property": "tint", "frame": 10, "value": 50})); + run(&mut s, "motion.set_key", json!({"property": "tint_red", "frame": 0, "value": 255})); + run(&mut s, "motion.set_key", json!({"property": "tint_green", "frame": 0, "value": 0})); + run(&mut s, "motion.set_key", json!({"property": "tint_blue", "frame": 0, "value": 0})); + s.set_frame(10); + let want = ColorTransform::brightness(0.6).concat(&ColorTransform::tint(Rgba::hex(0xff0000), 0.5)); + assert_eq!(effect(&s).transform(), want); + // Advanced channels on their own curves. + let mut s = square(); + run(&mut s, "timeline.create_motion_tween", json!({})); + run(&mut s, "motion.set_key", json!({"property": "red_offset", "frame": 10, "value": 255})); + run(&mut s, "motion.set_key", json!({"property": "alpha_multiplier", "frame": 10, "value": 0})); + s.set_frame(5); + let fx = effect(&s); + assert_eq!(fx.style(), ColorStyle::Advanced); + assert_eq!(fx.transform(), ColorTransform { mul: [1.0, 1.0, 1.0, 0.5], add: [0.5, 0.0, 0.0, 0.0] }); + assert!(s.execute("motion.set_key", &json!({"property": "red_offset", "frame": 3, "value": 256})).is_err()); + // Info lists the keys by their names. + let info = run(&mut s, "motion.info", json!({})); + assert!(info.to_string().contains("red_offset"), "{info}"); +} + +#[test] +fn a_motion_tween_has_one_colour_effect_style() { + let mut s = square(); + run(&mut s, "element.set_color_effect", json!({"tint": "#00ff00", "tint_amount": 40})); + run(&mut s, "timeline.create_motion_tween", json!({})); + // Untracked, the target's own tint shows all along. + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Tint { color: Rgba::hex(0x00ff00), amount: 0.4 }); + // Keying alpha makes it an alpha tween, as in Animate. + run(&mut s, "motion.set_key", json!({"property": "alpha", "frame": 10, "value": 0})); + s.set_frame(5); + assert_eq!(effect(&s), ColorEffect::Alpha(0.5)); + // Changing the alpha in Properties inside the span keys it there. + s.set_frame(4); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.set_color_effect", json!({"alpha": 90})); + s.set_frame(4); + assert!((effect(&s).alpha() - 0.9).abs() < 1e-4, "{:?}", effect(&s)); + assert!(layer_motion_has(&s, Property::Alpha) && !layer_motion_has(&s, Property::Tint)); + // Keying tint as well composes the two (older files keyed both); the tint colour is the + // target's own. + run(&mut s, "motion.set_key", json!({"property": "tint", "frame": 10, "value": 50})); + s.set_frame(10); + assert_eq!(effect(&s).transform(), ColorTransform::alpha(0.0).concat(&ColorTransform::tint(Rgba::hex(0x00ff00), 0.5)), "the tint keys start from the target's own colour"); +} + +fn layer_motion_has(s: &Session, p: Property) -> bool { + s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.as_ref()).is_some_and(|m| m.track(p).is_some()) +} + +#[test] +fn files_keep_every_style() { + let mut s = Session::default(); + for (i, p) in [json!({"brightness": -30}), json!({"tint": "#123456", "tint_amount": 0}), json!({"style": "advanced", "blue_multiplier": -40, "green_offset": 12}), json!({"alpha": 100})].into_iter().enumerate() { + let id = run(&mut s, "draw.rect", json!({"x": i * 20, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "element.select", json!({"ids": [id]})); + run(&mut s, "element.set_color_effect", p); + } + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + let styles: Vec = back.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| e.color.style()).collect(); + assert_eq!(styles, [ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha]); +} + +#[test] +fn plug_ins_may_set_colour_effects() { + assert!(crate::cmds_plugin::plugin_may_call("element.set_color_effect").is_ok()); +} + +#[test] +fn a_nine_slice_instance_takes_its_colour_effect() { + // ADR 0055 with ADR 0056: the slices are geometry; the colour effect applies to all of them. + let mut s = square(); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Panel"})); + run(&mut s, "symbol.set_scale_grid", json!({"on": true, "left": 5, "right": 15, "top": 5, "bottom": 15})); + run(&mut s, "element.set_transform", json!({"sx": 3.0, "sy": 3.0})); + run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50})); + let dl = anicraft_doc::evaluate(&s.doc, 0); + assert!(!dl.items.is_empty()); + let want = ColorTransform::tint(Rgba::hex(0xff0000), 0.5); + assert!(dl.items.iter().all(|i| i.color == want), "every slice is tinted"); +} diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 138d0fa0..f39c0c73 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -38,9 +38,13 @@ fn plural(n: usize, word: &str) -> String { if n == 1 { format!("1 {word}") } else { format!("{n} {word}s") } } +fn swatches(n: usize) -> String { + if n == 1 { "1 swatch".into() } else { format!("{n} swatches") } +} + fn target_layer<'a>(s: &'a Session, p: &Value) -> Option<&'a Layer> { let id = p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId); - s.doc.timeline(s.scene).layer(id) + s.timeline().layer(id) } fn target_frame(s: &Session, p: &Value) -> u32 { @@ -59,7 +63,7 @@ fn lost_keys(s: &Session, p: &Value, hit: impl Fn(&Keyframe) -> bool) -> Vec<(St None => vec![p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId)], }; ids.iter() - .filter_map(|id| s.doc.timeline(s.scene).layer(*id)) + .filter_map(|id| s.timeline().layer(*id)) .flat_map(|l| l.keyframes.iter().filter(|k| !k.elements.is_empty() && hit(k)).map(|k| (l.name.clone(), k.elements.len()))) .collect() } @@ -98,7 +102,108 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: true, }) } - "file.new" | "file.new_sample" | "file.open" | "file.recover" if s.is_dirty() => Some(Confirmation { + "file.save_as_template" => { + let path = crate::cmds_template::target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Saving the template")) + } + "file.delete_template" => { + let path = crate::cmds_template::target(p).ok()?; + let name = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + Some(Confirmation { + title: "Delete template?".into(), + message: format!("The template “{name}” and its picture will be deleted from your templates. This cannot be undone."), + action: "Delete Template".into(), + irreversible: true, + }) + } + // Saved commands are files in your preferences (ADR 0097). + "macro.save" => { + let path = crate::cmds_macro::target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Saving the command")) + } + "macro.import" => { + let path = crate::cmds_macro::import_target(p).ok()?; + crate::vfs::exists(&path).then(|| overwrite(&path, "Adding the command")) + } + "macro.delete" => { + let path = crate::cmds_macro::target(p).ok()?; + let name = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + crate::vfs::is_file(&path).then(|| Confirmation { + title: "Delete saved command?".into(), + message: format!("The saved command “{name}” will be deleted from your commands. This cannot be undone."), + action: "Delete Command".into(), + irreversible: true, + }) + } + // Brushes of your own live in your preferences, outside undo (ADR 0068). + "brush.preset_delete" => { + let name = p.get("name").and_then(Value::as_str)?; + let i = s.brushes.position(name)?; + let name = s.brushes.user().get(i)?.name.clone(); + Some(Confirmation { + title: "Delete brush?".into(), + message: format!("The brush “{name}” will be deleted from your brushes. This cannot be undone."), + action: "Delete Brush".into(), + irreversible: true, + }) + } + // Swatches are document data and undoable (ADR 0078): replacing many asks by default. + "swatch.export" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + crate::vfs::exists(path).then(|| overwrite(path, "Exporting the swatches")) + } + "swatch.clear" => { + let n = s.doc.swatches.len(); + (n > 2).then(|| Confirmation { + title: "Clear swatches?".into(), + message: format!("{} will be removed, leaving black and white. You can undo this.", swatches(n)), + action: "Clear Swatches".into(), + irreversible: false, + }) + } + "swatch.reset" => { + let custom = !anicraft_doc::swatch::is_default_set(&s.doc.swatches) && !s.doc.swatches.is_empty(); + custom.then(|| Confirmation { + title: "Load the default swatches?".into(), + message: "The document's swatches will be replaced with a new document's set. You can undo this.".into(), + action: "Load Default Swatches".into(), + irreversible: false, + }) + } + "swatch.import" if p.get("replace").and_then(Value::as_bool) == Some(true) && !s.doc.swatches.is_empty() => Some(Confirmation { + title: "Replace swatches?".into(), + message: format!("The document's {} will be replaced with the file's. You can undo this.", swatches(s.doc.swatches.len())), + action: "Replace Swatches".into(), + irreversible: false, + }), + // Filter presets live in your preferences, outside undo (ADR 0091). + "filter.preset_delete" => { + let name = s.filter_presets.find(p.get("name").and_then(Value::as_str)?)?.name.clone(); + Some(Confirmation { + title: "Delete filter preset?".into(), + message: format!("The filter preset “{name}” will be deleted from your presets. Artwork that uses its filters keeps them. This cannot be undone."), + action: "Delete Preset".into(), + irreversible: true, + }) + } + "filter.preset_save" => { + let name = s.filter_presets.find(p.get("name").and_then(Value::as_str)?)?.name.clone(); + Some(Confirmation { + title: "Replace filter preset?".into(), + message: format!("You already have a filter preset named “{name}”. Saving replaces its filters. This cannot be undone."), + action: "Replace".into(), + irreversible: true, + }) + } + "filter.preset_export" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + crate::vfs::exists(path).then(|| overwrite(path, "Exporting the filter presets")) + } + "brush.preset_export" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + crate::vfs::exists(path).then(|| overwrite(path, "Exporting the brushes")) + } + "file.new" | "file.new_sample" | "file.new_from_template" | "file.open" | "file.open_recent" | "file.recover" if s.is_dirty() => Some(Confirmation { title: "Discard unsaved changes?".into(), message: format!("“{}” has changes that are not saved. They will be lost, and its undo history is cleared.", doc_name(s)), action: "Discard Changes".into(), @@ -109,10 +214,28 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { let same = s.path.as_deref() == Some(path); (!same && crate::vfs::exists(path)).then(|| overwrite(path, "Saving")) } - "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => { + "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" | "file.export_plugin" => { let path = Path::new(p.get("path").and_then(Value::as_str)?); crate::vfs::exists(path).then(|| overwrite(path, "Exporting")) } + "file.publish" => { + // Publishing replaces what is already there; what this session published itself + // it replaces without asking again (ADR 0060). + let found = crate::publish::existing(s, &crate::publish::planned(s, p)?); + let names: Vec = found.iter().take(3).map(|f| f.display().to_string()).collect(); + let more = found.len().saturating_sub(names.len()); + (!found.is_empty()).then(|| Confirmation { + title: if found.len() == 1 { "Replace published file?".into() } else { "Replace published files?".into() }, + message: format!( + "Publishing replaces {} already there: {}{}. This cannot be undone.", + if found.len() == 1 { "a file".to_string() } else { plural(found.len(), "file") }, + names.join(", "), + if more > 0 { format!(" and {more} more") } else { String::new() } + ), + action: "Publish".into(), + irreversible: true, + }) + } "file.export_sprite_sheet" => { // The sheet and its frame map: either one already there is replaced. let path = Path::new(p.get("path").and_then(Value::as_str)?); @@ -144,6 +267,63 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: false, }) } + "find.replace" => { + // Replace All over many places asks first (ADR 0058); one undo step takes it back. + let n = crate::find::replace_count(s, p)?; + (n > crate::find::REPLACE_ASK).then(|| Confirmation { + title: "Replace all?".into(), + message: format!("This replaces what was found in {}. You can undo this in one step.", plural(n, "place")), + action: "Replace All".into(), + irreversible: false, + }) + } + "library.delete" => { + // Routine when nothing deleted is in use and no folder holds anything (undo is there); + // asks when instances go with it or a folder takes its contents (ADR 0050). + let list = crate::cmds_library::entries_of(s, p, "items").ok()?; + let (items, folders) = crate::cmds_library::deletion(s, &list); + let uses = s.doc.library_uses(); + let used: Vec<&anicraft_doc::LibraryItem> = items.iter().filter(|i| uses.get(i).is_some_and(|n| *n > 0)).collect(); + let n_uses: usize = used.iter().filter_map(|i| uses.get(*i)).sum(); + let inside = items.len() + folders.len() - list.len(); + if used.is_empty() && inside == 0 { + return None; + } + let what = match list.as_slice() { + [one] => format!("“{}”", s.doc.entry_name(*one).unwrap_or("")), + _ => plural(list.len(), "item"), + }; + let mut parts = Vec::new(); + if inside > 0 { + parts.push(format!("{what} {} {}, deleted with {}.", if list.len() == 1 { "holds" } else { "hold" }, plural(inside, "item"), if list.len() == 1 { "it" } else { "them" })); + } + if !used.is_empty() { + parts.push(format!("{} used {} in the movie; {} go too.", if used.len() == 1 { "One of them is".to_string() } else { format!("{} of them are", used.len()) }, plural(n_uses, "time"), if n_uses == 1 { "that use" } else { "those uses" })); + } + parts.push("You can undo this.".into()); + Some(Confirmation { + title: if inside > 0 && list.len() == 1 { "Delete folder?".into() } else { "Delete from Library?".into() }, + message: parts.join(" "), + action: "Delete".into(), + irreversible: false, + }) + } + "library.delete_unused" => { + let unused = s.doc.unused_items(); + let names: Vec = unused.iter().take(5).filter_map(|i| s.doc.item_name(*i)).map(|n| format!("“{n}”")).collect(); + let more = unused.len().saturating_sub(names.len()); + (!unused.is_empty()).then(|| Confirmation { + title: "Delete unused items?".into(), + message: format!( + "Nothing in the movie uses {}: {}{}. They leave the Library. You can undo this.", + if unused.len() == 1 { "this item".to_string() } else { format!("these {} items", unused.len()) }, + names.join(", "), + if more > 0 { format!(" and {more} more") } else { String::new() } + ), + action: "Delete Unused".into(), + irreversible: false, + }) + } "draw.erase_all" => { // Double-clicking the Eraser: everything on the stage at this frame (ADR 0034). let layers = crate::cmds_erase::erasable_layers(s); @@ -155,11 +335,11 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: false, }) } - "camera.remove" => camera_removal(s, s.doc.timeline(s.scene).camera_layer()?), + "camera.remove" => camera_removal(s, s.timeline().camera_layer()?), "bone.remove" => { // The bone's moves in every pose go with it (ADR 0043); one pose loses nothing. let id = anicraft_doc::BoneId(p.get("bone").and_then(Value::as_u64)?); - let l = s.doc.timeline(s.scene).layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?; + let l = s.timeline().layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?; let arm = l.armature.as_deref()?; let n = crate::cmds_bone::poses(l); let below = arm.subtree(id).len().saturating_sub(1); @@ -184,7 +364,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { } if l.kind == anicraft_doc::LayerKind::Folder { // A folder goes with everything in it. - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|x| x.id == l.id)?; let inner = tl.layers.get(tl.group_range(i))?; let n = inner.len().saturating_sub(1); diff --git a/crates/engine/src/desktop_tests.rs b/crates/engine/src/desktop_tests.rs new file mode 100644 index 00000000..c4831b04 --- /dev/null +++ b/crates/engine/src/desktop_tests.rs @@ -0,0 +1,161 @@ +//! AppImage desktop integration (ADR 0094): the desktop entry and MIME files it writes, quoting +//! of awkward paths, idempotent install and remove, and what it refuses. + +use super::*; +use crate::cmds_desktop::{APP_ID, MARKER_KEY, desktop_entry, entry_appimage, exec_argument, install, owned_files, read_status, uninstall}; +use serde_json::json; +use std::path::{Path, PathBuf}; + +/// A fresh folder with a fake AppImage in a folder whose name has a space, and a data folder. +fn setup(tag: &str) -> (PathBuf, PathBuf, PathBuf) { + let root = std::env::temp_dir().join(format!("anicraft-desktop-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let apps = root.join("My Apps"); + std::fs::create_dir_all(&apps).unwrap(); + let appimage = apps.join("AniCraft-0.1.0-x86_64.AppImage"); + std::fs::write(&appimage, b"\x7fELF fake").unwrap(); + let data = root.join("share"); + (root, appimage, data) +} + +fn value<'a>(entry: &'a str, key: &str) -> Option<&'a str> { + entry.lines().find_map(|l| l.strip_prefix(&format!("{key}="))) +} + +#[test] +fn the_entry_starts_the_appimage_and_keeps_the_packaged_fields() { + let entry = desktop_entry(Path::new("/home/ana/Apps/AniCraft.AppImage")).unwrap(); + assert!(entry.contains("[Desktop Entry]\n")); + assert_eq!(value(&entry, "Exec"), Some("\"/home/ana/Apps/AniCraft.AppImage\" %f")); + assert_eq!(value(&entry, "TryExec"), Some("/home/ana/Apps/AniCraft.AppImage")); + assert_eq!(value(&entry, MARKER_KEY), Some("/home/ana/Apps/AniCraft.AppImage")); + // Everything else is the packaged entry, so menus, docks and file types match the packages. + for key in ["Type", "Name", "Icon", "StartupWMClass", "Categories", "MimeType", "Terminal"] { + let packaged = include_str!("../../../packaging/linux/ai.storyteller.anicraft.desktop"); + assert_eq!(value(&entry, key), value(packaged, key), "{key}"); + } + assert_eq!(value(&entry, "Icon"), Some(APP_ID)); + assert_eq!(value(&entry, "MimeType"), Some("application/x-anicraft;application/x-fla;application/x-xfl;")); + assert_eq!(entry.matches("Exec=").count(), 2, "one Exec and one TryExec"); +} + +#[test] +fn awkward_paths_are_quoted_as_the_desktop_entry_spec_says() { + // Spaces and quotes go inside double quotes; ", `, $ and \ are escaped there; % is doubled; + // then the value's own backslashes are doubled. + assert_eq!(exec_argument("/home/a b/x.AppImage"), r#""/home/a b/x.AppImage""#); + assert_eq!(exec_argument(r#"/o'k/"q"/$HOME/`x`/100%"#), r#""/o'k/\\"q\\"/\\$HOME/\\`x\\`/100%%""#); + assert_eq!(exec_argument(r"/back\slash"), r#""/back\\\\slash""#); + // The marker reads back exactly, whatever the path. + for p in ["/home/a b/Ani Craft.AppImage", r"/weird\name/$x%.AppImage", "/ünï/çødé/日本.AppImage"] { + assert_eq!(entry_appimage(&desktop_entry(Path::new(p)).unwrap()), Some(PathBuf::from(p)), "{p}"); + } + // Line breaks, relative paths and nothing at all can't be in a desktop entry. + for bad in ["/a\nExec=evil", "relative/x.AppImage", ""] { + assert!(desktop_entry(Path::new(bad)).is_err(), "{bad:?}"); + } +} + +#[test] +fn install_writes_the_entry_mime_types_and_icons_and_is_idempotent() { + let (root, appimage, data) = setup("install"); + let r = install(&appimage, &data).unwrap(); + assert_eq!(r.written.len(), owned_files().len()); + assert!(r.unchanged.is_empty()); + let entry = std::fs::read_to_string(data.join("applications").join(format!("{APP_ID}.desktop"))).unwrap(); + assert_eq!(entry_appimage(&entry).as_deref(), Some(appimage.as_path())); + let mime = std::fs::read_to_string(data.join("mime/packages").join(format!("{APP_ID}.xml"))).unwrap(); + for ty in ["application/x-anicraft", "application/x-fla", "application/x-xfl"] { + assert!(mime.contains(&format!("")), "{ty}"); + } + for size in ["16x16", "48x48", "256x256"] { + let icon = std::fs::read(data.join("icons/hicolor").join(size).join("apps").join(format!("{APP_ID}.png"))).unwrap(); + assert_eq!(&icon[..8], b"\x89PNG\r\n\x1a\n", "{size}"); + } + assert!(data.join("icons/hicolor/scalable/apps").join(format!("{APP_ID}.svg")).is_file()); + // Again: nothing changes. + let again = install(&appimage, &data).unwrap(); + assert!(again.written.is_empty()); + assert_eq!(again.unchanged.len(), owned_files().len()); + // Moved to another folder: only the entry is rewritten. + let moved = root.join("AniCraft.AppImage"); + std::fs::copy(&appimage, &moved).unwrap(); + let r = install(&moved, &data).unwrap(); + assert_eq!(r.written.len(), 1); + assert_eq!(read_status(&data).appimage.as_deref(), Some(moved.as_path())); + // No temporary files left behind. + let mut stray = Vec::new(); + for rel in owned_files() { + let dir = data.join(rel).parent().unwrap().to_path_buf(); + stray.extend(std::fs::read_dir(dir).unwrap().flatten().filter(|e| e.file_name().to_string_lossy().ends_with(".anicraft-tmp")).map(|e| e.path())); + } + assert!(stray.is_empty(), "{stray:?}"); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn remove_deletes_exactly_what_install_wrote_and_is_idempotent() { + let (root, appimage, data) = setup("remove"); + // Someone else's files beside ours stay. + let other = data.join("applications").join("org.example.other.desktop"); + std::fs::create_dir_all(other.parent().unwrap()).unwrap(); + std::fs::write(&other, "[Desktop Entry]\nName=Other\n").unwrap(); + install(&appimage, &data).unwrap(); + let removed = uninstall(&data).unwrap(); + assert_eq!(removed.len(), owned_files().len()); + for rel in owned_files() { + assert!(!data.join(rel).exists()); + } + assert!(other.is_file()); + assert_eq!(read_status(&data), Default::default()); + // Again: nothing to do, and no error. + assert!(uninstall(&data).unwrap().is_empty()); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn an_entry_anicraft_did_not_write_is_never_replaced_or_removed() { + let (root, appimage, data) = setup("foreign"); + let entry = data.join("applications").join(format!("{APP_ID}.desktop")); + std::fs::create_dir_all(entry.parent().unwrap()).unwrap(); + std::fs::write(&entry, "[Desktop Entry]\nName=My own AniCraft\nExec=/opt/mine/anicraft\n").unwrap(); + assert!(install(&appimage, &data).is_err()); + assert!(uninstall(&data).is_err()); + assert!(std::fs::read_to_string(&entry).unwrap().contains("My own AniCraft")); + assert!(read_status(&data).foreign); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn system_folders_and_missing_appimages_are_refused() { + let (root, appimage, data) = setup("refuse"); + for system in ["/usr/share", "/usr/local/share", "/etc/xdg", "/opt", "/", "/var/lib/flatpak/exports/share", "/var/lib/snapd/desktop"] { + assert!(install(&appimage, Path::new(system)).is_err(), "{system}"); + assert!(uninstall(Path::new(system)).is_err(), "{system}"); + } + assert!(install(&root.join("gone.AppImage"), &data).is_err()); + assert!(install(&appimage, Path::new("relative/share")).is_err()); + assert!(!data.exists(), "nothing was written"); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn the_commands_add_report_and_remove() { + let (root, appimage, data) = setup("commands"); + let mut s = Session::default(); + let (a, d) = (appimage.display().to_string(), data.display().to_string()); + let st = s.execute("desktop.status", &json!({"data_home": d, "appimage": a})).unwrap(); + assert_eq!((st["added"].as_bool(), st["this_copy"].as_bool()), (Some(false), Some(false))); + let r = s.execute("desktop.integrate", &json!({"appimage": a, "data_home": d, "refresh": false})).unwrap(); + assert_eq!(r["written"].as_array().map(Vec::len), Some(owned_files().len())); + let st = s.execute("desktop.status", &json!({"data_home": d, "appimage": a})).unwrap(); + assert_eq!((st["added"].as_bool(), st["this_copy"].as_bool(), st["target_exists"].as_bool()), (Some(true), Some(true), Some(true))); + assert!(!s.is_dirty(), "the document is untouched"); + let r = s.execute("desktop.remove", &json!({"data_home": d, "refresh": false})).unwrap(); + assert_eq!(r["removed"].as_array().map(Vec::len), Some(owned_files().len())); + for bad in [json!({}), json!({"appimage": a}), json!({"data_home": ""}), json!({"appimage": "", "data_home": d}), json!({"appimage": 3, "data_home": d})] { + assert!(s.execute("desktop.integrate", &bad).is_err(), "{bad}"); + } + assert!(crate::cmds_plugin::plugin_may_call("desktop.integrate").is_err()); + let _ = std::fs::remove_dir_all(root); +} diff --git a/crates/engine/src/drop_tests.rs b/crates/engine/src/drop_tests.rs new file mode 100644 index 00000000..8f5b9d68 --- /dev/null +++ b/crates/engine/src/drop_tests.rs @@ -0,0 +1,224 @@ +//! Files dropped onto the window and recent files (ADR 0059): routing by type and target, what +//! `file.drop` brings in and where, one undo step, and the recent list that opening and saving +//! keep. + +use super::*; +use crate::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; +use serde_json::json; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-drop-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A 4 × 2 PNG, a one-rectangle SVG and a short WAV in `dir`. +fn media(dir: &Path) -> (String, String, String) { + let png = dir.join("photo.png"); + std::fs::write(&png, anicraft_render::encode_png(4, 2, &[255u8; 4 * 2 * 4]).unwrap()).unwrap(); + let svg = dir.join("badge.svg"); + std::fs::write(&svg, r##""##).unwrap(); + let wav = dir.join("beep.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &[0.25; 4000])).unwrap(); + (png.display().to_string(), svg.display().to_string(), wav.display().to_string()) +} + +#[test] +fn drops_route_by_file_type_and_target() { + use DropAction::*; + use DropTarget::*; + let k = |p: &str| kind_of(Path::new(p)); + assert_eq!(k("a.anicraft"), DropKind::Document); + assert_eq!(k("A.FLA"), DropKind::Document); + assert_eq!(k("b.xfl"), DropKind::Document); + assert_eq!(k("c.svg"), DropKind::Drawing); + assert_eq!(k("d.JPEG"), DropKind::Image); + assert_eq!(k("d.jpg"), DropKind::Image); + assert_eq!(k("e.png"), DropKind::Image); + assert_eq!(k("f.mp3"), DropKind::Sound); + assert_eq!(k("g.ogg"), DropKind::Sound); + assert_eq!(k("h.wav"), DropKind::Sound); + assert_eq!(k("i.psd"), DropKind::Unsupported); + assert_eq!(k("no extension"), DropKind::Unsupported); + // An XFL package is a folder with a DOMDocument.xml. + let dir = temp_dir("xfl").join("Movie"); + std::fs::create_dir_all(&dir).unwrap(); + assert_eq!(kind_of(&dir), DropKind::Unsupported, "a plain folder"); + std::fs::write(dir.join("DOMDocument.xml"), "").unwrap(); + assert_eq!(kind_of(&dir), DropKind::Document); + // Documents open wherever they land; media go where they are dropped. + for t in [Stage, Library, Window] { + assert_eq!(route(DropKind::Document, t), Open); + assert!(matches!(route(DropKind::Unsupported, t), Refuse(_))); + } + for kind in [DropKind::Drawing, DropKind::Image, DropKind::Sound] { + assert_eq!(route(kind, Stage), ImportToStage); + assert!(matches!(route(kind, Window), Refuse(_)), "only the stage, the timeline and the Library take media"); + // The Library takes drawings too, as graphic symbols (ADR 0065); a layer's frame takes all. + assert_eq!(route(kind, Library), ImportToLibrary); + assert_eq!(route(kind, Timeline), ImportToTimeline); + } + assert!(matches!(route(DropKind::Unsupported, Timeline), Refuse(_))); + assert_eq!(route(DropKind::Document, Timeline), Open); +} + +#[test] +fn media_dropped_on_the_stage_land_on_the_active_layer_at_the_drop_point_in_one_step() { + let dir = temp_dir("stage"); + let (png, svg, wav) = media(&dir); + let mut s = Session::default(); + run(&mut s, "timeline.insert_frame", json!({"count": 20})); + s.set_frame(5); + let layers = s.timeline().layers.len(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png, svg, wav], "to": "stage", "x": 100, "y": 60})); + assert_eq!(s.history_len(), history + 1, "one undo step for the whole drop"); + assert_eq!(s.timeline().layers.len(), layers, "everything went onto the active layer"); + assert_eq!(v["elements"].as_array().map(Vec::len), Some(2), "{v}"); + assert_eq!(s.selection.len(), 2, "what was dropped is selected"); + // Centred on the drop point, in the keyframe that shows at the playhead. + let layer = s.active_layer().unwrap(); + let key = layer.keyframe_at(5).unwrap(); + assert!(s.selection.ids().all(|id| key.elements.iter().any(|e| e.id == id))); + for id in s.selection.ids().collect::>() { + let b = s.element_bounds(id); + assert!((b.center().x - 100.0).abs() < 0.01 && (b.center().y - 60.0).abs() < 0.01, "{b:?}"); + } + assert!(key.sound.is_some(), "the sound is on the keyframe at the playhead"); + assert_eq!((s.doc.bitmaps.len(), s.doc.sounds.len()), (1, 1), "the image and the sound are in the Library"); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.bitmaps.is_empty() && s.doc.sounds.is_empty() && s.active_layer().unwrap().keyframe_at(5).is_none_or(|k| k.elements.is_empty())); +} + +#[test] +fn media_dropped_on_the_library_go_into_the_folder_under_the_pointer() { + let dir = temp_dir("library"); + let (png, svg, wav) = media(&dir); + let mut s = Session::default(); + let folder = run(&mut s, "library.new_folder", json!({"name": "Props"}))["folder"].as_u64().unwrap(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png.clone(), wav], "to": "library", "folder": folder})); + assert_eq!(s.history_len(), history + 1); + assert_eq!(v["items"].as_array().map(Vec::len), Some(2)); + let in_folder = s.doc.folder_contents(anicraft_doc::FolderId(folder)); + assert_eq!(in_folder.len(), 2, "{in_folder:?}"); + assert!(s.timeline().layers.iter().all(|l| l.keyframes.iter().all(|k| k.elements.is_empty() && k.sound.is_none())), "nothing placed on the stage"); + // The same image again: numbered, not refused. + run(&mut s, "file.drop", json!({"path": png.clone(), "to": "library", "folder": folder})); + let names: Vec = s.doc.folder_contents(anicraft_doc::FolderId(folder)).into_iter().filter_map(|e| s.doc.entry_name(e).map(str::to_string)).collect(); + assert!(names.contains(&"photo.png".to_string()) && names.contains(&"photo.png 2".to_string()), "{names:?}"); + // At the top level without a folder. + run(&mut s, "file.drop", json!({"path": png, "to": "library"})); + assert_eq!(s.doc.bitmaps.len(), 3); + // A drawing goes in as one graphic symbol named after the file (ADR 0065), into the folder. + let symbols = s.doc.library.len(); + let v = run(&mut s, "file.drop", json!({"paths": [svg], "to": "library", "folder": folder})); + assert_eq!(s.doc.library.len(), symbols + 1, "{v}"); + let sym = s.doc.library.last().unwrap(); + assert_eq!((sym.name.as_str(), sym.kind), ("badge", anicraft_doc::SymbolKind::Graphic)); + assert!(s.doc.folder_contents(anicraft_doc::FolderId(folder)).contains(&anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Symbol(sym.id)))); + // Nothing is imported when one file is refused. + let before = s.doc.clone(); + assert!(s.execute("file.drop", &json!({"paths": [png.clone(), dir.join("notes.txt").display().to_string()], "to": "library"})).is_err()); + assert!(s.doc == before); +} + +#[test] +fn drawings_with_layers_keep_them_and_bad_drops_change_nothing() { + let dir = temp_dir("bad"); + let (png, _, _) = media(&dir); + let masked = dir.join("masked.svg"); + std::fs::write(&masked, r##""##).unwrap(); + let mut s = Session::default(); + let layers = s.timeline().layers.len(); + run(&mut s, "file.drop", json!({"path": masked.display().to_string(), "to": "stage", "x": 10, "y": 10})); + assert!(s.timeline().layers.len() > layers + 1, "a masked drawing brings its folder and mask layer"); + let before = s.doc.clone(); + let doc = dir.join("x.anicraft"); + for p in [ + json!({"path": doc.display().to_string(), "to": "stage"}), + json!({"path": dir.join("y.psd").display().to_string(), "to": "stage"}), + json!({"paths": [png.clone(), dir.join("gone.png").display().to_string()], "to": "stage"}), + json!({"path": png.clone(), "to": "timeline"}), + json!({"path": png.clone(), "to": "library", "folder": u64::MAX}), + json!({"path": png.clone(), "to": "stage", "folder": 1}), + json!({"path": png.clone(), "to": "stage", "x": f64::MAX, "y": 0}), + json!({"paths": [], "to": "stage"}), + json!({"paths": vec![png.clone(); 65], "to": "stage"}), + json!({"paths": "x", "to": "stage"}), + json!({"paths": [1, 2], "to": "library"}), + json!({"to": "stage"}), + json!({}), + Value::Null, + ] { + assert!(s.execute("file.drop", &p).is_err(), "{p}"); + assert!(s.doc == before, "{p} changed the document"); + } + // A locked layer refuses the drop and says why. + let top = s.timeline().layers.len() - 1; + run(&mut s, "layer.select", json!({"index": top})); + run(&mut s, "layer.toggle_lock", json!({})); + let e = s.execute("file.drop", &json!({"path": png, "to": "stage"})).unwrap_err(); + assert!(e.to_string().contains("locked"), "{e}"); +} + +#[test] +fn opening_and_saving_keep_the_recent_list_and_open_recent_reopens() { + let dir = temp_dir("recent"); + let a = dir.join("a.anicraft"); + let b = dir.join("b.anicraft"); + let mut s = Session::new(anicraft_doc::sample::demo()); + run(&mut s, "file.save_as", json!({"path": a.display().to_string()})); + run(&mut s, "file.new", json!({"width": 1280, "height": 720})); + run(&mut s, "file.save_as", json!({"path": b.display().to_string()})); + let list = run(&mut s, "file.recent_list", json!({})); + let names: Vec<&str> = list["files"].as_array().unwrap().iter().filter_map(|f| f["name"].as_str()).collect(); + assert_eq!(names, ["b.anicraft", "a.anicraft"], "most recent first; New doesn't clear it"); + // Open Recent by index opens it, and moves it to the top. + run(&mut s, "file.open_recent", json!({"index": 1})); + assert_eq!(s.path.as_deref(), Some(a.as_path())); + assert_eq!(s.doc.stage.width, anicraft_doc::sample::demo().stage.width); + assert_eq!(s.recent.entries().first().map(|e| e.path.clone()), Some(a.clone())); + // Over unsaved work it asks first, like Open. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + assert!(s.confirmation("file.open_recent", &json!({"index": 1})).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.open_recent", &json!({"index": 1})).is_err()); + run(&mut s, "file.open_recent", json!({"index": 1, "confirm": true})); + assert_eq!(s.path.as_deref(), Some(b.as_path())); + // A file that is gone stays listed, marked missing, and says so when opened. + std::fs::remove_file(&a).unwrap(); + let list = run(&mut s, "file.recent_list", json!({})); + let gone = list["files"].as_array().unwrap().iter().find(|f| f["name"] == "a.anicraft").unwrap(); + assert_eq!(gone["missing"], true); + let e = s.execute("file.open_recent", &json!({"path": a.display().to_string()})).unwrap_err(); + assert!(e.to_string().contains("no longer there"), "{e}"); + // Pin, remove, clear. + run(&mut s, "prefs.recent_pin", json!({"path": a.display().to_string()})); + assert!(s.recent.entries().first().is_some_and(|e| e.pinned)); + run(&mut s, "prefs.recent_clear", json!({})); + assert_eq!(s.recent.len(), 1, "the pinned file stays"); + run(&mut s, "prefs.recent_remove", json!({"index": 0})); + assert!(s.recent.is_empty()); + // Hostile params never panic and never change the list. + run(&mut s, "file.open", json!({"path": b.display().to_string()})); + let before = s.recent.clone(); + for id in ["file.open_recent", "prefs.recent_pin", "prefs.recent_remove"] { + for p in [json!({"index": u64::MAX}), json!({"index": -1}), json!({"path": ""}), json!({"index": 0, "path": "x"}), json!({"pinned": "x"}), json!("x"), Value::Null] { + let _ = s.execute(id, &p); + assert_eq!(s.recent, before, "{id} {p}"); + } + } + // Restored autosaves and untitled opens aren't recent files. + let mut t = Session::default(); + run(&mut t, "file.open", json!({"path": b.display().to_string(), "unsaved": true})); + run(&mut t, "file.open", json!({"path": b.display().to_string(), "untitled": true, "confirm": true})); + assert!(t.recent.is_empty()); +} diff --git a/crates/engine/src/ease_tests.rs b/crates/engine/src/ease_tests.rs new file mode 100644 index 00000000..ed7c6dcb --- /dev/null +++ b/crates/engine/src/ease_tests.rs @@ -0,0 +1,231 @@ +//! Eases through the command registry (ADR 0081): presets by name, custom eases edited point by +//! point (one undo step per drag), saved eases on classic tweens and motion properties, copy +//! and paste, property groups, and the file round trip. + +use super::*; +use anicraft_doc::{CustomEase, EaseGroup, Easing, Property, TweenKind}; +use serde_json::json; + +pub(crate) fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A 10 × 10 square at the origin, tweened (classic) 100 to the right over ten frames. +pub(crate) fn tweened() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + 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": 100, "dy": 0})); + run(&mut s, "timeline.create_tween", json!({"frame": 0})); + s +} + +/// How far the square has moved at frame `f` (it starts centred on x = 5). +pub(crate) fn x_at(s: &mut Session, f: u32) -> f32 { + s.set_frame(f); + s.visible_elements().first().map(|e| e.transform.translation().x - 5.0).unwrap_or(f32::NAN) +} + +fn tween(s: &Session) -> anicraft_doc::Tween { + s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.tween.clone()).expect("a tween") +} + +#[test] +fn every_preset_applies_by_name_and_drives_the_tween() { + let mut s = tweened(); + for e in Easing::named() { + let name = e.name().unwrap(); + let v = run(&mut s, "timeline.set_easing", json!({"easing": name, "frame": 0})); + assert_eq!(v["easing"], e.label()); + assert_eq!(tween(&s).easing, e); + assert!((x_at(&mut s, 5) - 100.0 * e.apply(0.5)).abs() < 1e-3, "{name}"); + } + run(&mut s, "timeline.set_easing", json!({"easing": {"classic": 100}, "frame": 0})); + assert!((x_at(&mut s, 5) - 75.0).abs() < 1e-3); + // The list: every named preset and Classic Ease. + let l = run(&mut s, "ease.list", json!({})); + assert_eq!(l["presets"].as_array().unwrap().len(), 29); + assert!(s.execute("timeline.set_easing", &json!({"easing": "Wobbly"})).is_err()); +} + +#[test] +fn point_edits_shape_a_custom_ease_and_a_drag_is_one_undo_step() { + let mut s = tweened(); + // A point on the line keeps the motion as it was; the preset became a custom curve. + let v = run(&mut s, "ease.add_point", json!({"t": 0.5, "frame": 0})); + assert_eq!((v["index"].as_u64(), v["points"].as_u64()), (Some(1), Some(3))); + assert!(matches!(tween(&s).easing, Easing::Custom(_))); + assert!((x_at(&mut s, 3) - 30.0).abs() < 1e-2); + // Dragging it up and past its neighbour, as a gesture of many moves: one undo step. + let steps = s.history_len(); + s.begin_gesture("Ease point"); + for k in 0..=20 { + run(&mut s, "ease.move_point", json!({"index": 1, "x": 0.5 + k as f32 * 0.05, "y": 0.5 + k as f32 * 0.05, "frame": 0})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + let c = tween(&s).easing.custom().cloned().unwrap(); + assert_eq!(c.points()[1].at, anicraft_geom::Vec2::new(1.0, 1.5), "x stops at the end; y overshoots"); + assert!(x_at(&mut s, 9) > 100.0, "overshoots past the second keyframe"); + // Corner, smooth, handles, delete; the ends can't move or go. + run(&mut s, "ease.move_point", json!({"index": 1, "x": 0.4, "y": 1.2, "frame": 0})); + run(&mut s, "ease.convert_point", json!({"index": 1, "smooth": true, "frame": 0})); + run(&mut s, "ease.move_handle", json!({"index": 1, "handle": "out", "x": 0.6, "y": 1.4, "frame": 0})); + let p = tween(&s).easing.custom().unwrap().points()[1]; + assert!(p.smooth && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-4); + assert!(s.execute("ease.move_point", &json!({"index": 0, "x": 0.5, "y": 0.5, "frame": 0})).is_err()); + assert!(s.execute("ease.delete_point", &json!({"index": 2, "frame": 0})).is_err()); + assert!(s.execute("ease.move_handle", &json!({"index": 0, "handle": "in", "x": 0, "y": 0, "frame": 0})).is_err()); + run(&mut s, "ease.delete_point", json!({"index": 1, "frame": 0})); + assert_eq!(tween(&s).easing.custom().unwrap().points().len(), 2); + // Undo walks back through the edits. + s.undo().unwrap(); + assert_eq!(tween(&s).easing.custom().unwrap().points().len(), 3); + // Info gives the curve as points and the ease as params take it back. + let i = run(&mut s, "ease.info", json!({"frame": 0})); + assert_eq!(i["kind"], "custom"); + assert_eq!(i["points"].as_array().unwrap().len(), 3); + let back = run(&mut s, "timeline.set_easing", json!({"easing": i["easing"].clone(), "frame": 0})); + assert_eq!(back["easing"], "Custom"); +} + +#[test] +fn time_never_runs_backwards_after_any_command_edit() { + let mut s = tweened(); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 10_000) as f64 / 10_000.0 + }; + for _ in 0..400 { + let n = tween(&s).easing.to_custom().points().len() as f64; + let i = (rnd() * n) as u64; + let (x, y) = (rnd() * 1.6 - 0.3, rnd() * 30.0 - 15.0); + let (id, p) = match (rnd() * 5.0) as u32 { + 0 => ("ease.add_point", json!({"t": rnd(), "frame": 0})), + 1 => ("ease.move_point", json!({"index": i, "x": x, "y": y, "frame": 0})), + 2 => ("ease.move_handle", json!({"index": i, "handle": if rnd() > 0.5 { "in" } else { "out" }, "x": x, "y": y, "frame": 0})), + 3 => ("ease.convert_point", json!({"index": i, "smooth": rnd() > 0.5, "frame": 0})), + _ => ("ease.delete_point", json!({"index": i, "frame": 0})), + }; + let _ = s.execute(id, &p); + let c = tween(&s).easing.to_custom(); + for k in 0..c.points().len() - 1 { + let [a, b, cc, d] = c.segment(k).unwrap(); + assert!(a.x <= d.x && (a.x..=d.x).contains(&b.x) && (a.x..=d.x).contains(&cc.x), "{id} {p}: segment {k}"); + } + assert!((0..=10).all(|f| x_at(&mut s, f).is_finite())); + } +} + +#[test] +fn saved_eases_reach_classic_tweens_and_motion_properties() { + let mut s = tweened(); + run(&mut s, "ease.add_point", json!({"t": 0.3, "frame": 0})); + run(&mut s, "ease.move_point", json!({"index": 1, "x": 0.3, "y": 0.9, "frame": 0})); + let curve = tween(&s).easing.clone(); + run(&mut s, "ease.save", json!({"name": " Snap ", "frame": 0})); + assert_eq!(s.doc.eases.len(), 1); + assert_eq!(s.doc.eases[0].name, "Snap"); + assert!(s.execute("ease.save", &json!({"name": "snap", "easing": "QuadIn"})).is_err(), "a name is saved once (any case)"); + run(&mut s, "ease.save", json!({"name": "Bouncy", "easing": "BounceOut"})); + // Another tween takes it by name. + run(&mut s, "timeline.set_easing", json!({"easing": "Linear", "frame": 0})); + run(&mut s, "timeline.set_easing", json!({"easing": {"saved": "snap"}, "frame": 0})); + assert_eq!(tween(&s).easing, curve); + assert_eq!(cmds_ease::saved_name(&s.doc, &tween(&s).easing), Some("Snap")); + // A motion tween's property too. + let mut m = Session::default(); + m.doc.eases = s.doc.eases.clone(); + run(&mut m, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut m, "timeline.create_motion_tween", json!({})); + run(&mut m, "motion.set_key", json!({"property": "x", "frame": 20, "value": 205})); + run(&mut m, "motion.set_ease", json!({"property": "x", "frame": 3, "easing": {"saved": "Bouncy"}})); + let ease = m.active_layer().unwrap().keyframes[0].motion.as_ref().unwrap().track(Property::X).unwrap().keys[0].ease.clone(); + assert_eq!(ease, Easing::BounceOut); + // Point edits on a motion segment address it by property. + run(&mut m, "ease.add_point", json!({"property": "x", "frame": 3, "t": 0.5})); + assert!(matches!(m.active_layer().unwrap().keyframes[0].motion.as_ref().unwrap().track(Property::X).unwrap().keys[0].ease, Easing::Custom(_))); + // Edit the saved one directly, rename, delete: tweens keep their curves. + run(&mut s, "ease.set", json!({"saved": "Snap", "easing": "SineOut"})); + assert_eq!(s.doc.eases[0].ease, Easing::SineOut); + assert_eq!(tween(&s).easing, curve, "a tween keeps the curve it was given"); + run(&mut s, "ease.rename", json!({"name": "snap", "to": "Settle"})); + assert!(s.execute("ease.rename", &json!({"name": "Settle", "to": "bouncy"})).is_err()); + run(&mut s, "ease.delete", json!({"name": "SETTLE"})); + assert_eq!(s.doc.eases.iter().map(|e| e.name.as_str()).collect::>(), ["Bouncy"]); + assert!(s.execute("timeline.set_easing", &json!({"easing": {"saved": "Settle"}})).is_err()); + let l = run(&mut s, "ease.list", json!({})); + assert_eq!(l["saved"][0]["name"], "Bouncy"); +} + +#[test] +fn copy_and_paste_an_ease_between_tweens() { + let mut s = tweened(); + run(&mut s, "timeline.set_easing", json!({"easing": "BackOut", "frame": 0})); + assert!(s.execute("ease.paste", &json!({"frame": 0})).is_err(), "nothing copied yet"); + run(&mut s, "ease.copy", json!({"frame": 0})); + run(&mut s, "timeline.set_easing", json!({"easing": "Linear", "frame": 0})); + let steps = s.history_len(); + run(&mut s, "ease.paste", json!({"frame": 0, "group": "rotation"})); + assert_eq!(s.history_len(), steps + 1); + assert_eq!(tween(&s).ease(EaseGroup::Rotation), &Easing::BackOut); + // Copying doesn't change the document. + let steps = s.history_len(); + run(&mut s, "ease.copy", json!({"frame": 0})); + assert_eq!(s.history_len(), steps); +} + +#[test] +fn classic_tweens_ease_property_groups_separately() { + let mut s = tweened(); + run(&mut s, "timeline.set_easing", json!({"easing": "QuadIn", "group": "position", "frame": 0})); + assert!((x_at(&mut s, 5) - 25.0).abs() < 1e-3, "position eased in"); + assert_eq!(tween(&s).ease(EaseGroup::Scale), &Easing::Linear); + // Separate: every group gets the tween's ease (position keeps its own); one for all clears. + run(&mut s, "ease.separate", json!({"separate": true, "frame": 0})); + assert_eq!(tween(&s).groups.len(), 5); + assert_eq!(tween(&s).ease(EaseGroup::Position), &Easing::QuadIn); + run(&mut s, "ease.separate", json!({"separate": false, "frame": 0})); + assert!(tween(&s).groups.is_empty()); + assert!((x_at(&mut s, 5) - 50.0).abs() < 1e-3); + // Converting keeps groups on classic tweens; a shape tween has one ease. + run(&mut s, "timeline.set_easing", json!({"easing": "QuadIn", "group": "color", "frame": 0})); + run(&mut s, "timeline.create_shape_tween", json!({"frame": 0})); + assert!(tween(&s).groups.is_empty() && tween(&s).kind == TweenKind::Shape); + assert!(s.execute("timeline.set_easing", &json!({"easing": "QuadIn", "group": "color", "frame": 0})).is_err()); + assert!(s.execute("ease.separate", &json!({"separate": true, "frame": 0})).is_err()); + assert!(s.execute("timeline.set_easing", &json!({"easing": "QuadIn", "group": "sparkle", "frame": 0})).is_err()); +} + +#[test] +fn eases_survive_the_file_round_trip() { + let mut s = tweened(); + run(&mut s, "timeline.set_easing", json!({"easing": {"custom": [[0, 0], [0.2, 1.4], [0.3, 1.4], [0.4, 1.4], [0.6, 0.8], [0.8, 1], [1, 1]]}, "frame": 0})); + run(&mut s, "timeline.set_easing", json!({"easing": "ElasticOut", "group": "rotation", "frame": 0})); + run(&mut s, "ease.save", json!({"name": "Wave", "frame": 0})); + run(&mut s, "ease.save", json!({"name": "Classic 40", "easing": {"classic": 40}})); + let text = format::to_json(&s.doc).expect("save"); + let back = format::from_json(&text).expect("load"); + assert_eq!(back, s.doc); + assert_eq!(back.eases.len(), 2); + let t = back.timeline(0).layers[0].keyframes[0].tween.clone().unwrap(); + assert!(matches!(&t.easing, Easing::Custom(c) if c.points().len() == 3)); + assert_eq!(t.ease(EaseGroup::Rotation), &Easing::ElasticOut); + // A file from before saved eases and custom curves opens unchanged. + let old = text.replace("\"eases\":", "\"ignored_eases\":"); + assert!(format::from_json(&old).expect("older file").eases.is_empty()); + // A hostile curve in a file is repaired on load, never refused: reversed, out of range. + let bad = r#"{"Custom": {"points": [{"at": {"x": 2, "y": 99}}, {"at": {"x": 0.5, "y": -40}, "in": {"x": 5, "y": 0}}, {"at": {"x": -1, "y": 0}}]}}"#; + let e: Easing = serde_json::from_str(bad).unwrap(); + let c = e.custom().unwrap(); + assert_eq!((c.points().len(), c.points()[1].at.y, c.points()[1].h_in.x), (3, -anicraft_doc::MAX_EASE_Y, 0.0)); + let _ = CustomEase::linear(); +} diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs new file mode 100644 index 00000000..5024ceb3 --- /dev/null +++ b/crates/engine/src/editing.rs @@ -0,0 +1,624 @@ +//! Editing a symbol's timeline in place (ADR 0045), as Animate's double-click on an instance does. +//! +//! The session keeps a stack of open symbols. While one is open, every command works on its +//! timeline instead of the scene's ([`Session::timeline`]): its layers are the active layers, the +//! playhead is its playhead, and positions are in its own space. So drawing, merge drawing (ADR +//! 0031), the Selection tool (ADR 0041) and Subselection (ADR 0042) behave inside a symbol exactly +//! as on the stage: they are the same commands on another timeline. Which symbol is open is view +//! state, but undo snapshots keep it, so an undo goes back to where its change was made. +//! +//! The stage draws [`Session::stage_picture`]: the open symbol where its instance stands, over the +//! timelines it sits in, dimmed. + +use crate::history::StateId; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Selection, Session}; +use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_geom::{Affine, Vec2}; +use serde_json::{Value, json}; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "symbol.edit", + "Edit Symbols", + "Edit", + Some("Ctrl+E"), + "{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. A group (ADR 0073) or a drawing object (ADR 0080) opens in place the same way: inside, its raw shapes merge only with each other, and a drawing object closes as one object again (a group of its pieces when an edit left several). Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)", + false, + edit as crate::RunFn, + ), + c("symbol.exit", "Edit Document", "Edit", None, "{all?: bool} closes the open symbol (default: one level; all: back to the scene), selecting the instance it was opened from", false, exit), + ] +} + +/// Most symbols open inside each other at once. +const MAX_LEVELS: usize = 32; +/// How much the artwork around an open symbol shows (Animate dims it). +const DIM: f32 = 0.35; + +/// What a level of the editing stack has open. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Opened { + /// A symbol's timeline (ADR 0045). + Symbol(SymbolId), + /// A group's members (ADR 0073): the group is [`EditLevel::instance`] on the timeline below, + /// on the keyframe at [`EditLevel::frame`]. + Group, + /// A drawing object opened in place (ADR 0080): while it is open it is a group of its raw + /// shapes, as [`Opened::Group`]; closing it makes it one drawing object again when it holds + /// one shape (a group of its pieces when it holds several, as Combine Objects' Union). + Drawing, +} + +impl Opened { + /// Whether this level opens a group's members (a group, or a drawing object being edited). + pub fn is_group(self) -> bool { + matches!(self, Opened::Group | Opened::Drawing) + } +} + +/// A symbol or group open for editing, and what to go back to. +#[derive(Clone, Debug, PartialEq)] +pub struct EditLevel { + pub open: Opened, + /// The instance it was opened from, on the timeline below (none: from the Library). + pub instance: Option<(LayerId, ElementId)>, + /// Stage space from the symbol's space: where the instance stands (through every level). + pub transform: Affine, + /// The timeline below as it was: its active layer, playhead and selection. + pub layer: LayerId, + pub frame: u32, + pub selection: Selection, + /// A drawing object opened in place (ADR 0080): the document and state from before it was + /// opened, and the state right after, so closing it without an edit puts both back. + pub back: Option>, +} + +impl EditLevel { + /// The symbol this level has open (`None` for a group). + pub fn symbol(&self) -> Option { + match self.open { + Opened::Symbol(id) => Some(id), + Opened::Group | Opened::Drawing => None, + } + } +} + +/// The members of the group level `l` opens, on timeline `below`. +fn group_in<'a>(below: &'a Timeline, l: &EditLevel) -> Option<&'a Timeline> { + let (layer, id) = l.instance?; + let k = below.layer(layer)?.keyframe_at(l.frame)?; + match &k.elements.iter().find(|e| e.id == id)?.kind { + ElementKind::Group { members } => Some(members), + _ => None, + } +} + +/// [`group_in`], copy-on-write. +fn group_in_mut<'a>(below: &'a mut Timeline, l: &EditLevel) -> Option<&'a mut Timeline> { + let (layer, id) = l.instance?; + let layer = below.layer_mut(layer)?; + let k = layer.keyframe_index_at(l.frame)?; + let el = layer.keyframe_mut(k)?.elements_mut_where(|e| e == id).into_iter().next()?; + match &mut el.kind { + ElementKind::Group { members } => Some(members), + _ => None, + } +} + +/// How many levels of `editing`, from the outermost, still open something, and the timeline the +/// last of them opens. +fn walk<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> (usize, &'a Timeline) { + let mut tl = doc.timeline(scene); + for (i, l) in editing.iter().enumerate() { + let next = match l.open { + Opened::Symbol(id) => doc.symbol(id).map(|s| &s.timeline), + Opened::Group | Opened::Drawing => group_in(tl, l), + }; + match next { + Some(t) => tl = t, + None => return (i, tl), + } + } + (editing.len(), tl) +} + +/// The timeline being edited: the open symbol's or group's, else the scene's. +pub(crate) fn edited<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> &'a Timeline { + walk(doc, scene, editing).1 +} + +/// [`edited`] ([`Session::timeline`]), copy-on-write. Takes the fields, so a caller can keep using +/// the session's others. Fails only when an open group is gone, which [`Session::fix_editing`] +/// never leaves for long. +pub(crate) fn edited_mut<'a>(doc: &'a mut Document, scene: usize, editing: &[EditLevel]) -> Result<&'a mut Timeline> { + let (valid, _) = walk(doc, scene, editing); + let levels = editing.get(..valid).unwrap_or_default(); + // From the innermost open symbol (or the scene), through the groups opened inside it. + let base = levels.iter().rposition(|l| matches!(l.open, Opened::Symbol(_))); + let open = base.and_then(|b| levels.get(b)).and_then(EditLevel::symbol).and_then(|id| doc.library.iter().position(|s| s.id == id)); + let groups = levels.get(base.map_or(0, |b| b + 1)..).unwrap_or_default(); + // (Borrowed only on the branch that returns it.) + let mut tl = match open { + Some(i) if i < doc.library.len() => &mut Arc::make_mut(&mut doc.library[i]).timeline, + _ => doc.timeline_mut(scene), + }; + for l in groups { + tl = group_in_mut(tl, l).ok_or_else(|| EngineError::State("the group open for editing is gone".into()))?; + } + Ok(tl) +} + +/// How the stage shows the open symbol: its space on the stage is `translate(origin) · +/// scale(scale)`. `in_place` when that is exactly where its instance stands, so the artwork +/// around it shows too. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EditView { + pub origin: Vec2, + pub scale: f32, + pub in_place: bool, +} + +/// What the stage draws: a document, the movie frame of it to render, and a state id for caching +/// the picture (equal ids, equal pictures). +#[derive(Clone)] +pub struct StagePicture { + pub doc: Document, + pub frame: u32, + pub state: StateId, + /// The open symbol in front, when one is open: onion skin and Edit Multiple Frames compose + /// its own frames (ADR 0051). + pub front: Option>, +} + +/// The open symbol in a [`StagePicture`]: the picture's top layer `layer` shows `timeline` at its +/// `frame`, placed by `at`. With onion skin on, that layer is drawn instead as the timeline's +/// frames composed by [`crate::onion::compose_timeline`], placed the same way. +#[derive(Clone, Debug)] +pub struct Front { + pub layer: LayerId, + pub timeline: Timeline, + pub frame: u32, + pub at: Affine, + /// The timeline the symbol was opened from, when it shows around it (in place): with onion + /// skin on, its frames around its own playhead show dimmed too (ADR 0061). + pub parent: Option, +} + +/// A timeline drawn dimmed around an open symbol: the picture's layer `layer` shows `timeline` +/// (without the instance that was opened) at its `frame`, placed by `at`, at opacity `dim`. +#[derive(Clone, Debug)] +pub struct Around { + pub layer: LayerId, + pub timeline: Timeline, + pub frame: u32, + pub at: Affine, + pub dim: f32, +} + +impl Session { + /// The timeline being edited: the open symbol's (ADR 0045), else the scene's. + pub fn timeline(&self) -> &Timeline { + edited(&self.doc, self.scene, &self.editing) + } + + /// The symbol open for editing, if any (`None` on the stage and while a group is open). + pub fn editing_symbol(&self) -> Option { + self.editing.last().and_then(EditLevel::symbol) + } + + /// Whether a group is open for editing (ADR 0073). + pub fn editing_group(&self) -> bool { + self.editing.last().is_some_and(|l| l.open.is_group()) + } + + /// Whether a drawing object is open for editing (ADR 0080). + pub fn editing_drawing(&self) -> bool { + self.editing.last().is_some_and(|l| l.open == Opened::Drawing) + } + + /// Closes levels whose symbol or group is gone (an undo, a Library deletion, an ungroup), + /// from the first such. + pub(crate) fn fix_editing(&mut self) { + let (valid, _) = walk(&self.doc, self.scene, &self.editing); + while self.editing.len() > valid { + self.exit_level(); + } + } + + fn enter_level(&mut self, open: Opened, instance: Option<(LayerId, ElementId)>, transform: Affine, frame: u32) { + self.editing.push(EditLevel { open, instance, transform, layer: self.layer, frame: self.frame, selection: std::mem::take(&mut self.selection), back: None }); + // The top layer inside, at the frame the instance shows. + self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id); + self.frame = frame.min(self.timeline().frame_count().saturating_sub(1)); + self.revision += 1; + self.dl_cache.replace(None); + } + + /// Closes the open symbol; the instance it was opened from is selected again. False when + /// none is open. + pub(crate) fn exit_level(&mut self) -> bool { + let Some(l) = self.editing.pop() else { return false }; + let gone = l.open == Opened::Drawing && self.close_drawing(&l); + self.layer = l.layer; + self.frame = l.frame; + self.selection = match l.instance { + Some(_) if gone => Selection::default(), + Some((layer, id)) => Selection::only(layer, [id]), + None => l.selection, + }; + self.revision += 1; + self.dl_cache.replace(None); + true + } + + /// Closes every open symbol (scene changes, opening a document). + pub(crate) fn exit_all(&mut self) { + while self.exit_level() {} + } + + /// How the stage shows the open symbol, `None` on the stage itself. In place when its + /// instance is only moved and scaled evenly (the editor's view can follow that exactly); + /// otherwise upright and at full size, with its registration point where the instance's is. + pub fn edit_view(&self) -> Option { + let l = self.editing.last()?; + let [a, b, c, d, e, f] = l.transform.m; + let origin = Vec2::new(e, f); + let even = b.abs() < 1e-5 && c.abs() < 1e-5 && a > 1e-4 && (a - d).abs() <= 1e-4 * a.max(1.0); + let in_place = even && self.editing.iter().all(|l| l.instance.is_some()); + Some(if in_place { EditView { origin, scale: a, in_place } } else { EditView { origin, scale: 1.0, in_place: false } }) + } + + /// What the stage draws (ADR 0045): the document at the playhead; while a symbol is open, its + /// timeline at its playhead where its instance stands, over the timelines it sits in dimmed. + pub fn stage_picture(&self) -> Arc { + let Some(view) = self.edit_view() else { + return Arc::new(StagePicture { doc: self.doc.clone(), frame: self.doc.scene_start(self.scene).saturating_add(self.frame), state: self.state, front: None }); + }; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (self.state, self.scene, self.frame).hash(&mut h); + for l in &self.editing { + (l.open, l.instance, l.frame, l.transform.m.map(f32::to_bits)).hash(&mut h); + } + let hit = self.hit_overlay(); + hit.map(|(c, a)| [c.r, c.g, c.b, c.a, a].map(f32::to_bits)).hash(&mut h); + let key = h.finish(); + if let Some((k, pic)) = &*self.picture_cache.borrow() + && *k == key + { + return pic.clone(); + } + let mut doc = self.doc.clone(); + let mut tl = Timeline::default(); + // The open symbol, in front. + let at = Affine::translate(view.origin.x, view.origin.y).mul(&Affine::scale(view.scale, view.scale)); + let open = self.timeline().clone(); + // A button's hit area over the state being edited, translucent (ADR 0057). + if let Some((tint, alpha)) = hit { + let frame = anicraft_doc::player::hit_frame(open.frame_count()); + tl.layers.push(placed(&mut doc, hit_timeline(&open), at, frame, ColorEffect::Advanced(hit_tint(tint, alpha)))); + } + let layer = placed(&mut doc, open.clone(), at, self.frame, ColorEffect::default()); + let mut front = Front { layer: layer.id, timeline: open, frame: self.frame, at, parent: None }; + tl.layers.push(layer); + // Around it, dimmed: each timeline below, without the instance opened from it. + if view.in_place { + for (i, l) in self.editing.iter().enumerate().rev() { + let parent = i.checked_sub(1).and_then(|j| self.editing.get(j)); + let below = edited(&self.doc, self.scene, self.editing.get(..i).unwrap_or_default()).clone(); + let xf = parent.map_or(Affine::IDENTITY, |p| p.transform); + let around = without(below, l.instance); + let layer = placed(&mut doc, around.clone(), xf, l.frame, ColorEffect::opacity(DIM)); + // The timeline right under the open symbol is the one onion skin shows around it. + if front.parent.is_none() { + front.parent = Some(Around { layer: layer.id, timeline: around, frame: l.frame, at: xf, dim: DIM }); + } + tl.layers.push(layer); + } + } + let front = Arc::new(front); + *doc.timeline_mut(self.scene) = tl; + // Apart from document states (counted up from 1), and the same for the same picture. + let pic = Arc::new(StagePicture { frame: doc.scene_start(self.scene), doc, state: key | 1 << 63, front: Some(front) }); + self.picture_cache.replace(Some((key, pic.clone()))); + pic + } +} + +impl Session { + /// The tint and opacity the stage draws the open button's hit area in (ADR 0057): while a + /// button is open and its playhead is on another frame than the one that answers the + /// pointer (the Hit frame, or Up when it has none), and [`Session::hit_area`] is set. + pub fn hit_overlay(&self) -> Option<(anicraft_doc::Rgba, f32)> { + let (tint, alpha) = self.hit_area?; + let sym = self.editing_symbol().and_then(|id| self.doc.symbol(id))?; + let frame = anicraft_doc::player::hit_frame(sym.timeline.frame_count()); + (sym.kind == SymbolKind::Button && self.frame != frame && alpha.is_finite() && alpha > 0.0).then_some((tint, alpha.min(1.0))) + } +} + +/// What answers the pointer on a button with timeline `tl`, as a timeline to draw (the hit test's +/// rules, `doc::player::hit_area`): mask layers go and what they masked is whole again, guide +/// layers are hidden (they still steer what follows them). +fn hit_timeline(tl: &Timeline) -> Timeline { + let masks: Vec = tl.layers.iter().filter(|l| l.kind == LayerKind::Mask).map(|l| l.id).collect(); + let layers = tl + .layers + .iter() + .filter(|l| l.kind != LayerKind::Mask) + .map(|l| { + if l.kind != LayerKind::Guide && !l.parent.is_some_and(|p| masks.contains(&p)) { + return l.clone(); + } + let mut l = (**l).clone(); + if l.kind == LayerKind::Guide { + l.visible = false; + } + if l.parent.is_some_and(|p| masks.contains(&p)) { + l.parent = None; + } + Arc::new(l) + }) + .collect(); + Timeline { layers } +} + +/// A layer holding `timeline` as a graphic symbol's instance at `transform`, showing its `frame` +/// with colour effect `color` (a symbol added to `doc`, which is only drawn). +fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, color: ColorEffect) -> Arc { + let symbol = SymbolId(doc.alloc_id()); + doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline })); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(Element { + id: ElementId(doc.alloc_id()), + name: String::new(), + transform, + color, + kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + })); + let mut layer = Layer::new(LayerId(doc.alloc_id()), ""); + layer.keyframes.push(Arc::new(k)); + Arc::new(layer) +} + +impl Session { + /// Opens the drawing object `id` on `layer` in place (ADR 0080): it becomes a group of one + /// raw shape (its own, unmoved), which the level opens. The picture doesn't change, so this + /// is no undo step; [`Session::close_drawing`] turns it back. + fn open_drawing(&mut self, layer: LayerId, id: ElementId) -> Result<()> { + let inner = ElementId(self.doc.alloc_id()); + let inner_layer = LayerId(self.doc.alloc_id()); + let frame = self.frame; + let tl = edited_mut(&mut self.doc, self.scene, &self.editing)?; + let l = tl.layer_mut(layer).ok_or_else(|| EngineError::State("that drawing object's layer is gone".into()))?; + let k = l.keyframe_index_at(frame).ok_or_else(|| EngineError::State("no keyframe here".into()))?; + let kf = l.keyframe_mut(k).ok_or_else(|| EngineError::State("no keyframe here".into()))?; + let at = kf.elements.iter().position(|e| e.id == id).ok_or_else(|| EngineError::State("that drawing object is not on this keyframe".into()))?; + let Some(el) = kf.elements.get(at).cloned() else { return Err(EngineError::State("that drawing object is not on this keyframe".into())) }; + let ElementKind::Shape(sh) = &el.kind else { return Err(EngineError::State("that is not a drawing object".into())) }; + let shape = Element { id: inner, name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::Shape(anicraft_doc::Shape { merge: true, ..sh.clone() }) }; + let group = Element { id, name: el.name.clone(), transform: el.transform, color: el.color, kind: ElementKind::group(inner_layer, vec![Arc::new(shape)]) }; + if let Some(slot) = kf.elements.get_mut(at) { + *slot = Arc::new(group); + } + Ok(()) + } + + /// Closes a drawing object opened in place (level `l`, just taken off the stack): one shape + /// left inside is one drawing object again, exactly as it shows (its id, name and place); + /// nothing left, and it is gone; several, and they stay a group of raw shapes (what Combine + /// Objects' Union makes of shapes of several colours). Opening and closing it without an + /// edit leaves the document as it was, state and all. True when it is gone. + fn close_drawing(&mut self, l: &EditLevel) -> bool { + // Nothing changed since it was opened: the document goes back exactly as it was. + if let Some(back) = &l.back + && back.2 == self.state + { + self.doc = back.0.clone(); + self.state = back.1; + self.dl_cache.replace(None); + return false; + } + let Some((layer, id)) = l.instance else { return false }; + let below = self.editing.clone(); + let Ok(tl) = edited_mut(&mut self.doc, self.scene, &below) else { return false }; + let Some(lay) = tl.layer_mut(layer) else { return false }; + let Some(k) = lay.keyframe_index_at(l.frame) else { return false }; + let Some(kf) = lay.keyframe_mut(k) else { return false }; + let Some(at) = kf.elements.iter().position(|e| e.id == id) else { return false }; + let Some(group) = kf.elements.get(at).cloned() else { return false }; + let ElementKind::Group { members } = &group.kind else { return false }; + let inside: Vec> = members.layers.iter().filter_map(|m| m.keyframe_at(0)).flat_map(|k| k.elements.iter().cloned()).collect(); + let one_layer = members.layers.len() == 1; + let mut gone = false; + match inside.as_slice() { + [] if one_layer => { + kf.elements.remove(at); + gone = true; + } + [only] if one_layer => { + // Two colour effects only nest as one when one of them is none. + let color = match (group.color, only.color) { + (c, ColorEffect::None) | (ColorEffect::None, c) => Some(c), + _ => None, + }; + if let (ElementKind::Shape(sh), Some(color)) = (&only.kind, color) { + let object = Element { id, name: group.name.clone(), transform: group.transform.mul(&only.transform), color, kind: ElementKind::Shape(anicraft_doc::Shape { merge: false, ..sh.clone() }) }; + if let Some(slot) = kf.elements.get_mut(at) { + *slot = Arc::new(object); + } + } + } + _ => {} + } + self.state = crate::history::fresh_state(); + self.dl_cache.replace(None); + gone + } +} + +/// Whether an instance of `sym` placed in the open symbol would put a symbol inside itself: `sym` +/// is open, or uses an open one, however deep. +pub(crate) fn would_nest(s: &Session, sym: SymbolId) -> bool { + if s.editing.is_empty() { + return false; + } + let mut seen: Vec = Vec::new(); + let mut todo = vec![sym]; + while let Some(id) = todo.pop() { + if s.editing.iter().any(|l| l.symbol() == Some(id)) { + return true; + } + if seen.contains(&id) || seen.len() > 100_000 { + continue; + } + seen.push(id); + let Some(sym) = s.doc.symbol(id) else { continue }; + for k in sym.timeline.layers.iter().flat_map(|l| l.keyframes.iter()) { + todo.extend(anicraft_doc::expand_groups(&k.elements).iter().filter_map(|e| match e.kind { + ElementKind::Symbol { symbol, .. } => Some(symbol), + _ => None, + })); + } + } + false +} + +/// `tl` without the instance `which` (on every keyframe of its layer). +fn without(mut tl: Timeline, which: Option<(LayerId, ElementId)>) -> Timeline { + let Some((layer, id)) = which else { return tl }; + if let Some(l) = tl.layer_mut(layer) { + for k in &mut l.keyframes { + if k.elements.iter().any(|e| e.id == id) { + Arc::make_mut(k).elements.retain(|e| e.id != id); + } + } + } + tl +} + +/// Whether `symbol.edit` opens `e`: a symbol instance, a group or a drawing object. +pub fn opens(e: &Element) -> bool { + match &e.kind { + ElementKind::Symbol { .. } | ElementKind::Group { .. } => true, + // A warped shape (ADR 0079) keeps its outline as drawn under its mesh: it is edited + // through its pins, not opened. + ElementKind::Shape(sh) => !sh.merge && sh.warp.is_none(), + _ => false, + } +} + +/// The instance `id` on a layer at the playhead of the timeline being edited, and its layer. +fn instance(s: &Session, id: ElementId) -> Option<(LayerId, Arc)> { + s.timeline().layers.iter().map(|l| l.id).find_map(|l| s.elements_on(l).into_iter().find(|e| e.id == id).map(|e| (l, e))) +} + +pub(crate) fn edit(s: &mut Session, p: &Value) -> Result { + if s.editing.len() >= MAX_LEVELS { + return Err(EngineError::State(format!("at most {MAX_LEVELS} symbols can be open inside each other"))); + } + // From the Library: alone, its registration point at the stage's centre. + if let Some(sym) = opt_u64(p, "symbol")? { + let symbol = SymbolId(sym); + if s.doc.symbol(symbol).is_none() { + return Err(EngineError::State(format!("no symbol {sym} in the Library"))); + } + if s.editing.iter().any(|l| l.symbol() == Some(symbol)) { + return Err(EngineError::State("that symbol is open already".into())); + } + let c = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5); + s.enter_level(Opened::Symbol(symbol), None, Affine::translate(c.x, c.y), 0); + return Ok(editing_json(s)); + } + let id = match opt_u64(p, "id")? { + Some(i) => ElementId(i), + None => { + let picked: Vec = s.selection.on(s.layer).into_iter().filter(|id| instance(s, *id).is_some_and(|(_, e)| opens(&e))).collect(); + match picked.as_slice() { + [one] => *one, + // Nothing to open: Ctrl+E goes back to the document, as in Animate. + [] if !s.editing.is_empty() => { + s.exit_all(); + return Ok(editing_json(s)); + } + [] => return Err(EngineError::State("select a symbol instance, a group or a drawing object to edit it (or double-click it)".into())), + _ => return Err(EngineError::State("select one symbol instance, group or drawing object to edit".into())), + } + } + }; + let (layer, el) = instance(s, id).ok_or_else(|| EngineError::State(format!("element {} is not on a layer here at this frame", id.0)))?; + if !s.selectable(layer) { + return Err(EngineError::State("that instance's layer is locked or hidden".into())); + } + let below = s.editing.last().map_or(Affine::IDENTITY, |l| l.transform); + // A group opens where it stands (ADR 0073): its members at their only frame. The level finds + // the keyframe it is on through the playhead below. + if matches!(el.kind, ElementKind::Group { .. }) { + s.enter_level(Opened::Group, Some((layer, id)), below.mul(&el.transform), 0); + return Ok(editing_json(s)); + } + // A drawing object opens the same way (ADR 0080), as a group of its one raw shape. + if matches!(&el.kind, ElementKind::Shape(sh) if !sh.merge && sh.warp.is_some()) { + return Err(EngineError::State("that drawing object is warped (Asset Warp): edit it with its pins, or remove its warp to edit its outline".into())); + } + if matches!(&el.kind, ElementKind::Shape(sh) if !sh.merge) { + if crate::cmds_group::open_groups(s) + 1 > anicraft_doc::MAX_GROUP_DEPTH { + return Err(EngineError::State(format!("groups nest at most {} deep", anicraft_doc::MAX_GROUP_DEPTH))); + } + let (was, state) = (s.doc.clone(), s.state); + s.open_drawing(layer, id)?; + s.state = crate::history::fresh_state(); + s.enter_level(Opened::Drawing, Some((layer, id)), below.mul(&el.transform), 0); + if let Some(l) = s.editing.last_mut() { + l.back = Some(Arc::new((was, state, s.state))); + } + return Ok(editing_json(s)); + } + let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = el.kind else { return Err(EngineError::State("that is not a symbol instance, a group or a drawing object".into())) }; + let sym = s.doc.symbol(symbol).ok_or_else(|| EngineError::State("that instance's symbol is missing from the Library".into()))?; + if s.editing.iter().any(|l| l.symbol() == Some(symbol)) { + return Err(EngineError::State("that symbol is open already".into())); + } + // A graphic opens at the frame the instance shows; movie clips and buttons at their first. + let len = sym.timeline.frame_count(); + let start = s.timeline().layer(layer).and_then(|l| l.keyframe_at(s.frame)).map_or(s.frame, |k| k.start); + let frame = if sym.kind == SymbolKind::Graphic { loop_mode.local_frame(s.frame.saturating_sub(start), first_frame, len) } else { 0 }; + s.enter_level(Opened::Symbol(symbol), Some((layer, id)), below.mul(&el.transform), frame); + Ok(editing_json(s)) +} + +fn exit(s: &mut Session, p: &Value) -> Result { + if s.editing.is_empty() { + return Err(EngineError::State("no symbol or group is open for editing".into())); + } + if opt_bool(p, "all")?.unwrap_or(false) { + s.exit_all(); + } else { + s.exit_level(); + } + Ok(editing_json(s)) +} + +/// The open symbols, outermost first. +pub(crate) fn editing_json(s: &Session) -> Value { + let list: Vec = s + .editing + .iter() + .map(|l| match l.symbol() { + Some(id) => json!({"symbol": id.0, "name": s.doc.symbol(id).map(|x| x.name.clone()), "instance": l.instance.map(|(_, e)| e.0)}), + None if l.open == Opened::Drawing => json!({"drawing": l.instance.map(|(_, e)| e.0), "name": "Drawing Object", "instance": l.instance.map(|(_, e)| e.0)}), + None => json!({"group": l.instance.map(|(_, e)| e.0), "name": "Group", "instance": l.instance.map(|(_, e)| e.0)}), + }) + .collect(); + json!({"editing": list, "layer": s.layer.0, "frame": s.frame, "selected": s.selection.id_list()}) +} + +/// Every colour of the hit area replaced by `tint`, the whole faded to `alpha` (ADR 0057): what +/// Animate's Advanced effect calls multipliers 0 % and offsets of the tint, alpha at `alpha`. +fn hit_tint(tint: anicraft_doc::Rgba, alpha: f32) -> anicraft_doc::ColorTransform { + anicraft_doc::ColorTransform { mul: [0.0, 0.0, 0.0, alpha], add: [tint.r, tint.g, tint.b, 0.0] } +} diff --git a/crates/engine/src/editing_tests.rs b/crates/engine/src/editing_tests.rs new file mode 100644 index 00000000..4b38fa91 --- /dev/null +++ b/crates/engine/src/editing_tests.rs @@ -0,0 +1,184 @@ +//! Editing a symbol's timeline in place, with raw drawings inside it (ADR 0045). + +use crate::Session; +use anicraft_doc::{Element, ElementId, ElementKind, SymbolId}; +use anicraft_geom::Vec2; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn raw(s: &Session) -> Vec> { + s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect() +} + +fn has(points: &[Vec2], p: (f32, f32)) -> bool { + points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 0.3) +} + +/// A raw outlined rectangle (100 × 80) turned into a symbol, its instance moved to stand at +/// (250, 140): the symbol's space runs from (−50, −40) to (50, 40). +fn boxed() -> (Session, ElementId, SymbolId) { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let (inst, sym) = (ElementId(v["instance"].as_u64().unwrap_or(0)), SymbolId(v["symbol"].as_u64().unwrap_or(0))); + run(&mut s, "element.translate", json!({"dx": 200, "dy": 100})); + (s, inst, sym) +} + +#[test] +fn raw_shapes_inside_a_symbol_merge_and_take_the_selection_and_subselection_tools() { + let (mut s, inst, sym) = boxed(); + let steps = s.history_len(); + let v = run(&mut s, "symbol.edit", json!({})); + assert_eq!(v["editing"][0]["symbol"], json!(sym.0), "{v}"); + assert_eq!(s.history_len(), steps, "opening is not an edit"); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + assert!(view.in_place && view.origin.distance(Vec2::new(250.0, 140.0)) < 1e-3 && (view.scale - 1.0).abs() < 1e-6, "{view:?}"); + // Inside: the symbol's own layer, its raw drawing of five shapes, in its space. + assert_eq!(s.timeline().layers.len(), 1); + assert_eq!(raw(&s).len(), 5); + assert!(s.hit_test(Vec2::new(0.0, 0.0), 1.0).is_some(), "picking is in the symbol's space"); + // Subselection: everything connected shows its four corners. + let v = run(&mut s, "raw.subselect", json!({"x": 0, "y": -40})); + assert_eq!(v["anchors"].as_array().map(Vec::len), Some(4), "{v}"); + // The Selection tool: a corner moves with every shape on it. + run(&mut s, "raw.move_point", json!({"x": 50, "y": -40, "to_x": 60, "to_y": -50})); + assert!(has(&s.raw_points(&raw(&s).iter().map(|e| e.id).collect::>()).anchors, (60.0, -50.0))); + // Merge drawing: a line right across cuts the fill in two. + run(&mut s, "draw.line", json!({"x0": -70, "y0": 0, "x1": 70, "y1": 0, "stroke": "#000000"})); + let fills = raw(&s).into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(); + assert_eq!(fills, 2); + // Points: added and deleted inside, shared as on the stage. + run(&mut s, "raw.add_point", json!({"x": -50, "y": 20})); + run(&mut s, "raw.delete_points", json!({"points": [[-50, 20]]})); + // Back on the stage: the instance is selected and shows the edits where it stands. + run(&mut s, "symbol.exit", json!({})); + assert!(s.editing.is_empty()); + assert_eq!(s.selection.ids().collect::>(), vec![inst]); + let b = s.element_bounds(inst); + assert!(b.max.x > 309.0 && b.min.y < 91.0, "the moved corner at (310, 90): {b:?}"); +} + +#[test] +fn undo_goes_back_into_the_symbol_where_the_change_was_made() { + let (mut s, _, sym) = boxed(); + run(&mut s, "symbol.edit", json!({})); + run(&mut s, "raw.delete_points", json!({"points": [[-50, -40]]})); + assert_eq!(raw(&s).iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(), 1); + run(&mut s, "symbol.exit", json!({})); + assert!(s.undo().is_ok()); + assert_eq!(s.editing_symbol(), Some(sym), "undo opens the symbol again"); + assert_eq!(s.raw_points(&raw(&s).iter().map(|e| e.id).collect::>()).anchors.len(), 4, "with the corner back"); + // Undoing the conversion takes the symbol away: editing closes. + while s.undo().is_ok() {} + assert!(s.editing.is_empty() && s.doc.library.is_empty()); +} + +#[test] +fn opening_from_the_library_and_guards() { + let (mut s, inst, sym) = boxed(); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("symbol.edit", &json!({})).is_err(), "nothing selected to open"); + assert!(s.execute("symbol.exit", &json!({})).is_err(), "nothing open"); + run(&mut s, "symbol.edit", json!({"symbol": sym.0})); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + let centre = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5); + assert!(!view.in_place && view.origin == centre, "alone, at the stage's centre: {view:?}"); + assert!(s.execute("library.place", &json!({"symbol": sym.0})).is_err(), "not inside itself"); + assert!(s.execute("symbol.edit", &json!({"symbol": sym.0})).is_err(), "open already"); + // Ctrl+E with nothing to open goes back to the document. + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "symbol.edit", json!({})); + assert!(s.editing.is_empty()); + // A rotated instance opens upright where it stands, the artwork around it hidden. + run(&mut s, "element.select", json!({"ids": [inst.0]})); + run(&mut s, "modify.transform", json!({"a": 0.0, "b": 1.0, "c": -1.0, "d": 0.0, "e": 0.0, "f": 0.0})); + run(&mut s, "symbol.edit", json!({"id": inst.0})); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + assert!(!view.in_place && (view.scale - 1.0).abs() < 1e-6, "{view:?}"); + // A scene change closes it. + run(&mut s, "scene.new", json!({})); + assert!(s.editing.is_empty()); +} + +/// The sample's Play button open from the Library (at the stage's centre, 640 × 360): its face is +/// 220 × 80, its Hit frame 240 × 100. +fn open_button(hit: Option<(anicraft_doc::Rgba, f32)>) -> Session { + let mut s = Session::new(anicraft_doc::sample::interactive()); + let id = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id).unwrap_or_else(|| panic!("a button")); + run(&mut s, "symbol.edit", json!({"symbol": id.0})); + s.hit_area = hit; + s +} + +#[test] +fn an_open_button_shows_its_hit_area_over_its_other_states() { + let red = anicraft_doc::Rgba::new(1.0, 0.0, 0.0, 1.0); + let render = |s: &Session| { + let pic = s.stage_picture(); + anicraft_render::render_frame(&pic.doc, pic.frame, 1.0).unwrap_or_else(|e| panic!("{e}")) + }; + let plain = render(&open_button(None)); + let mut s = open_button(Some((red, 0.5))); + assert_eq!(s.hit_overlay(), Some((red, 0.5)), "on the Up frame"); + let shown = render(&s); + let px = |p: &anicraft_render::Pixmap, x: u32, y: u32| p.pixel(x, y).unwrap_or_else(|| panic!("({x}, {y}) in the picture")); + // Inside the Hit frame but outside the face (x = 640 + 115): the background, half red now. + let (bg, over) = (px(&plain, 755, 360), px(&shown, 755, 360)); + for c in 0..3 { + let want = bg[c] * 0.5 + if c == 0 { 0.5 } else { 0.0 }; + assert!((over[c] - want).abs() < 0.02, "channel {c}: {over:?} vs {want} (background {bg:?})"); + } + // Over the face (blue) and its arrow (white) alike: half red over what the state shows. + for (x, y) in [(600, 360), (640, 360)] { + let (art, over) = (px(&plain, x, y), px(&shown, x, y)); + for c in 0..3 { + let want = art[c] * 0.5 + if c == 0 { 0.5 } else { 0.0 }; + assert!((over[c] - want).abs() < 0.02, "({x}, {y}) channel {c}: {over:?} vs {want}"); + } + } + // Outside the Hit frame: untouched. + assert_eq!(px(&shown, 775, 360), px(&plain, 775, 360)); + // On the Hit frame itself, nothing over it; it isn't in the document either. + s.set_frame(3); + assert_eq!(s.hit_overlay(), None); + let on_hit = render(&s); + s.hit_area = None; + assert_eq!(on_hit.to_rgba8(), render(&s).to_rgba8()); + assert_eq!(s.doc.library.len(), anicraft_doc::sample::interactive().library.len()); + // Only buttons: a movie clip open shows none. + let mut s = Session::new(anicraft_doc::sample::interactive()); + let clip = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::MovieClip).map(|x| x.id).unwrap_or_else(|| panic!("a clip")); + run(&mut s, "symbol.edit", json!({"symbol": clip.0})); + s.hit_area = Some((red, 0.5)); + assert_eq!(s.hit_overlay(), None); +} + +#[test] +fn the_stage_shows_the_open_symbol_in_place_over_the_dimmed_stage() { + let (mut s, _, _) = boxed(); + // Something else on the stage, beside the instance. + run(&mut s, "draw.rect", json!({"x": 400, "y": 300, "w": 50, "h": 50, "fill": "#0000ff", "stroke": null, "object": true})); + run(&mut s, "element.pick", json!({"x": 250, "y": 140})); + run(&mut s, "symbol.edit", json!({})); + let pic = s.stage_picture(); + assert_eq!(pic.state, s.stage_picture().state, "the same picture twice"); + let px = anicraft_render::render_frame(&pic.doc, pic.frame, 1.0).unwrap_or_else(|e| panic!("{e}")); + let at = |x: u32, y: u32| px.pixel(x, y).unwrap_or_else(|| panic!("in the picture")); + // The symbol's fill in full red where its instance stands... + let red = at(250, 140); + assert!(red[0] > 0.95 && red[1] < 0.05 && red[2] < 0.05, "{red:?}"); + // ...and the stage around it dimmed (blue at about a third over white). + let blue = at(425, 325); + assert!(blue[2] > 0.95 && blue[0] > 0.5 && blue[0] < 0.8, "{blue:?}"); + // The document itself is untouched by the picture. + assert_eq!(s.doc.library.len(), 1); + // Back on the stage, the picture is the document. + run(&mut s, "symbol.exit", json!({})); + assert_eq!(s.stage_picture().state, s.state); +} diff --git a/crates/engine/src/erase_tests.rs b/crates/engine/src/erase_tests.rs index be5f6c42..8bf2200c 100644 --- a/crates/engine/src/erase_tests.rs +++ b/crates/engine/src/erase_tests.rs @@ -228,3 +228,130 @@ fn bad_params_are_errors_and_plug_ins_may_erase() { assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); } } + +// ----- ADR 0093: gradients and width profiles through the merge, erasing inside symbols -------- + +#[test] +fn an_erased_gradient_keeps_its_gradient_in_both_pieces_where_it_was() { + let mut s = blank(false); + let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, anicraft_doc::GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }]; + let paint = Paint::linear(Vec2::new(100.0, 100.0), Vec2::new(300.0, 100.0), stops); + s.style.fill_paint = Some(paint.clone()); + s.style.lock_fill = true; + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "stroke": null})); + run(&mut s, "edit.deselect", json!({})); + let r = run(&mut s, "draw.erase", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20})); + assert_eq!(r["erased"], true); + let pieces = shapes(&s); + assert_eq!(pieces.len(), 2, "cut in two"); + for (sh, m) in &pieces { + let f = sh.fill.as_ref().map(|f| f.transformed(m)).expect("filled"); + assert!(crate::merge::same_paint(&f, &paint), "the gradient stays in the same place on the stage: {f:?}"); + } + assert!(near(measure(&s).0, 18_000.0, 40.0)); + // The renderer agrees: left red, right blue, the band empty. + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let (l, r) = (img.pixel(110, 150).unwrap(), img.pixel(290, 150).unwrap()); + assert!(l[0] > 0.85 && l[2] < 0.15 && r[2] > 0.85 && r[0] < 0.15, "{l:?} {r:?}"); +} + +/// The raw strokes on the active layer with their profiles, as (start x, end x, profile). +fn profiled(s: &Session) -> Vec<(f32, f32, Option)> { + shapes(s) + .into_iter() + .filter_map(|(sh, m)| { + let st = sh.stroke.as_ref()?; + let ends: Vec = sh.path.anchors().iter().map(|p| m.apply(p.1)).collect(); + Some((ends.first()?.x, ends.last()?.x, st.profile.clone())) + }) + .collect() +} + +#[test] +fn a_variable_width_stroke_split_by_the_eraser_keeps_its_profile_per_piece() { + let mut s = blank(false); + s.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth); + let source = anicraft_doc::ProfilePreset::TaperBoth.profile().unwrap(); + run(&mut s, "draw.line", json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke": BLACK, "stroke_width": 12})); + run(&mut s, "edit.deselect", json!({})); + assert_eq!(profiled(&s).len(), 1, "a variable-width line is raw (ADR 0093)"); + let r = run(&mut s, "draw.erase", json!({"points": stroke(150.0, 60.0, 150.0, 140.0), "size": 20})); + assert_eq!(r["erased"], true); + let pieces = profiled(&s); + assert_eq!(pieces.len(), 2, "{pieces:?}"); + for (x0, x1, prof) in &pieces { + let prof = prof.as_ref().expect("each piece keeps a profile"); + // Every place on the piece has the width it had on the line. + for k in 0..=10 { + let u = k as f32 / 10.0; + let x = x0 + (x1 - x0) * u; + let want = source.at((x - 100.0) / 200.0); + let got = prof.at(u); + assert!((got.0 - want.0).abs() < 0.06 && (got.1 - want.1).abs() < 0.06, "at x {x}: {got:?} vs {want:?} ({x0}..{x1})"); + } + } + // The left piece starts at a point and ends wide; erasing nothing changes nothing. + let doc = s.doc.clone(); + let r = run(&mut s, "draw.erase", json!({"points": stroke(150.0, 300.0, 150.0, 340.0), "size": 20})); + assert_eq!(r["erased"], false); + assert_eq!(s.doc, doc); + // A line across a variable-width line cuts it too, the profile following each piece. + let mut t = blank(false); + t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth); + run(&mut t, "draw.line", json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke": BLACK, "stroke_width": 12})); + t.style.set_profile(anicraft_doc::ProfilePreset::Uniform); + run(&mut t, "draw.line", json!({"x0": 200, "y0": 0, "x1": 200, "y1": 200, "stroke": RED, "stroke_width": 2})); + let cut: Vec<_> = profiled(&t).into_iter().filter(|p| p.2.is_some()).collect(); + assert_eq!(cut.len(), 2, "{cut:?}"); + // Merging the pieces again (a drop) keeps them as they are. + let before = profiled(&t); + let ids: Vec = t.visible_elements().iter().map(|e| e.id.0).collect(); + t.select_only(ids.iter().map(|i| anicraft_doc::ElementId(*i))); + run(&mut t, "draw.drop", json!({})); + let after = profiled(&t); + assert_eq!(after.len(), before.len()); + for (a, b) in after.iter().filter(|p| p.2.is_some()).zip(before.iter().filter(|p| p.2.is_some())) { + let (pa, pb) = (a.2.as_ref().unwrap(), b.2.as_ref().unwrap()); + for k in 0..=10 { + let u = k as f32 / 10.0; + assert!((pa.at(u).0 - pb.at(u).0).abs() < 1e-3, "remerged profile drifted"); + } + } + // And the file keeps them. + let json = crate::format::to_json(&s.doc).unwrap(); + assert_eq!(crate::format::from_json(&json).unwrap(), s.doc); +} + +#[test] +fn the_eraser_works_inside_an_open_symbol_and_says_how_on_the_stage() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": BLUE, "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Card"})); + let inst = s.selection.id_list().first().copied().expect("the instance is selected"); + run(&mut s, "edit.deselect", json!({})); + // On the stage, the symbol is kept, and the reason says how to erase inside it. + let (doc, steps) = (s.doc.clone(), s.history_len()); + let r = run(&mut s, "draw.erase", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20})); + assert_eq!(r["erased"], false); + assert_eq!(r["kept"]["symbols"], 1); + assert!(r["reason"].as_str().unwrap().contains("double-click"), "{r}"); + assert_eq!((s.doc.clone(), s.history_len()), (doc, steps), "no change, no undo step"); + // Opened in place, its raw shapes erase, in the symbol's own space. + run(&mut s, "symbol.edit", json!({"id": inst})); + let to_symbol = s.editing.last().map(|l| l.transform).and_then(|m| m.inverse()).unwrap(); + let pts: Vec<[f32; 2]> = stroke(200.0, 60.0, 200.0, 240.0).into_iter().map(|[x, y]| to_symbol.apply(Vec2::new(x, y))).map(|p| [p.x, p.y]).collect(); + let r = run(&mut s, "draw.erase", json!({"points": pts, "size": 20})); + assert_eq!(r["erased"], true, "{r}"); + run(&mut s, "symbol.exit", json!({"all": true})); + // The instance on the stage shows the cut (the renderer, the oracle). + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let bg = s.doc.stage.background; + let (gap, kept) = (img.pixel(200, 150).unwrap(), img.pixel(150, 150).unwrap()); + assert!((gap[2] - bg.b).abs() < 0.02 && (gap[0] - bg.r).abs() < 0.02, "{gap:?}"); + assert!(kept[2] > 0.9, "{kept:?}"); + // One undo step puts the symbol back whole. + run(&mut s, "edit.undo", json!({})); + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + assert!(img.pixel(200, 150).unwrap()[2] > 0.9); +} diff --git a/crates/engine/src/explorer.rs b/crates/engine/src/explorer.rs new file mode 100644 index 00000000..55c2431b --- /dev/null +++ b/crates/engine/src/explorer.rs @@ -0,0 +1,527 @@ +//! The Movie Explorer (ADR 0058), as Animate's: the movie as a tree of scenes › layers › +//! keyframes › what is on them (symbol instances, text, bitmaps, sounds, frame scripts and +//! instance actions), each instance opening into its symbol's own layers, and the Library's +//! symbol definitions. Show filters hide kinds of rows; a text filter keeps the rows whose names +//! hold it, with the rows above them. +//! +//! [`tree`] gives the rows that are showing, in order, each with its depth, so a list can draw +//! only the rows in view. Only open rows' children are made, so the work follows what is shown, +//! and it stops at [`MAX_ROWS`] and [`MAX_DEPTH`]. Every row says where it is as `find.goto` +//! params, which is how a double-click jumps there. + +use crate::find::{Scope, Step}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Document, ElementId, ElementKind, FrameScript, Keyframe, LayerId, LayerKind, Paint, Symbol, SymbolId, SymbolKind, Timeline}; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet}; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![c( + "explorer.tree", + "Movie Explorer", + "", + None, + "{scope?: document (default) | scene, show?: {text?, symbols?, scripts?, media?, frames? (layers and keyframes)} (each default true), definitions?: bool (the Library's symbols; default true), expanded?: [row keys] (default: the top rows), all?: bool (everything open), filter?: text (rows whose names hold it, and the rows above them), offset?, limit? (default 1000, at most 10000)} → {rows: [{key, depth, kind, type?, name, extra, frame?, children, open, go: find.goto params}], total, truncated}", + false, + tree_cmd as crate::RunFn, + )] +} + +/// Most rows one tree makes. +pub const MAX_ROWS: usize = 200_000; +/// Deepest row (instances inside instances). +pub const MAX_DEPTH: usize = 48; +const DEFAULT_LIMIT: usize = 1_000; +const MAX_LIMIT: usize = 10_000; + +/// What a row is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NodeKind { + Scene, + /// The Library's symbols, under one row. + Definitions, + /// A symbol in the Library. + Symbol(SymbolKind), + Layer(LayerKind), + /// A keyframe (its name is its label). + Frame, + /// A keyframe's script or actions. + Script, + /// A button or movie clip instance's actions for one event. + Handler, + Sound, + Instance(SymbolKind), + Text, + Bitmap, +} + +impl NodeKind { + pub fn key(self) -> &'static str { + match self { + NodeKind::Scene => "scene", + NodeKind::Definitions => "definitions", + NodeKind::Symbol(_) => "symbol", + NodeKind::Layer(_) => "layer", + NodeKind::Frame => "frame", + NodeKind::Script => "script", + NodeKind::Handler => "handler", + NodeKind::Sound => "sound", + NodeKind::Instance(_) => "instance", + NodeKind::Text => "text", + NodeKind::Bitmap => "bitmap", + } + } +} + +/// Which kinds of rows show (Animate's Show buttons). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Show { + /// Text fields. + pub text: bool, + /// Buttons, movie clips and graphics. + pub symbols: bool, + /// Frame scripts and instance actions. + pub scripts: bool, + /// Sounds and bitmaps. + pub media: bool, + /// Layers and keyframes; off, what is on them is listed straight under the scene or symbol. + pub frames: bool, +} + +impl Default for Show { + fn default() -> Self { + Show { text: true, symbols: true, scripts: true, media: true, frames: true } + } +} + +/// What the tree shows. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Options { + pub scope: Scope, + pub show: Show, + pub definitions: bool, + /// Open rows, by key. `None`: only the top rows. + pub expanded: Option>, + /// Every row open. + pub all: bool, + pub filter: String, +} + +impl Default for Options { + fn default() -> Self { + Options { scope: Scope::Document, show: Show::default(), definitions: true, expanded: None, all: false, filter: String::new() } + } +} + +/// Where a row is, as `find.goto` params. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Go { + pub scene: Option, + /// The symbol opened alone (from the Library), or to open. + pub symbol: Option, + /// Instances opened in place from the scene or the symbol. + pub path: Vec, + pub layer: Option, + pub frame: Option, + pub element: Option, +} + +impl Go { + pub fn to_json(&self) -> Value { + let mut v = json!({}); + if let Some(s) = self.scene { + v["scene"] = json!(s); + } + if let Some(s) = self.symbol { + v["symbol"] = json!(s.0); + } + if !self.path.is_empty() { + v["path"] = Value::Array(self.path.iter().map(Step::to_json).collect()); + } + if let Some(l) = self.layer { + v["layer"] = json!(l.0); + } + if let Some(f) = self.frame { + v["frame"] = json!(f); + } + if let Some(e) = self.element { + v["element"] = json!(e.0); + } + v + } +} + +/// One row of the tree. +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + /// Stable while the document keeps its ids: what `expanded` names. + pub key: String, + pub depth: usize, + pub kind: NodeKind, + /// Document text: a scene, layer, symbol or sound name, a frame label, a text field's first + /// line, an instance's symbol, a script's summary. + pub name: String, + /// More document text: an instance's name, a text field's font and size. + pub extra: String, + /// The keyframe's first frame (keyframes and what is on them). + pub frame: Option, + pub children: bool, + pub open: bool, + pub go: Go, +} + +impl Row { + pub fn to_json(&self) -> Value { + let mut v = json!({"key": self.key, "depth": self.depth, "kind": self.kind.key(), "name": self.name, "extra": self.extra, "frame": self.frame, "children": self.children, "open": self.open, "go": self.go.to_json()}); + match self.kind { + NodeKind::Symbol(k) | NodeKind::Instance(k) => v["type"] = json!(crate::cmds_library::kind_key(k)), + NodeKind::Layer(k) => v["type"] = json!(format!("{k:?}").to_lowercase()), + _ => {} + } + v + } +} + +/// The tree's rows and whether it stopped at [`MAX_ROWS`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Tree { + pub rows: Vec, + pub truncated: bool, +} + +struct Walk<'a> { + doc: &'a Document, + syms: HashMap, + o: &'a Options, + /// Everything is open (all, or a filter is looking through it all). + every: bool, + rows: Vec, + truncated: bool, +} + +/// The first line of `t`, at most 80 characters. +fn line(t: &str) -> String { + let first = t.lines().next().unwrap_or("").trim(); + let mut out: String = first.chars().take(80).collect(); + if out.len() < first.len() || t.trim().lines().nth(1).is_some() { + out.push('…'); + } + out +} + +impl<'a> Walk<'a> { + fn open(&self, key: &str, depth: usize) -> bool { + self.every || self.o.expanded.as_ref().map_or(depth == 0, |e| e.contains(key)) + } + + /// Adds a row; false once the tree is full. + fn push(&mut self, row: Row) -> bool { + if self.rows.len() >= MAX_ROWS { + self.truncated = true; + return false; + } + self.rows.push(row); + true + } + + fn full(&self) -> bool { + self.truncated + } + + /// Whether a keyframe shows anything (with the frames shown, a labelled keyframe does too). + fn frame_items(&self, k: &Keyframe) -> bool { + let s = self.o.show; + (s.scripts && k.script.is_some()) + || (s.media && k.sound.is_some()) + || anicraft_doc::expand_groups(&k.elements).iter().any(|e| match &e.kind { + ElementKind::Symbol { .. } => s.symbols, + ElementKind::Text(_) => s.text, + ElementKind::Shape(sh) => s.media && matches!(sh.fill, Some(Paint::Bitmap { .. })), + ElementKind::Camera | ElementKind::Group { .. } => false, + }) + || (s.frames && !k.label.is_empty()) + } + + fn has_items(&self, tl: &Timeline) -> bool { + tl.layers.iter().any(|l| self.o.show.frames || l.keyframes.iter().any(|k| self.frame_items(k))) + } + + /// The rows of timeline `tl` under `key`, at `depth`. `go` is where the timeline is (scene or + /// symbol, and the instances opened to reach it); `stack` the symbols it is inside. + fn timeline(&mut self, tl: &Timeline, key: &str, depth: usize, go: &Go, stack: &[SymbolId]) { + if depth > MAX_DEPTH { + return; + } + let mut skip_to = 0usize; + for (i, l) in tl.layers.iter().enumerate() { + if self.full() { + return; + } + if i < skip_to { + continue; + } + let lkey = format!("{key}/l{}", l.id.0); + let lgo = Go { layer: Some(l.id), ..go.clone() }; + if self.o.show.frames { + let d = depth + tl.depth(i).min(MAX_DEPTH); + let folder = l.kind == LayerKind::Folder; + let children = if folder { tl.group_range(i).len() > 1 } else { l.keyframes.iter().any(|k| self.frame_items(k)) }; + let open = children && self.open(&lkey, d); + if !self.push(Row { key: lkey.clone(), depth: d, kind: NodeKind::Layer(l.kind), name: l.name.clone(), extra: String::new(), frame: None, children, open, go: lgo.clone() }) { + return; + } + if folder { + if !open { + skip_to = tl.group_range(i).end; + } + continue; + } + if !open { + continue; + } + for k in &l.keyframes { + if !self.frame_items(k) { + continue; + } + let kkey = format!("{lkey}/k{}", k.start); + let kgo = Go { frame: Some(k.start), ..lgo.clone() }; + let children = self.keyframe_has(k); + let open = children && self.open(&kkey, d + 1); + if !self.push(Row { key: kkey.clone(), depth: d + 1, kind: NodeKind::Frame, name: k.label.clone(), extra: String::new(), frame: Some(k.start), children, open, go: kgo.clone() }) { + return; + } + if open { + self.keyframe(k, &kkey, d + 2, &kgo, stack); + } + } + } else { + for k in &l.keyframes { + let kkey = format!("{lkey}/k{}", k.start); + let kgo = Go { frame: Some(k.start), ..lgo.clone() }; + self.keyframe(k, &kkey, depth, &kgo, stack); + } + } + } + } + + /// Whether a keyframe row has children (its label alone makes the row, not children). + fn keyframe_has(&self, k: &Keyframe) -> bool { + let s = self.o.show; + (s.scripts && k.script.is_some()) || (s.media && k.sound.is_some()) || anicraft_doc::expand_groups(&k.elements).iter().any(|e| self.element_shows(e)) + } + + fn element_shows(&self, e: &anicraft_doc::Element) -> bool { + let s = self.o.show; + match &e.kind { + ElementKind::Symbol { .. } => s.symbols, + ElementKind::Text(_) => s.text, + ElementKind::Shape(sh) => s.media && matches!(sh.fill, Some(Paint::Bitmap { .. })), + ElementKind::Camera | ElementKind::Group { .. } => false, + } + } + + /// What is on keyframe `k`: its script, its sound, then its elements. + fn keyframe(&mut self, k: &Keyframe, key: &str, depth: usize, go: &Go, stack: &[SymbolId]) { + let s = self.o.show; + let leaf = |key: String, kind: NodeKind, name: String, extra: String, go: Go| Row { key, depth, kind, name, extra, frame: Some(k.start), children: false, open: false, go }; + if s.scripts + && let Some(script) = &k.script + { + let name = match script { + FrameScript::Source(src) => line(&src.text), + other => line(&other.describe()), + }; + if !self.push(leaf(format!("{key}/x"), NodeKind::Script, name, String::new(), go.clone())) { + return; + } + } + if s.media + && let Some(fs) = &k.sound + { + let name = self.doc.sound(fs.sound).map(|x| x.name.clone()).unwrap_or_default(); + if !self.push(leaf(format!("{key}/a"), NodeKind::Sound, name, fs.sync.key().to_string(), go.clone())) { + return; + } + } + // What is inside a group is listed as on its keyframe (ADR 0073). + for e in anicraft_doc::expand_groups(&k.elements).iter() { + if self.full() || !self.element_shows(e) { + continue; + } + let ekey = format!("{key}/e{}", e.id.0); + let ego = Go { element: Some(e.id), ..go.clone() }; + match &e.kind { + ElementKind::Symbol { symbol, events, .. } => { + let sym = self.syms.get(symbol).copied(); + let nested = sym.filter(|_| !stack.contains(symbol) && stack.len() < MAX_DEPTH); + let children = (s.scripts && !events.is_empty()) || nested.is_some_and(|sym| self.has_items(&sym.timeline)); + let open = children && self.open(&ekey, depth); + let row = Row { + key: ekey.clone(), + depth, + kind: NodeKind::Instance(sym.map_or(SymbolKind::Graphic, |x| x.kind)), + name: sym.map_or_else(String::new, |x| x.name.clone()), + extra: e.name.clone(), + frame: Some(k.start), + children, + open, + go: ego.clone(), + }; + if !self.push(row) || !open { + continue; + } + if s.scripts { + for (n, h) in events.iter().enumerate() { + let desc = h.actions.iter().map(anicraft_doc::Action::describe).collect::>().join("; "); + if !self.push(Row { key: format!("{ekey}/h{n}"), depth: depth + 1, kind: NodeKind::Handler, name: h.event.key().to_string(), extra: line(&desc), frame: Some(k.start), children: false, open: false, go: ego.clone() }) { + return; + } + } + } + if let Some(sym) = nested { + // Inside: the symbol's own timeline, reached by opening this instance. + let (Some(layer), Some(frame)) = (go.layer, go.frame) else { continue }; + let mut inner = Go { scene: go.scene, symbol: go.symbol, path: go.path.clone(), layer: None, frame: None, element: None }; + inner.path.push(Step { layer, frame, element: e.id }); + let mut st = stack.to_vec(); + st.push(*symbol); + self.timeline(&sym.timeline, &ekey, depth + 1, &inner, &st); + } + } + ElementKind::Text(t) => { + if !self.push(leaf(ekey, NodeKind::Text, line(&t.text), format!("{} {}", t.font, t.size), ego)) { + return; + } + } + ElementKind::Shape(sh) => { + let name = match &sh.fill { + Some(Paint::Bitmap { bitmap, .. }) => self.doc.bitmap(*bitmap).map(|b| b.name.clone()).unwrap_or_default(), + _ => String::new(), + }; + if !self.push(leaf(ekey, NodeKind::Bitmap, name, e.name.clone(), ego)) { + return; + } + } + ElementKind::Camera | ElementKind::Group { .. } => {} + } + } + } +} + +/// The rows showing for `o`, from scene `scene` (the scope's scene). +pub fn tree(doc: &Document, scene: usize, o: &Options) -> Tree { + let filter = o.filter.trim().to_lowercase(); + let mut w = Walk { doc, syms: doc.library.iter().map(|s| (s.id, &**s)).collect(), o, every: o.all || !filter.is_empty(), rows: Vec::new(), truncated: false }; + let scenes: Vec = match o.scope { + Scope::Document => (0..doc.scenes.len()).collect(), + Scope::Scene => vec![scene.min(doc.scenes.len().saturating_sub(1))], + }; + for i in scenes { + let Some(sc) = doc.scenes.get(i) else { continue }; + let key = format!("s{i}"); + let children = w.has_items(&sc.timeline); + let open = children && w.open(&key, 0); + let go = Go { scene: Some(i), ..Go::default() }; + if !w.push(Row { key: key.clone(), depth: 0, kind: NodeKind::Scene, name: sc.name.clone(), extra: String::new(), frame: None, children, open, go: go.clone() }) { + break; + } + if open { + w.timeline(&sc.timeline, &key, 1, &go, &[]); + } + } + if o.definitions && !doc.library.is_empty() && !w.full() { + let open = w.open("d", 0); + w.push(Row { key: "d".into(), depth: 0, kind: NodeKind::Definitions, name: String::new(), extra: String::new(), frame: None, children: true, open, go: Go::default() }); + if open { + for sym in &doc.library { + let key = format!("d/y{}", sym.id.0); + let children = w.has_items(&sym.timeline); + let open = children && w.open(&key, 1); + let go = Go { symbol: Some(sym.id), ..Go::default() }; + if !w.push(Row { key: key.clone(), depth: 1, kind: NodeKind::Symbol(sym.kind), name: sym.name.clone(), extra: String::new(), frame: None, children, open, go: go.clone() }) { + break; + } + if open { + w.timeline(&sym.timeline, &key, 2, &go, &[sym.id]); + } + } + } + } + let Walk { mut rows, truncated, .. } = w; + if !filter.is_empty() { + rows = filtered(rows, &filter); + } + Tree { rows, truncated } +} + +/// The rows whose name or extra text holds `needle` (lower case), with every row above them. +fn filtered(rows: Vec, needle: &str) -> Vec { + let hit = |r: &Row| r.name.to_lowercase().contains(needle) || r.extra.to_lowercase().contains(needle); + let mut keep = vec![false; rows.len()]; + // The nearest row above at each depth. + let mut above: Vec = Vec::new(); + for (i, r) in rows.iter().enumerate() { + above.truncate(r.depth); + if hit(r) { + if let Some(k) = keep.get_mut(i) { + *k = true; + } + for &a in &above { + if let Some(k) = keep.get_mut(a) { + *k = true; + } + } + } + // (Depths can skip, inside folders: keep the stack's indices in order.) + while above.len() < r.depth { + above.push(above.last().copied().unwrap_or(i)); + } + above.push(i); + } + rows.into_iter().zip(keep).filter_map(|(r, k)| k.then_some(r)).collect() +} + +fn opt_flag(v: &Value, key: &str) -> Result { + Ok(opt_bool(v, key)?.unwrap_or(true)) +} + +/// The options in `p` (`explorer.tree`'s params). +pub fn options_of(p: &Value) -> Result { + let scope = match opt_str(p, "scope")? { + None | Some("document") => Scope::Document, + Some("scene") => Scope::Scene, + Some(o) => return Err(EngineError::Param(format!("'scope' is document or scene, not '{o}'"))), + }; + let show = match p.get("show") { + None | Some(Value::Null) => Show::default(), + Some(v) if v.is_object() => Show { text: opt_flag(v, "text")?, symbols: opt_flag(v, "symbols")?, scripts: opt_flag(v, "scripts")?, media: opt_flag(v, "media")?, frames: opt_flag(v, "frames")? }, + Some(_) => return Err(EngineError::Param("'show' must be {text?, symbols?, scripts?, media?, frames?}".into())), + }; + let expanded = match p.get("expanded") { + None | Some(Value::Null) => None, + Some(Value::Array(list)) => { + if list.len() > MAX_ROWS { + return Err(EngineError::Param(format!("'expanded' names at most {MAX_ROWS} rows"))); + } + Some(list.iter().map(|v| v.as_str().map(str::to_string).ok_or_else(|| EngineError::Param("'expanded' must be a list of row keys".into()))).collect::>>()?) + } + Some(_) => return Err(EngineError::Param("'expanded' must be a list of row keys".into())), + }; + let filter: String = opt_str(p, "filter")?.unwrap_or("").chars().take(256).collect(); + Ok(Options { scope, show, definitions: opt_bool(p, "definitions")?.unwrap_or(true), expanded, all: opt_bool(p, "all")?.unwrap_or(false), filter }) +} + +fn tree_cmd(s: &mut Session, p: &Value) -> Result { + let o = options_of(p)?; + let offset = opt_u64(p, "offset")?.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)); + let limit = opt_u64(p, "limit")?.map_or(DEFAULT_LIMIT, |n| usize::try_from(n).unwrap_or(MAX_LIMIT)).min(MAX_LIMIT); + let t = tree(&s.doc, s.scene, &o); + let rows: Vec = t.rows.iter().skip(offset).take(limit).map(Row::to_json).collect(); + Ok(json!({"rows": rows, "total": t.rows.len(), "offset": offset, "truncated": t.truncated})) +} + +#[cfg(test)] +#[path = "explorer_tests.rs"] +mod tests; diff --git a/crates/engine/src/explorer_tests.rs b/crates/engine/src/explorer_tests.rs new file mode 100644 index 00000000..49f08566 --- /dev/null +++ b/crates/engine/src/explorer_tests.rs @@ -0,0 +1,205 @@ +//! The Movie Explorer's tree (ADR 0058): its shape for scenes and nested symbols, open rows, +//! the show filters and the text filter, folders, symbols that hold themselves, paging, jumping +//! to a row, and a large document. + +use super::*; +use crate::find::tests::{Build, movie}; +use anicraft_doc::{LayerKind, Paint, Rgba, SymbolKind}; +use serde_json::json; + +fn keys_of(t: &Tree) -> Vec<(usize, NodeKind, String)> { + t.rows.iter().map(|r| (r.depth, r.kind, r.name.clone())).collect() +} + +fn all() -> Options { + Options { all: true, ..Options::default() } +} + +#[test] +fn the_top_rows_show_scenes_their_layers_and_the_library() { + let (s, ..) = movie(); + let t = tree(&s.doc, 0, &Options::default()); + let names: Vec<(usize, &str)> = t.rows.iter().map(|r| (r.depth, r.name.as_str())).collect(); + assert_eq!(names, [(0, "Scene 1"), (1, "Actions"), (1, "Art"), (0, "Scene 2"), (1, "Back"), (0, ""), (1, "Outer"), (1, "Inner"), (1, "Unused")]); + assert!(t.rows[1].children && !t.rows[1].open); + // Scene 2's only layer holds a plain shape: nothing to list under it. + assert!(!t.rows[4].children); + assert_eq!(t.rows[5].kind, NodeKind::Definitions); + assert_eq!(t.rows[6].kind, NodeKind::Symbol(SymbolKind::MovieClip)); + // Scope: one scene. + let one = tree(&s.doc, 1, &Options { scope: Scope::Scene, definitions: false, ..Options::default() }); + assert_eq!(one.rows.iter().map(|r| r.name.as_str()).collect::>(), ["Scene 2", "Back"]); +} + +#[test] +fn instances_open_into_their_symbols_layers_however_deep() { + let (s, outer, inner, _) = movie(); + let t = tree(&s.doc, 0, &all()); + let scene1: Vec<(usize, NodeKind, String)> = keys_of(&t).into_iter().take_while(|r| r.2 != "Scene 2").collect(); + let want = [ + (0, NodeKind::Scene, "Scene 1"), + (1, NodeKind::Layer(LayerKind::Normal), "Actions"), + (2, NodeKind::Frame, ""), + (3, NodeKind::Script, "stop(); // say hello"), + (1, NodeKind::Layer(LayerKind::Normal), "Art"), + (2, NodeKind::Frame, ""), + (3, NodeKind::Text, "Hello world"), + (3, NodeKind::Instance(SymbolKind::MovieClip), "Outer"), + (4, NodeKind::Layer(LayerKind::Normal), "Outer art"), + (5, NodeKind::Frame, ""), + (6, NodeKind::Instance(SymbolKind::Graphic), "Inner"), + (7, NodeKind::Layer(LayerKind::Normal), "Inner art"), + (8, NodeKind::Frame, ""), + (9, NodeKind::Text, "Hello inside"), + (2, NodeKind::Frame, "intro hello"), + (3, NodeKind::Text, "hello hello again"), + ]; + let want: Vec<(usize, NodeKind, String)> = want.iter().map(|(d, k, n)| (*d, *k, n.to_string())).collect(); + assert_eq!(scene1, want); + // The instance row names the instance too, and its frame. + let hero = t.rows.iter().find(|r| r.extra == "hero").unwrap(); + assert_eq!((hero.frame, hero.children, hero.open), (Some(0), true, true)); + // The deepest text: reached by opening hero, then wheel, in place. + let deep = t.rows.iter().find(|r| r.depth == 9).unwrap(); + assert_eq!(deep.go.path.len(), 2); + assert_eq!(deep.go.scene, Some(0)); + let mut s = s; + let v = s.execute("find.goto", &deep.go.to_json()).unwrap(); + assert_eq!(s.editing.iter().map(|l| l.symbol().unwrap_or(SymbolId(0))).collect::>(), [outer, inner], "{v}"); + assert_eq!(s.selection.id_list(), [deep.go.element.unwrap().0]); + // Under the Library's Outer: its own layers, then Inner inside it. + let defs: Vec<(usize, String)> = t.rows.iter().skip_while(|r| r.kind != NodeKind::Definitions).map(|r| (r.depth, r.name.clone())).take(8).collect(); + assert_eq!(defs, [(0, String::new()), (1, "Outer".into()), (2, "Outer art".into()), (3, String::new()), (4, "Inner".into()), (5, "Inner art".into()), (6, String::new()), (7, "Hello inside".into())]); + // Keys are unique, so open rows can be remembered. + let mut keys: Vec<&str> = t.rows.iter().map(|r| r.key.as_str()).collect(); + keys.sort_unstable(); + keys.dedup(); + assert_eq!(keys.len(), t.rows.len()); +} + +#[test] +fn only_open_rows_show_their_children() { + let (s, ..) = movie(); + let art = s.doc.timeline(0).layers[1].id.0; + let t = tree(&s.doc, 0, &Options { expanded: Some(["s0".to_string(), format!("s0/l{art}")].into()), definitions: false, ..Options::default() }); + let names: Vec<&str> = t.rows.iter().map(|r| r.name.as_str()).collect(); + assert_eq!(names, ["Scene 1", "Actions", "Art", "", "intro hello", "Scene 2"]); + assert!(t.rows[3].children && !t.rows[3].open); +} + +#[test] +fn show_filters_hide_kinds_and_frames_off_lists_items_straight_under_the_scene() { + let (s, ..) = movie(); + let no_symbols = tree(&s.doc, 0, &Options { show: Show { symbols: false, ..Show::default() }, definitions: false, ..all() }); + assert!(no_symbols.rows.iter().all(|r| !matches!(r.kind, NodeKind::Instance(_)))); + assert!(!no_symbols.rows.iter().any(|r| r.name == "Hello inside")); + let flat = tree(&s.doc, 0, &Options { show: Show { frames: false, ..Show::default() }, definitions: false, scope: Scope::Scene, ..all() }); + let names: Vec<(usize, &str)> = flat.rows.iter().map(|r| (r.depth, r.name.as_str())).collect(); + assert_eq!(names, [(0, "Scene 1"), (1, "stop(); // say hello"), (1, "Hello world"), (1, "Outer"), (2, "Inner"), (3, "Hello inside"), (1, "hello hello again")]); + let no_scripts = tree(&s.doc, 0, &Options { show: Show { scripts: false, ..Show::default() }, ..all() }); + assert!(no_scripts.rows.iter().all(|r| r.kind != NodeKind::Script && r.name != "Actions" || !r.children)); +} + +#[test] +fn the_text_filter_keeps_matches_and_the_rows_above_them() { + let (s, ..) = movie(); + let t = tree(&s.doc, 0, &Options { filter: "INSIDE".into(), ..Options::default() }); + let texts = t.rows.iter().filter(|r| r.kind == NodeKind::Text).count(); + assert_eq!(texts, 3, "{:?}", keys_of(&t)); + // Each row is a match or above one: its next row is deeper, or it matches. + for (i, r) in t.rows.iter().enumerate() { + let matches = r.name.to_lowercase().contains("inside"); + let parent = t.rows.get(i + 1).is_some_and(|n| n.depth > r.depth); + assert!(matches || parent, "{r:?}"); + } + assert!(tree(&s.doc, 0, &Options { filter: "zebra".into(), ..Options::default() }).rows.is_empty()); + // The instance name counts too. + assert!(tree(&s.doc, 0, &Options { filter: "wheel".into(), ..Options::default() }).rows.iter().any(|r| r.extra == "wheel")); +} + +#[test] +fn closed_folders_hide_the_layers_in_them() { + let mut b = Build::new(); + let t1 = b.text("one", Rgba::BLACK); + let t2 = b.text("two", Rgba::BLACK); + let mut folder = b.layer("Folder", vec![(0, 1, "", vec![])]); + folder.kind = LayerKind::Folder; + let mut a = b.layer("A", vec![(0, 1, "", vec![t1])]); + a.parent = Some(folder.id); + let c = b.layer("C", vec![(0, 1, "", vec![t2])]); + let fid = folder.id.0; + b.scene("S", vec![folder, a, c]); + let doc = crate::Session::new(b.doc).doc; + let closed = tree(&doc, 0, &Options { expanded: Some(["s0".to_string()].into()), ..Options::default() }); + assert_eq!(closed.rows.iter().map(|r| (r.depth, r.name.as_str())).collect::>(), [(0, "S"), (1, "Folder"), (1, "C")]); + let open = tree(&doc, 0, &Options { expanded: Some(["s0".to_string(), format!("s0/l{fid}")].into()), ..Options::default() }); + assert_eq!(open.rows.iter().map(|r| (r.depth, r.name.as_str())).collect::>(), [(0, "S"), (1, "Folder"), (2, "A"), (1, "C")]); +} + +#[test] +fn symbols_that_hold_themselves_stop() { + let mut b = Build::new(); + let a = b.symbol("A", SymbolKind::Graphic); + let c = b.symbol("B", SymbolKind::Graphic); + let (ia, ib, self_a) = (b.instance(c, ""), b.instance(a, ""), b.instance(a, "me")); + let l = b.layer("in A", vec![(0, 1, "", vec![ia, self_a])]); + b.fill(a, vec![l]); + let l = b.layer("in B", vec![(0, 1, "", vec![ib])]); + b.fill(c, vec![l]); + let top = b.instance(a, ""); + let l = b.layer("L", vec![(0, 1, "", vec![top])]); + b.scene("S", vec![l]); + let t = tree(&b.doc, 0, &all()); + assert!(t.rows.len() < 40 && !t.truncated, "{}", t.rows.len()); + assert!(t.rows.iter().all(|r| r.depth <= MAX_DEPTH)); +} + +#[test] +fn the_command_pages_rows_with_where_each_goes() { + let (mut s, ..) = movie(); + let v = s.execute("explorer.tree", &json!({"all": true, "offset": 2, "limit": 3})).unwrap(); + assert_eq!(v["rows"].as_array().map(Vec::len), Some(3)); + assert!(v["total"].as_u64().unwrap() > 20); + let r = &v["rows"][1]; + assert_eq!((r["kind"].as_str(), r["depth"].as_u64(), r["name"].as_str()), (Some("script"), Some(3), Some("stop(); // say hello"))); + assert_eq!(r["go"]["frame"], 0); + let v = s.execute("explorer.tree", &json!({"all": true, "show": {"text": false, "scripts": false, "media": false, "frames": false}, "definitions": false})).unwrap(); + let kinds: Vec<&str> = v["rows"].as_array().unwrap().iter().map(|r| r["kind"].as_str().unwrap()).collect(); + assert_eq!(kinds, ["scene", "instance", "instance", "scene"]); + assert_eq!(v["rows"][1]["type"], "movie_clip"); + assert!(s.execute("explorer.tree", &json!({"scope": "galaxy"})).is_err()); + assert!(s.execute("explorer.tree", &json!({"expanded": [1]})).is_err()); +} + +#[test] +fn a_large_movie_makes_its_tree_quickly() { + // 100 layers × 120 keyframes, each with a text and an instance of a symbol of 3 layers. + let mut b = Build::new(); + let sym = b.symbol("Prop", SymbolKind::MovieClip); + let inner: Vec<_> = (0..3).map(|i| { + let r = b.rect(Paint::Solid(Rgba::BLACK), None); + let t = b.text("label", Rgba::BLACK); + b.layer(&format!("p{i}"), vec![(0, 1, "", vec![r, t])]) + }).collect(); + b.fill(sym, inner); + let mut layers = Vec::new(); + for li in 0..100 { + let keys: Vec<_> = (0..120).map(|k| (k, 1, "", vec![b.text(&format!("t {li} {k}"), Rgba::BLACK), b.instance(sym, "")])).collect(); + layers.push(b.layer(&format!("Layer {li}"), keys)); + } + b.scene("Big", layers); + let doc = b.doc; + let t0 = std::time::Instant::now(); + let open = tree(&doc, 0, &all()); + let every = t0.elapsed(); + let t0 = std::time::Instant::now(); + let top = tree(&doc, 0, &Options::default()); + let closed = t0.elapsed(); + let t0 = std::time::Instant::now(); + let found = tree(&doc, 0, &Options { filter: "t 99 119".into(), ..Options::default() }); + let filtered = t0.elapsed(); + println!("Movie Explorer on 24,000 elements: everything open {every:?} ({} rows), top rows {closed:?} ({} rows), filtered {filtered:?} ({} rows)", open.rows.len(), top.rows.len(), found.rows.len()); + assert!(open.rows.len() > 100_000 && !open.truncated); + assert_eq!(found.rows.iter().filter(|r| r.kind == NodeKind::Text).count(), 1); + assert!(every.as_secs_f64() < 3.0 && closed.as_secs_f64() < 0.5); +} diff --git a/crates/engine/src/eyedropper_tests.rs b/crates/engine/src/eyedropper_tests.rs index 18efa673..7b99125b 100644 --- a/crates/engine/src/eyedropper_tests.rs +++ b/crates/engine/src/eyedropper_tests.rs @@ -26,7 +26,7 @@ fn rect(s: &mut Session, x: f32, fill: &str) -> u64 { /// A linear gradient across the shape's own width (local space: the shape is centred on 0). fn gradient() -> Paint { - Paint::Linear { start: Vec2::new(-50.0, 0.0), end: Vec2::new(50.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff8800) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0044ff) }] } + Paint::linear(Vec2::new(-50.0, 0.0), Vec2::new(50.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff8800) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0044ff) }]) } #[test] diff --git a/crates/engine/src/filter_library.rs b/crates/engine/src/filter_library.rs new file mode 100644 index 00000000..f3a0f4ad --- /dev/null +++ b/crates/engine/src/filter_library.rs @@ -0,0 +1,236 @@ +//! Filter presets (ADR 0091): named filter lists of the user's own, as Animate's Filters panel +//! keeps them (Save as Preset, apply, rename, delete). +//! +//! Like the user's brushes (ADR 0068) the presets belong to the session, not the document: they +//! survive New and Open, the desktop app keeps them in its preferences and puts them back at +//! start (so the engine never reads the settings folder), and they move between computers as a +//! small JSON file (`filter.preset_export`/`_import`). Applying one copies its list onto the +//! instances: a preset edited or deleted later never changes artwork behind the artist's back. + +use crate::{EngineError, Result}; +use anicraft_doc::FilterEntry; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Most presets. +pub const MAX_PRESETS: usize = 200; +/// Longest preset name, in characters. +pub const MAX_NAME: usize = 64; +/// Most filters on one instance (and so in one preset). +pub const MAX_FILTERS: usize = 16; +/// Largest preset file read. +pub const MAX_FILE_BYTES: u64 = 1 << 20; +/// What a preset file says it is. +pub const FILE_FORMAT: &str = "anicraft-filter-presets"; +pub const FILE_VERSION: u32 = 1; + +/// A named filter list. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct FilterPreset { + pub name: String, + #[serde(default)] + pub filters: Vec, +} + +impl FilterPreset { + /// The preset with a clean name and its filters in range (at most [`MAX_FILTERS`]); `None` + /// when the name is empty. + pub fn sanitized(self) -> Option { + let name = clean_name(&self.name)?; + Some(FilterPreset { name, filters: self.filters.iter().take(MAX_FILTERS).map(FilterEntry::sanitized).collect() }) + } +} + +/// A name as kept: one line, trimmed, at most [`MAX_NAME`] characters; `None` when empty. +pub fn clean_name(s: &str) -> Option { + 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) +} + +fn same_name(a: &str, b: &str) -> bool { + a.trim().to_lowercase() == b.trim().to_lowercase() +} + +/// The user's filter presets, in the order they were saved; names are unique, case aside. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct FilterLibrary { + presets: Vec, +} + +#[derive(Serialize, Deserialize)] +struct PresetFile { + format: String, + version: u32, + presets: Vec, +} + +impl FilterLibrary { + pub fn presets(&self) -> &[FilterPreset] { + &self.presets + } + + pub fn is_empty(&self) -> bool { + self.presets.is_empty() + } + + /// A library from untrusted entries (preferences, a file): bad entries skipped, values + /// clamped, names made unique, at most [`MAX_PRESETS`]. + pub fn from_values(values: impl IntoIterator) -> FilterLibrary { + let mut lib = FilterLibrary::default(); + for v in values.into_iter().take(MAX_PRESETS * 4) { + if let Ok(p) = serde_json::from_value::(v) { + let _ = lib.add_unique(p); + } + } + lib + } + + /// The same library with every entry sanitized (after deserializing preferences). + pub fn sanitized(self) -> FilterLibrary { + FilterLibrary::from_values(self.presets.into_iter().filter_map(|p| serde_json::to_value(p).ok())) + } + + pub fn position(&self, name: &str) -> Option { + self.presets.iter().position(|p| same_name(&p.name, name)) + } + + pub fn find(&self, name: &str) -> Option<&FilterPreset> { + self.position(name).and_then(|i| self.presets.get(i)) + } + + fn missing(name: &str) -> EngineError { + EngineError::Param(format!("you have no filter preset named '{}'", name.chars().take(MAX_NAME).collect::())) + } + + /// Saves `filters` under `name`, replacing the preset of that name. Returns the name kept + /// and whether it replaced one. + pub fn save(&mut self, name: &str, filters: &[FilterEntry]) -> Result<(String, bool)> { + let p = FilterPreset { name: name.to_string(), filters: filters.to_vec() }.sanitized().ok_or_else(|| EngineError::Param("a filter preset needs a name".into()))?; + if p.filters.is_empty() { + return Err(EngineError::State("there are no filters to save; add one first".into())); + } + let name = p.name.clone(); + if let Some(i) = self.position(&name) + && let Some(slot) = self.presets.get_mut(i) + { + // The name as written now (the case may differ). + *slot = p; + return Ok((name, true)); + } + if self.presets.len() >= MAX_PRESETS { + return Err(EngineError::State(format!("you have {MAX_PRESETS} filter presets already; delete some first"))); + } + self.presets.push(p); + Ok((name, false)) + } + + /// Adds `p`, renaming it ("Glow 2", "Glow 3", ..) if the name is taken. Returns its name. + pub fn add_unique(&mut self, p: FilterPreset) -> Result { + let p = p.sanitized().ok_or_else(|| EngineError::Param("a filter preset needs a name".into()))?; + if self.presets.len() >= MAX_PRESETS { + return Err(EngineError::State(format!("you have {MAX_PRESETS} filter presets already; delete some first"))); + } + let base = p.name.clone(); + let mut name = base.clone(); + let mut k = 2; + while self.position(&name).is_some() { + if k > MAX_PRESETS + 10 { + return Err(EngineError::State("too many filter presets of that name".into())); + } + let suffix = format!(" {k}"); + name = format!("{}{suffix}", base.chars().take(MAX_NAME.saturating_sub(suffix.chars().count())).collect::().trim_end()); + k += 1; + } + self.presets.push(FilterPreset { name: name.clone(), ..p }); + Ok(name) + } + + pub fn rename(&mut self, name: &str, to: &str) -> Result { + let i = self.position(name).ok_or_else(|| Self::missing(name))?; + let to = clean_name(to).ok_or_else(|| EngineError::Param("a filter preset needs a name".into()))?; + if self.position(&to).is_some_and(|j| j != i) { + return Err(EngineError::Param(format!("you already have a filter preset named '{to}'"))); + } + if let Some(p) = self.presets.get_mut(i) { + p.name = to.clone(); + } + Ok(to) + } + + pub fn delete(&mut self, name: &str) -> Result { + let i = self.position(name).ok_or_else(|| Self::missing(name))?; + Ok(self.presets.remove(i)) + } + + /// A preset file holding `presets`. + pub fn file_json(presets: &[FilterPreset]) -> String { + let f = PresetFile { format: FILE_FORMAT.into(), version: FILE_VERSION, presets: 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 preset file (bad entries skipped; values clamped). + pub fn parse_file(text: &str) -> Result> { + let f: PresetFile = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("not a filter preset file: {e}")))?; + if f.format != FILE_FORMAT { + return Err(EngineError::Param(format!("not a filter preset file (its format is '{}')", f.format.chars().take(40).collect::()))); + } + if f.version > FILE_VERSION { + return Err(EngineError::Param(format!("this filter preset file is version {}, newer than this AniCraft reads ({FILE_VERSION})", f.version))); + } + Ok(f.presets.into_iter().take(MAX_PRESETS * 4).filter_map(|v| serde_json::from_value::(v).ok()).filter_map(FilterPreset::sanitized).collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_doc::Filter; + + fn blur(b: f32) -> FilterEntry { + Filter::Blur { blur_x: b, blur_y: b, quality: 1 }.into() + } + + #[test] + fn saving_renaming_and_deleting() { + let mut lib = FilterLibrary::default(); + assert_eq!(lib.save(" Soft \n glow ", &[blur(4.0)]).unwrap(), ("Soft glow".to_string(), false)); + assert!(lib.save("soft GLOW", &[blur(8.0), blur(1e9)]).unwrap().1, "same name, case aside, replaces"); + assert_eq!(lib.presets().len(), 1); + assert_eq!(lib.presets()[0].filters[1], blur(anicraft_doc::MAX_BLUR), "values clamped"); + assert!(lib.save(" ", &[blur(1.0)]).is_err()); + assert!(lib.save("Empty", &[]).is_err(), "nothing to save"); + assert_eq!(lib.add_unique(FilterPreset { name: "soft glow".into(), filters: vec![blur(1.0)] }).unwrap(), "soft glow 2"); + assert_eq!(lib.rename("SOFT GLOW 2", "Haze").unwrap(), "Haze"); + assert!(lib.rename("Haze", "Soft Glow").is_err() && lib.rename("nope", "x").is_err() && lib.rename("Haze", " ").is_err()); + assert_eq!(lib.rename("haze", "HAZE").unwrap(), "HAZE", "a new case of its own name"); + assert_eq!(lib.find("haze").map(|p| p.filters.len()), Some(1)); + assert_eq!(lib.delete("haze").unwrap().name, "HAZE"); + assert!(lib.delete("haze").is_err()); + let long = "x".repeat(200); + assert_eq!(lib.save(&long, &[blur(1.0)]).unwrap().0.chars().count(), MAX_NAME); + } + + #[test] + fn preset_files_round_trip_and_reject_junk() { + let off = FilterEntry { filter: Filter::new("glow").unwrap(), enabled: false }; + let mine = vec![FilterPreset { name: "A".into(), filters: vec![blur(3.0), off] }, FilterPreset { name: "B".into(), filters: vec![Filter::new("bevel").unwrap().into()] }]; + let text = FilterLibrary::file_json(&mine); + assert!(text.contains("\"enabled\": false"), "a switched-off filter keeps its switch: {text}"); + assert_eq!(FilterLibrary::parse_file(&text).unwrap(), mine); + assert!(FilterLibrary::parse_file("{}").is_err()); + assert!(FilterLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 1, "presets": []}"#).is_err()); + assert!(FilterLibrary::parse_file(r#"{"format": "anicraft-filter-presets", "version": 99, "presets": []}"#).is_err()); + // Bad entries are skipped, values clamped, bare filters take their defaults. + let got = FilterLibrary::parse_file(r#"{"format": "anicraft-filter-presets", "version": 1, "presets": [7, {"name": ""}, {"name": "x", "filters": [{"type": "sparkle"}]}, {"name": "Old", "filters": [{"type": "blur", "blur_x": -4}, {"type": "glow"}]}]}"#).unwrap(); + assert_eq!(got.len(), 1); + assert_eq!(got[0].filters[0], Filter::Blur { blur_x: 0.0, blur_y: 5.0, quality: 1 }.into()); + assert!(matches!(got[0].filters[1], FilterEntry { filter: Filter::Glow { blur_x: 5.0, .. }, enabled: true })); + // Preferences: the library as a list, names made unique. + let lib = FilterLibrary::from_values(serde_json::from_str::>(&serde_json::to_string(&[mine[0].clone(), mine[0].clone()]).unwrap()).unwrap()); + assert_eq!(lib.presets().iter().map(|p| p.name.as_str()).collect::>(), ["A", "A 2"]); + assert_eq!(lib.clone().sanitized(), lib); + } +} diff --git a/crates/engine/src/find.rs b/crates/engine/src/find.rs new file mode 100644 index 00000000..ce601a20 --- /dev/null +++ b/crates/engine/src/find.rs @@ -0,0 +1,1120 @@ +//! Find and Replace (ADR 0058), as Animate's Edit › Find and Replace: text (in text fields, +//! frame labels, layer names, instance names and frame scripts), fonts, colours, symbols, sounds +//! and bitmaps, in the current scene (and the symbols it uses) or the whole document. +//! +//! `find.search` lists located hits; `find.replace` replaces one hit or all of them as one undo +//! step (asking first above [`REPLACE_ASK`] places, ADR 0004); `find.goto` jumps to a place: the +//! scene or symbol (opened in place through the instances that lead to it, ADR 0045), the layer, +//! the keyframe and the element, selected. The Movie Explorer (`explorer.tree`) navigates through +//! `find.goto` too. +//! +//! Text is matched with the `regex` crate, whose engine runs in time linear in the text and +//! refuses patterns that would compile too large, so no pattern can hang the editor. Plain text, +//! whole words and case are the same engine with an escaped pattern. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Selection, Session}; +use anicraft_doc::{BitmapId, Document, ElementId, ElementKind, FrameScript, LayerId, Paint, Rgba, SoundId, SourceScript, Symbol, SymbolId, Timeline}; +use regex::{Regex, RegexBuilder}; +use serde_json::{Value, json}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "find.search", + "Find and Replace", + "Edit", + Some("Ctrl+F"), + "{kind: text | font | color | symbol | sound | bitmap, text? (kind text: what to find), match_case?, whole_word?, regex? (a pattern; linear-time engine, size-limited), font? (family), color? (#rrggbb; alpha is ignored), symbol? | sound? | bitmap?: library id, in?: [text, labels, layers, instances, scripts] (kind text) | [fills, strokes, text] (kind color) (default: all), scope?: scene (the current scene and the symbols it uses; default) | document, offset?, limit? (default 500, at most 10000)} → {hits: [{kind, field, scene | symbol, layer, layer_name, frame (keyframe start; null on a layer name), element?, start, end (characters, text only), found, context}], total, truncated}", + false, + search_cmd as crate::RunFn, + ), + c( + "find.replace", + "Replace", + "", + None, + "{the find.search query, with: text (kind text; $1 and ${name} insert groups when regex) | family (font) | #rrggbb (color; each place keeps its alpha) | library id (symbol, sound, bitmap), at?: one hit as find.search returned it (Replace); without `at`, every hit (Replace All, one undo step; asks first above 100 places)} → {replaced, skipped, notes}", + true, + replace_cmd, + ), + c( + "find.goto", + "Go to Found Item", + "", + None, + "{layer?: id (its scene or symbol is found), scene?: index, symbol?: id, path?: [{layer, frame, element}] (instances to open in place from `scene`, or from `symbol` opened alone), frame?, element?} goes there: closes open symbols, switches scene or opens the symbol (in place through an instance that uses it when there is one), picks the layer and frame and selects the element", + false, + goto_cmd, + ), + ] +} + +/// Longest text to find (characters). +pub const MAX_QUERY_CHARS: usize = 1_000; +/// Most hits one search keeps. +pub const MAX_HITS: usize = 100_000; +/// Replace All asks first when it would change more places than this (ADR 0004). +pub const REPLACE_ASK: usize = 100; +/// Most a compiled pattern may take (bytes), and its lazy DFA. +const REGEX_LIMIT: usize = 1 << 20; +const DEFAULT_LIMIT: usize = 500; +const MAX_LIMIT: usize = 10_000; +/// Characters of context shown on each side of a text match. +const CONTEXT: usize = 32; +/// Most instances opened in place to reach a symbol (`editing`'s limit). +const MAX_ROUTE: usize = 32; + +/// What is searched for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Text, + Font, + Color, + Symbol, + Sound, + Bitmap, +} + +impl Kind { + pub const ALL: [Kind; 6] = [Kind::Text, Kind::Font, Kind::Color, Kind::Symbol, Kind::Sound, Kind::Bitmap]; + + pub fn key(self) -> &'static str { + match self { + Kind::Text => "text", + Kind::Font => "font", + Kind::Color => "color", + Kind::Symbol => "symbol", + Kind::Sound => "sound", + Kind::Bitmap => "bitmap", + } + } + + pub fn from_key(s: &str) -> Option { + Kind::ALL.into_iter().find(|k| k.key() == s || (s == "colour" && *k == Kind::Color)) + } +} + +/// Where a search looks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Scope { + /// The current scene, and every symbol it uses (however deep). + #[default] + Scene, + /// Every scene and every symbol in the Library, used or not. + Document, +} + +/// A timeline of the document: a scene's, or a Library symbol's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Where { + Scene(usize), + Symbol(SymbolId), +} + +/// The part of the document a hit is in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Field { + /// A text field's text. + Text, + /// A keyframe's label. + Label, + LayerName, + /// An element's instance name. + InstanceName, + /// A keyframe's script source. + Script, + /// A text field's font. + Font, + /// A shape's fill (solid or a gradient stop), stroke, or a text field's colour. + Fill, + Stroke, + TextColor, + /// A symbol instance. + Instance, + /// A keyframe's sound. + Sound, + /// A shape filled with a bitmap (a placed bitmap is one). + Bitmap, +} + +impl Field { + pub const ALL: [Field; 12] = [Field::Text, Field::Label, Field::LayerName, Field::InstanceName, Field::Script, Field::Font, Field::Fill, Field::Stroke, Field::TextColor, Field::Instance, Field::Sound, Field::Bitmap]; + + pub fn key(self) -> &'static str { + match self { + Field::Text => "text", + Field::Label => "label", + Field::LayerName => "layer_name", + Field::InstanceName => "instance_name", + Field::Script => "script", + Field::Font => "font", + Field::Fill => "fill", + Field::Stroke => "stroke", + Field::TextColor => "text_color", + Field::Instance => "instance", + Field::Sound => "sound", + Field::Bitmap => "bitmap", + } + } + + pub fn from_key(s: &str) -> Option { + Field::ALL.into_iter().find(|f| f.key() == s) + } +} + +/// Which places a text or colour search looks in (the others ignore it). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Within { + pub text: bool, + pub labels: bool, + pub layers: bool, + pub instances: bool, + pub scripts: bool, + pub fills: bool, + pub strokes: bool, + pub text_color: bool, +} + +impl Default for Within { + fn default() -> Self { + Within { text: true, labels: true, layers: true, instances: true, scripts: true, fills: true, strokes: true, text_color: true } + } +} + +/// What a query matches. +#[derive(Clone, Debug)] +pub enum Needle { + Text { re: Regex, expand: bool }, + /// A family name, lower-cased and trimmed. + Font(String), + Color([u8; 3]), + Symbol(SymbolId), + Sound(SoundId), + Bitmap(BitmapId), +} + +/// A checked search. +#[derive(Clone, Debug)] +pub struct Query { + pub needle: Needle, + pub within: Within, + pub scope: Scope, +} + +/// The text options of a text search, as the Find and Replace window holds them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct TextOptions { + pub match_case: bool, + pub whole_word: bool, + pub regex: bool, +} + +/// Compiles `text` as a bounded pattern. +pub fn text_needle(text: &str, o: TextOptions) -> Result { + if text.is_empty() { + return Err(EngineError::Param("type something to find".into())); + } + if text.chars().count() > MAX_QUERY_CHARS { + return Err(EngineError::Param(format!("what to find is at most {MAX_QUERY_CHARS} characters"))); + } + let body = if o.regex { text.to_string() } else { regex::escape(text) }; + let pattern = if o.whole_word { format!(r"\b(?:{body})\b") } else { body }; + let re = RegexBuilder::new(&pattern) + .case_insensitive(!o.match_case) + .size_limit(REGEX_LIMIT) + .dfa_size_limit(REGEX_LIMIT) + .nest_limit(64) + .build() + .map_err(|e| EngineError::Param(match e { + regex::Error::CompiledTooBig(_) => "that pattern is too large; make it simpler".to_string(), + regex::Error::Syntax(s) => format!("that isn't a pattern: {}", s.lines().last().unwrap_or("").trim()), + _ => "that isn't a pattern".to_string(), + }))?; + Ok(Needle::Text { re, expand: o.regex }) +} + +fn rgb8(c: Rgba) -> [u8; 3] { + let c = c.sanitized(); + let b = |v: f32| (v * 255.0).round() as u8; + [b(c.r), b(c.g), b(c.b)] +} + +fn font_key(f: &str) -> String { + f.trim().to_lowercase() +} + +fn opt_id(p: &Value, key: &str) -> Result { + opt_u64(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required: a Library id"))) +} + +impl Query { + /// The query in `p` (`find.search`'s params), checked against the document. + pub fn from_params(s: &Session, p: &Value) -> Result { + let kind = str_req(p, "kind")?; + let kind = Kind::from_key(kind).ok_or_else(|| EngineError::Param(format!("unknown kind '{kind}' (text, font, color, symbol, sound or bitmap)")))?; + let needle = match kind { + Kind::Text => { + let o = TextOptions { match_case: opt_bool(p, "match_case")?.unwrap_or(false), whole_word: opt_bool(p, "whole_word")?.unwrap_or(false), regex: opt_bool(p, "regex")?.unwrap_or(false) }; + text_needle(str_req(p, "text")?, o)? + } + Kind::Font => { + let f = font_key(str_req(p, "font")?); + if f.is_empty() || f.chars().count() > 256 { + return Err(EngineError::Param("'font' must be a family name".into())); + } + Needle::Font(f) + } + Kind::Color => Needle::Color(rgb8(opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' is required: #rrggbb".into()))?)), + Kind::Symbol => { + let id = SymbolId(opt_id(p, "symbol")?); + s.doc.symbol(id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + Needle::Symbol(id) + } + Kind::Sound => { + let id = SoundId(opt_id(p, "sound")?); + s.doc.sound(id).ok_or_else(|| EngineError::State(format!("no sound with id {}", id.0)))?; + Needle::Sound(id) + } + Kind::Bitmap => { + let id = BitmapId(opt_id(p, "bitmap")?); + s.doc.bitmap(id).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", id.0)))?; + Needle::Bitmap(id) + } + }; + let within = match p.get("in") { + None | Some(Value::Null) => Within::default(), + Some(Value::Array(list)) => { + let mut w = Within { text: false, labels: false, layers: false, instances: false, scripts: false, fills: false, strokes: false, text_color: false }; + for v in list.iter().take(16) { + match (kind, v.as_str()) { + (Kind::Text, Some("text")) => w.text = true, + (Kind::Text, Some("labels")) => w.labels = true, + (Kind::Text, Some("layers")) => w.layers = true, + (Kind::Text, Some("instances")) => w.instances = true, + (Kind::Text, Some("scripts")) => w.scripts = true, + (Kind::Color, Some("fills")) => w.fills = true, + (Kind::Color, Some("strokes")) => w.strokes = true, + (Kind::Color, Some("text")) => w.text_color = true, + (_, other) => return Err(EngineError::Param(format!("'in' can't hold {}", other.map_or_else(|| v.to_string(), |o| format!("'{o}'"))))), + } + } + w + } + Some(_) => return Err(EngineError::Param("'in' must be a list".into())), + }; + let scope = match opt_str(p, "scope")? { + None | Some("scene") => Scope::Scene, + Some("document") => Scope::Document, + Some(o) => return Err(EngineError::Param(format!("'scope' is scene or document, not '{o}'"))), + }; + Ok(Query { needle, within, scope }) + } + + pub fn kind(&self) -> Kind { + match self.needle { + Needle::Text { .. } => Kind::Text, + Needle::Font(_) => Kind::Font, + Needle::Color(_) => Kind::Color, + Needle::Symbol(_) => Kind::Symbol, + Needle::Sound(_) => Kind::Sound, + Needle::Bitmap(_) => Kind::Bitmap, + } + } +} + +/// One place a search found. +#[derive(Clone, Debug, PartialEq)] +pub struct Hit { + pub at: Where, + pub layer: LayerId, + /// The keyframe's first frame; `None` for a layer's name. + pub frame: Option, + pub element: Option, + pub field: Field, + /// A text match's characters in the field (`start..end`); `0..0` otherwise. + pub start: usize, + pub end: usize, + /// What was found: the matched text, the font, the colour (#rrggbb), or the item's name. + pub found: String, + /// The text around a match, on one line, for lists (empty for other kinds). + pub context: String, +} + +impl Hit { + pub fn to_json(&self, doc: &Document, kind: Kind) -> Value { + let mut v = json!({ + "kind": kind.key(), "field": self.field.key(), "layer": self.layer.0, "frame": self.frame, + "element": self.element.map(|e| e.0), "start": self.start, "end": self.end, "found": self.found, "context": self.context, + }); + match self.at { + Where::Scene(i) => { + v["scene"] = json!(i); + v["scene_name"] = json!(doc.scenes.get(i).map(|s| s.name.as_str())); + } + Where::Symbol(id) => { + v["symbol"] = json!(id.0); + v["symbol_name"] = json!(doc.symbol(id).map(|s| s.name.as_str())); + } + } + v["layer_name"] = json!(timeline_of(doc, self.at).and_then(|t| t.layer(self.layer)).map(|l| l.name.as_str())); + v + } + + /// The hit `v` names (as [`Hit::to_json`] wrote it), without what was found. + fn target(v: &Value) -> Result { + let bad = || EngineError::Param("'at' must be a hit as find.search returns it".into()); + if !v.is_object() { + return Err(bad()); + } + let at = match (opt_u64(v, "scene")?, opt_u64(v, "symbol")?) { + (Some(i), None) => Where::Scene(usize::try_from(i).map_err(|_| bad())?), + (None, Some(id)) => Where::Symbol(SymbolId(id)), + _ => return Err(bad()), + }; + let field = opt_str(v, "field")?.and_then(Field::from_key).ok_or_else(bad)?; + let layer = LayerId(opt_u64(v, "layer")?.ok_or_else(bad)?); + Ok(Target { at, layer, frame: opt_u32(v, "frame")?, element: opt_u64(v, "element")?.map(ElementId), field, start: opt_u64(v, "start")?.and_then(|n| usize::try_from(n).ok()).unwrap_or(0) }) + } +} + +/// A hit's place (what `find.replace`'s `at` names). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Target { + at: Where, + layer: LayerId, + frame: Option, + element: Option, + field: Field, + start: usize, +} + +impl Target { + fn is(&self, h: &Hit) -> bool { + self.at == h.at && self.layer == h.layer && self.frame == h.frame && self.element == h.element && self.field == h.field && (!matches!(h.field, Field::Text | Field::Label | Field::LayerName | Field::InstanceName | Field::Script) || self.start == h.start) + } +} + +/// The timeline `at` names. +pub fn timeline_of(doc: &Document, at: Where) -> Option<&Timeline> { + match at { + Where::Scene(i) => doc.scenes.get(i).map(|s| &s.timeline), + Where::Symbol(id) => doc.symbol(id).map(|s| &s.timeline), + } +} + +fn timeline_of_mut(doc: &mut Document, at: Where) -> Option<&mut Timeline> { + match at { + Where::Scene(i) => doc.scenes.get_mut(i).map(|s| &mut Arc::make_mut(s).timeline), + Where::Symbol(id) => doc.library.iter_mut().find(|s| s.id == id).map(|s| &mut Arc::make_mut(s).timeline), + } +} + +/// The symbols an instance on `tl` shows (directly). +fn used_symbols(tl: &Timeline, mut f: impl FnMut(SymbolId)) { + for k in tl.layers.iter().flat_map(|l| l.keyframes.iter()) { + for e in &k.elements { + if let ElementKind::Symbol { symbol, .. } = e.kind { + f(symbol); + } + } + } +} + +/// Every symbol reachable from `roots` through instances (the roots included), however deep. +pub fn reachable(doc: &Document, roots: impl IntoIterator) -> HashSet { + let by_id: HashMap = doc.library.iter().map(|s| (s.id, &**s)).collect(); + let mut seen = HashSet::new(); + let mut todo: Vec = roots.into_iter().collect(); + while let Some(id) = todo.pop() { + if !seen.insert(id) { + continue; + } + if let Some(sym) = by_id.get(&id) { + used_symbols(&sym.timeline, |u| { + if !seen.contains(&u) { + todo.push(u); + } + }); + } + } + seen +} + +/// The timelines a scope covers, in order: scenes first, then symbols in Library order. +pub fn timelines(doc: &Document, scene: usize, scope: Scope) -> Vec { + match scope { + Scope::Document => (0..doc.scenes.len()).map(Where::Scene).chain(doc.library.iter().map(|s| Where::Symbol(s.id))).collect(), + Scope::Scene => { + let mut used = Vec::new(); + used_symbols(doc.timeline(scene), |s| used.push(s)); + let inside = reachable(doc, used); + std::iter::once(Where::Scene(scene.min(doc.scenes.len().saturating_sub(1)))).chain(doc.library.iter().filter(|s| inside.contains(&s.id)).map(|s| Where::Symbol(s.id))).collect() + } + } +} + +/// Non-empty matches of `re` in `text`: byte range and character start/end. +fn text_matches<'a>(re: &'a Regex, text: &'a str) -> impl Iterator + 'a { + let (mut byte, mut ch) = (0usize, 0usize); + re.find_iter(text).filter(|m| !m.is_empty()).map(move |m| { + ch += text.get(byte..m.start()).map_or(0, |t| t.chars().count()); + let len = m.as_str().chars().count(); + byte = m.end(); + let out = (m.start(), m.end(), ch, ch + len); + ch += len; + out + }) +} + +/// At most `n` characters of `t`, with "…" when there were more. +fn clip(t: &str, n: usize) -> String { + let mut out: String = t.chars().take(n).collect(); + if out.len() < t.len() { + out.push('…'); + } + out +} + +/// `text` around bytes `a..b`, on one line (the match itself clipped too). +fn context(text: &str, a: usize, b: usize) -> String { + let mut before: Vec = text.get(..a).unwrap_or("").chars().rev().take(CONTEXT + 1).collect(); + let cut = before.len() > CONTEXT; + before.truncate(CONTEXT); + let mut out: String = if cut { "…".into() } else { String::new() }; + out.extend(before.into_iter().rev()); + out.push_str(&clip(text.get(a..b).unwrap_or(""), 4 * CONTEXT)); + out.push_str(&clip(text.get(b..).unwrap_or(""), CONTEXT)); + out.replace(['\n', '\r', '\t'], " ") +} + +/// Collects hits as they are found, up to [`MAX_HITS`]. +struct Found<'a> { + q: &'a Query, + doc: &'a Document, + hits: Vec, + truncated: bool, +} + +impl Found<'_> { + fn full(&mut self) -> bool { + if self.hits.len() >= MAX_HITS { + self.truncated = true; + } + self.truncated + } + + fn push(&mut self, h: Hit) { + if !self.full() { + self.hits.push(h); + } + } + + fn text(&mut self, place: (Where, LayerId, Option, Option), field: Field, text: &str) { + let q = self.q; + let Needle::Text { re, .. } = &q.needle else { return }; + for (a, b, ca, cb) in text_matches(re, text) { + if self.full() { + return; + } + self.hits.push(Hit { at: place.0, layer: place.1, frame: place.2, element: place.3, field, start: ca, end: cb, found: clip(text.get(a..b).unwrap_or(""), 4 * CONTEXT), context: context(text, a, b) }); + } + } + + fn timeline(&mut self, at: Where, tl: &Timeline) { + let q = self.q; + let w = q.within; + for l in &tl.layers { + if self.full() { + return; + } + if w.layers && matches!(q.needle, Needle::Text { .. }) { + self.text((at, l.id, None, None), Field::LayerName, &l.name); + } + for k in &l.keyframes { + let f = Some(k.start); + let place = |e: Option| Hit { at, layer: l.id, frame: f, element: e, field: Field::Text, start: 0, end: 0, found: String::new(), context: String::new() }; + match &q.needle { + Needle::Text { .. } => { + if w.labels { + self.text((at, l.id, f, None), Field::Label, &k.label); + } + if w.scripts + && let Some(FrameScript::Source(src)) = &k.script + { + self.text((at, l.id, f, None), Field::Script, &src.text); + } + } + Needle::Sound(id) if k.sound.as_ref().is_some_and(|fs| fs.sound == *id) => { + let found = self.doc.sound(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Sound, found, ..place(None) }); + } + _ => {} + } + for e in &k.elements { + if self.full() { + return; + } + let place = (at, l.id, f, Some(e.id)); + match (&q.needle, &e.kind) { + (Needle::Text { .. }, kind) => { + if w.instances { + self.text(place, Field::InstanceName, &e.name); + } + if w.text + && let ElementKind::Text(t) = kind + { + self.text(place, Field::Text, &t.text); + } + } + (Needle::Font(f), ElementKind::Text(t)) if font_key(&t.font) == *f => self.push(Hit { field: Field::Font, found: t.font.clone(), ..hit_at(place) }), + (Needle::Color(c), ElementKind::Shape(sh)) => { + if w.fills && sh.fill.as_ref().is_some_and(|p| paint_has(p, *c)) { + self.push(Hit { field: Field::Fill, found: hex(*c), ..hit_at(place) }); + } + if w.strokes && sh.stroke.as_ref().is_some_and(|s| rgb8(s.color) == *c) { + self.push(Hit { field: Field::Stroke, found: hex(*c), ..hit_at(place) }); + } + } + (Needle::Color(c), ElementKind::Text(t)) if w.text_color && rgb8(t.color) == *c => self.push(Hit { field: Field::TextColor, found: hex(*c), ..hit_at(place) }), + (Needle::Symbol(id), ElementKind::Symbol { symbol, .. }) if symbol == id => { + let found = self.doc.symbol(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Instance, found, ..hit_at(place) }); + } + (Needle::Bitmap(id), ElementKind::Shape(sh)) if matches!(&sh.fill, Some(Paint::Bitmap { bitmap, .. }) if bitmap == id) => { + let found = self.doc.bitmap(*id).map(|x| x.name.clone()).unwrap_or_default(); + self.push(Hit { field: Field::Bitmap, found, ..hit_at(place) }); + } + _ => {} + } + } + } + } + } +} + +fn hit_at(place: (Where, LayerId, Option, Option)) -> Hit { + Hit { at: place.0, layer: place.1, frame: place.2, element: place.3, field: Field::Text, start: 0, end: 0, found: String::new(), context: String::new() } +} + +fn hex(c: [u8; 3]) -> String { + format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) +} + +fn paint_has(p: &Paint, c: [u8; 3]) -> bool { + match p { + Paint::Solid(x) => rgb8(*x) == c, + Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => stops.iter().any(|s| rgb8(s.color) == c), + Paint::Bitmap { .. } => false, + } +} + +/// Every hit of `q` in its scope (from scene `scene`), in order, and whether the list stopped at +/// [`MAX_HITS`]. +pub fn search(doc: &Document, scene: usize, q: &Query) -> (Vec, bool) { + let mut f = Found { q, doc, hits: Vec::new(), truncated: false }; + for at in timelines(doc, scene, q.scope) { + if let Some(tl) = timeline_of(doc, at) { + f.timeline(at, tl); + } + if f.truncated { + break; + } + } + (f.hits, f.truncated) +} + +fn search_cmd(s: &mut Session, p: &Value) -> Result { + let q = Query::from_params(s, p)?; + let offset = opt_u64(p, "offset")?.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)); + let limit = opt_u64(p, "limit")?.map_or(DEFAULT_LIMIT, |n| usize::try_from(n).unwrap_or(MAX_LIMIT)).min(MAX_LIMIT); + let (hits, truncated) = search(&s.doc, s.scene, &q); + let kind = q.kind(); + let page: Vec = hits.iter().skip(offset).take(limit).map(|h| h.to_json(&s.doc, kind)).collect(); + Ok(json!({"hits": page, "total": hits.len(), "offset": offset, "truncated": truncated})) +} + +// ----- replace ----------------------------------------------------------------------------- + +/// What hits are replaced with. +#[derive(Clone, Debug)] +pub enum With { + Text(String), + Font(String), + Color(Rgba), + Symbol(SymbolId), + Sound(SoundId), + Bitmap(BitmapId), +} + +impl With { + fn from_params(s: &Session, kind: Kind, p: &Value) -> Result { + let v = p.get("with").ok_or_else(|| EngineError::Param("param 'with' is required: what to replace with".into()))?; + let id = || v.as_u64().ok_or_else(|| EngineError::Param("'with' must be a Library id".into())); + Ok(match kind { + Kind::Text => { + let t = v.as_str().ok_or_else(|| EngineError::Param("'with' must be text".into()))?; + if t.chars().count() > MAX_QUERY_CHARS { + return Err(EngineError::Param(format!("what to replace with is at most {MAX_QUERY_CHARS} characters"))); + } + With::Text(t.to_string()) + } + Kind::Font => { + let f = v.as_str().map(str::trim).filter(|f| !f.is_empty() && f.chars().count() <= 256).ok_or_else(|| EngineError::Param("'with' must be a font family".into()))?; + With::Font(f.to_string()) + } + Kind::Color => With::Color(opt_color(p, "with")?.ok_or_else(|| EngineError::Param("'with' must be a colour: #rrggbb".into()))?), + Kind::Symbol => { + let to = SymbolId(id()?); + s.doc.symbol(to).ok_or_else(|| EngineError::State(format!("no symbol with id {}", to.0)))?; + With::Symbol(to) + } + Kind::Sound => { + let to = SoundId(id()?); + s.doc.sound(to).ok_or_else(|| EngineError::State(format!("no sound with id {}", to.0)))?; + With::Sound(to) + } + Kind::Bitmap => { + let to = BitmapId(id()?); + s.doc.bitmap(to).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", to.0)))?; + With::Bitmap(to) + } + }) + } +} + +/// `text` with the matches of `re` replaced by `with` (only the one starting at character `only` +/// when given); `None` when nothing matched. +fn replace_text(re: &Regex, expand: bool, text: &str, with: &str, only: Option) -> Option { + let mut out = String::with_capacity(text.len()); + // `last`: copied up to here; `seen`, `ch`: characters counted up to byte `seen`. + let (mut last, mut seen, mut ch, mut any) = (0usize, 0usize, 0usize, false); + for caps in re.captures_iter(text) { + let Some(m) = caps.get(0) else { continue }; + if m.is_empty() { + continue; + } + ch += text.get(seen..m.start()).map_or(0, |t| t.chars().count()); + let this = ch; + ch += m.as_str().chars().count(); + seen = m.end(); + if only.is_some_and(|o| o != this) { + continue; + } + out.push_str(text.get(last..m.start()).unwrap_or("")); + if expand { + caps.expand(with, &mut out); + } else { + out.push_str(with); + } + last = m.end(); + any = true; + if only.is_some() { + break; + } + } + if !any { + return None; + } + out.push_str(text.get(last..).unwrap_or("")); + Some(out) +} + +/// The places Replace All would change (each field once). +pub fn places(hits: &[Hit]) -> usize { + let mut seen = HashSet::new(); + hits.iter().filter(|h| seen.insert((h.at, h.layer, h.frame, h.element, h.field))).count() +} + +/// How many places `find.replace` with `p` would change (for its confirmation); `None` when +/// the params don't make a query or name one hit. +pub(crate) fn replace_count(s: &Session, p: &Value) -> Option { + if p.get("at").is_some_and(|v| !v.is_null()) { + return None; + } + let q = Query::from_params(s, p).ok()?; + Some(places(&search(&s.doc, s.scene, &q).0)) +} + +/// What a replacement did. +#[derive(Default)] +struct Tally { + replaced: usize, + skipped: usize, + notes: Vec, +} + +impl Tally { + fn note(&mut self, n: String) { + if !self.notes.contains(&n) && self.notes.len() < 16 { + self.notes.push(n); + } + } +} + +fn replace_cmd(s: &mut Session, p: &Value) -> Result { + let q = Query::from_params(s, p)?; + let with = With::from_params(s, q.kind(), p)?; + let only = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some(Hit::target(v)?), + }; + let (mut hits, truncated) = search(&s.doc, s.scene, &q); + if let Some(t) = &only { + hits.retain(|h| t.is(h)); + if hits.is_empty() { + return Err(EngineError::State("that match isn't there any more; search again".into())); + } + } + if hits.is_empty() { + return Err(EngineError::State("nothing matches".into())); + } + // A symbol can't end up inside itself: no instance of `to` in `to`, or in a symbol it uses. + let blocked: HashSet = match with { + With::Symbol(to) => reachable(&s.doc, [to]), + _ => HashSet::new(), + }; + let sizes: HashMap = s.doc.bitmaps.iter().map(|b| (b.id, (b.name.clone(), b.width as f32, b.height as f32))).collect(); + let mut tally = Tally::default(); + let mut by_tl: Vec<(Where, Vec)> = Vec::new(); + for h in hits { + match by_tl.last_mut() { + Some((at, list)) if *at == h.at => list.push(h), + _ => by_tl.push((h.at, vec![h])), + } + } + for (at, list) in by_tl { + if let Where::Symbol(id) = at + && blocked.contains(&id) + { + tally.skipped += places(&list); + tally.note("an instance inside the symbol it would show (or one it uses) was left as it is: a symbol can't contain itself".into()); + continue; + } + let Some(tl) = timeline_of_mut(&mut s.doc, at) else { continue }; + apply(tl, &list, &q, &with, only.as_ref().map(|t| t.start), &sizes, &mut tally)?; + } + if tally.replaced == 0 { + return Err(EngineError::State(tally.notes.first().cloned().unwrap_or_else(|| "nothing could be replaced".into()))); + } + // The fill swatch and the text style keep what they were: replacing edits the document only. + Ok(json!({"replaced": tally.replaced, "skipped": tally.skipped, "notes": tally.notes, "truncated": truncated})) +} + +/// Replaces `hits` (all on `tl`) in place, un-sharing only the layers, keyframes and elements +/// they are on. `only`: the one text match to replace (Replace), by its first character. +fn apply(tl: &mut Timeline, hits: &[Hit], q: &Query, with: &With, only: Option, sizes: &HashMap, t: &mut Tally) -> Result<()> { + let layers: HashSet = hits.iter().map(|h| h.layer).collect(); + let (re, expand) = match &q.needle { + Needle::Text { re, expand } => (Some(re), *expand), + _ => (None, false), + }; + let new_text = |text: &str| -> Option { + match (re, with) { + (Some(re), With::Text(w)) => replace_text(re, expand, text, w, only), + _ => None, + } + }; + for l in tl.layers.iter_mut().filter(|l| layers.contains(&l.id)) { + let lh: Vec<&Hit> = hits.iter().filter(|h| h.layer == l.id).collect(); + let l = Arc::make_mut(l); + if lh.iter().any(|h| h.field == Field::LayerName) { + match new_text(&l.name).map(|n| n.chars().take(128).collect::()) { + Some(n) if !n.trim().is_empty() => { + l.name = n; + t.replaced += 1; + } + _ => { + t.skipped += 1; + t.note("a layer name can't be empty".into()); + } + } + } + let frames: HashSet = lh.iter().filter_map(|h| h.frame).collect(); + for k in l.keyframes.iter_mut().filter(|k| frames.contains(&k.start)) { + let kh: Vec<&&Hit> = lh.iter().filter(|h| h.frame == Some(k.start)).collect(); + let k = Arc::make_mut(k); + let has = |f: Field| kh.iter().any(|h| h.field == f && h.element.is_none()); + if has(Field::Label) + && let Some(n) = new_text(&k.label) + { + k.label = n.chars().take(256).collect(); + t.replaced += 1; + } + if has(Field::Script) + && let Some(FrameScript::Source(src)) = &k.script + && let Some(n) = new_text(&src.text) + { + if n.len() > anicraft_doc::actions::MAX_SOURCE_BYTES { + t.skipped += 1; + t.note("a script would be too long".into()); + } else { + k.script = Some(FrameScript::Source(Arc::new(SourceScript::new(src.language, n)))); + t.replaced += 1; + } + } + if has(Field::Sound) + && let (Some(fs), With::Sound(to)) = (k.sound.as_mut(), with) + { + fs.sound = *to; + t.replaced += 1; + } + let ids: HashSet = kh.iter().filter_map(|h| h.element).collect(); + for e in k.elements.iter_mut().filter(|e| ids.contains(&e.id)) { + let fields: Vec = kh.iter().filter(|h| h.element == Some(e.id)).map(|h| h.field).collect(); + let e = Arc::make_mut(e); + for f in Field::ALL.into_iter().filter(|f| fields.contains(f)) { + apply_element(e, f, q, with, &new_text, sizes, t)?; + } + } + } + } + Ok(()) +} + +/// Replaces field `f` of element `e`. +fn apply_element(e: &mut anicraft_doc::Element, f: Field, q: &Query, with: &With, new_text: &dyn Fn(&str) -> Option, sizes: &HashMap, t: &mut Tally) -> Result<()> { + match (f, &mut e.kind, with) { + (Field::InstanceName, _, _) => { + if let Some(n) = new_text(&e.name) { + e.name = n.chars().take(128).collect(); + t.replaced += 1; + } + } + (Field::Text, ElementKind::Text(tb), _) => { + if let Some(n) = new_text(&tb.text) { + if n.trim().is_empty() { + t.skipped += 1; + t.note("a text field can't be left empty (delete it instead)".into()); + } else { + // Laid out again as it is: text on a path stays on it (ADR 0070). + let (block, note, shift) = crate::cmds_text::relay_static(tb, &n, &crate::cmds_text::style_of(tb))?; + t.note_opt(note); + *tb = Arc::new(block); + e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y)); + t.replaced += 1; + } + } + } + (Field::Font, ElementKind::Text(tb), With::Font(family)) => { + let style = crate::cmds_text::TextStyle { font: family.clone(), ..crate::cmds_text::style_of(tb) }; + let (block, note, shift) = crate::cmds_text::relay_static(tb, &tb.text, &style)?; + t.note_opt(note); + *tb = Arc::new(block); + e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y)); + t.replaced += 1; + } + (Field::TextColor, ElementKind::Text(tb), With::Color(c)) => { + let tb = Arc::make_mut(tb); + tb.color = Rgba { a: tb.color.a, ..*c }; + t.replaced += 1; + } + (Field::Fill | Field::Stroke, ElementKind::Shape(sh), With::Color(c)) => { + let Needle::Color(from) = q.needle else { return Ok(()) }; + let recolour = |x: &mut Rgba| { + if rgb8(*x) == from { + *x = Rgba { a: x.a, ..*c }; + } + }; + if f == Field::Fill { + match &mut sh.fill { + Some(Paint::Solid(x)) => recolour(x), + Some(Paint::Linear { stops, .. } | Paint::Radial { stops, .. }) => stops.iter_mut().for_each(|s| recolour(&mut s.color)), + _ => {} + } + } else if let Some(st) = &mut sh.stroke { + recolour(&mut st.color); + } + t.replaced += 1; + } + (Field::Instance, ElementKind::Symbol { symbol, .. }, With::Symbol(to)) => { + *symbol = *to; + t.replaced += 1; + } + (Field::Bitmap, ElementKind::Shape(_), With::Bitmap(to)) => { + t.replaced += usize::from(crate::cmds_library::swap_bitmap_of(e, *to, sizes)); + } + _ => {} + } + Ok(()) +} + +impl Tally { + fn note_opt(&mut self, n: Option) { + if let Some(n) = n { + self.note(n); + } + } +} + +// ----- go to ------------------------------------------------------------------------------- + +/// One instance opened in place on the way to a symbol: on `layer`, at the keyframe starting at +/// `frame`, the instance `element`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Step { + pub layer: LayerId, + pub frame: u32, + pub element: ElementId, +} + +impl Step { + pub fn to_json(&self) -> Value { + json!({"layer": self.layer.0, "frame": self.frame, "element": self.element.0}) + } +} + +/// Where a scene or symbol timeline holding layer `id` is. +pub fn locate_layer(doc: &Document, id: LayerId) -> Option { + doc.scenes.iter().position(|s| s.timeline.layer(id).is_some()).map(Where::Scene).or_else(|| doc.library.iter().find(|s| s.timeline.layer(id).is_some()).map(|s| Where::Symbol(s.id))) +} + +/// The shortest chain of instances from scene `scene`'s timeline to symbol `target` (each opened +/// in place in turn), when an instance in that scene leads to it. +pub fn route(doc: &Document, scene: usize, target: SymbolId) -> Option> { + let by_id: HashMap = doc.library.iter().map(|s| (s.id, &**s)).collect(); + let mut seen: HashSet = HashSet::new(); + let mut todo: VecDeque<(&Timeline, Vec)> = VecDeque::from([(doc.timeline(scene), Vec::new())]); + while let Some((tl, path)) = todo.pop_front() { + if path.len() >= MAX_ROUTE { + continue; + } + for l in &tl.layers { + for k in &l.keyframes { + for e in &k.elements { + let ElementKind::Symbol { symbol, .. } = e.kind else { continue }; + let mut next = path.clone(); + next.push(Step { layer: l.id, frame: k.start, element: e.id }); + if symbol == target { + return Some(next); + } + if seen.insert(symbol) + && let Some(sym) = by_id.get(&symbol) + { + todo.push_back((&sym.timeline, next)); + } + } + } + } + } + None +} + +fn steps_of(p: &Value) -> Result>> { + let Some(list) = p.get("path").filter(|v| !v.is_null()) else { return Ok(None) }; + let list = list.as_array().ok_or_else(|| EngineError::Param("'path' must be a list of {layer, frame, element}".into()))?; + if list.len() > MAX_ROUTE { + return Err(EngineError::Param(format!("'path' opens at most {MAX_ROUTE} instances"))); + } + let bad = || EngineError::Param("each step of 'path' is {layer, frame, element}".into()); + list.iter() + .map(|v| Ok(Step { layer: LayerId(opt_u64(v, "layer")?.ok_or_else(bad)?), frame: opt_u32(v, "frame")?.ok_or_else(bad)?, element: ElementId(opt_u64(v, "element")?.ok_or_else(bad)?) })) + .collect::>>() + .map(Some) +} + +/// Opens each instance of `steps` in place, from the timeline being edited. False when one +/// can't be opened (a hidden or locked layer, an instance that isn't there). +fn walk(s: &mut Session, steps: &[Step]) -> bool { + for st in steps { + if s.timeline().layer(st.layer).is_none() { + return false; + } + s.layer = st.layer; + s.frame = st.frame.min(crate::MAX_FRAME); + s.selection.clear(); + if crate::editing::edit(s, &json!({"id": st.element.0})).is_err() { + return false; + } + } + true +} + +fn goto_cmd(s: &mut Session, p: &Value) -> Result { + let layer = opt_u64(p, "layer")?.map(LayerId); + let frame = opt_u32(p, "frame")?; + let element = opt_u64(p, "element")?.map(ElementId); + let scene = match opt_u64(p, "scene")? { + Some(i) => Some(usize::try_from(i).ok().filter(|i| *i < s.doc.scenes.len()).ok_or_else(|| EngineError::State(format!("there is no scene {i}")))?), + None => None, + }; + let symbol = opt_u64(p, "symbol")?.map(SymbolId); + if let Some(id) = symbol + && s.doc.symbol(id).is_none() + { + return Err(EngineError::State(format!("no symbol with id {}", id.0))); + } + let steps = steps_of(p)?; + if steps.is_some() && layer.is_none() { + return Err(EngineError::Param("a 'path' goes to a 'layer': name it".into())); + } + // Where to end up: the layer's timeline, else what the params name. + let target = match layer { + Some(l) => locate_layer(&s.doc, l).ok_or_else(|| EngineError::State(format!("no layer with id {}", l.0)))?, + None => match (symbol, scene) { + (Some(id), _) => Where::Symbol(id), + (None, Some(i)) => Where::Scene(i), + (None, None) => return Err(EngineError::Param("name where to go: {layer}, {scene} or {symbol}".into())), + }, + }; + let here = s.scene; + // Open symbols close first (ADR 0045). + s.exit_all(); + match target { + Where::Scene(i) => crate::cmds_scene::open_scene(s, i), + Where::Symbol(t) => { + let opened = match &steps { + // Through the instances named, from the scene (or from `symbol`, opened alone). + Some(steps) => { + match symbol { + Some(b) => { + crate::editing::edit(s, &json!({"symbol": b.0}))?; + } + None => crate::cmds_scene::open_scene(s, scene.unwrap_or(here)), + } + walk(s, steps) && s.editing_symbol() == Some(t) + } + // In place through the first instance that leads there: in this scene, else another. + None => { + let order = std::iter::once(scene.unwrap_or(here)).chain(0..s.doc.scenes.len()); + let found = order.into_iter().find_map(|i| route(&s.doc, i, t).map(|r| (i, r))); + match found { + Some((i, r)) => { + crate::cmds_scene::open_scene(s, i); + walk(s, &r) && s.editing_symbol() == Some(t) + } + None => false, + } + } + }; + if !opened { + // Alone, from the Library (no instance leads there, or one can't be opened). + s.exit_all(); + crate::editing::edit(s, &json!({"symbol": t.0}))?; + } + } + } + if let Some(l) = layer.filter(|l| s.timeline().layer(*l).is_some()) { + s.layer = l; + } + if let Some(f) = frame { + s.frame = f.min(crate::MAX_FRAME); + } + s.selection = match element { + Some(e) => Selection::only(s.layer, [e]), + None => Selection::default(), + }; + s.revision += 1; + s.dl_cache.replace(None); + s.fix_selection(); + let mut v = crate::editing::editing_json(s); + v["scene"] = json!(s.scene); + Ok(v) +} + +#[cfg(test)] +#[path = "find_tests.rs"] +pub(crate) mod tests; diff --git a/crates/engine/src/find_tests.rs b/crates/engine/src/find_tests.rs new file mode 100644 index 00000000..609a93d1 --- /dev/null +++ b/crates/engine/src/find_tests.rs @@ -0,0 +1,456 @@ +//! Find and Replace end to end (ADR 0058): each kind, scopes, text options and bounded patterns, +//! Replace and Replace All as one undo step, the confirmation, and going to what was found +//! (symbols opened in place through the instances that lead to them). + +use super::*; +use anicraft_doc::{ColorEffect, Document, Element, ElementKind, FrameSound, GradientStop, Keyframe, Layer, LayerId, LoopMode, Paint, Rgba, Scene, Shape, SourceScript, Symbol, SymbolKind, TextAlign, TextBlock}; +use anicraft_geom::{Affine, Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +/// Builds documents by hand, ids from the document. +pub(crate) struct Build { + pub doc: Document, +} + +impl Build { + pub fn new() -> Build { + let mut doc = Document::default(); + doc.scenes.clear(); + doc.next_id = 1; + Build { doc } + } + pub fn id(&mut self) -> u64 { + self.doc.alloc_id() + } + pub fn text(&mut self, t: &str, color: Rgba) -> Element { + let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None, on_path: None }; + Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) } + } + pub fn rect(&mut self, fill: Paint, stroke: Option) -> Element { + let mut sh = Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), fill); + if let Some(c) = stroke { + sh = sh.with_stroke(c, 2.0); + } + Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(sh) } + } + pub fn instance(&mut self, symbol: SymbolId, name: &str) -> Element { + Element { + id: ElementId(self.id()), + name: name.into(), + transform: Affine::translate(100.0, 50.0), + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + } + } + /// A layer with keyframes `(start, duration, label, elements)`. + pub fn layer(&mut self, name: &str, keys: Vec<(u32, u32, &str, Vec)>) -> Layer { + let mut l = Layer::new(LayerId(self.id()), name); + l.keyframes = keys + .into_iter() + .map(|(start, dur, label, els)| { + let mut k = Keyframe::new(start, dur); + k.label = label.into(); + k.elements = els.into_iter().map(Arc::new).collect(); + Arc::new(k) + }) + .collect(); + l + } + pub fn scene(&mut self, name: &str, layers: Vec) { + let mut sc = Scene::new(name); + sc.timeline.layers = layers.into_iter().map(Arc::new).collect(); + self.doc.scenes.push(Arc::new(sc)); + } + pub fn symbol(&mut self, name: &str, kind: SymbolKind) -> SymbolId { + let id = SymbolId(self.id()); + self.doc.library.push(Arc::new(Symbol { id, name: name.into(), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline::default() })); + id + } + pub fn fill(&mut self, id: SymbolId, layers: Vec) { + if let Some(s) = self.doc.library.iter_mut().find(|s| s.id == id) { + Arc::make_mut(s).timeline.layers = layers.into_iter().map(Arc::new).collect(); + } + } +} + +const RED: u32 = 0xff0000; + +/// Scene 1: an Art layer (a text field, a red rect with a blue stroke, an instance of Outer +/// named "hero"; a second keyframe labelled "intro hello" with more text), an Actions layer with a +/// script. Outer holds an instance of Inner and a red rect; Inner holds text. Unused holds text +/// and is in no scene. Scene 2 has a red rect. +pub(crate) fn movie() -> (Session, SymbolId, SymbolId, SymbolId) { + let mut b = Build::new(); + let outer = b.symbol("Outer", SymbolKind::MovieClip); + let inner = b.symbol("Inner", SymbolKind::Graphic); + let unused = b.symbol("Unused", SymbolKind::Graphic); + let t = b.text("Hello inside", Rgba::hex(RED)); + let l = b.layer("Inner art", vec![(0, 5, "", vec![t])]); + b.fill(inner, vec![l]); + let i = b.instance(inner, "wheel"); + let r = b.rect(Paint::Solid(Rgba::hex(RED)), None); + let l = b.layer("Outer art", vec![(0, 1, "", vec![r]), (3, 2, "", vec![i])]); + b.fill(outer, vec![l]); + let t = b.text("hello unused", Rgba::BLACK); + let l = b.layer("U", vec![(0, 1, "", vec![t])]); + b.fill(unused, vec![l]); + let t1 = b.text("Hello world", Rgba::BLACK); + let r = b.rect(Paint::Solid(Rgba::hex(RED).with_alpha(0.5)), Some(Rgba::hex(0x0000ff))); + let hero = b.instance(outer, "hero"); + let t2 = b.text("hello hello again", Rgba::hex(RED)); + let art = b.layer("Art", vec![(0, 10, "", vec![t1, r, hero]), (10, 5, "intro hello", vec![t2])]); + let mut actions = b.layer("Actions", vec![(0, 15, "", vec![])]); + if let Some(k) = actions.keyframe_mut(0) { + k.script = Some(FrameScript::Source(Arc::new(SourceScript::new(Default::default(), "stop(); // say hello")))); + } + b.scene("Scene 1", vec![actions, art]); + let r = b.rect(Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(RED) }, GradientStop { offset: 1.0, color: Rgba::WHITE }]), None); + let l = b.layer("Back", vec![(0, 1, "", vec![r])]); + b.scene("Scene 2", vec![l]); + (Session::new(b.doc), outer, inner, unused) +} + +fn hits(s: &mut Session, p: Value) -> Vec { + run(s, "find.search", p)["hits"].as_array().cloned().unwrap_or_default() +} + +fn fields(h: &[Value]) -> Vec { + h.iter().map(|h| h["field"].as_str().unwrap_or("").to_string()).collect() +} + +#[test] +fn text_is_found_in_every_place_and_scope() { + let (mut s, ..) = movie(); + // The scene and the symbols it uses: the script, text fields (Inner's too), the label. + let h = hits(&mut s, json!({"kind": "text", "text": "hello"})); + let found: Vec<&str> = h.iter().map(|h| h["found"].as_str().unwrap()).collect(); + assert_eq!(fields(&h), ["script", "text", "label", "text", "text", "text"], "{h:?}"); + assert_eq!(found, ["hello", "Hello", "hello", "hello", "hello", "Hello"]); + assert_eq!(h[1]["scene"], 0); + assert_eq!(h[1]["layer_name"], "Art"); + assert_eq!(h[3]["start"], 0); + assert_eq!(h[4]["start"], 6); + assert_eq!(h[4]["context"], "hello hello again"); + assert_eq!(h[5]["symbol_name"], "Inner"); + // The whole document adds the unused symbol (and Scene 2 has none). + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "hello", "scope": "document"})).len(), 7); + // Case, whole words and where to look. + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "Hello", "match_case": true})).len(), 2); + assert!(hits(&mut s, json!({"kind": "text", "text": "hell", "whole_word": true})).is_empty()); + assert_eq!(hits(&mut s, json!({"kind": "text", "text": "hell"})).len(), 6); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "hello", "in": ["labels"]}))), ["label"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "her", "in": ["instances"]}))), ["instance_name"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "text", "text": "art", "in": ["layers"]}))), ["layer_name", "layer_name", "layer_name"]); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "x", "in": ["fills"]})).contains("'in'")); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": ""})).contains("find")); + // Paging. + let v = run(&mut s, "find.search", json!({"kind": "text", "text": "hello", "offset": 4, "limit": 1})); + assert_eq!((v["total"].as_u64(), v["hits"].as_array().map(Vec::len)), (Some(6), Some(1))); +} + +#[test] +fn patterns_are_bounded() { + let (mut s, ..) = movie(); + let h = hits(&mut s, json!({"kind": "text", "text": r"h\w+o", "regex": true, "in": ["text"]})); + assert_eq!(h.len(), 4); + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "(", "regex": true})).contains("pattern")); + // Too large to compile is refused, not run. + assert!(err(&mut s, "find.search", json!({"kind": "text", "text": "a{1000}{1000}", "regex": true})).contains("too large")); + // What backtracking engines take exponential time over runs in linear time. + let mut b = Build::new(); + let t = b.text(&format!("{}b", "a".repeat(50_000)), Rgba::BLACK); + let l = b.layer("L", vec![(0, 1, "", vec![t])]); + b.scene("S", vec![l]); + let mut big = Session::new(b.doc); + let t0 = std::time::Instant::now(); + assert_eq!(hits(&mut big, json!({"kind": "text", "text": "(a+)+$", "regex": true})).len(), 0); + assert!(t0.elapsed().as_secs_f64() < 2.0, "{:?}", t0.elapsed()); + // An empty match finds nothing, rather than every gap. + assert!(hits(&mut s, json!({"kind": "text", "text": "x*", "regex": true})).is_empty()); +} + +#[test] +fn colours_fonts_and_library_items_are_found() { + let (mut s, outer, inner, _) = movie(); + // Red: a text colour (Scene 1's second text), a fill with alpha, Outer's fill, Inner's text. + let h = hits(&mut s, json!({"kind": "color", "color": "#FF0000"})); + assert_eq!(fields(&h), ["fill", "text_color", "fill", "text_color"], "{h:?}"); + assert_eq!(fields(&hits(&mut s, json!({"kind": "color", "color": "#0000ff"}))), ["stroke"]); + assert_eq!(fields(&hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["strokes"]}))).len(), 0); + // Gradient stops count (Scene 2). + assert_eq!(hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["fills"], "scope": "document"})).len(), 3); + assert_eq!(hits(&mut s, json!({"kind": "font", "font": " test sans "})).len(), 3); + let h = hits(&mut s, json!({"kind": "symbol", "symbol": inner.0})); + assert_eq!((h.len(), h[0]["symbol"].as_u64(), h[0]["found"].as_str()), (1, Some(outer.0), Some("Inner"))); + assert!(err(&mut s, "find.search", json!({"kind": "symbol", "symbol": 999_999})).contains("no symbol")); + assert!(err(&mut s, "find.search", json!({"kind": "sparkle"})).contains("unknown kind")); +} + +#[test] +fn sounds_and_bitmaps_are_found_and_replaced() { + let (mut s, ..) = movie(); + let wav = crate::cmds_sound::test_wav(8000, &[0.25; 800]); + let (a, b) = (anicraft_doc::SoundId(s.doc.alloc_id()), anicraft_doc::SoundId(s.doc.alloc_id())); + for (id, n) in [(a, "a.wav"), (b, "b.wav")] { + s.doc.sounds.push(Arc::new(anicraft_doc::Sound::from_data(id, n, wav.clone()).unwrap())); + } + let k = Arc::make_mut(&mut s.doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap(); + k.sound = Some(FrameSound::new(a)); + let h = hits(&mut s, json!({"kind": "sound", "sound": a.0})); + assert_eq!((fields(&h), h[0]["found"].as_str()), (vec!["sound".to_string()], Some("a.wav"))); + run(&mut s, "find.replace", json!({"kind": "sound", "sound": a.0, "with": b.0})); + assert_eq!(s.doc.timeline(0).layers[0].keyframes[0].sound.as_ref().map(|f| f.sound), Some(b)); + // A placed bitmap takes the new one's size. + let png = |w, h| anicraft_render::encode_png(w, h, &[0, 0, 255, 255].repeat((w * h) as usize)).unwrap(); + let (p, q) = (anicraft_doc::BitmapId(s.doc.alloc_id()), anicraft_doc::BitmapId(s.doc.alloc_id())); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(p, "p.png", png(3, 2)).unwrap())); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(q, "q.png", png(5, 4)).unwrap())); + run(&mut s, "library.place", json!({"bitmap": p.0})); + assert_eq!(hits(&mut s, json!({"kind": "bitmap", "bitmap": p.0})).len(), 1); + run(&mut s, "find.replace", json!({"kind": "bitmap", "bitmap": p.0, "with": q.0})); + assert!(hits(&mut s, json!({"kind": "bitmap", "bitmap": p.0})).is_empty()); + let placed = s.doc.timeline(0).layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find_map(|e| match &e.kind { + ElementKind::Shape(sh) if matches!(sh.fill, Some(Paint::Bitmap { bitmap, .. }) if bitmap == q) => Some(sh.path.bounds()), + _ => None, + }); + assert_eq!(placed.map(|r| (r.width(), r.height())), Some((5.0, 4.0))); +} + +#[test] +fn replace_all_is_one_undo_step_and_undo_brings_everything_back() { + let (mut s, ..) = movie(); + let before = s.doc.clone(); + let steps = s.history_len(); + let v = run(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "with": "bye", "in": ["text", "labels", "scripts"]})); + assert_eq!(v["replaced"], 5, "{v}"); + assert_eq!(s.history_len(), steps + 1); + let texts: Vec = s.doc.timelines().flat_map(|t| &t.layers).flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).filter_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }).collect(); + // Case-insensitive, every match; the unused symbol is outside the scene's scope. + assert_eq!(texts, ["bye world", "bye bye again", "bye inside", "hello unused"]); + assert_eq!(s.doc.timeline(0).layers[1].keyframes[1].label, "intro bye"); + match &s.doc.timeline(0).layers[0].keyframes[0].script { + Some(FrameScript::Source(src)) => assert_eq!(src.text, "stop(); // say bye"), + other => panic!("{other:?}"), + } + // A replaced text is laid out again (its outline was empty). + assert!(s.doc.timeline(0).layers[1].keyframes[1].elements.iter().any(|e| matches!(&e.kind, ElementKind::Text(t) if t.text == "bye bye again" && t.box_width != 10.0))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before); + // Nothing to replace is an error, and records nothing. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "zebra", "with": "x"})).contains("nothing")); + assert_eq!(s.history_len(), steps); +} + +#[test] +fn replace_one_changes_only_that_match() { + let (mut s, ..) = movie(); + let h = hits(&mut s, json!({"kind": "text", "text": "hello", "in": ["text"]})); + let second = h.iter().find(|h| h["start"] == 6).cloned().unwrap(); + run(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "in": ["text"], "with": "HI", "at": second})); + let t = s.doc.timeline(0).layers[1].keyframes[1].elements.iter().find_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }); + assert_eq!(t.as_deref(), Some("hello HI again")); + // The same hit again is gone. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "hello", "in": ["text"], "with": "HI", "at": second})).contains("isn't there")); + // Groups expand with a pattern, not with plain text. + run(&mut s, "find.replace", json!({"kind": "text", "text": r"(\w+) world", "regex": true, "with": "$1, $1 world"})); + let first = s.doc.timeline(0).layers[1].keyframes[0].elements.iter().find_map(|e| match &e.kind { + ElementKind::Text(t) => Some(t.text.clone()), + _ => None, + }); + assert_eq!(first.as_deref(), Some("Hello, Hello world")); + run(&mut s, "find.replace", json!({"kind": "text", "text": "world", "with": "$0$1"})); + assert!(s.doc.timeline(0).layers[1].keyframes[0].elements.iter().any(|e| matches!(&e.kind, ElementKind::Text(t) if t.text == "Hello, Hello $0$1"))); + // A layer name can't become empty: skipped, and said why. + assert!(err(&mut s, "find.replace", json!({"kind": "text", "text": "Actions", "in": ["layers"], "with": ""})).contains("can't be empty")); +} + +#[test] +fn colours_keep_alpha_and_fonts_lay_out_again() { + let (mut s, ..) = movie(); + let v = run(&mut s, "find.replace", json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "scope": "document"})); + assert_eq!(v["replaced"], 5, "{v}"); + assert!(hits(&mut s, json!({"kind": "color", "color": "#ff0000", "scope": "document"})).is_empty()); + let r = &s.doc.timeline(0).layers[1].keyframes[0].elements[1]; + match &r.kind { + ElementKind::Shape(sh) => assert_eq!(sh.fill, Some(Paint::Solid(Rgba::hex(0x00ff00).with_alpha(0.5)))), + other => panic!("{other:?}"), + } + match &s.doc.timeline(1).layers[0].keyframes[0].elements[0].kind { + ElementKind::Shape(sh) => assert!(matches!(&sh.fill, Some(Paint::Linear { stops, .. }) if stops[0].color == Rgba::hex(0x00ff00) && stops[1].color == Rgba::WHITE)), + other => panic!("{other:?}"), + } + let v = run(&mut s, "find.replace", json!({"kind": "font", "font": "Test Sans", "with": "Inter"})); + assert_eq!(v["replaced"], 3); + assert!(hits(&mut s, json!({"kind": "font", "font": "test sans"})).is_empty()); +} + +#[test] +fn a_symbol_that_would_contain_itself_is_skipped() { + let (mut s, outer, inner, unused) = movie(); + // Inner's instance is inside Outer: swapping it for Outer would nest Outer in itself. + assert!(err(&mut s, "find.replace", json!({"kind": "symbol", "symbol": inner.0, "with": outer.0})).contains("contain itself")); + // Into a symbol that doesn't hold the place: fine (and the scene's Outer becomes Unused). + let v = run(&mut s, "find.replace", json!({"kind": "symbol", "symbol": outer.0, "with": unused.0})); + assert_eq!(v["replaced"], 1); + let v = run(&mut s, "find.replace", json!({"kind": "symbol", "symbol": inner.0, "with": unused.0, "scope": "document"})); + assert_eq!(v["replaced"], 1); +} + +#[test] +fn replace_all_over_many_places_asks_first() { + let mut b = Build::new(); + let els: Vec = (0..(REPLACE_ASK + 1)).map(|_| b.rect(Paint::Solid(Rgba::hex(RED)), None)).collect(); + let l = b.layer("L", vec![(0, 1, "", els)]); + b.scene("S", vec![l]); + let mut s = Session::new(b.doc); + let p = json!({"kind": "color", "color": "#ff0000", "with": "#000000"}); + let c = s.confirmation("find.replace", &p).expect("asks above the limit"); + assert!(!c.irreversible && c.message.contains("101 places"), "{c:?}"); + // One place (Replace) never asks. + let one = hits(&mut s, p.clone()).remove(0); + let mut p1 = p.clone(); + p1["at"] = one; + assert!(s.confirmation("find.replace", &p1).is_none()); + // Undoable, so a script runs it without "confirm". + assert_eq!(run(&mut s, "find.replace", p)["replaced"], 101); +} + +#[test] +fn going_to_a_hit_opens_the_symbols_in_place_and_selects_it() { + let (mut s, outer, inner, unused) = movie(); + // Inner's text: through hero (Outer) and wheel (Inner), in place. + let h = hits(&mut s, json!({"kind": "text", "text": "inside"})).remove(0); + let v = run(&mut s, "find.goto", h.clone()); + let open: Vec = s.editing.iter().map(|l| l.symbol().unwrap_or(SymbolId(0))).collect(); + assert_eq!(open, [outer, inner], "{v}"); + assert!(s.editing.iter().all(|l| l.instance.is_some())); + assert_eq!(s.selection.id_list(), [h["element"].as_u64().unwrap()]); + assert_eq!(s.edit_view().map(|v| v.in_place), Some(true)); + // A symbol no scene uses opens alone, from the Library. + let h = hits(&mut s, json!({"kind": "text", "text": "unused", "scope": "document"})).remove(0); + run(&mut s, "find.goto", h.clone()); + assert_eq!((s.editing.len(), s.editing_symbol(), s.editing[0].instance), (1, Some(unused), None)); + assert_eq!(s.selection.id_list(), [h["element"].as_u64().unwrap()]); + // Another scene: the scene switches, the frame is the keyframe's. + let h = hits(&mut s, json!({"kind": "color", "color": "#ff0000", "scope": "document"})); + let back = h.iter().find(|h| h["scene"] == 1).cloned().unwrap(); + run(&mut s, "find.goto", back); + assert_eq!((s.scene, s.editing.len(), s.selection.len()), (1, 0, 1)); + // A label: the keyframe, nothing selected. + let h = hits(&mut s, json!({"kind": "text", "text": "intro", "scope": "document"})).remove(0); + run(&mut s, "find.goto", h); + assert_eq!((s.scene, s.frame, s.selection.len()), (0, 10, 0)); + assert_eq!(s.active_layer().map(|l| l.name.as_str()), Some("Art")); + // Going somewhere records nothing to undo. + assert!(!s.can_undo()); + assert!(err(&mut s, "find.goto", json!({})).contains("where")); + assert!(err(&mut s, "find.goto", json!({"layer": 999_999})).contains("no layer")); +} + +#[test] +fn going_to_a_symbol_behind_a_locked_layer_opens_it_alone() { + let (mut s, outer, ..) = movie(); + let art = s.doc.timeline(0).layers[1].id.0; + run(&mut s, "layer.toggle_lock", json!({"layer": art})); + let h = hits(&mut s, json!({"kind": "color", "color": "#ff0000", "in": ["fills"]})); + let inside = h.iter().find(|h| h["symbol"] == outer.0).cloned().unwrap(); + run(&mut s, "find.goto", inside); + assert_eq!((s.editing_symbol(), s.editing[0].instance), (Some(outer), None)); +} + +#[test] +fn search_and_replace_are_fast_on_a_large_document() { + // 40 layers × 300 keyframes (12,000 text fields and 12,000 shapes), 500 symbols. + let mut b = Build::new(); + let mut layers = Vec::new(); + for li in 0..40 { + let keys: Vec<(u32, u32, &str, Vec)> = (0..300).map(|k| (k, 1, "", vec![b.text(&format!("caption {li} {k} needle"), Rgba::BLACK), b.rect(Paint::Solid(Rgba::hex(RED)), None)])).collect(); + layers.push(b.layer(&format!("Layer {li}"), keys)); + } + b.scene("Big", layers); + for i in 0..500 { + let id = b.symbol(&format!("S{i}"), SymbolKind::Graphic); + let r = b.rect(Paint::Solid(Rgba::hex(RED)), None); + let l = b.layer("x", vec![(0, 1, "", vec![r])]); + b.fill(id, vec![l]); + } + let mut s = Session::new(b.doc); + let t0 = std::time::Instant::now(); + let n = run(&mut s, "find.search", json!({"kind": "text", "text": "needle", "whole_word": true, "limit": 1}))["total"].as_u64(); + let text = t0.elapsed(); + let t0 = std::time::Instant::now(); + let c = run(&mut s, "find.search", json!({"kind": "color", "color": "#ff0000", "scope": "document", "limit": 1}))["total"].as_u64(); + let colour = t0.elapsed(); + let t0 = std::time::Instant::now(); + let r = run(&mut s, "find.replace", json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "scope": "document"}))["replaced"].as_u64(); + let replace = t0.elapsed(); + let t0 = std::time::Instant::now(); + run(&mut s, "edit.undo", json!({})); + let undo = t0.elapsed(); + println!("find on 24,000 elements: text {text:?}, colour {colour:?}; Replace All of 12,500 colours {replace:?}, its undo {undo:?}"); + assert_eq!((n, c, r), (Some(12_000), Some(12_500), Some(12_500))); + assert!(text.as_secs_f64() < 2.0 && colour.as_secs_f64() < 2.0 && replace.as_secs_f64() < 5.0); +} + +#[test] +fn random_queries_never_panic() { + let (s0, outer, inner, _) = movie(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let atoms = ["a", "(", ")", "*", "+", "?", "|", "\\b", "\\w", "[", "]", "{2,}", ".", "^", "$", "hello", "é", "\\", "$1", "${x}", "\n"]; + let kinds = ["text", "font", "color", "symbol", "sound", "bitmap", "x"]; + let mut s = s0; + for _ in 0..400 { + let pat: String = (0..(next() % 6)).map(|_| atoms[(next() % atoms.len() as u64) as usize]).collect(); + let with: String = (0..(next() % 4)).map(|_| atoms[(next() % atoms.len() as u64) as usize]).collect(); + let kind = kinds[(next() % kinds.len() as u64) as usize]; + let id = [outer.0, inner.0, next()][(next() % 3) as usize]; + let p = json!({"kind": kind, "text": pat, "regex": next() % 2 == 0, "whole_word": next() % 3 == 0, "match_case": next() % 2 == 0, "font": pat, "color": format!("#{:06x}", next() % 0xffffff), "symbol": id, "sound": id, "bitmap": id, "with": if next() % 2 == 0 { json!(with) } else { json!(id) }, "scope": if next() % 2 == 0 { "scene" } else { "document" }}); + if let Ok(v) = s.execute("find.search", &p) + && let Some(h) = v["hits"].as_array().and_then(|h| h.first()) + { + let _ = s.execute("find.goto", h); + let mut one = p.clone(); + one["at"] = h.clone(); + let _ = s.execute("find.replace", &one); + } + let _ = s.execute("find.replace", &p); + if next() % 7 == 0 { + let _ = s.execute("edit.undo", &json!({})); + } + } + let _ = anicraft_render::render_frame(&s.doc, 0, 0.1); +} + +#[test] +fn the_new_namespaces_are_open_to_plug_ins() { + for id in ["find.search", "find.replace", "find.goto", "explorer.tree"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/format.rs b/crates/engine/src/format.rs index 1d8c3db0..5cd9b074 100644 --- a/crates/engine/src/format.rs +++ b/crates/engine/src/format.rs @@ -3,85 +3,36 @@ use crate::EngineError; use anicraft_doc::{Document, path_table}; use anicraft_geom::Path; -use serde::{Deserialize, Serialize}; +use craft_anicraft_format::PayloadDecoder; +pub use craft_anicraft_format::{FORMAT_NAME, FORMAT_VERSION, MAX_FILE_BYTES}; +use serde::Deserialize; use std::sync::Arc; -pub const FORMAT_NAME: &str = "anicraft"; -/// v1: inline tagged paths. v2: SVG path strings, shared paths stored once in `paths`. -/// v3: `scenes` (a list of named timelines) instead of one `timeline`; v1/v2 files load as one -/// scene. -pub const FORMAT_VERSION: u32 = 3; -/// Largest file we will parse. -pub const MAX_FILE_BYTES: u64 = 1024 * 1024 * 1024; -/// Files smaller than this (compact) are pretty-printed for humans and diffs. -const PRETTY_LIMIT: usize = 1024 * 1024; +/// AniCraft document deserialization uses its own path-table scope while the shared format crate +/// controls when a payload is decoded in the envelope stream. +struct DocumentDecoder; -/// Written in this field order: the path table precedes the document, so a reader can stream -/// the file in one pass with references already resolvable. -#[derive(Serialize)] -struct EnvelopeOut<'a> { - format: &'a str, - version: u32, - generator: String, - paths: &'a [Arc], - document: &'a Document, -} +impl PayloadDecoder> for DocumentDecoder { + type Document = Document; -/// Streaming reader: when `paths` arrives it opens a path-table scope for `document`. -struct EnvelopeIn { - format: String, - version: u32, - document: Option, -} - -impl<'de> Deserialize<'de> for EnvelopeIn { - fn deserialize>(d: D) -> Result { - struct V; - impl<'de> serde::de::Visitor<'de> for V { - type Value = EnvelopeIn; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("an .anicraft envelope object") - } - fn visit_map>(self, mut map: A) -> Result { - let (mut format, mut version, mut document) = (None, None, None); - let mut _scope = None; - while let Some(key) = map.next_key::()? { - match key.as_str() { - "format" => format = Some(map.next_value::()?), - "version" => version = Some(map.next_value::()?), - "paths" => { - let paths: Vec = map.next_value()?; - _scope = Some(path_table::begin_read(paths.into_iter().map(Arc::new).collect())); - } - "document" => document = Some(map.next_value::()?), - _ => { - map.next_value::()?; - } - } - } - Ok(EnvelopeIn { - format: format.ok_or_else(|| serde::de::Error::missing_field("format"))?, - version: version.ok_or_else(|| serde::de::Error::missing_field("version"))?, - document, - }) - } - } - d.deserialize_map(V) + fn decode<'de, D>(&mut self, deserializer: D, paths: Option>>) -> Result + where + D: serde::Deserializer<'de>, + { + let _scope = paths.map(path_table::begin_read); + Document::deserialize(deserializer) } } pub fn to_json(doc: &Document) -> Result { let paths = path_table::build_table(doc); - let env = EnvelopeOut { format: FORMAT_NAME, version: FORMAT_VERSION, generator: format!("AniCraft {}", env!("CARGO_PKG_VERSION")), paths: &paths, document: doc }; - let compact = path_table::write_with_paths(&paths, || serde_json::to_string(&env)).map_err(|e| EngineError::Format(e.to_string()))?; - if compact.len() < PRETTY_LIMIT { - return path_table::write_with_paths(&paths, || serde_json::to_string_pretty(&env)).map_err(|e| EngineError::Format(e.to_string())); - } - Ok(compact) + let generator = format!("AniCraft {}", env!("CARGO_PKG_VERSION")); + path_table::write_with_paths(&paths, || craft_anicraft_format::write(&generator, &paths, doc)).map_err(|e| EngineError::Format(e.to_string())) } pub fn from_json(text: &str) -> Result { - let env: EnvelopeIn = serde_json::from_str(text).map_err(|e| EngineError::Format(format!("not a valid .anicraft file: {e}")))?; + let env = craft_anicraft_format::read::, _>(text, &mut DocumentDecoder) + .map_err(|e| EngineError::Format(format!("not a valid .anicraft file: {e}")))?; if env.format != FORMAT_NAME { return Err(EngineError::Format(format!("unexpected format '{}'", env.format))); } @@ -136,10 +87,48 @@ mod tests { let back = from_json(&json).unwrap(); assert_eq!(d, back); let l = &back.timeline(0).layers[0]; - let (anicraft_doc::ElementKind::Shape(a), anicraft_doc::ElementKind::Shape(b)) = (&l.keyframes[0].elements[0].kind, &l.keyframes[3].elements[0].kind) else { panic!() }; + let (anicraft_doc::ElementKind::Shape(a), anicraft_doc::ElementKind::Shape(b)) = + (&l.keyframes[0].elements[0].kind, &l.keyframes[3].elements[0].kind) + else { + panic!() + }; assert!(Arc::ptr_eq(&a.path, &b.path), "sharing restored on load"); } + #[test] + fn duplicate_envelope_keys_keep_last_values_and_path_table_scope() { + let doc = sample::stress(2, 40, 48); + let wire: serde_json::Value = serde_json::from_str(&to_json(&doc).unwrap()).unwrap(); + let paths = wire["paths"].as_array().unwrap(); + let mut earlier_paths = paths.clone(); + earlier_paths.reverse(); + assert_ne!(earlier_paths.as_slice(), paths.as_slice()); + let json = format!( + "{{\"format\":\"other\",\"format\":\"anicraft\",\"version\":99,\"version\":3,\"paths\":{},\"paths\":{},\"document\":{},\"ignored\":true}}", + serde_json::to_string(&earlier_paths).unwrap(), + serde_json::to_string(paths).unwrap(), + serde_json::to_string(&wire["document"]).unwrap(), + ); + assert_eq!(from_json(&json).unwrap(), doc); + } + + #[test] + fn malformed_earlier_duplicate_document_keeps_error_precedence_and_location() { + let doc = sample::demo(); + let wire: serde_json::Value = serde_json::from_str(&to_json(&doc).unwrap()).unwrap(); + let later_document = serde_json::to_string(&wire["document"]).unwrap(); + let json = format!("{{\n \"format\":\"anicraft\",\n \"version\":3,\n \"document\":null,\n \"document\":{later_document}\n}}"); + let error = from_json(&json).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("not a valid .anicraft file: invalid type: null"), "{error}"); + assert!(error.contains("line 4"), "payload diagnostics keep source locations: {error}"); + } + + #[test] + fn absent_document_keeps_the_native_format_error() { + let error = from_json(r#"{"format":"anicraft","version":3}"#).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("the file has no document"), "{error}"); + } + #[test] fn version_1_files_still_load() { let v1 = r#"{"format":"anicraft","version":1,"document":{"timeline":{"layers":[{"id":1,"name":"L","keyframes":[{"start":0,"duration":2,"elements":[ @@ -166,7 +155,10 @@ mod tests { #[test] fn missing_fields_default() { - let d = from_json(r#"{"format":"anicraft","version":1,"document":{"stage":{"width":0,"height":50,"fps":-3,"background":{"r":2,"g":0,"b":0,"a":1}}}}"#).unwrap(); + let d = from_json( + r#"{"format":"anicraft","version":1,"document":{"stage":{"width":0,"height":50,"fps":-3,"background":{"r":2,"g":0,"b":0,"a":1}}}}"#, + ) + .unwrap(); assert_eq!(d.stage.width, 1); assert_eq!(d.stage.fps, 24.0); assert_eq!(d.stage.background.r, 1.0); diff --git a/crates/engine/src/gradient_tests.rs b/crates/engine/src/gradient_tests.rs new file mode 100644 index 00000000..9c204125 --- /dev/null +++ b/crates/engine/src/gradient_tests.rs @@ -0,0 +1,244 @@ +//! The fill swatch's gradients, Lock Fill and the Gradient Transform tool's command (ADR 0074). + +use crate::Session; +use anicraft_doc::{ElementId, ElementKind, Paint, Rgba, Shape, Spread}; +use anicraft_geom::{Affine, Vec2}; +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 shape(s: &Session, id: u64) -> (Shape, Affine) { + s.visible_elements() + .iter() + .find(|e| e.id == ElementId(id)) + .and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some((sh.clone(), e.transform)), + _ => None, + }) + .expect("a shape") +} + +/// A 100 × 100 square at (x, 100), selected (drawing commands select what they draw). +fn square(s: &mut Session, x: f32) -> u64 { + run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}))["element"].as_u64().unwrap() +} + +/// A 100 × 100 square at (x, 100) in the fill swatch. +fn poured(s: &mut Session, x: f32) -> u64 { + run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "stroke": null}))["element"].as_u64().unwrap() +} + +/// Where a shape's fill lies on the stage. +fn stage_frame(s: &Session, id: u64) -> Affine { + let (sh, m) = shape(s, id); + m.mul(&sh.fill.and_then(|f| f.frame(None)).expect("a gradient")) +} + +fn near(a: &Affine, b: &Affine) -> bool { + a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() <= 1e-3 * x.abs().max(y.abs()).max(1.0)) +} + +const RAMP: &str = r##"[{"offset": 0, "color": "#ff8800"}, {"offset": 0.5, "color": "#ffffff80"}, {"offset": 1, "color": "#0044ff"}]"##; + +#[test] +fn set_fill_makes_gradients_for_the_swatch_and_the_selection_in_one_step() { + let mut s = Session::default(); + let a = square(&mut s, 100.0); + let steps = s.history_len(); + let stops: Value = serde_json::from_str(RAMP).unwrap(); + let r = run(&mut s, "paint.set_fill", json!({"type": "linear", "stops": stops, "spread": "reflect", "linear_rgb": true})); + assert_eq!(r["changed"], 1); + assert_eq!(r["fill"]["type"], "linear"); + assert_eq!(r["fill"]["stops"][1]["color"], "#ffffff80", "alpha survives as #rrggbbaa"); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + // The selected square's fill is fitted to it: across its width, through its middle. + match shape(&s, a).0.fill { + Some(Paint::Linear { start, end, stops, spread, linear_rgb }) => { + assert_eq!((start, end), (Vec2::new(-50.0, 0.0), Vec2::new(50.0, 0.0))); + assert_eq!((stops.len(), spread, linear_rgb), (3, Spread::Reflect, true)); + assert!((stops[1].color.a - 128.0 / 255.0).abs() < 1e-6); + } + other => panic!("{other:?}"), + } + // The swatch holds it too (across the stage), so the next shape gets it, fitted. + assert!(matches!(s.style.fill_paint, Some(Paint::Linear { .. }))); + assert_eq!(s.style.fill, Rgba::hex(0xff8800), "the swatch shows the first colour"); + let b = run(&mut s, "draw.rect", json!({"x": 300, "y": 300, "w": 200, "h": 40, "stroke": null}))["element"].as_u64().unwrap(); + assert!(near(&stage_frame(&s, b), &Affine { m: [100.0, 0.0, 0.0, 100.0, 400.0, 320.0] }), "{:?}", stage_frame(&s, b)); + // Undo puts the solid colour back. + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(shape(&s, a).0.fill, Some(Paint::Solid(Rgba::hex(0xff0000)))); +} + +#[test] +fn editing_stops_keeps_where_a_gradient_lies() { + let mut s = Session::default(); + let a = square(&mut s, 100.0); + run(&mut s, "paint.set_fill", json!({"type": "radial"})); + // A white-to-black ring round the square's centre, touching its sides. + assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] })); + run(&mut s, "paint.transform_fill", json!({"move": [10, 0], "scale_x": 2})); + let moved = stage_frame(&s, a); + // New stops, overflow and focal point: the ring stays put. + let stops: Value = serde_json::from_str(RAMP).unwrap(); + run(&mut s, "paint.set_fill", json!({"stops": stops, "spread": "repeat", "focal": 0.5})); + assert!(near(&stage_frame(&s, a), &moved)); + match shape(&s, a).0.fill { + Some(Paint::Radial { stops, spread, focal, .. }) => assert_eq!((stops.len(), spread, focal), (3, Spread::Repeat, 0.5)), + other => panic!("{other:?}"), + } + // Changing kind fits it again; back to solid, and the swatch is solid too. + run(&mut s, "paint.set_fill", json!({"type": "linear"})); + assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] })); + assert!(matches!(shape(&s, a).0.fill, Some(Paint::Linear { spread: Spread::Repeat, .. })), "the gradient keeps its colours and overflow"); + run(&mut s, "paint.set_fill", json!({"type": "solid", "color": "#00ff00"})); + assert_eq!(shape(&s, a).0.fill, Some(Paint::Solid(Rgba::hex(0x00ff00)))); + assert!(s.style.fill_paint.is_none()); +} + +#[test] +fn set_fill_checks_its_params() { + let mut s = Session::default(); + square(&mut s, 100.0); + for bad in [ + json!({"type": "conic"}), + json!({"stops": [{"offset": 0, "color": "#ff0000"}]}), + json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1.5, "color": "#ff0000"}]}), + json!({"stops": [{"offset": 0, "color": "red"}, {"offset": 1, "color": "#ff0000"}]}), + json!({"stops": (0..16).map(|i| json!({"offset": i as f32 / 15.0, "color": "#000000"})).collect::>()}), + json!({"spread": "mirror"}), + json!({"focal": 1.0}), + json!({"type": "bitmap"}), + json!({"type": "bitmap", "bitmap": 999}), + ] { + let before = s.doc.clone(); + assert!(s.execute("paint.set_fill", &bad).is_err(), "{bad}"); + assert!(s.doc == before, "{bad} changed nothing"); + } + // Unselected: only the swatch. + s.selection.clear(); + let r = run(&mut s, "paint.set_fill", json!({"type": "radial"})); + assert_eq!(r["changed"], 0); + assert!(matches!(s.style.fill_paint, Some(Paint::Radial { .. }))); +} + +#[test] +fn transform_fill_moves_turns_scales_and_skews_analytically() { + let mut s = Session::default(); + let a = square(&mut s, 100.0); + run(&mut s, "paint.set_fill", json!({"type": "linear"})); + let f0 = stage_frame(&s, a); + // Scale along the gradient (its own x), then turn 90° about its centre, then move. + run(&mut s, "paint.transform_fill", json!({"scale_x": 0.5, "rotate": 90, "move": [5, -5]})); + let want = Affine::translate(5.0, -5.0).mul(&Affine::translate(150.0, 150.0)).mul(&Affine::rotate(std::f32::consts::FRAC_PI_2)).mul(&Affine::translate(-150.0, -150.0)).mul(&f0).mul(&Affine::scale(0.5, 1.0)); + let got = stage_frame(&s, a); + // A linear gradient keeps only its axis: compare the ends. + for x in [-1.0, 1.0] { + assert!(got.apply(Vec2::new(x, 0.0)).distance(want.apply(Vec2::new(x, 0.0))) < 1e-3, "{got:?} vs {want:?}"); + } + match shape(&s, a).0.fill { + Some(Paint::Linear { start, end, .. }) => { + assert!(start.distance(Vec2::new(5.0, -30.0)) < 1e-3 && end.distance(Vec2::new(5.0, 20.0)) < 1e-3, "{start:?} {end:?}"); + } + other => panic!("{other:?}"), + } + // A radial gradient takes any frame: skew and an absolute frame are kept exactly. + run(&mut s, "paint.set_fill", json!({"type": "radial"})); + let f1 = stage_frame(&s, a); + run(&mut s, "paint.transform_fill", json!({"skew_x": 30, "focal": -0.25})); + let want = f1.mul(&Affine { m: [1.0, 0.0, 30f32.to_radians().tan(), 1.0, 0.0, 0.0] }); + assert!(near(&stage_frame(&s, a), &want), "{:?}", stage_frame(&s, a)); + assert!(matches!(shape(&s, a).0.fill, Some(Paint::Radial { focal, .. }) if focal == -0.25)); + let frame = [40.0, 10.0, -5.0, 20.0, 160.0, 140.0]; + let r = run(&mut s, "paint.transform_fill", json!({"element": a, "frame": frame})); + assert_eq!(r["changed"], 1); + assert!(near(&stage_frame(&s, a), &Affine { m: frame })); + // The result reports the frames, so a script can carry on from them. + assert_eq!(r["frames"][0].as_array().map(Vec::len), Some(6)); +} + +#[test] +fn transform_fill_turns_bitmap_fills_and_refuses_what_it_cannot_do() { + let mut s = Session::default(); + // A 4 × 2 bitmap from the library, poured into a square. + let png = anicraft_render::encode_png(4, 2, &[255; 32]).unwrap(); + let id = s.doc.alloc_id(); + s.doc.bitmaps.push(std::sync::Arc::new(anicraft_doc::Bitmap::from_png(anicraft_doc::BitmapId(id), "tile.png", png).unwrap())); + let a = square(&mut s, 100.0); + run(&mut s, "paint.set_fill", json!({"type": "bitmap", "bitmap": id})); + let (sh, m) = shape(&s, a); + let fill = sh.fill.clone().unwrap(); + let frame = |s: &Session| { + let (sh, m) = shape(s, a); + let f = sh.fill.unwrap(); + m.mul(&f.frame(Some((4.0, 2.0))).unwrap()) + }; + // Tiled from the square's top-left at its own size. + assert!(near(&m.mul(&fill.frame(Some((4.0, 2.0))).unwrap()), &Affine { m: [2.0, 0.0, 0.0, 1.0, 102.0, 101.0] })); + let f0 = frame(&s); + let steps = s.history_len(); + run(&mut s, "paint.transform_fill", json!({"scale": 3, "skew_y": 20, "rotate": -45})); + assert_eq!(s.history_len(), steps + 1, "one step"); + let c = f0.apply(Vec2::ZERO); + let want = Affine::translate(c.x, c.y).mul(&Affine::rotate(-std::f32::consts::FRAC_PI_4)).mul(&Affine::translate(-c.x, -c.y)).mul(&f0).mul(&Affine::scale(3.0, 3.0)).mul(&Affine { m: [1.0, 20f32.to_radians().tan(), 0.0, 1.0, 0.0, 0.0] }); + assert!(near(&frame(&s), &want), "{:?} vs {want:?}", frame(&s)); + // Nothing to flatten a fill to, nor a solid fill to transform. + let before = s.doc.clone(); + assert!(s.execute("paint.transform_fill", &json!({"frame": [1, 0, 2, 0, 0, 0]})).is_err()); + assert!(s.execute("paint.transform_fill", &json!({"scale_x": 0})).is_err()); + assert!(s.execute("paint.transform_fill", &json!({"skew_x": 90})).is_err()); + assert!(s.doc == before); + let b = square(&mut s, 300.0); + assert!(s.execute("paint.transform_fill", &json!({"element": b, "move": [1, 1]})).is_err(), "a solid fill has no gradient to move"); + s.selection.clear(); + assert!(s.execute("paint.transform_fill", &json!({"move": [1, 1]})).is_err(), "nothing selected"); +} + +#[test] +fn lock_fill_runs_one_gradient_across_shapes() { + let mut s = Session::default(); + s.selection.clear(); + run(&mut s, "paint.set_fill", json!({"type": "linear"})); + // The swatch spans the stage, left to right. + let w = s.doc.stage.width as f32; + match &s.style.fill_paint { + Some(Paint::Linear { start, end, .. }) => assert_eq!((start.x, end.x), (0.0, w)), + other => panic!("{other:?}"), + } + // Unlocked (the default), each shape gets its own ramp. + let a = poured(&mut s, 100.0); + assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] })); + // Locked, the swatch's ramp across the stage, in each shape's own space. + let r = run(&mut s, "paint.lock_fill", json!({})); + assert_eq!(r["on"], true); + let b = poured(&mut s, 300.0); + let f = stage_frame(&s, b); + assert!(f.apply(Vec2::new(-1.0, 0.0)).x.abs() < 1e-3 && (f.apply(Vec2::new(1.0, 0.0)).x - w).abs() < 1e-3, "{f:?}"); + // The Paint Bucket follows it too: a click on the unlocked square locks its ramp to the stage. + run(&mut s, "paint.bucket", json!({"x": 150, "y": 150})); + let f = stage_frame(&s, a); + assert!(f.apply(Vec2::new(-1.0, 0.0)).x.abs() < 1e-3, "{f:?}"); + assert_eq!(run(&mut s, "paint.lock_fill", json!({"on": false}))["on"], false); + run(&mut s, "paint.bucket", json!({"x": 350, "y": 150})); + assert!(near(&stage_frame(&s, b), &Affine { m: [50.0, 0.0, 0.0, 50.0, 350.0, 150.0] })); + assert!(s.execute("paint.lock_fill", &json!({"on": "yes"})).is_err()); +} + +#[test] +fn a_raw_fill_keeps_its_id_through_a_drag_of_its_gradient() { + // The editor draws raw (merge) shapes; the Gradient Transform tool addresses one by id + // through every step of a drag, so moving where its fill lies never re-merges it. + let mut s = Session::default(); + s.style.object_drawing = false; + let a = square(&mut s, 100.0); + run(&mut s, "paint.set_fill", json!({"type": "radial"})); + let id = s.selection.id_list().first().copied().unwrap_or(a); + for k in 1..=3 { + let r = run(&mut s, "paint.transform_fill", json!({"element": id, "frame": [50.0 + 10.0 * k as f32, 0, 0, 50, 150, 150]})); + assert_eq!(r["changed"], 1, "step {k}"); + } + assert!(near(&stage_frame(&s, id), &Affine { m: [80.0, 0.0, 0.0, 50.0, 150.0, 150.0] })); +} diff --git a/crates/engine/src/group_tests.rs b/crates/engine/src/group_tests.rs new file mode 100644 index 00000000..bf1221fb --- /dev/null +++ b/crates/engine/src/group_tests.rs @@ -0,0 +1,365 @@ +//! Groups and Combine Objects (ADR 0073). + +use crate::Session; +use crate::cmds_group::even_odd_area; +use anicraft_doc::{Element, ElementId, ElementKind}; +use anicraft_geom::{Affine, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn id_of(v: &Value, key: &str) -> ElementId { + ElementId(v[key].as_u64().unwrap_or_else(|| panic!("no {key} in {v}"))) +} + +fn top(s: &Session) -> Vec> { + s.visible_elements() +} + +/// Every drawn item's transform, path and fill, in order: what the movie shows, exactly. +fn picture(s: &Session) -> Vec<([u32; 6], usize, String)> { + let dl = anicraft_doc::evaluate_scene(&s.doc, s.scene, s.frame); + dl.items.iter().map(|i| (i.transform.m.map(f32::to_bits), i.path.cmds.len(), format!("{:?}{:?}{:?}", i.fill, i.stroke, i.color))).collect() +} + +/// Three objects: a rotated, scaled red square, a blue oval and a green star; Object Drawing on. +fn three() -> (Session, [ElementId; 3]) { + let mut s = Session::new(anicraft_doc::Document::default()); + let a = run(&mut s, "draw.rect", json!({"x": 10, "y": 20, "w": 100, "h": 60, "fill": "#ff0000", "stroke": "#000000"})); + let a = id_of(&a, "element"); + run(&mut s, "element.set_transform", json!({"rotation": 33.0, "sx": 1.3, "sy": 0.7})); + let b = id_of(&run(&mut s, "draw.ellipse", json!({"x": 140, "y": 50, "w": 80, "h": 50, "fill": "#0000ff"})), "element"); + let c = id_of(&run(&mut s, "draw.star", json!({"cx": 300, "cy": 200, "outer": 40, "fill": "#00ff00"})), "element"); + (s, [a, b, c]) +} + +#[test] +fn group_and_ungroup_keep_every_members_place_exactly() { + let (mut s, ids) = three(); + let before = picture(&s); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + let v = run(&mut s, "modify.group", json!({})); + let g = id_of(&v, "group"); + assert_eq!(v["members"], json!(3)); + assert_eq!(top(&s).len(), 1, "one group on the layer"); + assert_eq!(s.selection.id_list(), vec![g.0]); + assert_eq!(picture(&s), before, "grouping changes nothing drawn"); + // Picking anything in it picks the group. + assert_eq!(s.hit_test(Vec2::new(300.0, 200.0), 1.0).map(|x| x.1), Some(g)); + // One undo step. + run(&mut s, "edit.undo", json!({})); + assert_eq!(top(&s).len(), 3); + run(&mut s, "edit.redo", json!({})); + // Moved and scaled as one, then ungrouped: each member is where the group showed it, bit for bit. + run(&mut s, "modify.transform", json!({"a": 1.5, "b": 0.2, "c": -0.1, "d": 0.8, "e": 12.5, "f": -7.25})); + let moved = picture(&s); + let v = run(&mut s, "modify.ungroup", json!({})); + assert_eq!(v["members"], json!(3)); + assert_eq!(picture(&s), moved, "ungrouping changes nothing drawn"); + let back: Vec = top(&s).iter().map(|e| e.id).collect(); + assert_eq!(back, ids.to_vec(), "members keep their ids and order"); + assert_eq!(s.selection.id_list().len(), 3); +} + +#[test] +fn groups_nest_and_take_the_topmost_members_place() { + let (mut s, [a, b, c]) = three(); + let before = picture(&s); + run(&mut s, "element.select", json!({"ids": [a.0, b.0]})); + let g1 = id_of(&run(&mut s, "modify.group", json!({})), "group"); + // The group stands where its topmost member stood: under the star. + assert_eq!(top(&s).iter().map(|e| e.id).collect::>(), vec![g1, c]); + run(&mut s, "element.select", json!({"ids": [g1.0, c.0]})); + let g2 = id_of(&run(&mut s, "modify.group", json!({})), "group"); + assert_eq!(picture(&s), before); + assert_eq!(crate::cmds_group::group_depth(&top(&s)[0]), 2); + // Break Apart on a group ungroups it, one level. + run(&mut s, "element.select", json!({"ids": [g2.0]})); + run(&mut s, "modify.break_apart", json!({})); + assert_eq!(top(&s).len(), 2); + assert_eq!(picture(&s), before); + // Ungroup a group that holds nothing selected says so. + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("modify.ungroup", &json!({})).is_err()); +} + +#[test] +fn a_group_opens_in_place_and_edits_there_with_every_tool() { + let (mut s, ids) = three(); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + let g = id_of(&run(&mut s, "modify.group", json!({})), "group"); + run(&mut s, "modify.transform", json!({"a": 1, "b": 0, "c": 0, "d": 1, "e": 100, "f": 50})); + let steps = s.history_len(); + let v = run(&mut s, "symbol.edit", json!({"id": g.0})); + assert_eq!(v["editing"][0]["group"], json!(g.0), "{v}"); + assert!(s.editing_group() && s.editing_symbol().is_none()); + assert_eq!(s.history_len(), steps, "opening is not an edit"); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + assert!(view.in_place && view.origin.distance(Vec2::new(100.0, 50.0)) < 1e-4, "{view:?}"); + // Inside: the members, in the group's space. + assert_eq!(top(&s).len(), 3); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "fill": "#123456"})); + assert_eq!(top(&s).len(), 4); + // A group is one layer and one frame. + assert!(s.execute("layer.new", &json!({})).is_err()); + assert!(s.execute("timeline.insert_keyframe", &json!({})).is_err()); + let _ = s.execute("timeline.goto", &json!({"frame": 5})); + assert_eq!(s.frame, 0, "the playhead stays on the group's frame"); + // The stage shows the edit where the group stands, the rest dimmed. + let pic = s.stage_picture(); + assert!(pic.front.is_some()); + run(&mut s, "symbol.exit", json!({})); + assert_eq!(s.selection.id_list(), vec![g.0], "the group is selected again"); + let members = top(&s)[0].kind.group_members(); + assert_eq!(members.len(), 4); + let new = members.last().cloned().unwrap_or_else(|| panic!("member")); + // The new rectangle sits at (100, 50) + its place inside, on the stage. + let b = s.element_bounds(g); + assert!(b.min.x <= 100.5 && b.min.y <= 50.5, "{b:?}"); + assert!(matches!(new.kind, ElementKind::Shape(_))); + // Undo goes back inside, where the change was made. + run(&mut s, "edit.undo", json!({})); + assert!(s.editing_group()); + assert_eq!(top(&s).len(), 3); + // An ungroup undone from inside closes the group when it goes. + run(&mut s, "symbol.exit", json!({})); + run(&mut s, "modify.ungroup", json!({})); + assert!(s.editing.is_empty()); +} + +#[test] +fn raw_shapes_in_a_group_merge_only_with_each_other() { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + let g = id_of(&run(&mut s, "modify.group", json!({})), "group"); + // A raw square drawn over it leaves the grouped square whole. + run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null})); + let group = top(&s).into_iter().find(|e| e.id == g).unwrap_or_else(|| panic!("group")); + let m = group.kind.group_members(); + assert_eq!(m.len(), 1); + let ElementKind::Shape(sh) = &m[0].kind else { panic!("shape") }; + assert!((even_odd_area(&sh.path, &m[0].transform) - 10_000.0).abs() < 1.0); + // The group sits above the raw drawing, as objects do... and inside, a raw square merges. + run(&mut s, "symbol.edit", json!({"id": g.0})); + run(&mut s, "draw.rect", json!({"x": 50, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + let fills = top(&s); + assert_eq!(fills.len(), 1, "one red fill: the two squares joined"); + run(&mut s, "symbol.exit", json!({})); + // Ungrouped, the red fill merges with the blue square it now stands in. + run(&mut s, "modify.ungroup", json!({})); + let raw = top(&s); + assert!(raw.iter().all(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)), "all raw"); + let red: f64 = raw.iter().filter_map(|e| match &e.kind { + ElementKind::Shape(sh) if sh.fill == Some(anicraft_doc::Paint::Solid(anicraft_doc::Rgba::hex(0xff0000))) => Some(even_odd_area(&sh.path, &e.transform)), + _ => None, + }).sum(); + // Red (150 × 100) on top of blue: all of it shows. + assert!((red - 15_000.0).abs() < 2.0, "{red}"); +} + +#[test] +fn copies_of_a_group_ungroup_with_their_own_ids() { + let (mut s, ids) = three(); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + run(&mut s, "modify.group", json!({})); + run(&mut s, "edit.duplicate", json!({"dx": 10, "dy": 10})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.ungroup", json!({})); + let all: Vec = top(&s).iter().map(|e| e.id.0).collect(); + let mut unique = all.clone(); + unique.sort_unstable(); + unique.dedup(); + assert_eq!((all.len(), unique.len()), (6, 6), "{all:?}"); +} + +#[test] +fn groups_save_and_open_and_older_files_have_none() { + let (mut s, ids) = three(); + let plain = crate::format::to_json(&s.doc).unwrap_or_default(); + assert!(!plain.contains("Group"), "nothing new in files without groups"); + run(&mut s, "element.select", json!({"ids": [ids[0].0, ids[1].0]})); + run(&mut s, "modify.group", json!({})); + run(&mut s, "element.select", json!({"ids": [ids[2].0]})); + let text = crate::format::to_json(&s.doc).unwrap_or_default(); + let back = crate::format::from_json(&text).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(back, s.doc); + // Ids inside groups count: what a loaded document makes next is new. + let mut d = back.clone(); + let next = d.alloc_id(); + assert!(next > ids.iter().map(|i| i.0).max().unwrap_or(0)); +} + +#[test] +fn symbols_inside_groups_count_as_used_and_go_with_their_symbol() { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 50, "h": 50, "fill": "#ff0000"})); + let sym = run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"}))["symbol"].as_u64().unwrap_or(0); + run(&mut s, "draw.rect", json!({"x": 100, "y": 0, "w": 50, "h": 50, "fill": "#00ff00"})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.group", json!({})); + assert!(s.doc.unused_items().is_empty(), "the instance inside the group uses it"); + assert_eq!(s.doc.library_uses().len(), 1); + // Deleting the symbol takes its instance out of the group, and keeps the rest. + run(&mut s, "library.delete", json!({"items": [{"symbol": sym}], "confirm": true})); + let g = top(&s); + assert_eq!(g.len(), 1); + assert_eq!(g[0].kind.group_members().len(), 1); +} + +/// Two 100 × 100 squares, overlapping by 50 × 50, as drawing objects; the second on top. +fn squares(s: &mut Session) { + run(s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null})); + run(s, "edit.select_all", json!({})); +} + +fn areas(s: &Session) -> Vec { + top(s) + .iter() + .map(|e| match &e.kind { + ElementKind::Shape(sh) => even_odd_area(&sh.path, &e.transform), + ElementKind::Group { .. } => e.kind.group_members().iter().filter_map(|m| match &m.kind { + ElementKind::Shape(sh) if sh.fill.is_some() => Some(even_odd_area(&sh.path, &e.transform.mul(&m.transform))), + _ => None, + }).sum(), + _ => 0.0, + }) + .collect() +} + +#[test] +fn combine_objects_areas_are_exact() { + let near = |a: &[f64], b: &[f64]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5); + // Union of two colours: a group of the merged pieces, whose area is the union's. + let mut s = Session::new(anicraft_doc::Document::default()); + squares(&mut s); + let v = run(&mut s, "modify.combine", json!({"op": "union"})); + assert_eq!(v["created"].as_array().map(Vec::len), Some(1)); + assert!(matches!(top(&s)[0].kind, ElementKind::Group { .. })); + assert!(near(&areas(&s), &[17_500.0]), "{:?}", areas(&s)); + // Intersect: the overlap, in the top's colour. + let mut s = Session::new(anicraft_doc::Document::default()); + squares(&mut s); + run(&mut s, "modify.intersect", json!({})); + assert!(near(&areas(&s), &[2_500.0]), "{:?}", areas(&s)); + assert!(matches!(&top(&s)[0].kind, ElementKind::Shape(sh) if sh.fill == Some(anicraft_doc::Paint::Solid(anicraft_doc::Rgba::hex(0x0000ff))) && !sh.merge)); + // Punch: the bottom square less the top one, which goes. + let mut s = Session::new(anicraft_doc::Document::default()); + squares(&mut s); + run(&mut s, "modify.punch", json!({})); + assert!(near(&areas(&s), &[7_500.0]), "{:?}", areas(&s)); + // Crop: the bottom square inside the top one. + let mut s = Session::new(anicraft_doc::Document::default()); + squares(&mut s); + run(&mut s, "modify.crop", json!({})); + assert!(near(&areas(&s), &[2_500.0]), "{:?}", areas(&s)); + assert!(matches!(&top(&s)[0].kind, ElementKind::Shape(sh) if sh.fill == Some(anicraft_doc::Paint::Solid(anicraft_doc::Rgba::hex(0xff0000))))); + // Union of one colour: one drawing object. + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.union", json!({})); + assert!(matches!(&top(&s)[0].kind, ElementKind::Shape(sh) if !sh.merge), "one object"); + assert!(near(&areas(&s), &[17_500.0]), "{:?}", areas(&s)); + // A hole punched in the middle: a ring, 100² − 40². + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 30, "y": 30, "w": 40, "h": 40, "fill": "#0000ff", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.punch", json!({})); + assert!(near(&areas(&s), &[8_400.0]), "{:?}", areas(&s)); + // A circle cropped by a square through its centre: a quarter of π r² (cubic arcs: 0.03 %). + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.ellipse", json!({"x": -100, "y": -100, "w": 200, "h": 200, "fill": "#ff0000", "stroke": null})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 200, "fill": "#0000ff", "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.crop", json!({})); + let a = areas(&s); + let quarter = std::f64::consts::PI * 100.0 * 100.0 / 4.0; + assert!(a.len() == 1 && (a[0] - quarter).abs() < quarter * 0.001, "{a:?} vs {quarter}"); +} + +#[test] +fn combine_refuses_what_it_cannot_combine() { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000"})); + run(&mut s, "edit.select_all", json!({})); + assert!(s.execute("modify.union", &json!({})).is_err(), "one shape"); + run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 100, "h": 100, "fill": "#ff0000"})); + run(&mut s, "edit.select_all", json!({})); + assert!(s.execute("modify.intersect", &json!({})).is_err(), "apart: nothing in common"); + assert!(s.execute("modify.combine", &json!({"op": "xor"})).is_err()); + // The document is as it was after a refusal. + assert_eq!(top(&s).len(), 2); + // A line can't punch (it has no area). + run(&mut s, "draw.line", json!({"x0": 0, "y0": 50, "x1": 400, "y1": 50, "stroke": "#000000"})); + run(&mut s, "edit.select_all", json!({})); + assert!(s.execute("modify.punch", &json!({})).is_err()); +} + +#[test] +fn ctrl_drag_pulls_a_sharp_corner_out_of_a_line() { + // What the Selection tool's Ctrl-drag runs (issue #200): a point where the edge was grabbed, + // then that point moved, in one gesture. + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + s.begin_gesture("Pull Corner"); + let v = run(&mut s, "raw.add_point", json!({"x": 50, "y": 0.4, "slop": 3})); + let (x, y) = (v["x"].as_f64().unwrap_or(-1.0), v["y"].as_f64().unwrap_or(-1.0)); + assert!((x - 50.0).abs() < 0.5 && y.abs() < 1e-3, "{v}"); + run(&mut s, "raw.move_point", json!({"x": x, "y": y, "to_x": 50, "to_y": -40, "merge": false})); + let ids: Vec = top(&s).iter().map(|e| e.id.0).collect(); + run(&mut s, "raw.merge", json!({"ids": ids})); + s.end_gesture(); + // The fill gained a triangle 100 wide and 40 high: straight sides meeting at a sharp point. + let fill = top(&s).into_iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).unwrap_or_else(|| panic!("fill")); + let ElementKind::Shape(sh) = &fill.kind else { panic!("shape") }; + assert!((even_odd_area(&sh.path, &fill.transform) - 12_000.0).abs() < 0.5); + assert!(sh.path.cmds.iter().all(|c| !matches!(c, anicraft_geom::PathCmd::CubicTo(..) | anicraft_geom::PathCmd::QuadTo(..))), "straight lines, no curve: {:?}", sh.path.cmds); + assert!(s.history_len() >= 2); + run(&mut s, "edit.undo", json!({})); + let fill = top(&s).into_iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).unwrap_or_else(|| panic!("fill")); + let ElementKind::Shape(sh) = &fill.kind else { panic!("shape") }; + assert!((even_odd_area(&sh.path, &fill.transform) - 10_000.0).abs() < 0.5, "one undo step"); +} + +#[test] +fn alt_drag_copies_leave_the_original_whole() { + // What the Selection tool's Alt-drag runs: a copy in place, moved, dropped into the drawing. + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "element.pick", json!({"x": 50, "y": 50})); + s.begin_gesture("Copy"); + run(&mut s, "edit.duplicate", json!({"dx": 0, "dy": 0})); + run(&mut s, "element.translate", json!({"dx": 200, "dy": 0})); + run(&mut s, "draw.drop", json!({})); + s.end_gesture(); + let a: Vec = areas(&s); + assert!(a.len() == 2 && a.iter().all(|x| (x - 10_000.0).abs() < 0.5), "{a:?}"); +} + +#[test] +fn groups_draw_their_colour_effect_and_fade_as_one() { + let (mut s, ids) = three(); + run(&mut s, "element.select", json!({"ids": ids.map(|i| i.0)})); + run(&mut s, "modify.group", json!({})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + let dl = s.display_list(); + assert_eq!(dl.groups.len(), 1, "a translucent group composites as one"); + assert!(dl.items.iter().all(|i| i.group == Some(0))); + assert!((dl.effective_alpha(&dl.items[0]) - 0.5).abs() < 1e-6); + // Placement composes: a member's item is the group's transform times its own. + let g = top(&s)[0].clone(); + let m = g.kind.group_members()[0].clone(); + let want = Affine::IDENTITY.mul(&g.transform).mul(&m.transform); + assert_eq!(dl.items[0].transform.m, want.m); +} diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 25294358..e62ab2e1 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -28,11 +28,96 @@ pub struct Snapshot { pub doc: Document, pub state: StateId, pub scene: usize, + /// The symbols open for editing (ADR 0045). + pub editing: Vec, pub frame: u32, pub layer: LayerId, pub selection: crate::Selection, /// Estimated bytes this snapshot keeps alive that the neighbouring state does not share. pub bytes: usize, + /// The commands the step from this state ran, in order, as a saved command would run them + /// again (ADR 0097). `None`: they weren't kept (too many, or the step came from elsewhere). + pub commands: Option>, +} + +/// A command a history step ran: its id and params (ADR 0097). +#[derive(Clone, Debug, PartialEq)] +pub struct Recorded { + pub cmd: String, + pub params: serde_json::Value, + /// Roughly how much memory the params hold (their JSON's length). + pub bytes: usize, +} + +impl Recorded { + pub fn new(cmd: &str, params: &serde_json::Value) -> Recorded { + Recorded { cmd: cmd.to_string(), params: params.clone(), bytes: cmd.len() + params.to_string().len() } + } +} + +/// Most commands one step keeps: a longer step (a very long drag) can't be saved as a command. +pub const MAX_RECORDED: usize = 4096; +/// Most bytes of params one step keeps. +pub const MAX_RECORDED_BYTES: usize = 1 << 20; + +/// The commands run since the last step was recorded (ADR 0097). +#[derive(Clone, Debug, Default)] +pub(crate) struct Recording { + pub cmds: Vec, + pub bytes: usize, + /// More than [`MAX_RECORDED`] commands or [`MAX_RECORDED_BYTES`] bytes: none are kept. + pub overflow: bool, +} + +impl Recording { + /// Adds a command that changed the document. Moves in a row (a drag) add up into one. + pub fn push(&mut self, r: Recorded) { + if self.overflow { + return; + } + if let Some(last) = self.cmds.last_mut() + && let Some(sum) = merged_translate(last, &r) + { + *last = sum; + return; + } + self.bytes += r.bytes; + self.cmds.push(r); + if self.cmds.len() > MAX_RECORDED || self.bytes > MAX_RECORDED_BYTES { + self.overflow = true; + self.cmds = Vec::new(); + self.bytes = 0; + } + } + + pub fn truncate(&mut self, len: usize) { + if !self.overflow && len < self.cmds.len() { + self.cmds.truncate(len); + self.bytes = self.cmds.iter().map(|r| r.bytes).sum(); + } + } + + pub fn clear(&mut self) { + *self = Recording::default(); + } + + /// The commands for a step being recorded, leaving this empty. + pub fn take(&mut self) -> Option> { + let r = std::mem::take(self); + (!r.overflow).then(|| r.cmds.into()) + } +} + +/// Two `element.translate {dx, dy}` in a row as one, or `None`. +fn merged_translate(a: &Recorded, b: &Recorded) -> Option { + let plain = |r: &Recorded| { + let o = r.params.as_object()?; + (r.cmd == "element.translate" && o.len() == 2).then_some(())?; + Some((o.get("dx")?.as_f64()?, o.get("dy")?.as_f64()?)) + }; + let ((ax, ay), (bx, by)) = (plain(a)?, plain(b)?); + let (dx, dy) = (ax + bx, ay + by); + (dx.is_finite() && dy.is_finite()).then(|| Recorded::new("element.translate", &serde_json::json!({"dx": dx, "dy": dy}))) } /// Default memory budget for undo history. @@ -60,7 +145,7 @@ impl Default for History { impl History { /// Records `before` as an undo step leading to `current`, and clears redo. pub fn record(&mut self, mut before: Snapshot, current: &Document) { - before.bytes = unique_bytes(&before.doc, current); + before.bytes = unique_bytes(&before.doc, current) + before.commands.as_ref().map_or(0, |c| c.iter().map(|r| r.bytes).sum()); self.undo_bytes += before.bytes; self.undo.push_back(before); self.redo.clear(); @@ -83,6 +168,7 @@ impl History { self.undo_bytes = self.undo_bytes.saturating_sub(s.bytes); current.bytes = unique_bytes(¤t.doc, &s.doc); current.label = s.label.clone(); + current.commands = s.commands.clone(); self.redo_bytes += current.bytes; self.redo.push(current); Some(s) @@ -94,6 +180,7 @@ impl History { self.redo_bytes = self.redo_bytes.saturating_sub(s.bytes); current.bytes = unique_bytes(¤t.doc, &s.doc); current.label = s.label.clone(); + current.commands = s.commands.clone(); self.undo_bytes += current.bytes; self.undo.push_back(current); self.enforce_budget(); @@ -126,6 +213,12 @@ impl History { pub fn redo_labels(&self) -> impl Iterator { self.redo.iter().rev().map(|s| s.label.as_str()) } + /// Every step as the History panel lists it, oldest first: the steps that can be undone, + /// then the ones that can be redone (next to redo first), each with its label and the + /// commands it ran (ADR 0097). + pub fn steps(&self) -> impl Iterator)> { + self.undo.iter().chain(self.redo.iter().rev()).map(|s| (s.label.as_str(), s.commands.as_deref())) + } /// Estimated memory held by history. pub fn bytes(&self) -> usize { self.undo_bytes + self.redo_bytes @@ -142,7 +235,7 @@ fn path_bytes(e: &Element) -> usize { match &e.kind { ElementKind::Shape(s) => size_of::() + s.path.cmds.len() * size_of::(), ElementKind::Text(t) => size_of::() + t.outline.cmds.len() * size_of::(), - ElementKind::Symbol { .. } | ElementKind::Camera => 0, + ElementKind::Symbol { .. } | ElementKind::Camera | ElementKind::Group { .. } => 0, } } @@ -156,6 +249,10 @@ fn element_bytes(e: &Element, shared_paths: &HashSet) -> usize { b += stops.len() * size_of::(); } } + // A group's members, as if each stood alone (ADR 0073; nesting is bounded by MAX_GROUP_DEPTH). + if let ElementKind::Group { .. } = &e.kind { + b += size_of::() + e.kind.group_members().iter().map(|m| element_bytes(m, shared_paths)).sum::(); + } if let ElementKind::Text(t) = &e.kind { b += size_of::() + t.text.len() + t.font.len(); if !shared_paths.contains(&ptr(&t.outline)) { @@ -174,7 +271,7 @@ fn keyframe_bytes(k: &Keyframe, other: Option<&Keyframe>) -> usize { .filter_map(|e| match &e.kind { ElementKind::Shape(s) => Some(ptr(&s.path)), ElementKind::Text(t) => Some(ptr(&t.outline)), - ElementKind::Symbol { .. } | ElementKind::Camera => None, + ElementKind::Symbol { .. } | ElementKind::Camera | ElementKind::Group { .. } => None, }) .collect() }) @@ -243,6 +340,6 @@ pub fn unique_bytes(old: &Document, new: &Document) -> usize { /// Estimated total bytes of a document (as if nothing were shared). Used for reporting. pub fn document_bytes(doc: &Document) -> usize { - let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: doc.next_id }; + let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: doc.aids.clone(), swatches: doc.swatches.clone(), eases: doc.eases.clone(), next_id: doc.next_id }; unique_bytes(doc, &empty) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 31d651af..5c19493b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,21 +5,38 @@ //! JSON params, so headless and interactive behaviour cannot drift apart. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod anim; mod cmds_actions; mod cmds_bone; +mod cmds_warp; pub mod cmds_brush; mod cmds_camera; mod cmds_draw; +pub mod cmds_filter; +pub mod cmds_ease; +pub mod cmds_envelope; +pub mod cmds_drop; pub mod cmds_erase; mod cmds_file; mod cmds_frames; +mod cmds_group; mod cmds_modify; mod cmds_motion; +mod cmds_retime; mod cmds_hints; -mod cmds_paint; +mod cmds_layer; +pub mod cmds_library; +pub mod cmds_macro; +pub mod cmds_paint; mod cmds_path; pub mod cmds_raw; pub mod cmds_rawsub; +mod cmds_rawpoints; +pub mod brush_library; +pub mod filter_library; +pub mod cmds_recent; +pub mod cmds_desktop; +pub mod cmds_template; mod cmds_recovery; mod cmds_script; pub mod cmds_plugin; @@ -27,22 +44,31 @@ mod cmds_scene; pub mod cmds_sound; pub mod cmds_text; mod cmds_timeline; +mod cmds_view; mod cmds_width; mod cmds_stroke; +pub mod cmds_swatch; pub mod confirm; +pub mod editing; +pub mod explorer; +pub mod find; pub mod format; pub mod history; mod merge; +pub mod multi; pub mod onion; pub mod recovery; pub mod render_service; pub mod selection; +pub mod snap; pub mod params; +pub mod plugin_export; pub mod player; +pub mod publish; pub mod vfs; use anicraft_doc::{DisplayList, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, evaluate_layer_elements, evaluate_scene}; -use anicraft_geom::{Rect, Vec2}; +use anicraft_geom::{Affine, Rect, Vec2}; use serde_json::{Value, json}; use history::History; use std::cell::RefCell; @@ -54,6 +80,9 @@ pub use anicraft_plugins as plugins; pub use anicraft_text as text; pub use anicraft_geom as geom; pub use anicraft_render as render; +/// Whether a path is an Animate document (`.fla`, `.xfl`, or an XFL folder) that `file.open` +/// imports. +pub use cmds_file::is_animate; #[derive(Debug, thiserror::Error)] pub enum EngineError { @@ -71,6 +100,9 @@ pub enum EngineError { Render(#[from] anicraft_render::RenderError), #[error("{0}")] NeedsConfirmation(String), + /// A running publish was cancelled (ADR 0060). + #[error("cancelled")] + Cancelled, } pub type Result = std::result::Result; @@ -104,24 +136,44 @@ impl CommandSpec { pub fn commands() -> Vec { let mut v = Vec::new(); v.extend(cmds_file::specs()); + v.extend(plugin_export::specs()); + v.extend(cmds_envelope::specs()); + v.extend(publish::specs()); + v.extend(cmds_recent::specs()); + v.extend(cmds_desktop::specs()); + v.extend(cmds_drop::specs()); v.extend(cmds_recovery::specs()); v.extend(cmds_timeline::specs()); + v.extend(cmds_layer::specs()); v.extend(cmds_camera::specs()); v.extend(cmds_bone::specs()); + v.extend(cmds_warp::specs()); v.extend(cmds_motion::specs()); + v.extend(cmds_retime::specs()); + v.extend(cmds_ease::specs()); v.extend(cmds_hints::specs()); v.extend(cmds_scene::specs()); v.extend(cmds_frames::specs()); v.extend(onion::specs()); + v.extend(multi::specs()); v.extend(cmds_draw::specs()); + v.extend(cmds_view::specs()); + v.extend(cmds_group::specs()); + v.extend(cmds_library::specs()); v.extend(merge::specs()); v.extend(cmds_modify::specs()); v.extend(cmds_path::specs()); v.extend(cmds_raw::specs()); v.extend(cmds_rawsub::specs()); + v.extend(cmds_rawpoints::specs()); + v.extend(editing::specs()); + v.extend(find::specs()); + v.extend(explorer::specs()); v.extend(cmds_brush::specs()); + v.extend(cmds_filter::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); + v.extend(cmds_swatch::specs()); v.extend(cmds_text::specs()); v.extend(cmds_width::specs()); v.extend(cmds_stroke::specs()); @@ -129,6 +181,7 @@ pub fn commands() -> Vec { v.extend(cmds_sound::specs()); v.extend(cmds_actions::specs()); v.extend(cmds_script::specs()); + v.extend(cmds_macro::specs()); v } @@ -138,14 +191,37 @@ pub const SHORTCUT_ALIASES: &[(&str, &str)] = &[ ("Backspace", "edit.delete"), ("Shift+,", "timeline.first_frame"), ("Shift+.", "timeline.last_frame"), + // Snap to Objects is Animate's Ctrl+Shift+/ (ADR 0045). Where / and ? share a key (US, UK), + // the key arrives as ?, so that spelling is bound too. + ("Ctrl+Shift+?", "draw.snap_to_objects"), ]; pub fn find_command(id: &str) -> Option { - commands().into_iter().find(|c| c.id == id) + // Built once: every command run looks itself up, and a saved command checks each of its + // steps (ADR 0097), so this must not rebuild the registry per call. + static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEX + .get_or_init(|| { + let mut m = std::collections::HashMap::new(); + for c in commands() { + // The first of a repeated id wins, as a search in registry order finds it. + m.entry(c.id).or_insert(c); + } + m + }) + .get(id) + .copied() } -pub use history::{Snapshot, StateId}; +pub use history::{Recorded, Snapshot, StateId}; pub use selection::Selection; +pub use snap::{Accuracy, SnapTo, ViewAids}; +pub use cmds_layer::LAYER_COLORS; + +/// The command namespaces that change a timeline's layers and frames, refused while a group is +/// open for editing (ADR 0073): a group is one layer and one frame. A name ending in `.` is a +/// namespace, any other one command. +const GROUP_REFUSES: &[&str] = &["timeline.", "layer.", "camera.", "bone.", "motion.", "tween.", "frames.", "sound.place", "script.set", "script.clear"]; /// Last addressable frame (0-based); about 70 minutes at 24 fps. pub const MAX_FRAME: u32 = 100_000; @@ -175,9 +251,13 @@ pub(crate) fn pick_index(dl: &DisplayList, p: Vec2, slop: f32, ok: impl Fn(usize #[derive(Clone, Debug)] pub struct ToolStyle { pub fill: anicraft_doc::Rgba, - /// The fill swatch holds a gradient or a bitmap (picked with the Eyedropper, ADR 0034), in - /// stage space; `fill` is then its representative colour. `None`: the solid `fill`. + /// The fill swatch holds a gradient or a bitmap (set in the Colour panel or picked with the + /// Eyedropper, ADR 0034 and 0074), in stage space; `fill` is then its representative colour. + /// `None`: the solid `fill`. pub fill_paint: Option, + /// Lock Fill (ADR 0074): a gradient or bitmap from the swatch is poured where it lies on the + /// stage, so it runs on across shapes. Off, each shape gets it fitted to its own bounds. + pub lock_fill: bool, pub stroke: anicraft_doc::Rgba, pub stroke_width: f32, pub use_fill: bool, @@ -199,7 +279,7 @@ pub struct ToolStyle { impl Default for ToolStyle { fn default() -> Self { - ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, line: anicraft_doc::StrokeStyle::default(), object_drawing: true, snap_objects: true } + ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, lock_fill: false, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, line: anicraft_doc::StrokeStyle::default(), object_drawing: true, snap_objects: true } } } @@ -208,6 +288,13 @@ impl ToolStyle { pub fn fill_paint(&self) -> anicraft_doc::Paint { self.fill_paint.clone().unwrap_or(anicraft_doc::Paint::Solid(self.fill)) } + /// The fill swatch's paint for a shape whose space is `to_local` from the stage and whose + /// outline has the local `bounds`: with Lock Fill, the stage-space paint carried into the + /// shape; without, a gradient or bitmap fitted to the bounds (as Animate pours them). + pub fn fill_paint_for(&self, to_local: &anicraft_geom::Affine, bounds: &anicraft_geom::Rect) -> anicraft_doc::Paint { + let paint = self.fill_paint(); + if self.lock_fill || matches!(paint, anicraft_doc::Paint::Solid(_)) { paint.transformed(to_local) } else { paint.fitted(bounds) } + } /// Sets the fill swatch to a solid colour (dropping a picked gradient or bitmap). pub fn set_fill_color(&mut self, c: anicraft_doc::Rgba) { self.fill = c; @@ -221,10 +308,6 @@ impl ToolStyle { pub fn new_stroke(&self, color: anicraft_doc::Rgba, width: f32) -> anicraft_doc::Stroke { anicraft_doc::Stroke::new(color, width).with_profile(self.profile()).with_style(self.line.clone()) } - /// The snapping radius a command asked for (`snap`), or none when Snap to Objects is off. - pub fn snap_radius(&self, asked: f32) -> f32 { - if self.snap_objects { asked } else { 0.0 } - } /// Sets the profile to a preset (dropping a picked custom one). pub fn set_profile(&mut self, p: anicraft_doc::ProfilePreset) { self.stroke_profile = p; @@ -233,14 +316,17 @@ impl ToolStyle { } /// An open document plus everything the editor tracks about it. -/// A display list and the `(state, scene, frame)` it was evaluated for. -type CachedList = (StateId, usize, u32, Arc); +/// A display list and the `(state, scene, frame, open symbol)` it was evaluated for. +type CachedList = (StateId, usize, u32, Option<(editing::Opened, Option<(LayerId, ElementId)>, usize)>, Arc); pub struct Session { /// The document: a persistent tree, so cloning it (undo, render thread) is cheap. pub doc: Document, /// The scene being edited (index into `doc.scenes`). pub scene: usize, + /// Symbols open for editing, outermost first (ADR 0045). While one is open, commands work on + /// its timeline: `frame`, `layer` and `selection` are its. + pub editing: Vec, /// Playhead within the scene (0-based). pub frame: u32, /// Active layer. @@ -254,6 +340,9 @@ pub struct Session { saved_state: Option, pub path: Option, pub style: ToolStyle, + /// Whether the rulers, grid and guides show and snap (ADR 0076): the editor's, not the + /// document's. + pub aids: ViewAids, /// The style new text gets (the last one used). pub text_style: cmds_text::TextStyle, history: History, @@ -263,8 +352,10 @@ pub struct Session { dl_cache: RefCell>, /// Copied elements (and the symbols they use), outside the document so undo leaves it alone. pub clipboard: cmds_modify::Clipboard, - /// Copied frames (Copy Frames), separate from copied artwork as in Animate. + /// Copied frames (Copy Frames), separate from copied artwork. pub frame_clipboard: cmds_frames::FrameClipboard, + /// A copied ease (Copy Ease, ADR 0081), for Paste Ease. + pub ease_clipboard: Option, /// A command is editing a motion tween's target (auto-key, ADR 0016). motion_edit: Option, /// Installed WebAssembly plug-ins (ADR 0017). They belong to the session, not the @@ -280,6 +371,37 @@ pub struct Session { pub(crate) pending_cut: Option<(CutOrigin, Vec)>, /// The open gesture began on a provisional cut: the document with the cut. gesture_cut: Option, + /// How a button open for editing shows its hit area over its other states (ADR 0057): the + /// tint and opacity, or `None` for no overlay (the default; the app sets it from its theme). + /// View state, like the playhead: never in the document or its undo history. + pub hit_area: Option<(anicraft_doc::Rgba, f32)>, + /// The last picture of an open symbol in place, by its key (ADR 0045). + picture_cache: RefCell)>>, + /// A publish this session runs: its Cancel and frame count, which exports check (ADR 0060). + pub job: Option>, + /// Files this session's publishes wrote: publishing again replaces them without asking. + pub published: std::collections::BTreeSet, + /// The files opened and saved last, and pinned favourites (ADR 0059). They belong to the + /// session, not the document: they survive New and Open. The desktop app keeps them in its + /// preferences. + pub recent: cmds_recent::RecentFiles, + /// The user's own brush presets (ADR 0068). Like recent files they belong to the session + /// and survive New and Open; the desktop app keeps them in its preferences. + pub brushes: brush_library::BrushLibrary, + /// The user's filter presets (ADR 0091). Like brushes they belong to the session and + /// survive New and Open; the desktop app keeps them in its preferences. + pub filter_presets: filter_library::FilterLibrary, + /// Copied filters (Copy Filters, ADR 0091), for Paste Filters. + pub filter_clipboard: Option>, + /// The open envelope (ADR 0080): view state over the shapes it bends, like a gesture. + pub(crate) envelope: Option, + /// The commands run since the last undo step was recorded, which the next step keeps so it + /// can be saved as a command (ADR 0097). + rec: history::Recording, + /// How many commands were recorded when the open gesture began (a revert goes back there). + gesture_rec: usize, + /// What the running command records instead of itself (`macro.run` records its steps). + pub(crate) record_as: Option>, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -323,6 +445,7 @@ impl Session { Session { doc, scene: 0, + editing: Vec::new(), frame: 0, layer, selection: Selection::default(), @@ -331,18 +454,32 @@ impl Session { saved_state: Some(state), path: None, style: ToolStyle::default(), + aids: ViewAids::default(), text_style: cmds_text::TextStyle::default(), history: History::default(), gesture: None, dl_cache: RefCell::new(None), clipboard: cmds_modify::Clipboard::default(), frame_clipboard: cmds_frames::FrameClipboard::default(), + ease_clipboard: None, motion_edit: None, plugins: anicraft_plugins::Registry::default(), step_label: None, provisional: None, pending_cut: None, gesture_cut: None, + hit_area: None, + picture_cache: RefCell::new(None), + job: None, + published: std::collections::BTreeSet::new(), + recent: cmds_recent::RecentFiles::default(), + brushes: brush_library::BrushLibrary::default(), + filter_presets: filter_library::FilterLibrary::default(), + filter_clipboard: None, + envelope: None, + rec: history::Recording::default(), + gesture_rec: 0, + record_as: None, } } @@ -385,6 +522,7 @@ impl Session { } // On a marquee's cut, the step (if the gesture makes one) starts from before the cut. let cut = self.live_cut().map(|p| (history::Snapshot { label: label.to_string(), ..p.before.clone() }, p.cut.clone())); + self.gesture_rec = self.rec.cmds.len(); match cut { Some((before, doc)) => { self.gesture_cut = Some(doc); @@ -408,8 +546,17 @@ impl Session { } self.provisional = None; } + self.record(before); + } + + /// Records `before` as the undo step to the current document, with the commands run since + /// the last step; an unchanged document records nothing and forgets them. + fn record(&mut self, mut before: Snapshot) { if self.doc != before.doc { + before.commands = self.rec.take(); self.history.record(before, &self.doc); + } else { + self.rec.clear(); } } @@ -424,7 +571,16 @@ impl Session { let budget = self.history.budget_bytes; let clipboard = std::mem::take(&mut self.clipboard); let plugins = std::mem::take(&mut self.plugins); + let recent = std::mem::take(&mut self.recent); + let brushes = std::mem::take(&mut self.brushes); + let filter_presets = std::mem::take(&mut self.filter_presets); + let filter_clipboard = self.filter_clipboard.take(); *self = Session::new(doc); + self.recent = recent; + self.brushes = brushes; + self.filter_presets = filter_presets; + // Like copied artwork, copied filters carry across to the next document. + self.filter_clipboard = filter_clipboard; // The clipboard survives New/Open, so artwork can move between documents. self.clipboard = clipboard; self.plugins = plugins; @@ -444,10 +600,12 @@ impl Session { { return Err(EngineError::NeedsConfirmation(format!("{} {} (pass \"confirm\": true to proceed)", c.title, c.message))); } + self.group_allows(&spec)?; self.settle_cut(id, params); if !spec.mutates { let r = (spec.run)(self, params); self.settle_cut(id, params); + self.hold_group_frame(); return r; } // An edit on a marquee's cut records its step from before the cut (ADR 0041). @@ -462,7 +620,9 @@ impl Session { self.pending_cut = None; self.motion_edit = None; self.step_label = None; + self.record_as = None; let result = (spec.run)(self, params); + let record_as = self.record_as.take(); // Edits to a motion tween's target become property keys (auto-key). if let Some(edit) = self.motion_edit.take() && result.is_ok() @@ -484,6 +644,10 @@ impl Session { if changed { self.state = history::fresh_state(); self.revision += 1; + match record_as { + Some(steps) => steps.into_iter().for_each(|r| self.rec.push(r)), + None => self.rec.push(Recorded::new(id, params)), + } match pending.filter(|_| self.gesture.is_none()) { // A marquee's cut: provisional, no step (yet). Some((origin, inside)) => self.begin_cut(before, cut.is_some(), origin, inside), @@ -491,13 +655,14 @@ impl Session { if cut.is_some() { self.provisional = None; } - if self.gesture.is_none() && self.doc != before.doc { - self.history.record(before, &self.doc); + if self.gesture.is_none() { + self.record(before); } } } } self.fix_selection(); + self.hold_group_frame(); Ok(v) } Err(e) => { @@ -508,6 +673,24 @@ impl Session { } } + /// A group open for editing is one layer and one frame (ADR 0073): commands that change + /// the timeline are refused inside it. + fn group_allows(&self, spec: &CommandSpec) -> Result<()> { + let id = spec.id; + if spec.mutates && self.editing_group() && GROUP_REFUSES.iter().any(|ns| if ns.ends_with('.') { id.starts_with(ns) } else { id == *ns }) { + return Err(EngineError::State("a group has one layer and one frame: close it (Edit › Edit Document) to change the timeline, or convert it to a symbol (F8) to animate inside it".into())); + } + Ok(()) + } + + /// Inside a group (ADR 0073) the playhead stays on its only frame. + fn hold_group_frame(&mut self) { + if self.frame != 0 && self.editing_group() { + self.frame = 0; + self.fix_selection(); + } + } + /// The marquee's cut, while nothing has changed since it. fn live_cut(&self) -> Option<&Provisional> { self.provisional.as_ref().filter(|p| p.state == self.state && self.gesture.is_none()) @@ -564,6 +747,8 @@ impl Session { if self.saved_state == Some(p.state) { self.saved_state = Some(p.before.state); } + // The cut's commands went with it. + self.rec.clear(); self.doc = p.before.doc; self.state = p.before.state; self.selection = sel; @@ -585,9 +770,19 @@ impl Session { if !spec.mutates { return (spec.run)(self, params); } + self.group_allows(&spec)?; let before = self.snapshot(""); self.dl_cache.replace(None); + // Each command's edits to a motion tween's target become its keys, as when it runs on + // its own (the next one may work at another frame). + let outer = self.motion_edit.take(); let result = (spec.run)(self, params); + if let Some(edit) = self.motion_edit.take() + && result.is_ok() + { + cmds_motion::finish_edit(self, edit); + } + self.motion_edit = outer; self.dl_cache.replace(None); self.pending_cut = None; match result { @@ -617,20 +812,23 @@ impl Session { if g.doc == self.doc && g.selection == self.selection { return; } - let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 }; + let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0, commands: None }; + self.rec.truncate(self.gesture_rec); self.restore(back); self.revision += 1; self.fix_selection(); } fn snapshot(&self, label: &str) -> Snapshot { - Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } + Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0, commands: None } } fn restore(&mut self, s: Snapshot) { self.doc = s.doc; self.state = s.state; self.scene = s.scene; + // Where the change was made: an undo inside a symbol opens it again (ADR 0045). + self.editing = s.editing; self.frame = s.frame; self.layer = s.layer; self.selection = s.selection; @@ -653,6 +851,7 @@ impl Session { pub fn undo(&mut self) -> Result { self.end_gesture(); self.heal_cut(); + self.rec.clear(); let cur = self.snapshot(""); let s = self.history.undo(cur).ok_or_else(|| EngineError::State("nothing to undo".into()))?; let label = s.label.clone(); @@ -665,6 +864,7 @@ impl Session { pub fn redo(&mut self) -> Result { self.end_gesture(); self.heal_cut(); + self.rec.clear(); let cur = self.snapshot(""); let s = self.history.redo(cur).ok_or_else(|| EngineError::State("nothing to redo".into()))?; let label = s.label.clone(); @@ -691,28 +891,31 @@ impl Session { // ----- queries --------------------------------------------------------------------------- pub fn frame_count(&self) -> u32 { - self.doc.timeline(self.scene).frame_count() + self.timeline().frame_count() } pub fn active_layer(&self) -> Option<&Layer> { - self.doc.timeline(self.scene).layer(self.layer) + self.timeline().layer(self.layer) } pub fn active_layer_index(&self) -> Option { - self.doc.timeline(self.scene).layers.iter().position(|l| l.id == self.layer) + self.timeline().layers.iter().position(|l| l.id == self.layer) } /// The current scene evaluated at the playhead, cached per `(state, scene, frame)`. pub fn display_list(&self) -> Arc { - if let Some((s, sc, f, dl)) = &*self.dl_cache.borrow() + let open = self.editing.last().map(|l| (l.open, l.instance, self.editing.len())); + if let Some((s, sc, f, o, dl)) = &*self.dl_cache.borrow() && *s == self.state && *sc == self.scene && *f == self.frame + && *o == open { return dl.clone(); } - let dl = Arc::new(evaluate_scene(&self.doc, self.scene, self.frame)); - self.dl_cache.replace(Some((self.state, self.scene, self.frame, dl.clone()))); + // An open symbol (ADR 0045) or group (ADR 0073) is edited in its own space. + let dl = Arc::new(if open.is_some() { anicraft_doc::evaluate_timeline(&self.doc, self.timeline(), self.frame) } else { evaluate_scene(&self.doc, self.scene, self.frame) }); + self.dl_cache.replace(Some((self.state, self.scene, self.frame, open, dl.clone()))); dl } @@ -725,12 +928,39 @@ impl Session { /// Topmost element under `p` (stage space) on a visible, unlocked layer. A bounding-box /// test rejects almost every item before any curve is flattened. pub fn hit_test(&self, p: Vec2, slop: f32) -> Option<(LayerId, ElementId)> { - let tl = self.doc.timeline(self.scene); + // The timeline being edited: a symbol open in place picks in its own layers (ADR 0045). + let tl = self.timeline(); let dl = self.display_list(); let i = pick_index(&dl, p, slop, |_, it| tl.layer(it.layer).is_some_and(|layer| !layer.locked && !tl.locked_by_folder(layer.id)))?; dl.items.get(i).map(|it| (it.layer, it.element)) } + /// Stage → output for layer `id` at the playhead as the camera shows it (ADR 0082): the + /// camera and the layer's depth then, the identity for an attached layer. `None` without a + /// camera that does something, while a symbol is open, or when the camera has passed the + /// layer. What editing through the camera maps the pointer back with. + pub fn camera_view(&self, id: LayerId) -> Option { + if !self.editing.is_empty() { + return None; + } + let tl = self.doc.timeline(self.scene); + let cam = tl.camera_at(self.frame, &self.doc.stage)?; + cam.layer_view(&self.doc.stage, tl.layer(id)?, self.frame) + } + + /// [`Session::hit_test`] through the scene's camera: the topmost element under output + /// point `p` (the movie's pixels) on a visible, unlocked layer, `slop` in output pixels. + /// Without a camera that does something this is the stage's hit test. + pub fn hit_test_camera(&self, p: Vec2, slop: f32) -> Option<(LayerId, ElementId)> { + if !self.editing.is_empty() || self.doc.timeline(self.scene).camera_at(self.frame, &self.doc.stage).is_none() { + return self.hit_test(p, slop); + } + let tl = self.timeline(); + let dl = anicraft_doc::evaluate_scene_camera(&self.doc, self.scene, self.frame); + let i = pick_index(&dl, p, slop, |_, it| tl.layer(it.layer).is_some_and(|layer| !layer.locked && !tl.locked_by_folder(layer.id)))?; + dl.items.get(i).map(|it| (it.layer, it.element)) + } + /// Stage-space bounds of a top-level element at the playhead. pub fn element_bounds(&self, id: ElementId) -> Rect { let mut r = Rect::EMPTY; @@ -750,7 +980,7 @@ impl Session { pub(crate) fn layer_mut(&mut self, id: Option) -> Result<&mut Layer> { let id = id.unwrap_or(self.layer); - self.doc.timeline_mut(self.scene).layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) + crate::editing::edited_mut(&mut self.doc, self.scene, &self.editing)?.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) } /// The keyframe on the active layer that edits at the playhead should change. Creates a @@ -764,7 +994,7 @@ impl Session { /// refused there. pub(crate) fn editable_keyframe_in(&mut self, what: KeyEdit) -> Result<&mut Keyframe> { let frame = self.frame; - let tl = self.doc.timeline(self.scene); + let tl = self.timeline(); if let Some(l) = tl.layer(self.layer) { if l.kind == LayerKind::Folder { return Err(EngineError::State(format!("'{}' is a folder; pick a layer inside it to draw on", l.name))); @@ -781,7 +1011,7 @@ impl Session { } // Through the fields, not `layer_mut`, so `motion_edit` can be set below. let (scene, active) = (self.scene, self.layer); - let layer = self.doc.timeline_mut(scene).layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?; + let layer = crate::editing::edited_mut(&mut self.doc, scene, &self.editing)?.layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?; if layer.locked { return Err(EngineError::State(format!("layer '{}' is locked", layer.name))); } @@ -818,17 +1048,39 @@ impl Session { Ok(kf.elements_mut_where(|id| sel.contains(&id))) } + /// [`Session::selected_elements_mut`] for the properties an instance keeps however it is + /// placed (colour effect, blending, filters). On an armature layer (ADR 0084) the selected + /// members are edited in place on every pose of the armature, so the property holds as the + /// armature moves and the bones and poses are untouched; elsewhere, as any edit. + pub(crate) fn selected_props_mut(&mut self) -> Result> { + let on_armature = self.timeline().layer(self.layer).is_some_and(|l| l.kind == LayerKind::Armature); + if !on_armature { + return self.selected_elements_mut(); + } + let sel: std::collections::HashSet = self.selection.on(self.layer).into_iter().collect(); + if sel.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + if self.timeline().locked_by_folder(self.layer) { + return Err(EngineError::State("the armature layer is in a locked folder".into())); + } + let layer = self.layer_mut(None)?; + if layer.locked { + return Err(EngineError::State(format!("layer '{}' is locked", layer.name))); + } + Ok(layer.keyframes.iter_mut().flat_map(|k| Arc::make_mut(k).elements_mut_where(|id| sel.contains(&id))).collect()) + } + /// JSON summary used by `doc.info` and the CLI. pub fn info(&self) -> Value { let layers: Vec = self - .doc - .timeline(self.scene) + .timeline() .layers .iter() .map(|l| { json!({ "id": l.id.0, "name": l.name, "visible": l.visible, "locked": l.locked, "volume": l.volume, "muted": l.muted, - "keyframes": l.keyframes.iter().map(|k| json!({"start": k.start, "duration": k.duration, "elements": k.elements.len(), "tween": k.tween.map(|t| t.easing.label()), "motion": k.motion.as_ref().map(|m| m.tracks.iter().map(|t| t.property.key()).collect::>()), "sound": k.sound.as_ref().map(|f| json!({"sound": f.sound.0, "sync": f.sync.key(), "repeat": f.repeat, "loop": f.looping, "effect": f.effect.key()})), "script": k.script.as_ref().map(anicraft_doc::FrameScript::describe)})).collect::>() + "keyframes": l.keyframes.iter().map(|k| json!({"start": k.start, "duration": k.duration, "elements": k.elements.len(), "tween": k.tween.as_ref().map(|t| t.easing.label()), "motion": k.motion.as_ref().map(|m| m.tracks.iter().map(|t| t.property.key()).collect::>()), "sound": k.sound.as_ref().map(|f| json!({"sound": f.sound.0, "sync": f.sync.key(), "repeat": f.repeat, "loop": f.looping, "effect": f.effect.key()})), "script": k.script.as_ref().map(anicraft_doc::FrameScript::describe)})).collect::>() }) }) .collect(); @@ -844,6 +1096,8 @@ impl Session { "layer": self.layer.0, "selection": self.selection.id_list(), "selection_layers": self.selected_layers().iter().map(|l| l.0).collect::>(), + // The symbols open for editing, outermost first (ADR 0045); `layers` are the open one's. + "editing": editing::editing_json(self)["editing"], "layers": layers, "library": symbols, "sounds": sounds, @@ -866,6 +1120,30 @@ pub(crate) enum KeyEdit { Pose, } +/// A colour effect as commands report it (ADR 0056): its style and that style's values, in the +/// units `element.set_color_effect` takes (percent; Advanced offsets −255..255). +pub fn color_effect_json(fx: &anicraft_doc::ColorEffect) -> serde_json::Value { + use anicraft_doc::ColorEffect; + let r = |v: f32, k: f32| f64::from((v * k * 100.0).round() / 100.0); + let mut v = serde_json::json!({"style": fx.style().key()}); + match *fx { + ColorEffect::None => {} + ColorEffect::Alpha(a) => v["alpha"] = r(a, 100.0).into(), + ColorEffect::Brightness(b) => v["brightness"] = r(b, 100.0).into(), + ColorEffect::Tint { color, amount } => { + v["tint"] = color.to_hex().into(); + v["tint_amount"] = r(amount, 100.0).into(); + } + ColorEffect::Advanced(t) => { + for (i, ch) in ["red", "green", "blue", "alpha"].iter().enumerate() { + v[format!("{ch}_multiplier")] = r(t.mul.get(i).copied().unwrap_or(1.0), 100.0).into(); + v[format!("{ch}_offset")] = r(t.add.get(i).copied().unwrap_or(0.0), 255.0).into(); + } + } + } + v +} + /// Short human label for an element (properties panel, library, CLI). pub fn element_label(doc: &Document, e: &Element) -> String { let kind = match &e.kind { @@ -879,6 +1157,14 @@ pub fn element_label(doc: &Document, e: &Element) -> String { None => "Graphic: missing".to_string(), }, ElementKind::Camera => "Camera".to_string(), + ElementKind::Group { .. } => "Group".to_string(), + // An empty field (an input field waiting for the viewer) is named by its type. + ElementKind::Text(t) if t.text.trim().is_empty() => match t.kind() { + anicraft_doc::TextKind::Static => "Static text", + anicraft_doc::TextKind::Dynamic => "Dynamic text", + anicraft_doc::TextKind::Input => "Input text", + } + .to_string(), ElementKind::Text(t) => { let first: String = t.text.lines().next().unwrap_or("").chars().take(24).collect(); format!("Text: {first}{}", if t.text.chars().count() > first.chars().count() { "…" } else { "" }) @@ -893,10 +1179,22 @@ mod tests; #[cfg(test)] mod motion_tests; #[cfg(test)] +mod retime_tests; +#[cfg(test)] +mod ease_tests; +#[cfg(test)] +mod color_tests; +#[cfg(test)] mod motion_path_tests; #[cfg(test)] +mod motion_pin_tests; +#[cfg(test)] mod plugin_tests; #[cfg(test)] +mod macro_tests; +#[cfg(test)] +mod plugin_kinds_tests; +#[cfg(test)] mod tests_sound; #[cfg(test)] mod hint_tests; @@ -909,18 +1207,62 @@ mod tests_camera; #[cfg(test)] mod tests_bone; #[cfg(test)] +mod tests_bone_spring; +#[cfg(test)] +mod tests_shape_bone; +#[cfg(test)] +mod tests_shape_weights; +#[cfg(test)] +mod tests_warp; +#[cfg(test)] +mod tests_filter; +#[cfg(test)] +mod tests_filter_tracks; +#[cfg(test)] +mod desktop_tests; +#[cfg(test)] mod merge_tests; #[cfg(test)] mod raw_tests; #[cfg(test)] mod rawsub_tests; #[cfg(test)] +mod rawpoints_tests; +#[cfg(test)] +mod editing_tests; +#[cfg(test)] mod brush_tests; #[cfg(test)] +mod brush_library_tests; +#[cfg(test)] mod web_tests; #[cfg(test)] mod erase_tests; #[cfg(test)] mod eyedropper_tests; #[cfg(test)] +mod gradient_tests; +#[cfg(test)] mod selection_tests; +#[cfg(test)] +mod scale_grid_tests; +#[cfg(test)] +mod drop_tests; +#[cfg(test)] +mod template_tests; +#[cfg(test)] +mod timeline_drop_tests; +#[cfg(test)] +mod timeline_key_tests; +#[cfg(test)] +mod tests_bone_chain; +#[cfg(test)] +mod view_tests; +#[cfg(test)] +mod path_text_tests; +#[cfg(test)] +mod group_tests; +#[cfg(test)] +mod swatch_tests; +#[cfg(test)] +mod parity_tests; diff --git a/crates/engine/src/library_tests.rs b/crates/engine/src/library_tests.rs new file mode 100644 index 00000000..318b460d --- /dev/null +++ b/crates/engine/src/library_tests.rs @@ -0,0 +1,319 @@ +//! Library management end to end (ADR 0050): folders, names, moves, duplicates, Swap Symbol, +//! deletion with its confirmations, unused items, smoothing, the file format and undo. + +use crate::Session; +use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryItem, SymbolId, sample}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +fn sym(s: &Session, name: &str) -> u64 { + s.doc.library.iter().find(|x| x.name == name).map(|x| x.id.0).unwrap_or_else(|| panic!("no symbol {name}")) +} + +fn folder(v: &Value) -> u64 { + v["folder"].as_u64().unwrap() +} + +fn path(s: &Session, symbol: u64) -> String { + s.doc.entry_path(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(symbol)))) +} + +/// Instances of `symbol` on every timeline. +fn instances(s: &Session, symbol: u64) -> usize { + s.doc.timelines().flat_map(|t| &t.layers).flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).filter(|e| matches!(e.kind, ElementKind::Symbol { symbol: x, .. } if x.0 == symbol)).count() +} + +#[test] +fn folders_are_made_named_and_nested() { + let mut s = Session::new(sample::demo()); + let a = run(&mut s, "library.new_folder", json!({})); + assert_eq!(a["name"], "Folder 1"); + let b = run(&mut s, "library.new_folder", json!({})); + assert_eq!(b["name"], "Folder 2"); + let inner = run(&mut s, "library.new_folder", json!({"name": "Hero", "parent": folder(&a)})); + assert_eq!(s.doc.entry_path(LibraryEntry::Folder(FolderId(folder(&inner)))), "Folder 1/Hero"); + // Names: unique per folder without case, no slashes, not empty. + assert!(err(&mut s, "library.new_folder", json!({"name": "folder 1"})).contains("already has")); + assert!(err(&mut s, "library.new_folder", json!({"name": "a/b"})).contains("/")); + assert!(err(&mut s, "library.new_folder", json!({"name": " "})).contains("empty")); + assert!(err(&mut s, "library.new_folder", json!({"parent": 999_999})).contains("no folder")); + run(&mut s, "library.new_folder", json!({"name": "Hero"})); + // Renaming. + run(&mut s, "library.rename", json!({"folder": folder(&a), "name": "Characters"})); + assert_eq!(s.doc.folder(FolderId(folder(&a))).unwrap().name, "Characters"); + let ball = sym(&s, "Ball"); + assert!(err(&mut s, "library.rename", json!({"symbol": ball, "name": "star"})).contains("already has")); + run(&mut s, "library.rename", json!({"symbol": ball, "name": "BALL"})); + run(&mut s, "library.rename", json!({"symbol": ball, "name": "Ball"})); + assert!(err(&mut s, "library.rename", json!({"symbol": ball, "folder": 1, "name": "x"})).contains("one Library entry")); + // One undo step each. + s.undo().unwrap(); + assert_eq!(s.doc.symbol(SymbolId(ball)).unwrap().name, "BALL"); +} + +#[test] +fn items_move_in_and_out_of_folders() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let chars = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + let hero = folder(&run(&mut s, "library.new_folder", json!({"name": "Hero", "parent": chars}))); + let v = run(&mut s, "library.move", json!({"items": [{"symbol": ball}, {"symbol": star}], "to": hero})); + assert_eq!(v["moved"], 2); + assert_eq!(path(&s, ball), "Characters/Hero/Ball"); + // Out again, one step for the whole move. + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": null})); + assert_eq!(path(&s, ball), "Ball"); + s.undo().unwrap(); + assert_eq!(path(&s, ball), "Characters/Hero/Ball"); + // A folder moves with what it holds, but never into itself. + let props = folder(&run(&mut s, "library.new_folder", json!({"name": "Props"}))); + run(&mut s, "library.move", json!({"items": [{"folder": hero}], "to": props})); + assert_eq!(path(&s, star), "Props/Hero/Star"); + assert!(err(&mut s, "library.move", json!({"items": [{"folder": props}], "to": hero})).contains("inside itself")); + assert!(err(&mut s, "library.move", json!({"items": [{"folder": props}], "to": props})).contains("inside itself")); + // A name clash stops the move and leaves everything where it was. + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": null})); + let star2 = run(&mut s, "library.duplicate", json!({"symbol": star, "name": "Ball"})); + let before = s.doc.library_tree.clone(); + let e = err(&mut s, "library.move", json!({"items": [{"symbol": star}, {"symbol": star2["symbol"]}], "to": null})); + assert!(e.contains("already has an item named “Ball”"), "{e}"); + assert_eq!(s.doc.library_tree, before); + assert!(err(&mut s, "library.move", json!({"items": [{"symbol": ball}]})).contains("'to'")); + assert!(err(&mut s, "library.move", json!({"items": [{"symbol": 424_242}], "to": null})).contains("no symbol")); +} + +#[test] +fn folders_survive_save_and_open() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = Session::new(crate::format::from_json(&text).unwrap()); + assert_eq!(path(&back, ball), "Characters/Ball"); + assert_eq!(back.doc.library_tree, s.doc.library_tree); + assert!(back.doc.next_id > f); +} + +#[test] +fn duplicates_are_named_after_their_original() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Props"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let a = run(&mut s, "library.duplicate", json!({"symbol": ball})); + assert_eq!(a["name"], "Ball copy"); + let b = run(&mut s, "library.duplicate", json!({"symbol": ball})); + assert_eq!(b["name"], "Ball copy 2"); + assert_eq!(path(&s, a["symbol"].as_u64().unwrap()), "Props/Ball copy"); + assert!(err(&mut s, "library.duplicate", json!({"symbol": ball, "name": "ball COPY"})).contains("already has")); + assert!(err(&mut s, "library.duplicate", json!({"symbol": 424_242})).contains("no symbol")); + assert_eq!(instances(&s, a["symbol"].as_u64().unwrap()), 0, "a copy isn't placed"); + s.undo().unwrap(); + assert!(s.doc.symbol(SymbolId(b["symbol"].as_u64().unwrap())).is_none()); +} + +#[test] +fn swap_symbol_keeps_everything_but_the_symbol() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let el = run(&mut s, "library.place", json!({"symbol": ball, "x": 100, "y": 50}))["element"].as_u64().unwrap(); + run(&mut s, "symbol.set_kind", json!({"symbol": ball, "kind": "movie_clip"})); + run(&mut s, "element.set_transform", json!({"sx": 2, "rotation": 30})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]})); + run(&mut s, "element.rename", json!({"name": "hero"})); + let find = |s: &Session| s.elements_on(s.layer).iter().find(|e| e.id.0 == el).map(|e| (**e).clone()).unwrap(); + let before = find(&s); + let v = run(&mut s, "element.swap_symbol", json!({"symbol": star})); + assert_eq!(v["swapped"], 1); + let after = find(&s); + assert_eq!((after.transform, after.color, &after.name), (before.transform, before.color, &before.name)); + match (&before.kind, &after.kind) { + (ElementKind::Symbol { symbol: a, loop_mode: la, filters: fa, blend: ba, .. }, ElementKind::Symbol { symbol: b, loop_mode: lb, filters: fb, blend: bb, .. }) => { + assert_eq!((a.0, b.0), (ball, star)); + assert_eq!((la, fa, ba), (lb, fb, bb)); + } + _ => panic!("still an instance"), + } + assert_eq!(s.selection.on(s.layer).first().map(|e| e.0), Some(el), "it stays selected"); + assert!(err(&mut s, "element.swap_symbol", json!({"symbol": 424_242})).contains("no symbol")); + assert!(err(&mut s, "element.swap_symbol", json!({})).contains("'symbol'")); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("element.swap_symbol", &json!({"symbol": ball})).is_err(), "nothing selected"); + s.undo().unwrap(); + assert!(matches!(find(&s).kind, ElementKind::Symbol { symbol, .. } if symbol.0 == ball)); +} + +#[test] +fn deleting_asks_when_it_takes_uses_or_folder_contents() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + assert!(instances(&s, star) > 0, "the sample places Star (inside Ball too)"); + // An unused item goes without asking. + let copy = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + let p = json!({"items": [{"symbol": copy}]}); + assert!(s.confirmation("library.delete", &p).is_none()); + run(&mut s, "library.delete", p); + assert!(s.doc.symbol(SymbolId(copy)).is_none()); + // A used one asks (undoable tier), and its instances go everywhere, inside symbols too. + let p = json!({"items": [{"symbol": star}]}); + let c = s.confirmation("library.delete", &p).expect("asks"); + assert!(!c.irreversible && c.message.contains("used") && c.message.contains("undo"), "{c:?}"); + run(&mut s, "library.delete", p); + assert_eq!(instances(&s, star), 0); + assert!(s.doc.symbol(SymbolId(ball)).is_some()); + s.undo().unwrap(); + assert!(instances(&s, star) > 0); + // A folder that holds items asks, and takes them with it. + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Old"}))); + let inner = folder(&run(&mut s, "library.new_folder", json!({"name": "Older", "parent": f}))); + let spare = run(&mut s, "library.duplicate", json!({"symbol": ball}))["symbol"].as_u64().unwrap(); + run(&mut s, "library.move", json!({"items": [{"symbol": spare}], "to": inner})); + let p = json!({"items": [{"folder": f}]}); + let c = s.confirmation("library.delete", &p).expect("asks"); + assert!(c.title.contains("folder") && c.message.contains("holds 2 items"), "{c:?}"); + let v = run(&mut s, "library.delete", p); + assert_eq!((v["deleted"].as_u64(), v["folders"].as_u64()), (Some(1), Some(2))); + assert!(s.doc.library_tree.is_empty() && s.doc.symbol(SymbolId(spare)).is_none()); + // An empty folder goes without asking. + let empty = folder(&run(&mut s, "library.new_folder", json!({}))); + assert!(s.confirmation("library.delete", &json!({"items": [{"folder": empty}]})).is_none()); + assert!(err(&mut s, "library.delete", json!({"items": []})).contains("nothing")); + assert!(err(&mut s, "library.delete", json!({"items": [{"folder": 1}]})).contains("no folder")); +} + +#[test] +fn deleting_a_bitmap_or_a_sound_takes_its_uses() { + let mut s = Session::new(sample::demo()); + let id = BitmapId(s.doc.alloc_id()); + let mut px = Vec::new(); + for _ in 0..4 { + px.extend_from_slice(&[255, 0, 0, 255]); + } + let bytes = anicraft_render::encode_png(2, 2, &px).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(id, "red.png", bytes).unwrap())); + let el = run(&mut s, "library.place", json!({"bitmap": id.0}))["element"].as_u64().unwrap(); + let item = LibraryItem::Bitmap(id); + assert_eq!(s.doc.library_uses().get(&item), Some(&1)); + // Smoothing toggles, is one undo step, and is kept by the file. + assert_eq!(run(&mut s, "library.set_smoothing", json!({"bitmap": id.0}))["smoothing"], false); + let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap(); + assert!(!back.bitmap(id).unwrap().smoothing); + s.undo().unwrap(); + assert!(s.doc.bitmap(id).unwrap().smoothing); + assert!(!crate::format::to_json(&s.doc).unwrap().contains("smoothing"), "the default is written as nothing"); + run(&mut s, "library.delete", json!({"items": [{"bitmap": id.0}]})); + assert!(s.doc.bitmap(id).is_none()); + assert!(s.elements_on(s.layer).iter().all(|e| e.id.0 != el), "the placed bitmap goes with it"); + assert!(err(&mut s, "library.set_smoothing", json!({"bitmap": id.0})).contains("no bitmap")); +} + +#[test] +fn unused_items_are_listed_and_deleted_after_asking() { + let mut s = Session::new(sample::demo()); + let star = sym(&s, "Star"); + assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([])); + assert!(s.confirmation("library.delete_unused", &json!({})).is_none()); + let a = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + let b = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + // In Library order: each copy sits right after its original, so the later one comes first. + assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([{"symbol": b}, {"symbol": a}])); + let c = s.confirmation("library.delete_unused", &json!({})).expect("asks"); + assert!(c.message.contains("these 2 items") && c.message.contains("Star copy"), "{c:?}"); + let v = run(&mut s, "library.delete_unused", json!({})); + assert_eq!(v["deleted"], 2); + assert!(s.doc.symbol(SymbolId(a)).is_none() && s.doc.symbol(SymbolId(star)).is_some()); + s.undo().unwrap(); + assert!(s.doc.symbol(SymbolId(a)).is_some()); +} + +#[test] +fn the_listing_has_paths_kinds_and_uses() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let v = run(&mut s, "library.items", json!({})); + assert_eq!(v["folders"], json!([{"folder": f, "name": "Characters", "parent": null, "path": "Characters"}])); + let b = v["items"].as_array().unwrap().iter().find(|i| i["symbol"] == ball).unwrap(); + assert_eq!((b["path"].as_str(), b["folder"].as_u64(), b["kind"].as_str(), b["unused"].as_bool()), (Some("Characters/Ball"), Some(f), Some("graphic"), Some(false))); + assert!(b["uses"].as_u64().unwrap() > 0); + assert_eq!(v["unused"], 0); +} + +#[test] +fn convert_to_symbol_picks_a_free_name() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let first = run(&mut s, "modify.convert_to_symbol", json!({})); + assert_eq!(first["name"], "Symbol 1"); + run(&mut s, "library.rename", json!({"symbol": first["symbol"], "name": "Symbol 2"})); + run(&mut s, "draw.rect", json!({"x": 20, "y": 0, "w": 10, "h": 10})); + let second = run(&mut s, "modify.convert_to_symbol", json!({})); + assert_eq!(second["name"], "Symbol 3", "“Symbol 2” is taken"); +} + +#[test] +fn inside_an_open_symbol_swap_never_nests_and_deleting_it_closes_it() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let outer = run(&mut s, "modify.convert_to_symbol", json!({"name": "Outer"}))["symbol"].as_u64().unwrap(); + run(&mut s, "draw.rect", json!({"x": 40, "y": 0, "w": 10, "h": 10})); + let other = run(&mut s, "modify.convert_to_symbol", json!({"name": "Other"}))["symbol"].as_u64().unwrap(); + run(&mut s, "symbol.edit", json!({"symbol": outer})); + assert_eq!(s.editing.len(), 1); + run(&mut s, "library.place", json!({"symbol": other})); + assert!(err(&mut s, "element.swap_symbol", json!({"symbol": outer})).contains("inside itself")); + // Deleting the open symbol takes the editor back to the scene. + run(&mut s, "library.delete", json!({"items": [{"symbol": outer}], "confirm": true})); + assert!(s.editing.is_empty() && s.doc.symbol(SymbolId(outer)).is_none()); +} + +#[test] +fn library_counts_stay_quick_on_a_large_document() { + // 100 layers × 100 shapes keyed every 12 frames over 240 frames (200,000 element keys), + // plus 1,000 symbols in 50 folders, each placed once. Measured, loosely bounded (CI varies); + // the shell works these out once per document change, not per frame. + let mut s = Session::new(anicraft_doc::sample::stress(100, 100, 240)); + // A new layer, so the symbol holds only the new rectangle (drawing selects it). + run(&mut s, "layer.new", json!({})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + let sym = run(&mut s, "modify.convert_to_symbol", json!({}))["symbol"].as_u64().unwrap(); + for i in 0..50 { + run(&mut s, "library.new_folder", json!({"name": format!("F{i}")})); + } + let folders: Vec = s.doc.library_tree.folders.iter().map(|f| f.id.0).collect(); + for i in 0..999 { + let c = run(&mut s, "library.duplicate", json!({"symbol": sym, "name": format!("S{i}")}))["symbol"].as_u64().unwrap(); + run(&mut s, "library.move", json!({"items": [{"symbol": c}], "to": folders[i % folders.len()]})); + } + let t = std::time::Instant::now(); + let uses = s.doc.library_uses(); + let counted = t.elapsed(); + let t = std::time::Instant::now(); + let unused = s.doc.unused_items(); + let reach = t.elapsed(); + let t = std::time::Instant::now(); + let listed = run(&mut s, "library.items", json!({})); + let listing = t.elapsed(); + println!("library of {} items, {} folders: use counts {counted:?}, unused {reach:?} ({} unused), library.items {listing:?}", s.doc.library.len(), folders.len(), unused.len()); + assert_eq!(listed["items"].as_array().map(Vec::len), Some(1000)); + assert_eq!(unused.len(), 999); + assert!(uses.values().sum::() >= 1); + assert!(counted.as_millis() < 500 && reach.as_millis() < 500, "counted {counted:?}, unused {reach:?}"); +} diff --git a/crates/engine/src/macro_tests.rs b/crates/engine/src/macro_tests.rs new file mode 100644 index 00000000..e41ca157 --- /dev/null +++ b/crates/engine/src/macro_tests.rs @@ -0,0 +1,353 @@ +//! Saved commands (ADR 0097): what history records, Save As Command from history steps, a run +//! as one transactional undo step, the folder's order, the policy, and hostile files. + +use super::*; +use crate::cmds_macro::{self, Macro, macro_may_call}; +use serde_json::json; +use std::path::PathBuf; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-macros-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The elements on the active layer at the playhead, without their ids (which differ between +/// documents), as JSON. +fn looks(s: &Session) -> Vec { + s.visible_elements() + .iter() + .map(|e| { + let mut v = serde_json::to_value(&**e).unwrap(); + v.as_object_mut().unwrap().remove("id"); + v + }) + .collect() +} + +/// A rectangle, selected. +fn with_rect(x: f64) -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": x, "y": 20, "w": 80, "h": 40})); + run(&mut s, "edit.select_all", json!({})); + s +} + +/// Three edits on the selection: a drag (many moves in one step), a quarter turn and a fade. +fn edit(s: &mut Session) { + s.begin_gesture("Move"); + for _ in 0..30 { + run(s, "element.translate", json!({"dx": 2, "dy": -1})); + } + s.end_gesture(); + run(s, "modify.rotate_cw", json!({})); + run(s, "element.set_color_effect", json!({"style": "alpha", "alpha": 40})); +} + +#[test] +fn history_keeps_each_steps_commands_and_a_drag_as_one_move() { + let mut s = with_rect(10.0); + edit(&mut s); + let steps: Vec<(String, Option>)> = s.history().steps().map(|(l, c)| (l.to_string(), c.map(<[Recorded]>::to_vec))).collect(); + assert_eq!(steps.len(), 4, "{:?}", steps.iter().map(|s| &s.0).collect::>()); + let cmds = |i: usize| steps[i].1.clone().unwrap(); + assert_eq!(cmds(0)[0].cmd, "draw.rect"); + // Thirty moves in a drag add up to one. + assert_eq!(cmds(1).len(), 1); + assert_eq!(cmds(1)[0].params, json!({"dx": 60.0, "dy": -30.0})); + assert_eq!(cmds(2)[0].cmd, "modify.rotate_cw"); + assert_eq!(cmds(3)[0].params, json!({"style": "alpha", "alpha": 40})); + // Undo and redo carry them along. + s.undo().unwrap(); + s.redo().unwrap(); + assert_eq!(s.history().steps().nth(3).and_then(|(_, c)| c).map(<[Recorded]>::len), Some(1)); +} + +#[test] +fn a_live_preview_records_only_what_it_ended_on() { + let mut s = with_rect(10.0); + s.begin_gesture("Nudge"); + run(&mut s, "modify.rotate_cw", json!({})); + s.revert_gesture(); + run(&mut s, "element.translate", json!({"dx": 5, "dy": 0})); + s.end_gesture(); + let last = s.history().steps().last().and_then(|(_, c)| c.map(<[Recorded]>::to_vec)).unwrap(); + assert_eq!(last.iter().map(|r| r.cmd.as_str()).collect::>(), ["element.translate"]); +} + +#[test] +fn record_and_replay_equals_the_original_edits_on_a_fresh_selection() { + let dir = temp_dir("replay"); + let folder = dir.display().to_string(); + let mut original = with_rect(10.0); + edit(&mut original); + let listed = run(&mut original, "macro.history", json!({})); + let keep: Vec = listed["steps"].as_array().unwrap().iter().map(|v| v["keep"].as_bool().unwrap()).collect(); + assert_eq!(keep, [true, true, true, true], "{listed}"); + let saved = run(&mut original, "macro.save", json!({"folder": folder, "name": "Turn and Fade", "history": [1, 2, 3]})); + assert_eq!(saved["steps"], 3); + assert!(dir.join("Turn and Fade.json").is_file()); + + // Elsewhere: another document, another rectangle drawn the same way but with other ids. + let mut other = Session::default(); + run(&mut other, "draw.ellipse", json!({"x": 300, "y": 300, "w": 10, "h": 10})); + run(&mut other, "edit.deselect", json!({})); + run(&mut other, "draw.rect", json!({"x": 10, "y": 20, "w": 80, "h": 40})); + let rect = other.visible_elements().last().unwrap().id; + run(&mut other, "element.select", json!({"ids": [rect.0]})); + let steps = other.history_len(); + let before_run = looks(&other); + let oval = before_run.first().cloned(); + let v = run(&mut other, "macro.run", json!({"folder": folder, "name": "Turn and Fade"})); + assert_eq!(v["steps"], 3); + assert_eq!(other.history_len(), steps + 1, "one undo step"); + assert_eq!(other.undo_label(), Some("Turn and Fade")); + let mine = looks(&other); + assert_eq!(mine.last(), looks(&original).last(), "the rectangle ends up as in the original"); + // The oval, not selected, is untouched. + assert_eq!(mine.first().cloned(), oval); + // One undo takes the whole run back. + other.undo().unwrap(); + assert_eq!(looks(&other), before_run); + // And the run's step can itself be saved again: history keeps its steps, not macro.run. + other.redo().unwrap(); + let again = run(&mut other, "macro.history", json!({})); + let last = again["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!((last["keep"].as_bool(), last["commands"].as_u64()), (Some(true), Some(3)), "{last}"); +} + +#[test] +fn a_failing_step_changes_nothing_and_is_named() { + let mut s = with_rect(10.0); + let (doc, state, steps) = (s.doc.clone(), s.state, s.history_len()); + let steps_json = json!([ + {"cmd": "element.translate", "params": {"dx": 10, "dy": 0}}, + {"cmd": "modify.rotate_cw"}, + {"cmd": "layer.set_height", "params": {"height": 7}, "label": "Taller row"}, + ]); + let e = s.execute("macro.run", &json!({"name": "Broken", "steps": steps_json})).unwrap_err().to_string(); + assert!(e.contains("“Broken” stopped at step 3 of 3 (Taller row)") && e.contains("Nothing was changed"), "{e}"); + assert!(s.doc == doc, "the document is as it was"); + assert_eq!((s.state, s.history_len()), (state, steps)); + assert_eq!(s.selection.len(), 1, "the selection too"); +} + +#[test] +fn steps_tied_to_this_document_act_on_the_selection_or_say_why_they_cant_be_kept() { + let mut s = with_rect(10.0); + let layer = s.layer.0; + let id = s.selection.id_list()[0]; + // A layer named by id: the step acts on the active layer instead. + run(&mut s, "layer.set_color", json!({"color": "#ff0000", "layer": layer})); + // An element named by id where the command can take the selection instead. + run(&mut s, "stroke.set_profile", json!({"profile": "taper_both", "id": id})); + // An element named by id where the command can't do without it. + run(&mut s, "path.move_points", json!({"id": id, "points": [[0, 0]], "dx": 3, "dy": 0})); + let v = run(&mut s, "macro.history", json!({})); + let steps = v["steps"].as_array().unwrap(); + assert_eq!(steps[1]["rewritten"], "acts on the active layer", "{v}"); + assert_eq!(steps[2]["rewritten"], "acts on the selection", "{v}"); + assert_eq!(steps[3]["keep"], false); + assert!(steps[3]["why"].as_str().unwrap().contains("particular objects"), "{v}"); + let dir = temp_dir("rewrite"); + let folder = dir.display().to_string(); + let e = s.execute("macro.save", &json!({"folder": folder, "name": "Mixed", "history": [1, 2, 3]})).unwrap_err().to_string(); + assert!(e.starts_with("step 4 “") && e.contains("can't be kept"), "{e}"); + assert!(!dir.join("Mixed.json").exists(), "nothing saved"); + let saved = run(&mut s, "macro.save", json!({"folder": folder, "name": "Mixed", "history": [2, 1]})); + assert_eq!(saved["rewritten"].as_array().map(Vec::len), Some(2)); + let m = cmds_macro::load(&dir.join("Mixed.json")).unwrap(); + assert_eq!(m.steps[0].params, json!({"color": "#ff0000"}), "in history order, the layer's id gone"); + assert_eq!(m.steps[1].params, json!({"profile": "taper_both"})); +} + +#[test] +fn saved_commands_call_only_what_a_plug_in_may() { + assert!(macro_may_call("element.translate").is_ok()); + for id in ["file.save", "edit.paste", "edit.undo", "plugin.run", "macro.run", "macro.delete", "prefs.set", "view.rulers"] { + assert!(macro_may_call(id).is_err(), "{id}"); + } + // Plug-ins can't reach saved commands either, so the two never call each other. + for c in commands().iter().filter(|c| c.id.starts_with("macro.")) { + assert!(crate::cmds_plugin::plugin_may_call(c.id).is_err(), "{}", c.id); + } + for (step, why) in [(json!({"cmd": "file.save", "params": {"path": "x.anicraft"}}), "files"), (json!({"cmd": "macro.run", "params": {"path": "x.json"}}), "saved commands"), (json!({"cmd": "no.such"}), "unknown command")] { + let e = Macro::from_json(&json!([step]), "x").unwrap_err().to_string(); + assert!(e.contains("step 1") && e.contains(why), "{e}"); + } + // A history step that used the clipboard can't be kept. + let mut s = with_rect(10.0); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "edit.paste", json!({})); + let v = run(&mut s, "macro.history", json!({})); + let last = v["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last["keep"], false); + assert!(last["why"].as_str().unwrap().contains("clipboard"), "{last}"); +} + +#[test] +fn the_folder_keeps_order_renames_and_deletes_only_when_confirmed() { + let dir = temp_dir("manage"); + let folder = dir.display().to_string(); + let mut s = with_rect(10.0); + run(&mut s, "modify.rotate_cw", json!({})); + for name in ["Alpha", "Bravo", "Charlie"] { + run(&mut s, "macro.save", json!({"folder": folder, "name": name, "history": [1]})); + } + let names = |s: &mut Session| -> Vec { run(s, "macro.list", json!({"folder": folder}))["commands"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap().to_string()).collect() }; + assert_eq!(names(&mut s), ["Alpha", "Bravo", "Charlie"], "in the order saved"); + run(&mut s, "macro.move", json!({"folder": folder, "name": "Charlie", "index": 0})); + assert_eq!(names(&mut s), ["Charlie", "Alpha", "Bravo"]); + run(&mut s, "macro.rename", json!({"folder": folder, "name": "Alpha", "to": "Delta"})); + assert_eq!(names(&mut s), ["Charlie", "Delta", "Bravo"], "a rename keeps its place"); + assert!(s.execute("macro.rename", &json!({"folder": folder, "name": "Delta", "to": "Bravo"})).unwrap_err().to_string().contains("already")); + assert!(s.execute("macro.rename", &json!({"folder": folder, "name": "Delta", "to": "a/b"})).is_err()); + // Saving over one asks first; deleting always does (a file: undo can't bring it back). + assert!(matches!(s.execute("macro.save", &json!({"folder": folder, "name": "Bravo", "history": [1]})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "macro.save", json!({"folder": folder, "name": "Bravo", "history": [0, 1], "confirm": true})); + assert_eq!(names(&mut s), ["Charlie", "Delta", "Bravo"], "a replaced command keeps its place"); + assert!(matches!(s.execute("macro.delete", &json!({"folder": folder, "name": "Charlie"})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "macro.delete", json!({"folder": folder, "name": "Charlie", "confirm": true})); + assert_eq!(names(&mut s), ["Delta", "Bravo"]); + // A shared file comes in under its own name, checked. + let shared = dir.join("shared"); + std::fs::create_dir_all(&shared).unwrap(); + std::fs::write(shared.join("Spin.json"), r#"[{"cmd": "modify.rotate_cw"}, {"command": "modify.rotate_cw"}]"#).unwrap(); + let v = run(&mut s, "macro.import", json!({"folder": folder, "path": shared.join("Spin.json").display().to_string()})); + assert_eq!(v["steps"], 2); + assert_eq!(names(&mut s), ["Delta", "Bravo", "Spin"]); + // ...and runs straight from where it is (Run Command…). + let before = s.visible_elements()[0].transform; + run(&mut s, "macro.run", json!({"path": shared.join("Spin.json").display().to_string()})); + assert_eq!(s.undo_label(), Some("Spin")); + assert_ne!(s.visible_elements()[0].transform, before); + // Files that aren't saved commands are listed as problems, never as commands. + std::fs::write(dir.join("junk.json"), "{nope").unwrap(); + let v = run(&mut s, "macro.list", json!({"folder": folder})); + assert_eq!(v["problems"][0]["file"], "junk.json"); + assert_eq!(names(&mut s).len(), 3); +} + +#[test] +fn hostile_saved_command_files_never_panic() { + let dir = temp_dir("hostile"); + let deep = format!("{}{}", "[".repeat(5000), "]".repeat(5000)); + let many = serde_json::to_string(&vec![json!({"cmd": "modify.rotate_cw"}); cmds_macro::MAX_STEPS + 1]).unwrap(); + let mut bodies: Vec> = vec![ + Vec::new(), + b"\xef\xbb\xbf".to_vec(), + b"\xff\xfe\x00\x01garbage".to_vec(), + deep.into_bytes(), + many.into_bytes(), + "x".repeat((cmds_macro::MAX_FILE_BYTES + 10) as usize).into_bytes(), + ]; + for text in [ + "null", + "7", + "\"steps\"", + "{}", + r#"{"format": "something-else", "steps": []}"#, + r#"{"format": "anicraft-command", "version": 99, "steps": []}"#, + r#"{"format": "anicraft-command", "version": -1, "steps": []}"#, + r#"{"steps": "no"}"#, + r#"{"steps": [7, null, "x"]}"#, + r#"{"steps": [{"cmd": 7}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": [1, 2]}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": {"dx": 1e308, "dy": -1e308}}]}"#, + r#"{"steps": [{"cmd": "element.translate", "params": {"dx": "a"}}]}"#, + r#"{"steps": [{"cmd": "draw.rect", "params": {"x": 0, "y": 0, "w": 1e30, "h": -1}, "label": 5}]}"#, + r#"{"steps": [{"cmd": "layer.delete"}, {"cmd": "layer.delete"}, {"cmd": "layer.delete"}]}"#, + r#"{"steps": [{"cmd": "edit.undo"}]}"#, + r#"{"steps": [{"cmd": "file.export_png", "params": {"path": "/tmp/x.png"}}]}"#, + r#"{"steps": [{"cmd": "macro.run", "params": {"path": "self.json"}}]}"#, + r#"{"steps": [{"cmd": "plugin.run", "params": {"id": "x"}}]}"#, + ] { + bodies.push(text.as_bytes().to_vec()); + } + bodies.push(json!({"steps": [{"cmd": "modify.rotate_cw", "label": "\u{0}\u{202e} evil"}]}).to_string().into_bytes()); + // Truncations of a good file at every byte, and a few flipped bytes. + let good = serde_json::to_vec(&Macro { name: String::new(), steps: vec![cmds_macro::Step { cmd: "element.translate".into(), params: json!({"dx": 3, "dy": 4}), label: "Move".into() }] }.to_json()).unwrap(); + for i in 0..good.len() { + bodies.push(good[..i].to_vec()); + let mut flipped = good.clone(); + flipped[i] ^= 0x5a; + bodies.push(flipped); + } + let mut s = with_rect(10.0); + for (i, body) in bodies.iter().enumerate() { + let path = dir.join(format!("h{i}.json")); + std::fs::write(&path, body).unwrap(); + let (doc, steps) = (s.doc.clone(), s.history_len()); + match s.execute("macro.run", &json!({"path": path.display().to_string()})) { + Ok(_) => assert!(s.history_len() <= steps + 1), + Err(_) => assert!(s.doc == doc && s.history_len() == steps, "a refused file changed the document"), + } + let _ = s.execute("macro.import", &json!({"folder": dir.join("in").display().to_string(), "path": path.display().to_string(), "confirm": true})); + } + // Listing a folder full of them never panics either. + let v = run(&mut s, "macro.list", json!({"folder": dir.display().to_string()})); + assert!(!v["problems"].as_array().unwrap().is_empty()); + // Hostile params, with every folder inside the temporary one. + let folder = dir.display().to_string(); + for p in [ + Value::Null, + json!({"folder": folder}), + json!({"folder": folder, "name": "", "history": [u64::MAX]}), + json!({"folder": folder, "name": "x", "history": "all"}), + json!({"folder": folder, "name": "x", "history": []}), + json!({"folder": folder, "name": "..", "history": [0]}), + json!({"folder": folder, "name": "CON", "history": [0]}), + json!({"folder": folder, "name": "a", "to": "", "index": u64::MAX}), + json!({"folder": "", "name": "a"}), + json!({"steps": {"steps": []}, "name": "\u{0}".repeat(500)}), + json!({"steps": []}), + json!({"path": folder}), + ] { + for c in commands().iter().filter(|c| c.id.starts_with("macro.")) { + let _ = s.execute(c.id, &p); + } + } +} + +#[test] +fn a_step_too_long_to_keep_says_so() { + let mut s = with_rect(10.0); + s.begin_gesture("Scribble"); + for i in 0..(history::MAX_RECORDED + 2) { + // Alternating commands, so they don't add up into one. + let id = if i % 2 == 0 { "element.translate" } else { "modify.rotate_cw" }; + run(&mut s, id, json!({"dx": 1, "dy": 0, "snap": 0})); + } + s.end_gesture(); + let v = run(&mut s, "macro.history", json!({})); + let last = v["steps"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last["keep"], false); + assert!(last["why"].as_str().unwrap().contains("too many"), "{last}"); +} + +#[test] +fn steps_run_inside_a_motion_tween_key_it_as_on_their_own() { + // Each step's edit becomes the tween's keys at the frame it ran at. + let tweened = || { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s + }; + let (mut a, mut b) = (tweened(), tweened()); + a.set_frame(5); + run(&mut a, "edit.select_all", json!({})); + run(&mut a, "element.translate", json!({"dx": 40, "dy": 0})); + b.set_frame(5); + run(&mut b, "edit.select_all", json!({})); + run(&mut b, "macro.run", json!({"steps": [{"cmd": "element.translate", "params": {"dx": 40, "dy": 0}}]})); + assert!(a.doc == b.doc, "a step in a saved command keys the tween as the command does alone"); +} diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 3e41aca4..f55b2ad8 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -19,22 +19,16 @@ pub fn specs() -> Vec { } /// A raw shape the merge can take: any fill (solid, gradient or bitmap: the paint is carried -/// into each piece, ADR 0042) or none, and a stroke of one width or none. A width profile runs -/// along the whole stroke, so cutting it would need its length carried through the merge; those -/// strokes stay whole, as objects, for now. +/// into each piece, ADR 0042) or none, and any stroke or none. A stroke's width profile is +/// carried into each piece of it (ADR 0093): the merge says which stretch of the stroke each +/// piece runs along, and the piece keeps the widths it had there. pub(crate) fn mergeable(e: &Element) -> Option<&Shape> { match &e.kind { - ElementKind::Shape(s) if s.merge && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s), + ElementKind::Shape(s) if s.merge => Some(s), _ => None, } } -/// Whether a new shape with this style can join the drawing (strokes with a width profile are -/// drawn as objects for now). -pub(crate) fn can_merge(stroke: Option<&Stroke>) -> bool { - stroke.is_none_or(|st| st.profile.is_none()) -} - pub(crate) fn reach(s: &Shape, m: &Affine) -> Rect { let pad = s.stroke.as_ref().map_or(0.0, Stroke::reach) * m.mean_scale(); s.path.bounds().transformed(m).inflate(pad + 2.0 * SNAP) @@ -140,6 +134,9 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt // Style tables: equal entries are one style to the merge. let mut fills: Vec<(Paint, ColorEffect)> = Vec::new(); let mut strokes: Vec<(Stroke, ColorEffect)> = Vec::new(); + // A stroke with a width profile is a style of its own (its pieces never chain into another + // stroke's), with the path its profile runs along (an index into `paths`). + let mut profiled: Vec<(u32, usize)> = Vec::new(); let mut paths: Vec = Vec::with_capacity(parts.len()); let mut styles: Vec<(Option, Option, anicraft_geom::FillRule)> = Vec::with_capacity(parts.len()); let mut marked: Vec = Vec::with_capacity(parts.len()); @@ -151,7 +148,17 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt // Gradients and bitmaps are placed in keyframe space, so every piece shows its // part of the paint where it was. let fill = sh.fill.as_ref().map(|f| fill_index(&mut fills, (f.transformed(&e.transform), e.color))); - let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (st.scaled(e.transform.mean_scale()), e.color))); + let stroke = sh.stroke.clone().map(|st| { + let st = (st.scaled(e.transform.mean_scale()), e.color); + if st.0.profile.is_some() { + strokes.push(st); + let i = (strokes.len() - 1) as u32; + profiled.push((i, paths.len() - 1)); + i + } else { + index_of(&mut strokes, st) + } + }); styles.push((fill, stroke, sh.fill_rule)); marked.push(*mark); } @@ -178,7 +185,12 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt (Some(f.clone()), None, *c) } else { let Some((st, c)) = strokes.get(piece.style as usize) else { continue }; - (None, Some(st.clone()), *c) + let mut st = st.clone(); + // Each piece of a variable-width stroke keeps the widths it had (ADR 0093). + if let (Some(profile), Some(path)) = (&st.profile, profiled.iter().find(|(i, _)| *i == piece.style).and_then(|(_, p)| paths.get(*p))) { + st.profile = profile.along(path, &piece.spans); + } + (None, Some(st), *c) }; // Local origin at the centre of the piece, as the drawing tools place shapes. let c = piece.path.bounds().center(); @@ -197,7 +209,7 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt name: String::new(), transform: Affine::translate(c.x, c.y), color, - kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill: fill.map(|f| f.transformed(&Affine::translate(-c.x, -c.y))), stroke, fill_rule: Default::default(), merge: true }), + kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill: fill.map(|f| f.transformed(&Affine::translate(-c.x, -c.y))), stroke, fill_rule: Default::default(), merge: true, warp: None }), })); } Some(Remerged { out, picked, inside, from }) @@ -245,13 +257,20 @@ fn fill_index(table: &mut Vec<(Paint, ColorEffect)>, v: (Paint, ColorEffect)) -> } /// Whether two paints look the same (positions within a thousandth of a unit). -pub(crate) fn same_paint(a: &Paint, b: &Paint) -> bool { +pub(crate) fn same_paint(x: &Paint, y: &Paint) -> bool { const EPS: f32 = 1e-3; let near = |p: Vec2, q: Vec2| p.distance(q) <= EPS; - match (a, b) { + match (x, y) { (Paint::Solid(x), Paint::Solid(y)) => x == y, - (Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => near(*s0, *s1) && near(*e0, *e1) && a == b, - (Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => near(*c0, *c1) && (r0 - r1).abs() <= EPS && a == b, + (Paint::Linear { start: s0, end: e0, stops: a, spread: p0, linear_rgb: l0 }, Paint::Linear { start: s1, end: e1, stops: b, spread: p1, linear_rgb: l1 }) => near(*s0, *s1) && near(*e0, *e1) && a == b && p0 == p1 && l0 == l1, + (Paint::Radial { stops: a, spread: p0, linear_rgb: l0, focal: f0, .. }, Paint::Radial { stops: b, spread: p1, linear_rgb: l1, focal: f1, .. }) => { + // The same ring: the frames agree (centre, axes and size). + let same_frame = match (x.frame(None), y.frame(None)) { + (Some(m0), Some(m1)) => m0.m.iter().zip(m1.m).all(|(u, v)| (u - v).abs() <= EPS * u.abs().max(v.abs()).max(1.0)), + _ => false, + }; + same_frame && a == b && p0 == p1 && l0 == l1 && (f0 - f1).abs() <= EPS + } (Paint::Bitmap { bitmap: b0, repeat: r0, matrix: m0 }, Paint::Bitmap { bitmap: b1, repeat: r1, matrix: m1 }) => { b0 == b1 && r0 == r1 && m0.m.iter().zip(m1.m).all(|(x, y)| (x - y).abs() <= EPS * x.abs().max(y.abs()).max(1.0)) } @@ -272,6 +291,11 @@ fn index_of(table: &mut Vec, v: T) -> u32 { /// `draw.drop`: the selected raw shapes go back into the drawing, on top (Animate merges a moved /// shape when it is let go). fn drop(s: &mut Session, _: &Value) -> Result { + drop_selected(s) +} + +/// [`drop`] on the active layer (also when an envelope closes, ADR 0080). +pub(crate) fn drop_selected(s: &mut Session) -> Result { let sel = s.selection.on(s.layer); let kf = s.editable_keyframe()?; let mut moving = Vec::new(); @@ -380,8 +404,28 @@ pub(crate) fn merge_document(doc: &mut Document) -> usize { } fn merge_timeline(doc: &mut Document, tl: &mut Timeline) -> usize { + merge_timeline_at(doc, tl, 0) +} + +/// [`merge_timeline`], inside groups too (ADR 0073): a group's raw shapes merge with each other. +fn merge_timeline_at(doc: &mut Document, tl: &mut Timeline, depth: usize) -> usize { let mut n = 0; + let is_group = |e: &Element| matches!(e.kind, ElementKind::Group { .. }); for layer in tl.layers.iter_mut() { + if depth < anicraft_doc::MAX_GROUP_DEPTH && layer.keyframes.iter().any(|k| k.elements.iter().any(|e| is_group(e))) { + let layer = Arc::make_mut(layer); + for kf in layer.keyframes.iter_mut().filter(|k| k.elements.iter().any(|e| is_group(e))) { + for e in Arc::make_mut(kf).elements.iter_mut().filter(|e| is_group(e)) { + let ElementKind::Group { members } = &e.kind else { continue }; + let mut members = members.clone(); + let k = merge_timeline_at(doc, &mut members, depth + 1); + if k > 0 { + Arc::make_mut(e).kind = ElementKind::Group { members }; + n += k; + } + } + } + } if !layer.keyframes.iter().any(|k| k.elements.iter().any(|e| mergeable(e).is_some())) { continue; } diff --git a/crates/engine/src/motion_path_tests.rs b/crates/engine/src/motion_path_tests.rs index f01e57b2..b5cd82e2 100644 --- a/crates/engine/src/motion_path_tests.rs +++ b/crates/engine/src/motion_path_tests.rs @@ -154,13 +154,14 @@ fn moving_the_object_on_a_path_reshapes_the_path() { s.set_frame(23); run(&mut s, "element.translate", json!({"dx": 10, "dy": 0})); assert!(pos(&mut s, 23).distance(Vec2::new(115.0, 5.0)) < 1e-3); - // In between: the path bends through where the object was put; no key is added. - let before = keys(&s); + // In between: an anchor where the object was put, pinned to that frame (ADR 0049; ADR 0030 + // bent the path instead and added no key). let want = pos(&mut s, 9) + Vec2::new(0.0, 40.0); s.set_frame(9); run(&mut s, "element.translate", json!({"dx": 0, "dy": 40})); - assert!(pos(&mut s, 9).distance(want) < 0.01, "{:?} vs {want:?}", pos(&mut s, 9)); - assert_eq!(keys(&s), before, "the timing keeps its keys"); + assert!(pos(&mut s, 9).distance(want) < 1e-3, "{:?} vs {want:?}", pos(&mut s, 9)); + assert_eq!(keys(&s), Some(vec![0, 9, 23]), "a position key on the pinned frame"); + assert_eq!(motion(&s).pins, vec![anicraft_doc::Pin { frame: 9, anchor: 1 }]); assert!(pos(&mut s, 0).distance(Vec2::new(0.0, 25.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(115.0, 5.0)) < 1e-3, "the ends stay"); // A drag on the stage is a gesture: one undo step however many moves. let steps = s.history_len(); diff --git a/crates/engine/src/motion_pin_tests.rs b/crates/engine/src/motion_pin_tests.rs new file mode 100644 index 00000000..447f9e5c --- /dev/null +++ b/crates/engine/src/motion_pin_tests.rs @@ -0,0 +1,229 @@ +//! Motion path anchors pinned to frames (ADR 0049) through the command registry: auto-key +//! pinning where the object is put, `motion.pin_point` / `motion.unpin_point`, the X/Y keys of a +//! pinned frame as its anchor's place, point edits keeping pins on their anchors, F6, undo and +//! the file round trip. + +use super::*; +use anicraft_doc::{Pin, Property}; +use anicraft_geom::Vec2; +use anicraft_geom::edit::ANCHOR; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn fails(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +/// A 10 × 10 square centred on (5, 5) with a motion tween over frames 0..24 travelling the hump +/// from (5, 5) up and over to (105, 5), reached on frame 23. +fn on_hump() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s.set_frame(23); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 0})); + s.set_frame(0); + run(&mut s, "motion.set_path", json!({"d": "M5 5 C38 -60 72 -60 105 5"})); + s +} + +fn pos(s: &mut Session, frame: u32) -> Vec2 { + s.set_frame(frame); + s.visible_elements().first().map(|e| e.transform.translation()).unwrap_or_default() +} + +fn motion(s: &Session) -> &anicraft_doc::MotionTween { + s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.as_ref()).expect("motion tween") +} + +fn anchor(s: &Session, i: usize) -> Vec2 { + motion(s).path.as_ref().and_then(|p| p.point(i, ANCHOR)).expect("anchor") +} + +fn key_frames(s: &Session, p: Property) -> Vec { + motion(s).track(p).map(|t| t.keys.iter().map(|k| k.frame).collect()).unwrap_or_default() +} + +#[test] +fn moving_the_object_at_a_middle_frame_pins_an_anchor_there() { + let mut s = on_hump(); + let was = pos(&mut s, 9); + // A drag on the stage: one undo step however many moves, one pin. + let steps = s.history_len(); + s.set_frame(9); + s.begin_gesture("Move"); + for _ in 0..4 { + run(&mut s, "element.translate", json!({"dx": 5, "dy": 10})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + let want = was + Vec2::new(20.0, 40.0); + assert!(pos(&mut s, 9).distance(want) < 1e-3, "{:?} vs {want:?}", pos(&mut s, 9)); + assert!(anchor(&s, 1).distance(want) < 1e-3, "the new anchor is where the object was put"); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }]); + assert!(pos(&mut s, 0).distance(Vec2::new(5.0, 5.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 5.0)) < 1e-3, "the ends stay"); + // motion.info reports every anchor tied to a frame, ends included. + let info = run(&mut s, "motion.info", json!({})); + let pins: Vec<(u64, u64, bool)> = info["pins"].as_array().unwrap().iter().map(|p| (p["anchor"].as_u64().unwrap(), p["frame"].as_u64().unwrap(), p["end"].as_bool().unwrap())).collect(); + assert_eq!(pins, vec![(0, 0, true), (1, 9, false), (2, 23, true)]); + // A later frame pins a later anchor; the first pin holds. + s.set_frame(16); + run(&mut s, "element.translate", json!({"dx": 0, "dy": -30})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }, Pin { frame: 16, anchor: 2 }]); + assert!(pos(&mut s, 9).distance(want) < 1e-3); + assert!(pos(&mut s, 16).distance(anchor(&s, 2)) < 1e-3); + // Undo takes the pin back with its anchor and keys. + s.undo().expect("undo"); + assert_eq!(motion(&s).pins, vec![Pin { frame: 9, anchor: 1 }]); + assert_eq!(key_frames(&s, Property::X), vec![0, 9, 23]); +} + +#[test] +fn moving_after_the_last_position_key_carries_the_path_on() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s.set_frame(12); + run(&mut s, "element.translate", json!({"dx": 60, "dy": 0})); + run(&mut s, "motion.set_path", json!({"d": "M5 5 C25 -30 45 -30 65 5"})); + let before: Vec = (0..=12).map(|f| pos(&mut s, f)).collect(); + s.set_frame(20); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 40})); + assert!(pos(&mut s, 20).distance(Vec2::new(105.0, 45.0)) < 1e-3); + assert_eq!(motion(&s).position_range(), Some((0, 20))); + assert_eq!(motion(&s).pins, vec![Pin { frame: 12, anchor: 1 }], "the old end stays pinned to its frame"); + for (f, b) in before.iter().enumerate() { + assert!(pos(&mut s, f as u32).distance(*b) < 1e-2, "frame {f} as it was"); + } +} + +#[test] +fn pin_and_unpin_an_anchor_by_command() { + let mut s = on_hump(); + let v = run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.5})); + assert_eq!(v["anchor"], 1); + let unpinned = motion(&s).clone(); + let off = pos(&mut s, 6); + assert!(off.distance(anchor(&s, 1)) > 5.0, "an anchor alone is reached when the timing says"); + let steps = s.history_len(); + let v = run(&mut s, "motion.pin_point", json!({"anchor": 1, "frame": 6})); + assert_eq!(s.history_len(), steps + 1); + assert_eq!((v["anchor"].as_u64(), v["frame"].as_u64()), (Some(1), Some(6))); + assert_eq!(v["pins"].as_array().map(Vec::len), Some(3)); + assert!(pos(&mut s, 6).distance(anchor(&s, 1)) < 1e-3, "passed exactly on its frame"); + assert_eq!(key_frames(&s, Property::Y), vec![0, 6, 23]); + // What can't be pinned is refused with the reason. + assert!(fails(&mut s, "motion.pin_point", json!({"anchor": 0, "frame": 6})).contains("always pinned")); + assert!(fails(&mut s, "motion.pin_point", json!({"anchor": 7, "frame": 6})).contains("no such anchor")); + assert!(fails(&mut s, "motion.unpin_point", json!({"anchor": 2})).contains("always pinned")); + assert!(fails(&mut s, "motion.unpin_point", json!({"frame": 3})).contains("no anchor is pinned to frame 4")); + // Unpinning (by anchor or by frame) gives the tween back as it was. + run(&mut s, "motion.unpin_point", json!({"anchor": 1})); + assert_eq!(*motion(&s), unpinned); + assert!(pos(&mut s, 6).distance(off) < 1e-3, "ADR 0038's timing again"); + run(&mut s, "motion.pin_point", json!({"anchor": 1, "frame": 6})); + run(&mut s, "motion.unpin_point", json!({"frame": 6})); + assert_eq!(*motion(&s), unpinned); +} + +#[test] +fn pin_point_without_an_anchor_pins_where_the_object_is() { + let mut s = on_hump(); + let was = pos(&mut s, 10); + let v = run(&mut s, "motion.pin_point", json!({"frame": 10})); + assert_eq!(v["anchor"], 1); + assert!(pos(&mut s, 10).distance(was) < 0.01, "nothing moves on that frame"); + assert!(anchor(&s, 1).distance(was) < 0.01); + // Outside the motion, or on an end: refused. + assert!(fails(&mut s, "motion.pin_point", json!({"frame": 0})).contains("outside the motion")); + // A straight motion's middle keys are pinned as soon as its path is the tween's own. + let mut t = Session::default(); + run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut t, "timeline.create_motion_tween", json!({})); + t.set_frame(10); + run(&mut t, "element.translate", json!({"dx": 100, "dy": 0})); + t.set_frame(20); + run(&mut t, "element.translate", json!({"dx": 0, "dy": 100})); + let info = run(&mut t, "motion.info", json!({})); + assert_eq!(info["pins"].as_array().map(Vec::len), Some(3), "shown pinned while straight"); + run(&mut t, "motion.pin_point", json!({"frame": 15})); + assert_eq!(motion(&t).pins, vec![Pin { frame: 10, anchor: 1 }, Pin { frame: 15, anchor: 2 }]); +} + +#[test] +fn a_pinned_frames_x_and_y_keys_are_its_anchors_place() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 8})); + let a = anchor(&s, 1); + // The Motion Editor sets X on the pinned frame: the anchor moves, and the object with it. + let v = run(&mut s, "motion.set_key", json!({"property": "x", "frame": 8, "value": a.x + 12.0})); + assert_eq!(v["anchor"], 1); + assert!(anchor(&s, 1).distance(a + Vec2::new(12.0, 0.0)) < 1e-3); + assert!(pos(&mut s, 8).distance(a + Vec2::new(12.0, 0.0)) < 1e-3); + // And the ends: X on the last frame moves the path's end. + run(&mut s, "motion.set_key", json!({"property": "y", "frame": 23, "value": 25.0})); + assert!(anchor(&s, 2).distance(Vec2::new(105.0, 25.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 25.0)) < 1e-3); + // Removing the pinned frame's X key lets the pin go, with its Y key. + let v = run(&mut s, "motion.remove_key", json!({"property": "x", "frame": 8})); + assert_eq!(v["unpinned"], 1); + assert_eq!(v["removed"], json!(["x", "y"])); + assert!(motion(&s).pins.is_empty() && !key_frames(&s, Property::Y).contains(&8)); +} + +#[test] +fn point_edits_keep_pins_on_their_anchors() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 14})); + let pinned = anchor(&s, 1); + // A point added before the pinned anchor: the pin follows it to index 2. + run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.5})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 14, anchor: 2 }]); + assert!(pos(&mut s, 14).distance(pinned) < 1e-3); + // Deleting the point before it keeps the pin; deleting the pinned point lets it go. + let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]})); + assert_eq!(v["unpinned"], 0); + assert_eq!(motion(&s).pins, vec![Pin { frame: 14, anchor: 1 }]); + assert!(pos(&mut s, 14).distance(pinned) < 1e-3); + let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]})); + assert_eq!(v["unpinned"], 1); + assert!(motion(&s).pins.is_empty() && key_frames(&s, Property::X) == vec![0, 23], "its keys went with it"); + // Straighten forgets the pins; their keys stay as the straight path's corners. + run(&mut s, "motion.pin_point", json!({"frame": 14})); + run(&mut s, "motion.clear_path", json!({})); + assert!(motion(&s).pins.is_empty() && key_frames(&s, Property::X).contains(&14)); +} + +#[test] +fn insert_keyframe_inside_a_path_tween_pins_the_path_there() { + let mut s = on_hump(); + let was = pos(&mut s, 11); + s.set_frame(11); + run(&mut s, "timeline.insert_keyframe", json!({})); + assert_eq!(motion(&s).pins, vec![Pin { frame: 11, anchor: 1 }]); + assert!(pos(&mut s, 11).distance(was) < 0.01, "{:?} vs {was:?}", pos(&mut s, 11)); + assert!(key_frames(&s, Property::Rotation).contains(&11), "every other property keyed too"); +} + +#[test] +fn pins_round_trip_through_the_file_format() { + let mut s = on_hump(); + run(&mut s, "motion.pin_point", json!({"frame": 7})); + let text = format::to_json(&s.doc).expect("save"); + assert!(text.contains("\"pins\"")); + let back = format::from_json(&text).expect("load"); + assert_eq!(back, s.doc); + // A path tween from before pins writes none and reads back the same. + let plain = on_hump(); + let text = format::to_json(&plain.doc).expect("save"); + assert!(!text.contains("\"pins\"")); + assert_eq!(format::from_json(&text).expect("load"), plain.doc); +} diff --git a/crates/engine/src/motion_tests.rs b/crates/engine/src/motion_tests.rs index dc7206cd..7f707024 100644 --- a/crates/engine/src/motion_tests.rs +++ b/crates/engine/src/motion_tests.rs @@ -95,7 +95,7 @@ fn transforms_and_colour_edits_key_their_own_properties() { assert!(m.track(Property::ScaleY).is_none() && m.track(Property::X).is_none()); s.set_frame(4); let e = s.visible_elements()[0].clone(); - assert!((e.color.alpha - 0.625).abs() < 1e-5 && (e.transform.decompose().sx - 1.5).abs() < 1e-4); + assert!((e.color.alpha() - 0.625).abs() < 1e-5 && (e.transform.decompose().sx - 1.5).abs() < 1e-4); // Non-tweenable edits change the object itself, whatever the frame. run(&mut s, "edit.select_all", json!({})); run(&mut s, "element.set_fill", json!({"color": "#ff0000"})); diff --git a/crates/engine/src/multi.rs b/crates/engine/src/multi.rs new file mode 100644 index 00000000..c7059569 --- /dev/null +++ b/crates/engine/src/multi.rs @@ -0,0 +1,463 @@ +//! Edit Multiple Frames, complete (ADR 0051; ADR 0047 began it with moves). +//! +//! With Edit Multiple Frames on, the artwork on every keyframe within the onion markers is edited +//! as if it were on one frame. These commands are that editing, on a list of [`FrameItem`]s (an +//! element on one keyframe), or on everything the markers show when no list is given: +//! +//! * `frames.edit_multiple` moves, `frames.transform` scales, rotates and skews about one shared +//! pivot, `frames.align` aligns: each item on its own keyframe, as one undo step; +//! * `frames.delete`, `frames.copy`, `frames.cut`; `frames.paste` pastes in place onto every +//! keyframe within the markers (artwork copied from several keyframes goes back keyframe by +//! keyframe); +//! * raw (merge-drawing) shapes that moved or landed go back into the drawing on their own +//! keyframe, cut and joined with what they touch, as `draw.drop` does on one frame +//! (`merge: false` holds that back while a drag is under way; `frames.merge` does it when the +//! drag ends). +//! +//! Every command answers with `items`: what the selection is afterwards (merged pieces have new +//! ids), so a front end keeps the multi-frame selection without asking again. +//! +//! The timeline is the one being edited, so all of this works inside a symbol open in place +//! (ADR 0045) on the symbol's own keyframes. + +use crate::cmds_modify::{ClipLayer, Clipboard, collect_symbols, import_symbols}; +use crate::onion::{FrameItem, multi_editable}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, LayerId, Timeline}; +use anicraft_geom::{Affine, Rect, Vec2}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, HashSet}; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..], merge?: bool} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; raw shapes merge again where they land unless merge is false; one undo step; answers the items after the move", true, move_cmd as crate::RunFn), + c("frames.transform", "Transform on Multiple Frames", "", None, "{first, last, items?, merge?, a, b, c, d, e, f} (an affine in stage space) | {rotate? (degrees), scale_x?, scale_y?, skew_x?, skew_y? (degrees), pivot?: [x, y] (default: the centre of every item's bounds together)} transforms the items on each keyframe about one shared pivot, as Free Transform does with Edit Multiple Frames on; one undo step", true, transform_cmd), + c("frames.align", "Align on Multiple Frames", "", None, "{first, last, edge: left|hcenter|right|top|vcenter|bottom, items?, to_stage? (default: one item aligns to the stage), merge?} lines the items up with the edge of their bounds together (or the stage's), each on its own keyframe", true, align_cmd), + c("frames.delete", "Clear on Multiple Frames", "", None, "{first, last, items?} deletes the items (default: everything shown) from their keyframes", true, delete_cmd), + c("frames.copy", "Copy on Multiple Frames", "", None, "{first, last, items?} copies the items (default: everything shown), remembering each one's keyframe: Paste on Multiple Frames puts them back keyframe by keyframe, Paste puts them all on the current frame", false, copy_cmd), + c("frames.cut", "Cut on Multiple Frames", "", None, "{first, last, items?} frames.copy, then frames.delete", true, cut_cmd), + c("frames.paste", "Paste in Place on Multiple Frames", "", None, "{first, last, layer?} pastes in place onto the keyframes within the markers: artwork copied from several keyframes onto the keyframe covering the frame each came from (on the layers it came from when it came from several, else on `layer` or the active layer); artwork copied on one frame onto every keyframe of the layer; raw shapes merge where they land", true, paste_cmd), + c("frames.merge", "Merge on Multiple Frames", "", None, "{first, last, items} the raw shapes among the items merge again with what they touch on their keyframes (the end of a drag made with merge: false); answers the items after the merge", true, merge_cmd), + ] +} + +// ----- params and the chosen items ----------------------------------------------------------- + +/// Most items a command takes. +const MAX_ITEMS: usize = 100_000; + +/// The `first` and `last` params, in order. +pub(crate) fn range_param(p: &Value) -> Result<(u32, u32)> { + let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)"))); + let (a, b) = (req("first")?, req("last")?); + if a.max(b) > crate::MAX_FRAME { + return Err(EngineError::Param(format!("frames go up to {}", crate::MAX_FRAME))); + } + Ok((a.min(b), a.max(b))) +} + +fn items_param(p: &Value) -> Result>> { + let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) }; + let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into()); + let list = v.as_array().ok_or_else(bad)?; + if list.len() > MAX_ITEMS { + return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items"))); + } + list.iter() + .map(|t| { + let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?; + let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad); + let frame = u32::try_from(n(1)?).map_err(|_| bad())?; + Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) }) + }) + .collect::>>() + .map(Some) +} + +/// The items a command acts on, with their stage bounds: the `items` given (each must be shown +/// in `first..=last`), or everything shown. +fn chosen(s: &Session, p: &Value, first: u32, last: u32) -> Result> { + let shown = s.multi_frame_items(first, last); + let Some(list) = items_param(p)? else { return Ok(shown) }; + let index: std::collections::HashMap = shown.into_iter().collect(); + let mut out = Vec::with_capacity(list.len()); + let mut seen = HashSet::new(); + for it in list { + let Some(&b) = index.get(&it) else { + return Err(EngineError::State(format!( + "element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)", + it.element.0, it.layer.0, it.frame + ))); + }; + if seen.insert(it) { + out.push((it, b)); + } + } + Ok(out) +} + +/// The items keyframe by keyframe: (layer, keyframe start) → ids, in the order first seen. +fn by_keyframe(items: &[FrameItem]) -> BTreeMap<(LayerId, u32), Vec> { + let mut out: BTreeMap<(LayerId, u32), Vec> = BTreeMap::new(); + for it in items { + let ids = out.entry((it.layer, it.frame)).or_default(); + if !ids.contains(&it.element) { + ids.push(it.element); + } + } + out +} + +fn items_json(items: &[FrameItem]) -> Value { + json!(items.iter().map(FrameItem::to_json).collect::>()) +} + +fn merge_param(p: &Value) -> Result { + Ok(opt_bool(p, "merge")?.unwrap_or(true)) +} + +/// Runs `f` with the playhead on frame `start` of `layer` (a keyframe's first frame), so the +/// editing helpers that work at the playhead work on that keyframe; both come back after. +fn at_keyframe(s: &mut Session, layer: LayerId, start: u32, f: impl FnOnce(&mut Session) -> Result) -> Result { + let frame = s.frame; + s.frame = start; + let r = s.with_layer(layer, f); + s.frame = frame; + r +} + +// ----- moves and transforms ------------------------------------------------------------------ + +/// Whether `m` only moves (no scale, rotation or skew). +fn translation_only(m: &Affine) -> bool { + let [a, b, c, d, _, _] = m.m; + (a - 1.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6 +} + +/// Applies each item's own stage-space affine to it on its keyframe (`t' = m · t`). A motion +/// tween's object carries its path and X/Y keys along; it can only move (refused otherwise). +/// Nothing changes when anything is refused (the session rolls back a failed command). +fn apply_each(s: &mut Session, moves: &[(FrameItem, Affine)]) -> Result { + let mut by: BTreeMap<(LayerId, u32), Vec<(ElementId, Affine)>> = BTreeMap::new(); + for (it, m) in moves { + if !m.is_finite() || m.determinant().abs() < 1e-8 { + return Err(EngineError::Param("the transform is degenerate (it would collapse the artwork)".into())); + } + by.entry((it.layer, it.frame)).or_default().push((it.element, *m)); + } + let mut n = 0usize; + for ((layer, start), list) in &by { + let l = s.layer_mut(Some(*layer))?; + let Some(ki) = l.keyframe_starting_at(*start) else { continue }; + let Some(kf) = l.keyframe_mut(ki) else { continue }; + if let Some(mt) = kf.motion.as_mut() + && let Some((_, m)) = list.iter().find(|(id, _)| *id == mt.target) + { + if !translation_only(m) { + return Err(EngineError::State("a motion tween's object can only be moved on several frames at once; scale, rotate or skew it on its own keyframe".into())); + } + let d = m.translation(); + if d != Vec2::ZERO && !mt.translate(d) { + return Err(EngineError::State("the motion path would move out of range".into())); + } + } + for e in kf.elements_mut_where(|id| list.iter().any(|(x, _)| *x == id)) { + let Some((_, m)) = list.iter().find(|(x, _)| *x == e.id) else { continue }; + let t = m.mul(&e.transform); + let d = t.decompose(); + if !t.is_finite() || d.sx.abs() > 10_000.0 || d.sy.abs() > 10_000.0 || d.sx.abs() < 1e-4 || d.sy.abs() < 1e-4 { + return Err(EngineError::Param("the transform would make an element too large or too small".into())); + } + e.transform = t; + n += 1; + } + } + Ok(n) +} + +/// The raw shapes among `items` go back into the drawing on their keyframes, on top of what they +/// touch, cutting and joining it (`draw.drop` on each keyframe). The items afterwards: objects as +/// they were, each raw shape's pieces with their new ids. +fn remerge(s: &mut Session, items: &[FrameItem]) -> Result> { + // Each keyframe's raw shapes merged: (layer, start) → the pieces (ids gone, ids new). + let mut merged: BTreeMap<(LayerId, u32), (Vec, Vec)> = BTreeMap::new(); + for ((layer, start), ids) in by_keyframe(items) { + let l = s.layer_mut(Some(layer))?; + let Some(ki) = l.keyframe_starting_at(start) else { continue }; + let Some(kf) = l.keyframe_mut(ki) else { continue }; + let mut moving: Vec = Vec::new(); + kf.elements.retain(|e| { + let take = ids.contains(&e.id) && crate::merge::mergeable(e).is_some(); + if take { + moving.push((**e).clone()); + } + !take + }); + if moving.is_empty() { + continue; + } + let gone: Vec = moving.iter().map(|e| e.id).collect(); + let fresh = at_keyframe(s, layer, start, |s| crate::merge::merge_in(s, moving))?; + merged.insert((layer, start), (gone, fresh)); + } + // In the order given: objects as they were, each keyframe's pieces where its first raw + // shape was. + let mut out: Vec = Vec::with_capacity(items.len()); + for it in items { + match merged.get_mut(&(it.layer, it.frame)) { + Some((gone, fresh)) if gone.contains(&it.element) => out.extend(std::mem::take(fresh).into_iter().map(|element| FrameItem { element, ..*it })), + _ => out.push(*it), + } + } + Ok(out) +} + +/// `remerge` when `merge`, else the items as they are. +fn finish(s: &mut Session, items: Vec, merge: bool) -> Result> { + if merge { remerge(s, &items) } else { Ok(items) } +} + +fn move_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); + if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT { + return Err(EngineError::Param("the move is too large".into())); + } + let merge = merge_param(p)?; + let items: Vec = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect(); + let keyframes = by_keyframe(&items).len(); + let mv = Affine::translate(d.x, d.y); + let moved = if d == Vec2::ZERO { 0 } else { apply_each(s, &items.iter().map(|it| (*it, mv)).collect::>())? }; + let items = if moved > 0 { finish(s, items, merge)? } else { items }; + Ok(json!({"moved": moved, "keyframes": keyframes, "dx": d.x, "dy": d.y, "items": items_json(&items)})) +} + +/// The transform a `frames.transform` call asks for, given the items' bounds together. +fn transform_param(p: &Value, bounds: Rect) -> Result { + let keys = ["a", "b", "c", "d", "e", "f"]; + if keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + let mut m = [0.0f32; 6]; + for (slot, k) in m.iter_mut().zip(keys) { + *slot = f32_req(p, k)?; + } + return Ok(Affine { m }); + } + let deg = |k: &str| -> Result { + let v = opt_f32(p, k)?.unwrap_or(0.0); + if v.abs() > 36_000.0 { + return Err(EngineError::Param(format!("param '{k}' is out of range"))); + } + Ok(v.to_radians()) + }; + let factor = |k: &str| -> Result { + let v = opt_f32(p, k)?.unwrap_or(1.0); + if !(1e-3..=1e3).contains(&v.abs()) { + return Err(EngineError::Param(format!("param '{k}' must be a scale between 0.001 and 1000 (negative flips)"))); + } + Ok(v) + }; + let (sx, sy, r, kx, ky) = (factor("scale_x")?, factor("scale_y")?, deg("rotate")?, deg("skew_x")?, deg("skew_y")?); + let pivot = match p.get("pivot").filter(|v| !v.is_null()) { + Some(v) => { + let bad = || EngineError::Param("param 'pivot' must be [x, y]".into()); + 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).map(|x| x as f32).filter(|x| x.is_finite() && x.abs() <= crate::cmds_draw::MAX_EXTENT).ok_or_else(bad); + Vec2::new(n(0)?, n(1)?) + } + None => bounds.center(), + }; + // Scale, then skew, then rotate, about the pivot. + let skew = Affine { m: [1.0, ky.tan(), kx.tan(), 1.0, 0.0, 0.0] }; + let m = Affine::rotate(r).mul(&skew).mul(&Affine::scale(sx, sy)); + Ok(Affine::translate(pivot.x, pivot.y).mul(&m).mul(&Affine::translate(-pivot.x, -pivot.y))) +} + +fn transform_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let merge = merge_param(p)?; + let chosen = chosen(s, p, first, last)?; + if chosen.is_empty() { + return Err(EngineError::State("nothing to transform on the frames between the markers".into())); + } + let bounds = chosen.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b)); + let m = transform_param(p, bounds)?; + let items: Vec = chosen.into_iter().map(|(it, _)| it).collect(); + let n = apply_each(s, &items.iter().map(|it| (*it, m)).collect::>())?; + let items = finish(s, items, merge)?; + Ok(json!({"transformed": n, "keyframes": by_keyframe(&items).len(), "matrix": m.m, "items": items_json(&items)})) +} + +fn align_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let edge = str_req(p, "edge")?; + let merge = merge_param(p)?; + let chosen: Vec<(FrameItem, Rect)> = chosen(s, p, first, last)?.into_iter().filter(|(_, b)| !b.is_empty()).collect(); + if chosen.is_empty() { + return Err(EngineError::State("nothing to align on the frames between the markers".into())); + } + let to_stage = opt_bool(p, "to_stage")?.unwrap_or(chosen.len() == 1); + let target = if to_stage { Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32) } else { chosen.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b)) }; + let d = |b: &Rect| -> Result { + Ok(match edge { + "left" => Vec2::new(target.min.x - b.min.x, 0.0), + "hcenter" => Vec2::new(target.center().x - b.center().x, 0.0), + "right" => Vec2::new(target.max.x - b.max.x, 0.0), + "top" => Vec2::new(0.0, target.min.y - b.min.y), + "vcenter" => Vec2::new(0.0, target.center().y - b.center().y), + "bottom" => Vec2::new(0.0, target.max.y - b.max.y), + _ => return Err(EngineError::Param(format!("unknown edge '{edge}' (left, hcenter, right, top, vcenter or bottom)"))), + }) + }; + let mut moves = Vec::with_capacity(chosen.len()); + for (it, b) in &chosen { + let v = d(b)?; + if v != Vec2::ZERO { + moves.push((*it, Affine::translate(v.x, v.y))); + } + } + let n = apply_each(s, &moves)?; + let moved: Vec = moves.iter().map(|(it, _)| *it).collect(); + let mut items: Vec = chosen.iter().map(|(it, _)| *it).filter(|it| !moved.contains(it)).collect(); + items.extend(finish(s, moved, merge)?); + Ok(json!({"moved": n, "to_stage": to_stage, "items": items_json(&items)})) +} + +fn merge_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + if items_param(p)?.is_none() { + return Err(EngineError::Param("param 'items' is required (the items a drag moved)".into())); + } + let items: Vec = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect(); + let items = remerge(s, &items)?; + Ok(json!({"items": items_json(&items)})) +} + +// ----- delete, copy, cut, paste -------------------------------------------------------------- + +fn delete_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let items: Vec = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect(); + if items.is_empty() { + return Err(EngineError::State("nothing to delete on the frames between the markers".into())); + } + let groups = by_keyframe(&items); + let mut deleted = 0usize; + for ((layer, start), ids) in &groups { + let l = s.layer_mut(Some(*layer))?; + let Some(ki) = l.keyframe_starting_at(*start) else { continue }; + let Some(kf) = l.keyframe_mut(ki) else { continue }; + let before = kf.elements.len(); + kf.elements.retain(|e| !ids.contains(&e.id)); + deleted += before - kf.elements.len(); + } + s.selection.clear(); + Ok(json!({"deleted": deleted, "keyframes": groups.len(), "items": []})) +} + +/// The layers' order in `tl`, top first, for sorting. +fn rank(tl: &Timeline, l: LayerId) -> usize { + tl.layers.iter().position(|x| x.id == l).unwrap_or(usize::MAX) +} + +fn copy_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + let items: Vec = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect(); + if items.is_empty() { + return Err(EngineError::State("nothing to copy on the frames between the markers".into())); + } + let tl = s.timeline(); + let mut groups: Vec<((LayerId, u32), Vec)> = by_keyframe(&items).into_iter().collect(); + // Top layer first, then frame order (a clipboard lists layers top to bottom). + groups.sort_by_key(|((l, f), _)| (rank(tl, *l), *f)); + let mut layers = Vec::with_capacity(groups.len()); + for ((layer, start), ids) in groups { + let Some(l) = tl.layer(layer) else { continue }; + let Some(k) = l.keyframe_starting_at(start).and_then(|i| l.keyframes.get(i)) else { continue }; + // In their stacking order on the keyframe. + let elements: Vec = k.elements.iter().filter(|e| ids.contains(&e.id)).map(|e| (**e).clone()).collect(); + if !elements.is_empty() { + layers.push(ClipLayer { layer, name: l.name.clone(), elements, frame: Some(start) }); + } + } + let all: Vec = layers.iter().flat_map(|c| c.elements.iter().cloned()).collect(); + let symbols = collect_symbols(s, &all); + let (n, keyframes) = (all.len(), layers.len()); + s.clipboard = Clipboard { layers, symbols }; + Ok(json!({"copied": n, "keyframes": keyframes})) +} + +fn cut_cmd(s: &mut Session, p: &Value) -> Result { + let v = copy_cmd(s, p)?; + delete_cmd(s, p)?; + Ok(json!({"cut": v["copied"], "keyframes": v["keyframes"], "items": []})) +} + +/// The first frames of `layer`'s keyframes that Edit Multiple Frames shows in `first..=last` +/// (the playhead's too); none when it doesn't edit that layer. +fn shown_keyframes(tl: &Timeline, layer: LayerId, first: u32, last: u32) -> Vec { + let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return Vec::new() }; + if !multi_editable(tl, i) { + return Vec::new(); + } + tl.layers.get(i).map(|l| l.keyframes.iter().filter(|k| k.start <= last && k.end() > first).map(|k| k.start).collect()).unwrap_or_default() +} + +fn paste_cmd(s: &mut Session, p: &Value) -> Result { + let (first, last) = range_param(p)?; + if s.clipboard.is_empty() { + return Err(EngineError::State("the clipboard is empty".into())); + } + if crate::cmds_modify::clipboard_nests(s) { + return Err(EngineError::State("a symbol can't be pasted inside itself".into())); + } + let active = match opt_u64(p, "layer")? { + Some(id) => LayerId(id), + None => s.layer, + }; + let clip = s.clipboard.clone(); + // Artwork from several layers goes back on those layers when they are all here and edited + // with Edit Multiple Frames; else everything goes on the one layer, as a paste does. + let mut from: Vec = Vec::new(); + for c in &clip.layers { + if !from.contains(&c.layer) { + from.push(c.layer); + } + } + let tl = s.timeline(); + let home = from.len() > 1 && from.iter().all(|l| !shown_keyframes(tl, *l, first, last).is_empty()); + let mut plan: Vec<(LayerId, u32, &ClipLayer)> = Vec::new(); + let mut skipped = 0usize; + for c in &clip.layers { + let target = if home { c.layer } else { active }; + let keys = shown_keyframes(tl, target, first, last); + match c.frame { + // Back onto the keyframe covering the frame it came from, if the markers show it. + Some(f) => match tl.layer(target).and_then(|l| l.keyframe_at(f)).map(|k| k.start).filter(|k| keys.contains(k)) { + Some(k) => plan.push((target, k, c)), + None => skipped += 1, + }, + // Copied on one frame: onto every keyframe shown. + None => plan.extend(keys.iter().map(|&k| (target, k, c))), + } + } + if plan.is_empty() { + let why = if tl.layer(active).is_some_and(|_| shown_keyframes(tl, active, first, last).is_empty()) { "the layer has no keyframe Edit Multiple Frames can paste onto between the markers (it must be visible, unlocked and hold artwork)" } else { "none of the copied keyframes is between the markers" }; + return Err(EngineError::State(why.into())); + } + import_symbols(s, &clip.symbols); + let mut items = Vec::new(); + let mut keyframes: HashSet<(LayerId, u32)> = HashSet::new(); + for (layer, start, c) in plan { + let (fresh, _) = at_keyframe(s, layer, start, |s| crate::cmds_modify::paste_layer(s, &c.elements, Vec2::ZERO))?; + keyframes.insert((layer, start)); + items.extend(fresh.into_iter().map(|element| FrameItem { layer, frame: start, element })); + } + s.selection.clear(); + Ok(json!({"pasted": items.len(), "keyframes": keyframes.len(), "skipped": skipped, "items": items_json(&items)})) +} + +#[cfg(test)] +#[path = "multi_tests.rs"] +mod tests; diff --git a/crates/engine/src/multi_tests.rs b/crates/engine/src/multi_tests.rs new file mode 100644 index 00000000..bd6ed5af --- /dev/null +++ b/crates/engine/src/multi_tests.rs @@ -0,0 +1,349 @@ +//! Edit Multiple Frames, complete (ADR 0051): transforms about one shared pivot, align, delete, +//! copy, cut and paste per keyframe, raw shapes merged again on their keyframes, and all of it +//! (with onion skin) inside a symbol open in place. + +use super::*; +use crate::Session; +use crate::onion::OnionSkin; +use anicraft_doc::{ElementKind, Keyframe, LayerId}; +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} {p}: {e}")) +} + +/// One layer, a 20 × 20 drawing object walking right: keyframes on frames 0, 4 and 8 with it at +/// x = 10, 50 and 90 (y = 10). The playhead is on frame 4. +fn walk() -> (Session, LayerId, ElementId) { + let mut s = Session::default(); + let layer = s.layer; + let id = ElementId(run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()); + for f in [4, 8] { + run(&mut s, "timeline.goto", json!({"frame": f})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [id.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + run(&mut s, "timeline.goto", json!({"frame": 4})); + (s, layer, id) +} + +fn key(s: &Session, layer: LayerId, start: u32) -> Keyframe { + let l = s.timeline().layer(layer).unwrap(); + (**l.keyframes.iter().find(|k| k.start == start).unwrap()).clone() +} + +/// The bounds of every element on the keyframe of `layer` starting at `start`. +fn bounds_on(s: &Session, layer: LayerId, start: u32) -> Vec { + key(s, layer, start).elements.iter().map(|e| e.bounds(&s.doc)).collect() +} + +fn near(a: Rect, b: [f32; 4]) -> bool { + [a.min.x, a.min.y, a.max.x, a.max.y].iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3) +} + +#[test] +fn a_transform_about_the_shared_pivot_lands_each_keyframes_artwork_exactly() { + let (mut s, a, _) = walk(); + let steps = s.history_len(); + // Together the three copies span x 10..110, y 10..30: the pivot is (60, 20). + let v = run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "scale_x": 2, "scale_y": 0.5})); + assert_eq!((v["transformed"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3))); + // x' = 60 + 2 (x − 60), y' = 20 + 0.5 (y − 20). + for (f, x) in [(0, 10.0), (4, 50.0), (8, 90.0)] { + let b = bounds_on(&s, a, f)[0]; + assert!(near(b, [60.0 + 2.0 * (x - 60.0), 15.0, 60.0 + 2.0 * (x + 20.0 - 60.0), 25.0]), "keyframe {f}: {b:?}"); + } + assert_eq!(s.history_len(), steps + 1, "one undo step"); + s.undo().unwrap(); + // A quarter turn (clockwise on the y-down stage): (x, y) → (60 − (y − 20), 20 + (x − 60)). + run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "rotate": 90})); + for (f, x) in [(0, 10.0), (4, 50.0), (8, 90.0)] { + let b = bounds_on(&s, a, f)[0]; + let (cx, cy) = (x + 10.0, 20.0); + let (nx, ny) = (60.0 - (cy - 20.0), 20.0 + (cx - 60.0)); + assert!(near(b, [nx - 10.0, ny - 10.0, nx + 10.0, ny + 10.0]), "keyframe {f}: {b:?}"); + } + // Its own pivot, and a matrix, as Free Transform sends. + s.undo().unwrap(); + let on8 = key(&s, a, 8).elements[0].id.0; + run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "scale_x": 2, "pivot": [10, 10], "items": [[a.0, 8, on8]]})); + assert!(near(bounds_on(&s, a, 8)[0], [170.0, 10.0, 210.0, 30.0])); + assert!(near(bounds_on(&s, a, 0)[0], [10.0, 10.0, 30.0, 30.0]), "only the item given"); + run(&mut s, "frames.transform", json!({"first": 0, "last": 4, "a": 1, "b": 0, "c": 0, "d": 1, "e": 5, "f": -5})); + assert!(near(bounds_on(&s, a, 0)[0], [15.0, 5.0, 35.0, 25.0])); + // Degenerate or wild transforms are refused, with nothing changed. + let before = s.doc.clone(); + assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "a": 0, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0})).is_err()); + assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "scale_x": 0})).is_err()); + assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "pivot": [1]})).is_err()); + assert!(s.doc == before); +} + +#[test] +fn align_lines_every_keyframes_artwork_up() { + let (mut s, a, _) = walk(); + run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 0, "dy": 0})); + let v = run(&mut s, "frames.align", json!({"first": 0, "last": 8, "edge": "left"})); + assert_eq!(v["moved"], json!(2), "the one already at the left edge stays"); + for f in [0, 4, 8] { + assert!(near(bounds_on(&s, a, f)[0], [10.0, 10.0, 30.0, 30.0]), "keyframe {f}"); + } + s.undo().unwrap(); + run(&mut s, "frames.align", json!({"first": 0, "last": 8, "edge": "bottom", "to_stage": true})); + let h = s.doc.stage.height as f32; + assert!([0, 4, 8].iter().all(|&f| (bounds_on(&s, a, f)[0].max.y - h).abs() < 1e-3)); + assert!(s.execute("frames.align", &json!({"first": 0, "last": 8, "edge": "middle"})).is_err()); +} + +#[test] +fn delete_copy_cut_and_paste_count_per_keyframe() { + let (mut s, a, id) = walk(); + // A second element on keyframes 0 and 8 only. + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "draw.rect", json!({"x": 10, "y": 100, "w": 10, "h": 10, "object": true})); + run(&mut s, "timeline.goto", json!({"frame": 8})); + run(&mut s, "draw.rect", json!({"x": 90, "y": 100, "w": 10, "h": 10, "object": true})); + run(&mut s, "timeline.goto", json!({"frame": 4})); + let count = |s: &Session| [0, 4, 8].map(|f| key(s, a, f).elements.len()); + assert_eq!(count(&s), [2, 1, 2]); + + // Copy the walker on 0 and 8 (with its keyframes), cut everything else. + let walker = |f| json!([a.0, f, id.0]); + let v = run(&mut s, "frames.copy", json!({"first": 0, "last": 8, "items": [walker(0), walker(8)]})); + assert_eq!((v["copied"].as_u64(), v["keyframes"].as_u64()), (Some(2), Some(2))); + assert_eq!(s.clipboard.layers.iter().map(|c| c.frame).collect::>(), vec![Some(0), Some(8)]); + let steps = s.history_len(); + let v = run(&mut s, "frames.delete", json!({"first": 0, "last": 8, "items": [walker(0), walker(4), walker(8)]})); + assert_eq!((v["deleted"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3))); + assert_eq!(count(&s), [1, 0, 1]); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + + // Paste in place: back keyframe by keyframe, where each came from. + let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 8})); + assert_eq!((v["pasted"].as_u64(), v["keyframes"].as_u64(), v["skipped"].as_u64()), (Some(2), Some(2), Some(0))); + assert_eq!(count(&s), [2, 0, 2]); + assert!(near(bounds_on(&s, a, 8)[1], [90.0, 10.0, 110.0, 30.0]), "in place"); + assert_eq!(v["items"].as_array().map(Vec::len), Some(2), "what was pasted is what is selected"); + // Markers that leave out frame 8: only the copy from 0 goes back. + let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 3})); + assert_eq!((v["pasted"].as_u64(), v["skipped"].as_u64()), (Some(1), Some(1))); + assert_eq!(count(&s), [3, 0, 2]); + + // Copied on one frame: onto every keyframe shown. + run(&mut s, "timeline.goto", json!({"frame": 0})); + let small = key(&s, a, 0).elements[0].id; + run(&mut s, "element.select", json!({"ids": [small.0]})); + run(&mut s, "edit.copy", json!({})); + let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 8})); + assert_eq!((v["pasted"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3))); + assert_eq!(count(&s), [4, 1, 3]); + + // Cut: copies, then deletes, as one step. + let steps = s.history_len(); + let v = run(&mut s, "frames.cut", json!({"first": 0, "last": 8})); + assert_eq!(v["cut"], json!(8)); + assert_eq!(count(&s), [0, 0, 0]); + assert_eq!(s.history_len(), steps + 1); + // A plain Paste puts a multi-frame copy on the current frame, on the active layer. + run(&mut s, "timeline.goto", json!({"frame": 4})); + run(&mut s, "edit.paste_in_place", json!({})); + assert_eq!(count(&s), [0, 8, 0]); + + // Nothing to act on, or nowhere to paste: refused. + run(&mut s, "layer.toggle_lock", json!({"layer": a.0})); + assert!(s.execute("frames.paste", &json!({"first": 0, "last": 8})).is_err(), "a locked layer"); +} + +/// Raw (merge-drawing) rectangles, the same colour, on keyframes 0 and 5: one at x 0..40 and one +/// at x 100..140 (y 0..40). Their ids on each keyframe. +fn raw_pair() -> (Session, LayerId) { + let mut s = Session::default(); + s.style.object_drawing = false; + let layer = s.layer; + for x in [0, 100] { + run(&mut s, "draw.rect", json!({"x": x, "y": 0, "w": 40, "h": 40, "fill": "#3366ff", "stroke": null})); + } + run(&mut s, "timeline.goto", json!({"frame": 5})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + (s, layer) +} + +fn raw_fills(s: &Session, layer: LayerId, start: u32) -> Vec { + key(s, layer, start).elements.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_some())).map(|e| e.bounds(&s.doc)).collect() +} + +#[test] +fn raw_shapes_merge_again_on_each_keyframe_after_a_move_or_transform() { + let (mut s, a) = raw_pair(); + assert_eq!(raw_fills(&s, a, 0).len(), 2); + let right = |s: &Session, f: u32| key(s, a, f).elements.iter().find(|e| e.bounds(&s.doc).min.x > 50.0).map(|e| json!([a.0, f, e.id.0])).unwrap(); + let items = json!([right(&s, 0), right(&s, 5)]); + // Moved left by 80 it overlaps the other (x 20..60): one fill region on each keyframe. + let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 5, "dx": -80, "dy": 0, "items": items})); + for f in [0, 5] { + let fills = raw_fills(&s, a, f); + assert_eq!(fills.len(), 1, "keyframe {f}: joined into one fill: {fills:?}"); + assert!(near(fills[0], [0.0, 0.0, 60.0, 40.0]), "keyframe {f}: {:?}", fills[0]); + } + // The selection is the merged pieces, with their new ids. + let after: Vec = v["items"].as_array().unwrap().clone(); + assert_eq!(after.len(), 2); + for it in &after { + let f = it[1].as_u64().unwrap() as u32; + assert!(key(&s, a, f).elements.iter().any(|e| json!(e.id.0) == it[2]), "{it} is on its keyframe"); + } + s.undo().unwrap(); + assert_eq!(raw_fills(&s, a, 5).len(), 2, "one undo takes the move and the merge back"); + + // A drag holds the merge back (merge: false) and merges when it ends (frames.merge). + let items = json!([right(&s, 0), right(&s, 5)]); + s.begin_gesture("Move"); + for _ in 0..4 { + run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 5, "dx": -20, "dy": 0, "items": items, "merge": false})); + } + assert_eq!(raw_fills(&s, a, 0).len(), 2, "not merged mid-drag"); + let v = run(&mut s, "frames.merge", json!({"first": 0, "last": 5, "items": items})); + s.end_gesture(); + assert_eq!([0, 5].map(|f| raw_fills(&s, a, f).len()), [1, 1]); + assert_eq!(v["items"].as_array().map(Vec::len), Some(2)); + assert!(s.execute("frames.merge", &json!({"first": 0, "last": 5})).is_err(), "items are required"); + + // A transform merges too: the right square scaled 3× about its right edge reaches over. + s.undo().unwrap(); + let items = json!([right(&s, 0), right(&s, 5)]); + run(&mut s, "frames.transform", json!({"first": 0, "last": 5, "items": items, "scale_x": 3, "pivot": [140, 0]})); + for f in [0, 5] { + let fills = raw_fills(&s, a, f); + assert_eq!(fills.len(), 1, "keyframe {f}: {fills:?}"); + assert!(near(fills[0], [0.0, 0.0, 140.0, 40.0]), "keyframe {f}: {:?}", fills[0]); + } +} + +#[test] +fn a_motion_tweens_object_moves_but_does_not_scale_on_several_frames() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "object": true})); + run(&mut s, "timeline.insert_frame", json!({"count": 9})); + run(&mut s, "timeline.create_motion_tween", json!({})); + let before = s.doc.clone(); + let e = s.execute("frames.transform", &json!({"first": 0, "last": 9, "rotate": 30})); + assert!(e.is_err_and(|e| e.to_string().contains("motion tween"))); + assert!(s.doc == before); + run(&mut s, "frames.transform", json!({"first": 0, "last": 9, "a": 1, "b": 0, "c": 0, "d": 1, "e": 10, "f": 0})); +} + +/// A symbol open in place (ADR 0045) whose own timeline has keyframes on 0 and 4, the playhead on 4. +fn in_symbol() -> (Session, LayerId, ElementId) { + let mut s = Session::default(); + let id = ElementId(run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Walker"})); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 50})); + run(&mut s, "symbol.edit", json!({})); + let inner = s.layer; + run(&mut s, "timeline.goto", json!({"frame": 4})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [id.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + assert_eq!(s.editing.len(), 1); + (s, inner, id) +} + +#[test] +fn inside_a_symbol_the_commands_edit_its_own_keyframes() { + let (mut s, inner, id) = in_symbol(); + let shown = s.multi_frame_items(0, 4); + assert_eq!(shown.iter().map(|(it, _)| it.frame).collect::>(), vec![0, 4], "the symbol's keyframes"); + run(&mut s, "frames.transform", json!({"first": 0, "last": 4, "scale_x": 2, "scale_y": 2})); + // In the symbol's space (its registration point at the square's centre) the two copies + // span x −10..50, y −10..10 together: the pivot is (20, 0). + assert!(near(bounds_on(&s, inner, 0)[0], [-40.0, -20.0, 0.0, 20.0])); + assert!(near(bounds_on(&s, inner, 4)[0], [40.0, -20.0, 80.0, 20.0])); + run(&mut s, "frames.copy", json!({"first": 0, "last": 4, "items": [[inner.0, 0, id.0]]})); + run(&mut s, "frames.paste", json!({"first": 0, "last": 4})); + assert_eq!(key(&s, inner, 0).elements.len(), 2); + run(&mut s, "frames.delete", json!({"first": 0, "last": 4})); + assert!([0, 4].iter().all(|&f| key(&s, inner, f).elements.is_empty())); + // The scene's own timeline never changed shape: one layer, one instance. + assert_eq!(s.doc.timeline(s.scene).layers.len(), 1); +} + +#[test] +fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() { + let (s, _, _) = in_symbol(); + let pic = s.stage_picture(); + let front = pic.front.clone().expect("the open symbol is in front"); + assert_eq!(front.frame, 4); + let plain = crate::render_service::display_list_with_onion(&pic.doc, pic.frame, None); + let ghosts = OnionSkin { markers: crate::onion::Markers::Relative { before: 4, after: 0 }, keyframes_only: true, ..OnionSkin::default() }; + let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &ghosts); + assert_eq!(dl.items.len(), plain.items.len() + 1, "frame 0 of the symbol under its frame 4"); + // The symbol's origin stands at x 110: its frame 0 (x −10..10) shows at x 100..120, tinted + // and faded; its frame 4 (x 30..50) at 140..160 at full strength, on top. + let left = |i: &anicraft_doc::DisplayItem| i.path.bounds().transformed(&i.transform).min.x; + let n = dl.items.len(); + let (ghost, now) = (&dl.items[n - 2], &dl.items[n - 1]); + assert_eq!((left(ghost), left(now)), (100.0, 140.0)); + assert!(ghost.color.mul[3] < 1.0 && ghost.color.changes_colour() && now.color.is_identity()); + // The job does the same, keyed apart from the plain picture. + let view = anicraft_render::View { transform: Affine::IDENTITY, width: 64, height: 64, background: None }; + let plain_job = crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, Some(&ghosts)); + let job = plain_job.clone().inside(pic.front.clone()); + assert_ne!(job.key, plain_job.key); + assert_eq!(job.display_list().items.len(), dl.items.len()); + // Edit Multiple Frames shows both keyframes at full strength. + let multi = OnionSkin { edit_multiple: true, markers: crate::onion::Markers::Relative { before: 4, after: 0 }, ..OnionSkin::default() }; + let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi); + assert!(dl.items.iter().rev().take(2).all(|i| i.color.is_identity())); + // With nothing to add, the job draws the picture as it is. + let off = make_off(&pic); + assert_eq!(off.display_list().items.len(), plain.items.len()); +} + +fn make_off(pic: &crate::editing::StagePicture) -> crate::render_service::FrameJob { + let view = anicraft_render::View { transform: Affine::IDENTITY, width: 64, height: 64, background: None }; + crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, None).inside(pic.front.clone()) +} + + +/// Measured numbers for ADR 0051: `cargo test -p anicraft-engine --lib multi_timings -- --ignored --nocapture`. +#[test] +#[ignore] +fn multi_timings() { + use std::time::Instant; + // 24 keyframes, each with 12 × 12 raw squares and 50 objects. + let mut s = Session::default(); + s.style.object_drawing = false; + for i in 0..144 { + let (x, y) = ((i % 12) as f32 * 50.0, (i / 12) as f32 * 50.0); + run(&mut s, "draw.rect", json!({"x": x, "y": y, "w": 30, "h": 30, "fill": "#3366ff", "stroke": null})); + } + for i in 0..50 { + run(&mut s, "draw.rect", json!({"x": 700 + i, "y": i * 10, "w": 20, "h": 20, "object": true})); + } + for f in 1..24 { + run(&mut s, "timeline.goto", json!({"frame": f * 2})); + run(&mut s, "timeline.insert_keyframe", json!({})); + } + let last = 47; + let t = |label: &str, f: &mut dyn FnMut(&mut Session)| { + let mut s2 = Session::new(s.doc.clone()); + let t0 = Instant::now(); + f(&mut s2); + eprintln!("{label}: {:.2} ms", t0.elapsed().as_secs_f64() * 1000.0); + }; + let objects = |s: &Session| -> Vec { s.multi_frame_items(0, last).into_iter().filter(|(it, _)| key(s, it.layer, it.frame).elements.iter().any(|e| e.id == it.element && !matches!(&e.kind, ElementKind::Shape(sh) if sh.merge))).map(|(it, _)| it.to_json()).collect() }; + let raws = |s: &Session| -> Vec { s.multi_frame_items(0, last).into_iter().filter(|(it, _)| key(s, it.layer, it.frame).elements.iter().any(|e| e.id == it.element && matches!(&e.kind, ElementKind::Shape(sh) if sh.merge))).map(|(it, _)| it.to_json()).take(24 * 12).collect() }; + let (objects, raws) = (objects(&s), raws(&s)); + eprintln!("items shown: {}, objects: {}, raw: {}", s.multi_frame_items(0, last).len(), objects.len(), raws.len()); + t("list what is shown (24 keyframes)", &mut |s| drop(s.multi_frame_items(0, last))); + t("move 1,200 objects, a drag step", &mut |s| drop(run(s, "frames.edit_multiple", json!({"first": 0, "last": last, "dx": 1, "dy": 0, "items": objects, "merge": false})))); + t("rotate 1,200 objects", &mut |s| drop(run(s, "frames.transform", json!({"first": 0, "last": last, "rotate": 15, "items": objects})))); + t("move and merge 288 raw squares (24 keyframes)", &mut |s| drop(run(s, "frames.edit_multiple", json!({"first": 0, "last": last, "dx": 25, "dy": 0, "items": raws})))); + t("copy 1,200 objects, paste in place", &mut |s| { + run(s, "frames.copy", json!({"first": 0, "last": last, "items": objects})); + run(s, "frames.paste", json!({"first": 0, "last": last})); + }); + t("delete everything shown", &mut |s| drop(run(s, "frames.delete", json!({"first": 0, "last": last})))); +} diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs index 932b58ab..cc51e5e8 100644 --- a/crates/engine/src/onion.rs +++ b/crates/engine/src/onion.rs @@ -18,10 +18,9 @@ //! Behaviour learned from Adobe's public help pages on onion skinning and from watching the //! program; nothing was copied. -use crate::params::*; -use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session}; -use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline}; -use anicraft_geom::{Affine, Rect, Vec2}; +use crate::{CommandSpec, MAX_FRAME, Result, Session}; +use anicraft_doc::{ColorTransform, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline}; +use anicraft_geom::{Rect, Vec2}; use serde_json::{Value, json}; use std::collections::{BTreeMap, HashSet}; use std::hash::{Hash, Hasher}; @@ -169,12 +168,12 @@ impl OnionSkin { } /// The colour effect an onion frame gets, and the outline colour (when outlines are on). - pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorEffect, Option) { + pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorTransform, Option) { let alpha = self.alpha(distance, reach); let color = if past { self.past } else { self.future }; let (tint, tint_amount) = if self.tint { (color, TINT_AMOUNT) } else { (Rgba::WHITE, 0.0) }; let outline = self.outlines.then(|| color.with_alpha(alpha * color.a.clamp(0.0, 1.0))); - (ColorEffect { alpha, tint, tint_amount }, outline) + (ColorTransform::alpha(alpha).concat(&ColorTransform::tint(tint, tint_amount)), outline) } /// A hash of everything that changes the picture, for render-cache keys. @@ -200,15 +199,22 @@ pub struct Extra { pub distance: u32, } -/// Whether onion skin draws `layer` (Animate doesn't onion-skin locked layers). -fn ghosted(tl: &Timeline, i: usize) -> bool { +/// Whether `layer` is shown and unlocked artwork (not a folder), itself and through its folders. +fn open_artwork(tl: &Timeline, i: usize) -> bool { tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder && !tl.locked_by_folder(l.id) && !tl.hidden_by_folder(i)) } +/// Whether onion skin draws `layer`: shown and unlocked (Animate doesn't onion-skin locked +/// layers), with its own onion toggle on (ADR 0061). +pub fn ghosted(tl: &Timeline, i: usize) -> bool { + open_artwork(tl, i) && tl.layers.get(i).is_some_and(|l| l.onion) +} + /// Whether Edit Multiple Frames shows and edits `layer`'s other keyframes: it is shown and /// unlocked, and holds artwork (not a folder, the camera or an armature posed by its bones). +/// A layer's onion toggle doesn't apply: it is about the faded frames, not editing. pub fn multi_editable(tl: &Timeline, i: usize) -> bool { - ghosted(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature)) + open_artwork(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature)) } /// The onion frames to draw for the playhead on `playhead`, farthest first (nearest on top), @@ -302,6 +308,9 @@ fn interleave(tl: &Timeline, parts: Vec) -> (DisplayList, Vec| c.map(|c| c + base); let gshift = move |g: Option| g.map(|g| g + gbase); dl.clip_parents.extend(part.clip_parents.into_iter().map(shift)); + for (i, m) in part.clip_modes.into_iter().enumerate() { + dl.set_clip_mode(base + i as u32, m); + } dl.groups.extend(part.groups.into_iter().map(|g| anicraft_doc::Group { parent: gshift(g.parent), clip: shift(g.clip), ..g })); iters.push( part.items @@ -341,9 +350,14 @@ fn interleave(tl: &Timeline, parts: Vec) -> (DisplayList, Vec, eval: impl Fn(usize, u32) -> DisplayList + Sync) -> DisplayList { - let now = eval(scene, local); + compose_timeline(doc.timeline(scene), local, skin, |f| eval(scene, f)) +} + +/// [`compose`] for any timeline: `tl` at its frame `local`, `eval` evaluating one of its frames +/// (a scene's, or a symbol's open in place, ADR 0051). Pure: the same inputs give the same list. +pub fn compose_timeline(tl: &Timeline, local: u32, skin: Option<&OnionSkin>, eval: impl Fn(u32) -> DisplayList + Sync) -> DisplayList { + let now = eval(local); let Some(skin) = skin.filter(|s| s.shows()) else { return now }; - let tl = doc.timeline(scene); let (first, last) = skin.range(local, tl.frame_count()); let extras = if skin.edit_multiple { multi_frames(tl, local, first, last) } else { onion_frames(tl, local, skin) }; if extras.is_empty() { @@ -351,7 +365,7 @@ pub fn compose(doc: &Document, scene: usize, local: u32, skin: Option<&OnionSkin } // The frames are independent: evaluated in parallel, kept in order. use rayon::prelude::*; - let mut parts: Vec = extras.par_iter().map(|e| eval(scene, e.frame)).collect(); + let mut parts: Vec = extras.par_iter().map(|e| eval(e.frame)).collect(); for (part, e) in parts.iter_mut().zip(&extras) { keep_layers(part, &e.layers); if let Some(past) = e.past { @@ -391,11 +405,12 @@ impl Session { /// (each keyframe as it looks on its first frame, the playhead's as it looks there), with /// the keyframe start of each item's layer (`None`: a layer it doesn't edit). fn multi_list(&self, first: u32, last: u32) -> (DisplayList, Vec>) { - let tl = self.doc.timeline(self.scene); + // The timeline being edited: a symbol open in place has its own frames (ADR 0045). + let tl = self.timeline(); let mut parts = Vec::new(); let mut starts: Vec> = Vec::new(); for e in multi_frames(tl, self.frame, first, last) { - let mut dl = anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame); + let mut dl = if self.editing.is_empty() { anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame) } else { anicraft_doc::evaluate_timeline(&self.doc, tl, e.frame) }; keep_layers(&mut dl, &e.layers); parts.push(dl); starts.push(e.layers.iter().map(|l| (*l, e.frame)).collect()); @@ -450,95 +465,15 @@ pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ c("frames.artwork", "Artwork on Multiple Frames", "", None, "{first, last} lists every element Edit Multiple Frames shows in frames first..=last (0-based): [layer, frame (its keyframe's first frame), id] with stage bounds; the playhead's elements as they look there", false, artwork as crate::RunFn), - c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..]} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; one undo step", true, edit_multiple), ] } -/// The `first` and `last` params, in order. -fn range_param(p: &Value) -> Result<(u32, u32)> { - let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)"))); - let (a, b) = (req("first")?, req("last")?); - if a.max(b) > MAX_FRAME { - return Err(EngineError::Param(format!("frames go up to {MAX_FRAME}"))); - } - Ok((a.min(b), a.max(b))) -} - fn artwork(s: &mut Session, p: &Value) -> Result { - let (first, last) = range_param(p)?; + let (first, last) = crate::multi::range_param(p)?; let items: Vec = s.multi_frame_items(first, last).into_iter().map(|(it, b)| json!({"layer": it.layer.0, "frame": it.frame, "id": it.element.0, "bounds": [b.min.x, b.min.y, b.max.x, b.max.y]})).collect(); Ok(json!({"first": first, "last": last, "items": items})) } -/// Most items `frames.edit_multiple` takes. -const MAX_ITEMS: usize = 100_000; - -fn items_param(p: &Value) -> Result>> { - let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) }; - let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into()); - let list = v.as_array().ok_or_else(bad)?; - if list.len() > MAX_ITEMS { - return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items"))); - } - list.iter() - .map(|t| { - let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?; - let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad); - let frame = u32::try_from(n(1)?).map_err(|_| bad())?; - Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) }) - }) - .collect::>>() - .map(Some) -} - -fn edit_multiple(s: &mut Session, p: &Value) -> Result { - let (first, last) = range_param(p)?; - let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); - if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT { - return Err(EngineError::Param("the move is too large".into())); - } - let shown: Vec = s.multi_frame_items(first, last).into_iter().map(|(it, _)| it).collect(); - let items = match items_param(p)? { - Some(list) => { - let have: HashSet = shown.iter().copied().collect(); - if let Some(bad) = list.iter().find(|it| !have.contains(it)) { - return Err(EngineError::State(format!( - "element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)", - bad.element.0, bad.layer.0, bad.frame - ))); - } - list - } - None => shown, - }; - // One pass per keyframe: (layer, keyframe start) → its ids. - let mut by_key: BTreeMap<(LayerId, u32), HashSet> = BTreeMap::new(); - for it in &items { - by_key.entry((it.layer, it.frame)).or_default().insert(it.element); - } - let mv = Affine::translate(d.x, d.y); - let mut moved = 0usize; - for ((layer, start), ids) in &by_key { - let l = s.layer_mut(Some(*layer))?; - let Some(ki) = l.keyframe_starting_at(*start) else { continue }; - let Some(kf) = l.keyframe_mut(ki) else { continue }; - // A motion tween's object carries its path and X/Y keys along (refused, with nothing - // changed, if they would leave the stage's range). - if let Some(m) = kf.motion.as_mut() - && ids.contains(&m.target) - && d != Vec2::ZERO - && !m.translate(d) - { - return Err(EngineError::State("the motion path would move out of range".into())); - } - for e in kf.elements_mut_where(|id| ids.contains(&id)) { - e.transform = mv.mul(&e.transform); - moved += 1; - } - } - Ok(json!({"moved": moved, "keyframes": by_key.len(), "dx": d.x, "dy": d.y})) -} - #[cfg(test)] #[path = "onion_tests.rs"] mod tests; diff --git a/crates/engine/src/onion_tests.rs b/crates/engine/src/onion_tests.rs index 014bc507..4da367cb 100644 --- a/crates/engine/src/onion_tests.rs +++ b/crates/engine/src/onion_tests.rs @@ -4,6 +4,7 @@ use super::*; use crate::Session; use anicraft_doc::{DisplayItem, ElementId, LayerId, Rgba, evaluate_scene, sample}; +use anicraft_geom::Affine; use anicraft_render::{View, render}; use serde_json::{Value, json}; @@ -105,11 +106,12 @@ fn onion_frames_fade_by_distance_in_their_colours() { assert!((1..=5).all(|d| flat.alpha(d, 5) == NEAR_ALPHA)); let (past, line) = o.look(true, 1, 2); - assert_eq!((past.tint, past.tint_amount, past.alpha, line), (o.past, TINT_AMOUNT, NEAR_ALPHA, None)); + let look = |c, a| anicraft_doc::ColorTransform::alpha(a).concat(&anicraft_doc::ColorTransform::tint(c, TINT_AMOUNT)); + assert_eq!((past, line), (look(o.past, NEAR_ALPHA), None)); let (future, _) = o.look(false, 2, 2); - assert_eq!((future.tint, future.alpha), (o.future, FAR_ALPHA)); + assert_eq!(future, look(o.future, FAR_ALPHA)); let (own, _) = OnionSkin { tint: false, ..o }.look(true, 1, 2); - assert_eq!(own.tint_amount, 0.0, "untinted frames keep their own colours"); + assert!(!own.changes_colour(), "untinted frames keep their own colours"); let (_, line) = OnionSkin { outlines: true, ..o }.look(false, 2, 2); assert_eq!(line, Some(o.future.with_alpha(FAR_ALPHA))); } @@ -181,10 +183,11 @@ fn composed_onion_frames_are_tinted_faded_and_under_the_playhead() { let skin = OnionSkin::default(); let dl = compose(&s.doc, 0, 4, Some(&skin), |sc, f| evaluate_scene(&s.doc, sc, f)); // Frames 2, 6, 3, 5 under frame 4: the keyframes there hold the rectangle at 10, 50, 10, 50. - let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect(); + let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.mul[3], 1.0 - i.color.mul[0])).collect(); assert_eq!(got, vec![(10.0, FAR_ALPHA, TINT_AMOUNT), (50.0, FAR_ALPHA, TINT_AMOUNT), (10.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, 1.0, 0.0)]); - assert_eq!(dl.items.first().map(|i| i.color.tint), Some(skin.past)); - assert_eq!(dl.items.get(1).map(|i| i.color.tint), Some(skin.future)); + let tint = |c| anicraft_doc::ColorTransform::tint(c, TINT_AMOUNT).add; + assert_eq!(dl.items.first().map(|i| i.color.add), Some(tint(skin.past))); + assert_eq!(dl.items.get(1).map(|i| i.color.add), Some(tint(skin.future))); // Off, or None: the frame alone. let off = OnionSkin { ghosts: false, ..skin }; assert_eq!(compose(&s.doc, 0, 4, Some(&off), |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1); @@ -229,7 +232,7 @@ fn edit_multiple_frames_shows_keyframes_within_the_markers_at_full_strength() { // doesn't; the one on 4 is the playhead's. assert_eq!(multi_frames(tl, 4, 2, 6).iter().map(|e| e.frame).collect::>(), vec![0]); let dl = compose(&s.doc, 0, 4, Some(&near), |sc, f| evaluate_scene(&s.doc, sc, f)); - assert_eq!(dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect::>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]); + assert_eq!(dl.items.iter().map(|i| (left(i), i.color.mul[3], 1.0 - i.color.mul[0])).collect::>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]); let wide = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..near }; let dl = compose(&s.doc, 0, 4, Some(&wide), |sc, f| evaluate_scene(&s.doc, sc, f)); assert_eq!(dl.items.iter().map(left).collect::>(), vec![10.0, 90.0, 50.0], "other keyframes in frame order, the playhead's on top"); @@ -419,7 +422,7 @@ fn extra_frames_sit_on_their_own_layer_over_an_opaque_background() { let ball = plain.items.last().unwrap().layer; let on_ball: Vec<&DisplayItem> = dl.items.iter().filter(|i| i.layer == ball).collect(); assert!(on_ball.len() > 1); - assert_eq!(on_ball.last().map(|i| (i.color.alpha, i.color.tint_amount)), Some((1.0, 0.0)), "the playhead's ball is on top"); + assert_eq!(on_ball.last().map(|i| i.color.is_identity()), Some(true), "the playhead's ball is on top"); } // Rendered: the ball on frame 1 (top left of its path) shows over the sky, in Edit Multiple // Frames at full strength. diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs index 58363868..66ecdd88 100644 --- a/crates/engine/src/params.rs +++ b/crates/engine/src/params.rs @@ -2,8 +2,10 @@ //! can show, never panics, and rejects non-finite numbers. use crate::{EngineError, Result}; -use anicraft_doc::{Easing, ProfilePreset, Rgba, WidthPoint, WidthProfile}; -use serde_json::Value; +use anicraft_doc::{CustomEase, Document, EasePoint, Easing, ProfilePreset, Rgba, SampledEase, WidthPoint, WidthProfile}; +use anicraft_geom::Vec2; +use std::sync::Arc; +use serde_json::{Value, json}; fn bad(key: &str, want: &str) -> EngineError { EngineError::Param(format!("param '{key}' must be {want}")) @@ -81,25 +83,17 @@ pub fn opt_u64_list(p: &Value, key: &str) -> Result>> { } } -/// Easing from a preset name (`"Linear"`, `"QuadIn"`…), `{"classic": n}` or `{"bezier": [x1,y1,x2,y2]}`. +/// Easing from a preset name (`"Linear"`, `"QuadIn"`, `"ElasticOut"`…), `{"classic": n}`, +/// `{"bezier": [x1, y1, x2, y2]}` or `{"custom": …}` (a custom ease: `{"points": [{at, in, +/// out, smooth}, ..]}` as `ease.info` gives it, or the flat list `[[x, y], ..]` of 3n + 1 +/// points XFL uses). Saved eases (`{"saved": name}`) need the document: [`opt_easing_in`]. pub fn opt_easing(p: &Value, key: &str) -> Result> { let Some(v) = p.get(key) else { return Ok(None) }; if v.is_null() { return Ok(None); } if let Some(s) = v.as_str() { - let e = match s.to_ascii_lowercase().replace(['-', '_', ' '], "").as_str() { - "linear" | "none" => Easing::Linear, - "quadin" | "easein" => Easing::QuadIn, - "quadout" | "easeout" => Easing::QuadOut, - "quadinout" | "easeinout" => Easing::QuadInOut, - "cubicin" => Easing::CubicIn, - "cubicout" => Easing::CubicOut, - "cubicinout" => Easing::CubicInOut, - "smooth" => Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), - _ => return Err(bad(key, "one of Linear, QuadIn, QuadOut, QuadInOut, CubicIn, CubicOut, CubicInOut, Smooth")), - }; - return Ok(Some(e)); + return Easing::from_name(s).map(Some).ok_or_else(|| bad(key, "a preset name: Linear, Smooth, or a family (Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce, Elastic) with In, Out or InOut, e.g. BackOut")); } if let Some(c) = v.get("classic") { let s = c.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(key, "{\"classic\": -100..100}"))?; @@ -111,7 +105,99 @@ pub fn opt_easing(p: &Value, key: &str) -> Result> { return Ok(Some(Easing::CubicBezier(x1.clamp(0.0, 1.0), y1.clamp(-5.0, 5.0), x2.clamp(0.0, 1.0), y2.clamp(-5.0, 5.0)))); } } - Err(bad(key, "an easing name, {\"classic\": n} or {\"bezier\": [x1, y1, x2, y2]}")) + if let Some(c) = v.get("custom") { + return custom_ease(c).map(|c| Some(Easing::Custom(Arc::new(c)))).ok_or_else(|| bad(key, "{\"custom\": {\"points\": [{\"at\": {\"x\", \"y\"}, \"in\": {..}, \"out\": {..}, \"smooth\"}, ..]}} or {\"custom\": [[x, y], ..]} (3n + 1 points)")); + } + if let Some(t) = v.get("sampled") { + return sampled_ease(t).map(|t| Some(Easing::Sampled(Arc::new(t)))).ok_or_else(|| bad(key, "{\"sampled\": {\"name\", \"plugin\", \"ease\", \"values\": [0, …, 1]}} (as ease.info gives a plug-in's ease)")); + } + Err(bad(key, "an easing name, {\"classic\": n}, {\"bezier\": [x1, y1, x2, y2]}, {\"custom\": …}, {\"saved\": name} or {\"plugin\": id, \"ease\": id}")) +} + +/// Most values read from a sampled ease param before it is thinned to the cap. +const MAX_SAMPLED_PARAM: usize = 65_536; + +fn sampled_ease(v: &Value) -> Option { + let o = v.as_object()?; + let values = o.get("values")?.as_array()?; + if values.len() > MAX_SAMPLED_PARAM { + return None; + } + let values: Option> = values.iter().map(|x| x.as_f64().map(|f| f as f32)).collect(); + let s = |k: &str| o.get(k).and_then(Value::as_str).unwrap_or(""); + Some(SampledEase::new(s("name"), s("plugin"), s("ease"), values?)) +} + +/// Most points read from a custom ease param before it is thinned to the cap. +const MAX_EASE_PARAM: usize = 16_384; + +fn custom_ease(v: &Value) -> Option { + match v { + Value::Array(flat) if flat.len() <= MAX_EASE_PARAM * 3 => { + let pts: Option> = flat.iter().map(|q| match q.as_array().map(Vec::as_slice) { + Some([x, y]) => Some(Vec2::new(x.as_f64()? as f32, y.as_f64()? as f32)), + _ => None, + }).collect(); + CustomEase::from_flat(&pts?) + } + Value::Object(o) => { + let pts = o.get("points")?.as_array()?; + if pts.len() > MAX_EASE_PARAM { + return None; + } + serde_json::from_value::>(Value::Array(pts.clone())).ok().map(CustomEase::new) + } + _ => None, + } +} + +/// [`opt_easing`], `{"saved": name}` for an ease saved in the document (ADR 0081), and +/// `{"plugin": id, "ease": id}` for an installed ease plug-in's (ADR 0088; the tween keeps +/// its sampled curve). +pub fn opt_easing_in(s: &crate::Session, p: &Value, key: &str) -> Result> { + if let Some(name) = p.get(key).and_then(|v| v.get("saved")) { + let name = name.as_str().ok_or_else(|| bad(key, "{\"saved\": name}"))?; + return saved_ease(&s.doc, name).map(Some); + } + if let Some(v) = p.get(key).filter(|v| v.get("plugin").is_some()) { + let (Some(plugin), Some(ease)) = (v.get("plugin").and_then(Value::as_str), v.get("ease").and_then(Value::as_str)) else { + return Err(bad(key, "{\"plugin\": an ease plug-in's id, \"ease\": one of its eases (see ease.list)}")); + }; + return plugin_ease(s, plugin, ease).map(Some); + } + opt_easing(p, key) +} + +/// Ease `ease` (its id, or its name in any case) of the installed ease plug-in `plugin`, as the +/// sampled curve a tween keeps. +pub fn plugin_ease(s: &crate::Session, plugin: &str, ease: &str) -> Result { + let p = s.plugins.get(plugin).filter(|p| p.manifest().kind == anicraft_plugins::Kind::Ease).ok_or_else(|| EngineError::State(format!("no ease plug-in “{plugin}” is installed (see ease.list)")))?; + let want = ease.trim().to_lowercase(); + let c = p.eases().iter().find(|c| c.id == ease || c.name.to_lowercase() == want).ok_or_else(|| { + let ids: Vec<&str> = p.eases().iter().map(|c| c.id.as_str()).collect(); + EngineError::State(format!("{} has no ease '{ease}' (it has {})", p.manifest().name, ids.join(", "))) + })?; + Ok(Easing::Sampled(Arc::new(SampledEase::new(&c.name, p.id(), &c.id, c.values.clone())))) +} + +/// The ease saved as `name` (any case). +pub fn saved_ease(doc: &Document, name: &str) -> Result { + let want = name.trim().to_lowercase(); + doc.eases.iter().find(|e| e.name.to_lowercase() == want).map(|e| e.ease.clone()).ok_or_else(|| { + let names: Vec<&str> = doc.eases.iter().map(|e| e.name.as_str()).take(20).collect(); + EngineError::State(if names.is_empty() { format!("no ease is saved as '{name}' (save one with ease.save)") } else { format!("no ease is saved as '{name}' (saved: {})", names.join(", ")) }) + }) +} + +/// An ease as commands take it back (see [`opt_easing`]): a name for presets, else its values. +pub fn easing_json(e: &Easing) -> Value { + match e { + Easing::Classic(s) => json!({"classic": s}), + Easing::CubicBezier(a, b, c, d) => json!({"bezier": [a, b, c, d]}), + Easing::Custom(c) => json!({"custom": serde_json::to_value(&**c).unwrap_or(Value::Null)}), + Easing::Sampled(t) => json!({"sampled": serde_json::to_value(&**t).unwrap_or(Value::Null)}), + named => named.name().map_or(Value::Null, Value::from), + } } /// A width profile (ADR 0018): a preset name (`"uniform"`, `"taper_both"`, `"taper_start"`, diff --git a/crates/engine/src/parity_tests.rs b/crates/engine/src/parity_tests.rs new file mode 100644 index 00000000..8d869360 --- /dev/null +++ b/crates/engine/src/parity_tests.rs @@ -0,0 +1,549 @@ +//! Drawing parity leftovers (ADR 0080): PolyStar options, Paint Selection and Paint Inside, +//! drawing objects edited in place, Envelope. + +use crate::Session; +use crate::cmds_erase::measure_els; +use anicraft_doc::{ElementKind, Paint, Rgba, Shape}; +use anicraft_geom::{Affine, Vec2}; +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(object: bool) -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": object})); + s +} + +/// The keyframe's shapes, bottom to top, with their transforms. +fn shapes(s: &Session) -> Vec<(Shape, Affine)> { + s.visible_elements() + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some((sh.clone(), e.transform)), + _ => None, + }) + .collect() +} + +/// Total fill area on the active layer, raw shapes and drawing objects (even-odd loops summed +/// by sign; exact for polygons, within the flattening for curves). +fn fill_area(s: &Session) -> f64 { + let raw = measure_els(&s.visible_elements()).0; + let objects: f64 = shapes(s).iter().filter(|(sh, _)| sh.fill.is_some() && !sh.merge).map(|(sh, m)| area_of(&sh.path, m)).sum(); + raw + objects +} + +fn area_of(path: &anicraft_geom::Path, m: &Affine) -> f64 { + path.flatten(m, 0.005) + .iter() + .map(|pl| { + let n = pl.points.len(); + (0..n).map(|i| { + let (a, b) = (pl.points[i], pl.points[(i + 1) % n]); + f64::from(a.x) * f64::from(b.y) - f64::from(b.x) * f64::from(a.y) + }).sum::() * 0.5 + }) + .sum::() + .abs() +} + +/// What colour covers stage point `p` (the topmost shape containing it). +fn top_at(s: &Session, p: Vec2) -> Option { + shapes(s).iter().rev().find(|(sh, m)| sh.fill.is_some() && sh.path.contains(p, m, sh.fill_rule)).and_then(|(sh, _)| match sh.fill { + Some(Paint::Solid(c)) => Some(c), + _ => None, + }) +} + +// ----- PolyStar ---------------------------------------------------------------------------------- + +/// A polygon of n sides has area n/2 · r² · sin(2π/n); a star at point size 1 covers the same. +#[test] +fn polystar_polygon_and_star_areas() { + for object in [false, true] { + for n in [3u32, 6, 32] { + let mut s = blank(object); + run(&mut s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "shape": "polygon", "sides": n, "stroke": null, "fill": "#336699"})); + let want = f64::from(n) / 2.0 * 2500.0 * (std::f64::consts::TAU / f64::from(n)).sin(); + assert!((fill_area(&s) - want).abs() < want * 1e-4, "polygon {n} object {object}: {} vs {want}", fill_area(&s)); + let mut t = blank(object); + let v = run(&mut t, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "sides": n, "point_size": 1.0, "stroke": null, "fill": "#336699"})); + assert_eq!(v["kind"], "star"); + assert!((fill_area(&t) - want).abs() < want * 1e-4, "star {n} at size 1"); + } + } +} + +/// A star's area is n · r · r_in · sin(π/n), r_in = r · size · cos(π/n); the old `inner` and +/// `points` params still work. +#[test] +fn polystar_star_follows_point_size() { + let mut s = blank(true); + run(&mut s, "draw.star", json!({"cx": 0, "cy": 0, "outer": 40, "sides": 5, "point_size": 0.3, "stroke": null, "fill": "#ff0000"})); + let half = std::f64::consts::PI / 5.0; + let inner = 40.0 * 0.3 * half.cos(); + let want = 5.0 * 40.0 * inner * half.sin(); + assert!((fill_area(&s) - want).abs() < want * 1e-4); + let mut t = blank(true); + run(&mut t, "draw.star", json!({"cx": 0, "cy": 0, "outer": 40, "inner": 10, "points": 6, "stroke": null, "fill": "#ff0000"})); + let want = 6.0 * 40.0 * 10.0 * (std::f64::consts::PI / 6.0).sin(); + assert!((fill_area(&t) - want).abs() < want * 1e-4); +} + +#[test] +fn polystar_refuses_bad_options() { + let mut s = blank(false); + for p in [ + json!({"cx": 0, "cy": 0, "outer": 40, "shape": "hexagon"}), + json!({"cx": 0, "cy": 0, "outer": 40, "sides": 2}), + json!({"cx": 0, "cy": 0, "outer": 40, "sides": 65}), + json!({"cx": 0, "cy": 0, "outer": 40, "point_size": 1.5}), + json!({"cx": 0, "cy": 0, "outer": 40, "point_size": -0.1}), + ] { + assert!(s.execute("draw.star", &p).is_err(), "{p}"); + } + assert!(s.visible_elements().is_empty()); +} + +/// Merge drawing: a polygon drawn over a raw fill of another colour cuts into it, as the other +/// shape tools do (ADR 0031). +#[test] +fn polystar_merges_like_the_other_shape_tools() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 200, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "shape": "polygon", "sides": 4, "stroke": null, "fill": "#ff0000"})); + // The square's area stays: the polygon replaced what it covers. + assert!((fill_area(&s) - 40_000.0).abs() < 1.0, "{}", fill_area(&s)); + assert_eq!(top_at(&s, Vec2::new(100.0, 100.0)), Some(Rgba::hex(0xff0000))); + assert_eq!(top_at(&s, Vec2::new(5.0, 5.0)), Some(Rgba::hex(0x0000ff))); + assert!(shapes(&s).iter().all(|(sh, _)| sh.merge)); +} + +// ----- Paint Selection and Paint Inside ---------------------------------------------------------- + +/// Fill area of one colour on the active layer. +fn area_in(s: &Session, color: u32) -> f64 { + shapes(s).iter().filter(|(sh, _)| matches!(sh.fill, Some(Paint::Solid(c)) if c == Rgba::hex(color))).map(|(sh, m)| area_of(&sh.path, m)).sum() +} + +/// A blue square at 0..100 and a green one at 200..300 (raw fills, no lines). +fn two_squares() -> Session { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.rect", json!({"x": 200, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#00ff00"})); + run(&mut s, "edit.deselect", json!({})); + s +} + +fn brush(s: &mut Session, mode: &str, from: [f32; 2], to: [f32; 2]) -> Value { + let pts: Vec<[f32; 2]> = (0..=40).map(|i| { + let t = i as f32 / 40.0; + [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t] + }).collect(); + run(s, "draw.brush", json!({"points": pts, "size": 20, "smoothing": 0, "mode": mode, "color": "#ff0000"})) +} + +fn blue_id(s: &Session) -> u64 { + s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill == Some(Paint::Solid(Rgba::hex(0x0000ff))))).map(|e| e.id.0).expect("the blue square") +} + +/// Paint Selection: a stroke across both squares paints only the selected one, exactly over +/// the 100 × 20 band inside it. +#[test] +fn paint_selection_clips_to_the_selected_fills() { + let mut s = two_squares(); + let blue = blue_id(&s); + run(&mut s, "element.select", json!({"ids": [blue]})); + let v = brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert_eq!(v["merged"], true, "{v}"); + let red = area_in(&s, 0xff0000); + assert!((red - 2000.0).abs() < 2.0, "the band inside the blue square: {red}"); + assert!((area_in(&s, 0x0000ff) - 8000.0).abs() < 2.0, "the rest of the blue square: {}", area_in(&s, 0x0000ff)); + assert!((area_in(&s, 0x00ff00) - 10_000.0).abs() < 0.5, "the green square is not selected"); + assert_eq!(top_at(&s, Vec2::new(250.0, 50.0)), Some(Rgba::hex(0x00ff00))); + assert_eq!(top_at(&s, Vec2::new(150.0, 50.0)), None, "nothing between them"); + assert_eq!(top_at(&s, Vec2::new(50.0, 50.0)), Some(Rgba::hex(0xff0000))); + // The selection stays on the blue square's pieces and the paint, for the next stroke. + let sel = s.selection.on(s.layer); + let els = s.visible_elements(); + assert!(sel.len() >= 2, "{sel:?}"); + for id in &sel { + let e = els.iter().find(|e| e.id == *id).expect("selected element"); + let ElementKind::Shape(sh) = &e.kind else { panic!("a shape") }; + let b = sh.path.bounds().transformed(&e.transform); + assert!(b.min.x > -0.5 && b.max.x < 100.5, "inside the blue square: {b:?}"); + } + let v = brush(&mut s, "selection", [-60.0, 20.0], [360.0, 20.0]); + assert!(v["elements"].as_array().is_some_and(|a| !a.is_empty()), "a second stroke paints too"); + assert!((area_in(&s, 0xff0000) - 4000.0).abs() < 4.0, "{}", area_in(&s, 0xff0000)); +} + +/// With nothing selected (or a stroke that misses the selection), nothing changes and there is +/// no undo step. +#[test] +fn paint_selection_without_a_selection_changes_nothing() { + let mut s = two_squares(); + let steps = s.history_len(); + let doc = s.doc.clone(); + let v = brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert_eq!(v["painted"], false); + assert_eq!(s.history_len(), steps); + assert!(s.doc == doc); + let blue = blue_id(&s); + run(&mut s, "element.select", json!({"ids": [blue]})); + let v = brush(&mut s, "selection", [150.0, 300.0], [160.0, 400.0]); + assert_eq!(v["painted"], false, "{v}"); + assert_eq!(s.history_len(), steps); +} + +/// Paint Inside: started in the blue square, the stroke stays inside it (a half-round start +/// cap and a 50 × 20 band) and never reaches the green one. +#[test] +fn paint_inside_clips_to_the_fill_it_starts_on() { + let mut s = two_squares(); + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + let red = area_in(&s, 0xff0000); + assert!((red - want).abs() < want * 0.01, "{red} vs {want}"); + assert!((area_in(&s, 0x00ff00) - 10_000.0).abs() < 0.5); + assert!((area_in(&s, 0x0000ff) + red - 10_000.0).abs() < 2.0, "the paint replaced its part of the blue square"); +} + +/// Paint Inside started on empty stage inside a closed outline paints only that empty area, +/// under the line; started on open stage, only empty areas (as Paint Behind). +#[test] +fn paint_inside_empty_areas() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000", "stroke_width": 2})); + let lines = measure_els(&s.visible_elements()).1; + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + let red = area_in(&s, 0xff0000); + assert!((red - want).abs() < want * 0.01, "{red} vs {want}"); + assert_eq!(top_at(&s, Vec2::new(200.0, 50.0)), None, "nothing outside the outline"); + assert!((measure_els(&s.visible_elements()).1 - lines).abs() < 0.5, "the outline is whole"); + + let mut t = two_squares(); + brush(&mut t, "inside", [-100.0, 50.0], [50.0, 50.0]); + assert!((area_in(&t, 0x0000ff) - 10_000.0).abs() < 0.5, "the blue square is untouched"); + assert!(area_in(&t, 0xff0000) > 1000.0, "the empty stage took the paint"); +} + +/// A line across the selected fill stays: clipped paint goes under lines. +#[test] +fn paint_selection_leaves_lines() { + let mut s = two_squares(); + run(&mut s, "draw.line", json!({"x0": 50, "y0": -20, "x1": 50, "y1": 120, "stroke": "#000000", "stroke_width": 2})); + let lines = measure_els(&s.visible_elements()).1; + run(&mut s, "edit.select_all", json!({})); + brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert!((measure_els(&s.visible_elements()).1 - lines).abs() < 0.5, "the line is whole"); + // Both squares were selected: the band in each. + assert!((area_in(&s, 0xff0000) - 4000.0).abs() < 4.0, "{}", area_in(&s, 0xff0000)); +} + +/// As drawing objects, the clipped paint is an object of exactly the clipped outline. +#[test] +fn paint_inside_as_a_drawing_object() { + let mut s = blank(true); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + assert!((area_in(&s, 0xff0000) - want).abs() < want * 0.01); + assert!((area_in(&s, 0x0000ff) - 10_000.0).abs() < 0.5, "objects don't cut each other"); +} + +// ----- drawing objects edited in place ----------------------------------------------------------- + +/// A drawing object (an orange rectangle at 100..300 × 100..200) beside a raw blue square on the +/// same layer; returns the object's id. +fn object_and_raw() -> (Session, u64) { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 400, "y": 100, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + let v = run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "stroke": null, "fill": "#ff8800", "object": true})); + let id = v["element"].as_u64().expect("the object"); + run(&mut s, "edit.deselect", json!({})); + (s, id) +} + +/// Double-clicking a drawing object opens it in place; opening and closing it without an edit +/// changes nothing: the same document and state, no undo step, the object selected. +#[test] +fn drawing_object_opens_and_closes_unchanged() { + let (mut s, id) = object_and_raw(); + let (doc, state, steps) = (s.doc.clone(), s.state, s.history_len()); + let v = run(&mut s, "symbol.edit", json!({"id": id})); + assert_eq!(v["editing"][0]["drawing"], id, "{v}"); + assert!(s.editing_drawing() && s.editing_group()); + // Inside, its one raw shape, where it showed. + let inside = s.visible_elements(); + assert_eq!(inside.len(), 1); + assert!(matches!(&inside[0].kind, ElementKind::Shape(sh) if sh.merge)); + run(&mut s, "symbol.exit", json!({})); + assert!(s.doc == doc, "the document is as it was"); + assert_eq!(s.state, state, "no unsaved change"); + assert_eq!(s.history_len(), steps); + assert_eq!(s.selection.id_list(), vec![id]); + assert!(s.visible_elements().iter().any(|e| e.id.0 == id && matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge))); +} + +/// Inside, a line drawn across merges only with the object's own shape: it splits the fill, the +/// raw square outside is untouched, and closing it leaves a group of the pieces (several +/// shapes stay one object, as Combine Objects' Union makes them). +#[test] +fn drawing_object_merges_only_inside() { + let (mut s, id) = object_and_raw(); + run(&mut s, "symbol.edit", json!({"id": id})); + // Positions inside are in the object's own space (its centre at the origin). + run(&mut s, "draw.line", json!({"x0": 0, "y0": -100, "x1": 0, "y1": 100, "stroke": "#000000", "stroke_width": 2, "object": false})); + let inside = s.visible_elements(); + let fills = inside.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(); + assert_eq!(fills, 2, "the line cut the fill in two"); + run(&mut s, "symbol.exit", json!({})); + let els = s.visible_elements(); + let obj = els.iter().find(|e| e.id.0 == id).expect("the object stays, with its id"); + assert!(matches!(obj.kind, ElementKind::Group { .. }), "several pieces: a group"); + assert!((area_in(&s, 0x0000ff) - 10_000.0).abs() < 0.5, "the raw square outside is whole"); + assert_eq!(els.len(), 2); +} + +/// An edit that leaves one shape makes it one drawing object again, moved as edited; undo goes +/// back inside, and closing then gives the object as it was. +#[test] +fn drawing_object_edit_keeps_one_object() { + let (mut s, id) = object_and_raw(); + let before = s.element_bounds(anicraft_doc::ElementId(id)); + run(&mut s, "symbol.edit", json!({"id": id})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 30, "dy": 10})); + run(&mut s, "symbol.exit", json!({})); + let els = s.visible_elements(); + let obj = els.iter().find(|e| e.id.0 == id).expect("the object"); + assert!(matches!(&obj.kind, ElementKind::Shape(sh) if !sh.merge), "one drawing object again"); + let after = s.element_bounds(anicraft_doc::ElementId(id)); + assert!((after.min.x - before.min.x - 30.0).abs() < 1e-3 && (after.min.y - before.min.y - 10.0).abs() < 1e-3, "{before:?} → {after:?}"); + // Undo: inside again, before the move. + run(&mut s, "edit.undo", json!({})); + assert!(s.editing_drawing()); + run(&mut s, "symbol.exit", json!({})); + assert!((s.element_bounds(anicraft_doc::ElementId(id)).min.x - before.min.x).abs() < 1e-3); +} + +/// Everything inside deleted: closing it removes the object. +#[test] +fn an_emptied_drawing_object_is_gone() { + let (mut s, id) = object_and_raw(); + run(&mut s, "symbol.edit", json!({"id": id})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "edit.delete", json!({})); + run(&mut s, "symbol.exit", json!({})); + assert!(s.visible_elements().iter().all(|e| e.id.0 != id)); + assert!(s.selection.is_empty()); + assert_eq!(s.visible_elements().len(), 1, "the raw square stays"); +} + +/// Raw shapes don't open (they are the drawing itself); the timeline stays one frame inside. +#[test] +fn only_drawing_objects_open() { + let (mut s, _) = object_and_raw(); + let raw = s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).map(|e| e.id.0).expect("raw"); + assert!(s.execute("symbol.edit", &json!({"id": raw})).is_err()); + let id = s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge)).map(|e| e.id.0).expect("object"); + run(&mut s, "symbol.edit", json!({"id": id})); + assert!(s.execute("timeline.insert_keyframe", &json!({})).is_err(), "one frame inside"); +} + +// ----- Envelope ---------------------------------------------------------------------------------- + +fn points_of(v: &Value) -> Vec<[f32; 2]> { + v["points"].as_array().expect("points").iter().map(|p| [p[0].as_f64().unwrap_or(0.0) as f32, p[1].as_f64().unwrap_or(0.0) as f32]).collect() +} + +/// A 100 × 50 orange drawing object at (10, 20), selected, with an envelope open on it. +fn enveloped() -> (Session, Value) { + let mut s = blank(true); + run(&mut s, "draw.rect", json!({"x": 10, "y": 20, "w": 100, "h": 50, "stroke": null, "fill": "#ff8800"})); + let v = run(&mut s, "modify.envelope", json!({})); + (s, v) +} + +/// At rest the envelope is the identity: its mesh is evenly over the bounds, and moving it to +/// the rest mesh changes nothing. +#[test] +fn envelope_identity_at_rest() { + let (mut s, v) = enveloped(); + assert_eq!(v["bounds"], json!([10.0, 20.0, 100.0, 50.0])); + let pts = points_of(&v); + assert_eq!(pts.len(), 16); + assert_eq!(pts[0], [10.0, 20.0]); + assert_eq!(pts[15], [110.0, 70.0]); + let before = shapes(&s); + run(&mut s, "modify.envelope_move", json!({"points": v["points"]})); + let after = shapes(&s); + assert_eq!(before.len(), after.len()); + let flat = |sh: &Shape, m: &Affine| sh.path.flatten(m, 0.01).into_iter().flat_map(|p| p.points).collect::>(); + for ((a, ma), (b, mb)) in before.iter().zip(&after) { + let (pa, pb) = (flat(a, ma), flat(b, mb)); + assert_eq!(pa.len(), pb.len()); + assert!(pa.iter().zip(&pb).all(|(x, y)| x.distance(*y) < 1e-3)); + } + assert!((fill_area(&s) - 5000.0).abs() < 0.01); +} + +/// Lifting the top side's two handles by 30 bends the top edge up: the area grows by +/// lift · width / 2 (∫ B₁ + B₂ = ½), and each move is one undo step. +#[test] +fn envelope_bends_by_the_mesh() { + let (mut s, v) = enveloped(); + let steps = s.history_len(); + let pts = points_of(&v); + run(&mut s, "modify.envelope_move", json!({"index": 1, "x": pts[1][0], "y": pts[1][1] - 30.0})); + let v = run(&mut s, "modify.envelope_move", json!({"index": 2, "x": pts[2][0], "y": pts[2][1] - 30.0})); + assert_eq!(s.history_len(), steps + 2, "one step per move"); + let want = 5000.0 + 30.0 * 100.0 / 2.0; + assert!((fill_area(&s) - want).abs() < want * 1e-3, "{} vs {want}", fill_area(&s)); + // The inner points followed the side (Coons). + let now = points_of(&v); + assert!(now[5][1] < pts[5][1] - 1.0 && now[6][1] < pts[6][1] - 1.0); + // Undo: the mesh that made the shapes on the stage. + run(&mut s, "edit.undo", json!({})); + let (_, _, mesh) = s.envelope().expect("still open"); + assert!((mesh[2].y - pts[2][1]).abs() < 1e-4 && (mesh[1].y - (pts[1][1] - 30.0)).abs() < 1e-4); + run(&mut s, "edit.undo", json!({})); + let (_, rest, mesh) = s.envelope().expect("still open"); + assert_eq!(mesh, anicraft_geom::envelope::rest_mesh(&rest)); + assert!((fill_area(&s) - 5000.0).abs() < 0.01); +} + +/// Moves bend the shapes as they were when the envelope opened, so a move and its reverse +/// leave them exactly as they were. +#[test] +fn envelope_moves_do_not_compound() { + let (mut s, v) = enveloped(); + let pts = points_of(&v); + let before = shapes(&s); + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": 160, "y": 120})); + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": pts[15][0], "y": pts[15][1]})); + let after = shapes(&s); + assert!((fill_area(&s) - 5000.0).abs() < 0.01); + assert_eq!(before[0].0.path.cmds.len(), after[0].0.path.cmds.len()); +} + +/// Symbols, text and groups can't be bent; nothing open is an error for a move. +#[test] +fn envelope_refuses_what_it_cannot_bend() { + let mut s = blank(true); + assert!(s.execute("modify.envelope", &json!({})).is_err(), "nothing selected"); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 50, "h": 50, "fill": "#ff0000"})); + run(&mut s, "modify.convert_to_symbol", json!({})); + assert!(s.execute("modify.envelope", &json!({})).is_err(), "a symbol instance"); + assert!(s.execute("modify.envelope_move", &json!({"index": 0, "x": 1, "y": 1})).is_err()); + let (mut t, _) = enveloped(); + for p in [json!({"index": 16, "x": 0, "y": 0}), json!({"points": [[0, 0]]}), json!({"index": 0, "x": 1e9, "y": 0}), json!({})] { + assert!(t.execute("modify.envelope_move", &p).is_err(), "{p}"); + } + // A new selection ends it. + run(&mut t, "edit.deselect", json!({})); + assert!(t.envelope().is_none()); +} + +/// Raw shapes bent by an envelope merge with the drawing they land on when it closes. +#[test] +fn envelope_close_merges_raw_shapes() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.rect", json!({"x": 200, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#ff0000"})); + // The red square is selected (the last drawn): bend its left side over the blue one. + let v = run(&mut s, "modify.envelope", json!({})); + let pts = points_of(&v); + let mut m = pts.clone(); + for i in [0usize, 4, 8, 12] { + m[i][0] -= 150.0; + } + run(&mut s, "modify.envelope_move", json!({"points": m})); + run(&mut s, "modify.envelope_close", json!({})); + assert!(s.envelope().is_none()); + // The red covers 50 of the blue square's width now. + assert!((area_in(&s, 0x0000ff) - 5000.0).abs() < 5.0, "{}", area_in(&s, 0x0000ff)); + assert!((area_in(&s, 0xff0000) - 25_000.0).abs() < 25.0, "{}", area_in(&s, 0xff0000)); +} + +/// A drag's moves are one undo step and remember only the last mesh; undo goes back to before +/// the drag with the envelope still open. +#[test] +fn envelope_drag_is_one_step() { + let (mut s, v) = enveloped(); + let pts = points_of(&v); + let steps = s.history_len(); + s.begin_gesture("Envelope"); + for k in 1..=300 { + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": pts[15][0] + k as f32 * 0.1, "y": pts[15][1]})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + assert!(s.envelope.as_ref().is_some_and(|e| e.states_len() == 2)); + run(&mut s, "edit.undo", json!({})); + let (_, rest, mesh) = s.envelope().expect("open"); + assert_eq!(mesh, anicraft_geom::envelope::rest_mesh(&rest)); + run(&mut s, "edit.redo", json!({})); + let (_, _, mesh) = s.envelope().expect("open"); + assert!((mesh[15].x - (pts[15][0] + 30.0)).abs() < 1e-3); +} + +/// Timings for ADR 0080 (`cargo test --release -p anicraft-engine parity_timings -- --ignored --nocapture`). +#[test] +#[ignore = "a measurement"] +fn parity_timings() { + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let wave: Vec<[f32; 2]> = (0..=400).map(|i| [20.0 + i as f32 * 2.5, 300.0 + (i as f32 * 0.05).sin() * 120.0]).collect(); + for mode in ["normal", "inside", "selection"] { + let mut times = Vec::new(); + for _ in 0..9 { + let mut s = blank(false); + run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 800, "h": 400, "fill": "#3d8bfd", "stroke": "#000000", "stroke_width": 2})); + run(&mut s, "edit.deselect", json!({})); + if mode == "selection" { + run(&mut s, "edit.select_all", json!({})); + } + let t = std::time::Instant::now(); + run(&mut s, "draw.brush", json!({"points": wave, "size": 30, "mode": mode, "color": "#ff0000"})); + times.push(t.elapsed().as_secs_f64() * 1e3); + } + eprintln!("brush 1000 px wave, size 30, {mode}: {:.2} ms", median(times)); + } + let mut times = Vec::new(); + for _ in 0..9 { + let mut s = blank(true); + run(&mut s, "draw.star", json!({"cx": 400, "cy": 300, "outer": 250, "sides": 32, "point_size": 0.5, "fill": "#ff0000"})); + run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 600, "h": 400, "fill": "#00ff00"})); + run(&mut s, "edit.select_all", json!({})); + let v = run(&mut s, "modify.envelope", json!({})); + let pts = points_of(&v); + let t = std::time::Instant::now(); + for k in 0..10 { + run(&mut s, "modify.envelope_move", json!({"index": 1, "x": pts[1][0], "y": pts[1][1] - 10.0 * k as f32})); + } + times.push(t.elapsed().as_secs_f64() * 1e3 / 10.0); + } + eprintln!("envelope move, a 32-point star and an oval: {:.2} ms", median(times)); +} + +/// Warped artwork (ADR 0079) neither opens in place nor takes an envelope: its warp keeps the +/// outline as drawn on every keyframe. +#[test] +fn warped_objects_refuse_envelope_and_editing() { + let mut s = blank(true); + let v = run(&mut s, "draw.rect", json!({"x": 10, "y": 20, "w": 100, "h": 50, "stroke": null, "fill": "#ff8800"})); + let id = v["element"].as_u64().expect("the object"); + run(&mut s, "warp.add", json!({"element": id})); + run(&mut s, "element.select", json!({"ids": [id]})); + assert!(s.execute("modify.envelope", &json!({})).is_err()); + assert!(s.execute("symbol.edit", &json!({"id": id})).is_err()); + assert!(s.editing.is_empty()); +} diff --git a/crates/engine/src/path_text_tests.rs b/crates/engine/src/path_text_tests.rs new file mode 100644 index 00000000..ff4f6f0e --- /dev/null +++ b/crates/engine/src/path_text_tests.rs @@ -0,0 +1,164 @@ +//! Text on a path (ADR 0070): attaching text to a shape's outline, by selection or by picking, +//! moving it along, flipping and releasing it, edits keeping it on the path, undo, the file. + +use crate::Session; +use anicraft_doc::{ElementId, ElementKind, TextBlock}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn fonts() -> bool { + let ok = !anicraft_text::Fonts::get().families().is_empty(); + if !ok { + eprintln!("no fonts on this computer: text on a path tests skipped"); + } + ok +} + +fn text_of(s: &Session, id: ElementId) -> (anicraft_geom::Affine, Arc) { + let e = s.visible_elements().into_iter().find(|e| e.id == id).unwrap(); + match &e.kind { + ElementKind::Text(t) => (e.transform, t.clone()), + other => panic!("not text: {other:?}"), + } +} + +/// A session with "Along the line" and a 400 px line from (100, 300) to (500, 300). +fn text_and_line() -> (Session, ElementId, ElementId) { + let mut s = Session::default(); + let text = ElementId(run(&mut s, "text.create", json!({"text": "Along the line", "x": 50, "y": 50, "size": 24}))["element"].as_u64().unwrap()); + let line = ElementId(run(&mut s, "draw.line", json!({"x0": 100, "y0": 300, "x1": 500, "y1": 300}))["element"].as_u64().unwrap()); + (s, text, line) +} + +#[test] +fn text_attaches_to_a_selected_shape_and_sits_on_it() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0, line.0]})); + let steps = s.history().undo_len(); + let v = run(&mut s, "text.attach_path", json!({})); + assert_eq!(s.history().undo_len(), steps + 1, "one undo step"); + assert!((v["length"].as_f64().unwrap() - 400.0).abs() < 0.5, "{v}"); + assert_eq!(v["offset"], 0.0, "left-aligned text starts at the path's start"); + let (xf, t) = text_of(&s, text); + let on = t.on_path.as_ref().expect("on a path"); + // In stage space the glyphs stand on the line, starting at its start. + let b = t.outline.bounds().transformed(&xf); + assert!(b.max.y <= 300.0 + 8.0 && b.max.y > 295.0 && b.min.y < 290.0, "standing on y 300 (descenders a little below): {b:?}"); + assert!((b.min.x - 100.0).abs() < 4.0, "{b:?}"); + let path = on.path.transformed(&xf).bounds(); + assert!((path.min.x - 100.0).abs() < 1e-3 && (path.max.x - 500.0).abs() < 1e-3); + // The box holds the path and the glyphs from the origin. + let local = t.outline.bounds().union(&on.path.bounds()); + assert!(local.min.x.abs() < 1e-3 && local.min.y.abs() < 1e-3 && (local.width() - t.box_width).abs() < 1e-3 && (local.height() - t.box_height).abs() < 1e-3, "{local:?}"); + // The shape is left as it is, and only the text is selected. + assert!(s.visible_elements().iter().any(|e| e.id == line)); + assert_eq!(s.selection.on(s.layer), vec![text]); + // Undo puts the text back in its lines. + s.undo().unwrap(); + assert!(text_of(&s, text).1.on_path.is_none()); +} + +#[test] +fn offset_flip_alignment_and_edits_keep_text_on_its_path() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0]})); + // Picking the shape at a stage point (the stage's pick mode does this). + run(&mut s, "text.attach_path", json!({"x": 300, "y": 300})); + let left = |s: &Session| { + let (xf, t) = text_of(s, text); + t.outline.bounds().transformed(&xf) + }; + let at0 = left(&s); + run(&mut s, "text.path", json!({"offset": 100})); + let at100 = left(&s); + assert!((at100.min.x - at0.min.x - 100.0).abs() < 0.5, "{at0:?} → {at100:?}"); + // Flipped: from the other end, below the line. + run(&mut s, "text.path", json!({"flip": true})); + let f = left(&s); + assert!(f.min.y > 290.0 && f.max.y > 310.0 && (f.max.x - 400.0).abs() < 1.0, "{f:?}"); + run(&mut s, "text.path", json!({"flip": false, "offset": 200})); + // Centred text is centred on its offset. + run(&mut s, "text.edit", json!({"align": "center"})); + let c = left(&s); + assert!((c.center().x - 300.0).abs() < 3.0, "centred on x 300: {c:?}"); + // Editing the words or the size keeps it on the path, where it was. + run(&mut s, "text.edit", json!({"text": "Hi", "size": 40})); + let (xf, t) = text_of(&s, text); + assert_eq!(t.text, "Hi"); + assert!(t.on_path.is_some()); + assert!((t.on_path.as_ref().unwrap().path.transformed(&xf).bounds().min.x - 100.0).abs() < 1e-3, "the path doesn't move"); + assert!((left(&s).center().x - 300.0).abs() < 3.0); + // Text on a path is static text. + assert!(s.execute("text.field", &json!({"type": "dynamic"})).is_err()); + // Released: back to a line of text where it started. + let before = left(&s); + run(&mut s, "text.release_path", json!({})); + let (_, t) = text_of(&s, text); + assert!(t.on_path.is_none()); + let after = left(&s); + assert!((after.min.x - before.min.x).abs() < 6.0 && (after.min.y - before.min.y).abs() < 12.0, "{before:?} → {after:?}"); + assert!(s.execute("text.path", &json!({"offset": 5})).is_err(), "no text on a path selected"); + let _ = line; +} + +#[test] +fn bad_requests_change_nothing() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + // No shape anywhere selected or there. + run(&mut s, "element.select", json!({"ids": [text.0]})); + assert!(s.execute("text.attach_path", &json!({})).is_err()); + assert!(s.execute("text.attach_path", &json!({"x": 5, "y": 5})).is_err()); + assert!(s.execute("text.attach_path", &json!({"x": 5})).is_err()); + assert!(s.execute("text.attach_path", &json!({"path": line.0, "offset": 1e9})).is_err()); + // Only the shape selected: no text. + run(&mut s, "element.select", json!({"ids": [line.0]})); + assert!(s.execute("text.attach_path", &json!({})).is_err()); + assert!(text_of(&s, text).1.on_path.is_none()); + // By id works from another layer too. + run(&mut s, "layer.new", json!({})); + let other = ElementId(run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 200, "h": 200}))["element"].as_u64().unwrap()); + let base = s.timeline().layers.last().unwrap().id; + run(&mut s, "layer.select", json!({"layer": base.0})); + run(&mut s, "element.select", json!({"ids": [text.0]})); + run(&mut s, "text.attach_path", json!({"path": other.0})); + assert!(text_of(&s, text).1.on_path.is_some()); +} + +#[test] +fn text_on_a_path_is_saved_and_older_files_open_without_it() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0, line.0]})); + run(&mut s, "text.attach_path", json!({"offset": 12.5, "flip": true})); + let (_, t) = text_of(&s, text); + let json = serde_json::to_string(&*t).unwrap(); + assert!(json.contains("\"on_path\"") && json.contains("\"offset\":12.5") && json.contains("\"flip\":true"), "{json}"); + let back: TextBlock = serde_json::from_str(&json).unwrap(); + assert_eq!(back, *t); + // The whole document round-trips through the file format. + let saved = crate::format::to_json(&s.doc).unwrap(); + let doc = crate::format::from_json(&saved).unwrap(); + assert_eq!(doc, s.doc); + // A block saved before text on a path opens as plain text. + let mut v: Value = serde_json::from_str(&json).unwrap(); + v.as_object_mut().unwrap().remove("on_path"); + assert!(serde_json::from_value::(v).unwrap().on_path.is_none()); + // It renders from its outlines alone: the same pixels without the font. + let a = anicraft_render::render_frame(&s.doc, 0, 0.5).unwrap(); + assert!(a.data.iter().any(|p| p[0] < 0.5), "the text draws"); +} diff --git a/crates/engine/src/place_tests.rs b/crates/engine/src/place_tests.rs new file mode 100644 index 00000000..6f4f9c05 --- /dev/null +++ b/crates/engine/src/place_tests.rs @@ -0,0 +1,219 @@ +//! Placing Library items (a drop on the stage, Place on Stage), Swap Bitmap and Convert to Symbol +//! into a folder (ADR 0053). + +use crate::Session; +use anicraft_doc::{BitmapId, Element, ElementKind, FolderId, LibraryEntry, LibraryItem, Paint, SymbolId, SymbolKind, sample}; +use anicraft_geom::{Affine, Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +fn sym(s: &Session, name: &str) -> u64 { + s.doc.library.iter().find(|x| x.name == name).map(|x| x.id.0).unwrap_or_else(|| panic!("no symbol {name}")) +} + +/// A `w`×`h` bitmap of one colour, added to the Library. +fn add_bitmap(s: &mut Session, name: &str, w: u32, h: u32) -> BitmapId { + let id = BitmapId(s.doc.alloc_id()); + let bytes = anicraft_render::encode_png(w, h, &[255, 0, 0, 255].repeat((w * h) as usize)).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(id, name, bytes).unwrap())); + id +} + +fn add_sound(s: &mut Session, name: &str) -> u64 { + let id = anicraft_doc::SoundId(s.doc.alloc_id()); + let wav = crate::cmds_sound::test_wav(8000, &[0.25; 8000]); + s.doc.sounds.push(Arc::new(anicraft_doc::Sound::from_data(id, name, wav).unwrap())); + id.0 +} + +/// Element `id` on the timeline being edited. +fn element(s: &Session, id: u64) -> Element { + s.timeline().layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find(|e| e.id.0 == id).map(|e| (**e).clone()).unwrap_or_else(|| panic!("no element {id}")) +} + +fn shape(e: &Element) -> &anicraft_doc::Shape { + match &e.kind { + ElementKind::Shape(sh) => sh, + k => panic!("not a shape: {k:?}"), + } +} + +#[test] +fn a_drop_places_symbols_bitmaps_and_a_sound_in_one_undo_step() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let bitmap = add_bitmap(&mut s, "red.png", 4, 2); + let sound = add_sound(&mut s, "beep.wav"); + run(&mut s, "timeline.goto", json!({"frame": 3})); + let layer = s.layer; + let before = s.doc.clone(); + let steps = s.history.undo_len(); + let v = run(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"symbol": star}, {"bitmap": bitmap.0}, {"sound": sound}], "x": 200, "y": 120})); + assert_eq!(s.history.undo_len(), steps + 1, "one undo step"); + let ids: Vec = v["elements"].as_array().unwrap().iter().map(|x| x.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 3); + assert_eq!(v["element"], ids[0]); + assert_eq!(s.selection.ids().map(|e| e.0).collect::>(), ids, "what was placed is selected"); + // Symbols stand with their registration point on the drop point; a bitmap is centred on it. + for &id in &ids[..2] { + assert_eq!(element(&s, id).transform.apply(Vec2::ZERO), Vec2::new(200.0, 120.0)); + } + assert_eq!(element(&s, ids[2]).transform.apply(Vec2::new(2.0, 1.0)), Vec2::new(200.0, 120.0)); + // All on the active layer's keyframe at the playhead, the sound too. + assert_eq!(s.layer, layer); + let k = s.active_layer().unwrap().keyframe_at(3).unwrap(); + assert!(ids.iter().all(|id| k.elements.iter().any(|e| e.id.0 == *id))); + assert_eq!(k.sound.as_ref().map(|f| f.sound.0), Some(sound)); + assert_eq!(v["sound"]["sound"], sound); + s.undo().unwrap(); + assert_eq!(s.doc, before, "one undo takes the whole drop back"); +} + +#[test] +fn placing_one_item_keeps_the_old_params_and_takes_a_sound_alone() { + let mut s = Session::new(sample::demo()); + let sound = add_sound(&mut s, "beep.wav"); + let selected: Vec<_> = s.selection.ids().collect(); + let v = run(&mut s, "library.place", json!({"sound": sound})); + assert_eq!(v["elements"], json!([])); + assert!(v["element"].is_null()); + assert_eq!(s.selection.ids().collect::>(), selected, "a sound alone leaves the selection"); + let k = s.active_layer().unwrap().keyframe_at(s.frame).unwrap(); + assert_eq!(k.sound.as_ref().map(|f| f.sound.0), Some(sound)); + // Without a position: the stage centre. + let ball = sym(&s, "Ball"); + let el = run(&mut s, "library.place", json!({"symbol": ball}))["element"].as_u64().unwrap(); + let c = Vec2::new(s.doc.stage.width as f32 / 2.0, s.doc.stage.height as f32 / 2.0); + assert_eq!(element(&s, el).transform.apply(Vec2::ZERO), c); +} + +#[test] +fn placing_refuses_what_it_cannot_do_and_changes_nothing() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let (a, b) = (add_sound(&mut s, "a.wav"), add_sound(&mut s, "b.wav")); + let f = run(&mut s, "library.new_folder", json!({}))["folder"].as_u64().unwrap(); + let before = s.doc.clone(); + assert!(err(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"folder": f}]})).contains("folder")); + assert!(err(&mut s, "library.place", json!({"items": [{"sound": a}, {"sound": b}]})).contains("one sound")); + assert!(err(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"symbol": 999_999}]})).contains("no symbol")); + assert!(err(&mut s, "library.place", json!({"items": []})).contains("nothing")); + assert!(err(&mut s, "library.place", json!({"items": "x"})).contains("list")); + assert!(err(&mut s, "library.place", json!({"items": (0..1001).map(|_| json!({"symbol": ball})).collect::>()})).contains("at most")); + assert!(err(&mut s, "library.place", json!({"symbol": ball, "bitmap": 1})).contains("one item")); + err(&mut s, "library.place", json!({"symbol": ball, "x": 1e300})); + assert!(err(&mut s, "library.place", json!({"symbol": ball, "x": 2e6})).contains("million")); + assert!(err(&mut s, "library.place", json!({"sound": 999_999})).contains("no sound")); + assert_eq!(s.doc, before); + // A locked layer takes neither artwork nor a sound. + let layer = s.layer.0; + run(&mut s, "layer.toggle_lock", json!({"layer": layer})); + let locked = s.doc.clone(); + assert!(err(&mut s, "library.place", json!({"symbol": ball})).contains("locked")); + assert!(err(&mut s, "library.place", json!({"sound": a})).contains("locked")); + assert_eq!(s.doc, locked); +} + +#[test] +fn placing_inside_a_symbol_open_for_editing_uses_its_space() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + run(&mut s, "symbol.edit", json!({"symbol": ball})); + let el = run(&mut s, "library.place", json!({"symbol": star, "x": 5, "y": -7}))["element"].as_u64().unwrap(); + let inside = s.doc.symbol(SymbolId(ball)).unwrap().timeline.layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find(|e| e.id.0 == el).cloned().expect("in the open symbol"); + assert_eq!(inside.transform.apply(Vec2::ZERO), Vec2::new(5.0, -7.0)); + assert!(err(&mut s, "library.place", json!({"items": [{"symbol": star}, {"symbol": ball}]})).contains("inside itself")); +} + +#[test] +fn swap_bitmap_resizes_a_placed_bitmap_and_keeps_a_filled_shape() { + let mut s = Session::new(sample::demo()); + let small = add_bitmap(&mut s, "small.png", 2, 2); + let big = add_bitmap(&mut s, "big.png", 6, 4); + let placed = run(&mut s, "library.place", json!({"bitmap": small.0, "x": 100, "y": 100}))["element"].as_u64().unwrap(); + let corner = element(&s, placed).transform.apply(Vec2::ZERO); + // A drawn rectangle filled with the small bitmap, tiled, on a second layer. + run(&mut s, "layer.new", json!({})); + let drawn = run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 30, "h": 30, "object": true}))["element"].as_u64().unwrap(); + let tiled = Paint::Bitmap { bitmap: small, repeat: true, matrix: Affine::scale(2.0, 2.0) }; + for e in s.editable_keyframe().unwrap().elements_mut_where(|id| id.0 == drawn) { + if let ElementKind::Shape(sh) = &mut e.kind { + sh.fill = Some(tiled.clone()); + } + } + let drawn_path = shape(&element(&s, drawn)).path.clone(); + run(&mut s, "edit.select_all", json!({})); + let steps = s.history.undo_len(); + let v = run(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})); + assert_eq!(v["swapped"], 2, "on both layers"); + assert_eq!(s.history.undo_len(), steps + 1); + let p = element(&s, placed); + assert_eq!(p.name, "big.png", "the name follows the bitmap"); + assert_eq!(p.transform.apply(Vec2::ZERO), corner, "the top-left corner stays"); + assert_eq!(*shape(&p).path, Path::rect(0.0, 0.0, 6.0, 4.0), "the new bitmap's size"); + assert_eq!(shape(&p).fill, Some(Paint::Bitmap { bitmap: big, repeat: false, matrix: Affine::IDENTITY })); + let d = element(&s, drawn); + assert_eq!(shape(&d).path, drawn_path, "a filled shape keeps its outline"); + assert_eq!(shape(&d).fill, Some(Paint::Bitmap { bitmap: big, repeat: true, matrix: Affine::scale(2.0, 2.0) }), "and its fill transform"); + // The old bitmap is now unused; one undo brings it back. + assert!(s.doc.unused_items().contains(&LibraryItem::Bitmap(small))); + s.undo().unwrap(); + assert!(!s.doc.unused_items().contains(&LibraryItem::Bitmap(small))); + // Refusals. + assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": 999_999})).contains("no bitmap")); + assert!(err(&mut s, "element.swap_bitmap", json!({})).contains("'bitmap'")); + run(&mut s, "edit.deselect", json!({})); + assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})).contains("nothing is selected")); + let other = run(&mut s, "draw.rect", json!({"x": 300, "y": 300, "w": 5, "h": 5, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "element.select", json!({"ids": [other]})); + assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})).contains("filled with one")); +} + +#[test] +fn convert_to_symbol_goes_into_the_folder_asked_for_with_a_free_name() { + let mut s = Session::new(sample::demo()); + let props = run(&mut s, "library.new_folder", json!({"name": "Props"}))["folder"].as_u64().unwrap(); + let entry = |v: &Value| LibraryEntry::Item(LibraryItem::Symbol(SymbolId(v["symbol"].as_u64().unwrap()))); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "object": true})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Ball", "kind": "movie_clip", "folder": props})); + assert_eq!(v["folder"], props); + assert_eq!(v["name"], "Ball", "Props has no Ball yet (the top level's doesn't count)"); + assert_eq!(s.doc.parent_of(entry(&v)), Some(FolderId(props))); + assert_eq!(s.doc.entry_path(entry(&v)), "Props/Ball"); + assert_eq!(s.doc.symbol(SymbolId(v["symbol"].as_u64().unwrap())).unwrap().kind, SymbolKind::MovieClip); + // The same name again in that folder gets a number; no name gives the next free “Symbol n”. + run(&mut s, "draw.rect", json!({"x": 50, "y": 10, "w": 20, "h": 20, "object": true})); + assert_eq!(run(&mut s, "modify.convert_to_symbol", json!({"name": "ball", "folder": props}))["name"], "ball 2"); + run(&mut s, "draw.rect", json!({"x": 90, "y": 10, "w": 20, "h": 20, "object": true})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"folder": props})); + assert!(v["name"].as_str().unwrap().starts_with("Symbol ")); + assert_eq!(s.doc.symbol(SymbolId(v["symbol"].as_u64().unwrap())).unwrap().kind, SymbolKind::Graphic, "graphic by default"); + // Without a folder: the top level, as before. + run(&mut s, "draw.rect", json!({"x": 130, "y": 10, "w": 20, "h": 20, "object": true})); + let v = run(&mut s, "modify.convert_to_symbol", json!({})); + assert!(v["folder"].is_null()); + assert_eq!(s.doc.parent_of(entry(&v)), None); + // Refusals change nothing. + run(&mut s, "draw.rect", json!({"x": 170, "y": 10, "w": 20, "h": 20, "object": true})); + let before = s.doc.clone(); + assert!(err(&mut s, "modify.convert_to_symbol", json!({"folder": 999_999})).contains("no folder")); + assert!(err(&mut s, "modify.convert_to_symbol", json!({"kind": "sprite"})).contains("symbol type")); + assert_eq!(s.doc, before); + // The file keeps where it went. + let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap(); + assert_eq!(back.library_tree, s.doc.library_tree); +} diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index df41bd67..9306aaea 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -9,9 +9,11 @@ //! its scripts, so a script that loops forever costs one frame's budget, then stops with a //! message. +use anicraft_doc::actions::as3::Problem; use anicraft_doc::actions::{Action, CompileResult, FrameScript, MAX_ACTIONS, PluginScript, check_actions}; -use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step}; -use anicraft_doc::{Document, LayerKind, SymbolKind, Timeline, player}; +use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step, TimelineRef}; +use anicraft_doc::field::{CaretLine, FieldLook}; +use anicraft_doc::{Document, LayerKind, SymbolKind, TextBlock, Timeline, player}; use anicraft_geom::Vec2; use anicraft_plugins::{Host, Kind, Limits, Registry}; use serde_json::{Map, Value, json}; @@ -91,6 +93,22 @@ impl ScriptHost for ScriptRunner<'_> { } } } + + fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { + field_look(block, shown) + } +} + +/// A field's text laid out with this computer's fonts, as the player draws and edits it +/// (ADR 0066). +pub fn field_look(block: &TextBlock, shown: &str) -> Option { + let f = block.field.as_ref()?; + let l = crate::cmds_text::field_layout(anicraft_text::Fonts::get(), &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?; + let mut lines: Vec = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, stops: c.stops }).collect(); + if lines.is_empty() { + lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }); + } + Some(FieldLook { outline: std::sync::Arc::new(l.outline), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height }) } /// What a running frame script talks to. @@ -164,6 +182,26 @@ pub fn state_view(doc: &Document, st: &PlayerState, nodes: &[Node], here: Option "hover": path_of(&st.hover), "tick": st.tick, }); + // Text fields (ADR 0066): their text as it is now, and which has the keyboard. + let fields: Vec = nodes + .iter() + .enumerate() + .filter_map(|(i, n)| n.field().map(|(t, f)| (i, n, t, f))) + .take(MAX_VIEW_CLIPS) + .map(|(i, n, t, f)| { + let fs = st.fields.get(&n.path); + let text = fs.map_or(t.text.as_str(), |x| x.value(t)); + let mut o = json!({"path": path_name(nodes, i), "name": n.name, "type": f.kind.key(), "text": text}); + if st.focus.as_ref() == Some(&n.path) { + let (a, b) = fs.map_or((0, 0), |x| x.selection()); + o["focus"] = json!({"caret": fs.map_or(0, |x| x.caret), "selection": [a, b]}); + } + o + }) + .collect(); + if !fields.is_empty() { + v["fields"] = Value::Array(fields); + } if let Some((i, frame, label)) = here { let n = nodes.get(i); v["timeline"] = json!({"path": path_name(nodes, i), "frame": frame, "frames": n.map_or(1, |n| n.frames), "label": label, "playing": n.and_then(|n| st.playhead(&n.path)).is_some_and(|c| c.playing)}); @@ -191,9 +229,14 @@ impl Movie { /// run and which are skipped and why (ADR 0013 tier 2), said once rather than each time the /// playhead passes. pub fn start(doc: &Document, scripts: &mut dyn ScriptHost) -> Movie { + Movie::start_seeded(doc, player::DEFAULT_SEED, scripts) + } + + /// [`Movie::start`] with `Math.random()` seeded by `seed`. + pub fn start_seeded(doc: &Document, seed: u64, scripts: &mut dyn ScriptHost) -> Movie { let mut m = Movie { state: PlayerState::default(), output: Vec::new(), sounds: Vec::new() }; m.output.extend(script_summary(doc).into_iter().map(|l| (0, l))); - let s = player::start(doc, scripts); + let s = player::start_seeded(doc, seed, scripts); m.take(s); m } @@ -233,10 +276,51 @@ impl Movie { } } -/// Parses a pointer event `{type: move|down|up|click|leave, x, y}` (a click is a press and -/// a release at one point). +/// The ActionScript key code a key event names: a number (1-255), a `Keyboard` constant +/// (`"LEFT"`, `"SPACE"`) or one letter or digit. +pub fn parse_key(v: &Value) -> Result { + match v { + Value::Number(n) => n.as_u64().filter(|k| (1..=255).contains(k)).map(|k| k as u32).ok_or_else(|| "a key code is 1-255".to_string()), + Value::String(s) => { + let t = s.trim(); + let one = t.chars().count() == 1 && t.chars().all(|c| c.is_ascii_alphanumeric()); + if one { + let c = t.to_ascii_uppercase(); + return anicraft_doc::actions::as3::ir::key_code(&c).or_else(|| anicraft_doc::actions::as3::ir::key_code(&format!("NUMBER_{c}"))).ok_or_else(|| format!("unknown key '{t}'")); + } + anicraft_doc::actions::as3::ir::key_code(&t.to_ascii_uppercase()).ok_or_else(|| format!("unknown key '{t}' (a key code, a letter, or a Keyboard name such as LEFT or SPACE)")) + } + _ => Err("a key event needs a \"key\": a key code, a letter, or a Keyboard name such as LEFT".into()), + } +} + +/// Most characters one `text` event types. +pub const MAX_TYPED: usize = 10_000; + +/// Parses an event: a pointer event `{type: move|down|up|click|leave, x, y}` (a click is a +/// press and a release at one point), a key event `{type: key_down|key_up|key, key}` (`key` +/// is a press and a release), or typing into the focused text field (ADR 0066): +/// `{type: text, text}` (each character typed in turn) and `{type: select_all}`. pub fn parse_events(v: &Value) -> Result, String> { - let kind = v.get("type").and_then(Value::as_str).ok_or("an event needs a \"type\": move, down, up, click or leave")?; + let kind = v.get("type").and_then(Value::as_str).ok_or("an event needs a \"type\": move, down, up, click, leave, key_down, key_up, key, text or select_all")?; + if kind == "text" { + let t = v.get("text").and_then(Value::as_str).ok_or("a text event needs a \"text\" to type")?; + if t.chars().count() > MAX_TYPED { + return Err(format!("a text event types at most {MAX_TYPED} characters")); + } + return Ok(t.chars().map(Event::Char).collect()); + } + if kind == "select_all" { + return Ok(vec![Event::SelectAll]); + } + if matches!(kind, "key_down" | "key_up" | "key") { + let k = parse_key(v.get("key").unwrap_or(&Value::Null))?; + return Ok(match kind { + "key_down" => vec![Event::KeyDown(k)], + "key_up" => vec![Event::KeyUp(k)], + _ => vec![Event::KeyDown(k), Event::KeyUp(k)], + }); + } let num = |k: &str| -> Result { v.get(k).and_then(Value::as_f64).filter(|f| f.is_finite() && f.abs() <= 1e7).map(|f| f as f32).ok_or(format!("a {kind} event needs a finite \"{k}\"")) }; Ok(match kind { "leave" => vec![Event::Leave], @@ -247,7 +331,7 @@ pub fn parse_events(v: &Value) -> Result, String> { let p = Vec2::new(num("x")?, num("y")?); vec![Event::Move(p), Event::Down(p), Event::Up(p)] } - other => return Err(format!("unknown event type '{other}' (move, down, up, click or leave)")), + other => return Err(format!("unknown event type '{other}' (move, down, up, click, leave, key_down, key_up, key, text or select_all)")), }) } @@ -258,12 +342,15 @@ pub struct KeptScript<'a> { /// The timeline runs frame scripts there (a scene or a movie clip, on a layer that plays). pub plays: bool, pub compiled: &'a CompileResult, + /// Why it doesn't run on its timeline although it compiles: names from other frames that + /// aren't there (ADR 0052). + pub links: Vec, } impl KeptScript<'_> { /// It runs when the movie plays. pub fn runs(&self) -> bool { - self.plays && self.compiled.is_ok() + self.plays && self.compiled.is_ok() && self.links.is_empty() } } @@ -276,17 +363,28 @@ fn layer_plays(tl: &Timeline, index: usize) -> bool { /// Every kept script in the document: the scenes' first, then the symbols'. pub fn kept_scripts(doc: &Document) -> Vec> { - let scenes = doc.scenes.iter().map(|s| (s.name.as_str(), &s.timeline, true)); - let symbols = doc.library.iter().map(|s| (s.name.as_str(), &s.timeline, s.kind == SymbolKind::MovieClip)); + let scenes = doc.scenes.iter().map(|s| (s.name.as_str(), &s.timeline, Some(TimelineRef::Root))); + let symbols = doc.library.iter().map(|s| (s.name.as_str(), &s.timeline, (s.kind == SymbolKind::MovieClip).then_some(TimelineRef::Symbol(s.id)))); let mut out = Vec::new(); - for (name, tl, runs) in scenes.chain(symbols) { + let mut root = None; + for (name, tl, which) in scenes.chain(symbols) { + let runs = which.is_some(); + let decls = match which { + Some(TimelineRef::Root) => root.get_or_insert_with(|| player::decls(doc, TimelineRef::Root)).clone(), + Some(w) => player::decls(doc, w), + None => Default::default(), + }; for (index, layer) in tl.layers.iter().enumerate() { for k in &layer.keyframes { let Some(FrameScript::Source(src)) = &k.script else { continue }; if out.len() >= MAX_LISTED_SCRIPTS { return out; } - out.push(KeptScript { place: format!("{name} › {}, frame {}", layer.name, u64::from(k.start) + 1), plays: runs && layer_plays(tl, index), compiled: src.compiled() }); + let links = match src.compiled() { + Ok(c) if runs => decls.problems(c), + _ => Vec::new(), + }; + out.push(KeptScript { place: format!("{name} › {}, frame {}", layer.name, u64::from(k.start) + 1), plays: runs && layer_plays(tl, index), compiled: src.compiled(), links }); } } } @@ -300,20 +398,24 @@ pub fn script_summary(doc: &Document) -> Vec { for k in kept_scripts(doc) { match (k.plays, k.compiled) { (false, _) => lines.push(format!("Frame script not run: {}: graphic and button timelines, guide layers and hidden layers don't run frame scripts", k.place)), - (true, Ok(c)) => { + (true, Ok(c)) if k.links.is_empty() => { lines.push(format!("Frame script runs: {}", k.place)); lines.extend(c.notes.iter().map(|n| format!("Frame script at {}: {n}", k.place))); } - (true, Err(problems)) => { - let first = problems.first().map_or_else(String::new, ToString::to_string); - let more = match problems.len() { - 0 | 1 => String::new(), - 2 => " (and 1 more problem: see the Actions panel)".into(), - n => format!(" (and {} more problems: see the Actions panel)", n - 1), - }; - lines.push(format!("Frame script not run: {}: {first}{more}", k.place)); - } + (true, Ok(_)) => lines.push(not_run(&k.place, &k.links)), + (true, Err(problems)) => lines.push(not_run(&k.place, problems)), } } lines } + +/// "Frame script not run: …" with the first problem and how many more there are. +fn not_run(place: &str, problems: &[Problem]) -> String { + let first = problems.first().map_or_else(String::new, ToString::to_string); + let more = match problems.len() { + 0 | 1 => String::new(), + 2 => " (and 1 more problem: see the Actions panel)".into(), + n => format!(" (and {} more problems: see the Actions panel)", n - 1), + }; + format!("Frame script not run: {place}: {first}{more}") +} diff --git a/crates/engine/src/plugin_export.rs b/crates/engine/src/plugin_export.rs new file mode 100644 index 00000000..44986403 --- /dev/null +++ b/crates/engine/src/plugin_export.rs @@ -0,0 +1,281 @@ +//! Exporter plug-ins (ADR 0088, `docs/plugins.md`): `file.export_plugin` and the list of every +//! export format, `file.export_formats`. +//! +//! An exporter never sees the document. Its host holds a snapshot and answers two requests: +//! `movie` (stage, frame rate, the range being exported, the scenes) and `frame` (one movie +//! frame evaluated into the same flattened display list the built-in exporters draw: paths in +//! local space with their stage transform, paints, strokes, colour effects, clips and groups). +//! The plug-in returns the file's bytes; AniCraft writes them. Progress is the frames it has +//! read, and Cancel (a publish [`Control`]) stops it at the next request or slice of fuel. + +use crate::params::*; +use crate::publish::Control; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{DisplayItem, DisplayList, Document, Paint, Rgba, Stroke}; +use anicraft_plugins::{Host, Kind, Limits, Plugin}; +use serde_json::{Map, Value, json}; +use std::path::PathBuf; +use std::sync::Arc; + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "file.export_plugin", + label: "Export with Plug-in…", + menu: "", + shortcut: None, + params: "{format: an exporter plug-in's id (see file.export_formats), path, from?, to? (movie frames: every scene in order), options?: {…} (the plug-in's; missing ones take their defaults), confirm?}", + mutates: false, + run: export_cmd, + }, + CommandSpec { + id: "file.export_formats", + label: "Export Formats", + menu: "", + shortcut: None, + params: "{} → every export format: the built-in ones (with their command) and the exporter plug-ins (with their extension and options)", + mutates: false, + run: |s, _| Ok(json!({"formats": formats(s)})), + }, + ] +} + +/// The built-in export formats: `(id, command, name, extensions, what the command's output +/// param is)`. The CLI's `export --format` takes these ids too. +pub const BUILT_IN: &[(&str, &str, &str, &[&str], &str)] = &[ + ("png", "file.export_png", "PNG image (one frame)", &["png"], "path"), + ("svg", "file.export_svg", "SVG image (one frame)", &["svg"], "path"), + ("png-sequence", "file.export_png_sequence", "PNG sequence", &[], "dir"), + ("sprite-sheet", "file.export_sprite_sheet", "Sprite sheet", &["png"], "path"), + ("gif", "file.export_gif", "Animated GIF", &["gif"], "path"), + ("apng", "file.export_apng", "Animated PNG", &["png", "apng"], "path"), + ("webp", "file.export_webp", "Animated WebP", &["webp"], "path"), + ("video", "file.export_video", "Video", &["webm", "mp4"], "path"), + ("lottie", "file.export_lottie", "Lottie animation", &["json"], "path"), + ("html", "file.export_html", "HTML canvas", &["html"], "path"), +]; + +/// Every export format, built-in first, then the installed exporter plug-ins by id. +pub fn formats(s: &Session) -> Vec { + let mut out: Vec = BUILT_IN.iter().map(|(id, cmd, name, ext, target)| json!({"id": id, "name": name, "extensions": ext, "command": cmd, "target": target, "plugin": false})).collect(); + for p in exporters(s) { + let m = p.manifest(); + let ext = m.format.as_ref().map_or("", |f| f.extension.as_str()); + let name = m.format.as_ref().map_or(m.name.as_str(), |f| f.name.as_str()); + out.push(json!({ + "id": m.id, + "name": name, + "extensions": [ext], + "command": "file.export_plugin", + "target": "path", + "plugin": true, + "description": m.description, + "options": crate::cmds_plugin::describe(s, &p)["params"], + })); + } + out +} + +/// The installed exporter plug-ins, by id. +pub fn exporters(s: &Session) -> Vec> { + s.plugins.list().filter(|p| p.manifest().kind == Kind::Exporter).cloned().collect() +} + +/// One export, checked: where, which movie frames, and the plug-in's resolved options. +#[derive(Clone, Debug, PartialEq)] +pub struct Job { + pub path: PathBuf, + pub from: u32, + pub to: u32, + pub options: Map, +} + +/// Reads `file.export_plugin`'s params against the session: the plug-in and the job. +pub fn plan(s: &Session, p: &Value) -> Result<(Arc, Job)> { + let id = str_req(p, "format")?; + let plugin = s.plugins.get(id).ok_or_else(|| { + let ids: Vec = exporters(s).iter().map(|p| p.id().to_string()).collect(); + EngineError::State(if ids.is_empty() { format!("no exporter plug-in “{id}” is installed (see file.export_formats)") } else { format!("no exporter plug-in “{id}” is installed (installed: {})", ids.join(", ")) }) + })?; + if plugin.manifest().kind != Kind::Exporter { + return Err(EngineError::State(format!("{} is not an exporter plug-in", plugin.manifest().name))); + } + let path = PathBuf::from(str_req(p, "path")?.trim()); + if path.as_os_str().is_empty() { + return Err(EngineError::Param("param 'path' is empty: name the file to write".into())); + } + 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 options = plugin.manifest().resolve_params(p.get("options").unwrap_or(&Value::Null)).map_err(|e| EngineError::Param(e.to_string()))?; + Ok((plugin, Job { path, from, to, options })) +} + +fn export_cmd(s: &mut Session, p: &Value) -> Result { + let (plugin, job) = plan(s, p)?; + run(&plugin, &s.doc, &job, s.job.as_deref()) +} + +/// Runs an export and writes its file: in a command, or on the app's worker thread with a +/// snapshot of the document and a [`Control`] for progress and Cancel. +pub fn run(plugin: &Plugin, doc: &Document, job: &Job, control: Option<&Control>) -> Result { + let frames = u64::from(job.to - job.from) + 1; + if let Some(c) = control { + c.begin(frames); + } + let started = web_time::Instant::now(); + let name: String = job.path.file_stem().map_or_else(|| "Untitled".into(), |n| n.to_string_lossy().chars().take(128).collect()); + let mut host = FrameHost { doc, from: job.from, to: job.to, name, control, read: vec![false; frames as usize], served: 0 }; + let (bytes, report) = plugin.export(&mut host, &job.options, &Limits::exporter()).map_err(|e| match e { + anicraft_plugins::Error::Cancelled => EngineError::Cancelled, + e => EngineError::State(e.to_string()), + })?; + crate::vfs::write(&job.path, &bytes)?; + let m = plugin.manifest(); + Ok(json!({ + "written": job.path.display().to_string(), + "bytes": bytes.len(), + "format": m.id, + "name": m.format.as_ref().map_or(m.name.as_str(), |f| f.name.as_str()), + "frames": frames, + "frames_read": host.served, + "options": job.options, + "log": report.log, + "calls": report.calls, + "fuel": report.fuel, + "ms": started.elapsed().as_millis() as u64, + })) +} + +/// What an exporter talks to: a snapshot of the document, never the session. +struct FrameHost<'a> { + doc: &'a Document, + from: u32, + to: u32, + name: String, + control: Option<&'a Control>, + /// Which frames of the range it has read (progress counts each once). + read: Vec, + served: u64, +} + +impl Host for FrameHost<'_> { + fn request(&mut self, op: &str, req: &Value) -> std::result::Result { + match op { + "movie" => Ok(self.movie()), + "frame" => { + let n = u64::from(self.to - self.from) + 1; + let i = req.get("index").and_then(Value::as_u64).ok_or("a frame request needs an \"index\": 0 for the first frame exported")?; + if i >= n { + return Err(format!("frame index {i} is past the end: the export has {n} frames (0..{})", n - 1)); + } + if let Some(seen) = self.read.get_mut(i as usize) + && !*seen + { + *seen = true; + self.served += 1; + let _ = crate::publish::tick(self.control, 1); + } + Ok(frame_json(self.doc, self.from + i as u32, i)) + } + "command" | "document" | "elements" => Err("an exporter reads the movie's frames (movie, frame); it can't read or change the document".into()), + _ => Err(format!("unknown op '{op}' (an exporter has movie, frame and log)")), + } + } + + fn cancelled(&self) -> bool { + self.control.is_some_and(Control::cancelled) + } +} + +impl FrameHost<'_> { + fn movie(&self) -> Value { + let d = self.doc; + let st = &d.stage; + let scenes: Vec = d.scenes.iter().enumerate().map(|(i, sc)| json!({"name": sc.name, "start": d.scene_start(i), "frames": d.timeline(i).frame_count()})).collect(); + json!({ + "abi": anicraft_plugins::ABI_VERSION, + "name": self.name, + "width": st.width, + "height": st.height, + "fps": st.fps, + "background": rgba_hex(st.background), + "from": self.from, + "to": self.to, + "frames": self.to - self.from + 1, + "total_frames": d.frame_count(), + "scenes": scenes, + }) + } +} + +/// `#rrggbbaa`. +fn rgba_hex(c: Rgba) -> String { + format!("{}{:02x}", c.to_hex(), (if c.a.is_finite() { c.a.clamp(0.0, 1.0) } else { 1.0 } * 255.0).round() as u8) +} + +fn stops_json(stops: &[anicraft_doc::GradientStop]) -> Value { + Value::Array(stops.iter().map(|s| json!([s.offset, rgba_hex(s.color)])).collect()) +} + +fn paint_json(p: &Paint) -> Value { + match p { + Paint::Solid(c) => json!({"type": "solid", "color": rgba_hex(*c)}), + Paint::Linear { start, end, stops, spread, linear_rgb } => json!({"type": "linear", "start": [start.x, start.y], "end": [end.x, end.y], "stops": stops_json(stops), "spread": format!("{spread:?}").to_lowercase(), "linear_rgb": linear_rgb}), + Paint::Radial { center, radius, stops, spread, linear_rgb, focal, matrix } => json!({"type": "radial", "center": [center.x, center.y], "radius": radius, "focal": focal, "matrix": matrix.m, "stops": stops_json(stops), "spread": format!("{spread:?}").to_lowercase(), "linear_rgb": linear_rgb}), + Paint::Bitmap { bitmap, repeat, matrix } => json!({"type": "bitmap", "bitmap": bitmap.0, "repeat": repeat, "matrix": matrix.m}), + } +} + +fn stroke_json(s: &Stroke) -> Value { + let mut v = json!({"color": rgba_hex(s.color), "width": s.width, "cap": s.style.cap.key(), "join": s.style.join.key(), "miter_limit": s.style.miter_limit}); + if let Some(d) = &s.style.dash { + v["dash"] = serde_json::to_value(d).unwrap_or(Value::Null); + } + if s.profile.is_some() { + v["variable_width"] = json!(true); + } + v +} + +fn item_json(it: &DisplayItem) -> Value { + let mut v = json!({ + "layer": it.layer.0, + "element": it.element.0, + "path": it.path.to_svg(), + "transform": it.transform.m, + "fill": it.fill.as_ref().map_or(Value::Null, paint_json), + "stroke": it.stroke.as_ref().map_or(Value::Null, stroke_json), + "fill_rule": format!("{:?}", it.fill_rule).to_lowercase(), + "alpha": it.color.mul[3], + }); + if it.color != anicraft_doc::ColorTransform::IDENTITY { + v["color"] = json!({"mul": it.color.mul, "add": it.color.add}); + } + for (k, x) in [("clip", it.clip), ("masks", it.masks), ("group", it.group)] { + if let Some(i) = x { + v[k] = json!(i); + } + } + v +} + +/// Movie frame `frame` as an exporter sees it (`index` is its place in the export). +pub fn frame_json(doc: &Document, frame: u32, index: u64) -> Value { + let dl: DisplayList = anicraft_doc::evaluate(doc, frame); + let (scene, local) = doc.locate(frame); + let items: Vec = dl.items.iter().filter(|i| !i.guide).map(item_json).collect(); + let groups: Vec = dl.groups.iter().map(|g| json!({"parent": g.parent, "alpha": g.alpha, "blend": format!("{:?}", g.blend).to_lowercase(), "clip": g.clip, "filters": g.filters.len()})).collect(); + json!({ + "index": index, + "frame": frame, + "scene": scene, + "scene_frame": local, + "items": items, + "clips": dl.clip_parents, + "groups": groups, + }) +} diff --git a/crates/engine/src/plugin_kinds_tests.rs b/crates/engine/src/plugin_kinds_tests.rs new file mode 100644 index 00000000..41f449d4 --- /dev/null +++ b/crates/engine/src/plugin_kinds_tests.rs @@ -0,0 +1,204 @@ +//! Exporter and ease plug-ins through the engine (ADR 0088): `file.export_plugin` and +//! `file.export_formats`, progress and Cancel, overwrite confirmation, the document never +//! reaching an exporter; plug-in eases on tweens, kept as sampled curves that play the same +//! once the plug-in is gone, through the file format too. + +use crate::ease_tests::{run, tweened, x_at}; +use crate::plugin_export; +use crate::plugin_tests::{esc, install, request_calls, temp}; +use crate::publish::Control; +use crate::{EngineError, Session}; +use anicraft_doc::{Easing, sample}; +use serde_json::{Value, json}; +use std::path::Path; + +const EXPORTER: &str = r#"{"id":"org.test.dump","name":"Frame Dump","kind":"exporter","format":{"name":"Frame Dump","extension":"dump"},"params":{"mode":{"type":"choice","options":["first","last"],"default":"first"}}}"#; + +/// An exporter that sends `requests` in order and returns the last answer as its file. +fn exporter(requests: &[&str]) -> Vec { + let (data, body) = request_calls(EXPORTER, requests, false); + let text = 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") 64) + {data} + (func (export "ac_abi_version") (result i32) i32.const 1) + (func (export "ac_manifest") (result i64) (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 1024))) + (func (export "ac_alloc") (param i32) (result i32) i32.const 70000) + (func (export "ac_export") (param i32 i32) (result i64) (local $n i32) + {body} + (local.set $n (call $response (i32.const 1048576) (local.get $n))) + (i64.or (i64.shl (i64.extend_i32_u (local.get $n)) (i64.const 32)) (i64.const 1048576))))"#, + len = EXPORTER.len() + ); + wat::parse_str(&text).expect("test WAT") +} + +const EASES: &str = r#"{"id":"org.test.steps","name":"Test Steps","kind":"ease","eases":[{"id":"steps4","name":"Stepped 4"}]}"#; + +/// Four steps: floor(4t) / 4. +fn ease_plugin() -> Vec { + let text = format!( + r#"(module (memory (export "memory") 1) (data (i32.const 1024) "{}") + (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_ease") (param $i i32) (param $t f64) (result f64) (f64.div (f64.floor (f64.mul (local.get $t) (f64.const 4))) (f64.const 4))))"#, + esc(EASES), + EASES.len() + ); + wat::parse_str(&text).expect("test WAT") +} + +/// The answer the dump exporter wrote: `{"ok": …, "result"|"error": …}`. +fn dumped(path: &Path) -> Value { + serde_json::from_slice(&std::fs::read(path).expect("written")).expect("JSON") +} + +#[test] +fn an_exporter_reads_evaluated_frames_and_its_file_is_written() { + let dir = temp("export"); + let mut s = Session::new(sample::demo()); + install(&mut s, &dir, "dump.wasm", &exporter(&[r#"{"op":"movie"}"#, r#"{"op":"frame","index":2}"#])); + // Listed with the built-in formats. + let f = run(&mut s, "file.export_formats", json!({})); + let fmts = f["formats"].as_array().expect("formats"); + assert!(fmts.iter().any(|x| x["id"] == "gif" && x["command"] == "file.export_gif")); + let mine = fmts.iter().find(|x| x["id"] == "org.test.dump").expect("the plug-in's format"); + assert_eq!((mine["name"].as_str(), mine["extensions"][0].as_str(), mine["plugin"].as_bool()), (Some("Frame Dump"), Some("dump"), Some(true))); + assert_eq!(mine["options"][0]["name"], "mode"); + let (rev, undo) = (s.revision, s.history_len()); + let out = dir.join("movie.dump"); + let v = run(&mut s, "file.export_plugin", json!({"format": "org.test.dump", "path": out.display().to_string(), "from": 3, "to": 9})); + assert_eq!((v["frames"].as_u64(), v["frames_read"].as_u64(), v["calls"].as_u64()), (Some(7), Some(1), Some(2))); + assert_eq!(v["options"]["mode"], "first"); + // Frame index 2 of an export from frame 3 is movie frame 5, evaluated as the stage shows it. + let d = dumped(&out); + assert_eq!(d["ok"], true, "{d}"); + let r = &d["result"]; + assert_eq!((r["index"].as_u64(), r["frame"].as_u64()), (Some(2), Some(5))); + let items = r["items"].as_array().expect("items"); + let dl = anicraft_doc::evaluate(&s.doc, 5); + assert_eq!(items.len(), dl.items.iter().filter(|i| !i.guide).count()); + let first = &items[0]; + assert!(first["path"].as_str().is_some_and(|p| p.starts_with('M')), "{first}"); + assert_eq!(first["transform"].as_array().map(Vec::len), Some(6)); + assert!(first["fill"]["type"].is_string() || first["fill"].is_null()); + // Exporting changes nothing in the document and adds no undo step. + assert_eq!((s.revision, s.history_len()), (rev, undo)); + // The file is there now: replacing it needs a confirmation (ADR 0004). + let again = s.execute("file.export_plugin", &json!({"format": "org.test.dump", "path": out.display().to_string()})); + assert!(matches!(again, Err(EngineError::NeedsConfirmation(_))), "{again:?}"); + run(&mut s, "file.export_plugin", json!({"format": "org.test.dump", "path": out.display().to_string(), "confirm": true})); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_movie_request_describes_the_range_and_bad_requests_are_answers() { + let dir = temp("movie"); + let mut s = Session::new(sample::demo()); + let out = dir.join("a.dump"); + let cases = [ + (r#"{"op":"movie"}"#, None), + (r#"{"op":"frame","index":99}"#, Some("past the end")), + (r#"{"op":"frame"}"#, Some("needs an \"index\"")), + (r#"{"op":"document"}"#, Some("can't read or change the document")), + (r#"{"op":"command","id":"draw.rect","params":{}}"#, Some("can't read or change the document")), + (r#"{"op":"teleport"}"#, Some("unknown op")), + ]; + for (i, (req, err)) in cases.iter().enumerate() { + install(&mut s, &dir, &format!("dump{i}.wasm"), &exporter(&[req])); + run(&mut s, "file.export_plugin", json!({"format": "org.test.dump", "path": out.display().to_string(), "to": 4, "confirm": true})); + let d = dumped(&out); + match err { + None => { + let m = &d["result"]; + assert_eq!((m["from"].as_u64(), m["to"].as_u64(), m["frames"].as_u64(), m["name"].as_str()), (Some(0), Some(4), Some(5), Some("a"))); + assert_eq!((m["width"].as_f64(), m["total_frames"].as_u64()), (Some(f64::from(s.doc.stage.width)), Some(u64::from(s.doc.frame_count())))); + assert!(m["background"].as_str().is_some_and(|b| b.len() == 9)); + } + Some(want) => assert!(d["ok"] == false && d["error"].as_str().is_some_and(|e| e.contains(want)), "{req}: {d}"), + } + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn export_params_are_checked() { + let dir = temp("params"); + let mut s = Session::new(sample::demo()); + install(&mut s, &dir, "dump.wasm", &exporter(&[r#"{"op":"movie"}"#])); + let path = dir.join("x.dump").display().to_string(); + let err = |s: &mut Session, p: Value| s.execute("file.export_plugin", &p).expect_err("refused").to_string(); + assert!(err(&mut s, json!({"format": "org.none", "path": path})).contains("installed: org.test.dump")); + assert!(err(&mut s, json!({"format": "org.test.dump"})).contains("path")); + assert!(err(&mut s, json!({"format": "org.test.dump", "path": " "})).contains("empty")); + assert!(err(&mut s, json!({"format": "org.test.dump", "path": path, "options": {"mode": "middle"}})).contains("mode")); + assert!(err(&mut s, json!({"format": "org.test.dump", "path": path, "from": 5, "to": 2})).contains("before")); + // An exporter is not a command, and a command plug-in can't export. + assert!(s.execute("plugin.run", &json!({"id": "org.test.dump"})).expect_err("not a command").to_string().contains("File › Export")); + assert!(crate::cmds_plugin::plugin_may_call("file.export_plugin").is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn progress_counts_frames_read_and_cancel_stops_before_anything_is_written() { + let dir = temp("cancel"); + let mut s = Session::new(sample::demo()); + let reqs: Vec = (0..4).map(|i| format!(r#"{{"op":"frame","index":{i}}}"#)).collect(); + let refs: Vec<&str> = reqs.iter().map(String::as_str).chain([r#"{"op":"frame","index":1}"#]).collect(); + install(&mut s, &dir, "dump.wasm", &exporter(&refs)); + let out = dir.join("p.dump"); + let (plugin, job) = plugin_export::plan(&s, &json!({"format": "org.test.dump", "path": out.display().to_string(), "from": 0, "to": 9})).expect("plan"); + let control = Control::default(); + let v = plugin_export::run(&plugin, &s.doc, &job, Some(&control)).expect("exports"); + // Frame 1 twice counts once. + assert_eq!(control.progress(), (4, 10)); + assert_eq!(v["frames_read"], 4); + let out2 = dir.join("cancelled.dump"); + let job2 = plugin_export::Job { path: out2.clone(), ..job }; + let control = Control::default(); + control.cancel(); + assert!(matches!(plugin_export::run(&plugin, &s.doc, &job2, Some(&control)), Err(EngineError::Cancelled))); + assert!(!out2.exists(), "a cancelled export writes nothing"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_plugin_ease_drives_a_tween_and_the_document_keeps_its_curve() { + let dir = temp("ease"); + let mut s = tweened(); + install(&mut s, &dir, "steps.wasm", &ease_plugin()); + let l = run(&mut s, "ease.list", json!({})); + assert_eq!(l["plugins"], json!([{"name": "Stepped 4", "plugin": "org.test.steps", "plugin_name": "Test Steps", "ease": "steps4", "easing": {"plugin": "org.test.steps", "ease": "steps4"}}])); + let v = run(&mut s, "timeline.set_easing", json!({"frame": 0, "easing": {"plugin": "org.test.steps", "ease": "steps4"}})); + assert_eq!(v["easing"], "Stepped 4"); + // Four steps of 25 over ten frames: frames 0-2 at 0, 3-4 at 25, 5-7 at 50, 8-9 at 75. + let xs: Vec = (0..10).map(|f| x_at(&mut s, f)).collect(); + assert_eq!(xs, [0.0, 0.0, 0.0, 25.0, 25.0, 50.0, 50.0, 50.0, 75.0, 75.0]); + let info = run(&mut s, "ease.info", json!({"frame": 0})); + assert_eq!((info["kind"].as_str(), info["label"].as_str()), (Some("plugin"), Some("Stepped 4"))); + assert_eq!(info["easing"]["sampled"]["values"].as_array().map(Vec::len), Some(257)); + // By name, any case; unknown eases and plug-ins are errors. + run(&mut s, "ease.set", json!({"frame": 0, "easing": {"plugin": "org.test.steps", "ease": "stepped 4"}})); + assert!(s.execute("ease.set", &json!({"frame": 0, "easing": {"plugin": "org.test.steps", "ease": "smooth"}})).expect_err("no such ease").to_string().contains("steps4")); + assert!(s.execute("ease.set", &json!({"frame": 0, "easing": {"plugin": "org.none", "ease": "x"}})).is_err()); + // The file keeps the table: the plug-in removed, the movie plays the same, and again + // after a save and load. + run(&mut s, "plugin.remove", json!({"id": "org.test.steps"})); + let again: Vec = (0..10).map(|f| x_at(&mut s, f)).collect(); + assert_eq!(again, xs); + let text = crate::format::to_json(&s.doc).expect("saves"); + assert!(text.contains("\"Sampled\"")); + let mut back = Session::new(crate::format::from_json(&text).expect("loads")); + let reloaded: Vec = (0..10).map(|f| x_at(&mut back, f)).collect(); + assert_eq!(reloaded, xs); + // Its sampled form is an easing param too (copy it to another tween with ease.info). + let mut t = tweened(); + run(&mut t, "ease.set", json!({"frame": 0, "easing": info["easing"]})); + assert_eq!(x_at(&mut t, 3), 25.0); + // Editing a point makes it a custom curve drawn like it. + run(&mut t, "ease.move_point", json!({"frame": 0, "index": 10, "x": 0.16, "y": 0.4})); + assert!(matches!(t.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.tween.as_ref()).map(|w| &w.easing), Some(Easing::Custom(_)))); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index c8239c34..454a95a6 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -9,7 +9,7 @@ use serde_json::{Value, json}; use std::path::PathBuf; /// WAT string literal contents for `s`. -fn esc(s: &str) -> String { +pub(crate) fn esc(s: &str) -> String { s.bytes().map(|b| if b == b'"' || b == b'\\' || !(0x20..0x7f).contains(&b) { format!("\\{b:02x}") } else { (b as char).to_string() }).collect() } @@ -21,17 +21,7 @@ pub(crate) fn plugin(manifest: &str, requests: &[&str], check: bool, code: i32) /// [`plugin`], running `tail` before it returns. pub(crate) fn plugin_then(manifest: &str, requests: &[&str], check: bool, tail: &str, code: i32) -> Vec { - let mut data = format!("(data (i32.const 1024) \"{}\")\n", esc(manifest)); - let mut body = String::new(); - let mut at = 8192; - for r in requests { - data.push_str(&format!("(data (i32.const {at}) \"{}\")\n", esc(r))); - body.push_str(&format!("(local.set $n (call $call (i32.const {at}) (i32.const {})))\n", r.len())); - if check { - body.push_str("(drop (call $response (i32.const 60000) (i32.const 16)))\n(if (i32.ne (i32.load8_u (i32.const 60006)) (i32.const 116)) (then (return (i32.const 1))))\n"); - } - at += r.len() + 16; - } + let (data, body) = request_calls(manifest, requests, check); let text = format!( r#"(module (import "anicraft" "call" (func $call (param i32 i32) (result i32))) @@ -50,7 +40,25 @@ pub(crate) fn plugin_then(manifest: &str, requests: &[&str], check: bool, tail: wat::parse_str(&text).expect("test WAT") } -const STARS: &str = r#"{"id":"org.test.stars","name":"Test Stars","version":"1.0","kind":"command","params":{"count":{"type":"int","min":1,"max":5,"default":3}}}"#; +/// WAT data for `manifest` (at 1024) and `requests` (from 8192), and the code that sends each +/// request in turn into local `$n` (with `check`, returning 1 at the first answer that isn't +/// `{"ok":true…`). +pub(crate) fn request_calls(manifest: &str, requests: &[&str], check: bool) -> (String, String) { + let mut data = format!("(data (i32.const 1024) \"{}\")\n", esc(manifest)); + let mut body = String::new(); + let mut at = 8192; + for r in requests { + data.push_str(&format!("(data (i32.const {at}) \"{}\")\n", esc(r))); + body.push_str(&format!("(local.set $n (call $call (i32.const {at}) (i32.const {})))\n", r.len())); + if check { + body.push_str("(drop (call $response (i32.const 60000) (i32.const 16)))\n(if (i32.ne (i32.load8_u (i32.const 60006)) (i32.const 116)) (then (return (i32.const 1))))\n"); + } + at += r.len() + 16; + } + (data, body) +} + +const STARS: &str =r#"{"id":"org.test.stars","name":"Test Stars","version":"1.0","kind":"command","params":{"count":{"type":"int","min":1,"max":5,"default":3}}}"#; const NUDGE: &str = r#"{"id":"org.test.nudge","name":"Nudge","kind":"command","selection":"required"}"#; fn stars() -> Vec { @@ -58,14 +66,14 @@ fn stars() -> Vec { plugin(STARS, &[r#"{"op":"command","id":"layer.new","params":{"name":"Stars"}}"#, star, star, star], true, 0) } -fn temp(name: &str) -> PathBuf { +pub(crate) fn temp(name: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("anicraft-engine-plugins-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).expect("temp dir"); d } -fn install(s: &mut Session, dir: &std::path::Path, file: &str, bytes: &[u8]) -> Value { +pub(crate) fn install(s: &mut Session, dir: &std::path::Path, file: &str, bytes: &[u8]) -> Value { let path = dir.join(file); std::fs::write(&path, bytes).expect("write module"); s.execute("plugin.install", &json!({"path": path.display().to_string()})).expect("installs") @@ -136,6 +144,8 @@ fn plugins_cannot_reach_files_history_the_clipboard_or_other_plugins() { let forbidden = [ save.as_str(), r#"{"op":"command","id":"file.export_png","params":{"path":"x.png"}}"#, + r#"{"op":"command","id":"file.export_apng","params":{"path":"x.png"}}"#, + r#"{"op":"command","id":"file.export_webp","params":{"path":"x.webp"}}"#, r#"{"op":"command","id":"plugin.run","params":{"id":"org.test.sneaky"}}"#, r#"{"op":"command","id":"plugin.remove","params":{"id":"org.test.sneaky","confirm":true}}"#, r#"{"op":"command","id":"edit.undo"}"#, @@ -169,12 +179,26 @@ fn every_command_namespace_has_a_plugin_policy() { let ns = c.id.split('.').next().unwrap_or(""); let verdict = plugin_may_call(c.id); match ns { - "file" | "plugin" | "control" => assert!(verdict.is_err(), "{} must be refused", c.id), + "file" | "plugin" | "control" | "prefs" | "desktop" | "macro" => assert!(verdict.is_err(), "{} must be refused", c.id), + // Publish Settings (ADR 0060): read yes, change no (it says what Publish writes). + "publish" => assert_eq!(verdict.is_ok(), c.id == "publish.settings_get", "{}", c.id), + // Brushes (ADR 0068): list yes; your own brushes and brush set files no. + "brush" => assert_eq!(verdict.is_ok(), c.id == "brush.preset_list", "{}", c.id), + // Filters (ADR 0091): the document's lists yes (and listing and applying presets); + // the clipboard, your presets and preset files no. + "filter" => assert_eq!(verdict.is_ok(), matches!(c.id, "filter.move" | "filter.enable" | "filter.remove" | "filter.preset_list" | "filter.preset_apply"), "{}", c.id), + // Swatches (ADR 0078): document data yes, swatch files no. + "swatch" => assert_eq!(verdict.is_ok(), !matches!(c.id, "swatch.import" | "swatch.export"), "{}", c.id), + // Rulers, grid and guides (ADR 0076): a scene's guides yes, how you see and snap no. + "view" => assert_eq!(verdict.is_ok(), matches!(c.id, "view.aids" | "view.guide_add" | "view.guide_move" | "view.guide_delete" | "view.guides_clear"), "{}", c.id), _ => assert!(verdict.is_ok() || matches!(c.id, "edit.undo" | "edit.redo") || c.id.contains("copy") || c.id.contains("cut") || c.id.contains("paste"), "{} has no plug-in policy (add its namespace to plugin_may_call)", c.id), } } assert!(plugin_may_call("draw.rect").is_ok()); assert!(plugin_may_call("future.thing").is_err()); + // Edit Multiple Frames (ADR 0051): document edits yes, the clipboard no. + assert!(["frames.transform", "frames.delete", "frames.align", "frames.merge", "frames.edit_multiple"].iter().all(|c| plugin_may_call(c).is_ok())); + assert!(["frames.copy", "frames.cut", "frames.paste"].iter().all(|c| plugin_may_call(c).is_err())); } #[test] diff --git a/crates/engine/src/publish.rs b/crates/engine/src/publish.rs new file mode 100644 index 00000000..6b206131 --- /dev/null +++ b/crates/engine/src/publish.rs @@ -0,0 +1,801 @@ +//! File › Publish Settings and File › Publish (ADR 0060). +//! +//! The document holds a [`PublishProfile`]: every format, on or off, with its options and an +//! output template relative to the document's folder (`{name}` is the document's name). Publish +//! turns the formats that are on into a [`Step`] each (the export command and its params), and +//! runs them in order through the same export commands File › Export uses, on a session of its +//! own: on the caller's thread for `file.publish` (CLI, MCP, the web build one step per frame), +//! or on a background worker in the desktop editor ([`Publisher`]). A [`Control`] cancels the +//! run between and inside exports and counts frames for the progress view. One [`Report`] says +//! what each format wrote, skipped or left out. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::Document; +use anicraft_doc::publish::{FrameRange, MAX_OUTPUT_CHARS, MAX_PUBLISH_SCALE, MAX_TITLE_CHARS, PublishFormat, PublishProfile}; +use serde_json::{Map, Value, json}; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "publish.settings_get", + label: "Publish Settings…", + menu: "File", + shortcut: Some("Ctrl+Shift+F12"), + params: "{} (the document's publish profile, and where each format would go)", + mutates: false, + run: settings_get, + }, + CommandSpec { + id: "publish.settings_set", + label: "Publish Settings", + menu: "", + shortcut: None, + params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", + mutates: true, + run: settings_set, + }, + CommandSpec { + id: "file.publish", + label: "Publish", + menu: "File", + shortcut: Some("Shift+F12"), + params: "{formats? ([format, …]: only these; default: the ones Publish Settings has on), confirm? (to replace files already there)}", + mutates: false, + run: publish_cmd, + }, + ] +} + +// ----- cancel and progress ------------------------------------------------------------------- + +/// Shared between a running publish and whoever watches it: Cancel, and frames done of the +/// format running. Exports check it between frames (`tick`). +#[derive(Debug, Default)] +pub struct Control { + cancel: AtomicBool, + done: AtomicU64, + total: AtomicU64, +} + +impl Control { + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + } + pub fn cancelled(&self) -> bool { + self.cancel.load(Ordering::Relaxed) + } + /// Frames done and frames in all, of the format running (0 in all: no frame count). + pub fn progress(&self) -> (u64, u64) { + (self.done.load(Ordering::Relaxed), self.total.load(Ordering::Relaxed)) + } + pub(crate) fn begin(&self, total: u64) { + self.done.store(0, Ordering::Relaxed); + self.total.store(total, Ordering::Relaxed); + } +} + +/// An export made `frames` more frames: counts them, and stops it when Publish was cancelled. +pub(crate) fn tick(job: Option<&Control>, frames: u64) -> Result<()> { + let Some(j) = job else { return Ok(()) }; + j.done.fetch_add(frames, Ordering::Relaxed); + if j.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) } +} + +// ----- where things go ----------------------------------------------------------------------- + +/// The folder outputs are relative to and the `{name}` they use: the document's folder and file +/// name. An untitled document has no folder on disk, so it can't publish until it is saved; in +/// the browser (no folders, files become downloads) it publishes as "Untitled". +pub fn base(path: Option<&Path>) -> std::result::Result<(PathBuf, String), String> { + match path { + Some(p) => { + let name = p.file_stem().map_or_else(|| "Untitled".to_string(), |n| n.to_string_lossy().into_owned()); + Ok((p.parent().map(Path::to_path_buf).unwrap_or_default(), name)) + } + None if crate::vfs::in_memory() => Ok((PathBuf::new(), "Untitled".into())), + None => Err("save the document first: Publish writes its files beside it".into()), + } +} + +/// Output template `template` of format `f`, for a document named `name`: a path inside the +/// document's folder. `{name}` is the only placeholder; the path may go into folders below +/// but never above or elsewhere (a document opened from someone else can't write anywhere +/// else on this computer); a file without an extension gets the format's. +pub fn resolve(f: PublishFormat, template: &str, name: &str) -> std::result::Result { + let t = template.trim(); + if t.is_empty() { + return Err("the output name is empty".into()); + } + if t.chars().count() > MAX_OUTPUT_CHARS { + return Err(format!("the output name is longer than {MAX_OUTPUT_CHARS} characters")); + } + let text = t.replace("{name}", name); + if t.replace("{name}", "").contains(['{', '}']) { + return Err(format!("“{t}” has a placeholder Publish doesn't know: {{name}} (the document's name) is the only one")); + } + let mut rel = PathBuf::new(); + for c in Path::new(&text).components() { + match c { + Component::Normal(part) => rel.push(part), + Component::CurDir => {} + _ => return Err(format!("“{t}” must stay in the document's folder (a name, or folders below it like web/{{name}}.html)")), + } + } + if rel.as_os_str().is_empty() { + return Err("the output name is empty".into()); + } + let exts = f.extensions(); + if !exts.is_empty() { + match rel.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase) { + None => { + let file = rel.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + rel.set_file_name(format!("{file}.{}", exts.first().copied().unwrap_or(""))); + } + Some(e) if exts.contains(&e.as_str()) => {} + Some(_) => return Err(format!("{} goes to {}", f.label(), exts.iter().map(|e| format!(".{e}")).collect::>().join(" or "))), + } + } + Ok(rel) +} + +// ----- the plan -------------------------------------------------------------------------------- + +/// One format to publish: the export command that writes it and its params. +#[derive(Clone, Debug)] +pub struct Step { + pub format: PublishFormat, + pub command: &'static str, + pub params: Value, + /// The files (or, for the PNG sequence, the folder) it writes. + pub outputs: Vec, + /// The scene the export runs in (one-frame formats), and frames it makes (0: not counted). + pub scene: usize, + pub frames: u64, + /// Why it won't run here, when it won't. + pub skip: Option, +} + +fn range_params(p: &mut Map, r: FrameRange, last: u32) -> u64 { + if let Some(f) = r.from { + p.insert("from".into(), json!(f)); + } + if let Some(t) = r.to { + p.insert("to".into(), json!(t)); + } + let from = r.from.unwrap_or(0).min(last); + let to = r.to.unwrap_or(last).min(last); + u64::from(to.saturating_sub(from)) + 1 +} + +/// The steps Publish runs for `doc` saved at `path`: the formats that are on (or `only`), in +/// order, or why it can't run (an output that isn't one, two formats writing the same file). +pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>) -> std::result::Result, String> { + let (dir, name) = base(path)?; + let prof = &doc.publish; + let formats: Vec = match only { + Some(list) => PublishFormat::ALL.into_iter().filter(|f| list.contains(f)).collect(), + None => prof.enabled(), + }; + let last = doc.frame_count().saturating_sub(1); + let mut steps: Vec = Vec::new(); + for f in formats { + let rel = resolve(f, prof.target(f).1, &name).map_err(|e| format!("{}: {e}", f.label()))?; + let out = dir.join(&rel); + let path_s = out.display().to_string(); + let mut p = Map::new(); + let (mut scene, mut skip) = (0, None); + let (command, frames, outputs) = match f { + PublishFormat::Html => { + let h = &prof.html; + if !h.title.trim().is_empty() { + p.insert("title".into(), json!(h.title)); + } + p.insert("sound".into(), json!(h.sound)); + p.insert("fit".into(), json!(h.fit)); + ("file.export_html", 0, vec![out]) + } + PublishFormat::Gif => { + let g = &prof.gif; + let n = range_params(&mut p, g.range, last); + p.insert("scale".into(), json!(g.scale)); + p.insert("loop".into(), json!(g.looping)); + ("file.export_gif", n, vec![out]) + } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background, command) = match f { + PublishFormat::Apng => (prof.apng.range, prof.apng.scale, prof.apng.plays, prof.apng.background, "file.export_apng"), + _ => (prof.webp.range, prof.webp.scale, prof.webp.plays, prof.webp.background, "file.export_webp"), + }; + let n = range_params(&mut p, range, last); + p.insert("scale".into(), json!(scale)); + p.insert("loop".into(), json!(plays)); + p.insert("background".into(), json!(background)); + (command, n, vec![out]) + } + PublishFormat::Video => { + let v = &prof.video; + let n = range_params(&mut p, v.range, last); + p.insert("scale".into(), json!(v.scale)); + p.insert("audio".into(), json!(v.audio)); + if crate::vfs::in_memory() { + skip = Some("video is made with ffmpeg, which a web browser can't run".to_string()); + } + ("file.export_video", n, vec![out]) + } + PublishFormat::Lottie => { + let l = &prof.lottie; + range_params(&mut p, l.range, last); + p.insert("background".into(), json!(l.background)); + ("file.export_lottie", 0, vec![out]) + } + PublishFormat::SpriteSheet => { + let sh = &prof.sprite_sheet; + let n = range_params(&mut p, sh.range, last); + p.insert("scale".into(), json!(sh.scale)); + if sh.columns > 0 { + p.insert("columns".into(), json!(sh.columns)); + } + p.insert("padding".into(), json!(sh.padding)); + p.insert("background".into(), json!(sh.background)); + let map = out.with_extension("json"); + ("file.export_sprite_sheet", n, vec![out, map]) + } + PublishFormat::PngSequence => { + let q = &prof.png_sequence; + let n = range_params(&mut p, q.range, last); + p.insert("scale".into(), json!(q.scale)); + ("file.export_png_sequence", n, vec![out]) + } + PublishFormat::Png => { + let (sc, local) = doc.locate(prof.png.frame.min(last)); + scene = sc; + p.insert("frame".into(), json!(local)); + p.insert("scale".into(), json!(prof.png.scale)); + ("file.export_png", 1, vec![out]) + } + PublishFormat::Svg => { + let (sc, local) = doc.locate(prof.svg.frame.min(last)); + scene = sc; + p.insert("frame".into(), json!(local)); + ("file.export_svg", 1, vec![out]) + } + PublishFormat::Audio => { + let a = &prof.audio; + range_params(&mut p, a.range, last); + p.insert("rate".into(), json!(a.rate)); + p.insert("bits".into(), json!(a.bits)); + if !anicraft_doc::sound::has_sounds(doc) { + skip = Some("the movie has no sounds".to_string()); + } + ("file.export_audio", 0, vec![out]) + } + }; + let key = if f == PublishFormat::PngSequence { "dir" } else { "path" }; + p.insert(key.into(), json!(path_s)); + // Publish's own confirmation covers replacing files (`existing`). + p.insert("confirm".into(), json!(true)); + // Two formats writing one file would leave only the second (names compared as the + // case-insensitive file systems of Windows and macOS see them). + let same = |a: &Path, b: &Path| a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase(); + if let Some(other) = steps.iter().find(|s| s.outputs.iter().any(|o| outputs.iter().any(|n| same(o, n)))) { + return Err(format!("{} and {} would both write {}: give one of them another output name", other.format.label(), f.label(), rel.display())); + } + steps.push(Step { format: f, command, params: Value::Object(p), outputs, scene, frames, skip }); + } + Ok(steps) +} + +/// Files already there that publishing `steps` would replace (a PNG sequence's folder when it +/// holds exported frames), leaving out those this session published itself. +pub fn existing(s: &Session, steps: &[Step]) -> Vec { + let mut v = Vec::new(); + for st in steps.iter().filter(|st| st.skip.is_none()) { + for o in &st.outputs { + if s.published.contains(o) { + continue; + } + let there = if st.format == PublishFormat::PngSequence { + crate::vfs::list(o, 10_000).iter().any(|e| { + let n = e.file_name().map(|n| n.to_string_lossy()).unwrap_or_default(); + n.starts_with("frame_") && n.ends_with(".png") + }) + } else { + crate::vfs::exists(o) + }; + if there { + v.push(o.clone()); + } + } + } + v +} + +/// The formats `file.publish` params name, if they name any. +pub fn formats_param(p: &Value) -> Result>> { + match p.get("formats") { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(list)) => list + .iter() + .take(64) + .map(|v| v.as_str().and_then(PublishFormat::from_key).ok_or_else(|| EngineError::Param(format!("unknown format {v} (html, gif, apng, webp, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))) + .collect::>>() + .map(Some), + Some(_) => Err(EngineError::Param("param 'formats' must be a list of format names".into())), + } +} + +/// The plan `file.publish` with `p` would run, for the confirmation (ADR 0004). +pub(crate) fn planned(s: &Session, p: &Value) -> Option> { + plan(&s.doc, s.path.as_deref(), formats_param(p).ok()?.as_deref()).ok() +} + +// ----- running --------------------------------------------------------------------------------- + +/// How one format went. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Status { + Published, + Skipped, + Failed, + Cancelled, +} + +impl Status { + pub fn key(self) -> &'static str { + match self { + Status::Published => "published", + Status::Skipped => "skipped", + Status::Failed => "failed", + Status::Cancelled => "cancelled", + } + } +} + +/// What one format did: the files it wrote, and what its exporter left out or why it failed. +#[derive(Clone, Debug)] +pub struct Outcome { + pub format: PublishFormat, + pub status: Status, + pub files: Vec, + /// The exporter's report of what it approximated or left out (HTML, Lottie), or why the + /// format was skipped, failed or stopped. + pub message: String, +} + +impl Outcome { + pub fn to_json(&self) -> Value { + json!({ + "format": self.format.key(), + "label": self.format.label(), + "status": self.status.key(), + "files": self.files.iter().map(|f| f.display().to_string()).collect::>(), + "message": self.message, + }) + } +} + +/// Every format's outcome, in order. +#[derive(Clone, Debug, Default)] +pub struct Report { + pub outcomes: Vec, +} + +impl Report { + pub fn count(&self, s: Status) -> usize { + self.outcomes.iter().filter(|o| o.status == s).count() + } + pub fn files(&self) -> Vec { + self.outcomes.iter().flat_map(|o| o.files.iter().cloned()).collect() + } + /// One sentence per format with something to say (left out, skipped, failed), in order. + pub fn summary(&self) -> String { + self.outcomes + .iter() + .filter(|o| !o.message.is_empty()) + .map(|o| { + let m = o.message.trim_end_matches('.'); + match o.status { + Status::Published => format!("{}: {m}.", o.format.label()), + Status::Skipped => format!("{} skipped: {m}.", o.format.label()), + Status::Failed => format!("{} failed: {m}.", o.format.label()), + Status::Cancelled => format!("{}: {m}.", o.format.label()), + } + }) + .collect::>() + .join(" ") + } + pub fn to_json(&self) -> Value { + json!({ + "published": self.count(Status::Published), + "skipped": self.count(Status::Skipped), + "failed": self.count(Status::Failed), + "cancelled": self.count(Status::Cancelled) > 0, + "files": self.files().iter().map(|f| f.display().to_string()).collect::>(), + "formats": self.outcomes.iter().map(Outcome::to_json).collect::>(), + "report": self.summary(), + }) + } +} + +/// Runs the steps of a publish one at a time, on a session of its own (the document as it was +/// when Publish started), so the editor keeps working while it runs. +pub struct Publisher { + s: Session, + steps: Vec, + next: usize, + report: Report, + control: Arc, +} + +impl Publisher { + pub fn new(doc: Document, path: Option, steps: Vec, control: Arc) -> Publisher { + let mut s = Session::new(doc); + s.path = path; + s.job = Some(control.clone()); + Publisher { s, steps, next: 0, report: Report::default(), control } + } + + /// The format running next (or now), if any is left. + pub fn current(&self) -> Option { + self.steps.get(self.next).map(|s| s.format) + } + + pub fn done(&self) -> bool { + self.next >= self.steps.len() + } + + /// Runs the next format; `None` when every format has run. Once cancelled, the formats + /// left are cancelled without running. + pub fn step(&mut self) -> Option<&Outcome> { + let st = self.steps.get(self.next)?.clone(); + self.next += 1; + let out = self.run(&st); + self.report.outcomes.push(out); + self.report.outcomes.last() + } + + fn run(&mut self, st: &Step) -> Outcome { + let mut out = Outcome { format: st.format, status: Status::Published, files: Vec::new(), message: String::new() }; + if self.control.cancelled() { + out.status = Status::Cancelled; + out.message = "not published (cancelled)".into(); + return out; + } + if let Some(why) = &st.skip { + out.status = Status::Skipped; + out.message.clone_from(why); + return out; + } + self.control.begin(st.frames); + // Folders below the document's are made as needed. + for o in &st.outputs { + let dir = if st.format == PublishFormat::PngSequence { Some(o.as_path()) } else { o.parent() }; + if let Some(d) = dir.filter(|d| !d.as_os_str().is_empty()) + && let Err(e) = crate::vfs::create_dir_all(d) + { + out.status = Status::Failed; + out.message = format!("could not make the folder {}: {e}", d.display()); + return out; + } + } + self.s.scene = st.scene.min(self.s.doc.scenes.len().saturating_sub(1)); + self.s.editing.clear(); + self.s.frame = 0; + let result = crate::find_command(st.command).ok_or_else(|| EngineError::UnknownCommand(st.command.into())).and_then(|spec| (spec.run)(&mut self.s, &st.params)); + match result { + Ok(v) => { + out.files.clone_from(&st.outputs); + out.message = v.get("report").and_then(Value::as_str).unwrap_or("").to_string(); + } + Err(EngineError::Cancelled) => { + out.status = Status::Cancelled; + out.message = if st.format == PublishFormat::PngSequence { "stopped part-way (the frames written so far are kept)".into() } else { "stopped before it was written".into() }; + } + Err(e) => { + out.status = Status::Failed; + out.message = e.to_string(); + } + } + out + } + + /// Runs every format left. + pub fn run_all(&mut self) { + while self.step().is_some() {} + } + + pub fn report(&self) -> &Report { + &self.report + } +} + +fn publish_cmd(s: &mut Session, p: &Value) -> Result { + let steps = plan(&s.doc, s.path.as_deref(), formats_param(p)?.as_deref()).map_err(EngineError::State)?; + if steps.is_empty() { + return Err(EngineError::State("no format is on in Publish Settings: turn one on first".into())); + } + let control = s.job.clone().unwrap_or_default(); + let mut job = Publisher::new(s.doc.clone(), s.path.clone(), steps, control); + job.run_all(); + let report = job.report(); + s.published.extend(report.files()); + Ok(report.to_json()) +} + +// ----- the settings commands ------------------------------------------------------------------- + +fn settings_get(s: &mut Session, _: &Value) -> Result { + Ok(settings_json(&s.doc, s.path.as_deref())) +} + +/// The profile, and for each format whether it is on, its output and where that goes now (or +/// why it can't go anywhere). +pub fn settings_json(doc: &Document, path: Option<&Path>) -> Value { + let base = base(path); + let formats: Vec = PublishFormat::ALL + .iter() + .map(|f| { + let (on, output) = doc.publish.target(*f); + let mut o = json!({"format": f.key(), "label": f.label(), "enabled": on, "output": output}); + match base.as_ref().map_err(Clone::clone).and_then(|(dir, name)| resolve(*f, output, name).map(|r| dir.join(r))) { + Ok(at) => { + o["path"] = json!(at.display().to_string()); + o["exists"] = json!(crate::vfs::exists(&at)); + } + Err(e) => o["error"] = json!(e), + } + o + }) + .collect(); + let (folder, name) = base.map_or((Value::Null, Value::Null), |(d, n)| (json!(d.display().to_string()), json!(n))); + json!({"profile": serde_json::to_value(&*doc.publish).unwrap_or(Value::Null), "formats": formats, "folder": folder, "name": name}) +} + +/// Keys each format's options take (besides `enabled` and `output`). +fn option_keys(f: PublishFormat) -> &'static [&'static str] { + match f { + PublishFormat::Html => &["title", "sound", "fit"], + PublishFormat::Gif => &["from", "to", "scale", "loop"], + PublishFormat::Apng | PublishFormat::Webp => &["from", "to", "scale", "loop", "background"], + PublishFormat::Video => &["from", "to", "scale", "audio"], + PublishFormat::Lottie => &["from", "to", "background"], + PublishFormat::SpriteSheet => &["from", "to", "scale", "columns", "padding", "background"], + PublishFormat::PngSequence => &["from", "to", "scale"], + PublishFormat::Png => &["frame", "scale"], + PublishFormat::Svg => &["frame"], + PublishFormat::Audio => &["from", "to", "rate", "bits"], + } +} + +/// A movie-frame param: absent (unchanged), null (the movie's end) or a frame. +fn opt_end(p: &Value, key: &str) -> Result>> { + match p.get(key) { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(_) => opt_u32(p, key).map(|v| Some(v.map(|f| f.min(crate::MAX_FRAME)))), + } +} + +fn set_range(r: &mut FrameRange, p: &Value) -> Result<()> { + if let Some(v) = opt_end(p, "from")? { + r.from = v; + } + if let Some(v) = opt_end(p, "to")? { + r.to = v; + } + if let (Some(a), Some(b)) = (r.from, r.to) + && b < a + { + return Err(EngineError::Param("'to' must not be before 'from'".into())); + } + Ok(()) +} + +fn set_scale(v: &mut f32, p: &Value) -> Result<()> { + if let Some(x) = opt_f32(p, "scale")? { + if !(x > 0.0 && x <= MAX_PUBLISH_SCALE) { + return Err(EngineError::Param(format!("param 'scale' must be in (0, {MAX_PUBLISH_SCALE}]"))); + } + *v = x; + } + Ok(()) +} + +fn set_bool(v: &mut bool, p: &Value, key: &str) -> Result<()> { + if let Some(b) = opt_bool(p, key)? { + *v = b; + } + Ok(()) +} + +/// Changes format `f`'s switch, output and options from `p`. +fn apply(prof: &mut PublishProfile, f: PublishFormat, p: &Value) -> Result<()> { + if let Some(obj) = p.as_object() { + let known = option_keys(f); + if let Some(k) = obj.keys().find(|k| !matches!(k.as_str(), "format" | "enabled" | "output" | "confirm") && !known.contains(&k.as_str())) { + return Err(EngineError::Param(format!("{} has no option '{k}' (it has {})", f.label(), known.join(", ")))); + } + } + if let Some(o) = opt_str(p, "output")? { + resolve(f, o, "name").map_err(|e| EngineError::Param(format!("{}: {e}", f.label())))?; + *prof.target_mut(f).1 = o.trim().to_string(); + } + if let Some(b) = opt_bool(p, "enabled")? { + *prof.target_mut(f).0 = b; + } + match f { + PublishFormat::Html => { + let h = &mut prof.html; + if let Some(t) = opt_str(p, "title")? { + if t.chars().count() > MAX_TITLE_CHARS { + return Err(EngineError::Param(format!("param 'title' is at most {MAX_TITLE_CHARS} characters"))); + } + h.title = t.to_string(); + } + set_bool(&mut h.sound, p, "sound")?; + set_bool(&mut h.fit, p, "fit")?; + } + PublishFormat::Gif => { + let g = &mut prof.gif; + set_range(&mut g.range, p)?; + set_scale(&mut g.scale, p)?; + set_bool(&mut g.looping, p, "loop")?; + } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background) = match f { + PublishFormat::Apng => (&mut prof.apng.range, &mut prof.apng.scale, &mut prof.apng.plays, &mut prof.apng.background), + _ => (&mut prof.webp.range, &mut prof.webp.scale, &mut prof.webp.plays, &mut prof.webp.background), + }; + set_range(range, p)?; + set_scale(scale, p)?; + if p.get("loop").is_some() { + *plays = crate::anim::plays(p)?; + } + set_bool(background, p, "background")?; + } + PublishFormat::Video => { + let v = &mut prof.video; + set_range(&mut v.range, p)?; + set_scale(&mut v.scale, p)?; + set_bool(&mut v.audio, p, "audio")?; + } + PublishFormat::Lottie => { + set_range(&mut prof.lottie.range, p)?; + set_bool(&mut prof.lottie.background, p, "background")?; + } + PublishFormat::SpriteSheet => { + let sh = &mut prof.sprite_sheet; + set_range(&mut sh.range, p)?; + set_scale(&mut sh.scale, p)?; + if let Some(c) = opt_u32(p, "columns")? { + sh.columns = c.min(10_000); + } + if let Some(x) = opt_u32(p, "padding")? { + if x > 256 { + return Err(EngineError::Param("param 'padding' must be at most 256".into())); + } + sh.padding = x; + } + set_bool(&mut sh.background, p, "background")?; + } + PublishFormat::PngSequence => { + set_range(&mut prof.png_sequence.range, p)?; + set_scale(&mut prof.png_sequence.scale, p)?; + } + PublishFormat::Png => { + if let Some(fr) = opt_u32(p, "frame")? { + prof.png.frame = fr.min(crate::MAX_FRAME); + } + set_scale(&mut prof.png.scale, p)?; + } + PublishFormat::Svg => { + if let Some(fr) = opt_u32(p, "frame")? { + prof.svg.frame = fr.min(crate::MAX_FRAME); + } + } + PublishFormat::Audio => { + let a = &mut prof.audio; + set_range(&mut a.range, p)?; + if let Some(r) = opt_u32(p, "rate")? { + if !(8_000..=192_000).contains(&r) { + return Err(EngineError::Param("param 'rate' must be between 8000 and 192000".into())); + } + a.rate = r; + } + if let Some(b) = opt_u32(p, "bits")? { + if !matches!(b, 16 | 24 | 32) { + return Err(EngineError::Param("param 'bits' must be 16, 24 or 32 (float)".into())); + } + a.bits = b; + } + } + } + Ok(()) +} + +fn settings_set(s: &mut Session, p: &Value) -> Result { + let mut prof = match p.get("profile") { + None | Some(Value::Null) => (*s.doc.publish).clone(), + Some(v) => { + let mut prof: PublishProfile = serde_json::from_value(v.clone()).map_err(|e| EngineError::Param(format!("param 'profile' is not a publish profile: {e}")))?; + prof.sanitize(); + prof + } + }; + match opt_str(p, "format")? { + Some(k) => { + let f = PublishFormat::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown format '{k}' (html, gif, apng, webp, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))?; + apply(&mut prof, f, p)?; + } + None if p.get("profile").is_none_or(Value::is_null) && p.as_object().is_some_and(|o| o.keys().any(|k| k != "confirm" && k != "profile")) => { + return Err(EngineError::Param("name the 'format' to change, or pass a whole 'profile'".into())); + } + None => {} + } + if prof != *s.doc.publish { + s.doc.publish = Arc::new(prof); + } + Ok(settings_json(&s.doc, s.path.as_deref())) +} + +/// Writes `files` (path, bytes) as one uncompressed ZIP archive, per PKWARE's APPNOTE (what the browser downloads +/// when Publish writes more than one file). Paths keep their folders, with `/` between them. +pub fn zip(files: &[(PathBuf, Vec)]) -> std::result::Result, String> { + let mut out: Vec = Vec::new(); + let mut central: Vec = Vec::new(); + let n = u16::try_from(files.len()).map_err(|_| "too many files for one archive".to_string())?; + let le16 = |v: &mut Vec, x: u16| v.extend_from_slice(&x.to_le_bytes()); + let le32 = |v: &mut Vec, x: u32| v.extend_from_slice(&x.to_le_bytes()); + for (path, data) in files { + let name: String = path.components().filter_map(|c| if let Component::Normal(p) = c { Some(p.to_string_lossy().into_owned()) } else { None }).collect::>().join("/"); + let name_len = u16::try_from(name.len()).map_err(|_| "a file name is too long".to_string())?; + let size = u32::try_from(data.len()).map_err(|_| format!("{name} is too large for a ZIP archive (4 GB)"))?; + let offset = u32::try_from(out.len()).map_err(|_| "the archive is too large (4 GB)".to_string())?; + let crc = anicraft_xfl::zip::crc32(data); + // Local file header: version 2.0, UTF-8 names (bit 11), stored. + le32(&mut out, 0x0403_4b50); + for x in [20u16, 0x0800, 0, 0, 0x21] { + le16(&mut out, x); + } + for x in [crc, size, size] { + le32(&mut out, x); + } + le16(&mut out, name_len); + le16(&mut out, 0); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(data); + // Its central directory entry. + le32(&mut central, 0x0201_4b50); + for x in [20u16, 20, 0x0800, 0, 0, 0x21] { + le16(&mut central, x); + } + for x in [crc, size, size] { + le32(&mut central, x); + } + for x in [name_len, 0, 0, 0, 0] { + le16(&mut central, x); + } + le32(&mut central, 0); + le32(&mut central, offset); + central.extend_from_slice(name.as_bytes()); + } + let at = u32::try_from(out.len()).map_err(|_| "the archive is too large (4 GB)".to_string())?; + let len = u32::try_from(central.len()).map_err(|_| "the archive is too large".to_string())?; + out.extend_from_slice(¢ral); + le32(&mut out, 0x0605_4b50); + for x in [0u16, 0, n, n] { + le16(&mut out, x); + } + le32(&mut out, len); + le32(&mut out, at); + le16(&mut out, 0); + Ok(out) +} + +#[cfg(test)] +#[path = "publish_tests.rs"] +mod tests; diff --git a/crates/engine/src/publish_tests.rs b/crates/engine/src/publish_tests.rs new file mode 100644 index 00000000..c30ac16b --- /dev/null +++ b/crates/engine/src/publish_tests.rs @@ -0,0 +1,307 @@ +//! Publish Settings and Publish (ADR 0060): the profile in the file, where outputs go, the +//! plan, running every exporter with its options, cancelling, the combined report, the +//! confirmation, the browser's archive. + +use super::*; +use crate::{EngineError, Session, vfs}; +use anicraft_doc::sample; +use serde_json::json; +use std::path::{Path, PathBuf}; + +fn temp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("anicraft-publish-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// The demo, saved as `walk.anicraft` in a fresh folder. +fn saved(name: &str) -> (Session, PathBuf) { + let dir = temp(name); + let mut s = Session::new(sample::demo()); + run(&mut s, "file.save", json!({"path": dir.join("walk.anicraft").display().to_string()})); + (s, dir) +} + +#[test] +fn templates_resolve_inside_the_documents_folder() { + let r = |f, t: &str| resolve(f, t, "walk"); + assert_eq!(r(PublishFormat::Html, "{name}.html").unwrap(), PathBuf::from("walk.html")); + assert_eq!(r(PublishFormat::Gif, "web/{name}-small.gif").unwrap(), Path::new("web").join("walk-small.gif")); + assert_eq!(r(PublishFormat::Gif, "./{name}").unwrap(), PathBuf::from("walk.gif"), "a missing extension is the format's"); + assert_eq!(r(PublishFormat::Video, "{name}.MP4").unwrap(), PathBuf::from("walk.MP4")); + assert_eq!(r(PublishFormat::PngSequence, "{name}_frames").unwrap(), PathBuf::from("walk_frames"), "a folder has no extension"); + for bad in ["../{name}.gif", "/tmp/{name}.gif", "web/../../x.gif", "{title}.gif", "{name.gif", " ", "{name}.png"] { + assert!(r(PublishFormat::Gif, bad).is_err(), "{bad}"); + } + #[cfg(windows)] + assert!(r(PublishFormat::Gif, "C:\\x.gif").is_err() && r(PublishFormat::Gif, "C:x.gif").is_err()); + assert!(r(PublishFormat::Gif, &"a".repeat(600)).is_err()); + // The folder and name come from the document's path. + assert_eq!(base(Some(Path::new("art/walk.anicraft"))).unwrap(), (PathBuf::from("art"), "walk".to_string())); + assert!(base(None).is_err(), "an untitled document on disk saves first"); +} + +#[test] +fn settings_round_trip_through_the_file_and_older_files_get_defaults() { + let (mut s, dir) = saved("roundtrip"); + let v = run(&mut s, "publish.settings_set", json!({"format": "gif", "enabled": true, "output": "web/{name}.gif", "scale": 0.5, "loop": false, "from": 2, "to": 9})); + let gif = v["formats"].as_array().unwrap().iter().find(|f| f["format"] == "gif").unwrap(); + assert_eq!(gif["path"], json!(dir.join("web").join("walk.gif").display().to_string())); + run(&mut s, "publish.settings_set", json!({"format": "html", "title": "Walk cycle", "sound": false})); + run(&mut s, "publish.settings_set", json!({"format": "audio", "rate": 22050, "bits": 24, "to": null})); + let path = dir.join("walk.anicraft"); + run(&mut s, "file.save", json!({})); + let back = crate::format::load(&path).unwrap(); + assert_eq!(*back.publish, *s.doc.publish); + let p = &back.publish; + assert!(p.gif.enabled && !p.gif.looping && p.gif.scale == 0.5 && p.gif.range == FrameRange { from: Some(2), to: Some(9) }); + assert_eq!((p.html.title.as_str(), p.html.sound, p.audio.rate, p.audio.bits), ("Walk cycle", false, 22050, 24)); + // An untouched profile isn't written at all, so files from before publish settings look + // the same: they open with the HTML page on and the rest off. + let mut fresh = Session::new(sample::demo()); + let text = serde_json::to_string(&fresh.doc).unwrap(); + assert!(!text.contains("\"publish\"")); + let older: anicraft_doc::Document = serde_json::from_str(&text).unwrap(); + assert_eq!(older.publish.enabled(), vec![PublishFormat::Html]); + // Settings are a document change: undo takes them back. + run(&mut fresh, "publish.settings_set", json!({"format": "svg", "enabled": true})); + assert!(fresh.is_dirty() && fresh.doc.publish.svg.enabled); + run(&mut fresh, "edit.undo", json!({})); + assert!(!fresh.doc.publish.svg.enabled); + // A whole profile, as publish.settings_get gives it. + let whole = run(&mut s, "publish.settings_get", json!({}))["profile"].clone(); + run(&mut fresh, "publish.settings_set", json!({"profile": whole})); + assert_eq!(*fresh.doc.publish, *s.doc.publish); +} + +#[test] +fn settings_refuse_what_publish_couldnt_use() { + let mut s = Session::new(sample::demo()); + let before = s.doc.publish.clone(); + for bad in [ + json!({"format": "flash"}), + json!({"format": "gif", "rate": 44100}), + json!({"format": "gif", "scale": 0}), + json!({"format": "gif", "scale": 9}), + json!({"format": "gif", "from": 9, "to": 2}), + json!({"format": "gif", "output": "../x.gif"}), + json!({"format": "gif", "output": "x.png"}), + json!({"format": "audio", "bits": 8}), + json!({"format": "audio", "rate": 1}), + json!({"format": "sprite_sheet", "padding": 999}), + json!({"format": "html", "title": "x".repeat(300)}), + json!({"format": "html", "enabled": "yes"}), + json!({"enabled": true}), + json!({"profile": 5}), + json!({"profile": {"gif": {"scale": "big"}}}), + ] { + assert!(s.execute("publish.settings_set", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc.publish, before, "a refused change changes nothing"); + assert!(!s.is_dirty()); +} + +#[test] +fn the_plan_runs_each_exporter_with_its_options() { + let mut doc = sample::demo(); + let p = std::sync::Arc::make_mut(&mut doc.publish); + p.gif.enabled = true; + p.gif.scale = 0.25; + p.gif.looping = false; + p.gif.range = FrameRange { from: Some(1), to: Some(4) }; + p.sprite_sheet.enabled = true; + p.sprite_sheet.columns = 2; + p.svg.enabled = true; + p.svg.frame = 5; + let steps = plan(&doc, Some(Path::new("art/walk.anicraft")), None).unwrap(); + let order: Vec = steps.iter().map(|s| s.format).collect(); + assert_eq!(order, [PublishFormat::Html, PublishFormat::Gif, PublishFormat::SpriteSheet, PublishFormat::Svg], "in Publish's order"); + let gif = &steps[1]; + assert_eq!(gif.command, "file.export_gif"); + assert_eq!((gif.params["scale"].as_f64(), gif.params["loop"].as_bool(), gif.params["from"].as_u64(), gif.params["to"].as_u64(), gif.frames), (Some(0.25), Some(false), Some(1), Some(4), 4)); + assert_eq!(gif.params["path"], json!(Path::new("art").join("walk.gif").display().to_string())); + assert_eq!(steps[2].outputs, vec![Path::new("art").join("walk_sheet.png"), Path::new("art").join("walk_sheet.json")], "the sheet and its frame map"); + assert_eq!(steps[2].params["columns"], 2); + assert_eq!((steps[3].scene, steps[3].params["frame"].as_u64()), (0, Some(5))); + // Only some formats, when asked. + let some = plan(&doc, Some(Path::new("walk.anicraft")), Some(&[PublishFormat::Svg])).unwrap(); + assert_eq!(some.len(), 1); + // Two formats writing one file is refused, whatever the case. + std::sync::Arc::make_mut(&mut doc.publish).png.enabled = true; + std::sync::Arc::make_mut(&mut doc.publish).png.output = "{name}_SHEET.png".into(); + let err = plan(&doc, Some(Path::new("walk.anicraft")), None).unwrap_err(); + assert!(err.contains("Sprite sheet") && err.contains("PNG image"), "{err}"); + // Untitled, it asks to save first. + assert!(plan(&doc, None, None).unwrap_err().contains("save")); +} + +#[test] +fn publish_writes_every_format_and_reports_once() { + let (mut s, dir) = saved("all"); + for p in [ + json!({"format": "gif", "enabled": true, "scale": 0.1, "to": 3}), + json!({"format": "lottie", "enabled": true, "to": 3}), + json!({"format": "sprite_sheet", "enabled": true, "scale": 0.1, "to": 3, "columns": 2}), + json!({"format": "png_sequence", "enabled": true, "scale": 0.1, "to": 2, "output": "out/{name}_frames"}), + json!({"format": "png", "enabled": true, "scale": 0.1, "frame": 2}), + json!({"format": "svg", "enabled": true}), + json!({"format": "audio", "enabled": true}), + json!({"format": "video", "enabled": false}), + ] { + run(&mut s, "publish.settings_set", p); + } + let v = run(&mut s, "file.publish", json!({})); + let formats = v["formats"].as_array().unwrap(); + let status = |k: &str| formats.iter().find(|f| f["format"] == k).map(|f| f["status"].clone()).unwrap_or(Value::Null); + for k in ["html", "gif", "lottie", "sprite_sheet", "png_sequence", "png", "svg"] { + assert_eq!(status(k), "published", "{k}: {v}"); + } + assert_eq!(status("audio"), "skipped", "the demo has no sounds"); + assert_eq!(status("video"), Value::Null, "off formats don't run"); + assert_eq!((v["published"].as_u64(), v["skipped"].as_u64(), v["failed"].as_u64(), v["cancelled"].as_bool()), (Some(7), Some(1), Some(0), Some(false))); + let report = v["report"].as_str().unwrap(); + assert!(report.contains("Audio skipped: the movie has no sounds."), "{report}"); + // The files are there, made with each format's options. + for f in ["walk.html", "walk.gif", "walk.json", "walk_sheet.png", "walk_sheet.json", "walk.png", "walk.svg"] { + assert!(dir.join(f).is_file(), "{f}"); + } + let frames = std::fs::read_dir(dir.join("out").join("walk_frames")).unwrap().count(); + assert_eq!(frames, 3, "frames 1 to 3, in a folder made for them"); + let gif = std::fs::read(dir.join("walk.gif")).unwrap(); + let (w, h) = (u16::from_le_bytes([gif[6], gif[7]]), u16::from_le_bytes([gif[8], gif[9]])); + let view = anicraft_render::View::stage(&s.doc, 0.1); + assert_eq!((u32::from(w), u32::from(h)), (view.width, view.height), "the GIF's scale"); + let sheet: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("walk_sheet.json")).unwrap()).unwrap(); + assert_eq!(sheet["frames"].as_object().unwrap().len(), 4); + assert_eq!(v["files"].as_array().unwrap().len(), 8); + + // Publishing again replaces this session's own files without asking... + run(&mut s, "file.publish", json!({"formats": ["svg"]})); + // ...but another session (the next time the app starts) asks first. + run(&mut s, "file.save", json!({})); + let mut t = Session::default(); + run(&mut t, "file.open", json!({"path": dir.join("walk.anicraft").display().to_string()})); + let err = t.execute("file.publish", &json!({})).unwrap_err(); + assert!(matches!(err, EngineError::NeedsConfirmation(_)), "{err}"); + assert!(err.to_string().contains("walk.html"), "{err}"); + let c = t.confirmation("file.publish", &json!({})).unwrap(); + assert!(c.irreversible && c.message.contains("and 5 more"), "{}", c.message); + run(&mut t, "file.publish", json!({"confirm": true})); + assert!(t.confirmation("file.publish", &json!({})).is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn one_failing_format_doesnt_stop_the_others() { + let (mut s, dir) = saved("fail"); + run(&mut s, "publish.settings_set", json!({"format": "gif", "enabled": true, "scale": 8})); + run(&mut s, "publish.settings_set", json!({"format": "svg", "enabled": true})); + let v = run(&mut s, "file.publish", json!({})); + assert_eq!((v["published"].as_u64(), v["failed"].as_u64()), (Some(2), Some(1)), "{v}"); + assert!(v["report"].as_str().unwrap().starts_with("Animated GIF failed: that GIF would be too large"), "{v}"); + assert!(dir.join("walk.svg").is_file() && !dir.join("walk.gif").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn cancel_stops_cleanly() { + let (mut s, dir) = saved("cancel"); + for p in [json!({"format": "gif", "enabled": true, "scale": 0.1}), json!({"format": "svg", "enabled": true}), json!({"format": "png_sequence", "enabled": true, "scale": 0.1})] { + run(&mut s, "publish.settings_set", p); + } + // Cancelled after the first format: the rest never run. + let control = Arc::new(Control::default()); + let steps = plan(&s.doc, s.path.as_deref(), None).unwrap(); + let mut job = Publisher::new(s.doc.clone(), s.path.clone(), steps, control.clone()); + assert_eq!(job.current(), Some(PublishFormat::Html)); + assert_eq!(job.step().map(|o| o.status), Some(Status::Published)); + control.cancel(); + job.run_all(); + let r = job.report(); + assert!(job.done() && r.count(Status::Cancelled) == 3, "{:?}", r.to_json()); + assert!(dir.join("walk.html").is_file() && !dir.join("walk.gif").exists() && !dir.join("walk.svg").exists() && !dir.join("walk_frames").exists()); + assert_eq!(r.to_json()["cancelled"], true); + + // Cancelled inside an export: the GIF stops between frames and writes nothing. + let stop = Arc::new(Control::default()); + stop.cancel(); + s.job = Some(stop.clone()); + let gif = dir.join("inside.gif"); + assert!(matches!(s.execute("file.export_gif", &json!({"path": gif.display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(!gif.exists()); + let seq = dir.join("seq"); + assert!(matches!(s.execute("file.export_png_sequence", &json!({"dir": seq.display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(matches!(s.execute("file.export_sprite_sheet", &json!({"path": dir.join("s.png").display().to_string(), "scale": 0.1})), Err(EngineError::Cancelled))); + assert!(!dir.join("s.png").exists()); + // Progress counts frames made. + let watch = Arc::new(Control::default()); + s.job = Some(watch.clone()); + watch.begin(4); + run(&mut s, "file.export_gif", json!({"path": gif.display().to_string(), "scale": 0.1, "to": 3})); + assert_eq!(watch.progress(), (4, 4)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn publish_refuses_what_it_cant_run() { + let mut s = Session::new(sample::demo()); + assert!(s.execute("file.publish", &json!({})).unwrap_err().to_string().contains("save the document first")); + for bad in [json!({"formats": "gif"}), json!({"formats": ["gif", 3]}), json!({"formats": ["nope"]}), json!({"formats": [null]})] { + assert!(s.execute("file.publish", &bad).is_err(), "{bad}"); + assert!(s.confirmation("file.publish", &bad).is_none()); + } + let (mut t, dir) = saved("none"); + run(&mut t, "publish.settings_set", json!({"format": "html", "enabled": false})); + assert!(t.execute("file.publish", &json!({})).unwrap_err().to_string().contains("no format is on")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn in_a_browser_every_file_comes_back_and_several_make_one_zip() { + std::thread::spawn(|| { + vfs::use_memory(); + // Untitled: the browser has no folders, so it publishes as "Untitled". + let mut s = Session::new(sample::demo()); + for p in [json!({"format": "gif", "enabled": true, "scale": 0.1, "to": 2}), json!({"format": "video", "enabled": true}), json!({"format": "svg", "enabled": true, "output": "img/{name}.svg"})] { + run(&mut s, "publish.settings_set", p); + } + let v = run(&mut s, "file.publish", json!({})); + let video = v["formats"].as_array().unwrap().iter().find(|f| f["format"] == "video").unwrap().clone(); + assert_eq!(video["status"], "skipped"); + assert!(video["message"].as_str().unwrap().contains("web browser")); + let files = vfs::take_written(); + let names: Vec = files.iter().map(|(p, _)| p.to_string_lossy().replace('\\', "/")).collect(); + assert_eq!(names, ["Untitled.gif", "Untitled.html", "img/Untitled.svg"]); + let z = zip(&files).unwrap(); + // The end record says three entries; each name is in the archive with `/` between folders. + let end = z.len() - 22; + assert_eq!(&z[end..end + 4], &[0x50, 0x4b, 0x05, 0x06]); + assert_eq!(u16::from_le_bytes([z[end + 10], z[end + 11]]), 3); + assert!(z.windows(16).any(|w| w == b"img/Untitled.svg")); + // AniCraft's hardened ZIP reader (the .fla one) opens it, checks every CRC, and gets + // each file back exactly. + let archive = anicraft_xfl::zip::Archive::open(&z).unwrap(); + for (p, data) in &files { + let name = p.to_string_lossy().replace('\\', "/"); + assert_eq!(archive.read(&name).unwrap().as_ref(), Some(data), "{name}"); + } + let total: usize = files.iter().map(|(_, d)| d.len()).sum(); + assert!(z.len() > total && z.len() < total + 400, "stored, not compressed: {} for {total}", z.len()); + }) + .join() + .unwrap(); +} + + +#[test] +fn plugins_may_read_but_not_change_or_run_publishing() { + use crate::cmds_plugin::plugin_may_call; + assert!(plugin_may_call("publish.settings_get").is_ok()); + assert!(plugin_may_call("publish.settings_set").is_err()); + assert!(plugin_may_call("file.publish").is_err()); +} diff --git a/crates/engine/src/rawpoints_tests.rs b/crates/engine/src/rawpoints_tests.rs new file mode 100644 index 00000000..d0aee124 --- /dev/null +++ b/crates/engine/src/rawpoints_tests.rs @@ -0,0 +1,330 @@ +//! Adding and deleting raw anchors, smooth handle pairs, Make Smooth / Corner and snapping while +//! drawing (ADR 0045), through the commands. + +use crate::Session; +use anicraft_doc::{Element, ElementKind}; +use anicraft_geom::raw::{self as rawgeom}; +use anicraft_geom::walk::cubic_point; +use anicraft_geom::Vec2; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn raw_session() -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + s +} + +fn raw(s: &Session) -> Vec> { + s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect() +} + +fn is_fill(e: &Element) -> bool { + matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some()) +} + +fn all_ids(s: &Session) -> Vec { + raw(s).iter().map(|e| e.id).collect() +} + +fn anchors(s: &Session) -> Vec { + s.raw_points(&all_ids(s)).anchors +} + +fn has(points: &[Vec2], p: (f32, f32)) -> bool { + points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 0.3) +} + +fn area(e: &Element) -> f32 { + let ElementKind::Shape(sh) = &e.kind else { return 0.0 }; + sh.path.flatten(&e.transform, 0.01).iter().map(|pl| pl.points.iter().zip(pl.points.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b)).sum::() * 0.5).sum::().abs() +} + +/// Every shape's anchors in stage space. +fn shape_anchors(e: &Element) -> Vec { + match &e.kind { + ElementKind::Shape(sh) => sh.path.editable_anchors().into_iter().map(|(_, q)| e.transform.apply(q)).collect(), + _ => Vec::new(), + } +} + +/// Largest distance from points of the curve `c` (stage space) to the shape's outline. +fn off_outline(e: &Element, c: &rawgeom::Cubic) -> f32 { + let ElementKind::Shape(sh) = &e.kind else { return f32::INFINITY }; + (0..=20).map(|i| sh.path.distance_to_edge(cubic_point(c, i as f32 / 20.0), &e.transform)).fold(0.0, f32::max) +} + +/// A raw arc (a fill under it and its outline): `M0 100 C0 0 200 0 200 100 Z`. +fn arc(s: &mut Session) -> rawgeom::Cubic { + run(s, "draw.path", json!({"d": "M0 100 C0 0 200 0 200 100 Z", "fill": "#ff0000", "stroke": "#000000"})); + run(s, "edit.deselect", json!({})); + [Vec2::new(0.0, 100.0), Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), Vec2::new(200.0, 100.0)] +} + +#[test] +fn an_added_point_is_shared_by_every_shape_on_the_edge_and_the_curve_keeps_its_shape() { + let mut s = raw_session(); + let c = arc(&mut s); + let before = anchors(&s).len(); + // How far the outlines are from the drawn curve (flattening): adding may not change it. + let was: Vec<(anicraft_doc::ElementId, f32)> = raw(&s).iter().map(|e| (e.id, off_outline(e, &c))).collect(); + let top = cubic_point(&c, 0.5); + let v = run(&mut s, "raw.add_point", json!({"x": top.x, "y": top.y + 1.0, "slop": 4})); + let at = Vec2::new(v["x"].as_f64().unwrap_or(0.0) as f32, v["y"].as_f64().unwrap_or(0.0) as f32); + assert!(at.distance(top) < 0.05, "on the curve: {at:?} vs {top:?}"); + assert_eq!(v["changed"].as_array().map(Vec::len), Some(2), "the fill and its outline: {v}"); + assert_eq!(anchors(&s).len(), before + 1, "listed once"); + let changed: Vec = v["changed"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + for e in raw(&s).into_iter().filter(|e| changed.contains(&e.id.0)) { + assert!(has(&shape_anchors(&e), (at.x, at.y)), "{} lacks the point", e.id.0); + // Analytic: the old curve still lies on every shape's outline, as closely as before. + let w = was.iter().find(|x| x.0 == e.id).map_or(0.0, |x| x.1); + assert!(off_outline(&e, &c) <= w + 1e-3 && w < 0.25, "the curve moved: {} (was {w})", off_outline(&e, &c)); + } + // One undo step; a second point at the same place is refused. + assert!(s.can_undo()); + assert!(s.execute("raw.add_point", &json!({"x": at.x, "y": at.y})).is_err()); + assert!(s.execute("raw.add_point", &json!({"x": 900, "y": 900})).is_err(), "nothing there"); + // Deleting it gives the curve back, in both shapes. + run(&mut s, "raw.delete_points", json!({"points": [[at.x, at.y]]})); + assert_eq!(anchors(&s).len(), before); + let on_curve: Vec> = raw(&s).into_iter().filter(|e| off_outline(e, &c) < 0.3).collect(); + assert_eq!(on_curve.len(), 2, "the fill and the arc's line still follow the curve"); +} + +#[test] +fn deleting_a_corner_rejoins_the_fill_and_its_outline() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + let steps = s.history_len(); + let v = run(&mut s, "raw.delete_points", json!({"points": [[0, 0]]})); + assert_eq!(v["deleted"], json!(1), "{v}"); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + // A triangle of half the area, outlined all round. + let fill: Vec> = raw(&s).into_iter().filter(|e| is_fill(e)).collect(); + assert_eq!(fill.len(), 1); + assert!((area(&fill[0]) - 4000.0).abs() < 1.0, "{}", area(&fill[0])); + let pts = anchors(&s); + assert_eq!(pts.len(), 3, "{pts:?}"); + assert!(!has(&pts, (0.0, 0.0))); + // Connectivity: every shape's anchors are shared with another shape. + let all = raw(&s); + for e in &all { + for p in shape_anchors(e) { + let n = all.iter().filter(|o| o.id != e.id && has(&shape_anchors(o), (p.x, p.y))).count(); + assert!(n >= 1, "{p:?} of {} is on no other shape", e.id.0); + } + } + // The diagonal is stroked: some outline runs from (0, 80) to (100, 0). + let diag = rawgeom::Seg::line(Vec2::new(0.0, 80.0), Vec2::new(100.0, 0.0)).c; + assert!(all.iter().filter(|e| !is_fill(e)).any(|e| off_outline(e, &diag) < 0.05), "no line on the new edge"); + s.undo().unwrap_or_default(); + assert_eq!(anchors(&s).len(), 4); +} + +#[test] +fn deleting_the_last_points_of_a_line_removes_it_and_junctions_stay() { + let mut s = raw_session(); + run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0, "stroke": "#000000"})); + let v = run(&mut s, "raw.delete_points", json!({"points": [[100, 0]]})); + assert_eq!(v["removed"].as_array().map(Vec::len), Some(1), "a one-segment line goes: {v}"); + assert!(raw(&s).is_empty()); + assert!(s.selection.is_empty(), "nothing selected that is gone"); + // A T: the point where the stem stands on the bar joins three edges. + run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0, "stroke": "#000000"})); + run(&mut s, "draw.line", json!({"x0": 50, "y0": 0, "x1": 50, "y1": 60, "stroke": "#000000"})); + let n = raw(&s).len(); + let e = s.execute("raw.delete_points", &json!({"points": [[50, 0]]})); + assert!(e.is_err_and(|e| e.to_string().contains("three or more"))); + assert_eq!(raw(&s).len(), n); + // The stem's free end shortens nothing else. + run(&mut s, "raw.delete_points", json!({"points": [[50, 60]]})); + assert!(!has(&anchors(&s), (50.0, 60.0))); + assert!(has(&anchors(&s), (0.0, 0.0)) && has(&anchors(&s), (100.0, 0.0))); + assert!(s.execute("raw.delete_points", &json!({"points": []})).is_err()); + assert!(s.execute("raw.delete_points", &json!({"points": [[500, 500]]})).is_err()); +} + +/// A raw S-curve stroke through (100, 0) with a smooth anchor there. +fn s_curve(s: &mut Session) { + run(s, "draw.path", json!({"d": "M0 0 C0 -50 60 -50 100 0 C140 50 200 50 200 0", "stroke": "#000000", "fill": null})); + run(s, "edit.deselect", json!({})); +} + +/// The handles at `a` listed by `raw.points`. +fn handles_at(s: &Session, a: Vec2) -> Vec { + s.raw_points(&all_ids(s)).handles.into_iter().filter(|h| h.anchor.distance(a) < 0.3).collect() +} + +#[test] +fn dragging_a_smooth_anchors_handle_keeps_the_other_opposite_and_alt_breaks_it() { + let mut s = raw_session(); + s_curve(&mut s); + let a = Vec2::new(100.0, 0.0); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2, "{hs:?}"); + let (h, k) = (hs[0], hs[1]); + let len_k = k.at.distance(a); + run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 0, "dy": 30})); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2); + let (moved, other) = if hs[0].at.distance(h.at + Vec2::new(0.0, 30.0)) < 0.5 { (hs[0], hs[1]) } else { (hs[1], hs[0]) }; + assert!(moved.at.distance(h.at + Vec2::new(0.0, 30.0)) < 0.5, "{hs:?}"); + // Colinear: on one line through the anchor, opposite, the other's length kept. + assert!(rawgeom::smooth_at(a, moved.at, other.at), "{moved:?} {other:?}"); + assert!((moved.at - a).normalized().cross((other.at - a).normalized()).abs() < 1e-3); + assert!((other.at.distance(a) - len_k).abs() < 0.3); + // Alt (smooth: false) moves the handle alone: a corner. + let before = other.at; + run(&mut s, "raw.move_handle", json!({"id": moved.id.0, "cmd": moved.cmd, "slot": moved.slot, "dx": 30, "dy": 0, "smooth": false})); + let hs = handles_at(&s, a); + assert!(hs.iter().any(|x| x.at.distance(before) < 0.3), "the other stays: {hs:?}"); + assert!(!rawgeom::smooth_at(a, hs[0].at, hs[1].at)); +} + +#[test] +fn make_corner_and_make_smooth_on_raw_anchors() { + let mut s = raw_session(); + s_curve(&mut s); + let a = Vec2::new(100.0, 0.0); + let v = run(&mut s, "raw.convert_points", json!({"points": [[a.x, a.y]], "smooth": false})); + assert_eq!(v["converted"], json!(1), "{v}"); + assert!(handles_at(&s, a).is_empty(), "the handles are drawn in"); + let v = run(&mut s, "raw.convert_points", json!({"points": [[a.x, a.y]], "smooth": true})); + assert_eq!(v["converted"], json!(1), "{v}"); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2, "{hs:?}"); + assert!(rawgeom::smooth_at(a, hs[0].at, hs[1].at)); + // Smooth on a fill's corner: the fill and both sides it has there follow. + run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "raw.convert_points", json!({"points": [[300, 0]], "smooth": true})); + assert_eq!(v["converted"], json!(1)); + let fill = raw(&s).into_iter().find(|e| is_fill(e)).unwrap_or_else(|| panic!("a fill")); + assert!(area(&fill) > 8000.0, "the corner rounds out: {}", area(&fill)); + for e in raw(&s).iter().filter(|e| !is_fill(e) && e.transform.apply(Vec2::ZERO).x > 250.0) { + let ElementKind::Shape(sh) = &e.kind else { continue }; + let ElementKind::Shape(fs) = &fill.kind else { continue }; + for pl in sh.path.flatten(&e.transform, 0.05) { + for p in pl.points { + assert!(fs.path.distance_to_edge(p, &fill.transform) < 0.3, "{p:?} off the fill's edge"); + } + } + } +} + +#[test] +fn drawing_snaps_to_anchors_then_lines_while_snap_to_objects_is_on() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "draw.snap", json!({"x": 104, "y": 3, "snap": 10})); + assert_eq!(v["snapped"]["to"], json!("point"), "{v}"); + assert_eq!((v["x"].as_f64(), v["y"].as_f64()), (Some(100.0), Some(0.0))); + let v = run(&mut s, "draw.snap", json!({"x": 50, "y": 84, "snap": 10})); + assert_eq!(v["snapped"]["to"], json!("line"), "{v}"); + assert!((v["y"].as_f64().unwrap_or(0.0) - 80.0).abs() < 1e-3 && (v["x"].as_f64().unwrap_or(0.0) - 50.0).abs() < 1e-3); + let v = run(&mut s, "draw.snap", json!({"x": 300, "y": 300, "snap": 10})); + assert!(v["snapped"].is_null()); + // Off, nothing snaps. + run(&mut s, "draw.snap_to_objects", json!({"on": false})); + let v = run(&mut s, "draw.snap", json!({"x": 104, "y": 3, "snap": 10})); + assert!(v["snapped"].is_null() && v["x"] == json!(104.0)); + // A line drawn from a snapped point shares the rectangle's corner. + run(&mut s, "draw.snap_to_objects", json!({"on": true})); + let a = run(&mut s, "draw.snap", json!({"x": 98, "y": 78, "snap": 10})); + run(&mut s, "draw.line", json!({"x0": a["x"], "y0": a["y"], "x1": 200, "y1": 200, "stroke": "#000000"})); + assert!(has(&anchors(&s), (100.0, 80.0)) && anchors(&s).len() == 5, "{:?}", anchors(&s)); +} + +#[test] +fn an_object_paths_smooth_anchor_keeps_its_handles_opposite() { + let mut s = Session::new(anicraft_doc::Document::default()); + let v = run(&mut s, "draw.path", json!({"d": "M0 0 C0 -50 60 -50 100 0 C140 50 200 50 200 0", "stroke": "#000000", "fill": null})); + let id = v["element"].as_u64().unwrap_or(0); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + let p = sh.path.clone(); + // The in-handle of anchor 1 (C2 of command 1) moves; command 2's C1 turns with it. + run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 2]], "dx": 0, "dy": 25})); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + let (a, h, k) = (sh.path.point(1, 0), sh.path.point(1, 2), sh.path.point(2, 1)); + let (Some(a), Some(h), Some(k)) = (a, h, k) else { panic!("points") }; + assert!(rawgeom::smooth_at(a, h, k), "{a:?} {h:?} {k:?}"); + assert!((k.distance(a) - p.point(2, 1).map_or(0.0, |q| q.distance(a))).abs() < 1e-3, "length kept"); + run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 2]], "dx": 30, "dy": 0, "smooth": false})); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + assert_eq!(sh.path.point(2, 1), Some(k), "Alt moves the handle alone"); +} + +#[test] +fn raw_points_timings() { + // ADR 0042's drawing: 12 × 12 outlined, rounded squares and a line across every row. + let mut s = raw_session(); + for i in 0..12 { + for j in 0..12 { + run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000", "radius": 6})); + } + run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"})); + } + run(&mut s, "edit.deselect", json!({})); + let n = s.visible_elements().len(); + let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let v = run(&mut s, "raw.add_point", json!({"x": 320, "y": 300})); + let add = ms(t); + let at = [v["x"].as_f64().unwrap_or(0.0), v["y"].as_f64().unwrap_or(0.0)]; + let t = std::time::Instant::now(); + run(&mut s, "raw.delete_points", json!({"points": [at]})); + let delete = ms(t); + let t = std::time::Instant::now(); + run(&mut s, "raw.convert_points", json!({"points": [[306, 300]], "smooth": true})); + let smooth = ms(t); + let h = handles_at(&s, Vec2::new(306.0, 300.0)).first().copied().unwrap_or_else(|| panic!("handles after Make Smooth")); + s.begin_gesture("Move Handle"); + let t = std::time::Instant::now(); + run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 1, "dy": 1, "merge": false})); + let pair = ms(t); + s.end_gesture(); + let t = std::time::Instant::now(); + for k in 0..100 { + let _ = s.execute("draw.snap", &json!({"x": 3 + k * 6, "y": 303, "snap": 10})); + } + let snap = ms(t) / 100.0; + // Inside a symbol: the whole drawing converted, opened in place, and its stage picture. + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Grid"})); + let t = std::time::Instant::now(); + run(&mut s, "symbol.edit", json!({})); + let open = ms(t); + let t = std::time::Instant::now(); + let pic = s.stage_picture(); + let picture = ms(t); + let a = anchors(&s).first().copied().unwrap_or_else(|| panic!("anchors inside")); + let t = std::time::Instant::now(); + run(&mut s, "raw.move_point", json!({"x": a.x, "y": a.y, "to_x": a.x - 5.0, "to_y": a.y})); + let inside = ms(t); + eprintln!("{n} raw shapes; add point {add:.2} ms, delete point {delete:.2} ms, make smooth {smooth:.2} ms, smooth handle frame {pair:.2} ms, draw snap {snap:.3} ms; inside a symbol: open {open:.2} ms, stage picture {picture:.2} ms (frame {}), point move {inside:.2} ms", pic.frame); +} + +#[test] +fn point_edits_keep_a_dashed_lines_style() { + let mut s = raw_session(); + // A dashed, butt-capped, mitred zigzag (ADR 0046). + run(&mut s, "draw.path", json!({"d": "M0 0 L50 40 L100 0 L150 40", "stroke": "#000000", "fill": null, "stroke_width": 2, "cap": "none", "join": "miter", "dash": [6, 3]})); + let styled = |s: &Session| { + raw(s).iter().all(|e| match &e.kind { + ElementKind::Shape(sh) => sh.stroke.as_ref().is_some_and(|st| st.style.dash == anicraft_doc::Dash::dashed(6.0, 3.0) && st.style.cap == anicraft_doc::Cap::Butt && st.style.join == anicraft_doc::Join::Miter), + _ => false, + }) + }; + run(&mut s, "raw.add_point", json!({"x": 25, "y": 20})); + run(&mut s, "raw.delete_points", json!({"points": [[50, 40]]})); + run(&mut s, "raw.convert_points", json!({"points": [[100, 0]], "smooth": true})); + assert!(!raw(&s).is_empty() && styled(&s), "every piece keeps the line's style"); +} diff --git a/crates/engine/src/rawsub_tests.rs b/crates/engine/src/rawsub_tests.rs index e3a49050..7442dca4 100644 --- a/crates/engine/src/rawsub_tests.rs +++ b/crates/engine/src/rawsub_tests.rs @@ -291,13 +291,14 @@ fn a_pasted_raw_shape_cuts_what_it_lands_on() { } fn linear() -> Paint { - Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(200.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }] } + Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }]) } #[test] fn gradient_fills_take_part_in_the_merge() { let mut s = raw_session(); s.style.fill_paint = Some(linear()); + s.style.lock_fill = true; run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null})); assert_eq!(fills(&s).len(), 1, "raw, not an object"); // A line across cuts it in two; each half shows its part of the gradient where it was. @@ -321,11 +322,11 @@ fn gradient_fills_take_part_in_the_merge() { run(&mut s, "draw.rect", json!({"x": 50, "y": 25, "w": 50, "h": 50, "fill": "#00ff00", "stroke": null})); let g = fills(&s).into_iter().find(|e| fill_color(e).is_none()).unwrap(); assert!((area(&g) - (20_000.0 - 2_500.0)).abs() < 1.0); - // A width profile still makes an object. + // A width profile is raw too (ADR 0093: the merge carries it into each piece). let mut t = raw_session(); t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth); run(&mut t, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0})); - assert!(raw(&t).is_empty()); + assert_eq!(raw(&t).len(), 1); let _ = Affine::IDENTITY; } @@ -383,6 +384,7 @@ fn subselection_timings() { fn the_eraser_takes_gradient_fills_too() { let mut s = raw_session(); s.style.fill_paint = Some(linear()); + s.style.lock_fill = true; run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null})); let before: f32 = fills(&s).iter().map(|e| area(e)).sum(); run(&mut s, "draw.erase", json!({"points": [[100, -20], [100, 120]], "size": 20})); diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 946ec440..5053f4a3 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -358,7 +358,7 @@ impl SessionLock { // ----- background writer ------------------------------------------------------------------------ enum Job { - Write { doc: Document, meta: Box, tag: u64 }, + Write { doc: Box, meta: Box, tag: u64 }, Clear { tag: u64 }, } @@ -412,7 +412,7 @@ impl Autosaver { /// Queues a write of `doc` (a cheap snapshot). Returns its tag. pub fn write(&mut self, doc: Document, original: Option<&Path>) -> u64 { let meta = RecoveryMeta::describe(self.id(), &doc, original); - self.send(|tag| Job::Write { doc, meta: Box::new(meta), tag }) + self.send(|tag| Job::Write { doc: Box::new(doc), meta: Box::new(meta), tag }) } /// Queues removal of this session's recovery copy (after a save, or when the work is gone). diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs index db6e1a17..01014d59 100644 --- a/crates/engine/src/render_service.rs +++ b/crates/engine/src/render_service.rs @@ -14,6 +14,7 @@ //! keep its pictures on the GPU ([`Raster::Native`], ADR 0029): the cache then holds them, under //! a budget of their own, and only the shell knows what they are. +use crate::editing::Front; use crate::history::StateId; use crate::onion::OnionSkin; use anicraft_doc::{DisplayList, Document, evaluate_scene, evaluate_scene_camera}; @@ -41,6 +42,9 @@ pub struct FrameJob { /// Seen through the scene's camera (View › Preview Through Camera, ADR 0027): what the /// movie shows, rather than the stage as edited. pub camera: bool, + /// A symbol open in place, in front of the picture (ADR 0045): onion skin composes its own + /// frames (ADR 0051). Set with [`FrameJob::inside`]. + pub front: Option>, } impl FrameJob { @@ -58,6 +62,81 @@ impl FrameJob { } self } + + /// The same job for a stage picture whose top layer is the open symbol `front` (from + /// [`crate::editing::StagePicture::front`]): onion skin and Edit Multiple Frames then compose + /// the symbol's frames, not the picture's one frame. Keyed apart from the plain job. + pub fn inside(mut self, front: Option>) -> FrameJob { + if let Some(f) = front { + if self.onion.is_some() { + let mix = |k: u64| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (k, "front", f.layer.0).hash(&mut h); + h.finish() + }; + self.key = mix(self.key); + self.scene = mix(self.scene); + } + self.front = Some(f); + } + self + } + + /// What the job draws: its frame with what its onion settings add (ADR 0047), on the open + /// symbol's own timeline when there is one (ADR 0051). + pub fn display_list(&self) -> DisplayList { + let onion = self.onion.as_ref().filter(|o| o.shows()); + match (&self.front, onion) { + (Some(front), Some(skin)) => display_list_inside(&self.doc, self.frame, front, skin), + _ => display_list_for(&self.doc, self.frame, self.onion.as_ref(), self.camera), + } + } +} + +/// A stage picture's frame with the open symbol in front composed by `skin`: the timelines around +/// it as they are, then the symbol's frames, each layer's onion frames under its artwork. With +/// onion skin on (not Edit Multiple Frames), the timeline the symbol was opened from shows its +/// own onion frames too, dimmed with it (ADR 0061). +pub fn display_list_inside(doc: &Document, frame: u32, front: &Front, skin: &OnionSkin) -> DisplayList { + let (scene, local) = doc.locate(frame); + let tl = &front.timeline; + let parent = front.parent.as_ref().filter(|_| skin.ghosts && !skin.edit_multiple); + let mut dl = DisplayList::default(); + // Back to front: the picture's layers from the bottom up, each its own timeline. + for l in doc.timeline(scene).layers.iter().rev() { + if l.id == front.layer { + dl.append(crate::onion::compose_timeline(tl, front.frame, Some(skin), |f| anicraft_doc::evaluate_timeline_at(doc, tl, f, front.at))); + } else if let Some(p) = parent.filter(|p| p.layer == l.id) { + dl.append(parent_onion(doc, p, front, skin)); + } else { + dl.append(anicraft_doc::evaluate_timeline(doc, &anicraft_doc::Timeline { layers: vec![l.clone()] }, local)); + } + } + dl +} + +/// The timeline around an open symbol with its onion frames, all at its dim opacity. Markers that +/// follow the playhead reach as many frames from the parent's frame; anchored ones (which name +/// the symbol's frames) as far as they reach from the symbol's playhead. +fn parent_onion(doc: &Document, p: &crate::editing::Around, front: &Front, skin: &OnionSkin) -> DisplayList { + let mut own = *skin; + if skin.anchored() { + let (first, last) = skin.range(front.frame, front.timeline.frame_count()); + own.markers = crate::onion::Markers::Relative { before: front.frame.saturating_sub(first), after: last.saturating_sub(front.frame) }; + } + let composed = crate::onion::compose_timeline(&p.timeline, p.frame, Some(&own), |f| anicraft_doc::evaluate_timeline_at(doc, &p.timeline, f, p.at)); + // It fades as one, as the dimmed instance it replaces does: everything in a group at `dim`. + let alpha = if p.dim.is_finite() { p.dim.clamp(0.0, 1.0) } else { 1.0 }; + let mut dl = DisplayList::default(); + dl.groups.push(anicraft_doc::Group { parent: None, alpha, blend: Default::default(), filters: Arc::from(Vec::new()), clip: None }); + dl.append(composed); + for g in dl.groups.iter_mut().skip(1) { + g.parent = Some(g.parent.unwrap_or(0)); + } + for it in dl.items.iter_mut().filter(|i| i.masks.is_none()) { + it.group = Some(it.group.unwrap_or(0)); + } + dl } /// A finished image: premultiplied RGBA8, ready for a texture upload, or (`native`) an image @@ -128,7 +207,7 @@ pub fn frame_key(state: StateId, frame: u32, view: &View, onion: Option<&OnionSk /// A job whose `scene` is derived from the same inputs as its key. pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob { let onion = onion.filter(|o| o.shows()).copied(); - FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false } + FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false, front: None } } /// A job for rasterizer `raster` (from [`RenderService::raster_id`]; 0 is the CPU oracle, and @@ -192,7 +271,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>) /// Renders a job synchronously, evaluating its scene. pub fn render_job(job: &FrameJob) -> FrameImage { - render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion.as_ref(), job.camera)) + render_job_with(job, &job.display_list()) } /// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel. @@ -204,7 +283,7 @@ pub fn render_batch(jobs: &[FrameJob]) -> Vec { fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec { let mut scenes: HashMap> = HashMap::new(); for j in jobs { - scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera))); + scenes.entry(j.scene).or_insert_with(|| Arc::new(j.display_list())); } jobs.par_iter() .map(|j| { @@ -212,7 +291,7 @@ fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec { let raster = slot.raster.as_ref().filter(|_| j.raster != 0 && j.raster == slot.id); match scenes.get(&j.scene) { Some(dl) => render_job_by(j, dl, raster), - None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera), raster), + None => render_job_by(j, &j.display_list(), raster), } }) .collect() diff --git a/crates/engine/src/retime_tests.rs b/crates/engine/src/retime_tests.rs new file mode 100644 index 00000000..0c1ef984 --- /dev/null +++ b/crates/engine/src/retime_tests.rs @@ -0,0 +1,211 @@ +//! Retiming through the command registry (ADR 0083): property keys moved in time, span +//! stretching, whole spans moved and copied, Split and Join Motion. + +use super::*; +use anicraft_doc::Property; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A square at (5, 5) with a 24-frame motion tween: X keyed 5 → 105 at frame 12, and Y +/// 5 → 55 at frame 23. +fn tweened() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.create_motion_tween", json!({})); + s.set_frame(12); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 0})); + s.set_frame(23); + run(&mut s, "element.translate", json!({"dx": 0, "dy": 50})); + s +} + +fn pos(s: &mut Session, frame: u32) -> (f32, f32) { + s.set_frame(frame); + let t = s.visible_elements().first().map(|e| e.transform.translation()).unwrap_or_default(); + (t.x, t.y) +} + +fn keys(s: &Session, p: Property) -> Vec<(u32, f32)> { + let l = s.active_layer().expect("layer"); + let k = l.keyframes.first().expect("key"); + k.motion.as_ref().and_then(|m| m.track(p)).map(|t| t.keys.iter().map(|k| (k.frame, k.value)).collect()).unwrap_or_default() +} + +fn spans(s: &Session) -> Vec<(u32, u32, bool)> { + s.active_layer().expect("layer").keyframes.iter().map(|k| (k.start, k.duration, k.motion.is_some())).collect() +} + +#[test] +fn a_moved_key_keeps_its_value_at_its_new_frame() { + let mut s = tweened(); + let steps = s.history_len(); + let v = run(&mut s, "motion.move_keys", json!({"keys": [{"property": "x", "frame": 12}], "by": 4})); + assert_eq!(v["by"], 4); + assert_eq!(v["keys"], json!([{"property": "x", "frame": 16}])); + assert_eq!(keys(&s, Property::X), vec![(0, 5.0), (16, 105.0)]); + assert_eq!(pos(&mut s, 16).0, 105.0); + assert_eq!(pos(&mut s, 8).0, 55.0, "halfway to the key that is now at 16"); + assert_eq!(s.history_len(), steps + 1); + // Past the end of the span or a neighbour it stops: never crosses or lands on one. + let v = run(&mut s, "motion.move_keys", json!({"keys": [{"property": "x", "frame": 16}], "by": 100})); + assert_eq!(v["by"], 7, "the span's last frame is 23"); + let v = run(&mut s, "motion.move_keys", json!({"keys": [{"property": "x", "frame": 23}], "by": -100})); + assert_eq!(v["by"], -22, "the key at frame 0 stays first"); + // A key that isn't there is an error, not a silent no-op. + assert!(s.execute("motion.move_keys", &json!({"keys": [{"property": "y", "frame": 5}], "by": 1})).is_err()); + assert!(s.execute("motion.move_keys", &json!({"keys": [], "by": 1})).is_err()); +} + +#[test] +fn a_drag_is_one_undo_step() { + let mut s = tweened(); + let steps = s.history_len(); + s.begin_gesture("Move property keyframes"); + for _ in 0..5 { + run(&mut s, "motion.move_keys", json!({"keys": [{"property": "x", "frame": 12}, {"property": "y", "frame": 23}], "by": 0})); + } + let mut at = (12, 23); + for _ in 0..3 { + let v = run(&mut s, "motion.move_keys", json!({"keys": [{"property": "x", "frame": at.0}, {"property": "y", "frame": at.1}], "by": -1})); + at = (v["keys"][0]["frame"].as_u64().unwrap_or(0) as u32, v["keys"][1]["frame"].as_u64().unwrap_or(0) as u32); + } + s.end_gesture(); + assert_eq!(at, (9, 20)); + assert_eq!(s.history_len(), steps + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(keys(&s, Property::X), vec![(0, 5.0), (12, 105.0)]); +} + +#[test] +fn stretching_a_span_scales_its_keys_in_proportion() { + let mut s = tweened(); + run(&mut s, "timeline.insert_blank_keyframe", json!({"frame": 24})); + run(&mut s, "timeline.insert_frame", json!({"frame": 24, "count": 4})); + let before: Vec<(f32, f32)> = (0..24).map(|f| pos(&mut s, f)).collect(); + // 24 frames (0..=23) to 47 (0..=46): every key's offset doubles. + let v = run(&mut s, "timeline.resize_span", json!({"frame": 0, "frames": 47})); + assert_eq!(v["scaled"], true); + assert_eq!(keys(&s, Property::X), vec![(0, 5.0), (24, 105.0)]); + assert_eq!(keys(&s, Property::Y), vec![(0, 5.0), (46, 55.0)]); + for (f, want) in before.iter().enumerate() { + assert_eq!(pos(&mut s, 2 * f as u32), *want, "frame {}", 2 * f); + } + // Later frames moved with the end. + assert_eq!(spans(&s), vec![(0, 47, true), (47, 5, false)]); + // Shorter again, and back where it was. + run(&mut s, "timeline.resize_span", json!({"frame": 0, "frames": 24})); + assert_eq!(keys(&s, Property::X), vec![(0, 5.0), (12, 105.0)]); + assert_eq!(spans(&s), vec![(0, 24, true), (24, 5, false)]); + // Keeping the keys where they are (Shift-drag). + let v = run(&mut s, "timeline.resize_span", json!({"frame": 0, "frames": 30, "scale_keys": false})); + assert_eq!(v["scaled"], false); + assert_eq!(keys(&s, Property::X), vec![(0, 5.0), (12, 105.0)]); + assert!(s.execute("timeline.resize_span", &json!({"frame": 0, "frames": 0})).is_err()); +} + +#[test] +fn classic_and_shape_tween_spans_stretch_too() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_keyframe", json!({"frame": 10})); + run(&mut s, "timeline.create_tween", json!({"frame": 0})); + s.set_frame(10); + run(&mut s, "element.translate", json!({"dx": 100, "dy": 0})); + run(&mut s, "timeline.resize_span", json!({"frame": 0, "frames": 20})); + assert_eq!(spans(&s), vec![(0, 20, false), (20, 1, false)]); + assert_eq!(pos(&mut s, 10).0, 55.0, "halfway through the longer tween"); + run(&mut s, "timeline.create_shape_tween", json!({"frame": 0})); + run(&mut s, "timeline.resize_span", json!({"frame": 0, "frames": 5})); + assert_eq!(spans(&s), vec![(0, 5, false), (5, 1, false)]); +} + +#[test] +fn a_whole_span_moves_and_alt_drag_copies_it() { + let mut s = tweened(); + let before: Vec<(f32, f32)> = (0..24).map(|f| pos(&mut s, f)).collect(); + run(&mut s, "timeline.move_spans", json!({"from": 0, "to": 23, "by": 10})); + // It keeps its length and its motion; the frames it left are empty. + assert_eq!(spans(&s), vec![(0, 10, false), (10, 24, true)]); + for (f, want) in before.iter().enumerate() { + assert_eq!(pos(&mut s, 10 + f as u32), *want); + } + run(&mut s, "timeline.move_spans", json!({"from": 10, "to": 33, "by": 30, "copy": true})); + // Past the layer's end: the frames between are a gap (empty). + assert_eq!(spans(&s), vec![(0, 10, false), (10, 24, true), (40, 24, true)]); + for (f, want) in before.iter().enumerate() { + assert_eq!(pos(&mut s, 40 + f as u32), *want); + } + assert!(s.execute("timeline.move_spans", &json!({"from": 10, "to": 33, "by": 0, "copy": true})).is_err()); +} + +#[test] +fn split_then_join_motion_is_a_round_trip() { + let mut s = tweened(); + let before: Vec<(f32, f32)> = (0..24).map(|f| pos(&mut s, f)).collect(); + let original = s.active_layer().map(|l| l.keyframes.clone()).unwrap_or_default(); + let v = run(&mut s, "motion.split", json!({"frame": 8})); + assert_eq!(v, json!({"first": 0, "second": 8})); + assert_eq!(spans(&s), vec![(0, 8, true), (8, 16, true)]); + for (f, want) in before.iter().enumerate() { + let (x, y) = pos(&mut s, f as u32); + assert!((x - want.0).abs() < 1e-3 && (y - want.1).abs() < 1e-3, "split, frame {f}: {x},{y} vs {want:?}"); + } + let v = run(&mut s, "motion.join", json!({"frame": 0})); + assert_eq!(v["frames"], 24); + let now = s.active_layer().map(|l| l.keyframes.clone()).unwrap_or_default(); + assert_eq!(now, original, "the very tween comes back"); + // On the first frame there is nothing to split; elsewhere than a motion tween neither. + assert!(s.execute("motion.split", &json!({"frame": 0})).is_err()); + assert!(s.execute("motion.join", &json!({"frame": 0})).is_err(), "nothing after it to join"); +} + +#[test] +fn joining_two_tweens_of_one_object_keeps_every_frame() { + let mut s = tweened(); + run(&mut s, "motion.split", json!({"frame": 8})); + // The second half changes on its own, so it is no longer the first's continuation. + s.set_frame(20); + run(&mut s, "modify.rotate_cw", json!({})); + let before: Vec<(f32, f32)> = (0..24).map(|f| pos(&mut s, f)).collect(); + let turned: Vec = (0..24).map(|f| { + s.set_frame(f); + s.visible_elements().first().map_or(0.0, |e| e.transform.decompose().rotation) + }).collect(); + run(&mut s, "motion.join", json!({"frame": 3})); + assert_eq!(spans(&s), vec![(0, 24, true)]); + for f in 0..24u32 { + let (x, y) = pos(&mut s, f); + let want = before[f as usize]; + assert!((x - want.0).abs() < 1e-2 && (y - want.1).abs() < 1e-2, "frame {f}: {x},{y} vs {want:?}"); + let r = s.visible_elements().first().map_or(0.0, |e| e.transform.decompose().rotation); + assert!((r - turned[f as usize]).abs() < 1e-3, "frame {f}: {r} vs {}", turned[f as usize]); + } +} + +#[test] +fn join_motion_refuses_what_it_cannot_keep() { + let mut s = tweened(); + run(&mut s, "motion.split", json!({"frame": 8})); + // Actions on the second key would be dropped. + let k = s.layer_mut(None).ok().and_then(|l| l.keyframe_mut(1)).map(|k| { + k.script = Some(anicraft_doc::FrameScript::Actions(Vec::new())); + }); + assert!(k.is_some()); + assert!(s.execute("motion.join", &json!({"frame": 0})).is_err()); +} + +#[test] +fn retimed_tweens_survive_the_file_round_trip() { + let mut s = tweened(); + run(&mut s, "motion.move_keys", json!({"keys": [{"property": "x", "frame": 12}], "by": 3})); + run(&mut s, "timeline.resize_span", json!({"frame": 0, "frames": 40})); + let text = crate::format::to_json(&s.doc).expect("save"); + let doc = crate::format::from_json(&text).expect("load"); + assert_eq!(doc.scenes, s.doc.scenes); +} diff --git a/crates/engine/src/scale_grid_tests.rs b/crates/engine/src/scale_grid_tests.rs new file mode 100644 index 00000000..74b1ca2e --- /dev/null +++ b/crates/engine/src/scale_grid_tests.rs @@ -0,0 +1,175 @@ +//! 9-slice scaling end to end (ADR 0055): the command, undo, the file format, plug-ins and what +//! a scaled instance renders. + +use crate::Session; +use anicraft_doc::{ScaleGrid, SymbolId}; +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} {p}: {e}")) +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +/// A 100 × 40 rounded drawing object turned into a symbol (its space runs from (−50, −20) to +/// (50, 20)), its instance selected. +fn panel() -> (Session, SymbolId) { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 40, "radius": 10, "fill": "#3366cc", "stroke": "#000000", "stroke_width": 2})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Panel"})); + (s, SymbolId(v["symbol"].as_u64().unwrap())) +} + +fn grid(s: &Session, id: SymbolId) -> Option { + s.doc.symbol(id).and_then(|x| x.scale_grid) +} + +#[test] +fn turning_guides_on_puts_them_a_quarter_in_and_moving_one_keeps_the_rest() { + let (mut s, id) = panel(); + let v = run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert_eq!(v["symbol"], json!(id.0)); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -25.0, right: 25.0, top: -10.0, bottom: 10.0 })); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + run(&mut s, "symbol.set_scale_grid", json!({"top": -12})); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -40.0, right: 40.0, top: -12.0, bottom: 10.0 })); + // Off hides them: the symbol scales as a whole (ADR 0057). + let v = run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + assert_eq!(v["scale_grid"], Value::Null); + assert_eq!(grid(&s, id), None); + // Moving a guide turns them on, from where they were. + run(&mut s, "symbol.set_scale_grid", json!({"symbol": id.0, "left": -45})); + assert_eq!(grid(&s, id), Some(ScaleGrid { left: -45.0, right: 40.0, top: -12.0, bottom: 10.0 })); +} + +#[test] +fn guides_switched_off_and_on_again_come_back_where_they_were() { + let (mut s, id) = panel(); + let moved = ScaleGrid { left: -40.0, right: 30.0, top: -12.0, bottom: 6.0 }; + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 30, "top": -12, "bottom": 6})); + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let kept = |s: &Session| s.doc.symbol(id).and_then(|x| x.scale_grid_kept); + assert_eq!((grid(&s, id), kept(&s)), (None, Some(moved)), "kept, not applied"); + // Off twice keeps them still; saved and opened, they are still there. + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let file = crate::format::to_json(&s.doc).unwrap(); + assert!(file.contains("scale_grid_kept")); + let mut s = Session::new(crate::format::from_json(&file).unwrap()); + assert_eq!(kept(&s), Some(moved)); + run(&mut s, "symbol.set_scale_grid", json!({"symbol": id.0, "on": true})); + assert_eq!((grid(&s, id), kept(&s)), (Some(moved), None), "on again: back where they were"); + // Undo goes back to off with the guides kept. + s.undo().unwrap(); + assert_eq!((grid(&s, id), kept(&s)), (None, Some(moved))); + // A kept grid that isn't usable, or kept beside guides that are on, is dropped on load. + let mut d = s.doc.clone(); + let sym = std::sync::Arc::make_mut(&mut d.library[0]); + sym.scale_grid_kept = Some(ScaleGrid { left: 5.0, right: -5.0, top: 0.0, bottom: 1.0 }); + let d = crate::format::from_json(&crate::format::to_json(&d).unwrap()).unwrap(); + assert_eq!(d.library[0].scale_grid_kept, None); + let mut d = s.doc.clone(); + let sym = std::sync::Arc::make_mut(&mut d.library[0]); + sym.scale_grid = Some(moved); + let d = crate::format::from_json(&crate::format::to_json(&d).unwrap()).unwrap(); + assert_eq!((d.library[0].scale_grid, d.library[0].scale_grid_kept), (Some(moved), None)); +} + +#[test] +fn bad_guides_are_refused_and_change_nothing() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + let before = grid(&s, id); + assert!(err(&mut s, "symbol.set_scale_grid", json!({"left": 30})).contains("left"), "past the right guide"); + assert!(err(&mut s, "symbol.set_scale_grid", json!({"bottom": -20})).contains("top")); + err(&mut s, "symbol.set_scale_grid", json!({"left": 1e30})); + err(&mut s, "symbol.set_scale_grid", json!({})); + err(&mut s, "symbol.set_scale_grid", json!({"on": false, "left": 1})); + err(&mut s, "symbol.set_scale_grid", json!({"on": true, "symbol": 999_999})); + assert_eq!(grid(&s, id), before); + // With nothing selected and no symbol open there is nothing to set it on. + run(&mut s, "edit.deselect", json!({})); + err(&mut s, "symbol.set_scale_grid", json!({"on": true})); +} + +#[test] +fn each_change_is_one_undo_step_and_a_drag_of_moves_is_one_too() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert_eq!(s.undo_label(), Some("9-Slice Scaling")); + // A guide dragged: many moves, one step. + s.begin_gesture("Move 9-Slice Guide"); + for x in [-26, -30, -35, -38] { + run(&mut s, "symbol.set_scale_grid", json!({"left": x})); + } + s.end_gesture(); + assert_eq!(grid(&s, id).map(|g| g.left), Some(-38.0)); + s.undo().unwrap(); + assert_eq!(grid(&s, id).map(|g| g.left), Some(-25.0)); + s.undo().unwrap(); + assert_eq!(grid(&s, id), None); + s.redo().unwrap(); + assert!(grid(&s, id).is_some()); +} + +#[test] +fn inside_the_open_symbol_it_needs_no_selection() { + let (mut s, id) = panel(); + run(&mut s, "symbol.edit", json!({})); + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "symbol.set_scale_grid", json!({"on": true})); + assert!(grid(&s, id).is_some()); +} + +#[test] +fn the_guides_survive_the_file_and_older_files_open_without_them() { + let (mut s, id) = panel(); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(text.contains("\"scale_grid\"")); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back.symbol(id).and_then(|x| x.scale_grid), grid(&s, id)); + // A symbol whose guides are off keeps them apart (ADR 0057), and one that never had any + // writes nothing for them, so older files read the same. + run(&mut s, "symbol.set_scale_grid", json!({"on": false})); + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(!text.contains("\"scale_grid\"") && text.contains("\"scale_grid_kept\"")); + assert!(!crate::format::to_json(&panel().0.doc).unwrap().contains("scale_grid")); + assert_eq!(crate::format::from_json(&text).unwrap().symbol(id).and_then(|x| x.scale_grid), None); + // Unusable guides in a file are dropped, not drawn. + let mut doc = s.doc.clone(); + if let Some(sym) = doc.library.first_mut() { + std::sync::Arc::make_mut(sym).scale_grid = Some(ScaleGrid { left: 9.0, right: -9.0, top: 0.0, bottom: 1.0 }); + } + let text = crate::format::to_json(&doc).unwrap(); + assert_eq!(crate::format::from_json(&text).unwrap().symbol(id).and_then(|x| x.scale_grid), None); +} + +#[test] +fn a_scaled_instance_renders_with_unscaled_corners() { + // The CPU renderer (the oracle) draws the sliced instance: at 3× wide its top-left corner + // pixels match the unscaled instance's, while plain scaling stretches them. + let (mut s, _) = panel(); + s.doc.stage = anicraft_doc::Stage { width: 400, height: 200, ..s.doc.stage }; + let corner = |s: &Session| { + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + // The instance's top-left corner is at (100, 100): the 12 × 12 pixels there. + (0..12u32).flat_map(|y| (0..12u32).map(move |x| (x, y))).map(|(x, y)| format!("{:?}", img.pixel(100 + x, 100 + y))).collect::>() + }; + let at_one = corner(&s); + // Scale about the left edge: 3× wide. + run(&mut s, "modify.transform", json!({"a": 3, "b": 0, "c": 0, "d": 1, "e": -200, "f": 0})); + let plain = corner(&s); + assert_ne!(plain, at_one, "plain scaling stretches the corner"); + run(&mut s, "symbol.set_scale_grid", json!({"left": -40, "right": 40, "top": -10, "bottom": 10})); + assert_eq!(corner(&s), at_one, "9-slice keeps it"); +} + +#[test] +fn plug_ins_may_set_guides() { + assert!(crate::cmds_plugin::plugin_may_call("symbol.set_scale_grid").is_ok()); +} diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index 964cfa78..8d727b37 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -184,13 +184,13 @@ fn merge_results(results: Vec<(LayerId, Value)>) -> Value { impl Session { /// The elements on `layer` at the playhead (tweens applied). pub fn elements_on(&self, layer: LayerId) -> Vec> { - self.doc.timeline(self.scene).layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() + self.timeline().layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() } /// Whether artwork on `layer` can be selected: it is in this scene, shown and unlocked /// (folders included), and not a folder. pub fn selectable(&self, layer: LayerId) -> bool { - let tl = self.doc.timeline(self.scene); + let tl = self.timeline(); let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return false }; tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder) && !tl.locked_by_folder(layer) && !tl.hidden_by_folder(i) } @@ -199,14 +199,14 @@ impl Session { /// artwork on it. The camera layer holds only the camera, and an armature layer's /// instances are posed by their bones, so they are gathered only while active. pub fn gathers(&self, layer: LayerId) -> bool { - let kind = self.doc.timeline(self.scene).layer(layer).map(|l| l.kind); + let kind = self.timeline().layer(layer).map(|l| l.kind); self.selectable(layer) && (layer == self.layer || !matches!(kind, Some(LayerKind::Camera | LayerKind::Armature))) } /// The layers with selected items, top to bottom. pub fn selected_layers(&self) -> Vec { let mine = self.selection.layers(); - self.doc.timeline(self.scene).layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect() + self.timeline().layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect() } /// Every selected element as it looks at the playhead, with its layer: layers top to @@ -249,8 +249,10 @@ impl Session { /// locked (a locked or hidden layer is never selected), and keeps the active layer valid. pub fn fix_selection(&mut self) { self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1)); - if self.doc.timeline(self.scene).layer(self.layer).is_none() { - self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id); + // A symbol that is gone closes (ADR 0045). + self.fix_editing(); + if self.timeline().layer(self.layer).is_none() { + self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id); } if self.selection.is_empty() { return; @@ -321,7 +323,7 @@ impl Session { } } } - if self.doc.timeline(self.scene).layer(active).is_some() { + if self.timeline().layer(active).is_some() { self.layer = active; } self.selection = after; @@ -341,7 +343,7 @@ impl Session { crate::cmds_motion::finish_edit(self, edit); } self.dl_cache.replace(None); - if self.doc.timeline(self.scene).layer(active).is_some() { + if self.timeline().layer(active).is_some() { self.layer = active; } r diff --git a/crates/engine/src/selection_tests.rs b/crates/engine/src/selection_tests.rs index 6ae32395..5ace4650 100644 --- a/crates/engine/src/selection_tests.rs +++ b/crates/engine/src/selection_tests.rs @@ -206,7 +206,7 @@ fn properties_edits_apply_to_each_layer() { run(&mut s, "element.set_transform", json!({"rotation": 45})); for (l, id) in [(top, a), (bottom, b)] { let e = element(&s, l, id).unwrap(); - assert_eq!(e.color.alpha, 0.5); + assert_eq!(e.color, anicraft_doc::ColorEffect::Alpha(0.5)); assert_eq!(e.name, "both"); assert!((e.transform.decompose().rotation.to_degrees() - 45.0).abs() < 1e-3); let ElementKind::Shape(sh) = &e.kind else { panic!() }; @@ -375,6 +375,41 @@ fn break_apart_works_on_each_layer() { assert_eq!(s.selected_layers(), vec![top, bottom]); } +/// #253: a drawing object (Object Drawing) breaks apart into raw shapes that merge with the raw +/// drawing they touch, so it can be edited as a merged shape again; one undo step brings the +/// object back. +#[test] +fn break_apart_turns_a_drawing_object_into_raw_shapes() { + let mut s = Session::default(); + s.style.object_drawing = false; + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#00ff00", "stroke": null})); + let raw = s.visible_elements().len(); + let obj = el_id(&run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null, "object": true}))); + let squiggle = el_id(&run(&mut s, "draw.freehand", json!({"points": [[300, 0], [320, 30], [340, 0], [360, 30]], "object": true}))); + let shapes = |s: &Session| -> Vec<(ElementId, bool)> { + s.visible_elements().iter().filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some((e.id, sh.merge)), + _ => None, + }).collect() + }; + assert!(shapes(&s).iter().filter(|(id, _)| [obj, squiggle].contains(id)).all(|(_, m)| !m), "drawn as objects"); + let before = s.doc.clone(); + let steps = s.history_len(); + run(&mut s, "element.select", json!({"ids": [obj.0, squiggle.0]})); + let v = run(&mut s, "modify.break_apart", json!({})); + assert!(v["created"].as_u64().unwrap() >= 2, "{v}"); + assert!(shapes(&s).iter().all(|(_, m)| *m), "every shape is raw now: {:?}", shapes(&s)); + assert!(!shapes(&s).iter().any(|(id, _)| *id == obj), "the object merged into the drawing"); + assert!(s.visible_elements().len() > raw + 1, "the red square cut the green one"); + assert!(!s.selection.is_empty(), "what came out of it is selected"); + assert_eq!(s.history_len(), steps + 1); + s.undo().unwrap(); + assert!(s.doc == before, "one undo brings the objects back"); + // Nothing to break apart: an error, not a no-op step. + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("modify.break_apart", &json!({})).is_err()); +} + // ----- the marquee across layers with raw parts (ADR 0041) ------------------------------------ /// Raw squares on two layers: Top's 0..100, Bottom's 200..300 (both 0..100 high). @@ -562,3 +597,14 @@ fn clicking_a_layer_name_selects_its_artwork() { run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true})); assert!(s.selection.is_empty()); } + +#[test] +fn select_with_toggle_takes_one_out_and_puts_it_back_across_layers() { + // Shift+Space on a stage element (ADR 0064): the others stay selected, on either layer. + let (mut s, top, bottom, a, b) = two_layers(); + run(&mut s, "element.select", json!({"ids": [b.0], "toggle": true})); + assert!(s.selection.contains(top, a) && !s.selection.contains(bottom, b)); + run(&mut s, "element.select", json!({"ids": [b.0], "toggle": true})); + assert!(s.selection.contains(top, a) && s.selection.contains(bottom, b)); + assert!(s.execute("element.select", &json!({"ids": [b.0], "toggle": "yes"})).is_err(), "toggle is a bool"); +} diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs new file mode 100644 index 00000000..1468ae5d --- /dev/null +++ b/crates/engine/src/snap.rs @@ -0,0 +1,273 @@ +//! One snap engine for every tool (ADR 0076): a point being drawn, dragged or moved snaps to +//! the artwork (Snap to Objects, ADR 0041/0045), the scene's guides, the grid and whole pixels, +//! in a fixed order of priority: +//! +//! 1. an object's **point** (corner or end) within the radius: both coordinates; +//! 2. a **guide**, each coordinate on its own (a vertical guide takes x, a horizontal one y; two +//! together are their crossing); +//! 3. an object's **line** or fill edge, only when no guide took either coordinate; +//! 4. the **grid**, each coordinate not yet taken; +//! 5. a whole **pixel**, each coordinate not yet taken (Snap to Pixels). +//! +//! The radius is what the caller asks (`snap`, in the space the tool works in: 10 screen pixels +//! at the zoom of the moment), so snapping feels the same at every zoom. The guides' and grid's +//! own accuracy scales it. Guides and the grid are in stage pixels; while a symbol is open in +//! place (ADR 0045) points are mapped there and back, so they line up with what the stage shows. + +use crate::Session; +use anicraft_doc::GuideAxis; +use anicraft_geom::Vec2; +use serde::{Deserialize, Serialize}; + +/// How near a point must come to a guide or a grid line to snap to it (Animate's Snap +/// accuracy), as a factor of the radius the tool asks for. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Accuracy { + /// Must be close: half the usual distance. + Close, + #[default] + Normal, + /// Can be distant: twice the usual distance. + Distant, + /// Always snap (the grid only): every point goes to the nearest line. + Always, +} + +impl Accuracy { + pub const ALL: [Accuracy; 4] = [Accuracy::Close, Accuracy::Normal, Accuracy::Distant, Accuracy::Always]; + + pub fn key(self) -> &'static str { + match self { + Accuracy::Close => "close", + Accuracy::Normal => "normal", + Accuracy::Distant => "distant", + Accuracy::Always => "always", + } + } + pub fn parse(s: &str) -> Option { + Accuracy::ALL.into_iter().find(|a| a.key() == s.trim().to_ascii_lowercase()) + } + /// The name a menu or dialog shows (English; translated where it is drawn). + pub fn label(self) -> &'static str { + match self { + Accuracy::Close => "Must be close", + Accuracy::Normal => "Normal", + Accuracy::Distant => "Can be distant", + Accuracy::Always => "Always snap", + } + } + fn factor(self) -> f32 { + match self { + Accuracy::Close => 0.5, + Accuracy::Normal => 1.0, + Accuracy::Distant => 2.0, + Accuracy::Always => f32::INFINITY, + } + } +} + +/// Whether the rulers, grid and guides show and snap (View › Rulers, Grid, Guides, Snapping): +/// the editor's working preferences, kept from session to session by the editor and never in +/// the document or its undo history (ADR 0076). How the grid and guides look, and where the +/// guides are, is the document's (`anicraft_doc::Aids`, `Scene::guides`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ViewAids { + pub rulers: bool, + pub show_grid: bool, + pub show_guides: bool, + /// Guides can't be dragged (commands that move or delete one refuse too). + pub lock_guides: bool, + pub snap_grid: bool, + pub snap_guides: bool, + pub snap_pixels: bool, + pub grid_accuracy: Accuracy, + pub guide_accuracy: Accuracy, +} + +impl Default for ViewAids { + fn default() -> Self { + // As in Animate: guides show and snap; the rulers, grid and pixel snapping are off. + ViewAids { rulers: false, show_grid: false, show_guides: true, lock_guides: false, snap_grid: false, snap_guides: true, snap_pixels: false, grid_accuracy: Accuracy::Normal, guide_accuracy: Accuracy::Normal } + } +} + +/// What a point snapped to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SnapTo { + /// An anchor (corner or end). + Point, + /// A guide. + Guide, + /// A stroke or a fill's edge. + Line, + /// A grid line. + Grid, + /// A whole pixel. + Pixel, +} + +impl SnapTo { + pub fn key(&self) -> &'static str { + match self { + SnapTo::Point => "point", + SnapTo::Guide => "guide", + SnapTo::Line => "line", + SnapTo::Grid => "grid", + SnapTo::Pixel => "pixel", + } + } + /// Lower wins (the order of priority above). + pub(crate) fn rank(self) -> u8 { + match self { + SnapTo::Point => 0, + SnapTo::Guide => 1, + SnapTo::Line => 2, + SnapTo::Grid => 3, + SnapTo::Pixel => 4, + } + } +} + +/// The artwork's points and lines to snap to, as each caller gathers them. +pub(crate) trait ObjectTargets { + /// The nearest point within `r` of `p`, and how far it is. + fn nearest_point(&self, p: Vec2, r: f32) -> Option<(Vec2, f32)>; + /// The nearest point on a line or fill edge within `r` of `p`. + fn nearest_line(&self, p: Vec2, r: f32) -> Option<(Vec2, f32)>; +} + +/// Where stage space is from the space tools work in: `stage = origin + scale · p`. +fn space(s: &Session) -> (Vec2, f32) { + match s.edit_view() { + Some(v) if v.scale.is_finite() && v.scale > 1e-4 && v.origin.is_finite() => (v.origin, v.scale), + _ => (Vec2::ZERO, 1.0), + } +} + +impl Session { + /// Whether anything snaps at all: a radius, and Snap to Objects, Guides, Grid or Pixels on. + pub(crate) fn snaps(&self, r: f32) -> bool { + r > 0.0 && (self.style.snap_objects || self.aids.snap_guides || self.aids.snap_grid || self.aids.snap_pixels) + } + + /// The scene's guides (the main timeline's, also while a symbol is open). + pub fn guides(&self) -> &[anicraft_doc::Guide] { + self.doc.scenes.get(self.scene).map_or(&[], |sc| &sc.guides[..]) + } +} + +/// The nearest of `lines` within `r` of `v`. +fn nearest(v: f32, r: f32, lines: impl Iterator) -> Option { + lines.map(|q| (q, (q - v).abs())).filter(|(_, d)| *d <= r).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(q, _)| q) +} + +/// The nearest grid line within `r` of `v`, lines every `spacing`. +fn grid_line(v: f32, spacing: f32, r: f32) -> Option { + if spacing.is_nan() || spacing <= 0.0 { + return None; + } + let q = (v / spacing).round() * spacing; + ((q - v).abs() <= r && q.is_finite()).then_some(q) +} + +/// Where `p` (in the space tools work in) snaps within `r`, by the order of priority above; +/// `objects` are the artwork's points and lines (`None`: not looked at). `None` when nothing is +/// near or nothing snaps. +pub(crate) fn resolve(s: &Session, p: Vec2, r: f32, objects: Option<&dyn ObjectTargets>) -> Option<(Vec2, SnapTo)> { + if !(r > 0.0 && r.is_finite() && p.is_finite()) { + return None; + } + let objects = objects.filter(|_| s.style.snap_objects); + if let Some((q, _)) = objects.and_then(|t| t.nearest_point(p, r)) { + return Some((q, SnapTo::Point)); + } + let (o, k) = space(s); + let sp = o + p * k; + let sr = r * k; + let a = &s.aids; + // Each coordinate: where it goes and why. + type Axis = Option<(f32, SnapTo)>; + let (mut x, mut y): (Axis, Axis) = (None, None); + if a.snap_guides { + // Guides snap within the radius at most ("always" is the grid's). + let gr = sr * a.guide_accuracy.factor().min(2.0); + let at = |axis: GuideAxis| s.guides().iter().filter(move |g| g.axis == axis).map(|g| g.at); + x = nearest(sp.x, gr, at(GuideAxis::Vertical)).map(|v| (v, SnapTo::Guide)); + y = nearest(sp.y, gr, at(GuideAxis::Horizontal)).map(|v| (v, SnapTo::Guide)); + } + if x.is_none() + && y.is_none() + && let Some((q, _)) = objects.and_then(|t| t.nearest_line(p, r)) + { + return Some((q, SnapTo::Line)); + } + if a.snap_grid { + let g = s.doc.aids.grid; + let gr = sr * a.grid_accuracy.factor(); + x = x.or_else(|| grid_line(sp.x, g.spacing_x, gr).map(|v| (v, SnapTo::Grid))); + y = y.or_else(|| grid_line(sp.y, g.spacing_y, gr).map(|v| (v, SnapTo::Grid))); + } + if a.snap_pixels { + x = x.or(Some((sp.x.round(), SnapTo::Pixel))); + y = y.or(Some((sp.y.round(), SnapTo::Pixel))); + } + let to = [x, y].into_iter().flatten().map(|(_, t)| t).min_by_key(|t| t.rank())?; + let q = Vec2::new(x.map_or(sp.x, |v| v.0), y.map_or(sp.y, |v| v.0)); + let back = (q - o) * (1.0 / k); + back.is_finite().then_some((back, to)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Session; + use anicraft_doc::{Document, Guide}; + use std::sync::Arc; + + fn session(guides: &[Guide]) -> Session { + let mut d = Document::default(); + Arc::make_mut(&mut d.scenes[0]).guides = guides.to_vec(); + let mut s = Session::new(d); + s.style.snap_objects = false; + s + } + + #[test] + fn guides_snap_each_axis_and_their_crossing() { + let s = session(&[Guide { axis: GuideAxis::Vertical, at: 100.0 }, Guide { axis: GuideAxis::Horizontal, at: 50.0 }]); + assert_eq!(resolve(&s, Vec2::new(104.0, 300.0), 10.0, None), Some((Vec2::new(100.0, 300.0), SnapTo::Guide))); + assert_eq!(resolve(&s, Vec2::new(97.0, 58.0), 10.0, None), Some((Vec2::new(100.0, 50.0), SnapTo::Guide))); + assert_eq!(resolve(&s, Vec2::new(120.0, 300.0), 10.0, None), None, "too far"); + assert_eq!(resolve(&s, Vec2::new(104.0, 300.0), 0.0, None), None, "no radius: nothing snaps (Shift)"); + } + + #[test] + fn the_radius_follows_the_zoom() { + // The shell asks for 10 screen pixels: 10 / zoom stage pixels. + let s = session(&[Guide { axis: GuideAxis::Vertical, at: 100.0 }]); + for (zoom, off, snaps) in [(1.0, 8.0, true), (1.0, 12.0, false), (4.0, 2.0, true), (4.0, 3.0, false), (0.25, 39.0, true), (0.25, 41.0, false)] { + let r = 10.0 / zoom; + assert_eq!(resolve(&s, Vec2::new(100.0 + off, 0.0), r, None).is_some(), snaps, "zoom {zoom}, {off} px off"); + } + } + + #[test] + fn grid_pixels_and_accuracy() { + let mut s = session(&[]); + s.aids.snap_grid = true; + assert_eq!(resolve(&s, Vec2::new(43.0, 18.0), 10.0, None), Some((Vec2::new(40.0, 20.0), SnapTo::Grid))); + s.aids.grid_accuracy = Accuracy::Close; + assert_eq!(resolve(&s, Vec2::new(46.0, 13.0), 10.0, None), None, "Must be close: within 5"); + s.aids.grid_accuracy = Accuracy::Always; + assert_eq!(resolve(&s, Vec2::new(49.0, 9.0), 1.0, None), Some((Vec2::new(40.0, 0.0), SnapTo::Grid))); + s.aids.snap_grid = false; + s.aids.snap_pixels = true; + assert_eq!(resolve(&s, Vec2::new(4.4, 7.6), 10.0, None), Some((Vec2::new(4.0, 8.0), SnapTo::Pixel))); + // A guide on x wins over the grid there; y still goes to the grid, then pixels. + let mut s = session(&[Guide { axis: GuideAxis::Vertical, at: 33.0 }]); + s.aids.snap_grid = true; + assert_eq!(resolve(&s, Vec2::new(36.0, 22.0), 10.0, None), Some((Vec2::new(33.0, 20.0), SnapTo::Guide))); + } +} diff --git a/crates/engine/src/swatch_tests.rs b/crates/engine/src/swatch_tests.rs new file mode 100644 index 00000000..d4e6b061 --- /dev/null +++ b/crates/engine/src/swatch_tests.rs @@ -0,0 +1,261 @@ +//! The Swatches panel's commands (ADR 0078). + +use crate::Session; +use anicraft_doc::{Document, ElementId, ElementKind, Paint, Rgba, Shape, Swatch, SwatchPaint}; +use serde_json::{Value, 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 blank() -> Session { + Session::new(Document::default()) +} + +fn shape(s: &Session, id: u64) -> Shape { + s.visible_elements() + .iter() + .find(|e| e.id == ElementId(id)) + .and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }) + .expect("a shape") +} + +/// A selected 100 × 100 square at (x, 100), red with a black stroke. +fn square(s: &mut Session, x: f32) -> u64 { + run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": "#000000"}))["element"].as_u64().unwrap() +} + +fn find(s: &Session, name: &str) -> usize { + s.doc.swatches.iter().position(|w| w.name == name).unwrap_or_else(|| panic!("no swatch {name}")) +} + +#[test] +fn a_new_document_has_the_default_swatches_and_older_files_open_with_them() { + let s = blank(); + assert_eq!(s.doc.swatches.len(), 19); + // A file from before swatches (no "swatches" key) opens with the default set; the set is + // not written while unchanged, so such files stay as they were. + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(!text.contains("\"swatches\""), "the default set isn't written"); + let back = crate::format::from_json(&text).unwrap(); + assert!(anicraft_doc::swatch::is_default_set(&back.swatches)); +} + +#[test] +fn swatches_round_trip_through_the_file() { + let mut s = blank(); + run(&mut s, "swatch.clear", json!({"confirm": true})); + run(&mut s, "swatch.add", json!({"color": "#12345680", "name": "Ink"})); + run(&mut s, "swatch.add", json!({"type": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 0.7, "color": "#ff000080"}], "spread": "reflect", "linear_rgb": true, "focal": 0.5, "name": "Glow"})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(*back.swatches, *s.doc.swatches); + assert_eq!(back.swatches.len(), 4); + let SwatchPaint::Radial { spread, linear_rgb, focal, stops } = &back.swatches[3].paint else { panic!("a radial swatch") }; + assert_eq!((spread.key(), *linear_rgb, *focal, stops.len()), ("reflect", true, 0.5, 2)); + // An explicitly empty list stays empty (it isn't the default set). + let mut e = blank(); + run(&mut e, "swatch.clear", json!({"confirm": true})); + run(&mut e, "swatch.remove", json!({"index": 0})); + run(&mut e, "swatch.remove", json!({"index": 0})); + let back = crate::format::from_json(&crate::format::to_json(&e.doc).unwrap()).unwrap(); + assert!(back.swatches.is_empty()); + // A damaged file's swatches are repaired or dropped on open. + let mut v: Value = serde_json::from_str(&text).unwrap(); + v["document"]["swatches"] = json!([{"paint": {"type": "linear", "stops": [{"offset": 0, "color": {"r": 0, "g": 0, "b": 0, "a": 1}}]}}, {"name": "ok", "paint": {"type": "solid", "color": {"r": 9, "g": 0.5, "b": 0, "a": 1}}}]); + let fixed = crate::format::from_json(&v.to_string()).unwrap(); + assert_eq!(fixed.swatches.len(), 1); + assert_eq!(fixed.swatches[0].paint.primary_color().r, 1.0); +} + +#[test] +fn add_takes_the_current_fill_or_stroke_or_a_given_swatch() { + let mut s = blank(); + let n = s.doc.swatches.len(); + s.style.set_fill_color(Rgba::hex(0x3366ff)); + s.style.stroke = Rgba::hex(0x00aa00); + assert_eq!(run(&mut s, "swatch.add", json!({}))["index"], n); + assert_eq!(s.doc.swatches[n].paint, SwatchPaint::Solid { color: Rgba::hex(0x3366ff) }); + run(&mut s, "swatch.add", json!({"from": "stroke", "at": 0, "name": "Leaf"})); + assert_eq!((s.doc.swatches[0].name.as_str(), s.doc.swatches[0].paint.primary_color()), ("Leaf", Rgba::hex(0x00aa00))); + // A gradient fill swatch adds its ramp and options. + run(&mut s, "paint.set_fill", json!({"type": "radial", "spread": "repeat", "selection": false})); + let i = run(&mut s, "swatch.add", json!({"from": "fill"}))["index"].as_u64().unwrap() as usize; + assert!(matches!(&s.doc.swatches[i].paint, SwatchPaint::Radial { spread: anicraft_doc::Spread::Repeat, .. })); + // Each add is one undo step. + let len = s.doc.swatches.len(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.swatches.len(), len - 1); + for bad in [json!({"from": "middle"}), json!({"type": "solid"}), json!({"type": "linear"}), json!({"type": "conic", "color": "#000000"}), json!({"from": "fill", "color": "#000000"}), json!({"color": "#00"}), json!({"color": "#000000", "at": 9999})] { + assert!(s.execute("swatch.add", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn remove_move_duplicate_and_rename() { + let mut s = blank(); + let n = s.doc.swatches.len(); + let red = s.doc.swatches[6].clone(); + run(&mut s, "swatch.move", json!({"from": 6, "to": 0})); + assert_eq!(s.doc.swatches[0], red); + assert_eq!(s.doc.swatches.len(), n); + run(&mut s, "swatch.move", json!({"from": 0, "to": n - 1})); + assert_eq!(s.doc.swatches[n - 1], red, "to the end"); + assert_eq!(run(&mut s, "swatch.duplicate", json!({"index": n - 1}))["index"], n); + assert_eq!(s.doc.swatches[n], red); + run(&mut s, "swatch.rename", json!({"index": n, "name": " Fire engine "})); + assert_eq!(s.doc.swatches[n].name, "Fire engine"); + run(&mut s, "swatch.remove", json!({"index": n})); + assert_eq!(s.doc.swatches.len(), n); + for (id, bad) in [("swatch.remove", json!({"index": n})), ("swatch.remove", json!({})), ("swatch.move", json!({"from": 0, "to": n})), ("swatch.duplicate", json!({"index": -1})), ("swatch.rename", json!({"index": 0}))] { + assert!(s.execute(id, &bad).is_err(), "{id} {bad}"); + } +} + +#[test] +fn apply_sets_the_fill_or_the_stroke_of_the_selection_and_the_tool() { + let mut s = blank(); + let id = square(&mut s, 50.0); + let blue = find_colour(&s, 0x0000ff); + // Fill: the selection and the fill swatch. + assert_eq!(run(&mut s, "swatch.apply", json!({"index": blue}))["changed"], 1); + assert_eq!(shape(&s, id).fill, Some(Paint::Solid(Rgba::hex(0x0000ff)))); + assert_eq!(s.style.fill_paint(), Paint::Solid(Rgba::hex(0x0000ff))); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::BLACK, "the stroke is untouched"); + // Stroke: the selection's lines and the stroke colour; the fill stays. + let yellow = find_colour(&s, 0xffff00); + run(&mut s, "swatch.apply", json!({"index": yellow, "target": "stroke"})); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::hex(0xffff00)); + assert_eq!(s.style.stroke, Rgba::hex(0xffff00)); + assert_eq!(shape(&s, id).fill, Some(Paint::Solid(Rgba::hex(0x0000ff)))); + // A gradient swatch is fitted to the shape, and the swatch holds it. + let glow = find(&s, "Red ball"); + run(&mut s, "swatch.apply", json!({"index": glow})); + let Some(Paint::Radial { center, radius, stops, .. }) = shape(&s, id).fill else { panic!("a radial fill") }; + assert_eq!(stops[0].color, Rgba::hex(0xff8080)); + assert!(center.x.abs() < 1e-3 && center.y.abs() < 1e-3 && (radius - 50.0).abs() < 1.0, "fitted to the 100-unit square: {center:?} {radius}"); + assert!(matches!(s.style.fill_paint, Some(Paint::Radial { .. }))); + // Strokes are one colour. + assert!(s.execute("swatch.apply", &json!({"index": glow, "target": "stroke"})).is_err()); + // With `selection: false` only the tool colour changes. + let white = find_colour(&s, 0xffffff); + assert_eq!(run(&mut s, "swatch.apply", json!({"index": white, "selection": false}))["changed"], 0); + assert_eq!(s.style.fill_paint(), Paint::Solid(Rgba::WHITE)); + assert!(matches!(shape(&s, id).fill, Some(Paint::Radial { .. }))); + // Nothing selected: the tool colour. + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "swatch.apply", json!({"index": blue, "target": "stroke"})); + assert_eq!(s.style.stroke, Rgba::hex(0x0000ff)); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::hex(0xffff00)); + // On the selection: one undo step (the tool colour alone is no document change). + run(&mut s, "edit.select_all", json!({})); + let before = s.history_len(); + run(&mut s, "swatch.apply", json!({"index": blue, "target": "fill"})); + assert_eq!(s.history_len(), before + 1); + assert!(s.execute("swatch.apply", &json!({"index": 0, "target": "outline"})).is_err()); +} + +fn find_colour(s: &Session, rgb: u32) -> usize { + s.doc.swatches.iter().position(|w| w.paint == SwatchPaint::Solid { color: Rgba::hex(rgb) }).expect("a default colour") +} + +#[test] +fn clear_and_reset_ask_first_and_undo() { + let mut s = blank(); + let c = s.confirmation("swatch.clear", &json!({})).expect("clearing 19 swatches asks"); + assert!(!c.irreversible, "undoable, so it asks by default only"); + run(&mut s, "swatch.clear", json!({})); + assert_eq!(*s.doc.swatches, vec![Swatch::solid(Rgba::BLACK), Swatch::solid(Rgba::WHITE)]); + assert!(s.confirmation("swatch.clear", &json!({})).is_none(), "nothing to lose"); + assert!(s.confirmation("swatch.reset", &json!({})).is_some()); + run(&mut s, "swatch.reset", json!({})); + assert!(anicraft_doc::swatch::is_default_set(&s.doc.swatches)); + assert!(s.confirmation("swatch.reset", &json!({})).is_none(), "already the default set"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.swatches.len(), 2); +} + +/// Runs `f` on a thread of its own with the in-memory file store, so no other test's files +/// (on a reused test thread) see it. +fn in_memory(f: impl FnOnce() + Send + 'static) { + std::thread::spawn(move || { + crate::vfs::use_memory(); + f(); + }) + .join() + .unwrap(); +} + +#[test] +fn swatch_files_export_and_import() { + in_memory(swatch_files_export_and_import_in_memory); +} + +fn swatch_files_export_and_import_in_memory() { + let mut s = blank(); + run(&mut s, "swatch.add", json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff00"}], "name": "Fade"})); + let v = run(&mut s, "swatch.export", json!({"path": "set.json"})); + assert_eq!(v["swatches"], 20); + let text = crate::vfs::read_to_string(Path::new("set.json")).unwrap(); + assert!(text.contains("\"format\": \"anicraft-swatches\"") && text.contains("\"Fade\"") && text.contains("#ffffff00")); + assert!(s.confirmation("swatch.export", &json!({"path": "set.json"})).is_some_and(|c| c.irreversible), "overwriting a file asks"); + // Another document: added at the end, or replacing (which asks by default). + let mut t = blank(); + assert_eq!(run(&mut t, "swatch.import", json!({"path": "set.json"}))["count"], 39); + assert!(t.confirmation("swatch.import", &json!({"path": "set.json", "replace": true})).is_some_and(|c| !c.irreversible)); + run(&mut t, "swatch.import", json!({"path": "set.json", "replace": true})); + assert_eq!(*t.doc.swatches, *s.doc.swatches, "the same swatches, exactly"); + // Unknown swatches in a newer file are skipped; junk is refused. + crate::vfs::put(Path::new("new.json"), br##"{"format": "anicraft-swatches", "version": 2, "swatches": [{"type": "conic"}, {"type": "solid", "color": "#010203"}]}"##.to_vec()).unwrap(); + let before = t.doc.swatches.len(); + assert_eq!(run(&mut t, "swatch.import", json!({"path": "new.json"}))["imported"], 1); + assert_eq!(t.doc.swatches.len(), before + 1); + for (name, body) in [("a.json", "{}"), ("b.json", "[1, 2]"), ("c.json", "not json"), ("d.json", r#"{"format": "anicraft-brushes"}"#), ("e.json", r#"{"format": "anicraft-swatches", "swatches": []}"#)] { + crate::vfs::put(Path::new(name), body.as_bytes().to_vec()).unwrap(); + assert!(t.execute("swatch.import", &json!({"path": name})).is_err(), "{name}"); + } + assert!(t.execute("swatch.import", &json!({"path": "missing.json"})).is_err()); +} + +#[test] +fn gimp_palettes_import() { + in_memory(gimp_palettes_import_in_memory); +} + +fn gimp_palettes_import_in_memory() { + let mut s = blank(); + crate::vfs::put(Path::new("brand.gpl"), b"GIMP Palette\nName: Brand\nColumns: 3\n#\n230 57 70\tRed\n 29 53 87\tNavy\n241 250 238 Untitled\n".to_vec()).unwrap(); + run(&mut s, "swatch.import", json!({"path": "brand.gpl", "replace": true, "confirm": true})); + assert_eq!(s.doc.swatches.len(), 3); + assert_eq!(s.doc.swatches[0].name, "Red"); + assert_eq!(s.doc.swatches[1].paint.primary_color().to_hex(), "#1d3557"); + assert_eq!(s.doc.swatches[2].name, ""); + // Then they paint like any swatch. + let id = square(&mut s, 0.0); + run(&mut s, "swatch.apply", json!({"index": 1})); + assert_eq!(shape(&s, id).fill.map(|p| p.primary_color().to_hex()), Some("#1d3557".into())); +} + +#[test] +fn swatches_are_bounded() { + let mut s = blank(); + s.doc.swatches = std::sync::Arc::new(vec![Swatch::solid(Rgba::BLACK); anicraft_doc::MAX_SWATCHES]); + assert!(s.execute("swatch.add", &json!({"color": "#ffffff"})).is_err()); + assert!(s.execute("swatch.duplicate", &json!({"index": 0})).is_err()); + let list = run(&mut s, "swatch.list", json!({})); + assert_eq!(list["count"], anicraft_doc::MAX_SWATCHES); + assert_eq!(list["swatches"][3]["index"], 3); +} + +#[test] +fn plug_ins_edit_swatches_but_not_swatch_files() { + use crate::cmds_plugin::plugin_may_call; + for id in ["swatch.add", "swatch.apply", "swatch.remove", "swatch.move", "swatch.list", "swatch.clear"] { + assert!(plugin_may_call(id).is_ok(), "{id}"); + } + assert!(plugin_may_call("swatch.import").is_err() && plugin_may_call("swatch.export").is_err()); +} diff --git a/crates/engine/src/template_tests.rs b/crates/engine/src/template_tests.rs new file mode 100644 index 00000000..c14f0678 --- /dev/null +++ b/crates/engine/src/template_tests.rs @@ -0,0 +1,153 @@ +//! Templates (ADR 0065): every built-in template opens as a new untitled document and saves, +//! and Save as Template keeps the document with a picture in the user's folder, round trip. + +use super::*; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-templates-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// `panic_hunt_every_command` leaves `file.*` out (they touch the disk): the template commands +/// and timeline drops get hostile params here, with every folder inside a temporary one. +#[test] +fn template_and_timeline_drop_commands_never_panic_on_hostile_params() { + let dir = temp_dir("fuzz"); + let folder = dir.display().to_string(); + let junk = [ + Value::Null, + json!([]), + json!("x"), + json!({}), + json!({"folder": folder}), + json!({"folder": folder, "name": 7}), + json!({"folder": folder, "name": "a", "category": ["x"]}), + json!({"folder": folder, "name": "\u{0}", "category": "\u{202e}"}), + json!({"folder": folder, "name": "é".repeat(64), "category": "ü".repeat(65)}), + json!({"folder": 3, "name": "a"}), + json!({"folder": folder, "name": "ok", "confirm": "yes"}), + json!({"template": 3}), + json!({"template": ""}), + json!({"path": ""}), + json!({"path": dir.join("nope.anicraft").display().to_string()}), + json!({"path": folder, "confirm": true}), + json!({"paths": ["a.png"], "to": "timeline", "layer": -1, "frame": 1e30}), + json!({"paths": ["a.wav"], "to": "timeline", "layer": "x", "frame": "y"}), + json!({"paths": ["a.svg"], "to": "timeline", "layer": 1, "frame": 0, "x": f64::NAN}), + ]; + for id in ["file.templates", "file.new_from_template", "file.save_as_template", "file.delete_template", "file.drop"] { + for p in &junk { + let mut s = Session::new(anicraft_doc::sample::demo()); + let _ = s.execute(id, p); + let mut confirmed = p.clone(); + if let Some(o) = confirmed.as_object_mut() { + o.insert("confirm".into(), json!(true)); + } + let _ = s.execute(id, &confirmed); + } + } +} + +#[test] +fn every_built_in_template_opens_untitled_and_survives_a_save() { + let dir = temp_dir("builtin"); + let list = run(&mut Session::default(), "file.templates", json!({})); + let builtin = list["builtin"].as_array().unwrap(); + assert_eq!(builtin.len(), anicraft_doc::templates::TEMPLATES.len()); + assert!(list["user"].as_array().unwrap().is_empty()); + for t in builtin { + let id = t["id"].as_str().unwrap(); + let mut s = Session::new(anicraft_doc::sample::demo()); + s.path = Some(dir.join("was.anicraft")); + let v = run(&mut s, "file.new_from_template", json!({"template": id})); + assert_eq!(v["template"], t["name"]); + assert!(s.path.is_none() && !s.is_dirty(), "{id}: a new, untitled document"); + assert_eq!((u64::from(s.doc.stage.width), u64::from(s.doc.stage.height)), (t["width"].as_u64().unwrap(), t["height"].as_u64().unwrap())); + // Drawing works straight away on a drawing layer, and it saves and opens again. + let active = s.active_layer().unwrap(); + assert!(active.kind == anicraft_doc::LayerKind::Normal && !active.locked, "{id}: the active layer takes drawing"); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20})); + let path = dir.join(format!("{id}.anicraft")); + run(&mut s, "file.save_as", json!({"path": path.display().to_string()})); + let saved = s.doc.clone(); + run(&mut s, "file.open", json!({"path": path.display().to_string()})); + assert!(s.doc == saved, "{id}: round trip"); + // Thumbnails render (the shell draws these on the start screen). + let png = crate::cmds_template::picture_png(&s.doc).unwrap(); + assert!(png.len() > 100); + } + let mut s = Session::default(); + assert!(s.execute("file.new_from_template", &json!({"template": "nope"})).is_err()); + assert!(s.execute("file.new_from_template", &json!({})).is_err()); + assert!(s.execute("file.new_from_template", &json!({"template": "storyboard", "path": "x.anicraft"})).is_err()); + // Over unsaved work it asks first, like New. + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + assert!(s.confirmation("file.new_from_template", &json!({"template": "storyboard"})).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.new_from_template", &json!({"template": "storyboard"})).is_err()); + run(&mut s, "file.new_from_template", json!({"template": "storyboard", "confirm": true})); + assert_eq!(s.doc.stage.width, 1920); +} + +#[test] +fn save_as_template_keeps_the_document_and_a_picture_and_opens_as_new() { + let dir = temp_dir("user"); + let folder = dir.display().to_string(); + let mut s = Session::new(anicraft_doc::sample::demo()); + let mine = dir.join("walk.anicraft"); + run(&mut s, "file.save_as", json!({"path": mine.display().to_string()})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + let doc = s.doc.clone(); + let v = run(&mut s, "file.save_as_template", json!({"folder": folder, "name": " Walk cycle ", "category": "Characters"})); + let path = dir.join("Characters").join("Walk cycle.anicraft"); + assert_eq!(v["path"].as_str(), Some(path.display().to_string().as_str())); + assert!(path.is_file() && path.with_extension("png").is_file(), "{v}"); + assert_eq!(s.path.as_deref(), Some(mine.as_path()), "the open document keeps its own file"); + assert!(s.is_dirty(), "and its unsaved changes"); + // Listed, with its picture; a default category when none is given. + run(&mut s, "file.save_as_template", json!({"folder": folder, "name": "Blank"})); + let list = run(&mut s, "file.templates", json!({"folder": folder})); + let user: Vec<(String, String, bool)> = list["user"].as_array().unwrap().iter().map(|t| (t["category"].as_str().unwrap().to_string(), t["name"].as_str().unwrap().to_string(), t["thumbnail"].is_string())).collect(); + assert_eq!(user, [("Characters".to_string(), "Walk cycle".to_string(), true), (crate::cmds_template::DEFAULT_CATEGORY.to_string(), "Blank".to_string(), true)]); + // Opened from the template: the same document, new and untitled. + let mut other = Session::default(); + run(&mut other, "file.new_from_template", json!({"path": path.display().to_string()})); + assert!(other.doc == doc && other.path.is_none() && !other.is_dirty()); + assert!(other.recent.is_empty(), "a template is not a recent file"); + // The same name again replaces it only when confirmed. + let again = json!({"folder": folder, "name": "Walk cycle", "category": "Characters"}); + assert!(s.confirmation("file.save_as_template", &again).is_some_and(|c| c.irreversible)); + assert!(s.execute("file.save_as_template", &again).is_err()); + let mut confirmed = again.clone(); + confirmed["confirm"] = json!(true); + run(&mut s, "file.save_as_template", confirmed); + // Names that can't be file names are refused before anything is written. + for (name, category) in [("", "x"), (" ", "x"), ("a/b", "x"), ("a", "..\\up"), ("CON", "x"), ("ok", "lpt1"), (".hidden", "x"), ("x", "dot."), ("tab\there", "x")] { + let p = json!({"folder": folder, "name": name, "category": category}); + assert!(s.execute("file.save_as_template", &p).is_err(), "{p}"); + } + let long = "x".repeat(crate::cmds_template::MAX_NAME_CHARS + 1); + assert!(s.execute("file.save_as_template", &json!({"folder": folder, "name": long})).is_err()); + // Deleting always confirms, and takes the picture and the emptied category with it. + let del = json!({"folder": folder, "name": "Walk cycle", "category": "Characters"}); + assert!(s.execute("file.delete_template", &del).is_err()); + assert!(path.is_file()); + let mut del = del; + del["confirm"] = json!(true); + run(&mut s, "file.delete_template", del.clone()); + assert!(!path.exists() && !path.with_extension("png").exists() && !dir.join("Characters").exists()); + assert!(s.execute("file.delete_template", &del).is_err(), "gone already"); + assert_eq!(run(&mut s, "file.templates", json!({"folder": folder}))["user"].as_array().map(Vec::len), Some(1)); + // A folder that isn't there lists nothing, and a non-template file doesn't open. + assert_eq!(run(&mut s, "file.templates", json!({"folder": dir.join("nope").display().to_string()}))["user"].as_array().map(Vec::len), Some(0)); + assert!(s.execute("file.new_from_template", &json!({"path": dir.join("x.png").display().to_string(), "confirm": true})).is_err()); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d1f34945..0334ece1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -368,15 +368,10 @@ fn animated_gif_export() { let bytes = std::fs::read(&path).unwrap(); assert_eq!(&bytes[..6], b"GIF89a"); // decode: 48 frames, 160×90, total delay ≈ 2 s at 24 fps - let mut opts = gif::DecodeOptions::new(); - opts.set_color_output(gif::ColorOutput::Indexed); - let mut dec = opts.read_info(std::fs::File::open(&path).unwrap()).unwrap(); - assert_eq!((dec.width(), dec.height()), (160, 90)); - let (mut n, mut total) = (0, 0u32); - while let Some(f) = dec.read_next_frame().unwrap() { - n += 1; - total += u32::from(f.delay); - } + let info = craft_gif::scan(&bytes, 1024).unwrap(); + assert_eq!((info.width, info.height), (160, 90)); + let n = info.frames.len(); + let total: u32 = info.frames.iter().map(|f| u32::from(f.delay_cs)).sum(); assert_eq!(n, 48); assert_eq!(total, 200, "delays sum to exactly 2 s"); // overwriting asks; absurd sizes are refused @@ -513,7 +508,7 @@ fn save_load_round_trip() { /// Adversarial params for every command: must return Ok or Err, never panic. #[test] fn panic_hunt_every_command() { - let hostile: Vec = vec![ + let mut hostile: Vec = vec![ Value::Null, json!({}), json!([]), @@ -552,6 +547,17 @@ fn panic_hunt_every_command() { json!({"id": 3, "profile": [[0, 1e30, -5], ["x"], [0.5, 16, 16]], "index": u64::MAX, "t": -0.5, "left": 1e9, "width": f64::MAX}), json!({"id": 3, "profile": "taper_both", "index": 0, "t": 1, "x": 1e30, "y": -1e30, "left": 0, "right": 16}), json!({"profile": (0..500).map(|i| json!([f64::from(i) / 500.0, 2, 2])).collect::>()}), + // Brush presets, curves and the Paint Brush (ADR 0068): junk, extremes, both modes. + json!({"points": [[0, 0, 0.5], [300, 40, 1], [600, 0, 0]], "preset": "chalk", "as_stroke": true, "curve": [[0, 1], [0.5, 0], [1, 1]], "taper_start": 50, "taper_end": 50}), + json!({"points": [[0, 0], [1e5, 1e5]], "preset": "dotted", "spacing": 5, "jitter": 50, "size": 2000, "name": "x", "to": "y"}), + json!({"points": [[0, 0], [10, 0]], "preset": "nope", "curve": "wobbly", "spacing": 1, "jitter": -1, "name": "", "from": "missing", "names": [1, 2]}), + json!({"points": [[f64::MAX, 0]], "curve": [[f64::NAN, 2]], "pressure_size": "yes", "pressure_opacity": 1, "as_stroke": "no", "name": "Chalk", "to": "Pencil"}), + json!({"points": (0..2000).map(|i| json!([f64::from(i), f64::from(i % 7) * 3.0, f64::from(i % 3) * 0.5])).collect::>(), "preset": "ink_pen", "as_stroke": true, "name": "a".repeat(5000)}), + // Swatches (ADR 0078): junk kinds, indices and paints, both targets, a missing file. + json!({"index": 0, "from": 18, "to": 0, "target": "stroke", "name": "a".repeat(5000)}), + json!({"index": 12, "target": "stroke", "selection": false, "type": "radial", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}], "focal": 0.98, "at": 0}), + json!({"index": u64::MAX, "from": "nowhere", "target": 3, "type": "conic", "stops": [{"offset": 2, "color": "#00"}], "spread": "wrap", "path": "no/such/palette.gpl"}), + json!({"color": "#ff000000", "name": "\u{0}\n", "at": u64::MAX, "replace": true, "path": ""}), // Stroke styles (ADR 0046): junk, extremes and patterns that would be very fine. json!({"cap": "none", "join": "miter", "miter": 100, "dash": [0, 1e-30], "dash_offset": -1e4, "style": "dashed"}), json!({"cap": 7, "join": "mitre", "miter": f64::NAN, "dash": vec![1e4; 16], "dot_spacing": 0, "style": "dotted"}), @@ -617,12 +623,48 @@ fn panic_hunt_every_command() { json!({"from": 10, "to": 12, "head": [0, 0], "tail": [1e30, 0], "name": "x".repeat(300)}), json!({"from": 12, "to": 10, "head": [5], "tail": "x", "bone": u64::MAX}), json!({"from": 11, "to": 13, "head": [-1e6, 1e6], "layer": 101}), + // Springs and joint translation (ADR 0084): hostile strengths, damping and limits. + json!({"bone": 102, "axis": "x", "enabled": true, "constrain": true, "min": 1e30, "max": -1e30, "strength": 1e30, "damping": -1e30, "slide_x": 1e30, "slide_y": f64::NAN}), + json!({"bone": 102, "axis": "y", "enabled": "yes", "constrain": false, "min": -10_000, "max": 10_000, "strength": 100, "damping": 0, "slide_y": -10_000, "x": 1e5, "y": -1e5}), + json!({"bone": 100, "axis": 7, "min": 0, "max": 0, "strength": 0.000_001, "damping": 99.999_99, "slide_x": 0.5, "enabled": false}), + json!({"bone": u64::MAX, "axis": "x", "strength": f64::MAX, "damping": f64::MIN, "enabled": true, "layer": 101}), + // Shape armatures (ADR 0071): the shaped session's tail is 3, its bones 100 and 103. + json!({"shape": 3, "head": [1e30, 0], "tail": [-1e30, 0], "parent": 103, "points": [0, 1, u64::MAX], "mode": "add"}), + json!({"shape": 3, "head": [150, 150], "tail": [150, 150], "bone": 103, "points": (0..30).collect::>(), "mode": "remove"}), + json!({"parent": 100, "tail": [250, 290], "bone": 100, "points": [], "mode": "auto", "points_": true}), + json!({"bone": 100, "points": ["a", -1, 1e30], "mode": 7}), // Edit Multiple Frames (ADR 0047): ranges past the end or reversed, items that aren't // there or aren't triples, moves at the limits. json!({"first": 0, "last": 99_999, "dx": 1e7, "dy": -1e7, "items": [[0, 0, 1], "x", [u64::MAX, u64::MAX, u64::MAX]]}), json!({"first": u64::MAX, "last": 0, "dx": 5, "dy": 5, "items": []}), json!({"first": 40, "last": 0, "dx": 3, "dy": -2}), json!({"first": 0, "last": 100_001, "dx": f64::NAN, "dy": 0, "items": [[1, 2]]}), + // Edit Multiple Frames, complete (ADR 0051): transforms at the limits, pivots and edges + // that aren't, pastes onto ranges with nothing in them, merges of what isn't raw. + json!({"first": 0, "last": 99_999, "a": 0, "b": 0, "c": 0, "d": 0, "e": 1e30, "f": 0, "merge": "x"}), + json!({"first": 0, "last": 50, "a": 1e9, "b": 1, "c": 1, "d": 1e-9, "e": 0, "f": f64::NAN}), + json!({"first": 0, "last": 50, "rotate": 1e9, "scale_x": 1e-9, "scale_y": -1e9, "skew_x": 90, "skew_y": -90, "pivot": [1e30, 0]}), + json!({"first": 0, "last": 50, "rotate": 45, "skew_x": 89.999, "pivot": [5], "edge": "nope", "to_stage": "x"}), + json!({"first": 0, "last": 50, "scale_x": -1, "pivot": [0, 0], "edge": "vcenter", "to_stage": true, "merge": false}), + json!({"first": 3, "last": 1, "edge": "right", "layer": u64::MAX, "items": [[0, 0, 0]]}), + json!({"first": 0, "last": 99_999, "layer": 0, "items": (0..200).map(|i| json!([i, i, i])).collect::>()}), + // 9-slice guides (ADR 0055): crossed, huge, not numbers, moved while turned off. + json!({"on": true, "left": 90, "right": 10, "top": 1e30, "bottom": -1e30, "symbol": 1}), + json!({"on": false, "left": 5}), + json!({"on": "x", "left": f64::NAN, "right": "y", "top": null}), + json!({"left": -1e7, "right": 1e7, "top": -1e7, "bottom": 1e7}), + json!({"on": true, "symbol": u64::MAX}), + // Publish Settings (ADR 0060): ends past the movie, junk scales and names, whole + // profiles out of range. + json!({"format": "gif", "from": u64::MAX, "to": -1, "scale": f64::NAN, "output": "{name}\u{0}.gif"}), + json!({"format": "png", "frame": u64::MAX, "scale": 1e-30, "output": "a/b/c/../../{name}"}), + json!({"format": "sprite_sheet", "columns": u64::MAX, "padding": 256, "from": null, "to": null, "output": "{name}{name}{name}.png"}), + json!({"profile": {"gif": {"scale": 1e30, "range": {"from": 5, "to": 1}, "output": ""}, "audio": {"bits": 3, "rate": 0}, "html": {"title": "x"}}}), + json!({"profile": {"png": {"frame": 99_999, "enabled": true}}, "format": "svg", "enabled": true}), + // Desktop integration (ADR 0094): system folders, missing files, line breaks, junk. + json!({"appimage": "/no/such/AniCraft.AppImage", "data_home": "/usr/share", "refresh": "x"}), + json!({"appimage": "/a +Exec=evil", "data_home": "relative/share", "refresh": false}), ]; // File commands are exercised separately (they touch the disk). let skip = |id: &str| id.starts_with("file."); @@ -661,8 +703,44 @@ fn panic_hunt_every_command() { for (id, p) in [("bone.pose", json!({"bone": b1, "angle": 30, "frame": 8})), ("bone.set_limits", json!({"bone": b2, "min": -30, "max": 30})), ("bone.pin", json!({"bone": b1, "pinned": true}))] { rig.execute(id, &p).unwrap(); } + // A bouncy, sliding elbow (ADR 0084), the root moving under it. + for (id, p) in [("bone.set_spring", json!({"bone": b2, "strength": 100, "damping": 0})), ("bone.set_translation", json!({"bone": b2, "axis": "x", "min": -40, "max": 40})), ("bone.pose", json!({"dx": 0, "dy": 90, "frame": 12}))] { + rig.execute(id, &p).unwrap(); + } assert_eq!((b1, b2), (100, 102), "the hostile params name these bones"); rig.set_frame(4); + // A shape armature: a tail with two bones, bent at frame 8, a point bound by hand (ADR 0071). + let mut shaped = Session::default(); + shaped.style.object_drawing = false; + shaped.execute("draw.rect", &json!({"x": 100, "y": 140, "w": 200, "h": 20})).unwrap(); + shaped.doc.next_id = 100; + let tail = shaped.doc.timeline(0).layers[0].keyframes[0].elements[0].id.0; + let sb1 = shaped.execute("bone.add_in_shape", &json!({"shape": tail, "head": [100, 150], "tail": [200, 150]})).unwrap()["bone"].as_u64().unwrap(); + let sb2 = shaped.execute("bone.add_in_shape", &json!({"parent": sb1, "tail": [300, 150]})).unwrap()["bone"].as_u64().unwrap(); + for (id, p) in [("bone.pose", json!({"bone": sb2, "angle": 60, "frame": 8})), ("bone.bind", json!({"bone": sb1, "points": [0], "mode": "add"}))] { + shaped.execute(id, &p).unwrap(); + } + assert_eq!((tail, sb1, sb2), (3, 100, 103), "the hostile params name these"); + shaped.set_frame(4); + // Asset Warp (ADR 0079): a warped rectangle and bitmap, a pin moved at frame 8 inside a + // tween, the playhead mid-tween, the rectangle selected. + let (mut warped, wr, wb) = crate::tests_warp::warped(); + let pin = |s: &mut Session, el: u64, x: f32, y: f32| s.execute("warp.pin_add", &json!({"element": el, "x": x, "y": y})).unwrap()["pin"].as_u64().unwrap(); + let (wp1, wp2) = (pin(&mut warped, wr, 110.0, 140.0), pin(&mut warped, wr, 290.0, 140.0)); + let wp3 = pin(&mut warped, wb, 290.0, 230.0); + for (id, p) in [("timeline.goto", json!({"frame": 8})), ("timeline.insert_keyframe", json!({})), ("timeline.goto", json!({"frame": 0})), ("timeline.create_tween", json!({})), ("warp.pin_move", json!({"element": wr, "pin": wp2, "x": 300, "y": 220, "frame": 8}))] { + warped.execute(id, &p).unwrap(); + } + warped.selection = crate::Selection::only(warped.layer, [anicraft_doc::ElementId(wr)]); + warped.set_frame(4); + hostile.extend([ + json!({"element": wr, "pin": wp2, "x": 1e30, "y": -1e30, "dx": 1e7, "dy": -1e7, "frame": 99_999, "resolution": 0}), + json!({"element": wr, "pin": wp1, "x": 200, "y": 140, "dx": f64::NAN, "resolution": 48}), + json!({"element": wb, "pin": wp3, "x": 0, "y": 0, "dx": -1e6, "dy": 1e6, "resolution": u64::MAX}), + json!({"element": wb, "pin": u64::MAX, "x": 290, "y": 231, "frame": 4, "resolution": 2}), + json!({"element": u64::MAX, "pin": "a", "x": "b", "y": [1], "resolution": -3}), + json!({"element": wr, "x": 299.9, "y": 179.9, "pin": wp1, "dx": 0.0001}), + ]); // Raw drawings and an object on two layers, selected on both through a marquee's cut that // is still provisional (ADR 0041, 0044). let mut layered = Session::default(); @@ -677,7 +755,133 @@ fn panic_hunt_every_command() { layered.execute(id, &p).unwrap(); } assert_eq!(layered.selected_layers().len(), 2, "the fuzz starts with a selection on two layers"); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered] { + // Raw drawings inside a symbol open for editing in place (ADR 0045), with a point added. + let mut in_symbol = Session::default(); + in_symbol.style.object_drawing = false; + for (id, p) in [ + ("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})), + ("modify.convert_to_symbol", json!({"name": "Inner"})), + ("element.translate", json!({"dx": 30, "dy": 15})), + ("symbol.edit", json!({})), + ("draw.rect", json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"})), + ("raw.add_point", json!({"x": 45, "y": 90})), + ] { + in_symbol.execute(id, &p).unwrap(); + } + assert_eq!(in_symbol.editing.len(), 1, "the fuzz starts inside a symbol"); + // Raw drawings on several keyframes, artwork copied from two of them (ADR 0051). + let mut keyed = Session::default(); + keyed.style.object_drawing = false; + for (id, p) in [ + ("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})), + ("draw.rect", json!({"x": 100, "y": 0, "w": 60, "h": 60, "fill": "#ff0000"})), + ("timeline.goto", json!({"frame": 4})), + ("timeline.insert_keyframe", json!({})), + ("timeline.goto", json!({"frame": 8})), + ("timeline.insert_keyframe", json!({})), + ("frames.copy", json!({"first": 0, "last": 8})), + ("timeline.goto", json!({"frame": 4})), + ] { + keyed.execute(id, &p).unwrap(); + } + // Library folders, nested, with items in them (ADR 0050); the fuzz moves, renames and + // deletes them, folders into themselves, names that clash or hold a slash. + let mut library = Session::new(sample::demo()); + let outer = library.execute("library.new_folder", &json!({"name": "Characters"})).unwrap()["folder"].as_u64().unwrap(); + let inner = library.execute("library.new_folder", &json!({"name": "Hero", "parent": outer})).unwrap()["folder"].as_u64().unwrap(); + let ball = library.doc.library.first().map(|x| x.id.0).unwrap(); + library.execute("library.move", &json!({"items": [{"symbol": ball}], "to": inner})).unwrap(); + library.execute("library.duplicate", &json!({"symbol": ball})).unwrap(); + // ...and a bitmap placed on the stage, for Swap Bitmap (ADR 0053). + let bm = anicraft_doc::BitmapId(library.doc.alloc_id()); + let png = anicraft_render::encode_png(3, 2, &[0, 0, 255, 255].repeat(6)).unwrap(); + library.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(bm, "b.png", png).unwrap())); + library.execute("library.place", &json!({"bitmap": bm.0})).unwrap(); + hostile.push(json!({"bitmap": bm.0, "items": [{"bitmap": bm.0}, {"symbol": ball}], "x": 3, "y": 4})); + hostile.extend([ + json!({"items": [{"folder": outer}], "to": inner, "folder": outer, "name": "Hero", "parent": inner, "confirm": true}), + json!({"items": [{"folder": inner}, {"symbol": ball}, {"folder": inner}], "to": null, "folder": inner, "name": "a/b", "symbol": ball}), + json!({"items": [{"symbol": ball, "folder": outer}, "x", {"sound": u64::MAX}], "to": u64::MAX, "parent": "x", "name": " "}), + json!({"items": (0..200).map(|i| json!({"folder": i})).collect::>(), "to": outer, "symbol": ball, "name": "x".repeat(300), "on": "x", "bitmap": 1}), + json!({"items": [{"symbol": ball}], "to": outer, "symbol": ball, "name": "Ball copy", "confirm": true}), + // Drops from the Library and Swap Bitmap (ADR 0053): mixed lists, two sounds, far points. + json!({"items": [{"symbol": ball}, {"sound": SOUND}, {"bitmap": u64::MAX}], "x": 1e300, "y": -1e300}), + json!({"items": [{"sound": SOUND}, {"sound": SOUND}, {"symbol": ball}], "x": 999_999, "y": -999_999, "bitmap": 0}), + json!({"items": [{"symbol": ball}, {"symbol": ball}, {"folder": inner}, null], "x": "a"}), + json!({"items": (0..1500).map(|_| json!({"symbol": ball})).collect::>(), "x": 0, "y": 0}), + json!({"sound": SOUND, "symbol": ball, "x": 10, "y": 10}), + // Find and Replace and the Movie Explorer (ADR 0058): patterns that are slow in + // backtracking engines or too large, replacements that would nest a symbol in itself, + // stale hits, junk paths, rows and pages. + json!({"kind": "text", "text": "(a+)+$", "regex": true, "with": "$1$1$1${x}", "in": ["text", "labels", "layers", "instances", "scripts"], "scope": "document"}), + json!({"kind": "text", "text": "a{1000}{1000}", "regex": true, "with": ""}), + json!({"kind": "text", "text": "", "with": "x"}), + json!({"kind": "text", "text": "[a-z]", "regex": true, "with": "", "whole_word": false, "match_case": true, "confirm": true}), + json!({"kind": "text", "text": "L", "with": "", "at": {"scene": 0, "layer": 1, "field": "layer_name", "start": u64::MAX}}), + json!({"kind": "text", "text": "e", "with": "x".repeat(1000), "at": {"symbol": ball, "layer": u64::MAX, "field": "text", "frame": -1}}), + json!({"kind": "color", "color": "#ff0000", "with": "#00ff00", "in": ["fills", "strokes", "text", "nope"]}), + json!({"kind": "color", "color": "#3d8bfd", "with": "#000000", "scope": "document"}), + json!({"kind": "font", "font": "Inter", "with": "No Such Font"}), + json!({"kind": "symbol", "symbol": ball, "with": ball, "scope": "document"}), + json!({"kind": "sound", "sound": SOUND, "with": SOUND}), + json!({"kind": "bitmap", "bitmap": bm.0, "with": bm.0, "scope": "document"}), + json!({"kind": "nope", "layer": u64::MAX, "path": [{"layer": 1, "frame": u32::MAX, "element": u64::MAX}], "symbol": ball, "scene": 0}), + json!({"path": (0..100).map(|i| json!({"layer": i, "frame": i, "element": i})).collect::>(), "layer": 1}), + json!({"all": true, "filter": "a", "show": {"frames": false, "symbols": "x"}, "expanded": ["s0", 5], "offset": u64::MAX, "limit": u64::MAX}), + json!({"all": true, "scope": "scene", "definitions": false, "show": {"frames": false}, "limit": 0}), + ]); + // Eases (ADR 0081): a classic tween with a custom ease of several segments and property + // groups of their own, an ease saved and one copied; the fuzz edits, saves and pastes them + // with hostile curves (NaN-like and reversed points, thousands of them, ends that move). + let mut eased = Session::new(sample::demo()); + let tl = eased.doc.timeline(0).layers.iter().find(|l| l.keyframes.first().is_some_and(|k| k.tween.is_some() && k.motion.is_none())).map(|l| l.id.0).unwrap(); + for (id, p) in [ + ("timeline.set_easing", json!({"easing": {"custom": [[0, 0], [0.2, 1.4], [0.3, 1.4], [0.4, 1.4], [0.5, 1.4], [0.6, 0.8], [0.7, 0.8], [0.8, 0.8], [0.9, 1], [1, 1]]}, "frame": 0, "layer": tl})), + ("ease.separate", json!({"separate": true, "frame": 0, "layer": tl})), + ("ease.set", json!({"easing": "ElasticOut", "group": "rotation", "frame": 0, "layer": tl})), + ("ease.save", json!({"name": "Wobble", "easing": "BounceOut"})), + ("ease.copy", json!({"frame": 0, "layer": tl})), + ("timeline.goto", json!({"frame": 5})), + ("layer.select", json!({"layer": tl})), + ] { + eased.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + } + hostile.extend([ + json!({"easing": {"custom": (0..30_000).map(|i| json!([f64::from(i) / 30_000.0, f64::from(i % 7) * 1e30])).collect::>()}, "t": 0.5, "index": 1, "x": 0.5, "y": 1e30, "handle": "out", "smooth": true, "name": "Wobble", "group": "position"}), + json!({"easing": {"custom": {"points": [{"at": {"x": 1, "y": 1}}, {"at": {"x": -5, "y": 1e30}, "in": {"x": 9, "y": -1e30}}, {"at": {"x": 0.5, "y": 0.5}, "out": {"x": -9, "y": 0}}]}}, "saved": "Wobble", "index": 0, "handle": "sideways", "t": 2}), + json!({"easing": {"custom": {"points": (0..20_000).map(|i| json!({"at": {"x": f64::from(20_000 - i) / 20_000.0, "y": 0.5}})).collect::>()}}, "saved": "Wobble", "index": u64::MAX, "x": f64::MAX, "y": f64::MIN}), + json!({"easing": {"saved": 3}, "group": "sparkle", "to": "", "name": "a".repeat(500), "replace": "yes", "separate": true}), + json!({"easing": {"saved": "Wobble"}, "group": "filters", "name": "Wobble", "replace": true, "to": "wobble", "separate": false, "property": "x", "index": 1, "smooth": false}), + json!({"easing": {"custom": [[0, 0], [1, 1]]}, "t": f64::NAN, "index": 1, "handle": "in", "x": -1e7, "y": 1e7, "property": "nope", "saved": ""}), + ]); + // A button open for editing, its hit area drawn over its other states (ADR 0057). + let mut button = Session::new(sample::interactive()); + if let Some(id) = button.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id) { + button.execute("symbol.edit", &json!({"symbol": id.0})).unwrap(); + } + // Groups (ADR 0073): raw shapes, an object and a symbol instance in a group inside a group, + // the outer one moved and translucent, the inner one open for editing in place. + let mut grouped = Session::new(sample::demo()); + grouped.style.object_drawing = false; + for (id, p) in [ + ("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})), + ("draw.ellipse", json!({"x": 20, "y": 20, "w": 60, "h": 60, "fill": "#ff0000", "object": true})), + ("edit.select_all", json!({})), + ("modify.group", json!({})), + ("draw.rect", json!({"x": 100, "y": 0, "w": 60, "h": 60, "object": true})), + ("edit.select_all", json!({})), + ("modify.group", json!({})), + ("element.translate", json!({"dx": 30, "dy": 15})), + ("element.set_alpha", json!({"alpha": 0.5})), + ("symbol.edit", json!({})), + ("edit.select_all", json!({})), + ] { + grouped.execute(id, &p).unwrap(); + } + let inner = grouped.visible_elements().into_iter().find(|e| matches!(e.kind, anicraft_doc::ElementKind::Group { .. })).map(|e| e.id.0).unwrap(); + grouped.execute("symbol.edit", &json!({"id": inner})).unwrap(); + assert_eq!(grouped.editing.len(), 2, "the fuzz starts inside a group inside a group"); + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, warped, layered, in_symbol, keyed, library, button, grouped, eased] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { @@ -689,14 +893,27 @@ fn panic_hunt_every_command() { let _ = s.execute(spec.id, p); } } - // The document must still evaluate and render. + // The document must still evaluate and render, and so must what the stage shows. for f in [0, 1, 5, 47, 1000] { let _ = anicraft_render::render_frame(&s.doc, f, 0.1); } + s.hit_area = Some((anicraft_doc::Rgba::WHITE, 0.4)); + let pic = s.stage_picture(); + // ...and every button's hit area draws, under a pointer that goes over and presses. + let mut ns = anicraft_doc::player::NoScripts; + let st = anicraft_doc::player::start(&s.doc, &mut ns).state; + let p = anicraft_geom::Vec2::new(640.0, 400.0); + let st = anicraft_doc::player::input(&s.doc, &st, &[anicraft_doc::player::Event::Move(p), anicraft_doc::player::Event::Down(p), anicraft_doc::player::Event::Up(p)], &mut ns).state; + let _ = anicraft_render::render(&anicraft_doc::player::hit_overlay(&s.doc, &st, anicraft_doc::Rgba::WHITE, 0.4), &anicraft_render::View { transform: anicraft_geom::Affine::scale(0.1, 0.1), width: 128, height: 72, background: None }); + let _ = anicraft_render::render_frame(&pic.doc, pic.frame, 0.1); // ...and its sounds lay out and mix. let voices = anicraft_doc::sound::voices(&s.doc, 8000); let mut out = vec![0.0; 2 * 4096]; anicraft_doc::audio::mix(&voices, 8000, Default::default(), 0, &mut out); + // ...and its Library tree stays whole: nothing a load would have to repair. + let mut loaded = s.doc.clone(); + loaded.sanitize(); + assert_eq!(loaded.library_tree, s.doc.library_tree); } } @@ -1225,7 +1442,7 @@ fn opening_an_xfl_folder_imports_it_untitled() { assert_eq!((s.doc.stage.width, s.doc.stage.fps), (320, 12.0)); assert_eq!(s.doc.timeline(s.scene).layers[0].name, "Art"); assert_eq!(s.doc.frame_count(), 6); - assert!(v["report"].as_str().unwrap().contains("1 dynamic and input text fields (imported as static text)"), "{v}"); + assert!(v["report"].as_str().unwrap().contains("Runs in Test Movie: 1 dynamic text fields"), "{v}"); assert!(s.path.is_none(), "imported documents are untitled: Save never writes over the original"); assert!(s.execute("file.save", &json!({})).is_err()); // It renders. @@ -1248,6 +1465,8 @@ fn opening_an_xfl_folder_imports_it_untitled() { run(&mut back, "file.open", json!({"path": file.display().to_string()})); let ElementKind::Text(t) = &back.doc.timeline(0).layers[0].keyframes[0].elements.iter().find(|e| e.id == text.id).unwrap().kind else { panic!("text") }; assert_eq!((t.text.as_str(), t.size, t.bold), ("Hello again", 20.0, true)); + assert_eq!(t.kind(), anicraft_doc::TextKind::Dynamic, "a dynamic field stays one (ADR 0066)"); + assert_eq!((t.box_width, t.field.as_ref().map(|f| f.lines)), (200.0, Some(anicraft_doc::LineType::Single))); } std::fs::remove_dir_all(&dir).ok(); } @@ -1382,6 +1601,99 @@ fn masked_frames_round_trip_through_svg_onto_mask_layers() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn soft_masks_round_trip_through_svg_onto_soft_mask_layers() { + // A grey ellipse as a luminance mask (ADR 0070) over an orange rect, on a dark background. + let mut src = Session::default(); + run(&mut src, "draw.rect", json!({"x": 0, "y": 0, "w": 640, "h": 360, "fill": "#20304a"})); + run(&mut src, "layer.new", json!({"name": "Art"})); + run(&mut src, "draw.rect", json!({"x": 100, "y": 60, "w": 400, "h": 240, "fill": "#ff6b4a"})); + run(&mut src, "layer.new", json!({"name": "Mask"})); + run(&mut src, "draw.ellipse", json!({"x": 180, "y": 80, "w": 260, "h": 200, "fill": "#808080", "stroke": null})); + run(&mut src, "layer.toggle_mask", json!({})); + run(&mut src, "layer.set_mask", json!({"mask": "luminance"})); + // The middle shows half the orange (grey #808080 is 0.502 bright) over the background. + let pm = anicraft_render::render_frame(&src.doc, 0, 1.0).unwrap(); + let px = pm.pixel(310, 180).unwrap(); + let k = 128.0 / 255.0; + let want = [k * 1.0 + (1.0 - k) * 0x20 as f32 / 255.0, k * 0x6b as f32 / 255.0 + (1.0 - k) * 0x30 as f32 / 255.0]; + assert!((px[0] - want[0]).abs() < 2e-3 && (px[1] - want[1]).abs() < 2e-3, "{px:?} vs {want:?}"); + let svg_text = crate::cmds_file::frame_svg(&src.doc, 0); + assert!(svg_text.contains("() / a.len() as f64; + assert!(mean < 0.01 && worst <= 2, "mean {mean:.3}, worst {worst} of 255"); + assert_eq!(crate::cmds_file::frame_svg(&s.doc, 0).matches(" = tl.layers.iter().filter(|l| l.kind == anicraft_doc::LayerKind::Mask).map(|l| l.mask_mode).collect(); + modes.sort_by_key(|m| m.key()); + assert_eq!(modes, [anicraft_doc::MaskMode::Alpha, anicraft_doc::MaskMode::Luminance]); + let pm = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let px = |x, y| pm.pixel(x, y).unwrap(); + // Alpha mask: red fades out left to right, x 25 → 1 − 25.5 / 100. + for (x, y) in [(25u32, 10u32), (75, 10)] { + let want = 1.0 - (x as f32 + 0.5) / 100.0; + assert!((px(x, y)[0] - want).abs() < 6e-3 && px(x, y)[1] < 1e-3, "({x}, {y}): {:?} vs {want}", px(x, y)); + } + // Luminance mask: #808080 shows 128 / 255 of the green. + assert!((px(150, 95)[1] - 128.0 / 255.0).abs() < 3e-3 && px(150, 95)[0] < 1e-3, "{:?}", px(150, 95)); + // The text follows the arc, centred on it, when this computer has fonts. + if !anicraft_text::Fonts::get().families().is_empty() { + let els: Vec> = s.timeline().layers.iter().filter_map(|l| anicraft_doc::evaluate_layer_elements(l, 0)).flat_map(|(_, e)| e.into_owned()).collect(); + let text = els.into_iter().find_map(|e| match &e.kind { + anicraft_doc::ElementKind::Text(t) => Some((e.transform, t.clone())), + _ => None, + }); + let (xf, t) = text.expect("the text"); + assert_eq!(t.text, "on the arc"); + let on = t.on_path.as_ref().expect("on its path"); + assert!(t.align == anicraft_doc::TextAlign::Center && on.offset > 50.0); + let b = t.outline.bounds().transformed(&xf); + assert!((b.center().x - 100.0).abs() < 4.0 && b.min.y > 20.0 && b.max.y < 70.0, "{b:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn imported_svg_text_is_editable_text() { if anicraft_text::Fonts::get().families().is_empty() { @@ -1464,7 +1776,7 @@ fn create_shape_tween_morphs_and_keeps_the_easing() { run(&mut s, "timeline.create_tween", json!({"easing": "ease-in"})); let v = run(&mut s, "timeline.create_shape_tween", json!({})); assert_eq!(v["kind"], "shape"); - let t = s.active_layer().unwrap().keyframes[0].tween.unwrap(); + let t = s.active_layer().unwrap().keyframes[0].tween.clone().unwrap(); assert_eq!(t.kind, anicraft_doc::TweenKind::Shape); assert_ne!(t.easing, anicraft_doc::Easing::Linear, "switching kinds keeps the easing"); // Midway the shape has moved off the square. @@ -1472,7 +1784,7 @@ fn create_shape_tween_morphs_and_keeps_the_easing() { let mid = item.path.bounds().transformed(&item.transform); assert!(mid.max.x > 110.0, "{mid:?}"); s.undo().unwrap(); - assert_eq!(s.active_layer().unwrap().keyframes[0].tween.unwrap().kind, anicraft_doc::TweenKind::Classic); + assert_eq!(s.active_layer().unwrap().keyframes[0].tween.clone().unwrap().kind, anicraft_doc::TweenKind::Classic); } #[test] @@ -1640,7 +1952,7 @@ fn add_motion_guide_steers_the_tween_and_stays_out_of_exports() { // Orient to path, and the guided type. run(&mut s, "layer.select", json!({"layer": art.0})); assert_eq!(run(&mut s, "timeline.set_orient", json!({"orient": true}))["orient"], true); - assert!(s.active_layer().unwrap().keyframes[0].tween.unwrap().orient); + assert!(s.active_layer().unwrap().keyframes[0].tween.clone().unwrap().orient); assert_eq!(run(&mut s, "layer.set_type", json!({"type": "normal"}))["type"], "normal"); assert_eq!(run(&mut s, "layer.set_type", json!({"type": "guided"}))["type"], "guided"); // A masked layer can't also follow a guide. @@ -1677,11 +1989,9 @@ fn sprite_sheet_export_lays_frames_in_a_grid_with_a_frame_map() { let total: u64 = frames.values().map(|f| f["duration"].as_u64().unwrap()).sum(); assert!((200..=220).contains(&total), "5 frames at 24 fps ≈ 208 ms: {total}"); // The PNG is that size, transparent between frames, and each cell matches a plain render. - let dec = png::Decoder::new(std::io::Cursor::new(std::fs::read(&sheet).unwrap())); - let mut r = dec.read_info().unwrap(); - let mut buf = vec![0; r.output_buffer_size()]; - let info = r.next_frame(&mut buf).unwrap(); - assert_eq!((info.width, info.height), (388, 146)); + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &std::fs::read(&sheet).unwrap()).unwrap(); + assert_eq!(img.dimensions(), (388, 146)); + let buf = img.to_rgba8(); let at = |x: usize, y: usize| buf[(y * 388 + x) * 4 + 3]; assert_eq!(at(129, 10), 0, "the padding is transparent"); // Replacing either file asks first; an impossible sheet is refused. @@ -1982,7 +2292,7 @@ fn blend_modes_apply_to_movie_clips_and_survive_a_save() { run(&mut s, "layer.new", json!({})); run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000"})); run(&mut s, "modify.convert_to_symbol", json!({"name": "Red"})); - // A graphic can't blend, as in Animate; a movie clip can. + // A graphic can't blend; a movie clip can. assert!(s.execute("element.set_blend", &json!({"mode": "multiply"})).unwrap_err().to_string().contains("movie clip")); run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); assert!(s.execute("element.set_blend", &json!({"mode": "sparkle"})).is_err()); @@ -2033,7 +2343,7 @@ fn filters_render_on_movie_clips_clip_after_masks_and_save() { assert!(crate::cmds_file::frame_svg(&s.doc, 0).contains(" Session { 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))) })); k }); - d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let inst = |id: u64, x: f32| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 100.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: bar, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } }); let shape = Arc::new(Element { id: ElementId(SHAPE), name: String::new(), transform: Affine::translate(100.0, 250.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::BLACK))) }); let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); diff --git a/crates/engine/src/tests_bone_chain.rs b/crates/engine/src/tests_bone_chain.rs new file mode 100644 index 00000000..61a77d0d --- /dev/null +++ b/crates/engine/src/tests_bone_chain.rs @@ -0,0 +1,97 @@ +//! A bone chain stays one chain (user report #239): bones join end to start wherever the Bone +//! tool's drag began on an instance, lengths hold, the joints stay joined through many IK drags, +//! a small pointer move is a small turn, and grabbing a bone along its length doesn't snap its +//! end to the pointer. + +use super::*; +use crate::tests_bone::{ARM, HAND, ROOT, three_bars}; +use anicraft_doc::armature; +use anicraft_geom::Vec2; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn bones(s: &mut Session) -> Vec { + run(s, "bone.info", json!({}))["armatures"][0]["bones"].as_array().cloned().unwrap_or_default() +} + +fn pt(v: &Value) -> Vec2 { + Vec2::new(v[0].as_f64().unwrap_or(f64::NAN) as f32, v[1].as_f64().unwrap_or(f64::NAN) as f32) +} + +/// The reporter's steps: a bone from the first bar to the second, then one from the second bar +/// to the third, started on the bar a little way from the first bone's end (as a quick drag does). +fn drawn_by_hand() -> (Session, u64, u64) { + let mut s = three_bars(); + let b1 = run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM, "head": [150, 100], "tail": [250, 100]}))["bone"].as_u64().unwrap(); + let b2 = run(&mut s, "bone.add", json!({"from": ARM, "to": HAND, "head": [262, 103], "tail": [350, 100]}))["bone"].as_u64().unwrap(); + (s, b1, b2) +} + +#[test] +fn a_bone_from_an_instance_on_a_chain_starts_at_its_joint() { + let (mut s, _, _) = drawn_by_hand(); + let bs = bones(&mut s); + assert!(pt(&bs[1]["head"]).distance(pt(&bs[0]["tail"])) < 1e-3, "the second bone starts where the first ends: {} vs {}", bs[1]["head"], bs[0]["tail"]); + // A root's bones still start where they were drawn (a torso's shoulders and hips). + let mut s = three_bars(); + run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM, "head": [150, 100]})); + run(&mut s, "bone.add", json!({"from": ROOT, "to": HAND, "head": [180, 100]})); + let bs = bones(&mut s); + assert!(pt(&bs[0]["head"]).distance(Vec2::new(150.0, 100.0)) < 1e-3); + assert!(pt(&bs[1]["head"]).distance(Vec2::new(180.0, 100.0)) < 1e-3); +} + +#[test] +fn repeated_ik_drags_keep_the_chain_joined_and_its_lengths() { + let (mut s, _, b2) = drawn_by_hand(); + let lengths = |bs: &[Value]| bs.iter().map(|b| pt(&b["head"]).distance(pt(&b["tail"]))).collect::>(); + let first = lengths(&bones(&mut s)); + let mut prev: Option> = None; + // Round and round, in and out of reach, several times over (400 small pointer moves). + for i in 0..400 { + let t = i as f32 / 400.0 * std::f32::consts::TAU * 3.0; + let r = 40.0 + 170.0 * (t * 0.5).sin().abs(); + let (x, y) = (150.0 + r * t.cos(), 100.0 + r * t.sin()); + run(&mut s, "bone.solve", json!({"bone": b2, "x": x, "y": y})); + let bs = bones(&mut s); + assert!(pt(&bs[0]["tail"]).distance(pt(&bs[1]["head"])) < 1e-3, "the elbow came apart at step {i}"); + for (a, b) in lengths(&bs).iter().zip(&first) { + assert!((a - b).abs() < 1e-2, "a bone changed length at step {i}: {a} vs {b}"); + } + let angles: Vec = bs.iter().map(|b| b["angle"].as_f64().unwrap_or(0.0)).collect(); + if let Some(p) = &prev { + let turn = angles.iter().zip(p).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max); + // About 4 px of pointer travel per step at 40–210 px from the shoulder. + assert!(turn < 30.0, "a small move turned a joint {turn:.1}° at step {i}"); + } + prev = Some(angles); + } +} + +#[test] +fn grabbing_a_bone_along_its_length_moves_from_where_it_was_grabbed() { + let (mut s, b1, _) = drawn_by_hand(); + let (l, arm) = { + let l = s.timeline().layers.iter().find(|l| l.armature.is_some()).cloned().unwrap(); + let arm = l.armature.clone().unwrap(); + (l, arm) + }; + let (_, els) = anicraft_doc::evaluate_layer_elements(&l, 0).unwrap(); + let pose = armature::pose_at(&l, 0).unwrap_or_default(); + // Pressed a quarter of the way along the first bone, near the shoulder. + let press = Vec2::new(175.0, 100.0); + let local = armature::grab_point(&arm, &els, &pose, anicraft_doc::BoneId(b1), press).unwrap(); + let v = run(&mut s, "bone.solve", json!({"bone": b1, "x": press.x, "y": press.y, "local": [local.x, local.y]})); + assert!(v["error"].as_f64().unwrap() < 0.05, "{v}"); + let bs = bones(&mut s); + assert!(bs[0]["angle"].as_f64().unwrap().abs() < 1e-3, "pressing alone turns nothing"); + // A small drag down turns the bone a little about the shoulder: the grabbed point follows. + run(&mut s, "bone.solve", json!({"bone": b1, "x": 175.0, "y": 105.0, "local": [local.x, local.y]})); + let a = bones(&mut s)[0]["angle"].as_f64().unwrap(); + assert!((a - 5.0f64.atan2(25.0).to_degrees()).abs() < 0.5, "{a}°"); + // The bone's end, by contrast, would have been pulled 75 px onto the pointer. + assert!(armature::grab_point(&arm, &els, &pose, anicraft_doc::BoneId(999), press).is_none()); +} diff --git a/crates/engine/src/tests_bone_spring.rs b/crates/engine/src/tests_bone_spring.rs new file mode 100644 index 00000000..d05fcd0b --- /dev/null +++ b/crates/engine/src/tests_bone_spring.rs @@ -0,0 +1,197 @@ +//! Bones, second slice (ADR 0084): joint translation, springs and editing armature members in +//! place, end to end through the commands. + +use super::*; +use crate::tests_bone::{ARM, HAND, ROOT, rigged}; +use anicraft_doc::{BoneId, SymbolKind, evaluate}; +use anicraft_geom::Affine; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn bone_at(s: &mut Session, frame: u32, bone: u64) -> Value { + let v = run(s, "bone.info", json!({"frame": frame})); + v["armatures"][0]["bones"].as_array().unwrap().iter().find(|b| b["id"] == bone).cloned().unwrap() +} + +fn num(v: &Value) -> f32 { + v.as_f64().unwrap() as f32 +} + +/// Where element `id` is drawn at movie frame `frame` (what every export sees). +fn drawn(s: &Session, frame: u32, id: u64) -> Affine { + evaluate(&s.doc, frame).items.iter().find(|i| i.element.0 == id).map(|i| i.transform).unwrap() +} + +#[test] +fn a_sliding_joint_poses_within_its_limits() { + let (mut s, b1, b2) = rigged(); + let v = run(&mut s, "bone.set_translation", json!({"bone": b2, "axis": "x", "min": 0, "max": 60})); + assert_eq!((v["enabled"].clone(), v["constrain"].clone()), (json!(true), json!(true))); + // Out of reach of the turning joints: the elbow slides out, no farther than its limit. + let r = run(&mut s, "bone.solve", json!({"bone": b2, "x": 450, "y": 100})); + assert_eq!(r["reached"], true, "{r}"); + let slide = bone_at(&mut s, 0, b2)["slide"].clone(); + assert!((num(&slide[0]) - 50.0).abs() < 0.5 && num(&slide[1]) == 0.0, "{slide}"); + let r = run(&mut s, "bone.solve", json!({"bone": b2, "x": 700, "y": 100})); + assert_eq!(r["reached"], false); + assert_eq!(num(&bone_at(&mut s, 0, b2)["slide"][0]), 60.0, "stops at the limit"); + // Within reach, it turns as before and doesn't slide. + run(&mut s, "bone.pose", json!({"bone": b2, "slide_x": 0})); + run(&mut s, "bone.solve", json!({"bone": b2, "x": 320, "y": 160})); + assert_eq!(num(&bone_at(&mut s, 0, b2)["slide"][0]), 0.0); + // Posing by number keeps to the limits; a joint that doesn't slide refuses. + assert_eq!(run(&mut s, "bone.pose", json!({"bone": b2, "slide_x": 500}))["slide"], json!([60.0, 0.0])); + assert!(s.execute("bone.pose", &json!({"bone": b1, "slide_x": 5})).unwrap_err().to_string().contains("translation")); + // The hand moved with its sliding joint: the elbow is 60 px along the arm. + let elbow = bone_at(&mut s, 0, b2)["head"].clone(); + let shoulder = bone_at(&mut s, 0, b1)["head"].clone(); + let d = Vec2::new(num(&elbow[0]) - num(&shoulder[0]), num(&elbow[1]) - num(&shoulder[1])).length(); + assert!((d - 160.0).abs() < 1e-2, "{d}"); + // Narrowing the limits brings every pose inside; turning it off slides nothing. + run(&mut s, "bone.set_translation", json!({"bone": b2, "axis": "x", "max": 20})); + assert_eq!(num(&bone_at(&mut s, 0, b2)["slide"][0]), 20.0); + run(&mut s, "bone.set_translation", json!({"bone": b2, "axis": "x", "enabled": false})); + assert_eq!(bone_at(&mut s, 0, b2)["slide"], json!([0.0, 0.0])); + assert_eq!(bone_at(&mut s, 0, b2)["slide_x"], Value::Null); + // Free sliding, and the refusals. + assert_eq!(run(&mut s, "bone.set_translation", json!({"bone": b2, "axis": "y", "enabled": true}))["constrain"], false); + for p in [json!({"bone": b2, "axis": "z", "enabled": true}), json!({"bone": b2, "axis": "x", "min": 10, "max": -10}), json!({"bone": b2, "axis": "x", "min": -1e9}), json!({"bone": b2, "axis": "x"})] { + assert!(s.execute("bone.set_translation", &p).is_err(), "{p}"); + } +} + +/// [`rigged`] with the body (the root) dropping 150 px from frame 0 to frame 8, then holding, +/// and both bones springy. +fn springy() -> (Session, u64, u64) { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.pose", json!({"dx": 0, "dy": 150, "frame": 8})); + for b in [b1, b2] { + run(&mut s, "bone.set_spring", json!({"bone": b, "strength": 40, "damping": 25})); + } + (s, b1, b2) +} + +#[test] +fn springs_swing_every_export_and_never_change_the_keyed_poses() { + let (mut s, b1, _) = springy(); + let keyed: Vec<_> = s.doc.timeline(0).layers[0].keyframes.iter().map(|k| k.pose.clone()).collect(); + // Mid-swing: the hand is drawn away from where the keyed pose has it. + let swing = num(&bone_at(&mut s, 12, b1)["swing"]); + assert!(swing.abs() > 1.0, "{swing}°"); + let mut still = s.doc.clone(); + Arc::make_mut(Arc::make_mut(&mut still.timeline_mut(0).layers[0]).armature.as_mut().unwrap()).springs_off = true; + let hand = |d: &anicraft_doc::Document, f| evaluate(d, f).items.iter().find(|i| i.element.0 == HAND).map(|i| i.transform.translation()).unwrap(); + assert!(hand(&s.doc, 12).distance(hand(&still, 12)) > 1.0); + // The keyed poses (and what commands read) are untouched. + assert_eq!(s.doc.timeline(0).layers[0].keyframes.iter().map(|k| k.pose.clone()).collect::>(), keyed); + assert_eq!(bone_at(&mut s, 12, b1)["angle"], json!(0.0)); + // A raster render is the display list: the swung hand shows in the pixels. + let (a, b) = (anicraft_render::render_frame(&s.doc, 12, 1.0).unwrap(), anicraft_render::render_frame(&still, 12, 1.0).unwrap()); + assert_ne!(a.data, b.data); + // Turning the springs off plays the keyed poses exactly. + run(&mut s, "bone.enable_springs", json!({"bone": b1, "enabled": false})); + assert_eq!(drawn(&s, 12, HAND), evaluate(&still, 12).items.iter().find(|i| i.element.0 == HAND).unwrap().transform); + assert_eq!(bone_at(&mut s, 12, b1)["swing"], json!(0.0)); + assert_eq!(run(&mut s, "bone.info", json!({}))["armatures"][0]["springs"], false); + s.undo().unwrap(); + assert!(drawn(&s, 12, HAND) != evaluate(&still, 12).items.iter().find(|i| i.element.0 == HAND).unwrap().transform, "undo turns them back on"); +} + +#[test] +fn seeking_any_frame_draws_what_playing_draws() { + let (s, _, _) = springy(); + let bits = |s: &Session, f: u32| evaluate(&s.doc, f).items.iter().map(|i| i.transform.m.map(f32::to_bits)).collect::>(); + let played: Vec<_> = (0..20).map(|f| bits(&s, f)).collect(); + for f in [19, 3, 12, 0, 12, 7, 18, 1] { + assert_eq!(bits(&s, f), played[f as usize], "frame {f}"); + } +} + +#[test] +fn damping_one_hundred_is_no_spring_and_spring_values_are_checked() { + let (mut s, b1, b2) = springy(); + let mut plain = rigged().0; + run(&mut plain, "bone.pose", json!({"dx": 0, "dy": 150, "frame": 8})); + for b in [b1, b2] { + run(&mut s, "bone.set_spring", json!({"bone": b, "damping": 100})); + } + for f in 0..20 { + assert_eq!(drawn(&s, f, HAND), drawn(&plain, f, HAND), "frame {f}"); + } + let v = run(&mut s, "bone.info", json!({})); + assert_eq!(v["armatures"][0]["bones"][0]["spring"], json!({"strength": 40.0, "damping": 100.0})); + for p in [json!({"bone": b1, "strength": 101}), json!({"bone": b1, "damping": -1}), json!({"bone": b1}), json!({"bone": 999_999, "strength": 5})] { + assert!(s.execute("bone.set_spring", &p).is_err(), "{p}"); + } + // Strength and damping both 0: no spring left in the file. + run(&mut s, "bone.set_spring", json!({"bone": b1, "strength": 0, "damping": 0})); + assert_eq!(s.doc.timeline(0).layers[0].armature.as_ref().unwrap().bone(BoneId(b1)).unwrap().spring, None); +} + +#[test] +fn springs_and_slides_survive_the_file() { + let (mut s, _, b2) = springy(); + run(&mut s, "bone.set_translation", json!({"bone": b2, "axis": "y", "min": -30, "max": 30})); + run(&mut s, "bone.pose", json!({"bone": b2, "slide_y": 12, "frame": 4})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + let b = back.timeline(0).layers[0].armature.as_ref().unwrap().bone(BoneId(b2)).cloned().unwrap(); + assert_eq!(b.slide_y, Some(anicraft_doc::Limits { min: -30.0, max: 30.0 })); + assert!(b.spring.is_some()); +} + +#[test] +fn a_members_colour_effect_filters_and_blend_edit_in_place_on_every_pose() { + let (mut s, b1, _) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 40, "frame": 10})); + // Blending and filters are for movie clips, as in Animate. + let sym = s.doc.library[0].id; + Arc::make_mut(s.doc.library.iter_mut().find(|x| x.id == sym).unwrap()).kind = SymbolKind::MovieClip; + let lid = s.doc.timeline(0).layers[0].id; + let poses_before: Vec<_> = s.doc.timeline(0).layers[0].keyframes.iter().map(|k| k.pose.clone()).collect(); + run(&mut s, "element.select", json!({"ids": [ARM], "layer": lid.0})); + let steps = s.history_len(); + run(&mut s, "element.set_color_effect", json!({"style": "tint", "tint": "#ff0000", "tint_amount": 50})); + run(&mut s, "element.set_blend", json!({"mode": "multiply"})); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "glow"}]})); + assert_eq!(s.history_len(), steps + 3, "one undo step each"); + let l = s.doc.timeline(0).layers[0].clone(); + assert_eq!(l.keyframes.len(), 2, "no frame keyed: the member changed on every pose"); + for k in &l.keyframes { + let e = k.elements.iter().find(|e| e.id.0 == ARM).unwrap(); + assert!(matches!(e.color, anicraft_doc::ColorEffect::Tint { .. }), "{:?}", e.color); + let ElementKind::Symbol { blend, filters, .. } = &e.kind else { panic!() }; + assert_eq!((*blend, filters.len()), (anicraft_doc::BlendMode::Multiply, 1)); + // The others are untouched. + assert_eq!(k.elements.iter().find(|e| e.id.0 == HAND).unwrap().color, anicraft_doc::ColorEffect::default()); + } + assert_eq!(l.keyframes.iter().map(|k| k.pose.clone()).collect::>(), poses_before, "the armature is intact"); + // In the tween between the poses the member keeps its look and still moves with its bone. + let mid = evaluate(&s.doc, 5); + let arm = mid.items.iter().find(|i| i.element.0 == ARM).unwrap(); + assert!(arm.transform.translation().distance(Vec2::new(200.0, 100.0)) < 1e-3); + // Moving it is still the bones' job. + assert!(s.execute("element.translate", &json!({"dx": 5, "dy": 0})).unwrap_err().to_string().contains("armature")); + s.undo().unwrap(); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(s.doc.timeline(0).layers[0].keyframes[1].elements.iter().find(|e| e.id.0 == ARM).unwrap().color, anicraft_doc::ColorEffect::default()); + // A locked armature layer refuses. + run(&mut s, "element.select", json!({"ids": [ROOT], "layer": lid.0})); + run(&mut s, "layer.toggle_lock", json!({"layer": lid.0})); + assert!(s.execute("element.set_alpha", &json!({"alpha": 0.5})).is_err()); +} + +#[test] +fn plug_ins_may_set_springs_and_translation() { + for id in ["bone.set_translation", "bone.set_spring", "bone.enable_springs"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/tests_camera.rs b/crates/engine/src/tests_camera.rs index 477bca6f..fad49877 100644 --- a/crates/engine/src/tests_camera.rs +++ b/crates/engine/src/tests_camera.rs @@ -228,6 +228,9 @@ fn plugins_may_drive_the_camera() { assert!(crate::cmds_plugin::plugin_may_call("camera.set").is_ok()); assert!(crate::cmds_plugin::plugin_may_call("camera.add").is_ok()); assert!(crate::cmds_plugin::plugin_may_call("layer.set_depth").is_ok()); + for id in ["layer.remove_depth_key", "layer.set_attached", "layer.depths"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } } /// Every command with hostile params while the scene has an animated camera: Ok or Err, never @@ -242,6 +245,11 @@ fn panic_hunt_with_a_camera() { json!({"x": 1e7, "y": -1e7, "zoom": 5, "zoom_by": 1e7, "reset": true, "frame": 99_999, "layer": 1}), json!({"layers": [1, 2, 3], "from": 0, "to": 100, "by": 1, "layer_by": 1, "frame": 0}), json!({"layer": 2, "type": "camera", "depth": 10000, "count": 50}), + // Depth keys and attachment (ADR 0082): huge, negative, overflowing and wrong-typed. + json!({"depth": -1e39, "key": true, "frame": 4_000_000_000u64, "attached": "x"}), + json!({"depth": 1e39, "key": "yes", "layer": u64::MAX, "view": "camera", "x": 1e30, "y": -1e30}), + json!({"depth": -500, "key": true, "frame": 0, "attached": true, "style": "advanced", "red_multiplier": -100, "blue_offset": 255}), + json!({"depth": 10000, "key": true, "frame": 19, "style": "alpha", "alpha": 0, "brightness": 1e9, "view": "nowhere"}), ]; let mut base = stage_with(&[(95.0, 45.0, 10.0, 10.0)]); run(&mut base, "camera.add", json!({})); @@ -262,3 +270,158 @@ fn panic_hunt_with_a_camera() { let tl = s.doc.timeline(0); assert!(tl.layers.iter().skip(1).all(|l| l.kind != LayerKind::Camera), "at most one camera, on top"); } + +// ----- ADR 0082: depth over time, perspective, attaching layers, colour, editing through it --- + +/// A stage with a 10 × 10 square on a layer behind (depth `far`) and one on the stage plane, +/// both at (95, 45), and a camera. Returns (session, far layer, near layer). +fn two_planes(far: f32) -> (Session, anicraft_doc::LayerId, anicraft_doc::LayerId) { + let mut s = stage_with(&[(95.0, 45.0, 10.0, 10.0)]); + let back = s.layer; + run(&mut s, "layer.set_depth", json!({"depth": far})); + run(&mut s, "layer.new", json!({})); + let near = s.layer; + run(&mut s, "draw.rect", json!({"x": 95, "y": 45, "w": 10, "h": 10, "fill": "#000000", "stroke": null})); + run(&mut s, "camera.add", json!({})); + (s, back, near) +} + +/// The x of the left edge of the black run on row `y` starting the search at `from`. +fn left_edge(s: &Session, frame: u32, y: u32, from: u32) -> Option { + (from..200).find(|&x| black(s, frame, x, y)) +} + +#[test] +fn depth_keys_tween_the_parallax_and_undo_in_one_step() { + let (mut s, back, _) = two_planes(0.0); + run(&mut s, "layer.set_depth", json!({"layer": back.0, "depth": 1000, "key": true, "frame": 10})); + let l = s.doc.timeline(0).layer(back).unwrap().clone(); + assert_eq!(l.depth_keys.len(), 2, "frame 0 keeps the depth it had"); + assert_eq!(l.depth_at(5), 500.0, "the midpoint"); + // Keyed from now on: a plain set at the playhead adds a key there. + s.set_frame(15); + run(&mut s, "layer.set_depth", json!({"layer": back.0, "depth": 3000})); + assert_eq!(s.doc.timeline(0).layer(back).unwrap().depth_keys.len(), 3); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.timeline(0).layer(back).unwrap().depth_keys.len(), 2); + // A 40 px pan: at frame 10 the far square moves 20 px (75..85); the near one 40 (55..65). + let cam = camera_id(&s); + run(&mut s, "timeline.insert_keyframe", json!({"layer": cam.0, "frame": 10})); + run(&mut s, "camera.set", json!({"frame": 0, "dx": 40})); + run(&mut s, "camera.set", json!({"frame": 10, "dx": 40})); + assert_eq!(left_edge(&s, 10, 50, 0), Some(55)); + assert_eq!(left_edge(&s, 10, 50, 66), Some(75)); + // Frame 5 (depth 500): moved 40 · 1000 / 1500 = 26.67 px, to 68.33: pixel 69 is fully in. + assert!(black(&s, 5, 69, 50) && !black(&s, 5, 67, 50)); + // Removing keys: the last leaves the depth it had there. + run(&mut s, "layer.remove_depth_key", json!({"layer": back.0, "frame": 10})); + assert!(s.execute("layer.remove_depth_key", &json!({"layer": back.0, "frame": 10})).is_err()); + run(&mut s, "layer.remove_depth_key", json!({"layer": back.0, "frame": 0})); + let l = s.doc.timeline(0).layer(back).unwrap(); + assert!(l.depth_keys.is_empty() && l.depth == 0.0); + // `key: false` makes it one value again. + run(&mut s, "layer.set_depth", json!({"layer": back.0, "depth": 200, "key": true, "frame": 3})); + run(&mut s, "layer.set_depth", json!({"layer": back.0, "depth": 50, "key": false})); + let l = s.doc.timeline(0).layer(back).unwrap(); + assert!(l.depth_keys.is_empty() && l.depth == 50.0); +} + +#[test] +fn a_camera_zoom_scales_deeper_layers_less() { + // Zoom 200 % about the centre (100, 50): the stage-plane square doubles (90..110); one + // 1000 px back grows by 4/3 (93.33..106.67). + let (mut s, _, _) = two_planes(1000.0); + run(&mut s, "camera.set", json!({"zoom": 200})); + let dl = anicraft_doc::evaluate(&s.doc, 0); + let scales: Vec = dl.items.iter().map(|i| i.transform.mean_scale()).collect(); + assert!((scales[0] - 4.0 / 3.0).abs() < 1e-4 && (scales[1] - 2.0).abs() < 1e-5, "{scales:?}"); + assert_eq!(left_edge(&s, 0, 50, 0), Some(90)); +} + +#[test] +fn attached_layers_stay_on_screen_while_the_camera_moves() { + let (mut s, back, near) = two_planes(0.0); + assert_eq!(run(&mut s, "layer.set_attached", json!({"layer": near.0}))["attached"], true, "toggles on"); + run(&mut s, "camera.set", json!({"dx": 40, "zoom": 150, "rotation": 20})); + // The attached square is exactly where it was drawn. + let dl = anicraft_doc::evaluate(&s.doc, 0); + let it = dl.items.iter().find(|i| i.layer == near).unwrap(); + assert_eq!(it.transform, anicraft_doc::evaluate_scene(&s.doc, 0, 0).items.iter().find(|i| i.layer == near).unwrap().transform); + assert!(black(&s, 0, 96, 46) && black(&s, 0, 104, 54)); + assert!(dl.items.iter().find(|i| i.layer == back).unwrap().transform != it.transform); + // Listed, and refused on the camera layer and inside a symbol. + let v = run(&mut s, "layer.depths", json!({})); + assert_eq!(v["camera"], true); + assert!(v["layers"].as_array().unwrap().iter().any(|r| r["layer"] == near.0 && r["attached"] == true)); + assert!(s.execute("layer.set_attached", &json!({"layer": camera_id(&s).0})).is_err()); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(!s.doc.timeline(0).layer(near).unwrap().attached); +} + +#[test] +fn layer_depths_list_nearest_first_ties_in_timeline_order() { + let mut s = stage_with(&[(0.0, 0.0, 5.0, 5.0)]); + let a = s.layer; + run(&mut s, "layer.new", json!({})); + let b = s.layer; + run(&mut s, "layer.new", json!({})); + let c = s.layer; + run(&mut s, "layer.set_depth", json!({"layer": a.0, "depth": -100})); + run(&mut s, "layer.set_depth", json!({"layer": c.0, "depth": 400})); + let v = run(&mut s, "layer.depths", json!({})); + let ids: Vec = v["layers"].as_array().unwrap().iter().map(|r| r["layer"].as_u64().unwrap()).collect(); + assert_eq!(ids, [a.0, b.0, c.0]); + // Ties: b and a at 0 go top first (b is above a). + run(&mut s, "layer.set_depth", json!({"layer": a.0, "depth": 0})); + let v = run(&mut s, "layer.depths", json!({})); + let ids: Vec = v["layers"].as_array().unwrap().iter().map(|r| r["layer"].as_u64().unwrap()).collect(); + assert_eq!(ids, [b.0, a.0, c.0]); +} + +#[test] +fn camera_colour_effects_reach_the_pixels() { + let mut s = stage_with(&[(95.0, 45.0, 10.0, 10.0)]); + run(&mut s, "camera.add", json!({})); + // Brightness +50 %: white stays white, black becomes mid grey (0.5). + let v = run(&mut s, "camera.set", json!({"brightness": 50})); + assert_eq!(v["color_effect"]["style"], "brightness"); + let px = render_frame(&s.doc, 0, 1.0).unwrap(); + let p = px.pixel(100, 50).unwrap(); + assert!((p[0] - 0.5).abs() < 0.01 && (p[2] - 0.5).abs() < 0.01, "{p:?}"); + // Advanced: red × 0 and blue + 255 turn white blue-ish and black blue. + run(&mut s, "camera.set", json!({"style": "none"})); + run(&mut s, "camera.set", json!({"style": "advanced", "red_multiplier": 0, "blue_offset": 255})); + let px = render_frame(&s.doc, 0, 1.0).unwrap(); + let sq = px.pixel(100, 50).unwrap(); + assert!(sq[0] < 0.01 && sq[1] < 0.01 && sq[2] > 0.99, "the square: {sq:?}"); + // The camera has no opacity. + assert!(s.execute("camera.set", &json!({"alpha_multiplier": 50})).is_err()); + assert!(s.execute("camera.set", &json!({"style": "alpha"})).is_err()); + let info = run(&mut s, "camera.info", json!({})); + assert_eq!(info["color_effect"]["style"], "advanced"); + // A colour change alone keys inside a camera tween like any other edit, and round-trips. + let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap(); + assert_eq!(back, s.doc); +} + +#[test] +fn picking_through_the_camera_finds_what_the_movie_shows() { + // The far square (depth 1000) and the near one start together; a 40 px pan puts the near + // one at 55..65 on the picture and the far one at 75..85. + let (mut s, back, near) = two_planes(1000.0); + run(&mut s, "camera.set", json!({"dx": 40})); + assert_eq!(run(&mut s, "element.pick", json!({"x": 80, "y": 50, "view": "camera"}))["layer"], back.0); + assert_eq!(run(&mut s, "element.pick", json!({"x": 60, "y": 50, "view": "camera"}))["layer"], near.0); + assert!(run(&mut s, "element.pick", json!({"x": 100, "y": 50, "view": "camera"}))["element"].is_null(), "nothing shows there"); + assert!(s.execute("element.pick", &json!({"x": 1, "y": 1, "view": "sideways"})).is_err()); + // Dragging maps the pointer back through the layer's view: 10 picture px on the far layer + // are 10 stage px at zoom 100 % (a pan keeps sizes). + let v = s.camera_view(back).unwrap(); + let d = v.inverse().unwrap().apply_vector(anicraft_geom::Vec2::new(10.0, 0.0)); + assert!((d.x - 10.0).abs() < 1e-4); + run(&mut s, "camera.set", json!({"zoom": 200})); + let v = s.camera_view(near).unwrap(); + let d = v.inverse().unwrap().apply_vector(anicraft_geom::Vec2::new(10.0, 0.0)); + assert!((d.x - 5.0).abs() < 1e-4, "{d:?}"); +} diff --git a/crates/engine/src/tests_filter.rs b/crates/engine/src/tests_filter.rs new file mode 100644 index 00000000..8e9a2e33 --- /dev/null +++ b/crates/engine/src/tests_filter.rs @@ -0,0 +1,247 @@ +//! Filter lists (ADR 0091): order, on/off, copy and paste, presets, and tweened values. + +use super::*; +use anicraft_doc::{ElementKind, Filter, FilterEntry}; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A red 100 × 100 movie clip at (100, 100), selected. +fn clip() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); + s +} + +fn list(s: &Session) -> Vec { + match &s.doc.timeline(s.scene).layers[0].keyframes[0].elements[0].kind { + ElementKind::Symbol { filters, .. } => filters.clone(), + _ => Vec::new(), + } +} + +fn kinds(s: &Session) -> Vec<(&'static str, bool)> { + list(s).iter().map(|e| (e.filter.label(), e.enabled)).collect() +} + +fn px(s: &Session, x: u32, y: u32) -> [f32; 4] { + anicraft_render::render_frame(&s.doc, s.frame, 1.0).unwrap().pixel(x, y).unwrap() +} + +#[test] +fn the_order_changes_the_pixels() { + // A green glow outside the box, then Adjust Color taking all the saturation: the glow + // turns grey. The other way round the glow is added after the colour is gone: green. + let mut s = clip(); + let glow = json!({"type": "glow", "blur_x": 0, "blur_y": 0, "color": "#00ff00", "strength": 1}); + let grey = json!({"type": "adjust_color", "saturation": -100}); + // A glow with no blur is the artwork's own outline: widen it with a blur instead. + let glow = { + let mut g = glow; + g["blur_x"] = json!(20); + g["blur_y"] = json!(20); + g["strength"] = json!(10); + g + }; + run(&mut s, "element.set_filters", json!({"filters": [glow, grey]})); + let [r, g, b, a] = px(&s, 96, 150); + assert!(a > 0.5 && (r - g).abs() < 0.02 && (g - b).abs() < 0.02, "glow then grey: a grey glow {:?}", [r, g, b, a]); + let inside_grey = px(&s, 150, 150); + run(&mut s, "filter.move", json!({"from": 1, "to": 0})); + assert_eq!(kinds(&s), [("Adjust Color", true), ("Glow", true)]); + let [r, g, b, a] = px(&s, 96, 150); + assert!(a > 0.5 && g > 0.9 && r < 0.05 && b < 0.05, "grey then glow: a green glow {:?}", [r, g, b, a]); + assert_eq!(px(&s, 150, 150), inside_grey, "the box is grey either way"); + // One undo step puts the order back. + s.undo().unwrap(); + assert_eq!(kinds(&s), [("Glow", true), ("Adjust Color", true)]); + // `to` past the end is the end; an index the list doesn't have is refused. + run(&mut s, "filter.move", json!({"from": 0, "to": 99})); + assert_eq!(kinds(&s), [("Adjust Color", true), ("Glow", true)]); + assert!(s.execute("filter.move", &json!({"from": 5, "to": 0})).is_err()); + assert!(s.execute("filter.move", &json!({"from": 0})).is_err()); +} + +#[test] +fn a_filter_switched_off_is_as_if_absent_and_keeps_its_settings() { + let blur = json!({"type": "blur", "blur_x": 6, "blur_y": 6}); + let glow = json!({"type": "glow", "blur_x": 12, "blur_y": 12, "color": "#0000ff", "strength": 3}); + let mut only = clip(); + run(&mut only, "element.set_filters", json!({"filters": [blur.clone()]})); + let mut off = clip(); + run(&mut off, "element.set_filters", json!({"filters": [blur, glow]})); + let both = anicraft_render::render_frame(&off.doc, 0, 1.0).unwrap(); + run(&mut off, "filter.enable", json!({"index": 1, "enabled": false})); + assert_eq!(kinds(&off), [("Blur", true), ("Glow", false)]); + // The oracle, the SVG and the HTML page all see the list without it. + let a = anicraft_render::render_frame(&only.doc, 0, 1.0).unwrap(); + let b = anicraft_render::render_frame(&off.doc, 0, 1.0).unwrap(); + assert_eq!(a.data, b.data, "off draws exactly as absent"); + assert_ne!(both.data, b.data, "the glow did draw when on"); + let svg = |s: &Session| anicraft_render::svg::to_svg(&anicraft_doc::evaluate(&s.doc, 0), &s.doc.stage); + assert_eq!(svg(&only), svg(&off)); + let html = |s: &Session| anicraft_render::html::movie(&s.doc, &Default::default()).json; + assert_eq!(html(&only), html(&off)); + // Its settings stay, and the file keeps the switch. + let Some(FilterEntry { filter: Filter::Glow { strength, blur_x, .. }, enabled: false }) = list(&off).get(1).cloned() else { panic!("{:?}", list(&off)) }; + assert_eq!((strength, blur_x), (3.0, 12.0)); + let text = crate::format::to_json(&off.doc).unwrap(); + assert!(text.contains("\"enabled\":false") || text.contains("\"enabled\": false"), "saved switched off"); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, off.doc, "round trip"); + // Back on: as before. + run(&mut off, "filter.enable", json!({"enabled": true})); + assert_eq!(anicraft_render::render_frame(&off.doc, 0, 1.0).unwrap().data, both.data); + // All off, then removing one and all. + run(&mut off, "filter.enable", json!({"enabled": false})); + assert_eq!(anicraft_render::render_frame(&off.doc, 0, 1.0).unwrap().data, anicraft_render::render_frame(&clip().doc, 0, 1.0).unwrap().data, "all off is no filters"); + run(&mut off, "filter.remove", json!({"index": 0})); + assert_eq!(kinds(&off), [("Glow", false)]); + assert!(off.execute("filter.enable", &json!({"index": 3, "enabled": true})).is_err()); + assert!(off.execute("filter.enable", &json!({"index": 0})).is_err(), "enabled is required"); + run(&mut off, "filter.remove", json!({})); + assert!(list(&off).is_empty()); + assert!(off.execute("filter.remove", &json!({})).is_err(), "nothing to remove"); + // `element.set_filters` takes the switch too. + run(&mut off, "element.set_filters", json!({"filters": [{"type": "blur", "enabled": false}]})); + assert_eq!(kinds(&off), [("Blur", false)]); +} + +#[test] +fn graphics_take_no_filters() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "G"})); + for (id, p) in [("filter.enable", json!({"enabled": false})), ("filter.remove", json!({})), ("filter.move", json!({"from": 0, "to": 1})), ("filter.copy", json!({}))] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("movie clip"), "{id}: {e}"); + } +} + +#[test] +fn copy_and_paste_filters_between_instances() { + let mut s = clip(); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}, {"type": "glow", "enabled": false}]})); + let first = s.selection.on(s.layer); + assert!(s.execute("filter.paste", &json!({})).is_err(), "nothing copied yet"); + run(&mut s, "filter.copy", json!({})); + // A second clip with a bevel of its own. + run(&mut s, "draw.rect", json!({"x": 300, "y": 100, "w": 50, "h": 50, "fill": "#00ff00", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Other", "kind": "movie_clip"})); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "bevel"}]})); + let second = s.selection.on(s.layer); + assert_ne!(first, second); + run(&mut s, "filter.paste", json!({})); + let of = |s: &Session, id: anicraft_doc::ElementId| match &s.doc.timeline(s.scene).layers[0].keyframes[0].elements.iter().find(|e| e.id == id).unwrap().kind { + ElementKind::Symbol { filters, .. } => filters.iter().map(|e| (e.filter.label(), e.enabled)).collect::>(), + _ => Vec::new(), + }; + assert_eq!(of(&s, second[0]), [("Bevel", true), ("Blur", true), ("Glow", false)], "added after its own, switches kept"); + run(&mut s, "filter.paste", json!({"replace": true})); + assert_eq!(of(&s, second[0]), [("Blur", true), ("Glow", false)]); + // One filter; past the limit is refused, whole. + run(&mut s, "filter.copy", json!({"index": 1})); + run(&mut s, "filter.paste", json!({})); + assert_eq!(of(&s, second[0]).len(), 3); + for _ in 0..13 { + run(&mut s, "filter.paste", json!({})); + } + assert_eq!(of(&s, second[0]).len(), 16); + assert!(s.execute("filter.paste", &json!({})).is_err()); + assert!(s.execute("filter.copy", &json!({"index": 40})).is_err()); + // Copied filters carry across to another document, as copied artwork does. + s.replace_document(anicraft_doc::Document::default(), None); + assert_eq!(s.filter_clipboard.as_ref().map(Vec::len), Some(1)); +} + +#[test] +fn filter_presets_save_apply_rename_delete_and_round_trip() { + let mut s = clip(); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "drop_shadow", "distance": 9}, {"type": "blur", "enabled": false}]})); + assert!(s.execute("filter.preset_apply", &json!({"name": "Shadowed"})).is_err()); + let rev = s.revision; + let v = run(&mut s, "filter.preset_save", json!({"name": " Shadowed "})); + assert_eq!((v["name"].as_str(), v["replaced"].as_bool()), (Some("Shadowed"), Some(false))); + // Saving over it asks (the old one can't come back), and replaces when confirmed. + assert!(matches!(s.execute("filter.preset_save", &json!({"name": "shadowed"})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "filter.preset_save", json!({"name": "shadowed", "filters": [{"type": "glow", "color": "#ff00ff"}, {"type": "blur", "enabled": false}], "confirm": true})); + assert_eq!(s.filter_presets.presets().len(), 1); + // Saving and listing are outside the document and its undo. + assert_eq!(s.revision, rev); + let listed = run(&mut s, "filter.preset_list", json!({})); + assert_eq!(listed["presets"][0]["filters"][1]["enabled"], json!(false)); + // Applying replaces the instance's filters (as Animate does), one undo step. + run(&mut s, "filter.preset_apply", json!({"name": "SHADOWED"})); + assert_eq!(kinds(&s), [("Glow", true), ("Blur", false)]); + s.undo().unwrap(); + assert_eq!(kinds(&s), [("Drop Shadow", true), ("Blur", false)]); + run(&mut s, "filter.preset_rename", json!({"name": "shadowed", "to": "Neon"})); + assert!(s.execute("filter.preset_rename", &json!({"name": "nope", "to": "x"})).is_err()); + // A file round trip, into a session that has a preset of that name already. + let dir = std::env::temp_dir().join(format!("anicraft-filter-presets-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("presets.json"); + let _ = std::fs::remove_file(&path); + run(&mut s, "filter.preset_export", json!({"path": path.display().to_string()})); + assert!(matches!(s.execute("filter.preset_export", &json!({"path": path.display().to_string()})), Err(EngineError::NeedsConfirmation(_))), "replacing the file asks"); + let mut other = Session::default(); + run(&mut other, "filter.preset_save", json!({"name": "neon", "filters": [{"type": "blur"}]})); + let v = run(&mut other, "filter.preset_import", json!({"path": path.display().to_string()})); + assert_eq!(v["imported"], json!(["Neon 2"])); + assert_eq!(other.filter_presets.find("neon 2").map(|p| p.filters.clone()), s.filter_presets.find("neon").map(|p| p.filters.clone())); + std::fs::write(dir.join("junk.json"), "{\"format\": \"anicraft-brushes\"}").unwrap(); + assert!(other.execute("filter.preset_import", &json!({"path": dir.join("junk.json").display().to_string()})).is_err()); + // Deleting asks (it can't be undone); the artwork keeps the filters it got. + run(&mut s, "filter.preset_apply", json!({"name": "neon"})); + assert!(matches!(s.execute("filter.preset_delete", &json!({"name": "neon"})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "filter.preset_delete", json!({"name": "neon", "confirm": true})); + assert!(s.filter_presets.is_empty()); + assert_eq!(kinds(&s), [("Glow", true), ("Blur", false)]); + assert!(s.execute("filter.preset_export", &json!({"path": dir.join("none.json").display().to_string()})).is_err(), "nothing to export"); + // Presets survive New and Open, like brushes. + run(&mut s, "filter.preset_save", json!({"name": "Keep"})); + s.replace_document(anicraft_doc::Document::default(), None); + assert!(s.filter_presets.find("keep").is_some()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn classic_tweens_carry_blur_and_glow_to_their_midpoint() { + // Blur 0 → 20 and a glow's strength 0 → 200 %, over a linear tween of 10 frames. + let mut s = clip(); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 0, "blur_y": 0}, {"type": "glow", "strength": 0, "color": "#0000ff"}]})); + 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.set_filters", json!({"filters": [{"type": "blur", "blur_x": 20, "blur_y": 20}, {"type": "glow", "strength": 2, "color": "#0000ff"}]})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + let dl = anicraft_doc::evaluate(&s.doc, 5); + let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group"); + assert_eq!(g.filters.len(), 2); + assert!(matches!(g.filters[0], Filter::Blur { blur_x, blur_y, .. } if (blur_x - 10.0).abs() < 1e-4 && (blur_y - 10.0).abs() < 1e-4), "{:?}", g.filters[0]); + assert!(matches!(g.filters[1], Filter::Glow { strength, .. } if (strength - 1.0).abs() < 1e-4), "{:?}", g.filters[1]); + // The midpoint renders as a still instance with the midpoint's values. + let mut still = clip(); + run(&mut still, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 10, "blur_y": 10}, {"type": "glow", "strength": 1, "color": "#0000ff"}]})); + assert_eq!(anicraft_render::render_frame(&s.doc, 5, 1.0).unwrap().data, anicraft_render::render_frame(&still.doc, 0, 1.0).unwrap().data); + // A filter switched off on the first keyframe stays off through the tween, values travelling. + s.set_frame(0); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "filter.enable", json!({"index": 1, "enabled": false})); + let dl = anicraft_doc::evaluate(&s.doc, 5); + let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group"); + assert_eq!(g.filters.len(), 1, "only the blur draws"); + // Reordered on one keyframe, the lists no longer pair up: the first keyframe's holds. + run(&mut s, "filter.move", json!({"from": 1, "to": 0})); + let dl = anicraft_doc::evaluate(&s.doc, 5); + let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group"); + assert!(matches!(g.filters[0], Filter::Blur { blur_x, .. } if blur_x == 0.0), "{:?}", g.filters); +} diff --git a/crates/engine/src/tests_filter_tracks.rs b/crates/engine/src/tests_filter_tracks.rs new file mode 100644 index 00000000..413be9ab --- /dev/null +++ b/crates/engine/src/tests_filter_tracks.rs @@ -0,0 +1,149 @@ +//! Motion tween tracks for filters (ADR 0092), through the command registry: keys, eases and +//! retiming on a filter's numbers, auto-key when a filter is edited inside the tween, tracks +//! following their filter, F6, undo and the file round trip. + +use super::*; +use anicraft_doc::{ElementKind, FilterEntry, FilterParam, FilterProp, Property}; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A red 100 × 100 movie clip at (100, 100) with `filters`, selected, in a one-second motion +/// tween. +fn tweened(filters: Value) -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); + run(&mut s, "element.set_filters", json!({ "filters": filters })); + run(&mut s, "timeline.create_motion_tween", json!({})); + s +} + +/// The object's filters as the base holds them. +fn base_list(s: &Session) -> Vec { + match &s.doc.timeline(s.scene).layers[0].keyframes[0].elements[0].kind { + ElementKind::Symbol { filters, .. } => filters.clone(), + _ => Vec::new(), + } +} + +fn value(s: &mut Session, frame: u32, key: &str) -> f64 { + let v = run(s, "motion.info", json!({ "frame": frame })); + v["values"][key].as_f64().unwrap_or_else(|| panic!("no {key} in {}", v["values"])) +} + +fn track_keys(s: &mut Session, key: &str) -> Vec<(u64, f64)> { + let v = run(s, "motion.info", json!({})); + let t = v["tracks"].as_array().and_then(|ts| ts.iter().find(|t| t["property"] == key).cloned()); + t.map(|t| t["keys"].as_array().map(|ks| ks.iter().map(|k| (k["frame"].as_u64().unwrap_or(0), k["value"].as_f64().unwrap_or(0.0))).collect()).unwrap_or_default()).unwrap_or_default() +} + +/// The green of a pixel: 1 on the white stage, less where the red box's blur reaches. +fn green_at(s: &Session, frame: u32, x: u32, y: u32) -> f32 { + anicraft_render::render_frame(&s.doc, frame, 1.0).unwrap().pixel(x, y).unwrap()[1] +} + +#[test] +fn a_blur_tweens_by_commands_with_eases_and_retiming() { + let mut s = tweened(json!([{"type": "blur", "blur_x": 0, "blur_y": 0}])); + run(&mut s, "motion.set_key", json!({"property": "filter.0.blur_x", "frame": 12, "value": 40})); + run(&mut s, "motion.set_key", json!({"property": "filter.0.blur_y", "frame": 12, "value": 40})); + assert_eq!(track_keys(&mut s, "filter.0.blur_x"), vec![(0, 0.0), (12, 40.0)]); + assert_eq!(value(&mut s, 6, "filter.0.blur_x"), 20.0); + let info = run(&mut s, "motion.info", json!({})); + let t = info["tracks"].as_array().unwrap().iter().find(|t| t["property"] == "filter.0.blur_x").unwrap().clone(); + assert_eq!((t["label"].as_str(), t["unit"].as_str(), &t["filter"]), (Some("Blur X"), Some("px"), &json!({"slot": 0, "kind": "Blur"}))); + // The render follows: at frame 0 the box's edge is sharp, at frame 12 the blur spills out. + assert!((green_at(&s, 0, 95, 150) - 1.0).abs() < 1e-6); + assert!(green_at(&s, 12, 95, 150) < 0.95); + // Eases like any property's segment. + run(&mut s, "motion.set_ease", json!({"property": "filter.0.blur_x", "frame": 3, "easing": "CubicOut"})); + assert!(value(&mut s, 6, "filter.0.blur_x") > 30.0, "cubic out is past halfway at half time"); + // Retimed: the key moves with its value and ease. + let v = run(&mut s, "motion.move_keys", json!({"keys": [{"property": "filter.0.blur_x", "frame": 12}], "by": 4})); + assert_eq!(v["keys"], json!([{"property": "filter.0.blur_x", "frame": 16}])); + assert_eq!(value(&mut s, 16, "filter.0.blur_x"), 40.0); + // Removed. + let v = run(&mut s, "motion.remove_key", json!({"property": "filter.0.blur_y", "frame": 12})); + assert_eq!(v["removed"], json!(["filter.0.blur_y"])); + // What can't be keyed says why. + for (p, want) in [(json!({"property": "filter.1.blur_x", "value": 3}), "no filter 1"), (json!({"property": "filter.0.angle", "value": 3}), "has no Angle"), (json!({"property": "filter.0.blur_x", "value": 900}), "between"), (json!({"property": "filter.0.sparkle", "value": 1}), "unknown property")] { + let e = s.execute("motion.set_key", &p).expect_err("refused").to_string(); + assert!(e.contains(want), "{p}: {e}"); + } +} + +#[test] +fn editing_a_filter_inside_the_tween_keys_it_and_undo_takes_it_back() { + let mut s = tweened(json!([{"type": "drop_shadow", "distance": 4}])); + let steps = s.history_len(); + s.set_frame(10); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "drop_shadow", "distance": 24}]})); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + assert_eq!(track_keys(&mut s, "filter.0.distance"), vec![(0, 4.0), (10, 24.0)]); + assert!(track_keys(&mut s, "filter.0.blur_x").is_empty(), "only the number that changed is keyed"); + // The object keeps its own distance underneath; the curve gives the rest. + assert_eq!(base_list(&s)[0].filter.param(FilterParam::Distance), Some(4.0)); + assert_eq!(value(&mut s, 5, "filter.0.distance"), 14.0); + // Switching the filter off keeps the tween (the list keeps its shape). + run(&mut s, "filter.enable", json!({"enabled": false, "index": 0})); + assert!(!base_list(&s)[0].enabled && track_keys(&mut s, "filter.0.distance").len() == 2); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(track_keys(&mut s, "filter.0.distance").is_empty()); + // On the span's first frame an untracked number changes the object itself. + s.set_frame(0); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "drop_shadow", "distance": 9}]})); + assert!(track_keys(&mut s, "filter.0.distance").is_empty()); + assert_eq!(base_list(&s)[0].filter.param(FilterParam::Distance), Some(9.0)); +} + +#[test] +fn tracks_follow_their_filter_when_the_list_is_reordered_or_cut() { + let mut s = tweened(json!([{"type": "blur"}, {"type": "glow", "strength": 1}])); + run(&mut s, "motion.set_key", json!({"property": "filter.1.strength", "frame": 10, "value": 300})); + run(&mut s, "motion.set_key", json!({"property": "filter.0.blur_x", "frame": 10, "value": 30})); + // Reordered at a frame inside the tween: the glow goes first, its track with it, and the + // object's own values stay underneath (not the playhead's). + s.set_frame(5); + run(&mut s, "filter.move", json!({"from": 1, "to": 0})); + assert_eq!(track_keys(&mut s, "filter.0.strength"), vec![(0, 100.0), (10, 300.0)]); + assert_eq!(track_keys(&mut s, "filter.1.blur_x"), vec![(0, 5.0), (10, 30.0)]); + let base = base_list(&s); + assert_eq!((base[0].filter.label(), base[0].filter.param(FilterParam::Strength)), ("Glow", Some(100.0))); + assert_eq!(base[1].filter.param(FilterParam::BlurX), Some(5.0)); + assert_eq!(value(&mut s, 10, "filter.0.strength"), 300.0); + // The glow removed: its track goes; the blur's moves up. + run(&mut s, "filter.remove", json!({"index": 0})); + assert!(track_keys(&mut s, "filter.0.strength").is_empty()); + assert_eq!(track_keys(&mut s, "filter.0.blur_x"), vec![(0, 5.0), (10, 30.0)]); + // A filter pasted after it leaves the tracks where they are. + run(&mut s, "filter.copy", json!({})); + run(&mut s, "filter.paste", json!({})); + assert_eq!(base_list(&s).len(), 2); + assert_eq!(track_keys(&mut s, "filter.0.blur_x").len(), 2); +} + +#[test] +fn f6_keys_the_filters_and_the_file_keeps_their_tracks() { + let mut s = tweened(json!([{"type": "adjust_color", "hue": 0}])); + run(&mut s, "motion.set_key", json!({"property": "filter.0.hue", "frame": 20, "value": 120})); + s.set_frame(10); + run(&mut s, "timeline.insert_keyframe", json!({})); + let hue = track_keys(&mut s, "filter.0.hue"); + assert!(hue.contains(&(10, 60.0)), "{hue:?}"); + assert_eq!(track_keys(&mut s, "filter.0.saturation"), vec![(0, 0.0), (10, 0.0)]); + // The document round-trips through JSON (the file format), tracks and all. + let json = serde_json::to_string(&s.doc).unwrap(); + assert!(json.contains("\"filter_tracks\"") && json.contains("filter.0.hue")); + let back: anicraft_doc::Document = serde_json::from_str(&json).unwrap(); + assert!(back == s.doc); + let m = back.timeline(0).layers[0].keyframes[0].motion.clone().unwrap(); + assert!(m.track(Property::Filter(FilterProp { slot: 0, param: FilterParam::Hue })).is_some()); +} diff --git a/crates/engine/src/tests_script.rs b/crates/engine/src/tests_script.rs index e8827631..f6d52817 100644 --- a/crates/engine/src/tests_script.rs +++ b/crates/engine/src/tests_script.rs @@ -3,7 +3,7 @@ use crate::{Session, format}; use anicraft_doc::actions::{FrameScript, Language}; -use anicraft_doc::{LayerKind, SymbolId, SymbolKind, sample}; +use anicraft_doc::{ElementKind, LayerKind, SymbolId, SymbolKind, sample}; use serde_json::{Value, json}; const AS3: &str = "import flash.events.MouseEvent;\r\n\tstop(); // “wait”\n"; @@ -145,14 +145,14 @@ fn scripts_in_the_subset_run_and_the_rest_are_kept_and_said_so() { assert!(v["state"]["frame"].as_u64().unwrap() < 10 && v["state"]["playing"] == false, "it stopped: {}", v["state"]); // The HTML export runs it too, as the same actions. let out = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap(); - assert!(out.html.contains("xyzzy-1") && !out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report); + assert!(out.html.contains("xyzzy-") && !out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report); // One outside the subset doesn't run at all, and Test Movie says where and why. let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "stop(); -var n:int = 1;"})).unwrap(); +var n:int = 1; switch (n) { }"})).unwrap(); assert_eq!(v["runs"], false); - assert_eq!(v["problems"][0], json!({"line": 2, "column": 1, "message": "variables (`var`) aren't supported yet"})); + assert_eq!(v["problems"][0], json!({"line": 2, "column": 16, "message": "`switch` statements aren't supported yet"})); let v = s.execute("control.test_movie", &json!({"frames": 20, "events": [{"tick": 2, "type": "click", "x": 640, "y": 400}]})).unwrap(); - assert_eq!(v["output"][0]["line"], "Frame script not run: Scene 1 › Actions, frame 2: line 2, column 1: variables (`var`) aren't supported yet"); + assert_eq!(v["output"][0]["line"], "Frame script not run: Scene 1 › Actions, frame 2: line 2, column 16: `switch` statements aren't supported yet"); assert!(v["state"]["frame"].as_u64().unwrap() > 10, "it played on: {}", v["state"]); let out = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap(); assert!(out.report.keys().any(|k| k.starts_with("kept frame scripts")), "{:?}", out.report); @@ -174,11 +174,88 @@ btn.addEventListener(MouseEvent.CLICK, go); function go(e:MouseEvent):void { gotoAndPlay(\"run\"); } navigateToURL(new URLRequest(\"x\"));"})).unwrap(); assert_eq!(v["runs"], true); - assert_eq!(v["describe"], json!(["Stop", "On click (btn): Go to “run” and play"])); - assert_eq!(v["steps"][1]["listen"]["target"], "btn"); + assert_eq!(v["steps"], 3); + assert_eq!(v["program"]["body"][1]["s"], "listen"); + assert_eq!(v["program"]["body"][1]["at"]["path"], "btn"); + assert_eq!(v["program"]["functions"][0]["name"], "go"); assert_eq!(v["notes"][0]["line"], 4); + // Names from other frames are listed; the text alone can't say whether they are there. + let v = s.execute("script.check", &json!({"text": "score += bonus(2);"})).unwrap(); + assert_eq!((v["runs"].as_bool(), v["uses"].clone()), (Some(true), json!([{"name": "score", "line": 1, "column": 1, "call": false}, {"name": "bonus", "line": 1, "column": 10, "call": true}]))); let v = s.execute("script.check", &json!({"text": "stop();", "language": "actionscript1or2"})).unwrap(); assert_eq!((v["runs"].as_bool(), v["problems"][0]["line"].as_u64()), (Some(false), Some(0))); assert!(s.execute("script.check", &json!({})).is_err()); assert!(s.doc == before && s.undo_label().is_none()); } + +#[test] +fn scripts_link_through_their_timeline_and_test_movie_plays_keys() { + let mut s = Session::new(sample::interactive()); + let layer = s.doc.timeline(0).layers[0].id.0; + // Frame 2 uses a variable and a function that no frame declares yet: it doesn't run. + let v = s.execute("script.set", &json!({"layer": layer, "frame": 1, "text": "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\nfunction onKey(e:KeyboardEvent):void { hits++; trace(\"key \" + e.keyCode + \" \" + hits + \" \" + Math.floor(Math.random() * 1000)); }"})).unwrap(); + assert_eq!(v["runs"], false, "{v}"); + assert_eq!(v["problems"][0]["message"], "`hits` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)"); + let out = s.execute("control.test_movie", &json!({"frames": 5})).unwrap(); + assert!(out["output"][0]["line"].as_str().unwrap().starts_with("Frame script not run: Scene 1 › Actions, frame 2: line 3"), "{}", out["output"]); + // Declaring it on frame 1 links frame 2. + s.execute("script.set", &json!({"layer": layer, "frame": 0, "text": "var hits:int = 0;"})).unwrap(); + let list = s.execute("script.list", &json!({"text": false})).unwrap(); + assert!(list["frames"].as_array().unwrap().iter().all(|f| f["runs"] == true), "{list}"); + let play = |s: &mut Session, seed: u64| { + let v = s.execute("control.test_movie", &json!({"frames": 6, "seed": seed, "events": [{"tick": 3, "type": "key_down", "key": "LEFT"}, {"tick": 4, "type": "key", "key": "a"}, {"tick": 5, "type": "key_down", "key": 32}]})).unwrap(); + v["output"].as_array().unwrap().iter().filter_map(|l| l["line"].as_str().map(str::to_string)).filter(|l| l.starts_with("key ")).collect::>() + }; + let a = play(&mut s, 1); + assert_eq!(a.len(), 3, "{a:?}"); + assert!(a[0].starts_with("key 37 1 ") && a[1].starts_with("key 65 2 ") && a[2].starts_with("key 32 3 "), "{a:?}"); + assert_eq!(play(&mut s, 1), a, "the same seed plays the same"); + assert_ne!(play(&mut s, 2), a, "another seed draws other numbers"); + for bad in [json!({"tick": 1, "type": "key_down"}), json!({"tick": 1, "type": "key_down", "key": 0}), json!({"tick": 1, "type": "key_up", "key": "WIGGLE"})] { + assert!(s.execute("control.test_movie", &json!({"events": [bad]})).is_err()); + } +} + +/// Dynamic and input text fields (ADR 0066), end to end through commands: Text type, instance +/// names, the file format, and a headless Test Movie that types into a field. +#[test] +fn text_fields_are_made_named_saved_and_typed_into() { + if anicraft_text::Fonts::get().families().is_empty() { + return; // A computer without fonts: the player tests cover fields with a test layout. + } + let mut s = Session::default(); + let ok = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + ok(&mut s, "text.create", json!({"text": "0", "x": 20, "y": 20, "size": 20})); + assert!(s.execute("instance.set_name", &json!({"name": "score_txt"})).unwrap_err().to_string().contains("static text has no instance name")); + assert!(s.execute("text.field", &json!({"type": "dynamic", "lines": "password"})).unwrap_err().to_string().contains("only input text")); + ok(&mut s, "text.field", json!({"type": "dynamic", "width": 200, "border": true})); + ok(&mut s, "instance.set_name", json!({"name": "score_txt"})); + let field = |s: &Session, name: &str| s.doc.timeline(0).layers[0].keyframes[0].elements.iter().find(|e| e.name == name).cloned().unwrap(); + let ElementKind::Text(t) = &field(&s, "score_txt").kind else { panic!("text") }; + assert_eq!((t.kind(), t.box_width), (anicraft_doc::TextKind::Dynamic, 200.0)); + assert!(t.outline.bounds().min.x >= anicraft_doc::FIELD_GUTTER - 0.5, "the text sits inside the gutter"); + // An empty input field, with a script reading it when Enter is pressed. + ok(&mut s, "text.create", json!({"text": "", "type": "input", "x": 20, "y": 80, "size": 20})); + ok(&mut s, "text.field", json!({"width": 200, "height": 30, "max_chars": 5})); + ok(&mut s, "instance.set_name", json!({"name": "name_txt"})); + ok(&mut s, "script.set", json!({"frame": 0, "text": "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, k);\nfunction k(e:KeyboardEvent):void { if (e.keyCode == Keyboard.ENTER) { score_txt.text = \"Hi \" + name_txt.text; trace(name_txt.length); } }"})); + // Saved and opened again, the fields are the same. + let dir = std::env::temp_dir().join(format!("anicraft-fields-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("fields.anicraft"); + ok(&mut s, "file.save", json!({"path": file.display().to_string()})); + let mut back = Session::default(); + ok(&mut back, "file.open", json!({"path": file.display().to_string()})); + assert_eq!(field(&back, "name_txt").kind, field(&s, "name_txt").kind); + std::fs::remove_dir_all(&dir).ok(); + // Headless Test Movie: click the input field, type past its limit, press Enter. + let v = ok(&mut back, "control.test_movie", json!({"frames": 3, "events": [{"tick": 1, "type": "click", "x": 40, "y": 92}, {"tick": 1, "type": "text", "text": "Adalovelace"}, {"tick": 2, "type": "key", "key": "ENTER"}]})); + let fields = v["state"]["fields"].as_array().unwrap(); + let text_of = |n: &str| fields.iter().find(|f| f["name"] == n).map(|f| f["text"].clone()).unwrap(); + assert_eq!(text_of("name_txt"), "Adalo", "at most 5 characters"); + assert_eq!(text_of("score_txt"), "Hi Adalo"); + assert!(v["output"].as_array().unwrap().iter().any(|l| l["line"] == "5"), "{}", v["output"]); + assert!(back.execute("control.test_movie", &json!({"events": [{"type": "text"}]})).is_err()); + // Plug-ins may set text types (document content, like the rest of text.*). + assert!(crate::cmds_plugin::plugin_may_call("text.field").is_ok()); +} diff --git a/crates/engine/src/tests_shape_bone.rs b/crates/engine/src/tests_shape_bone.rs new file mode 100644 index 00000000..564ee773 --- /dev/null +++ b/crates/engine/src/tests_shape_bone.rs @@ -0,0 +1,292 @@ +//! Shape armatures end to end (ADR 0071): bones drawn inside a shape, automatic binding, the +//! Bind tool's command, posing by angle and by IK, pose tweens, removal, undo, refusals, the +//! file format, analytic renders and plug-in policy. + +use super::*; +use anicraft_doc::{ColorEffect, Document, ElementKind, Paint, Rgba, Shape, Stage}; +use anicraft_geom::{Affine, Path, PathCmd}; +use anicraft_render::render_frame; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +const TAIL: u64 = 10; + +/// A 400 × 300 stage, 20 frames, with a black tail 200 × 20 px lying along y = 150 from +/// x = 100 (anchors every 25 px along both edges, part of the layer's merged drawing). +fn tail() -> Session { + let mut d = Document { stage: Stage { width: 400, height: 300, ..Stage::default() }, ..Document::default() }; + 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 shape = Shape { merge: true, ..Shape::filled(p, Paint::Solid(Rgba::BLACK)) }; + let el = Arc::new(Element { id: ElementId(TAIL), name: String::new(), transform: Affine::translate(100.0, 150.0), color: ColorEffect::default(), kind: ElementKind::Shape(shape) }); + let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); + l.keyframes = vec![Arc::new({ + let mut k = Keyframe::new(0, 20); + k.elements = vec![el]; + k + })]; + d.next_id = 100; + Session::new(d) +} + +/// [`tail`] with two bones along its middle: (100, 150) → (200, 150) → (300, 150). +fn rigged() -> (Session, u64, u64) { + let mut s = tail(); + let v = run(&mut s, "bone.add_in_shape", json!({"shape": TAIL, "head": [100, 150], "tail": [200, 150]})); + assert_eq!(v["created"], true); + let b1 = v["bone"].as_u64().unwrap(); + let b2 = run(&mut s, "bone.add_in_shape", json!({"parent": b1, "tail": [300, 150]}))["bone"].as_u64().unwrap(); + (s, b1, b2) +} + +fn shape_at(s: &Session, frame: u32) -> (Affine, Arc, bool) { + let tl = s.doc.timeline(s.scene); + tl.layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + els.iter().find(|e| e.id.0 == TAIL).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some((e.transform, sh.path.clone(), sh.merge)), + _ => None, + }) + }) + .unwrap() +} + +/// The tail's anchors on the stage at `frame`. +fn points(s: &Session, frame: u32) -> Vec { + let (m, p, _) = shape_at(s, frame); + anicraft_doc::skin::anchors(&p).into_iter().map(|a| m.apply(a)).collect() +} + +fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 { + let (sn, c) = a.sin_cos(); + let d = p - j; + Vec2::new(j.x + d.x * c - d.y * sn, j.y + d.x * sn + d.y * c) +} + +fn black(s: &Session, frame: u32, x: u32, y: u32) -> bool { + render_frame(&s.doc, frame, 1.0).unwrap().pixel(x, y).unwrap()[0] < 0.1 +} + +#[test] +fn bones_inside_a_shape_move_it_to_an_armature_layer_as_drawn() { + let before = render_frame(&tail().doc, 0, 1.0).unwrap().data; + let drawn = points(&tail(), 0); + let (mut s, b1, b2) = rigged(); + let tl = s.doc.timeline(0); + assert_eq!(tl.layers.len(), 2); + let arm = &tl.layers[0]; + assert_eq!(arm.kind, LayerKind::Armature); + assert_eq!(s.layer, arm.id, "the armature layer is active"); + assert!(tl.layers[1].keyframes[0].elements.is_empty(), "the shape left its layer"); + let (m, _, merge) = shape_at(&s, 0); + assert_eq!(m, Affine::translate(100.0, 150.0)); + assert!(!merge, "an armature's shape is an object: merge drawing leaves it"); + // The rest pose is the drawing, exactly. + assert_eq!(points(&s, 0), drawn); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + let v = run(&mut s, "bone.info", json!({"points": true})); + let a = &v["armatures"][0]; + assert_eq!(a["shape"], TAIL); + assert_eq!(a["roots"], json!([TAIL])); + let bones = a["bones"].as_array().unwrap(); + assert_eq!((bones[0]["id"].as_u64(), bones[1]["id"].as_u64()), (Some(b1), Some(b2))); + assert_eq!(bones[1]["parent_bone"], b1); + assert_eq!(bones[1]["head"], json!([200.0, 150.0]), "the chain joins end to start"); + // Every point is bound, its weights summing to 1. + let pts = a["points"].as_array().unwrap(); + assert_eq!(pts.len(), drawn.len()); + for p in pts { + let sum: f64 = p["bones"].as_array().unwrap().iter().map(|i| i[1].as_f64().unwrap()).sum(); + assert!((sum - 1.0).abs() < 1e-5, "{p}"); + } + let (n1, n2) = (bones[0]["points"].as_u64().unwrap(), bones[1]["points"].as_u64().unwrap()); + assert!(n1 > 0 && n2 > 0 && n1 + n2 >= drawn.len() as u64, "{n1} + {n2}"); +} + +#[test] +fn a_quarter_bend_swings_the_tail_and_tweens_through_the_middle() { + let (mut s, _, b2) = rigged(); + let drawn = points(&s, 0); + // Key the bend at frame 10 (the rest pose at 0 tweens into it). + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90, "frame": 10})); + let joint = Vec2::new(200.0, 150.0); + let bent = points(&s, 10); + // The tip's corners (the 8th and 9th points) follow the second bone alone. + for i in [8, 9] { + assert!(bent[i].distance(turned(drawn[i], joint, std::f32::consts::FRAC_PI_2)) < 1e-3, "{i}: {:?}", bent[i]); + } + // The root half didn't move. + assert_eq!(bent[1], drawn[1]); + assert_eq!(bent[0], drawn[0]); + // Half way the tip has turned 45°. + let mid = points(&s, 5); + assert!(mid[8].distance(turned(drawn[8], joint, std::f32::consts::FRAC_PI_4)) < 1e-3, "{:?}", mid[8]); + // The render shows it: the tail now hangs down from x = 200, its old tip area is empty. + assert!(black(&s, 0, 280, 150) && !black(&s, 0, 200, 230)); + assert!(!black(&s, 10, 280, 150) && black(&s, 10, 200, 230)); +} + +#[test] +fn dragging_a_shape_bone_bends_it_by_ik_in_one_undo_step() { + let (mut s, _, b2) = rigged(); + let steps = s.history_len(); + s.begin_gesture("Pose Armature"); + for t in [[290.0, 120.0], [270.0, 90.0], [250.0, 60.0]] { + run(&mut s, "bone.solve", json!({"bone": b2, "x": t[0], "y": t[1]})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + let v = run(&mut s, "bone.info", json!({})); + let tail = &v["armatures"][0]["bones"][1]["tail"]; + let end = Vec2::new(tail[0].as_f64().unwrap() as f32, tail[1].as_f64().unwrap() as f32); + assert!(end.distance(Vec2::new(250.0, 60.0)) < 0.5, "{end:?}"); + // The outline follows the bones; the file holds what shows. + let shown = points(&s, 0); + assert!(shown[8].distance(Vec2::new(250.0, 60.0)) < 11.0, "{:?}", shown[8]); + let k = &s.doc.timeline(0).layers[0].keyframes[0]; + let ElementKind::Shape(sh) = &k.elements[0].kind else { panic!("not a shape") }; + assert_eq!(anicraft_doc::skin::anchors(&sh.path).iter().map(|p| Affine::translate(100.0, 150.0).apply(*p)).collect::>(), shown); + s.undo().unwrap(); + assert_eq!(points(&s, 0), points(&rigged().0, 0), "undo puts the rest pose back"); +} + +#[test] +fn binding_points_by_hand() { + let (mut s, b1, b2) = rigged(); + let tip = 8usize; + // The tip follows only the first bone: bending the second leaves it. + let v = run(&mut s, "bone.bind", json!({"bone": b1, "points": [tip, 9]})); + assert_eq!(v["changed"], 2); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90})); + let drawn = points(&tail(), 0); + let now = points(&s, 0); + assert_eq!(now[tip], drawn[tip], "bound to the bone that didn't turn"); + assert_ne!(now[7], drawn[7], "its neighbours bend"); + // Shared: half way between staying and turning. + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "add"})); + let want = (drawn[tip] + turned(drawn[tip], Vec2::new(200.0, 150.0), std::f32::consts::FRAC_PI_2)) * 0.5; + assert!(points(&s, 0)[tip].distance(want) < 1e-3); + let info = run(&mut s, "bone.info", json!({"points": true})); + let p = &info["armatures"][0]["points"][tip]; + assert_eq!(p["manual"], true); + assert_eq!(p["bones"].as_array().unwrap().len(), 2); + // Removed from both: it stays where it was drawn. + run(&mut s, "bone.bind", json!({"bone": b1, "points": [tip], "mode": "remove"})); + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "remove"})); + assert_eq!(points(&s, 0)[tip], drawn[tip]); + // Automatic again: it follows the second bone round. + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "auto"})); + assert!(points(&s, 0)[tip].distance(turned(drawn[tip], Vec2::new(200.0, 150.0), std::f32::consts::FRAC_PI_2)) < 1e-3); + // Each bind is one undo step. + s.undo().unwrap(); + assert_eq!(points(&s, 0)[tip], drawn[tip]); +} + +#[test] +fn shape_bones_refuse_what_cant_be_done() { + let mut s = tail(); + let steps = s.history_len(); + for (p, want) in [ + (json!({"shape": TAIL, "head": [100, 50], "tail": [200, 50]}), "inside"), + (json!({"shape": TAIL, "head": [150, 150], "tail": [150.5, 150]}), "length"), + (json!({"shape": TAIL, "tail": [200, 150]}), "head"), + (json!({"shape": TAIL, "head": [150, 150]}), "tail"), + (json!({"shape": 999, "head": [150, 150], "tail": [200, 150]}), "no shape"), + (json!({"head": [150, 150], "tail": [200, 150]}), "shape"), + (json!({"parent": 999, "tail": [200, 150]}), "no bone"), + ] { + let e = s.execute("bone.add_in_shape", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(s.history_len(), steps, "refusals leave no undo steps"); + let (mut s, b1, _) = rigged(); + for (p, want) in [(json!({"bone": b1, "points": [9999]}), "below"), (json!({"bone": b1, "mode": "glue"}), "mode"), (json!({"bone": b1, "points": "all"}), "points"), (json!({"bone": 4242}), "no bone")] { + let e = s.execute("bone.bind", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + // The shape's outline is the armature's: artwork edits are refused on its layer. + s.select_only([ElementId(TAIL)]); + for (id, p) in [("element.translate", json!({"dx": 5, "dy": 0})), ("edit.delete", json!({})), ("draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5}))] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("armature"), "{id}: {e}"); + } + // Bones of symbol instances bind nothing; instances don't join a shape's armature. + let (mut inst, ib1, _) = crate::tests_bone::rigged(); + assert!(inst.execute("bone.bind", &json!({"bone": ib1})).unwrap_err().to_string().contains("instances")); + assert!(inst.execute("bone.add_in_shape", &json!({"parent": ib1, "tail": [0, 0]})).unwrap_err().to_string().contains("instances")); + let e = inst.execute("bone.add_in_shape", &json!({"shape": crate::tests_bone::ROOT, "head": [150, 100], "tail": [190, 100]})).unwrap_err().to_string(); + assert!(e.contains("shape"), "{e}"); +} + +#[test] +fn merged_drawing_leaves_the_armature_shape_alone() { + let (mut s, _, _) = rigged(); + let drawn = shape_at(&s, 0).1; + let other = s.doc.timeline(0).layers[1].id; + run(&mut s, "layer.select", json!({"layer": other.0})); + run(&mut s, "draw.rect", json!({"x": 150, "y": 100, "w": 60, "h": 100})); + assert_eq!(*shape_at(&s, 0).1, *drawn, "a shape drawn over it on another layer doesn't cut it"); +} + +#[test] +fn removing_shape_bones_rebinds_and_the_last_frees_the_shape_as_it_looks() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 30})); + let v = run(&mut s, "bone.remove", json!({"bone": b2})); + assert_eq!(v["armature_removed"], false); + let tl = s.doc.timeline(0); + assert_eq!(tl.layers.len(), 2, "no layer for freed instances: a shape's bones move none"); + let arm = tl.layers[0].armature.as_ref().unwrap(); + assert!(arm.skin.as_ref().unwrap().points.iter().all(|p| p.bones == vec![anicraft_doc::skin::Influence(anicraft_doc::BoneId(b1), 1.0)]), "every point follows the bone that's left"); + let shown = points(&s, 0); + run(&mut s, "bone.remove", json!({"bone": b1})); + let tl = s.doc.timeline(0); + assert!(tl.layers.iter().all(|l| l.kind != LayerKind::Armature)); + assert_eq!(points(&s, 0), shown, "the shape stays as it looked, now a drawing object"); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(s.doc.timeline(0).layers[0].armature.as_ref().unwrap().bones.len(), 2); +} + +#[test] +fn shape_armatures_survive_a_file_round_trip_and_render_the_same() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.bind", json!({"bone": b1, "points": [3], "mode": "add"})); + run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -100, "max": 100})); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90, "frame": 10})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + for f in [0, 5, 10] { + assert_eq!(render_frame(&back, f, 1.0).unwrap().data, render_frame(&s.doc, f, 1.0).unwrap().data, "frame {f}"); + } + // The file stores the outline as drawn, so a keyframe's bent outline never drifts. + let skin = back.timeline(0).layers[0].armature.as_ref().unwrap().skin.clone().unwrap(); + assert_eq!(skin.rest.cmds.first(), Some(&PathCmd::MoveTo(Vec2::new(0.0, -10.0)))); + // New ids never collide with the bones' joint nodes. + let mut back = Session::new(back); + let v = run(&mut back, "bone.add_in_shape", json!({"parent": b2, "tail": [200, 280]})); + assert!(v["bone"].as_u64().unwrap() > b2); +} + +#[test] +fn plug_ins_may_rig_shapes() { + for id in ["bone.add_in_shape", "bone.bind"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/tests_shape_weights.rs b/crates/engine/src/tests_shape_weights.rs new file mode 100644 index 00000000..048e79c4 --- /dev/null +++ b/crates/engine/src/tests_shape_weights.rs @@ -0,0 +1,224 @@ +//! Painted weights and reshaping a bound shape end to end (ADR 0090): the brush, numeric +//! weights, undo per stroke, Subselection edits at rest keeping the binding, refusals and +//! plug-in policy. + +use super::*; +use anicraft_doc::{BoneId, ColorEffect, Document, ElementKind, Paint, Rgba, Shape, Stage}; +use anicraft_geom::{Affine, Path}; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +const TAIL: u64 = 10; + +/// The tail outline of `tests_shape_bone`: 200 × 20 px, anchors every 25 px on both edges. +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)); + } + for i in (0..=8).rev() { + p.line_to(Vec2::new(25.0 * i as f32, 10.0)); + } + p.close(); + p +} + +/// A tail at (100, 150) with two bones along its middle: (100, 150) → (200, 150) → (300, 150). +fn rigged() -> (Session, u64, u64) { + let mut d = Document { stage: Stage { width: 400, height: 300, ..Stage::default() }, ..Document::default() }; + let shape = Shape { merge: true, ..Shape::filled(outline(), Paint::Solid(Rgba::BLACK)) }; + let el = Arc::new(Element { id: ElementId(TAIL), name: String::new(), transform: Affine::translate(100.0, 150.0), color: ColorEffect::default(), kind: ElementKind::Shape(shape) }); + let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); + l.keyframes = vec![Arc::new({ + let mut k = Keyframe::new(0, 20); + k.elements = vec![el]; + k + })]; + d.next_id = 100; + let mut s = Session::new(d); + let b1 = run(&mut s, "bone.add_in_shape", json!({"shape": TAIL, "head": [100, 150], "tail": [200, 150]}))["bone"].as_u64().unwrap(); + let b2 = run(&mut s, "bone.add_in_shape", json!({"parent": b1, "tail": [300, 150]}))["bone"].as_u64().unwrap(); + (s, b1, b2) +} + +fn skin(s: &Session) -> anicraft_doc::skin::Skin { + s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.clone())).unwrap() +} + +fn weight(s: &Session, point: usize, bone: u64) -> f32 { + skin(s).points[point].weight(BoneId(bone)) +} + +fn shown_path(s: &Session, frame: u32) -> Arc { + s.timeline() + .layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + els.iter().find(|e| e.id.0 == TAIL).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.path.clone()), + _ => None, + }) + }) + .unwrap() +} + +fn normalised(s: &Session) -> bool { + skin(s).points.iter().all(|b| b.bones.is_empty() || ((b.bones.iter().map(|i| i.1).sum::() - 1.0).abs() < 1e-5 && b.bones.len() <= 4)) +} + +#[test] +fn a_brush_stroke_paints_locally_and_undoes_in_one_step() { + let (mut s, _, b2) = rigged(); + let before = skin(&s).points.clone(); + assert_eq!(weight(&s, 1, b2), 0.0); + // A stroke of three moves over the point at (125, 140), as the Bind tool sends it. + s.begin_gesture("Paint Weights"); + for x in [120.0, 125.0, 130.0] { + run(&mut s, "bone.paint_weights", json!({"bone": b2, "at": [[x, 140.0]], "radius": 12, "strength": 50})); + } + s.end_gesture(); + assert!(weight(&s, 1, b2) > 0.5, "{}", weight(&s, 1, b2)); + assert!(normalised(&s)); + // Only points within the radius of a dab changed. + let rest = anicraft_doc::skin::anchors(&skin(&s).rest); + for (i, p) in rest.iter().enumerate() { + let at = *p + Vec2::new(100.0, 150.0); + if [120.0, 125.0, 130.0].iter().all(|x| at.distance(Vec2::new(*x, 140.0)) >= 12.0) { + assert_eq!(skin(&s).points[i], before[i], "point {i}"); + } + } + s.undo().unwrap(); + assert_eq!(skin(&s).points, before); +} + +#[test] +fn painted_weights_bend_the_shape_and_stay_normalised() { + let (mut s, b1, b2) = rigged(); + for (mode, bone) in [("add", b2), ("subtract", b1), ("smooth", b2), ("subtract", b2), ("add", b1)] { + let at: Vec<[f32; 2]> = (0..30).map(|i| [100.0 + 7.0 * i as f32, if i % 2 == 0 { 140.0 } else { 160.0 }]).collect(); + run(&mut s, "bone.paint_weights", json!({"bone": bone, "at": at, "radius": 30, "strength": 40, "mode": mode})); + assert!(normalised(&s), "{mode}"); + } + // Point 1 painted onto B2 entirely now turns with B2. + run(&mut s, "bone.set_weight", json!({"bone": b2, "points": [1], "weight": 100})); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90, "frame": 10})); + let bent = anicraft_doc::skin::anchors(&shown_path(&s, 10)); + let rest = anicraft_doc::skin::anchors(&skin(&s).rest); + assert!(bent[1].distance(rest[1]) > 10.0, "{:?} vs {:?}", bent[1], rest[1]); +} + +#[test] +fn weights_are_editable_numerically_per_point() { + let (mut s, b1, b2) = rigged(); + let v = run(&mut s, "bone.set_weight", json!({"bone": b1, "points": [1, 2], "weight": 30})); + assert_eq!(v["changed"], 2); + assert!((weight(&s, 1, b1) - 0.3).abs() < 1e-6 && (weight(&s, 1, b2) - 0.7).abs() < 1e-6); + assert!(skin(&s).points[1].manual); + // bone.info reports them. + let info = run(&mut s, "bone.info", json!({"points": true})); + let bones = info["armatures"][0]["points"][1]["bones"].as_array().unwrap().clone(); + assert_eq!(bones.len(), 2); + // Refusals: out-of-range weights and points, and bones of instance armatures. + assert!(s.execute("bone.set_weight", &json!({"bone": b1, "points": [1], "weight": 101})).is_err()); + assert!(s.execute("bone.set_weight", &json!({"bone": b1, "points": [999], "weight": 10})).is_err()); + assert!(s.execute("bone.set_weight", &json!({"bone": b1, "weight": 10})).is_err()); + assert!(s.execute("bone.paint_weights", &json!({"bone": b1, "at": [[1, 2]], "radius": 0})).is_err()); + assert!(s.execute("bone.paint_weights", &json!({"bone": b1, "at": [[1, 2]], "mode": "blur"})).is_err()); + assert!(s.execute("bone.paint_weights", &json!({"bone": b1, "at": [[1, "x"]]})).is_err()); + assert!(s.execute("bone.paint_weights", &json!({"bone": 4242, "at": [[1, 2]]})).is_err()); +} + +#[test] +fn reshaping_at_rest_keeps_the_binding_and_is_exact() { + let (mut s, b1, b2) = rigged(); + let k0 = skin(&s); + // Hand-bind the neighbours apart: anchor 3 (x = 75) to B1, anchor 4 (x = 100) to B2. + run(&mut s, "bone.bind", json!({"bone": b1, "points": [3], "mode": "only"})); + run(&mut s, "bone.bind", json!({"bone": b2, "points": [4], "mode": "only"})); + // Subselection's double-click on the top edge a quarter of the way from x = 75 to x = 100. + let lid = s.layer; + let v = run(&mut s, "path.add_point", json!({"id": TAIL, "x": 181.25, "y": 140.0})); + assert_eq!(s.layer, lid); + let cmd = v["cmd"].as_u64().unwrap() as usize; + let k = skin(&s); + let n = anicraft_doc::skin::anchors(&k.rest).len(); + assert_eq!(k.points.len(), n); + assert!(n > k0.points.len()); + // The new anchor blends its neighbours by where it sits between them. + let i = cmd; + assert!((k.points[i].weight(BoneId(b1)) - 0.75).abs() < 1e-3 && (k.points[i].weight(BoneId(b2)) - 0.25).abs() < 1e-3, "{:?}", k.points[i]); + // The rest pose shows exactly the edited outline: what the same edit gives an unbound shape. + let mut want = outline(); + want.close_explicitly(); + let (c, t, _) = want.nearest_segment(Vec2::new(181.25, 140.0), &Affine::translate(100.0, 150.0)).unwrap(); + assert!(want.split_segment(c, t)); + assert_eq!(*k.rest, want); + assert_eq!(*shown_path(&s, 0), want); + assert!(Arc::ptr_eq(&shown_path(&s, 0), &k.rest)); + // Moving a point keeps every binding; deleting one drops its own. + run(&mut s, "path.move_points", json!({"id": TAIL, "points": [[cmd, 0]], "dx": 0, "dy": -6})); + assert_eq!(skin(&s).points, k.points); + run(&mut s, "path.delete_points", json!({"id": TAIL, "cmds": [cmd]})); + let mut left = k.points.clone(); + left.remove(i); + assert_eq!(skin(&s).points, left); + // Undo walks back through each edit. + s.undo().unwrap(); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(*skin(&s).rest, outline()); +} + +#[test] +fn a_posed_frame_bends_the_reshaped_outline_and_refuses_reshaping() { + let (mut s, _, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 45, "frame": 10})); + run(&mut s, "path.add_point", json!({"id": TAIL, "x": 281.25, "y": 140.0})); + let n = anicraft_doc::skin::anchors(&skin(&s).rest).len(); + // Every keyframe holds the new outline, bent by its pose. + assert_eq!(anicraft_doc::skin::anchors(&shown_path(&s, 10)).len(), n); + assert_ne!(*shown_path(&s, 10), *skin(&s).rest); + s.set_frame(10); + let e = s.execute("path.move_points", &json!({"id": TAIL, "points": [[2, 0]], "dx": 0, "dy": -6})).unwrap_err(); + assert!(e.to_string().contains("rest pose"), "{e}"); + // A locked armature layer refuses too. + s.set_frame(0); + let lid = s.layer; + Arc::make_mut(s.doc.timeline_mut(0).layers.iter_mut().find(|l| l.id == lid).unwrap()).locked = true; + assert!(s.execute("path.move_points", &json!({"id": TAIL, "points": [[2, 0]], "dx": 0, "dy": -6})).is_err()); +} + +#[test] +fn files_keep_painted_and_reshaped_bindings() { + let (mut s, _, b2) = rigged(); + run(&mut s, "bone.paint_weights", json!({"bone": b2, "at": [[150, 140]], "radius": 30, "strength": 60})); + run(&mut s, "path.add_point", json!({"id": TAIL, "x": 181.25, "y": 140.0})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + let k = back.timeline(0).layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.clone())).unwrap(); + assert_eq!(k, skin(&s)); +} + +#[test] +fn plug_ins_may_paint_weights() { + for id in ["bone.paint_weights", "bone.set_weight"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} + +#[test] +fn subselection_picks_the_bound_shape_to_show_its_points() { + let (mut s, _, _) = rigged(); + run(&mut s, "element.pick", json!({"x": 150, "y": 150})); + assert!(s.selection.contains(s.layer, ElementId(TAIL))); + // It is a drawing object, so the Subselection tool lists its own points. + assert!(s.visible_elements().iter().any(|e| e.id.0 == TAIL && matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge))); +} diff --git a/crates/engine/src/tests_sound.rs b/crates/engine/src/tests_sound.rs index d3922655..0947853b 100644 --- a/crates/engine/src/tests_sound.rs +++ b/crates/engine/src/tests_sound.rs @@ -308,7 +308,7 @@ fn sounds_inside_symbols_are_in_the_exported_soundtrack_at_their_offset_and_loop let mut k = Keyframe::new(1, 3); k.sound = Some(FrameSound::new(SoundId(id))); inner.keyframes = vec![Arc::new(Keyframe::new(0, 1)), Arc::new(k)]; - s.doc.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + s.doc.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let mut k = Keyframe::new(1, 8); k.elements.push(Arc::new(Element { id: ElementId(502), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(501), loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } })); let mut outer = Layer::new(LayerId(503), "puppet"); @@ -328,3 +328,78 @@ fn sounds_inside_symbols_are_in_the_exported_soundtrack_at_their_offset_and_loop } let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn sounds_on_a_button_s_frames_play_in_test_movie_and_stay_out_of_the_soundtrack() { + let dir = temp_dir("button"); + let wav = dir.join("click.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &source())).unwrap(); + let mut s = Session::new(anicraft_doc::sample::interactive()); + let id = run(&mut s, "file.import_to_library", json!({"path": wav.display().to_string()}))["sound"].as_u64().unwrap(); + // Inside the Play button, a click on its Over frame and another on its Down frame. + let button = s.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id).unwrap(); + run(&mut s, "symbol.edit", json!({"symbol": button.0})); + run(&mut s, "sound.place", json!({"sound": id, "frame": 1})); + run(&mut s, "sound.place", json!({"sound": id, "frame": 2, "sync": "stream"})); + run(&mut s, "symbol.exit", json!({})); + // The button stands at (640, 400) on the menu. + let v = run(&mut s, "control.test_movie", json!({"frames": 6, "events": [{"tick": 2, "type": "move", "x": 640, "y": 400}, {"tick": 4, "type": "down", "x": 640, "y": 400}]})); + let heard: Vec<(u64, &str)> = v["sounds"].as_array().unwrap().iter().map(|x| (x["tick"].as_u64().unwrap(), x["sync"].as_str().unwrap())).collect(); + assert_eq!(heard, [(2, "event"), (4, "event")], "Over, then Down (a stream plays as an event): {v}"); + assert_eq!(v["sounds"][0]["name"], "click.wav"); + // Nothing on the timelines plays them: the exported soundtrack is silent. + let out = dir.join("silent.wav"); + run(&mut s, "file.export_audio", json!({"path": out.display().to_string(), "rate": 8000, "bits": 32, "confirm": true})); + let pcm = audio::decode(&std::fs::read(&out).unwrap()).unwrap(); + assert!(pcm.samples.iter().all(|x| *x == 0.0)); +} + +/// Hostile envelopes and settings through `sound.set` (ADR 0095): huge, negative, fractional +/// and out-of-order times, levels far outside 0–1, too many points, wrong types. Each is +/// refused or cleaned up; the movie then lays out and mixes at several rates without a panic, +/// every sample finite. +#[test] +fn hostile_envelopes_are_refused_or_tamed_and_always_mix() { + let dir = temp_dir("hostile"); + let (mut s, id) = session_with_sound(&dir); + run(&mut s, "sound.place", json!({"sound": id, "frame": 0, "extend": true})); + let times = [json!(0), json!(-1), json!(1e308), json!(-1e308), json!(0.0001), json!(3.5), json!(u64::MAX), json!("1"), json!(null)]; + let levels = [json!(0), json!(1), json!(-5), json!(1e300), json!(0.5), json!(true), json!([]), json!(-0.0)]; + let mut seed = 7u64; + let mut next = move || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize + }; + let mut accepted = 0; + for round in 0..200 { + let n = next() % 20; + let points: Vec = (0..n).map(|_| json!({"at": times[next() % times.len()], "left": levels[next() % levels.len()], "right": levels[next() % levels.len()]})).collect(); + let sync = ["event", "start", "stop", "stream"][round % 4]; + let repeats = [json!(0), json!(1), json!(65_535), json!(-3), json!(1e12)]; + let p = match round % 5 { + 0 => json!({"frame": 0, "envelope": "loud"}), + 1 => json!({"frame": 0, "envelope": points, "sync": sync, "loop": round % 2 == 0}), + 2 => json!({"frame": 0, "envelope": points, "repeat": repeats[round % repeats.len()]}), + 3 => json!({"frame": 0, "envelope": points, "sync": sync}), + _ => json!({"frame": 0, "envelope": [{"at": 0, "left": 1, "right": 0}, {"at": 0.1 * n as f64, "left": 0, "right": 1}], "sync": sync}), + }; + if s.execute("sound.set", &p).is_ok() { + accepted += 1; + } + let fs = s.timeline().layers.iter().find_map(|l| l.keyframe_at(0).and_then(|k| k.sound.clone())); + if let Some(anicraft_doc::SoundEffect::Custom(points)) = fs.as_ref().map(|f| &f.effect) { + assert!(points.len() <= 16, "at most 16 points kept"); + assert!(points.iter().all(|q| q.at.is_finite() && q.at >= 0.0 && (0.0..=1.0).contains(&q.left) && (0.0..=1.0).contains(&q.right)), "{points:?}"); + } + for rate in [8000, 44_100, 192_000] { + let voices = anicraft_doc::sound::voices(&s.doc, rate); + let mut out = vec![0.0; 2 * 4096]; + for start in [0, 1000, u64::from(rate)] { + audio::mix(&voices, rate, audio::MixOptions::default(), start, &mut out); + assert!(out.iter().all(|x| x.is_finite()), "round {round}, {rate} Hz: {p}"); + } + } + } + assert!(accepted >= 40, "well-formed envelopes still apply ({accepted})"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests_warp.rs b/crates/engine/src/tests_warp.rs new file mode 100644 index 00000000..1a3aab39 --- /dev/null +++ b/crates/engine/src/tests_warp.rs @@ -0,0 +1,264 @@ +//! Asset Warp end to end (ADR 0079): meshes on a shape and a bitmap, pins added, moved and +//! removed, keyframed and tweened, undo, refusals, stale artwork, the file format, renders and +//! exports, and plug-in policy. + +use super::*; +use anicraft_doc::warp::PinId; +use anicraft_doc::{Document, ElementKind, Shape, Stage}; +use anicraft_geom::{Path, Vec2}; +use anicraft_render::render_frame; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +/// The shape of element `id` as it shows at `frame`. +fn shape_at(s: &Session, id: u64, frame: u32) -> Shape { + s.timeline() + .layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + els.iter().find(|e| e.id.0 == id).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }) + }) + .unwrap_or_else(|| panic!("no shape {id} at frame {frame}")) +} + +/// A 400 × 300 stage, 20 frames, with a blue 200 × 80 drawing object at (100, 100) and a +/// 40 × 20 bitmap placed at (300, 230). Returns the session, the rectangle and the bitmap. +pub(crate) fn warped() -> (Session, u64, u64) { + let d = Document { stage: Stage { width: 400, height: 300, ..Stage::default() }, ..Document::default() }; + let mut s = Session::new(d); + let rect = run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 80, "fill": "#3080ff", "object": true}))["element"].as_u64().unwrap(); + let bm = anicraft_doc::BitmapId(s.doc.alloc_id()); + let mut rgba = Vec::new(); + for y in 0..20u32 { + for x in 0..40u32 { + rgba.extend_from_slice(&[(x * 6) as u8, (y * 12) as u8, 128, 255]); + } + } + let png = anicraft_render::encode_png(40, 20, &rgba).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(bm, "ramp.png", png).unwrap())); + let bitmap = run(&mut s, "library.place", json!({"bitmap": bm.0, "x": 300, "y": 230}))["element"].as_u64().unwrap(); + run(&mut s, "timeline.insert_frame", json!({"frame": 19})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + (s, rect, bitmap) +} + +fn pin_add(s: &mut Session, el: u64, x: f32, y: f32) -> u64 { + run(s, "warp.pin_add", json!({"element": el, "x": x, "y": y}))["pin"].as_u64().unwrap() +} + +#[test] +fn pins_bend_a_shape_and_the_rest_pose_is_the_drawing() { + let (mut s, rect, _) = warped(); + let drawn = shape_at(&s, rect, 0).path.clone(); + let before = render_frame(&s.doc, 0, 1.0).unwrap().data; + let v = run(&mut s, "warp.add", json!({"element": rect})); + assert_eq!((v["created"].as_bool(), v["resolution"].as_u64(), v["columns"].as_u64(), v["rows"].as_u64()), (Some(true), Some(12), Some(12), Some(5))); + let a = pin_add(&mut s, rect, 110.0, 140.0); + let b = pin_add(&mut s, rect, 200.0, 140.0); + let c = pin_add(&mut s, rect, 290.0, 140.0); + // Pins alone move nothing: the outline is the drawing, bit for bit, and so is the render. + let sh = shape_at(&s, rect, 0); + assert_eq!(*sh.path, *drawn); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + let info = run(&mut s, "warp.info", json!({"element": rect})); + assert_eq!((info["pins"].as_array().map(Vec::len), info["bent"].as_bool()), (Some(3), Some(false))); + // Dragging the right pin down bends the right end most. + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": c, "x": 290, "y": 200})); + let w = shape_at(&s, rect, 0).live_warp().cloned().unwrap(); + // The rectangle's own space is centred on it. + let local = |x: f32, y: f32| Vec2::new(x - 200.0, y - 140.0); + let moved = |x: f32| w.map(local(x, 140.0)).distance(local(x, 140.0)); + assert!(moved(280.0) > 40.0 && moved(250.0) > moved(150.0) && moved(120.0) < 3.0, "{} {} {}", moved(280.0), moved(250.0), moved(120.0)); + assert!(w.pin(PinId(a)).is_some() && w.pin(PinId(b)).is_some()); + assert_ne!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + // Off the artwork there is nothing to pin; a pin can't go twice in one place. + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 10, "y": 10})).contains("on the artwork")); + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 110, "y": 140})).contains("already")); +} + +#[test] +fn a_drag_is_one_undo_step_and_remove_restores_the_drawing() { + let (mut s, rect, _) = warped(); + let drawn = shape_at(&s, rect, 0).path.clone(); + pin_add(&mut s, rect, 110.0, 140.0); + let p = pin_add(&mut s, rect, 290.0, 140.0); + let at = |s: &Session| shape_at(s, rect, 0).live_warp().and_then(|w| w.pin(PinId(p)).map(|q| q.at)).unwrap(); + s.begin_gesture("Move Pin"); + for i in 1..=10 { + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": p, "dx": 0, "dy": 3})); + assert_eq!(at(&s).y, 3.0 * i as f32); + } + s.end_gesture(); + s.undo().unwrap(); + assert_eq!(at(&s), Vec2::new(90.0, 0.0), "the whole drag undoes at once"); + s.redo().unwrap(); + assert_eq!(at(&s).y, 30.0); + // Removing a pin: the artwork follows the pins that are left (one pin: it just moves). + run(&mut s, "warp.pin_remove", json!({"element": rect, "pin": p})); + assert!(shape_at(&s, rect, 0).live_warp().unwrap().at_rest()); + run(&mut s, "warp.remove", json!({"element": rect})); + let sh = shape_at(&s, rect, 0); + assert!(sh.warp.is_none() && *sh.path == *drawn); + assert!(err(&mut s, "warp.remove", json!({"element": rect})).contains("no warp")); +} + +#[test] +fn pin_poses_tween_between_keyframes_with_easing() { + let (mut s, rect, _) = warped(); + pin_add(&mut s, rect, 110.0, 140.0); + let p = pin_add(&mut s, rect, 290.0, 140.0); + // A keyframe at frame 11 holding the same mesh, a classic tween, then the pose there. + let lid = s.timeline().layers[0].id.0; + run(&mut s, "layer.select", json!({"layer": lid})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({})); + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": p, "x": 290, "y": 240, "frame": 10})); + let pin_y = |s: &Session, f: u32| shape_at(s, rect, f).live_warp().and_then(|w| w.pin(PinId(p)).map(|q| q.at.y)).unwrap(); + assert_eq!((pin_y(&s, 0), pin_y(&s, 10)), (0.0, 100.0)); + assert!((pin_y(&s, 5) - 50.0).abs() < 1e-3, "halfway: {}", pin_y(&s, 5)); + // The tweened outline is the mesh bent by the halfway pins (not a blend of two outlines). + let mid = shape_at(&s, rect, 5); + let mut want = shape_at(&s, rect, 0).live_warp().cloned().unwrap(); + if let Some(q) = want.pins.iter_mut().find(|q| q.id == PinId(p)) { + q.at.y = 50.0; + } + assert_eq!(*mid.path, *want.outline()); + // Easing applies to the pins. + run(&mut s, "timeline.set_easing", json!({"easing": "quad_in"})); + assert!(pin_y(&s, 5) < 40.0, "eased in: {}", pin_y(&s, 5)); + // A pin added later lands on both keyframes, where the artwork shows on each. + let late = pin_add(&mut s, rect, 200.0, 110.0); + for f in [0, 10] { + assert!(shape_at(&s, rect, f).live_warp().unwrap().pin(PinId(late)).is_some(), "frame {f}"); + } + // Moving a pin mid-tween keys the frame with what it shows. + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": late, "dx": 0, "dy": -5, "frame": 4})); + assert!(s.timeline().layers[0].keyframe_starting_at(4).is_some()); +} + +#[test] +fn a_bitmap_bends_in_every_renderer_and_export() { + let (mut s, _, bmp) = warped(); + let before = render_frame(&s.doc, 0, 1.0).unwrap(); + pin_add(&mut s, bmp, 285.0, 230.0); + let p = pin_add(&mut s, bmp, 315.0, 230.0); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before.data, "pinned, not yet moved: exactly as drawn"); + run(&mut s, "warp.pin_move", json!({"element": bmp, "pin": p, "x": 315, "y": 270})); + let after = render_frame(&s.doc, 0, 1.0).unwrap(); + // The bent image covers pixels below where the image was. + let covered = |pm: &anicraft_render::Pixmap, x: u32, y: u32| pm.pixel(x, y).is_some_and(|c| c[2] > 0.45 && c[0] < 0.95); + assert!(!covered(&before, 318, 262) && covered(&after, 318, 262)); + let info = run(&mut s, "warp.info", json!({"element": bmp})); + assert_eq!((info["bitmap"].as_bool(), info["bent"].as_bool()), (Some(true), Some(true))); + // SVG bakes the bent image; the HTML page reports it. + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + assert!(svg.contains(" p); + // Older files (no warp) still read; a warped file read by this build keeps its shape. + let plain = crate::format::to_json(&warped().0.doc).unwrap(); + assert!(!plain.contains("\"warp\"")); + // Another tool changes the outline: the warp no longer shows, and the next pin move + // starts from the shape as it is, with its pins where they show (nothing jumps). + let edited = { + let l = Arc::make_mut(&mut t.doc.timeline_mut(0).layers[0]); + let k = Arc::make_mut(&mut l.keyframes[0]); + let e = k.elements.iter_mut().find(|e| e.id.0 == rect).unwrap(); + let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind else { panic!() }; + sh.path = Arc::new(sh.path.transformed(&anicraft_geom::Affine::translate(5.0, 0.0))); + sh.path.clone() + }; + assert!(shape_at(&t, rect, 0).live_warp().is_none()); + assert_eq!(*shape_at(&t, rect, 0).path, *edited); + run(&mut t, "warp.pin_move", json!({"element": rect, "pin": p, "dx": 0, "dy": 0})); + let sh = shape_at(&t, rect, 0); + assert!(sh.live_warp().is_some_and(|w| w.at_rest()) && *sh.path == *edited); +} + +#[test] +fn warp_refusals() { + let (mut s, rect, _) = warped(); + // Nothing selected and no element. + s.selection.clear(); + assert!(err(&mut s, "warp.add", json!({})).contains("select")); + assert!(err(&mut s, "warp.add", json!({"element": rect, "resolution": 1})).contains("resolution")); + assert!(err(&mut s, "warp.add", json!({"element": 999_999})).contains("no element")); + assert!(err(&mut s, "warp.pin_move", json!({"element": rect, "pin": 5, "x": 1, "y": 1})).contains("no warp")); + // Symbols and text aren't warped. + let sym = run(&mut s, "draw.ellipse", json!({"x": 10, "y": 10, "w": 30, "h": 30, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Dot"})); + let inst = s.selection.on(s.layer).first().map(|e| e.0).unwrap_or(sym); + assert!(err(&mut s, "warp.add", json!({"element": inst})).contains("shapes and bitmaps")); + // A locked layer. + let lid = s.timeline().layers[0].id.0; + run(&mut s, "layer.toggle_lock", json!({"layer": lid})); + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 150, "y": 140})).contains("locked")); +} + +#[test] +fn plug_ins_may_warp() { + assert!(crate::cmds_plugin::plugin_may_call("warp.pin_move").is_ok()); + assert!(crate::cmds_plugin::plugin_may_call("warp.add").is_ok()); +} + +#[test] +fn warp_measured() { + // A 1,200-anchor outline on a 48 × 48 mesh with 32 pins, bent: release numbers go in the ADR. + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)); + for i in 1..600 { + p.line_to(Vec2::new(i as f32, (i as f32 * 0.05).sin() * 20.0)); + } + for i in (0..600).rev() { + p.line_to(Vec2::new(i as f32, 200.0 + (i as f32 * 0.05).cos() * 20.0)); + } + p.close(); + let mut w = anicraft_doc::warp::Warp::new(Arc::new(p), 48); + w.pins = (0..32).map(|i| anicraft_doc::warp::Pin { id: PinId(i), rest: Vec2::new(i as f32 * 18.0, 100.0), at: Vec2::new(i as f32 * 18.0, 100.0 + (i % 5) as f32 * 9.0) }).collect(); + let t = std::time::Instant::now(); + let n = 20; + let mut cmds = 0; + for _ in 0..n { + cmds += w.outline().cmds.len(); + } + eprintln!("warp: bend 1,200 anchors on 48×48 with 32 pins: {:.3} ms per frame ({} commands)", t.elapsed().as_secs_f64() * 1000.0 / f64::from(n), cmds / n as usize); +} diff --git a/crates/engine/src/timeline_drop_tests.rs b/crates/engine/src/timeline_drop_tests.rs new file mode 100644 index 00000000..8e26b9de --- /dev/null +++ b/crates/engine/src/timeline_drop_tests.rs @@ -0,0 +1,163 @@ +//! SVG into the Library and drops on the timeline (ADR 0065): a drawing becomes one graphic +//! symbol; media dropped on a layer's frame land there, in one undo step, and layers that can't +//! take them refuse without changing anything. + +use super::*; +use serde_json::json; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-tldrop-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A 4 × 2 PNG, a 40 × 20 one-rectangle SVG, a short WAV and a masked SVG in `dir`. +fn media(dir: &Path) -> (String, String, String, String) { + let png = dir.join("photo.png"); + std::fs::write(&png, anicraft_render::encode_png(4, 2, &[255u8; 4 * 2 * 4]).unwrap()).unwrap(); + let svg = dir.join("badge.svg"); + std::fs::write(&svg, r##""##).unwrap(); + let wav = dir.join("beep.wav"); + std::fs::write(&wav, crate::cmds_sound::test_wav(8000, &[0.25; 4000])).unwrap(); + let masked = dir.join("masked.svg"); + std::fs::write(&masked, r##""##).unwrap(); + let s = |p: std::path::PathBuf| p.display().to_string(); + (s(png), s(svg), s(wav), s(masked)) +} + +#[test] +fn an_svg_imported_to_the_library_is_one_graphic_symbol_centred_on_its_registration_point() { + let dir = temp_dir("svgsym"); + let (_, svg, _, masked) = media(&dir); + let mut s = Session::default(); + let history = s.history_len(); + let v = run(&mut s, "file.import_to_library", json!({"path": svg})); + assert_eq!(s.history_len(), history + 1, "one undo step"); + assert_eq!((s.doc.library.len(), v["name"].as_str()), (1, Some("badge"))); + let sym = s.doc.library[0].clone(); + assert_eq!(sym.kind, anicraft_doc::SymbolKind::Graphic); + assert_eq!(sym.timeline.layers.len(), 1); + // The 40 × 20 drawing sits around the registration point. + let k = &sym.timeline.layers[0].keyframes[0]; + let b = k.elements.iter().fold(anicraft_geom::Rect::EMPTY, |r, e| match &e.kind { + anicraft_doc::ElementKind::Shape(sh) => r.union(&sh.path.bounds().transformed(&e.transform)), + _ => r, + }); + assert!(b.center().x.abs() < 0.01 && b.center().y.abs() < 0.01 && (b.width() - 40.0).abs() < 0.01, "{b:?}"); + assert!(s.timeline().layers.iter().all(|l| l.keyframes.iter().all(|k| k.elements.is_empty())), "nothing on the stage"); + // Again: a free name. A masked drawing keeps its mask layer inside the symbol. + assert_eq!(run(&mut s, "file.import_to_library", json!({"path": svg}))["name"], "badge 2"); + run(&mut s, "file.import_to_library", json!({"path": masked})); + let m = s.doc.library.last().unwrap(); + assert!(m.timeline.layers.iter().any(|l| l.kind == anicraft_doc::LayerKind::Mask) && m.timeline.layers.len() == 2, "{:?}", m.timeline.layers.iter().map(|l| (&l.name, l.kind)).collect::>()); + // Placed, it shows. + run(&mut s, "library.place", json!({"symbol": sym.id.0, "x": 100, "y": 100})); + assert!(!anicraft_doc::evaluate(&s.doc, 0).items.is_empty()); + let empty = dir.join("empty.svg"); + std::fs::write(&empty, r#""#).unwrap(); + let before = s.doc.clone(); + assert!(s.execute("file.import_to_library", &json!({"path": empty.display().to_string()})).is_err(), "a drawing with no shapes adds nothing"); + assert!(s.doc == before); +} + +/// A session whose one layer has a keyframe at 0, 12 frames long, holding a rectangle. +fn timeline_session() -> (Session, anicraft_doc::LayerId) { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_frame", json!({"count": 11})); + let layer = s.layer; + (s, layer) +} + +#[test] +fn an_image_dropped_on_a_layers_frame_goes_into_a_keyframe_there_in_one_step() { + let dir = temp_dir("tlimg"); + let (png, svg, _, _) = media(&dir); + let (mut s, layer) = timeline_session(); + let above = run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap(); + let history = s.history_len(); + let v = run(&mut s, "file.drop", json!({"paths": [png, svg], "to": "timeline", "layer": layer.0, "frame": 5, "x": 200, "y": 100})); + assert_eq!(s.history_len(), history + 1, "one undo step for the whole drop"); + assert_eq!((s.layer, s.frame, v["keyframe_made"].as_bool()), (layer, 5, Some(true)), "the playhead and layer go to the drop"); + let l = s.timeline().layer(layer).unwrap(); + let k = l.keyframe_at(5).unwrap(); + assert_eq!(k.start, 5, "a keyframe starting at the frame"); + assert_eq!(k.elements.len(), 3, "what the frame showed, the image and the drawing"); + assert_eq!(l.keyframe_at(0).unwrap().elements.len(), 1, "the frames before are untouched"); + assert_eq!(s.selection.len(), 2, "what was dropped is selected"); + for id in s.selection.ids().collect::>() { + let b = s.element_bounds(id); + assert!((b.center().x - 200.0).abs() < 0.01 && (b.center().y - 100.0).abs() < 0.01, "{b:?}"); + } + assert!(s.timeline().layer(anicraft_doc::LayerId(above)).unwrap().keyframes.iter().all(|k| k.elements.is_empty()), "the layer active before the drop is untouched"); + run(&mut s, "edit.undo", json!({})); + let l = s.timeline().layer(layer).unwrap(); + assert!(l.keyframe_starting_at(5).is_none() && s.doc.bitmaps.is_empty()); + // On a keyframe's first frame, no new keyframe: the image joins it. + let v = run(&mut s, "file.drop", json!({"paths": [media(&dir).0], "to": "timeline", "layer": layer.0, "frame": 0})); + assert_eq!(v["keyframe_made"].as_bool(), Some(false)); + assert_eq!(s.timeline().layer(layer).unwrap().keyframes.len(), 1); +} + +#[test] +fn a_sound_dropped_on_a_frame_goes_onto_the_keyframe_holding_it() { + let dir = temp_dir("tlsnd"); + let (_, _, wav, _) = media(&dir); + let (mut s, layer) = timeline_session(); + let v = run(&mut s, "file.drop", json!({"path": wav, "to": "timeline", "layer": layer.0, "frame": 7})); + assert_eq!(v["keyframe_made"].as_bool(), Some(false)); + let l = s.timeline().layer(layer).unwrap(); + assert_eq!(l.keyframes.len(), 1, "no keyframe made for a sound"); + assert!(l.keyframes[0].sound.is_some(), "onto the keyframe the frame is in"); + // Past the layer's end, a keyframe is made there for it. + run(&mut s, "file.drop", json!({"path": media(&dir).2, "to": "timeline", "layer": layer.0, "frame": 30})); + let l = s.timeline().layer(layer).unwrap(); + assert!(l.keyframe_at(30).is_some_and(|k| k.start == 30 && k.sound.is_some())); +} + +#[test] +fn drops_on_the_timeline_refuse_layers_that_cant_take_them_and_change_nothing() { + let dir = temp_dir("tlbad"); + let (png, _, wav, masked) = media(&dir); + let (mut s, layer) = timeline_session(); + let folder = run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap(); + let layers = s.timeline().layers.len(); + // A drawing with masks can't go on one layer: a graphic symbol holding it goes there. + run(&mut s, "file.drop", json!({"path": masked, "to": "timeline", "layer": layer.0, "frame": 2})); + assert_eq!(s.timeline().layers.len(), layers, "no layers added"); + let k = s.timeline().layer(layer).unwrap().keyframe_at(2).unwrap(); + assert!(k.elements.iter().any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { .. }))); + assert_eq!(s.doc.library.len(), 1); + let before = s.doc.clone(); + let wav2 = dir.join("beep2.wav"); + std::fs::copy(&wav, &wav2).unwrap(); + for p in [ + json!({"path": png.clone(), "to": "timeline", "layer": folder, "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": u64::MAX, "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0}), + json!({"path": png.clone(), "to": "timeline", "frame": 0}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0, "frame": u64::MAX}), + json!({"path": png.clone(), "to": "timeline", "layer": layer.0, "frame": -1}), + json!({"paths": [wav.clone(), wav2.display().to_string()], "to": "timeline", "layer": layer.0, "frame": 0}), + json!({"paths": [png.clone(), dir.join("gone.png").display().to_string()], "to": "timeline", "layer": layer.0, "frame": 4}), + ] { + assert!(s.execute("file.drop", &p).is_err(), "{p}"); + assert!(s.doc == before, "{p} changed the document"); + } + s.layer = layer; + run(&mut s, "layer.toggle_lock", json!({})); + let before = s.doc.clone(); + for f in [png, wav] { + let e = s.execute("file.drop", &json!({"path": f, "to": "timeline", "layer": layer.0, "frame": 1})).unwrap_err(); + assert!(e.to_string().contains("locked"), "{e}"); + assert!(s.doc == before); + } +} diff --git a/crates/engine/src/timeline_key_tests.rs b/crates/engine/src/timeline_key_tests.rs new file mode 100644 index 00000000..32946f09 --- /dev/null +++ b/crates/engine/src/timeline_key_tests.rs @@ -0,0 +1,137 @@ +//! F5, F6 and F7 as the keys work in the editor (user reports #242 and #254). + +use super::*; +use anicraft_doc::{Keyframe, LayerId}; +use serde_json::json; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn spans(s: &Session, layer: LayerId) -> Vec<(u32, u32)> { + s.timeline().layer(layer).unwrap().keyframes.iter().map(|k| (k.start, k.duration)).collect() +} + +/// A layer whose keyframes are exactly `keys` (start, duration). +fn layer_with(s: &mut Session, keys: &[(u32, u32)]) -> LayerId { + let id = LayerId(run(s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let l = s.layer_mut(Some(id)).unwrap(); + l.keyframes = keys.iter().map(|&(a, d)| Arc::new(Keyframe::new(a, d))).collect(); + id +} + +#[test] +fn f5_with_no_frame_selection_extends_every_layer_that_reaches_the_playhead() { + // The report's example: playhead at frame 5 (index 4). + let mut s = Session::default(); + let l1 = layer_with(&mut s, &[(0, 8)]); + let l2 = layer_with(&mut s, &[(0, 4)]); + let l3 = layer_with(&mut s, &[(0, 6)]); + let l4 = layer_with(&mut s, &[(0, 2), (2, 7)]); + // Content only after the playhead, and a gap under it: both move along. + let later = layer_with(&mut s, &[(6, 3)]); + let gap = layer_with(&mut s, &[(0, 2), (7, 2)]); + let first = s.timeline().layers.iter().find(|l| ![l1, l2, l3, l4, later, gap].contains(&l.id)).map(|l| l.id).unwrap(); + s.layer_mut(Some(first)).unwrap().keyframes = vec![Arc::new(Keyframe::new(0, 1))]; + s.layer = l2; + s.set_frame(4); + let v = run(&mut s, "timeline.insert_frame", json!({"all_layers": true})); + assert_eq!(spans(&s, l1), vec![(0, 9)], "frames 1–8: extended"); + assert_eq!(spans(&s, l2), vec![(0, 4)], "frames 1–4 end before the playhead: unchanged, even when active"); + assert_eq!(spans(&s, l3), vec![(0, 7)], "frames 1–6: extended"); + assert_eq!(spans(&s, l4), vec![(0, 2), (2, 8)], "frames 1–9: extended"); + assert_eq!(spans(&s, later), vec![(7, 3)], "a key after the playhead moves one frame later"); + assert_eq!(spans(&s, gap), vec![(0, 2), (8, 2)], "a gap under the playhead grows by one"); + assert_eq!(spans(&s, first), vec![(0, 1)]); + assert_eq!(v["layers"].as_array().unwrap().len(), 5); + assert_eq!(s.frame, 4, "without advance the playhead stays"); + // One undo step takes it back on every layer. + run(&mut s, "edit.undo", json!({})); + assert_eq!(spans(&s, l1), vec![(0, 8)]); + assert_eq!(spans(&s, l4), vec![(0, 2), (2, 7)]); + assert_eq!(spans(&s, gap), vec![(0, 2), (7, 2)]); +} + +#[test] +fn f5_past_every_layer_lengthens_the_active_one() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(0, 3)]); + let b = layer_with(&mut s, &[(0, 5)]); + s.layer = a; + s.set_frame(9); + run(&mut s, "timeline.insert_frame", json!({"all_layers": true, "advance": true})); + assert_eq!(spans(&s, a), vec![(0, 10)], "extended up to the playhead"); + assert_eq!(spans(&s, b), vec![(0, 5)]); + assert_eq!(s.frame, 9, "the frame made is the playhead's own"); +} + +#[test] +fn f5_advance_moves_the_playhead_onto_the_new_frame() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(0, 1)]); + s.layer = a; + for want in 1..4 { + let v = run(&mut s, "timeline.insert_frame", json!({"layer": a.0, "advance": true})); + assert_eq!(s.frame, want); + assert_eq!(v["playhead"], json!(want)); + } + assert_eq!(spans(&s, a), vec![(0, 4)], "holding F5 walks along, one frame each"); +} + +#[test] +fn f6_on_a_keyframe_keys_the_next_frame_and_follows() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(0, 1)]); + s.layer = a; + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + for want in 1..4 { + run(&mut s, "timeline.insert_keyframe", json!({"advance": true})); + assert_eq!(s.frame, want, "F6 on a keyframe makes the next one and goes there"); + } + assert_eq!(spans(&s, a), vec![(0, 1), (1, 1), (2, 1), (3, 1)]); + assert_eq!(s.timeline().layer(a).unwrap().keyframes[3].elements.len(), 1, "a copy of the drawing"); + // Inside a span (not on its key) F6 keys the playhead's own frame. + run(&mut s, "timeline.insert_frame", json!({"layer": a.0, "frame": 3, "count": 3})); + s.set_frame(5); + run(&mut s, "timeline.insert_keyframe", json!({"advance": true})); + assert_eq!(s.frame, 5); + assert_eq!(spans(&s, a), vec![(0, 1), (1, 1), (2, 1), (3, 2), (5, 2)]); + // Without advance (scripts), the old behaviour: nothing new on a keyframe. + run(&mut s, "timeline.insert_keyframe", json!({})); + assert_eq!(s.frame, 5); + assert_eq!(spans(&s, a).len(), 5); +} + +#[test] +fn f7_on_a_keyframe_makes_a_blank_one_next_instead_of_clearing() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(0, 1)]); + s.layer = a; + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.insert_blank_keyframe", json!({"advance": true})); + assert_eq!(s.frame, 1); + let l = s.timeline().layer(a).unwrap(); + assert_eq!(l.keyframes[0].elements.len(), 1, "the drawing is kept"); + assert!(l.keyframes[1].elements.is_empty(), "a blank key on the next frame"); + // Across two layers it advances only when both are on a keyframe. + let b = layer_with(&mut s, &[(0, 4)]); + run(&mut s, "timeline.insert_blank_keyframe", json!({"layers": [a.0, b.0], "frame": 1, "advance": true})); + assert_eq!(s.frame, 1); + assert_eq!(spans(&s, b), vec![(0, 1), (1, 3)]); +} + +#[test] +fn advance_at_the_last_frame_stays_in_range() { + let mut s = Session::default(); + let a = layer_with(&mut s, &[(MAX_FRAME - 1, 2)]); + s.layer = a; + s.set_frame(MAX_FRAME); + assert!(s.execute("timeline.insert_frame", &json!({"advance": true})).is_err()); + s.layer_mut(Some(a)).unwrap().keyframes = vec![Arc::new(Keyframe::new(MAX_FRAME, 1))]; + let _ = s.execute("timeline.insert_keyframe", &json!({"advance": true})); + assert!(s.frame <= MAX_FRAME); +} diff --git a/crates/engine/src/view_tests.rs b/crates/engine/src/view_tests.rs new file mode 100644 index 00000000..7f12466f --- /dev/null +++ b/crates/engine/src/view_tests.rs @@ -0,0 +1,218 @@ +//! Rulers, grid and guides (ADR 0076) through the commands: guides per scene with undo, the +//! settings, persistence, and the snap engine's priorities at several zooms. + +use crate::Session; +use anicraft_doc::{Document, GuideAxis}; +use anicraft_geom::Vec2; +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 guides(s: &Session) -> Vec<(GuideAxis, f32)> { + s.guides().iter().map(|g| (g.axis, g.at)).collect() +} + +/// A blank document drawing raw shapes, with a 100 × 80 rectangle at the origin. +fn rect_session() -> Session { + let mut s = Session::new(Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + s +} + +fn snap_at(s: &mut Session, x: f32, y: f32, r: f32) -> Option<(Vec2, String)> { + let v = run(s, "draw.snap", json!({"x": x, "y": y, "snap": r})); + let sn = v.get("snapped").filter(|v| v.is_object())?; + let f = |k: &str| sn[k].as_f64().unwrap_or(f64::NAN) as f32; + Some((Vec2::new(f("x"), f("y")), sn["to"].as_str().unwrap_or("").to_string())) +} + +#[test] +fn guides_are_added_moved_deleted_and_cleared_with_undo() { + let mut s = Session::new(Document::default()); + let v = run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 120})); + assert_eq!(v["index"], 0); + run(&mut s, "view.guide_add", json!({"axis": "h", "at": 64.5})); + assert_eq!(guides(&s), [(GuideAxis::Vertical, 120.0), (GuideAxis::Horizontal, 64.5)]); + assert!(s.is_dirty(), "guides are part of the document"); + run(&mut s, "view.guide_move", json!({"index": 0, "at": 300})); + assert_eq!(guides(&s)[0], (GuideAxis::Vertical, 300.0)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(guides(&s)[0], (GuideAxis::Vertical, 120.0), "a move is one undo step"); + run(&mut s, "view.guide_delete", json!({"index": 0})); + assert_eq!(guides(&s), [(GuideAxis::Horizontal, 64.5)]); + // Locked guides can't be moved or deleted one by one; new ones can still come. + run(&mut s, "view.guides_lock", json!({})); + assert!(s.execute("view.guide_move", &json!({"index": 0, "at": 1})).is_err()); + assert!(s.execute("view.guide_delete", &json!({"index": 0})).is_err()); + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": -40})); + run(&mut s, "view.guides_lock", json!({"on": false})); + assert_eq!(run(&mut s, "view.guides_clear", json!({}))["cleared"], 2); + assert!(guides(&s).is_empty()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(guides(&s).len(), 2, "Clear Guides is undoable"); + // Bad input says why and changes nothing. + for (id, p) in [ + ("view.guide_add", json!({"axis": "diagonal", "at": 1})), + ("view.guide_add", json!({"axis": "vertical"})), + ("view.guide_add", json!({"axis": "vertical", "at": 1e9})), + ("view.guide_move", json!({"index": 9, "at": 1})), + ("view.guide_delete", json!({})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + assert_eq!(guides(&s).len(), 2); +} + +#[test] +fn guides_belong_to_their_scene() { + let mut s = Session::new(Document::default()); + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 10})); + run(&mut s, "scene.new", json!({})); + assert!(guides(&s).is_empty(), "a new scene has no guides"); + run(&mut s, "view.guide_add", json!({"axis": "horizontal", "at": 20})); + run(&mut s, "scene.select", json!({"scene": 0})); + assert_eq!(guides(&s), [(GuideAxis::Vertical, 10.0)]); + run(&mut s, "scene.duplicate", json!({})); + assert_eq!(guides(&s), [(GuideAxis::Vertical, 10.0)], "a duplicated scene keeps its guides"); +} + +#[test] +fn guides_and_grid_settings_are_saved_and_older_files_open() { + let mut s = Session::new(Document::default()); + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 33.25})); + run(&mut s, "view.grid_set", json!({"spacing_x": 16, "spacing_y": 24, "color": "#ff000080", "over_objects": true, "show": true})); + run(&mut s, "view.guides_set", json!({"color": "#00ff00"})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + assert_eq!(back.scenes[0].guides.len(), 1); + assert_eq!((back.aids.grid.spacing_x, back.aids.grid.spacing_y, back.aids.grid.over_objects), (16.0, 24.0, true)); + assert!((back.aids.grid.color.a - 128.0 / 255.0).abs() < 1e-3); + // Whether the grid shows is the editor's, not the file's. + assert!(!text.contains("show_grid")); + // A document without any of it writes none of it, and a file from before opens as before. + let plain = crate::format::to_json(&Document::default()).unwrap(); + assert!(!plain.contains("guides") && !plain.contains("aids"), "{plain}"); + let old = crate::format::from_json(&plain).unwrap(); + assert!(old.scenes[0].guides.is_empty() && old.aids.is_default()); +} + +#[test] +fn settings_are_checked_and_toggles_take_no_undo_step() { + let mut s = Session::new(Document::default()); + let before = s.state; + let v = run(&mut s, "view.rulers", json!({})); + assert_eq!(v["rulers"], true); + run(&mut s, "view.grid_show", json!({})); + run(&mut s, "view.grid_snap", json!({"on": true})); + run(&mut s, "view.snap_pixels", json!({})); + run(&mut s, "view.grid_set", json!({"accuracy": "always"})); + run(&mut s, "view.guides_set", json!({"accuracy": "close", "snap": false})); + assert_eq!(s.state, before, "showing and snapping change no document"); + assert!(s.undo_label().is_none()); + let a = run(&mut s, "view.aids", json!({})); + assert_eq!((a["grid"]["show"].clone(), a["grid"]["snap"].clone(), a["grid"]["accuracy"].clone()), (json!(true), json!(true), json!("always"))); + assert_eq!((a["guides"]["snap"].clone(), a["guides"]["accuracy"].clone(), a["snap_pixels"].clone()), (json!(false), json!("close"), json!(true))); + for p in [json!({"spacing": 0}), json!({"spacing_x": 5000}), json!({"accuracy": "sometimes"}), json!({"color": "teal"})] { + assert!(s.execute("view.grid_set", &p).is_err(), "{p}"); + } + assert!(s.execute("view.guides_set", &json!({"accuracy": "always"})).is_err(), "guides never always snap"); + assert_eq!(*s.doc.aids, anicraft_doc::Aids::default(), "nothing changed on a refusal"); + run(&mut s, "view.grid_set", json!({"spacing": 50})); + assert_eq!(s.undo_label(), Some("Edit Grid…")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.aids.grid.spacing_x, 20.0); +} + +#[test] +fn snapping_priorities_hold_at_every_zoom() { + for zoom in [0.5f32, 1.0, 2.0, 8.0] { + let r = 10.0 / zoom; + // Distances in screen pixels, so each case means the same at every zoom. + let d = |px: f32| px / zoom; + let mut s = rect_session(); + // A point beats a guide nearer still: the rectangle's corner (100, 0). + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 100.0 + d(4.0)})); + assert_eq!(snap_at(&mut s, 100.0 + d(3.0), d(2.0), r), Some((Vec2::new(100.0, 0.0), "point".into())), "zoom {zoom}"); + // Away from corners, the guide beats the rectangle's right edge (a line). + let (q, to) = snap_at(&mut s, 100.0 + d(2.0), 40.0, r).unwrap(); + assert_eq!(to, "guide", "zoom {zoom}"); + assert!((q.x - (100.0 + d(4.0))).abs() < 1e-3 && (q.y - 40.0).abs() < 1e-3, "zoom {zoom}: {q:?}"); + // Without guides snapping, the edge. + run(&mut s, "view.guides_snap", json!({"on": false})); + let (q, to) = snap_at(&mut s, 100.0 + d(2.0), 40.0, r).unwrap(); + assert_eq!((to.as_str(), q.x), ("line", 100.0), "zoom {zoom}"); + // The grid, where no artwork is near: 100-pixel lines. + run(&mut s, "view.grid_set", json!({"spacing": 100, "snap": true})); + assert_eq!(snap_at(&mut s, 300.0 + d(4.0), 300.0 - d(6.0), r), Some((Vec2::new(300.0, 300.0), "grid".into())), "zoom {zoom}"); + assert_eq!(snap_at(&mut s, 300.0 + d(12.0), 300.0 + d(12.0), r), None, "zoom {zoom}: beyond 10 screen pixels"); + // The artwork's points still beat the grid. + assert_eq!(snap_at(&mut s, 100.0 - d(3.0), 80.0 + d(3.0), r), Some((Vec2::new(100.0, 80.0), "point".into())), "zoom {zoom}"); + // Shift (no radius) snaps nothing. + assert_eq!(snap_at(&mut s, 300.0 + d(4.0), 300.0, 0.0), None); + } +} + +#[test] +fn guides_grid_and_pixels_snap_with_snap_to_objects_off() { + let mut s = rect_session(); + run(&mut s, "draw.snap_to_objects", json!({"on": false})); + assert_eq!(snap_at(&mut s, 103.0, 1.0, 10.0), None, "nothing to snap to"); + run(&mut s, "view.snap_pixels", json!({"on": true})); + assert_eq!(snap_at(&mut s, 103.4, 1.6, 10.0), Some((Vec2::new(103.0, 2.0), "pixel".into())), "the corner isn't looked at, pixels are"); + // A raw line's end dragged near a grid crossing goes onto it. + run(&mut s, "draw.line", json!({"x0": 200, "y0": 200, "x1": 260, "y1": 200, "stroke": "#0000ff"})); + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "view.grid_set", json!({"spacing": 50, "snap": true})); + let v = run(&mut s, "raw.move_point", json!({"x": 260, "y": 200, "to_x": 296, "to_y": 246, "snap": 10})); + assert_eq!((v["x"].as_f64(), v["y"].as_f64(), v["snapped"]["to"].as_str()), (Some(300.0), Some(250.0), Some("grid")), "{v}"); +} + +#[test] +fn a_moved_symbol_snaps_its_box_to_a_guide() { + let mut s = Session::new(Document::default()); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 40, "h": 40, "object": true})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "view.guide_add", json!({"axis": "vertical", "at": 200})); + let b = s.selection_bounds(); + // Grabbed near its top-right corner and moved so that corner lands 6 pixels short of the + // guide. + let dx = 200.0 - 6.0 - b.max.x; + let v = run(&mut s, "element.translate", json!({"dx": dx, "dy": 0, "snap": 10, "from": [b.max.x + dx - 2.0, b.min.y + 3.0]})); + assert_eq!(v["snapped"]["to"], "guide", "{v}"); + assert!((s.selection_bounds().max.x - 200.0).abs() < 1e-3, "{:?}", s.selection_bounds()); +} + +#[test] +fn inside_a_symbol_guides_line_up_with_the_stage() { + let mut s = Session::new(Document::default()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 40, "h": 40, "object": true})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "element.set_transform", json!({"x": 150, "y": 90, "sx": 2, "sy": 2})); + run(&mut s, "symbol.edit", json!({})); + let v = s.edit_view().expect("open in place"); + assert!(v.in_place && (v.scale - 2.0).abs() < 1e-4, "{v:?}"); + run(&mut s, "view.guide_add", json!({"axis": "horizontal", "at": 130})); + run(&mut s, "draw.snap_to_objects", json!({"on": false})); + // In the symbol's space, a point 2 stage pixels (1 symbol unit) off the guide. + let p = Vec2::new(5.0, (130.0 + 2.0 - v.origin.y) / v.scale); + let (q, to) = snap_at(&mut s, p.x, p.y, 10.0 / v.scale).expect("snaps"); + assert_eq!(to, "guide"); + assert!((v.origin.y + q.y * v.scale - 130.0).abs() < 1e-3, "lands on the guide as the stage shows it: {q:?}"); + assert_eq!(q.x, 5.0); +} + +#[test] +fn plug_ins_may_edit_guides_but_not_the_view() { + use crate::cmds_plugin::plugin_may_call; + for id in ["view.aids", "view.guide_add", "view.guide_move", "view.guide_delete", "view.guides_clear"] { + assert!(plugin_may_call(id).is_ok(), "{id}"); + } + for id in ["view.rulers", "view.grid_show", "view.grid_set", "view.guides_lock", "view.snap_pixels"] { + assert!(plugin_may_call(id).is_err(), "{id}"); + } +} diff --git a/crates/engine/src/web_tests.rs b/crates/engine/src/web_tests.rs index d496a0f5..2d04c05c 100644 --- a/crates/engine/src/web_tests.rs +++ b/crates/engine/src/web_tests.rs @@ -57,6 +57,8 @@ fn exports_come_back_as_files() { ("file.export_png", json!({"path": "frame.png"})), ("file.export_svg", json!({"path": "frame.svg"})), ("file.export_gif", json!({"path": "movie.gif", "to": 3})), + ("file.export_apng", json!({"path": "movie.png", "to": 3})), + ("file.export_webp", json!({"path": "movie.webp", "to": 3})), ("file.export_lottie", json!({"path": "movie.json"})), ("file.export_html", json!({"path": "movie.html"})), ("file.export_audio", json!({"path": "track.wav"})), @@ -67,12 +69,16 @@ fn exports_come_back_as_files() { s.execute("file.export_png_sequence", &json!({"dir": "frames", "to": 2})).unwrap(); let out = vfs::take_written(); let n = names(&out); - for want in ["frame.png", "frame.svg", "movie.gif", "movie.json", "movie.html", "track.wav", "sheet.png", "sheet.json", "frames/frame_00001.png", "frames/frame_00003.png"] { + for want in ["frame.png", "frame.svg", "movie.gif", "movie.png", "movie.webp", "movie.json", "movie.html", "track.wav", "sheet.png", "sheet.json", "frames/frame_00001.png", "frames/frame_00003.png"] { assert!(n.iter().any(|x| x == want), "{want} missing from {n:?}"); } assert!(out.iter().all(|(_, b)| !b.is_empty())); let png = &out.iter().find(|(p, _)| p == Path::new("frame.png")).unwrap().1; assert!(png.starts_with(b"\x89PNG")); + let apng = &out.iter().find(|(p, _)| p == Path::new("movie.png")).unwrap().1; + assert!(apng.starts_with(b"\x89PNG") && apng.windows(4).any(|w| w == b"acTL"), "an animated PNG"); + let webp = &out.iter().find(|(p, _)| p == Path::new("movie.webp")).unwrap().1; + assert!(webp.starts_with(b"RIFF") && webp.windows(4).any(|w| w == b"ANMF"), "an animated WebP"); let wav = &out.iter().find(|(p, _)| p == Path::new("track.wav")).unwrap().1; assert!(wav.starts_with(b"RIFF") && !n.iter().any(|x| x.ends_with(".tmp"))); let err = s.execute("file.export_video", &json!({"path": "movie.webm"})).unwrap_err().to_string(); diff --git a/crates/engine/tests/display_names.rs b/crates/engine/tests/display_names.rs new file mode 100644 index 00000000..928f929b --- /dev/null +++ b/crates/engine/tests/display_names.rs @@ -0,0 +1,210 @@ +//! Guard the production display surfaces without banning compatibility identifiers or notices. +use std::path::{Path, PathBuf}; + +const BANNED: &[&str] = &["as in Animate", "like Animate"]; +const ALLOWED: &[&str] = &[]; +const ROOTS: &[&str] = &["src", "../../src"]; + +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +fn banned_display(text: &str) -> bool { + if ALLOWED.contains(&text) { + return false; + } + BANNED.iter().any(|banned| { + text.match_indices(banned) + .any(|(at, _)| !text[..at].chars().next_back().is_some_and(is_word) && !text[at + banned.len()..].chars().next().is_some_and(is_word)) + }) +} + +// Read ordinary and raw Rust string literals, ignoring comments. No compiler dependency is +// needed, so this guard can also run by itself when a full application build is unavailable. +#[allow(clippy::cognitive_complexity)] // This small test-only lexer keeps raw-string/comment state together. +fn literals(source: &str) -> Vec { + let chars: Vec = source.chars().collect(); + let mut out = Vec::new(); + let mut at = 0; + let mut test_module = false; + let mut test_depth = 0_usize; + while at < chars.len() { + if chars.get(at..at + 12) == Some(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) { + at += 12; + let rest: String = chars[at..].iter().collect(); + if rest.trim_start().starts_with("mod ") { + test_module = true; + } + } else if chars.get(at..at + 2) == Some(&['/', '/']) { + while at < chars.len() && chars[at] != '\n' { + at += 1; + } + } else if chars.get(at..at + 2) == Some(&['/', '*']) { + at += 2; + let mut depth = 1; + while at < chars.len() && depth > 0 { + if chars.get(at..at + 2) == Some(&['/', '*']) { + depth += 1; + at += 2; + } else if chars.get(at..at + 2) == Some(&['*', '/']) { + depth -= 1; + at += 2; + } else { + at += 1; + } + } + } else if chars[at] == 'r' && matches!(chars.get(at + 1), Some('"' | '#')) { + let start = at; + at += 1; + while chars.get(at) == Some(&'#') { + at += 1; + } + let hashes = at - start - 1; + if chars.get(at) != Some(&'"') { + continue; + } + at += 1; + let begin = at; + while at < chars.len() { + if chars[at] == '"' && (1..=hashes).all(|n| chars.get(at + n) == Some(&'#')) { + break; + } + at += 1; + } + if !test_module { + out.push(chars[begin..at].iter().collect()); + } + at += 1 + hashes; + } else if chars[at] == '"' { + at += 1; + let mut text = String::new(); + while at < chars.len() { + let c = chars[at]; + at += 1; + if c == '"' { + break; + } + if c == '\\' && at < chars.len() { + text.push(chars[at]); + at += 1; + } else { + text.push(c); + } + } + if !test_module { + out.push(text); + } + } else if let Some(end) = char_literal_end(&chars, at) { + at = end; + } else { + if test_module { + match chars[at] { + '{' => test_depth += 1, + '}' => { + test_depth = test_depth.saturating_sub(1); + if test_depth == 0 { + test_module = false; + } + } + ';' if test_depth == 0 => test_module = false, + _ => {} + } + } + at += 1; + } + } + out +} + +fn char_literal_end(chars: &[char], at: usize) -> Option { + if chars.get(at) != Some(&'\'') { + return None; + } + let mut end = at + 2; + if chars.get(at + 1) == Some(&'\\') { + end += 1; + match chars.get(at + 2)? { + 'x' => end += 2, + 'u' if chars.get(at + 3) == Some(&'{') => { + end = at + 4; + while chars.get(end).is_some_and(|c| *c != '}') { + end += 1; + } + end += 1; + } + _ => {} + } + } + (chars.get(end) == Some(&'\'')).then_some(end + 1) +} + +fn check_tree(path: &Path, failures: &mut Vec) { + if path.is_dir() { + for entry in std::fs::read_dir(path).expect("source directory") { + let path = entry.expect("source entry").path(); + if path.file_name().is_some_and(|name| name == "tests") { + continue; + } + check_tree(&path, failures); + } + } else if path.extension().is_some_and(|ext| ext == "rs") { + let name = path.file_name().expect("source filename").to_string_lossy(); + if name == "tests.rs" || name.ends_with("_tests.rs") { + return; + } + let source = std::fs::read_to_string(path).expect("UTF-8 Rust source"); + // Skip only inline test modules, not later production following test-only imports. + for text in literals(&source) { + if banned_display(&text) { + failures.push(format!("{}: {text:?}", path.display())); + } + } + } +} + +#[test] +fn production_display_names_stay_neutral() { + let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut failures = Vec::new(); + for root in ROOTS { + let root = base.join(root); + assert!(root.exists(), "missing display source: {}", root.display()); + check_tree(&root, &mut failures); + } + assert!(failures.is_empty(), "Banned display names:\n{}", failures.join("\n")); +} + +#[test] +fn guard_distinguishes_labels_from_identifiers_and_comments() { + for name in BANNED { + assert!(banned_display(name), "{name}"); + } + for name in ALLOWED { + assert!(!banned_display(name), "{name}"); + } + assert!(!banned_display("filter.cameraRaw")); + assert!(!banned_display("tool.guidedUpright")); + assert!(!banned_display("insert.smartArt")); + assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]); + assert_eq!(literals("r#\"raw label\"#"), ["raw label"]); +} + +#[test] +fn guard_scans_production_after_test_only_items() { + let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"live label"#; } + "###; + assert_eq!(literals(source), ["live label"]); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]); +} + +#[test] +fn guard_scans_after_escaped_character_literals() { + let source = r###"let a = '\"'; let b = '\''; let c = '\\'; + let d = '\u{22}'; let e = '\x22'; + let label = "as in Animate"; + fn lifetime<'a>(value: &'a str) { let _ = "like Animate"; } + "###; + assert_eq!(literals(source), ["as in Animate", "like Animate"]); +} diff --git a/crates/engine/tests/example_plugins.rs b/crates/engine/tests/example_plugins.rs new file mode 100644 index 00000000..3fc2461b --- /dev/null +++ b/crates/engine/tests/example_plugins.rs @@ -0,0 +1,82 @@ +//! The sample plug-ins of `examples/plugins`, built to WebAssembly, through the engine: the +//! Plain Text Frames exporter on the sample movie and the Stepped Eases on a tween. +//! +//! They are built by `examples/plugins/build.sh` (CI's web job does, then sets +//! `ANICRAFT_EXAMPLE_PLUGINS` to their folder, so a missing module fails there). Without the +//! variable the test uses `examples/plugins/dist` when it is there and otherwise skips. + +use anicraft_engine::Session; +use serde_json::{Value, json}; +use std::path::PathBuf; +use std::time::Instant; + +fn folder() -> Option { + if let Ok(d) = std::env::var("ANICRAFT_EXAMPLE_PLUGINS") { + let d = PathBuf::from(d); + assert!(d.join("text_export.wasm").is_file() && d.join("stepped_ease.wasm").is_file(), "ANICRAFT_EXAMPLE_PLUGINS={} has no built sample plug-ins", d.display()); + return Some(d); + } + let d = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/plugins/dist"); + if d.join("text_export.wasm").is_file() && d.join("stepped_ease.wasm").is_file() { + Some(d) + } else { + eprintln!("skipped: build the sample plug-ins with examples/plugins/build.sh"); + None + } +} + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +#[test] +fn the_text_exporter_writes_the_sample_movie() { + let Some(dir) = folder() else { return }; + let mut s = Session::new(anicraft_doc::sample::demo()); + run(&mut s, "plugin.install", json!({"path": dir.join("text_export.wasm").display().to_string()})); + let formats = run(&mut s, "file.export_formats", json!({})); + assert!(formats["formats"].as_array().is_some_and(|f| f.iter().any(|x| x["id"] == "org.anicraft.text-export" && x["extensions"][0] == "txt"))); + let out = std::env::temp_dir().join(format!("anicraft-example-text-{}.txt", std::process::id())); + let _ = std::fs::remove_file(&out); + let t = Instant::now(); + let v = run(&mut s, "file.export_plugin", json!({"format": "org.anicraft.text-export", "path": out.display().to_string(), "options": {"detail": "Paths"}})); + let ms = t.elapsed().as_secs_f64() * 1e3; + let text = std::fs::read_to_string(&out).expect("written"); + let frames = s.doc.frame_count(); + assert_eq!(v["frames_read"].as_u64(), Some(u64::from(frames))); + assert!(text.starts_with("# anicraft-example-text-"), "{}", &text[..80.min(text.len())]); + assert_eq!(text.matches("\nframe ").count(), frames as usize); + assert!(text.contains("\nframe 1 (scene 1): ") && text.contains(" M"), "shapes with their outlines"); + eprintln!("Plain Text Frames: {frames} frames, {} bytes, {} instructions, {ms:.0} ms", text.len(), v["fuel"]); + // Every other frame, summary only. + let v = run(&mut s, "file.export_plugin", json!({"format": "org.anicraft.text-export", "path": out.display().to_string(), "options": {"detail": "Summary", "every": 2}, "confirm": true})); + assert_eq!(v["frames_read"].as_u64(), Some(u64::from(frames.div_ceil(2)))); + assert!(!std::fs::read_to_string(&out).expect("written").contains("element ")); + let _ = std::fs::remove_file(&out); +} + +#[test] +fn the_stepped_eases_drive_a_tween() { + let Some(dir) = folder() else { return }; + let mut s = Session::default(); + let t = Instant::now(); + run(&mut s, "plugin.install", json!({"path": dir.join("stepped_ease.wasm").display().to_string()})); + eprintln!("Stepped Eases: loaded and sampled 4 eases in {:.1} ms", t.elapsed().as_secs_f64() * 1e3); + let l = run(&mut s, "ease.list", json!({})); + let names: Vec<&str> = l["plugins"].as_array().into_iter().flatten().filter_map(|e| e["name"].as_str()).collect(); + assert_eq!(names, ["Stepped 2", "Stepped 4", "Stepped 8", "Smooth Steps 4"]); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut s, "timeline.goto", json!({"frame": 8})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 80, "dy": 0})); + run(&mut s, "timeline.create_tween", json!({"frame": 0, "easing": {"plugin": "org.anicraft.stepped-ease", "ease": "steps2"}})); + let xs: Vec = (0..9) + .map(|f| { + s.set_frame(f); + s.visible_elements().first().map_or(f32::NAN, |e| e.transform.translation().x - 5.0) + }) + .collect(); + // On twos over eight frames: still for the first half, then half way, then there. + assert_eq!(xs, [0.0, 0.0, 0.0, 0.0, 40.0, 40.0, 40.0, 40.0, 80.0]); +} diff --git a/crates/engine/tests/golden/mod.rs b/crates/engine/tests/golden/mod.rs index 0ddee4d3..d4f33418 100644 --- a/crates/engine/tests/golden/mod.rs +++ b/crates/engine/tests/golden/mod.rs @@ -34,14 +34,9 @@ fn out_dir() -> PathBuf { } fn decode(bytes: &[u8]) -> Result<(u32, u32, Vec), String> { - let mut reader = png::Decoder::new(bytes).read_info().map_err(|e| e.to_string())?; - let mut buf = vec![0; reader.output_buffer_size()]; - let info = reader.next_frame(&mut buf).map_err(|e| e.to_string())?; - if info.color_type != png::ColorType::Rgba || info.bit_depth != png::BitDepth::Eight { - return Err(format!("expected 8-bit RGBA, found {:?} {:?}", info.color_type, info.bit_depth)); - } - buf.truncate(info.buffer_size()); - Ok((info.width, info.height, buf)) + let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, bytes).map_err(|e| e.to_string())?; + let (w, h) = img.dimensions(); + Ok((w, h, img.to_rgba8())) } fn write(path: &Path, width: u32, height: u32, rgba: &[u8]) { diff --git a/crates/engine/tests/lottie_parity.rs b/crates/engine/tests/lottie_parity.rs new file mode 100644 index 00000000..114c1ea3 --- /dev/null +++ b/crates/engine/tests/lottie_parity.rs @@ -0,0 +1,243 @@ +//! Lottie export parity (ADR 0089): the exported animation, played by a Lottie player written +//! for the test from the public format description (`lottie_player`), draws what `evaluate` +//! draws at every frame, for the sample scenes, a movie of every kind of tween and ease, and +//! the self-authored XFL corpus. +//! +//! Each frame is drawn three ways by the CPU oracle: the document itself, the eased export +//! and the frame-by-frame export of earlier builds (`LottieKeys::Frames`). Where the export +//! reports nothing lost, the eased export must match the document; where it reports a loss +//! (a symbol fading as one group is faded shape by shape, a stretched radial gradient…), it +//! must draw at least as close to the document as the frame-by-frame export does. File sizes +//! of both are printed (`--nocapture`) and the eased one must be smaller. + +mod lottie_player; + +use anicraft_engine::doc::{ColorEffect, CustomEase, Document, Easing, Element, ElementId, ElementKind, Keyframe, LayerId, MotionTween, Paint, Property, PropertyKey, Rgba, Shape, Stroke, Track, Tween, TweenKind, sample}; +use anicraft_engine::geom::{Affine, Path, Vec2}; +use anicraft_engine::render::lottie::{LottieKeys, STEPPED, to_lottie_keyed}; +use anicraft_engine::render::{View, render}; +use anicraft_engine::text::Fonts; +use serde_json::Value; +use std::sync::Arc; + +/// A colour channel counts as different above this (out of 255): anti-aliasing noise from +/// sub-thousandth-of-a-pixel differences stays below it. +const CHANNEL: u8 = 3; + +/// How a drawing differs from the document's: pixels with a channel off by more than +/// [`CHANNEL`], and the largest difference. +fn diff(a: &[u8], b: &[u8]) -> (usize, u8) { + let mut count = 0; + let mut worst = 0u8; + for (p, q) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) { + let d = p.iter().zip(q).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0); + worst = worst.max(d); + if d > CHANNEL { + count += 1; + } + } + (count, worst) +} + +fn draw(dl: &anicraft_engine::doc::DisplayList, view: &View) -> Vec { + render(dl, view).unwrap().0.to_rgba8() +} + +/// Plays both exports of `doc` against the oracle at every frame; returns (eased, frames) +/// sizes in bytes. +fn check(name: &str, doc: &Document, scale: f32) -> (usize, usize) { + let last = doc.frame_count().saturating_sub(1); + let eased = to_lottie_keyed(doc, name, 0, last, true, LottieKeys::Eased); + let frames = to_lottie_keyed(doc, name, 0, last, true, LottieKeys::Frames); + let lossless = eased.report.keys().all(|k| k == STEPPED); + let (ev, fv): (Value, Value) = (serde_json::from_str(&eased.json).unwrap(), serde_json::from_str(&frames.json).unwrap()); + let view = View::stage(doc, scale); + let pixels = (view.width * view.height) as usize; + for f in 0..=last { + let want = draw(&anicraft_engine::doc::evaluate(doc, f), &view); + let got = draw(&lottie_player::frame(&ev, f64::from(f)), &view); + let (n, worst) = diff(&got, &want); + if lossless { + // Exact but for a few edge pixels (a thousandth of the frame). + assert!(n * 1000 <= pixels, "{name}, frame {f}: {n} of {pixels} pixels differ (worst {worst}); report {:?}", eased.report); + } else { + let old = draw(&lottie_player::frame(&fv, f64::from(f)), &view); + let (m, _) = diff(&old, &want); + assert!(n <= m + pixels / 1000, "{name}, frame {f}: eased {n} vs frame by frame {m} pixels off; report {:?}", eased.report); + } + } + println!("LOTTIE {name}: {} frames, eased {} bytes, frame by frame {} bytes ({:.0} % smaller), report {:?}", last + 1, eased.json.len(), frames.json.len(), 100.0 * (1.0 - eased.json.len() as f64 / frames.json.len() as f64), eased.report); + assert!(eased.json.len() <= frames.json.len(), "{name}: eased {} > frame by frame {}", eased.json.len(), frames.json.len()); + (eased.json.len(), frames.json.len()) +} + +fn shape_el(id: u64, m: Affine, shape: Shape) -> Arc { + Arc::new(Element { id: ElementId(id), name: String::new(), transform: m, color: ColorEffect::default(), kind: ElementKind::Shape(shape) }) +} + +/// A two-second movie, one layer per ease: classic tweens moving, turning, growing, skewing +/// and changing colour with every kind of ease (one cubic, several pieces, none exact), a +/// stroked shape growing evenly, a shape tween between compatible outlines, property groups +/// eased their own way, and a motion tween keyed on x, y, rotation and scale apart. +fn tweens_movie() -> Document { + let mut doc = Document::default(); + doc.stage.width = 480; + doc.stage.height = 360; + let custom = Easing::Custom(Arc::new(CustomEase::from_flat(&[(0.0, 0.0), (0.2, 1.4), (0.3, 1.4), (0.4, 1.4), (0.6, 0.5), (0.8, 1.0), (1.0, 1.0)].map(|(x, y)| Vec2::new(x, y))).unwrap())); + let eases = [Easing::Linear, Easing::Classic(-80.0), Easing::Classic(100.0), Easing::QuadInOut, Easing::BackOut, Easing::BounceOut, custom.clone(), Easing::ElasticOut, Easing::SineInOut, Easing::CubicBezier(0.2, 0.9, 0.3, 1.3)]; + let tl = doc.timeline_mut(0); + tl.layers.clear(); + for (i, e) in eases.iter().enumerate() { + let y = 20.0 + 30.0 * i as f32; + let fill = Paint::Solid(Rgba::new(0.1 * i as f32, 0.5, 1.0 - 0.08 * i as f32, 1.0)); + let shape = Shape::filled(Path::rect(-10.0, -8.0, 20.0, 16.0), fill); + let a = Affine::translate(30.0, y); + let b = Affine::translate(400.0, y + 10.0).mul(&Affine::rotate(1.0 + i as f32 * 0.4)).mul(&Affine::scale(1.5, 0.75)); + let mut l = anicraft_engine::doc::Layer::new(LayerId(10 + i as u64), format!("ease {i}")); + let mut k0 = Keyframe::new(0, 30); + k0.elements = vec![shape_el(100 + i as u64, a, shape.clone())]; + let mut tw = Tween::new(e.clone(), TweenKind::Classic); + if i == 1 { + // Position eased one way, rotation another, scale linear. + tw.groups = vec![(anicraft_engine::doc::EaseGroup::Rotation, Easing::BackOut), (anicraft_engine::doc::EaseGroup::Scale, Easing::Linear)]; + } + k0.tween = Some(tw); + let mut k1 = Keyframe::new(30, 18); + let mut end = shape.clone(); + end.fill = Some(Paint::Solid(Rgba::new(1.0, 0.2 * (i % 5) as f32, 0.1, 0.6))); + k1.elements = vec![shape_el(100 + i as u64, b, end)]; + l.keyframes = vec![Arc::new(k0), Arc::new(k1)]; + tl.layers.push(Arc::new(l)); + } + // A stroked circle growing evenly (its stroke widens with it), then shrinking linearly. + let mut ring = Shape::filled(Path::ellipse(0.0, 0.0, 12.0, 12.0), Paint::Solid(Rgba::hex(0xffcc00))); + ring.stroke = Some(Stroke::new(Rgba::hex(0x223344), 3.0)); + let mut l = anicraft_engine::doc::Layer::new(LayerId(40), "ring"); + let mut k0 = Keyframe::new(0, 20); + k0.elements = vec![shape_el(140, Affine::translate(240.0, 330.0), ring.clone())]; + k0.tween = Some(Tween::new(Easing::Classic(60.0), TweenKind::Classic)); + let mut k1 = Keyframe::new(20, 20); + k1.elements = vec![shape_el(140, Affine::translate(240.0, 320.0).mul(&Affine::scale(2.0, 2.0)), ring.clone())]; + k1.tween = Some(Tween::new(Easing::Linear, TweenKind::Classic)); + let mut k2 = Keyframe::new(40, 8); + k2.elements = vec![shape_el(140, Affine::translate(100.0, 330.0).mul(&Affine::rotate(-0.5)), ring)]; + l.keyframes = vec![Arc::new(k0), Arc::new(k1), Arc::new(k2)]; + tl.layers.push(Arc::new(l)); + // A shape tween between outlines of the same structure, eased. + let mut l = anicraft_engine::doc::Layer::new(LayerId(41), "morph"); + let mut k0 = Keyframe::new(0, 24); + k0.elements = vec![shape_el(141, Affine::IDENTITY, Shape::filled(Path::rect(380.0, 300.0, 40.0, 40.0), Paint::Solid(Rgba::hex(0x884488))))]; + k0.tween = Some(Tween::new(Easing::CubicOut, TweenKind::Shape)); + let mut k1 = Keyframe::new(24, 24); + k1.elements = vec![shape_el(141, Affine::IDENTITY, Shape::filled(Path::rect(400.0, 280.0, 70.0, 20.0), Paint::Solid(Rgba::hex(0x44aa88))))]; + l.keyframes = vec![Arc::new(k0), Arc::new(k1)]; + tl.layers.push(Arc::new(l)); + // A motion tween: x, y, rotation and scale keyed at different frames with their own eases. + let mut l = anicraft_engine::doc::Layer::new(LayerId(42), "motion"); + let mut k0 = Keyframe::new(0, 48); + k0.elements = vec![shape_el(142, Affine::translate(60.0, 300.0), Shape::filled(Path::rect(-6.0, -6.0, 12.0, 12.0), Paint::Solid(Rgba::hex(0x00aa44))))]; + let key = |frame: u32, value: f32, ease: Easing| PropertyKey { frame, value, ease }; + let mut m = MotionTween::new(ElementId(142)); + m.tracks = vec![ + Track { property: Property::X, keys: vec![key(0, 60.0, Easing::QuadIn), key(20, 200.0, custom), key(47, 300.0, Easing::Linear)] }, + Track { property: Property::Y, keys: vec![key(0, 300.0, Easing::Linear), key(30, 250.0, Easing::BackInOut), key(47, 320.0, Easing::Linear)] }, + Track { property: Property::Rotation, keys: vec![key(0, 0.0, Easing::Classic(-40.0)), key(47, 540.0, Easing::Linear)] }, + Track { property: Property::ScaleX, keys: vec![key(10, 100.0, Easing::Linear), key(40, 250.0, Easing::Linear)] }, + Track { property: Property::ScaleY, keys: vec![key(10, 100.0, Easing::Linear), key(40, 250.0, Easing::Linear)] }, + ]; + k0.motion = Some(m); + l.keyframes = vec![Arc::new(k0)]; + tl.layers.push(Arc::new(l)); + doc +} + +#[test] +fn the_sample_scenes_play_as_evaluated() { + for (name, doc) in [("demo", sample::demo()), ("interactive", sample::interactive())] { + let scale = 320.0 / doc.stage.width as f32; + check(name, &doc, scale.min(1.0)); + } +} + +#[test] +fn every_tween_and_ease_plays_as_evaluated_with_few_keys() { + let doc = tweens_movie(); + let (eased, frames) = check("tweens", &doc, 0.5); + // A layer per ease: the exact ones are a few keys each. + let e = to_lottie_keyed(&doc, "tweens", 0, doc.frame_count() - 1, false, LottieKeys::Eased); + let v: Value = serde_json::from_str(&e.json).unwrap(); + let tr = |name: &str| -> Value { + let l = v["layers"].as_array().unwrap().iter().find(|l| l["nm"] == name).unwrap_or_else(|| panic!("{name}")); + l["shapes"][0]["it"].as_array().unwrap().last().unwrap().clone() + }; + let count = |p: &Value| if p["a"] == 1 { p["k"].as_array().unwrap().len() } else { 1 }; + for (name, keys) in [("ease 0", 2), ("ease 1", 2), ("ease 2", 2), ("ease 3", 3), ("ease 4", 2), ("ease 5", 8), ("ease 6", 3), ("ease 9", 2)] { + assert_eq!(count(&tr(name)["p"]), keys, "{name}: {}", tr(name)["p"]); + assert_eq!(count(&tr(name)["r"]), if name == "ease 1" { 2 } else { keys }, "{name} rotation"); + } + // Elastic and Sine: a key per frame while they move, and reported. + assert!(count(&tr("ease 7")["p"]) >= 29); + assert!(e.report.contains_key(STEPPED), "{:?}", e.report); + assert!(eased * 2 < frames, "eased {eased} vs frame by frame {frames}"); +} + +fn corpus_doc(case: &str) -> Document { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../xfl/tests/corpus").join(case); + let read = |p: &str| -> Result>, anicraft_xfl::XflError> { + match std::fs::read(dir.join(p)) { + Ok(b) => Ok(Some(b)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } + }; + anicraft_xfl::import_with_fonts(&read, &Fonts::from_faces(Vec::new())).unwrap_or_else(|e| panic!("{case}: {e}")).0 +} + +#[test] +fn the_xfl_corpus_plays_as_evaluated() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../xfl/tests/corpus"); + let mut cases: Vec = std::fs::read_dir(&root).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + cases.sort(); + assert!(cases.len() >= 10); + let (mut eased, mut frames) = (0, 0); + for case in &cases { + let (e, f) = check(case, &corpus_doc(case), 0.5); + eased += e; + frames += f; + } + println!("LOTTIE corpus: eased {eased} bytes, frame by frame {frames} bytes"); +} + + +#[test] +#[ignore = "timing; run with --ignored --nocapture"] +fn zz_timing() { + // A minute of Elastic: nothing fits, every frame is tried against every ease. + let mut long = Document::default(); + { + use anicraft_engine::doc::{Keyframe, Tween, TweenKind}; + let sq = |x: f32| shape_el(9, Affine::translate(x, 50.0), Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK))); + let mut k0 = Keyframe::new(0, 1440); + k0.elements = vec![sq(0.0)]; + k0.tween = Some(Tween::new(Easing::ElasticInOut, TweenKind::Classic)); + let mut k1 = Keyframe::new(1440, 1); + k1.elements = vec![sq(300.0)]; + let l = Arc::make_mut(&mut long.timeline_mut(0).layers[0]); + l.keyframes = vec![Arc::new(k0), Arc::new(k1)]; + let mut other = Tween::new(Easing::CubicBezier(0.3, 0.1, 0.2, 1.0), TweenKind::Classic); + other.groups = vec![(anicraft_engine::doc::EaseGroup::Rotation, Easing::BounceInOut), (anicraft_engine::doc::EaseGroup::Scale, Easing::BackInOut)]; + let mut k = Keyframe::new(0, 1); + k.tween = Some(other); + let mut l2 = anicraft_engine::doc::Layer::new(LayerId(77), "eases"); + l2.keyframes = vec![Arc::new(k)]; + long.timeline_mut(0).layers.push(Arc::new(l2)); + } + for (n, doc) in [("stress", sample::stress(20, 10, 240)), ("tweens", tweens_movie()), ("elastic minute", long)] { + let last = doc.frame_count() - 1; + for keys in [LottieKeys::Frames, LottieKeys::Eased] { + let t = std::time::Instant::now(); + let e = to_lottie_keyed(&doc, n, 0, last, false, keys); + println!("TIME {n} {keys:?}: {} frames, {:.1} ms, {} bytes", last + 1, t.elapsed().as_secs_f64() * 1000.0, e.json.len()); + } + } +} diff --git a/crates/engine/tests/lottie_player/mod.rs b/crates/engine/tests/lottie_player/mod.rs new file mode 100644 index 00000000..c71548a1 --- /dev/null +++ b/crates/engine/tests/lottie_player/mod.rs @@ -0,0 +1,282 @@ +//! A small Lottie player for tests (ADR 0089), written from the public Lottie format +//! description and independent of the exporter's code: it reads the JSON, evaluates every +//! keyframed property at a frame (holds, and Bézier eases solved on their own), and turns the +//! shape layers into a display list for the CPU oracle to draw. +//! +//! It plays what AniCraft writes: shape layers (paths, fills, linear and radial gradient +//! fills, strokes with caps, joins and dashes, group transforms with position — whole or +//! split — anchor, scale, rotation, skew and opacity), layer masks (added), track mattes +//! (alpha and luma) and the solid stage layer. Group opacity fades each shape, as Lottie's +//! shape groups do. A stroke under a stretched or skewed group would need Lottie's stretched +//! pen, which the oracle doesn't draw: it fails the test rather than being drawn wrongly. + +use anicraft_engine::doc::{Cap, ColorTransform, Dash, DisplayItem, DisplayList, ElementId, GradientStop, Join, LayerId, MaskMode, Paint, Rgba, Stroke, StrokeStyle}; +use anicraft_engine::geom::{Affine, FillRule, Path, PathCmd, Vec2}; +use serde_json::Value; +use std::sync::Arc; + +/// Numbers of a value: a number, or an array of numbers. +fn nums(v: &Value) -> Vec { + match v { + Value::Array(a) => a.iter().filter_map(Value::as_f64).collect(), + Value::Number(x) => x.as_f64().into_iter().collect(), + _ => Vec::new(), + } +} + +/// An ease handle's coordinate: a number or the first of an array. +fn first(v: &Value) -> f64 { + nums(v).first().copied().unwrap_or(0.0) +} + +/// CSS / Lottie cubic-bezier ease from (0,0) to (1,1) through (x1,y1), (x2,y2), at time x: +/// x(s) solved by bisection (monotonic for x handles within 0..1). +fn ease(x1: f64, y1: f64, x2: f64, y2: f64, x: f64) -> f64 { + let b = |s: f64, p1: f64, p2: f64| 3.0 * (1.0 - s) * (1.0 - s) * s * p1 + 3.0 * (1.0 - s) * s * s * p2 + s * s * s; + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..80 { + let mid = 0.5 * (lo + hi); + if b(mid, x1, x2) < x { lo = mid } else { hi = mid } + } + b(0.5 * (lo + hi), y1, y2) +} + +/// The keyframe pair around `t` and how far along: `(from, to, eased share)`. +fn segment(keys: &[Value], t: f64) -> (&Value, &Value, f64) { + let start = |k: &Value| k["t"].as_f64().unwrap(); + let k0 = &keys[0]; + if t <= start(k0) { + return (k0, k0, 0.0); + } + let i = keys.iter().rposition(|k| start(k) <= t).unwrap(); + let a = &keys[i]; + let Some(b) = keys.get(i + 1) else { return (a, a, 0.0) }; + if a["h"] == 1 { + return (a, a, 0.0); + } + let x = (t - start(a)) / (start(b) - start(a)); + let y = ease(first(&a["o"]["x"]), first(&a["o"]["y"]), first(&a["i"]["x"]), first(&a["i"]["y"]), x); + (a, b, y) +} + +fn mix(a: &[f64], b: &[f64], y: f64) -> Vec { + a.iter().zip(b).map(|(p, q)| p + (q - p) * y).collect() +} + +/// A property (`{a, k}`, or a split position `{s: true, x, y}`) at frame `t`. +pub fn prop(p: &Value, t: f64) -> Vec { + if p["s"] == true { + return [prop(&p["x"], t), prop(&p["y"], t)].concat(); + } + if p["a"] != 1 { + return nums(&p["k"]); + } + let keys = p["k"].as_array().unwrap(); + let (a, b, y) = segment(keys, t); + mix(&nums(&a["s"]), &nums(&b["s"]), y) +} + +/// Points of a path. +type Points = Vec<[f64; 2]>; + +/// A path property at frame `t`: vertices, in and out tangents, closed. +fn shape(p: &Value, t: f64) -> (Points, Points, Points, bool) { + let flat = |b: &Value, k: &str| -> Vec { b[k].as_array().unwrap().iter().flat_map(nums).collect() }; + let parts = |b: &Value| (flat(b, "v"), flat(b, "i"), flat(b, "o"), b["c"] == true); + let (v, i, o, c) = if p["a"] != 1 { + parts(&p["k"]) + } else { + let keys = p["k"].as_array().unwrap(); + let (a, b, y) = segment(keys, t); + let (pa, pb) = (parts(&a["s"][0]), parts(&b["s"][0])); + (mix(&pa.0, &pb.0, y), mix(&pa.1, &pb.1, y), mix(&pa.2, &pb.2, y), pa.3) + }; + let pairs = |f: Vec| f.chunks(2).map(|c| [c[0], c[1]]).collect::>(); + (pairs(v), pairs(i), pairs(o), c) +} + +fn path_of(p: &Value, t: f64) -> Path { + let (v, i, o, closed) = shape(p, t); + let pt = |q: [f64; 2]| Vec2::new(q[0] as f32, q[1] as f32); + let mut path = Path::new(); + if v.is_empty() { + return path; + } + path.cmds.push(PathCmd::MoveTo(pt(v[0]))); + let n = v.len(); + let segs = if closed { n } else { n - 1 }; + for k in 0..segs { + let (a, b) = (k, (k + 1) % n); + let c1 = [v[a][0] + o[a][0], v[a][1] + o[a][1]]; + let c2 = [v[b][0] + i[b][0], v[b][1] + i[b][1]]; + path.cmds.push(PathCmd::CubicTo(pt(c1), pt(c2), pt(v[b]))); + } + if closed { + path.cmds.push(PathCmd::Close); + } + path +} + +/// A group transform (`tr`) at `t`: T(p) · R(r) · R(−sa) · Shear(−tan sk) · R(sa) · S(s) · T(−a), +/// and its opacity. +fn transform(tr: &Value, t: f64) -> (Affine, f64) { + let get = |k: &str, d: &[f64]| if tr.get(k).is_some() { prop(&tr[k], t) } else { d.to_vec() }; + let (p, a, s) = (get("p", &[0.0, 0.0]), get("a", &[0.0, 0.0]), get("s", &[100.0, 100.0])); + let (r, sk, sa, o) = (get("r", &[0.0])[0], get("sk", &[0.0])[0], get("sa", &[0.0])[0], get("o", &[100.0])[0]); + let rot = |deg: f64| Affine::rotate(deg.to_radians() as f32); + let shear = Affine { m: [1.0, 0.0, -(sk.to_radians().tan()) as f32, 1.0, 0.0, 0.0] }; + let m = Affine::translate(p[0] as f32, p[1] as f32) + .mul(&rot(r)) + .mul(&rot(-sa)) + .mul(&shear) + .mul(&rot(sa)) + .mul(&Affine::scale((s[0] / 100.0) as f32, (s[1] / 100.0) as f32)) + .mul(&Affine::translate(-a[0] as f32, -a[1] as f32)); + (m, o / 100.0) +} + +fn item(path: Path, transform: Affine, fill: Option, stroke: Option, rule: FillRule) -> DisplayItem { + DisplayItem { + path: Arc::new(path), + transform, + fill, + stroke, + fill_rule: rule, + color: ColorTransform::IDENTITY, + layer: LayerId(0), + element: ElementId(0), + outline: None, + clip: None, + masks: None, + guide: false, + group: None, + image: None, + smooth: true, + warp: None, + } +} + +fn rgba(c: &[f64], alpha: f64) -> Rgba { + Rgba::new(c[0] as f32, c[1] as f32, c[2] as f32, alpha.clamp(0.0, 1.0) as f32) +} + +/// The items one shape group draws at `t`, bottom first, faded by `fade`. +fn group(g: &Value, t: f64, fade: f64, out: &mut Vec) { + let it = g["it"].as_array().unwrap(); + let tr = it.iter().find(|x| x["ty"] == "tr").unwrap(); + let (m, o) = transform(tr, t); + let fade = fade * o; + let mut path = Path::new(); + for sh in it.iter().filter(|x| x["ty"] == "sh") { + path.cmds.extend(path_of(&sh["ks"], t).cmds); + } + let rule = |x: &Value| if x["r"] == 2 { FillRule::EvenOdd } else { FillRule::NonZero }; + // Listed top first: the stroke (above) comes before the fill. + for x in it.iter().rev() { + match x["ty"].as_str().unwrap_or("") { + "fl" => { + let c = prop(&x["c"], t); + let o = prop(&x["o"], t)[0] / 100.0; + out.push(item(path.clone(), m, Some(Paint::Solid(rgba(&c, o * fade))), None, rule(x))); + } + "gf" => { + let (s, e) = (prop(&x["s"], t), prop(&x["e"], t)); + let count = x["g"]["p"].as_u64().unwrap() as usize; + let k = prop(&x["g"]["k"], t); + let o = prop(&x["o"], t)[0] / 100.0; + let stops: Vec = (0..count) + .map(|j| { + let c = &k[j * 4..j * 4 + 4]; + let a = k.get(count * 4 + j * 2 + 1).copied().unwrap_or(1.0); + GradientStop { offset: c[0] as f32, color: rgba(&c[1..], a * o * fade) } + }) + .collect(); + let (s, e) = (Vec2::new(s[0] as f32, s[1] as f32), Vec2::new(e[0] as f32, e[1] as f32)); + let paint = if x["t"] == 2 { Paint::radial(s, (e - s).length(), stops) } else { Paint::linear(s, e, stops) }; + out.push(item(path.clone(), m, Some(paint), None, rule(x))); + } + "st" => { + let d = m.decompose(); + assert!((d.sx.abs() - d.sy.abs()).abs() <= 1e-3 * d.sx.abs().max(1e-3) && d.skew.abs() < 1e-3, "a stroke under a stretched group: {:?}", m); + let c = prop(&x["c"], t); + let o = prop(&x["o"], t)[0] / 100.0; + let cap = match x["lc"].as_u64() { Some(1) => Cap::Butt, Some(3) => Cap::Square, _ => Cap::Round }; + let join = match x["lj"].as_u64() { Some(1) => Join::Miter, Some(3) => Join::Bevel, _ => Join::Round }; + let dash = x.get("d").and_then(Value::as_array).map(|d| { + let lengths: Vec = d.iter().filter(|e| e["n"] != "o").map(|e| prop(&e["v"], t)[0] as f32).collect(); + let offset = d.iter().find(|e| e["n"] == "o").map_or(0.0, |e| prop(&e["v"], t)[0] as f32); + Dash::Dashed { lengths: lengths.into(), offset } + }); + let style = StrokeStyle { cap, join, miter_limit: x["ml"].as_f64().unwrap_or(4.0) as f32, dash }; + let st = Stroke::new(rgba(&c, o * fade), prop(&x["w"], t)[0] as f32).with_style(style); + out.push(item(path.clone(), m, None, Some(st), FillRule::NonZero)); + } + _ => {} + } + } +} + +/// What a layer draws at `t`, bottom first. +fn layer_items(l: &Value, t: f64) -> Vec { + let mut out = Vec::new(); + match l["ty"].as_u64() { + Some(1) => { + let (w, h) = (l["sw"].as_f64().unwrap() as f32, l["sh"].as_f64().unwrap() as f32); + let c = Rgba::parse_hex(l["sc"].as_str().unwrap()).unwrap(); + out.push(item(Path::rect(0.0, 0.0, w, h), Affine::IDENTITY, Some(Paint::Solid(c)), None, FillRule::NonZero)); + } + Some(4) => { + for g in l["shapes"].as_array().unwrap().iter().rev() { + group(g, t, 1.0, &mut out); + } + } + _ => {} + } + out +} + +/// The animation at frame `t` as a display list (layer transforms are the identity, as +/// AniCraft writes them). +pub fn frame(anim: &Value, t: f64) -> DisplayList { + let mut dl = DisplayList::default(); + let layers = anim["layers"].as_array().unwrap(); + let shows = |l: &Value| l["ip"].as_f64().unwrap() <= t && t < l["op"].as_f64().unwrap(); + // Bottom first; a matte (`td`) is the layer just above the one that uses it (`tt`). + for (i, l) in layers.iter().enumerate().rev() { + if l["td"] == 1 || !shows(l) { + continue; + } + let mut items = layer_items(l, t); + if let Some(mode) = l["tt"].as_u64() { + let matte = &layers[i - 1]; + let c = dl.clip_parents.len() as u32; + dl.clip_parents.push(None); + dl.set_clip_mode(c, if mode == 3 { MaskMode::Luminance } else { MaskMode::Alpha }); + if shows(matte) { + for mut m in layer_items(matte, t) { + m.masks = Some(c); + dl.items.push(m); + } + } + for it in &mut items { + it.clip = Some(c); + } + } + if let Some(masks) = l["masksProperties"].as_array() { + let c = dl.clip_parents.len() as u32; + dl.clip_parents.push(None); + for m in masks { + assert_eq!(m["mode"], "a", "added masks only"); + let mut it = item(path_of(&m["pt"], t), Affine::IDENTITY, Some(Paint::Solid(Rgba::WHITE)), None, FillRule::NonZero); + it.masks = Some(c); + dl.items.push(it); + } + for it in &mut items { + assert!(it.clip.is_none(), "a mask and a matte on one layer"); + it.clip = Some(c); + } + } + dl.items.extend(items); + } + dl +} diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index 26fa9b41..c8956425 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -6,10 +6,15 @@ //! package's `golden/` folder. Probes then check, by hand-worked colours, what the golden //! should show. `UPDATE_GOLDENS=1` rewrites the goldens (see `golden/mod.rs`). //! +//! Each package also opens as a `.fla` archive, packed in every layout zip writers use, with +//! `file.open`, as the same document and the same golden frames (ADR 0054). +//! //! The report and structure of each package, and its hostile variants, are checked in the xfl //! crate (`crates/xfl/tests/corpus.rs`). mod golden; +#[path = "../../xfl/tests/support/fla.rs"] +mod pack; use anicraft_engine::Session; use anicraft_engine::doc::Document; @@ -24,18 +29,23 @@ fn corpus() -> PathBuf { /// The frames rendered for each package (frames count across scenes, from 0). const FRAMES: &[(&str, &[u32])] = &[ ("bitmaps", &[0]), + ("colour", &[0, 6, 12]), ("filters", &[0]), ("gradients", &[0]), ("guides", &[0, 6, 12]), ("interactive", &[0, 9]), ("masks", &[0]), + ("nineslice", &[0]), ("primitives", &[0]), ("scenes", &[0, 3, 7, 8, 10]), ("scripts", &[0, 4]), ("shapes", &[0]), + ("sounds", &[0]), ("symbols", &[0, 5]), ("text", &[0]), + ("textfields", &[0]), ("tweens", &[0, 6, 12]), + ("video", &[0]), ]; /// Render scale: the corpus stages are 320 × 180. @@ -51,6 +61,18 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("shapes", 0, 80.0, 30.0, 0x2B6CD9), ("shapes", 0, 95.0, 50.0, 0xF4F1EA), ("shapes", 0, 270.0, 60.0, 0xF29E1F), + // ADR 0086: the sounds package's artwork under its sound layers, on its own stage colour. + ("sounds", 0, 40.0, 60.0, 0x2A9D8F), + ("sounds", 0, 160.0, 90.0, 0xE9C46A), + ("sounds", 0, 10.0, 10.0, 0xF4F1EA), + // The Screen Video's first frame at 1.5 times (20..116 × 20..92), its quarters the right + // way up and round; the VP6 video draws nothing; the rectangle beside it. + ("video", 0, 35.0, 35.0, 0xE63946), + ("video", 0, 100.0, 35.0, 0x2A9D8F), + ("video", 0, 35.0, 80.0, 0x2646C8), + ("video", 0, 100.0, 80.0, 0xE9C46A), + ("video", 0, 200.0, 50.0, 0x264653), + ("video", 0, 10.0, 150.0, 0xFFFFFF), ("primitives", 0, 40.0, 50.0, 0xF2CC8F), ("primitives", 0, 210.0, 40.0, 0xE07A5F), ("primitives", 0, 6.0, 170.0, 0xFFFFFF), @@ -68,17 +90,47 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("symbols", 5, 130.0, 40.0, 0x457B9D), // The button's Up frame. ("symbols", 0, 82.0, 130.0, 0x2A9D8F), - // Brightness +60% and -50% of #6D597A. + // Brightness +60% and -50% of #6D597A; Advanced: red ×20 %, green +120, at 80 % over white. ("symbols", 0, 230.0, 130.0, 0xC5BDCA), ("symbols", 0, 260.0, 130.0, 0x372D3D), + ("symbols", 0, 290.0, 130.0, 0x44DA95), + // Colour effects on #2A9D8F (ADR 0056): None, Brightness +50 %, Tint 60 % #E9C46A, Advanced + // (red −100 % +255, green 50 %, blue −60), Alpha 25 % over white. + ("colour", 0, 30.0, 40.0, 0x2A9D8F), + ("colour", 0, 90.0, 40.0, 0x94CEC7), + ("colour", 0, 150.0, 40.0, 0x9DB479), + ("colour", 0, 210.0, 40.0, 0xD54F53), + ("colour", 0, 270.0, 40.0, 0xCAE6E3), + // Brightness −40 % around a 50 % red tint: both, exactly (not the stronger one alone). + ("colour", 0, 60.0, 110.0, 0x592F2B), + // Tint #264653 to Advanced: the ends, and halfway in the advanced space. + ("colour", 0, 160.0, 105.0, 0x264653), + ("colour", 6, 220.0, 105.0, 0x614771), + ("colour", 12, 280.0, 105.0, 0x944C8D), + // Brightness −100 % to +60 %: halfway is brightness −20 % (not the transforms' midpoint). + ("colour", 0, 160.0, 152.0, 0x000000), + ("colour", 6, 220.0, 152.0, 0x227E72), + ("colour", 12, 280.0, 152.0, 0xAAD8D2), ("tweens", 0, 20.0, 25.0, 0xF4A261), ("tweens", 12, 300.0, 25.0, 0xF4A261), + // Per-property custom eases (ADR 0081): halfway, position's three-segment curve has carried + // the ball past its end (x 180) to about 214; at the end it is there, half as big again. + ("tweens", 6, 214.0, 145.0, 0xF4A261), + ("tweens", 12, 180.0, 145.0, 0xF4A261), // Masked stripes: inside the spot, and outside it. ("masks", 0, 60.0, 22.0, 0x264653), ("masks", 0, 60.0, 27.0, 0xFFFFFF), ("masks", 0, 10.0, 22.0, 0xFFFFFF), ("masks", 0, 145.0, 10.0, 0xFFFFFF), ("masks", 0, 270.0, 70.0, 0xCB997E), + // 9-slice (ADR 0055): the stretched panel's top-left corner keeps its radius-10 curve (plain + // scaling would leave the background there), its middle is the panel, and the graphic inside + // it scales normally (a dot 2.8 times as wide). + ("nineslice", 0, 27.0, 113.0, 0x2A9D8F), + ("nineslice", 0, 137.0, 13.0, 0x2A9D8F), + ("nineslice", 0, 100.0, 125.0, 0x2A9D8F), + ("nineslice", 0, 151.0, 130.0, 0xE9C46A), + ("nineslice", 0, 21.0, 111.0, 0xF1FAEE), // Guide artwork never draws. ("guides", 0, 5.0, 5.0, 0xFFFFFF), ("guides", 0, 160.0, 60.0, 0xFFFFFF), @@ -93,6 +145,10 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[ ("scripts", 4, 160.0, 90.0, 0xE76F51), ("scripts", 4, 240.0, 90.0, 0xF4F1EA), ("text", 0, 300.0, 80.0, 0xE9EDC9), + // Fields draw their box (white behind a border) with no fonts at all (ADR 0066). + ("text", 0, 290.0, 134.0, 0xFFFFFF), + ("textfields", 0, 100.0, 30.0, 0xFFFFFF), + ("textfields", 0, 300.0, 170.0, 0xF4F1EA), ]; fn import(case: &str) -> Document { @@ -185,7 +241,7 @@ fn every_package_opens_with_file_open_and_round_trips_through_the_file_format() fn raw_shapes_open_raw_merged_and_unchanged_to_the_eye() { let mut failures = Vec::new(); let (mut raw_total, mut merged_total) = (0, 0); - for (case, frames) in FRAMES.iter().filter(|(c, _)| !matches!(*c, "text")) { + for (case, frames) in FRAMES.iter().filter(|(c, _)| !matches!(*c, "text" | "textfields")) { let mut s = Session::default(); let info = s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}")); let raw = s.doc.scenes.iter().flat_map(|sc| sc.timeline.layers.iter()).chain(s.doc.library.iter().flat_map(|sym| sym.timeline.layers.iter())).flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()).filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).count(); @@ -204,3 +260,114 @@ fn raw_shapes_open_raw_merged_and_unchanged_to_the_eye() { assert!(raw_total > 0 && merged_total > 0, "the corpus has raw shapes, merged: {raw_total} shapes, {merged_total} keyframes"); assert!(failures.is_empty(), "merged raw shapes look different:\n{}", failures.join("\n")); } + +/// Each package as a `.fla` file, in every zip layout (ADR 0054), opens with `file.open` as +/// the same document as its folder and renders the same golden frames. +#[test] +fn every_package_opens_from_a_fla_with_the_same_golden_frames() { + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-fla"); + std::fs::create_dir_all(&dir).unwrap(); + let mut failures = Vec::new(); + let mut checked = 0; + for (case, frames) in FRAMES { + let folder = corpus().join(case); + let mut s = Session::default(); + let want = s.execute("file.open", &json!({"path": folder.display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}")); + // Animate's own pointer file inside the folder opens it too. + let mut x = Session::default(); + x.execute("file.open", &json!({"path": folder.join(format!("{case}.xfl")).display().to_string()})).unwrap_or_else(|e| panic!("{case}.xfl: {e}")); + assert!(x.doc == s.doc, "{case}: the .xfl opens differently from its folder"); + let files = pack::package(&folder); + for (n, v) in pack::VARIANTS.iter().enumerate() { + let path = dir.join(format!("{case}-{n}.fla")); + std::fs::write(&path, pack::pack(&files, v)).unwrap(); + let mut t = Session::default(); + let got = t.execute("file.open", &json!({"path": path.display().to_string()})).unwrap_or_else(|e| panic!("{case}, {}: {e}", v.name)); + assert_eq!(got["report"], want["report"], "{case}, {}", v.name); + assert_eq!(got["named"], want["named"], "{case}, {}", v.name); + assert!(t.doc == s.doc, "{case}, {}: the .fla opens differently from the folder", v.name); + } + // The goldens (imported without fonts, as they were made), rendered from the .fla in + // its most unusual layout. + let fla = pack::pack(&files, &pack::VARIANTS[pack::VARIANTS.len() - 1]); + let (doc, _) = anicraft_xfl::import_fla_with_fonts(&fla, &Fonts::from_faces(Vec::new())).unwrap_or_else(|e| panic!("{case}: {e}")); + for &f in *frames { + let (w, h, rgba) = render(&doc, f); + let golden = corpus().join(case).join("golden").join(format!("frame-{f:03}.png")); + if let Err(e) = golden::compare(&golden, &format!("{case}-fla-frame-{f:03}"), w, h, &rgba, golden::DEFAULT) { + failures.push(e); + } + checked += 1; + } + } + assert!(failures.is_empty(), "{} of {checked} .fla frames differ from their goldens: +{}", failures.len(), failures.join(" +")); +} + +/// #226: each package as a `.fla` opens as the same document through every way in: File › Open, +/// the command line and a document the system hands over (all `file.open`), Open Recent and the +/// start screen's list (`file.open_recent`), a drop anywhere on the window (routed to +/// `file.open`), an upper-case extension, and a file a web browser hands over (`vfs`). +#[test] +fn every_entry_point_opens_the_corpus_as_a_fla() { + use anicraft_engine::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-entry-points"); + std::fs::create_dir_all(&dir).unwrap(); + for (case, _) in FRAMES { + let mut s = Session::default(); + s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}")); + let bytes = pack::pack(&pack::package(&corpus().join(case)), &pack::VARIANTS[0]); + let fla = dir.join(format!("{case}.fla")); + std::fs::write(&fla, &bytes).unwrap(); + let upper = dir.join(format!("{case} COPY.FLA")); + std::fs::write(&upper, &bytes).unwrap(); + let open = |path: &Path| { + let mut t = Session::default(); + t.execute("file.open", &json!({"path": path.display().to_string()})).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + t + }; + for path in [&fla, &upper] { + let t = open(path); + assert!(t.doc == s.doc, "{}: opens differently from its folder", path.display()); + assert!(t.path.is_none(), "{case}: imported untitled, so Save never writes over the Animate file"); + } + // Open Recent reopens the Animate file it imported. + let mut t = open(&fla); + t.execute("file.new", &json!({})).unwrap(); + t.execute("file.open_recent", &json!({"index": 0, "confirm": true})).unwrap_or_else(|e| panic!("{case}: Open Recent: {e}")); + assert!(t.doc == s.doc, "{case}: Open Recent opens it the same"); + // A drop anywhere opens it. + for path in [&fla, &upper] { + assert_eq!(kind_of(path), DropKind::Document, "{}", path.display()); + for target in [DropTarget::Stage, DropTarget::Timeline, DropTarget::Library, DropTarget::Window] { + assert_eq!(route(kind_of(path), target), DropAction::Open, "{case} on {target:?}"); + } + } + // In a browser the file arrives in memory, on the thread that opens it (ADR 0036). + let (name, data, want) = (format!("{case}.fla"), bytes.clone(), s.doc.clone()); + std::thread::spawn(move || { + anicraft_engine::vfs::use_memory(); + anicraft_engine::vfs::put(Path::new(&name), data).unwrap(); + let mut w = Session::default(); + w.execute("file.open", &json!({"path": name})).unwrap_or_else(|e| panic!("{name} in a browser: {e}")); + assert!(w.doc == want, "{name}: opens differently in a browser"); + }) + .join() + .unwrap(); + } +} + +/// ADR 0086: opening a document headless (the CLI and MCP) says which sounds and videos didn't +/// come across, by name, and the sounds that did are in the Library with their waveforms. +#[test] +fn file_open_names_the_sounds_and_videos_that_did_not_come_across() { + let mut s = Session::default(); + let got = s.execute("file.open", &json!({"path": corpus().join("sounds").display().to_string()})).unwrap(); + assert_eq!(got["named"]["missing sound files"], json!(["lost.wav"])); + assert!(got["report"].as_str().unwrap().contains("2 sounds in formats AniCraft can't decode (theme.aif: AIFF; Sounds/loop: Animate's own sound data)"), "{}", got["report"]); + assert_eq!(s.doc.sounds.len(), 3); + assert!(s.doc.sounds.iter().all(|x| x.decoded().is_some_and(|d| d.pcm.frames() > 0)), "waveforms ready to draw"); + let got = s.execute("file.open", &json!({"path": corpus().join("video").display().to_string(), "confirm": true})).unwrap(); + assert_eq!(got["named"]["videos AniCraft can't play"], json!(["intro.flv: FLV, On2 VP6, 4.5 s", "gone.mp4: its file is missing, 1.0 s"])); +} diff --git a/crates/geom/src/brush.rs b/crates/geom/src/brush.rs index a4fd2d3d..354f8d5e 100644 --- a/crates/geom/src/brush.rs +++ b/crates/geom/src/brush.rs @@ -21,6 +21,13 @@ //! //! The result is closed loops (outer boundaries and holes) filled with the even-odd rule. The //! grid has at most `MAX_CELLS` cells, so cost and memory are bounded for any input. +//! +//! **Tilt** (ADR 0093) turns the tip with the pen's azimuth and widens it as the pen leans. +//! When the tip turns along a stroke there is no one tip space, so the field is sampled in stage +//! space (in tip radii) instead, and each short piece of the stroke measures its distance in its +//! own tip space. **Texture** opens a paper grain of holes in the paint, and **scatter** throws +//! the dabs either side of the line: both are fixed patterns, so the same stroke always gives +//! the same outline, and both are still vector outlines. use crate::{Affine, Path, PathCmd, Vec2, fit_curve, trace}; @@ -64,11 +71,66 @@ impl Tip { } } -/// One pointer sample: where, and the pen pressure (0..1; a mouse gives 1). +/// One pointer sample: where, the pen pressure (0..1; a mouse gives 1) and the pen's tilt +/// where the system reports it. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Sample { pub at: Vec2, pub pressure: f32, + pub tilt: Option, +} + +impl Sample { + /// A sample with no tilt. + pub fn new(at: Vec2, pressure: f32) -> Sample { + Sample { at, pressure, tilt: None } + } +} + +/// A pen's tilt, as the W3C Pointer Events spec gives it (in degrees): `altitude` from 90 +/// (upright) to 0 (lying on the tablet), and `azimuth`, the direction the pen leans toward on +/// the stage, clockwise from the +x axis. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tilt { + pub altitude: f32, + pub azimuth: f32, +} + +impl Tilt { + /// How far the pen leans: 0 upright, 1 flat (`1 − altitude / 90°`). + pub fn lean(self) -> f32 { + let a = if self.altitude.is_finite() { self.altitude.clamp(0.0, 90.0) } else { 90.0 }; + 1.0 - a / 90.0 + } + /// The lean as a vector toward the azimuth (length [`Tilt::lean`]), which blends smoothly + /// between samples and through upright. + fn vector(self) -> Vec2 { + let az = if self.azimuth.is_finite() { self.azimuth.rem_euclid(360.0).to_radians() } else { 0.0 }; + Vec2::new(az.cos(), az.sin()) * self.lean() + } +} + +/// What a pen's tilt shapes (Animate's tilt option). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TiltResponse { + /// The tip turns with the pen: its angle is the brush's angle plus the azimuth. + pub angle: bool, + /// The tip widens as the pen leans: by `1 + TILT_WIDTH × lean`. + pub width: bool, +} + +/// How much wider a flat pen paints than an upright one, as a part of the size. +pub const TILT_WIDTH: f32 = 1.0; +/// Below this lean the azimuth is too noisy to turn the tip by. +const MIN_LEAN: f32 = 0.02; + +/// The tip's angle (degrees) and size factor when the pen leans by `lean` (a vector toward the +/// azimuth, length 0..1), for a brush at `angle` (ADR 0093). Analytic: the angle is `angle + +/// azimuth`, and the size factor `1 + TILT_WIDTH × |lean|`. +pub fn tilted(angle: f32, lean: Vec2, response: TiltResponse) -> (f32, f32) { + let l = if lean.is_finite() { lean.length().min(1.0) } else { 0.0 }; + let turned = if response.angle && l >= MIN_LEAN { angle + lean.y.atan2(lean.x).to_degrees() } else { angle }; + (turned, if response.width { 1.0 + TILT_WIDTH * l } else { 1.0 }) } /// The tip's size factor at `pressure`: from `MIN_PRESSURE_SIZE` at none to 1 at full. @@ -77,26 +139,127 @@ pub fn size_factor(pressure: f32) -> f32 { MIN_PRESSURE_SIZE + (1.0 - MIN_PRESSURE_SIZE) * p } +/// How a stroke is shaped beyond its tip (ADR 0068): tapered ends, separate dabs and a ragged +/// edge. The default shapes nothing (ADR 0033's plain sweep). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Shaping { + /// The part of the stroke's length (`0..=0.5`) over which it swells from a point at its + /// start, and thins to a point at its end. + pub taper_start: f32, + pub taper_end: f32, + /// `0`: one continuous sweep. Otherwise the tip is stamped as separate dabs this far apart, + /// as a multiple of its size (`0.05..=10`). + pub spacing: f32, + /// How far the edge is worn away, as a part of the tip's size (`0..=0.5`): a chalk-like + /// ragged edge from a fixed noise pattern, so it is the same every time. + pub jitter: f32, + /// A paper grain of holes through the paint (`0..=1`: none to most of it), fixed on the + /// stage and scaled to the tip's size, as dry media on rough paper (ADR 0093). + pub texture: f32, + /// Dabs thrown either side of the line, up to this many sizes away (`0..=2`), and varied in + /// size: spatter and stipple. A continuous stroke scatters as dabs a quarter size apart. + pub scatter: f32, + /// What the pen's tilt shapes. + pub tilt: TiltResponse, +} + +/// Most dabs one stroke stamps (the spacing widens past it). +pub const MAX_DABS: usize = 20_000; +/// Thinnest a taper makes the tip, as a part of its size. +const TAPER_TIP: f32 = 0.05; +/// Dab spacing of a scattered stroke that has none of its own, as a part of the size. +const SCATTER_SPACING: f32 = 0.25; + +impl Shaping { + /// The values clamped to their ranges (not a number reads as none). + pub fn sanitized(self) -> Shaping { + let c = |v: f32, hi: f32| if v.is_finite() { v.clamp(0.0, hi) } else { 0.0 }; + let spacing = c(self.spacing, 10.0); + Shaping { + taper_start: c(self.taper_start, 0.5), + taper_end: c(self.taper_end, 0.5), + spacing: if spacing > 0.0 { spacing.max(0.05) } else { 0.0 }, + jitter: c(self.jitter, 0.5), + texture: c(self.texture, 1.0), + scatter: c(self.scatter, 2.0), + tilt: self.tilt, + } + } + + /// The dab spacing a stroke stamps at (scatter needs dabs). + fn dab_spacing(&self) -> f32 { + if self.spacing <= 0.0 && self.scatter > 0.0 { SCATTER_SPACING } else { self.spacing } + } + + /// The tapers' factor at fraction `u` of the stroke's length. + pub fn taper(&self, u: f32) -> f32 { + let ease = |x: f32| { + let x = x.clamp(0.0, 1.0); + x * (2.0 - x) + }; + let mut f: f32 = 1.0; + if self.taper_start > 1e-4 { + f = f.min(ease(u / self.taper_start)); + } + if self.taper_end > 1e-4 { + f = f.min(ease((1.0 - u) / self.taper_end)); + } + TAPER_TIP + (1.0 - TAPER_TIP) * f + } +} + /// The smoothed centre line: points with the tip's size factor at each. `smoothing` is the /// curve fit's tolerance (stage units); `flatness` how closely the points follow the fitted /// curves. One distinct sample gives one point (a dab). pub fn centreline(samples: &[Sample], smoothing: f32, flatness: f32) -> Vec<(Vec2, f32)> { + centreline_shaped(samples, smoothing, flatness, &Shaping::default()) +} + +/// The centre line with the shaping's tapers applied to the size factors (and the tilt's +/// widening, when the shaping says tilt shapes the width). +pub fn centreline_shaped(samples: &[Sample], smoothing: f32, flatness: f32, shaping: &Shaping) -> Vec<(Vec2, f32)> { + centre_points(samples, smoothing, flatness, shaping).into_iter().map(|p| (p.at, p.f)).collect() +} + +/// A point of the centre line: where, the tip's size factor, and the pen's lean there (a vector +/// toward the azimuth, zero without tilt). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Pt { + at: Vec2, + f: f32, + lean: Vec2, +} + +impl Pt { + fn lerp(self, o: Pt, t: f32) -> Pt { + Pt { at: self.at.lerp(o.at, t), f: self.f + (o.f - self.f) * t, lean: self.lean.lerp(o.lean, t) } + } +} + +fn centre_points(samples: &[Sample], smoothing: f32, flatness: f32, shaping: &Shaping) -> Vec { + let shaping = shaping.sanitized(); let mut pts: Vec = Vec::with_capacity(samples.len().min(MAX_SAMPLES)); let mut press: Vec = Vec::with_capacity(pts.capacity()); + let mut leans: Vec = Vec::with_capacity(pts.capacity()); + let lean_of = |s: &Sample| s.tilt.map_or(Vec2::ZERO, Tilt::vector); for s in samples.iter().take(MAX_SAMPLES).filter(|s| s.at.is_finite()) { if pts.last().is_some_and(|l| l.distance(s.at) <= 1e-4) { - // A held pointer: keep the latest pressure. - if let Some(p) = press.last_mut() { + // A held pointer: keep the latest pressure and tilt. + if let (Some(p), Some(l)) = (press.last_mut(), leans.last_mut()) { *p = size_factor(s.pressure); + *l = lean_of(s); } continue; } pts.push(s.at); press.push(size_factor(s.pressure)); + leans.push(lean_of(s)); } - match (pts.as_slice(), press.as_slice()) { - ([], _) => return Vec::new(), - ([p], [f, ..]) => return vec![(*p, *f)], + // The tilt's widening multiplies the size factor (ADR 0093). + let widen = |f: f32, lean: Vec2| f * tilted(0.0, lean, TiltResponse { angle: false, width: shaping.tilt.width }).1; + match (pts.as_slice(), press.as_slice(), leans.as_slice()) { + ([], _, _) => return Vec::new(), + ([p], [f, ..], [l, ..]) => return vec![Pt { at: *p, f: widen(*f, *l), lean: *l }], _ => {} } let tol = if smoothing.is_finite() && smoothing > 0.01 { smoothing } else { 0.01 }; @@ -118,6 +281,8 @@ pub fn centreline(samples: &[Sample], smoothing: f32, flatness: f32) -> Vec<(Vec acc.iter_mut().for_each(|a| *a /= total); acc }; + // A taper needs points along the line to follow it (a straight drag flattens to two). + let line = if shaping.taper_start > 0.0 || shaping.taper_end > 0.0 { subdivide(&line, 96) } else { line }; let (src, dst) = (along(&pts), along(&line)); let mut j = 0; line.iter() @@ -128,29 +293,137 @@ pub fn centreline(samples: &[Sample], smoothing: f32, flatness: f32) -> Vec<(Vec } let (s0, s1) = (src.get(j).copied().unwrap_or(0.0), src.get(j + 1).copied().unwrap_or(1.0)); let (f0, f1) = (press.get(j).copied().unwrap_or(1.0), press.get(j + 1).copied().or(press.get(j).copied()).unwrap_or(1.0)); + let (l0, l1) = (leans.get(j).copied().unwrap_or(Vec2::ZERO), leans.get(j + 1).copied().or(leans.get(j).copied()).unwrap_or(Vec2::ZERO)); let t = if s1 - s0 > 1e-9 { ((u - s0) / (s1 - s0)).clamp(0.0, 1.0) } else { 0.0 }; - (*p, f0 + (f1 - f0) * t) + let lean = l0.lerp(l1, t); + Pt { at: *p, f: widen((f0 + (f1 - f0) * t) * shaping.taper(u), lean), lean } }) .collect() } +/// The polyline with no piece longer than a `n`th of its length (at most `n` points added). +fn subdivide(line: &[Vec2], n: usize) -> Vec { + let total: f32 = line.windows(2).map(|w| if let [a, b] = w { a.distance(*b) } else { 0.0 }).sum(); + let piece = total / n.max(1) as f32; + if !(piece.is_finite() && piece > 1e-6) { + return line.to_vec(); + } + let mut out = Vec::with_capacity(line.len() + n + 1); + out.extend(line.first().copied()); + for w in line.windows(2) { + let &[a, b] = w else { continue }; + let k = (a.distance(b) / piece).ceil().clamp(1.0, n as f32 + 1.0) as usize; + out.extend((1..=k).map(|i| a.lerp(b, i as f32 / k as f32))); + } + out +} + +/// The Paint Brush's line (ADR 0068): the smoothed centre line as an open path, and the tip's +/// size factor along it as `(fraction of length, factor)` at `max` (2..) evenly spaced places. +/// An empty path when the samples don't make a line (one point, or none finite). +pub fn centre_stroke(samples: &[Sample], shaping: &Shaping, smoothing: f32, flatness: f32, max: usize) -> (Path, Vec<(f32, f32)>) { + let line = centreline_shaped(samples, smoothing, flatness, shaping); + if line.len() < 2 { + return (Path::new(), Vec::new()); + } + let pts: Vec = line.iter().map(|(p, _)| *p).collect(); + let tol = if smoothing.is_finite() && smoothing > 0.01 { smoothing.min(flatness.max(0.05) * 4.0) } else { 0.05 }; + let path = fit_curve(&pts, tol, tol * 2.0, false); + let mut along = Vec::with_capacity(line.len()); + let mut d = 0.0; + for w in line.windows(2) { + if let [a, b] = w { + along.push(d); + d += a.0.distance(b.0); + } + } + along.push(d); + let total = d.max(1e-9); + let n = max.clamp(2, 1000); + let mut j = 0; + let profile = (0..n) + .map(|i| { + let u = i as f32 / (n - 1) as f32; + let at = u * total; + while j + 2 < along.len() && along.get(j + 1).is_some_and(|a| *a < at) { + j += 1; + } + let (a0, a1) = (along.get(j).copied().unwrap_or(0.0), along.get(j + 1).copied().unwrap_or(total)); + let (f0, f1) = (line.get(j).map_or(1.0, |l| l.1), line.get(j + 1).map_or(1.0, |l| l.1)); + let t = if a1 - a0 > 1e-9 { ((at - a0) / (a1 - a0)).clamp(0.0, 1.0) } else { 0.0 }; + (u, f0 + (f1 - f0) * t) + }) + .collect(); + (path, profile) +} + +/// Dabs every `step` stage units along a centre line (the first point always), with the size +/// factor where each falls. At most [`MAX_DABS`]: a longer line spaces them wider. +pub fn dabs(line: &[(Vec2, f32)], step: f32) -> Vec<(Vec2, f32)> { + let pts: Vec = line.iter().map(|&(at, f)| Pt { at, f, lean: Vec2::ZERO }).collect(); + dab_points(&pts, step).into_iter().map(|(p, _)| (p.at, p.f)).collect() +} + +/// [`dabs`] over centre-line points, each with the line's direction there. +fn dab_points(line: &[Pt], step: f32) -> Vec<(Pt, Vec2)> { + let total: f32 = line.windows(2).map(|w| if let [a, b] = w { a.at.distance(b.at) } else { 0.0 }).sum(); + let dir0 = line.windows(2).find_map(|w| if let [a, b] = w { Some((b.at - a.at).normalized()).filter(|d| d.is_finite() && d.length() > 0.5) } else { None }).unwrap_or(Vec2::new(1.0, 0.0)); + let mut out: Vec<(Pt, Vec2)> = line.first().copied().map(|p| (p, dir0)).into_iter().collect(); + if !(step.is_finite() && step > 1e-3) { + return out; + } + let step = step.max(total / MAX_DABS as f32); + let mut next = step; + let mut walked = 0.0; + for w in line.windows(2) { + let &[a, b] = w else { continue }; + let l = a.at.distance(b.at); + let dir = if l > 1e-9 { (b.at - a.at) * (1.0 / l) } else { dir0 }; + while next <= walked + l && out.len() < MAX_DABS { + let t = if l > 1e-9 { (next - walked) / l } else { 0.0 }; + out.push((a.lerp(b, t), dir)); + next += step; + } + walked += l; + } + out +} + /// The filled outline of a brush stroke: closed loops (even-odd), or an empty path when there /// is nothing to paint (no finite samples, a zero-size tip, or a stroke too large to resolve). /// `smoothing` is the centre line's curve-fit tolerance and `tolerance` the outline's (both in /// stage units). pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> Path { + outline_shaped(samples, tip, &Shaping::default(), smoothing, tolerance) +} + +/// The outline with tapers, dabs, a ragged edge, texture, scatter or tilt (ADR 0068, 0093). +pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothing: f32, tolerance: f32) -> Path { + let shaping = shaping.sanitized(); let tol = if tolerance.is_finite() && tolerance > 1e-3 { tolerance } else { 0.25 }; - let line = centreline(samples, smoothing, tol * 0.25); - let m = tip.to_stage(); - let Some(inv) = m.inverse().filter(|i| i.is_finite()) else { return Path::new() }; + let mut line = centre_points(samples, smoothing, tol * 0.25, &shaping); + let spacing = shaping.dab_spacing(); + let dabbed = spacing > 0.0 && line.len() > 1; + if dabbed { + line = scattered(dab_points(&line, spacing * tip.size), shaping.scatter * tip.size); + } if line.is_empty() || !(tip.size.is_finite() && tip.size > 0.0) { return Path::new(); } - // Tip space, in f64. - let q: Vec<(P, f64)> = line.iter().map(|(p, f)| (v64(inv.apply(*p)), f64::from(*f))).collect(); + // The tip's angle at each point: the brush's, turned by the pen's azimuth (ADR 0093). + let angles: Vec = line.iter().map(|p| tilted(tip.angle, p.lean, TiltResponse { angle: shaping.tilt.angle, width: false }).0).collect(); + let turns = angles.iter().any(|a| (a - tip.angle).abs() > 1e-3); + let round = if tip.roundness.is_finite() { f64::from(tip.roundness.clamp(0.05, 1.0)) } else { 1.0 }; + let half = if tip.size.is_finite() { tip.size.max(0.0) * 0.5 } else { 0.0 }; + // The grid's space: the tip's own, or (when the tip turns) the stage in tip radii, where + // each piece measures in its own tip space. + let m = if turns { Affine::scale(half, half) } else { tip.to_stage() }; + let Some(inv) = m.inverse().filter(|i| i.is_finite()) else { return Path::new() }; + // Grid space, in f64, with each point's tip angle (radians). + let q: Vec<(P, f64, f64)> = line.iter().zip(&angles).map(|(p, a)| (v64(inv.apply(p.at)), f64::from(p.f), f64::from(*a).to_radians())).collect(); let (mut lo, mut hi) = ((f64::INFINITY, f64::INFINITY), (f64::NEG_INFINITY, f64::NEG_INFINITY)); let mut fmin: f64 = 1.0; - for (p, f) in &q { + for (p, f, _) in &q { lo = (lo.0.min(p.0 - f), lo.1.min(p.1 - f)); hi = (hi.0.max(p.0 + f), hi.1.max(p.1 + f)); fmin = fmin.min(*f); @@ -164,7 +437,12 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> TipShape::Round => 1.0 / 6.0, TipShape::Square => 1.0 / 8.0, }; - let mut c: f64 = (fmin / 2.5).min(fine); + // A ragged edge needs cells finer than its grain, and the paper grain finer still. + let fine: f64 = if shaping.jitter > 0.0 { f64::min(fine, 1.0 / 14.0) } else { fine }; + let fine: f64 = if shaping.texture > 0.0 { f64::min(fine, 1.0 / 18.0) } else { fine }; + // In stage space the tip's narrow side is `round` radii across. + let narrow = if turns { round } else { 1.0 }; + let mut c: f64 = (fmin / 2.5).min(fine) * narrow; for _ in 0..4 { let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0); if cells <= MAX_CELLS as f64 { @@ -180,9 +458,16 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> } let (w, h) = (w as usize, h as usize); let mut field = vec![OUTSIDE as f32; w * h]; + // How deep the ragged edge wears in, in cells (the tip's radius is 1, its size 2); the + // field inside reaches that much deeper, so the wear never opens holes in the middle. + let wear = f64::from(shaping.jitter) * 2.0 / c; + let top = 1.0 + MARGIN + wear; // Nothing thinner than a cell, so no part slips between the samples. - let pts: Vec<(P, f64)> = thin(&q, c * 0.5).into_iter().map(|(p, f)| (p, f.max(c))).collect(); - let mut stamp = |a: P, ra: f64, b: P, rb: f64| { + let pts: Vec<(P, f64, f64)> = thin(&q, c * 0.5).into_iter().map(|(p, f, a)| (p, f.max(c / narrow), a)).collect(); + // A piece's frame when the tip turns: grid space to its tip space is a turn by −angle and + // a stretch of the narrow side. A distance there times `round` is at most the distance in + // the grid, with the same zero level. + let mut stamp = |a: P, ra: f64, b: P, rb: f64, turn: Option<(f64, f64)>| { let reach = ra.max(rb) + (MARGIN - 1.0) * c; let (x0, x1) = (((a.0.min(b.0) - reach - origin.0) / c).floor().max(0.0), ((a.0.max(b.0) + reach - origin.0) / c).ceil()); let (y0, y1) = (((a.1.min(b.1) - reach - origin.1) / c).floor().max(0.0), ((a.1.max(b.1) + reach - origin.1) / c).ceil()); @@ -190,15 +475,22 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> if x1 < x0 || y1 < y0 { return; } + let to_tip = |p: P| match turn { + Some((cs, sn)) => (p.0 * cs + p.1 * sn, (-p.0 * sn + p.1 * cs) / round), + None => p, + }; + let scale = if turn.is_some() { round } else { 1.0 }; + let (ta, tb) = (to_tip(a), to_tip(b)); for y in y0 as usize..=y1 as usize { let py = origin.1 + (y as f64 + 0.5) * c; for x in x0 as usize..=x1 as usize { let px = origin.0 + (x as f64 + 0.5) * c; + let tx = to_tip((px, py)); let d = match tip.shape { - TipShape::Round => round_dist((px, py), a, ra, b, rb), - TipShape::Square => square_dist((px, py), a, ra, b, rb), - }; - let v = (0.5 - d / c).clamp(OUTSIDE, 1.0 + MARGIN) as f32; + TipShape::Round => round_dist(tx, ta, ra, tb, rb), + TipShape::Square => square_dist(tx, ta, ra, tb, rb), + } * scale; + let v = (0.5 - d / c).clamp(OUTSIDE, top) as f32; if let Some(cell) = field.get_mut(y * w + x) && v > *cell { @@ -207,21 +499,59 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> } } }; + let turn_at = |a: f64| turns.then(|| (a.cos(), a.sin())); match pts.as_slice() { - [(p, f)] => stamp(*p, *f, *p, *f), + [(p, f, a)] => stamp(*p, *f, *p, *f, turn_at(*a)), + _ if dabbed => pts.iter().for_each(|(p, f, a)| stamp(*p, *f, *p, *f, turn_at(*a))), _ => { for pair in pts.windows(2) { - let &[(a, ra), (b, rb)] = pair else { continue }; + let &[(a, ra, aa), (b, rb, ab)] = pair else { continue }; // Long segments in short pieces, so each one's bounds stay small (the pieces' - // sweeps are the segment's). - let n = (dist(a, b) / PIECE.max(16.0 * c)).ceil().clamp(1.0, 1e6) as usize; + // sweeps are the segment's); a turning tip turns at most 3° a piece. + let n = (dist(a, b) / PIECE.max(16.0 * c)).ceil().clamp(1.0, 1e6); + let da = half_turn(ab - aa); + let n = if turns { n.max((da.abs() / 3f64.to_radians()).ceil()).min(1e6) } else { n } as usize; for i in 0..n { let (t0, t1) = (i as f64 / n as f64, (i + 1) as f64 / n as f64); - stamp(lerp(a, b, t0), ra + (rb - ra) * t0, lerp(a, b, t1), ra + (rb - ra) * t1); + let mid = aa + da * (t0 + t1) * 0.5; + stamp(lerp(a, b, t0), ra + (rb - ra) * t0, lerp(a, b, t1), ra + (rb - ra) * t1, turn_at(mid)); } } } } + if wear > 0.0 { + // Wear the edge by a fixed noise pattern in tip space (so the grain stays put however + // the stroke runs): the field is a distance, so lowering it by `wear × n` moves the + // edge in by that much. + for (i, v) in field.iter_mut().enumerate() { + if *v <= OUTSIDE as f32 { + continue; + } + let (x, y) = ((i % w) as f64, (i / w) as f64); + *v -= (wear * grain((origin.0 + (x + 0.5) * c, origin.1 + (y + 0.5) * c))) as f32; + } + } + if shaping.texture > 0.0 { + // The paper grain: where a fixed noise on the stage (in tip radii, so it scales with + // the brush) falls below the threshold, the paint has a hole. The noise's slope is about + // one per grain, so `(n − τ) × grain` is roughly a distance, which is all the tracing's + // interpolation needs. + let tau = 0.2 + 0.4 * f64::from(shaping.texture); + let unit = 1.0 / f64::from(half).max(1e-9); + let grain_cells = PAPER / c; + for (i, v) in field.iter_mut().enumerate() { + if *v <= 0.0 { + continue; + } + let (x, y) = ((i % w) as f64, (i / w) as f64); + let st = m.apply(Vec2::new((origin.0 + (x + 0.5) * c) as f32, (origin.1 + (y + 0.5) * c) as f32)); + let n = paper((f64::from(st.x) * unit, f64::from(st.y) * unit)); + let hole = ((n - tau) * grain_cells) as f32; + if hole < *v { + *v = hole; + } + } + } let to_stage = |p: Vec2| m.apply(Vec2::new((origin.0 + f64::from(p.x) * c) as f32, (origin.1 + f64::from(p.y) * c) as f32)); // A corner is a turn of 60° over the window either side. Round tips: two cells (their // tightest curve is 2.5 cells, too gentle to count). Square tips: four, so a corner the @@ -233,7 +563,7 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> }; let window = (cells * cell_stage).max(tol * 2.0); let mut out = Path::new(); - for lp in trace::contours(&field, w, h) { + for lp in trace::contours(&field, w, h).into_iter().take(MAX_LOOPS) { let stage: Vec = lp.into_iter().map(to_stage).collect(); let part = fit_curve(&stage, tol, window, true); if part.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) { @@ -243,6 +573,50 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) -> out } +/// Most loops one outline keeps (a fine paper grain on a long stroke opens many holes). +pub const MAX_LOOPS: usize = 20_000; +/// The paper grain's size, in tip radii. +const PAPER: f64 = 0.35; + +/// An angle difference (radians) as the shortest turn of a tip that looks the same turned +/// half way round: in `-π/2..=π/2`. +fn half_turn(d: f64) -> f64 { + let pi = std::f64::consts::PI; + let d = d.rem_euclid(pi); + if d > pi * 0.5 { d - pi } else { d } +} + +/// Dabs thrown up to `reach` either side of the line, and varied from 60 to 100 % in size, by +/// a fixed hash of each dab's number (so the same stroke scatters the same way). +fn scattered(dabs: Vec<(Pt, Vec2)>, reach: f32) -> Vec { + if !(reach.is_finite() && reach > 0.0) { + return dabs.into_iter().map(|(p, _)| p).collect(); + } + dabs.into_iter() + .enumerate() + .map(|(i, (p, dir))| { + let (u, v) = (unit_hash(i as u64, 1), unit_hash(i as u64, 2)); + let side = Vec2::new(-dir.y, dir.x) * ((u as f32 * 2.0 - 1.0) * reach); + Pt { at: p.at + side, f: p.f * (0.6 + 0.4 * v as f32), lean: p.lean } + }) + .collect() +} + +/// A number in `0..1` from `(i, k)`, the same on every platform (SplitMix64's finaliser). +fn unit_hash(i: u64, k: u64) -> f64 { + let mut z = i.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ k.wrapping_mul(0xD1B5_4A32_D192_ED03); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + (z >> 11) as f64 / (1u64 << 53) as f64 +} + +/// The paper grain: value noise in `0..1`, two octaves ([`PAPER`] and 0.4 of it), on lattice +/// rows of its own (apart from the ragged edge's). +fn paper(p: P) -> f64 { + grain_octaves(p, PAPER, PAPER * 0.4, 7) +} + type P = (f64, f64); /// Cells of free margin round the sweep (the field is sampled this far out). @@ -262,18 +636,49 @@ fn lerp(a: P, b: P, t: f64) -> P { (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t) } +/// Smooth value noise in `0..1` from a fixed integer hash: two octaves, 0.5 and 0.2 tip units +/// across. The same point always gives the same value, on every platform. +fn grain(p: P) -> f64 { + grain_octaves(p, 0.5, 0.2, 0) +} + +/// Two octaves of value noise (`big` and `small` across, the big one weighted twice) on lattice +/// rows from `layer`: each octave reads rows of its own (`layer` shifts them far apart), so the +/// octaves are independent. +fn grain_octaves(p: P, big: f64, small: f64, layer: i64) -> f64 { + fn hash(x: i64, y: i64) -> f64 { + // SplitMix64's finaliser over the lattice point. + let mut z = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + (z >> 11) as f64 / (1u64 << 53) as f64 + } + fn octave(p: P, size: f64, layer: i64) -> f64 { + let (u, v) = (p.0 / size, p.1 / size); + let (x0, y0) = (u.floor(), v.floor()); + let s = |t: f64| t * t * (3.0 - 2.0 * t); + let (sx, sy) = (s(u - x0), s(v - y0)); + let (xi, yi) = (x0.clamp(-1e15, 1e15) as i64, (y0.clamp(-1e15, 1e15) as i64).wrapping_add(layer << 52)); + let top = hash(xi, yi) + (hash(xi + 1, yi) - hash(xi, yi)) * sx; + let bottom = hash(xi, yi + 1) + (hash(xi + 1, yi + 1) - hash(xi, yi + 1)) * sx; + top + (bottom - top) * sy + } + (octave(p, big, layer) * 2.0 + octave(p, small, layer + 1)) / 3.0 +} + /// Drops points closer than `gap` to the last kept one (the last point always stays). -fn thin(q: &[(P, f64)], gap: f64) -> Vec<(P, f64)> { - let mut out: Vec<(P, f64)> = Vec::with_capacity(q.len()); - for (i, &(p, f)) in q.iter().enumerate() { +fn thin(q: &[(P, f64, f64)], gap: f64) -> Vec<(P, f64, f64)> { + let mut out: Vec<(P, f64, f64)> = Vec::with_capacity(q.len()); + for (i, &(p, f, a)) in q.iter().enumerate() { let last = i + 1 == q.len(); match out.last_mut() { - Some((l, lf)) if dist(*l, p) < gap => { + Some((l, lf, la)) if dist(*l, p) < gap => { if last { - (*l, *lf) = (p, f); + (*l, *lf, *la) = (p, f, a); } } - _ => out.push((p, f)), + _ => out.push((p, f, a)), } } out @@ -331,7 +736,7 @@ mod tests { use crate::FillRule; fn line(a: Vec2, b: Vec2, n: usize, pressure: impl Fn(f32) -> f32) -> Vec { - (0..=n).map(|i| i as f32 / n as f32).map(|t| Sample { at: a.lerp(b, t), pressure: pressure(t) }).collect() + (0..=n).map(|i| i as f32 / n as f32).map(|t| Sample::new(a.lerp(b, t), pressure(t))).collect() } /// Area of an even-odd path (flattened finely). @@ -365,12 +770,12 @@ mod tests { #[test] fn a_dab_is_the_tip() { - let p = outline(&[Sample { at: Vec2::new(10.0, 10.0), pressure: 1.0 }], &Tip::round(8.0), 1.0, 0.05); + let p = outline(&[Sample::new(Vec2::new(10.0, 10.0), 1.0)], &Tip::round(8.0), 1.0, 0.05); let want = std::f32::consts::PI * 16.0; assert!((area(&p) - want).abs() / want < 0.01, "{}", area(&p)); // A square tip at 45°: a diamond of the same area as the square. let tip = Tip { shape: TipShape::Square, size: 10.0, angle: 45.0, roundness: 1.0 }; - let d = outline(&[Sample { at: Vec2::ZERO, pressure: 1.0 }], &tip, 1.0, 0.05); + let d = outline(&[Sample::new(Vec2::ZERO, 1.0)], &tip, 1.0, 0.05); assert!((area(&d) - 100.0).abs() < 2.0, "{}", area(&d)); assert!(d.contains(Vec2::new(0.0, 6.8), &Affine::IDENTITY, FillRule::EvenOdd), "a corner points down"); assert!(!d.contains(Vec2::new(4.6, 4.6), &Affine::IDENTITY, FillRule::EvenOdd), "an unturned square's corner is outside"); @@ -391,7 +796,7 @@ mod tests { #[test] fn smoothing_reduces_anchors() { // A shaky hand: a straight drag with jitter. - let s: Vec = (0..=200).map(|i| Sample { at: Vec2::new(i as f32 * 2.0, ((i * 7919) % 13) as f32 * 0.35), pressure: 1.0 }).collect(); + let s: Vec = (0..=200).map(|i| Sample::new(Vec2::new(i as f32 * 2.0, ((i * 7919) % 13) as f32 * 0.35), 1.0)).collect(); let rough = outline(&s, &Tip::round(12.0), 0.3, 0.3); let smooth = outline(&s, &Tip::round(12.0), 6.0, 0.3); let (a, b) = (rough.anchors().len(), smooth.anchors().len()); @@ -401,7 +806,7 @@ mod tests { #[test] fn crossing_strokes_leave_holes_and_ellipses_follow_the_angle() { // A loop that closes on itself leaves a hole in the middle. - let ring: Vec = (0..=72).map(|i| i as f32 / 72.0 * std::f32::consts::TAU).map(|a| Sample { at: Vec2::new(100.0 * a.cos(), 100.0 * a.sin()), pressure: 1.0 }).collect(); + let ring: Vec = (0..=72).map(|i| i as f32 / 72.0 * std::f32::consts::TAU).map(|a| Sample::new(Vec2::new(100.0 * a.cos(), 100.0 * a.sin()), 1.0)).collect(); let p = outline(&ring, &Tip::round(10.0), 0.5, 0.2); let loops = p.cmds.iter().filter(|c| matches!(c, PathCmd::MoveTo(_))).count(); assert_eq!(loops, 2, "outer edge and hole"); @@ -429,10 +834,174 @@ mod tests { } } + fn loops(p: &Path) -> usize { + p.cmds.iter().filter(|c| matches!(c, PathCmd::MoveTo(_))).count() + } + + #[test] + fn tapers_come_to_points_and_keep_the_middle() { + let s = line(Vec2::ZERO, Vec2::new(300.0, 0.0), 60, |_| 1.0); + let sh = Shaping { taper_start: 0.3, taper_end: 0.3, ..Shaping::default() }; + let p = outline_shaped(&s, &Tip::round(20.0), &sh, 1.0, 0.1); + let inside = |x: f32, y: f32| p.contains(Vec2::new(x, y), &Affine::IDENTITY, FillRule::EvenOdd); + assert!(inside(150.0, 9.0), "full width in the middle: {:?} {}", p.bounds(), loops(&p)); + assert!(inside(5.0, 0.0) && !inside(5.0, 3.0), "pointed at the start"); + assert!(!inside(295.0, 3.0), "pointed at the end"); + // Area: less than the plain stroke, more than its middle part alone. + let plain = area(&outline(&s, &Tip::round(20.0), 1.0, 0.1)); + let a = area(&p); + assert!(a < plain * 0.85 && a > 0.4 * 300.0 * 20.0, "{a} vs {plain}"); + assert!((sh.taper(0.5) - 1.0).abs() < 1e-6 && sh.taper(0.0) < 0.06 && sh.taper(1.0) < 0.06); + } + + #[test] + fn spacing_stamps_separate_dabs() { + let s = line(Vec2::ZERO, Vec2::new(200.0, 0.0), 40, |_| 1.0); + // Dabs two sizes apart: 200 / 20 + 1 = 11 separate dots of the tip's area. + let sh = Shaping { spacing: 2.0, ..Shaping::default() }; + let p = outline_shaped(&s, &Tip::round(10.0), &sh, 0.5, 0.1); + assert_eq!(loops(&p), 11); + let want = 11.0 * std::f32::consts::PI * 25.0; + assert!((area(&p) - want).abs() / want < 0.02, "{} vs {want}", area(&p)); + // Closer than the tip's size, they join into one stroke. + let joined = outline_shaped(&s, &Tip::round(10.0), &Shaping { spacing: 0.5, ..Shaping::default() }, 0.5, 0.1); + assert_eq!(loops(&joined), 1); + // A dab budget: a huge stroke at the smallest spacing still stamps a bounded number. + let long = dabs(&[(Vec2::ZERO, 1.0), (Vec2::new(1e6, 0.0), 1.0)], 0.01); + assert!(long.len() <= MAX_DABS); + } + + #[test] + fn a_ragged_edge_wears_in_and_is_the_same_every_time() { + let s = line(Vec2::ZERO, Vec2::new(300.0, 40.0), 60, |t| 0.6 + 0.4 * t); + let sh = Shaping { jitter: 0.2, ..Shaping::default() }; + let tip = Tip::round(24.0); + let p = outline_shaped(&s, &tip, &sh, 1.0, 0.2); + let plain = outline(&s, &tip, 1.0, 0.2); + let (a, b) = (area(&p), area(&plain)); + // It wears in by up to a fifth of the size on each side: within the plain stroke, + // never less than what is left after the deepest wear. + assert!(a < b * 0.97 && a > b * 0.55, "{a} vs {b}"); + assert!(p.bounds().width() <= plain.bounds().width() + 0.5); + assert!(p.anchors().len() > plain.anchors().len() * 2, "ragged: {} vs {}", p.anchors().len(), plain.anchors().len()); + assert_eq!(p, outline_shaped(&s, &tip, &sh, 1.0, 0.2), "deterministic"); + } + + #[test] + fn the_paint_brush_line_has_a_profile() { + let s = line(Vec2::ZERO, Vec2::new(200.0, 0.0), 40, |t| t); + let (path, prof) = centre_stroke(&s, &Shaping::default(), 1.0, 0.1, 16); + assert!(!path.is_empty() && prof.len() == 16); + assert_eq!(prof.first().map(|p| p.0), Some(0.0)); + assert_eq!(prof.last().map(|p| p.0), Some(1.0)); + // Pressure from 0 to 1: factors from the floor to full. + assert!(prof.first().is_some_and(|p| (p.1 - MIN_PRESSURE_SIZE).abs() < 0.03)); + assert!(prof.last().is_some_and(|p| p.1 > 0.97)); + assert!(prof.windows(2).all(|w| w[1].1 >= w[0].1 - 1e-4), "rising"); + let b = path.bounds(); + assert!((b.width() - 200.0).abs() < 1.0 && b.height() < 1.0); + assert!(centre_stroke(&s[..1], &Shaping::default(), 1.0, 0.1, 16).0.is_empty(), "a dab is no line"); + } + + /// The bounds of the curve itself (`Path::bounds` includes control points). + trait Tight { + fn tight(&self) -> crate::Rect; + } + impl Tight for Path { + fn tight(&self) -> crate::Rect { + let mut r = crate::Rect::EMPTY; + for pl in self.flatten(&Affine::IDENTITY, 0.05) { + pl.points.into_iter().for_each(|x| r.include(x)); + } + r + } + } + + fn tilted_line(n: usize, len: f32, tilt: impl Fn(f32) -> Tilt) -> Vec { + (0..=n).map(|i| i as f32 / n as f32).map(|t| Sample { at: Vec2::new(len * t, 0.0), pressure: 1.0, tilt: Some(tilt(t)) }).collect() + } + + #[test] + fn tilt_maps_to_angle_and_width_analytically() { + let both = TiltResponse { angle: true, width: true }; + let lean = |alt: f32, az: f32| Tilt { altitude: alt, azimuth: az }.vector(); + // Upright: the brush as set. + assert_eq!(tilted(20.0, lean(90.0, 75.0), both), (20.0, 1.0)); + // Lying flat toward 30°: turned by 30°, twice as wide. + let (a, f) = tilted(20.0, lean(0.0, 30.0), both); + assert!((a - 50.0).abs() < 1e-3 && (f - 2.0).abs() < 1e-5, "{a} {f}"); + // Half way down (45°): half the lean, 1.5 × as wide; azimuth 270 is −90. + let (a, f) = tilted(0.0, lean(45.0, 270.0), both); + assert!((a + 90.0).abs() < 1e-3 && (f - 1.5).abs() < 1e-5, "{a} {f}"); + // Each part only when asked for. + assert_eq!(tilted(10.0, lean(0.0, 30.0), TiltResponse::default()), (10.0, 1.0)); + assert!((tilted(10.0, lean(0.0, 30.0), TiltResponse { angle: false, width: true }).1 - 2.0).abs() < 1e-5); + // Hostile tilts read as upright. + assert_eq!(Tilt { altitude: f32::NAN, azimuth: f32::INFINITY }.lean(), 0.0); + assert_eq!(tilted(5.0, Vec2::new(f32::NAN, 1.0), both), (5.0, 1.0)); + } + + #[test] + fn a_tilted_flat_tip_turns_with_the_pen() { + let flat = Tip { shape: TipShape::Round, size: 20.0, angle: 0.0, roundness: 0.2 }; + let turn = Shaping { tilt: TiltResponse { angle: true, width: false }, ..Shaping::default() }; + // Leaning toward 90° all along: the nib stands across the drag, as a 90° brush does. + let across = outline_shaped(&tilted_line(10, 100.0, |_| Tilt { altitude: 30.0, azimuth: 90.0 }), &flat, &turn, 1.0, 0.1); + let set = outline(&line(Vec2::ZERO, Vec2::new(100.0, 0.0), 10, |_| 1.0), &Tip { angle: 90.0, ..flat }, 1.0, 0.1); + assert!((across.tight().height() - 20.0).abs() < 0.6, "{:?}", across.tight()); + assert!((area(&across) - area(&set)).abs() / area(&set) < 0.03, "{} vs {}", area(&across), area(&set)); + // Without the tilt option the pen's lean does nothing. + let plain = outline_shaped(&tilted_line(10, 100.0, |_| Tilt { altitude: 30.0, azimuth: 90.0 }), &flat, &Shaping::default(), 1.0, 0.1); + assert!((plain.tight().height() - 4.0).abs() < 0.6, "{:?}", plain.tight()); + // Turning from along the drag (thin) to across it (wide) as it goes. + let s = tilted_line(60, 300.0, |t| Tilt { altitude: 20.0, azimuth: 90.0 * t }); + let p = outline_shaped(&s, &flat, &turn, 1.0, 0.1); + let inside = |x: f32, y: f32| p.contains(Vec2::new(x, y), &Affine::IDENTITY, FillRule::EvenOdd); + assert!(inside(15.0, 0.0) && !inside(15.0, 4.0), "thin at the start"); + assert!(inside(290.0, 9.0), "wide at the end"); + assert_eq!(loops(&p), 1); + // Widening: a round 10 tip flat on the paper paints 20 wide. + let wide = Shaping { tilt: TiltResponse { angle: false, width: true }, ..Shaping::default() }; + let w = outline_shaped(&tilted_line(10, 100.0, |_| Tilt { altitude: 0.0, azimuth: 0.0 }), &Tip::round(10.0), &wide, 1.0, 0.1); + assert!((w.tight().height() - 20.0).abs() < 0.5, "{:?}", w.tight()); + assert_eq!(w, outline_shaped(&tilted_line(10, 100.0, |_| Tilt { altitude: 0.0, azimuth: 0.0 }), &Tip::round(10.0), &wide, 1.0, 0.1), "deterministic"); + } + + #[test] + fn texture_opens_a_fixed_paper_grain_and_scatter_throws_dabs() { + let s = line(Vec2::ZERO, Vec2::new(300.0, 30.0), 60, |_| 1.0); + let tip = Tip::round(30.0); + let plain = outline(&s, &tip, 1.0, 0.2); + let sh = Shaping { texture: 0.5, ..Shaping::default() }; + let p = outline_shaped(&s, &tip, &sh, 1.0, 0.2); + let (a, b) = (area(&p), area(&plain)); + assert!(a < b * 0.9 && a > b * 0.25, "grain takes some of the paint: {a} vs {b}"); + assert!(loops(&p) > 10, "holes through the paint: {}", loops(&p)); + assert!(p.tight().width() <= plain.tight().width() + 0.5 && p.tight().height() <= plain.tight().height() + 0.5); + assert_eq!(p, outline_shaped(&s, &tip, &sh, 1.0, 0.2), "deterministic"); + // More texture, less paint. + let more = area(&outline_shaped(&s, &tip, &Shaping { texture: 1.0, ..Shaping::default() }, 1.0, 0.2)); + assert!(more < a, "{more} vs {a}"); + // Scatter: dabs either side of the line, past the plain stroke's edge. + let flat = line(Vec2::ZERO, Vec2::new(300.0, 0.0), 60, |_| 1.0); + let sc = Shaping { scatter: 1.5, spacing: 0.8, ..Shaping::default() }; + let q = outline_shaped(&flat, &Tip::round(10.0), &sc, 1.0, 0.2); + assert!(q.tight().height() > 20.0, "{:?}", q.tight()); + assert!(q.tight().height() < 10.0 + 2.0 * 15.0 + 1.0, "within the scatter's reach: {:?}", q.tight()); + assert!(loops(&q) > 5); + assert_eq!(q, outline_shaped(&flat, &Tip::round(10.0), &sc, 1.0, 0.2), "deterministic"); + // Scatter on a continuous brush stamps dabs a quarter size apart. + let cont = outline_shaped(&flat, &Tip::round(10.0), &Shaping { scatter: 1.0, ..Shaping::default() }, 1.0, 0.2); + assert!(cont.tight().height() > 12.0); + } + #[test] fn hostile_input_is_empty_or_bounded() { + let wild = Shaping { taper_start: f32::NAN, taper_end: 1e9, spacing: -3.0, jitter: f32::INFINITY, texture: f32::NAN, scatter: 1e9, tilt: TiltResponse::default() }; + assert_eq!(wild.sanitized(), Shaping { taper_start: 0.0, taper_end: 0.5, spacing: 0.0, jitter: 0.0, texture: 0.0, scatter: 2.0, tilt: TiltResponse::default() }); + let _ = outline_shaped(&line(Vec2::ZERO, Vec2::new(10.0, 0.0), 3, |_| 1.0), &Tip::round(5.0), &Shaping { spacing: 1e-9, jitter: 0.5, ..wild }, 1.0, 1.0); assert!(outline(&[], &Tip::round(10.0), 1.0, 1.0).is_empty()); - let nan = [Sample { at: Vec2::new(f32::NAN, 0.0), pressure: f32::NAN }]; + let nan = [Sample::new(Vec2::new(f32::NAN, 0.0), f32::NAN)]; assert!(outline(&nan, &Tip::round(10.0), 1.0, 1.0).is_empty()); assert!(outline(&line(Vec2::ZERO, Vec2::new(10.0, 0.0), 3, |_| 1.0), &Tip::round(0.0), 1.0, 1.0).is_empty()); assert!(outline(&line(Vec2::ZERO, Vec2::new(10.0, 0.0), 3, |_| 1.0), &Tip::round(f32::INFINITY), 1.0, 1.0).is_empty()); diff --git a/crates/geom/src/edit.rs b/crates/geom/src/edit.rs index 8f0c0a93..ea9ed0ec 100644 --- a/crates/geom/src/edit.rs +++ b/crates/geom/src/edit.rs @@ -383,7 +383,7 @@ fn leaving(cands: [Vec2; 3]) -> Option { } /// One cubic in place of `a` then `b` (see [`Path::merge_at`]). `None` for non-finite input. -fn merge_cubics(a: [Vec2; 4], b: [Vec2; 4]) -> Option<[Vec2; 4]> { +pub(crate) fn merge_cubics(a: [Vec2; 4], b: [Vec2; 4]) -> Option<[Vec2; 4]> { use crate::walk::cubic_point; const N: usize = 24; let (p0, p3) = (a[0], b[3]); diff --git a/crates/geom/src/envelope.rs b/crates/geom/src/envelope.rs new file mode 100644 index 00000000..1ab79870 --- /dev/null +++ b/crates/geom/src/envelope.rs @@ -0,0 +1,256 @@ +//! Envelope (ADR 0080): bending outlines by a bicubic Bézier patch, as Animate's Modify › +//! Transform › Envelope does. +//! +//! The patch has 4 × 4 control points over a rest rectangle. A point at `(u, v)` of the +//! rectangle (0 to 1 across and down) goes to `Σ Bᵢ(u) Bⱼ(v) Pᵢⱼ`, the Bernstein polynomials of +//! degree 3. At rest the control points are evenly spaced (a third of the way apart), and the +//! map is exactly the identity (Bernstein polynomials reproduce linear functions). +//! +//! The image of a cubic under the patch is a curve of degree 9, so it is approximated: each +//! segment is cut in halves until the cubic through its mapped control points is within the +//! tolerance of the true image at its quarter points. A straight segment that stays straight (any +//! affine part of the patch) stays one line. + +use crate::{Path, PathCmd, Rect, Vec2}; + +/// Most times a segment is halved. +const MAX_DEPTH: u32 = 10; +/// Most commands a bent path may have; beyond it [`warp`] declines. +pub const MAX_COMMANDS: usize = 200_000; + +/// The patch's control points, row by row from the top-left (`points[4 * row + column]`). +pub type Mesh = [Vec2; 16]; + +/// The mesh that leaves everything where it is: control points evenly over `rest`. +pub fn rest_mesh(rest: &Rect) -> Mesh { + let mut m = [Vec2::ZERO; 16]; + for (k, p) in m.iter_mut().enumerate() { + let (i, j) = ((k % 4) as f32, (k / 4) as f32); + *p = Vec2::new(rest.min.x + rest.width() * i / 3.0, rest.min.y + rest.height() * j / 3.0); + } + m +} + +/// The indices of the boundary handles, clockwise from the top-left corner: corners and the two +/// tangent points of each side (the inner four follow them, [`coons_interior`]). +pub const BOUNDARY: [usize; 12] = [0, 1, 2, 3, 7, 11, 15, 14, 13, 12, 8, 4]; +/// The corners, clockwise from the top-left. +pub const CORNERS: [usize; 4] = [0, 3, 15, 12]; + +/// Sets the four inner control points from the boundary, as a bicubic Coons patch does: the +/// sides bend the inside smoothly, and a rest boundary gives the rest mesh. +pub fn coons_interior(m: &mut Mesh) { + let p = |r: usize, c: usize| m[4 * r + c]; + let blend = |a: Vec2, b: Vec2, c: Vec2, d: Vec2, e: Vec2, f: Vec2, g: Vec2, h: Vec2| (a * -4.0 + (b + c) * 6.0 - (d + e) * 2.0 + (f + g) * 3.0 - h) * (1.0 / 9.0); + let p11 = blend(p(0, 0), p(0, 1), p(1, 0), p(0, 3), p(3, 0), p(3, 1), p(1, 3), p(3, 3)); + let p12 = blend(p(0, 3), p(0, 2), p(1, 3), p(0, 0), p(3, 3), p(3, 2), p(1, 0), p(3, 0)); + let p21 = blend(p(3, 0), p(3, 1), p(2, 0), p(3, 3), p(0, 0), p(0, 1), p(2, 3), p(0, 3)); + let p22 = blend(p(3, 3), p(3, 2), p(2, 3), p(3, 0), p(0, 3), p(0, 2), p(2, 0), p(0, 0)); + m[5] = p11; + m[6] = p12; + m[9] = p21; + m[10] = p22; +} + +fn bernstein(t: f64) -> [f64; 4] { + let u = 1.0 - t; + [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t] +} + +/// Where the patch puts `p` (a point of the rest rectangle's plane; outside it, the patch's +/// polynomial carries on). +pub fn map(mesh: &Mesh, rest: &Rect, p: Vec2) -> Vec2 { + let (w, h) = (f64::from(rest.width()), f64::from(rest.height())); + if !(w > 1e-9 && h > 1e-9) { + return p; + } + let u = (f64::from(p.x) - f64::from(rest.min.x)) / w; + let v = (f64::from(p.y) - f64::from(rest.min.y)) / h; + let (bu, bv) = (bernstein(u), bernstein(v)); + let (mut x, mut y) = (0.0f64, 0.0f64); + for (k, q) in mesh.iter().enumerate() { + let wgt = bu[k % 4] * bv[k / 4]; + x += wgt * f64::from(q.x); + y += wgt * f64::from(q.y); + } + Vec2::new(x as f32, y as f32) +} + +fn cubic_at(c: &[Vec2; 4], t: f32) -> Vec2 { + let u = 1.0 - t; + c[0] * (u * u * u) + c[1] * (3.0 * u * u * t) + c[2] * (3.0 * u * t * t) + c[3] * (t * t * t) +} + +fn split(c: &[Vec2; 4]) -> ([Vec2; 4], [Vec2; 4]) { + let (ab, bc, cd) = (c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5)); + let (abc, bcd) = (ab.lerp(bc, 0.5), bc.lerp(cd, 0.5)); + let m = abc.lerp(bcd, 0.5); + ([c[0], ab, abc, m], [m, bcd, cd, c[3]]) +} + +/// Whether every mesh point is finite and the rest rectangle has an area. +pub fn valid(mesh: &Mesh, rest: &Rect) -> bool { + mesh.iter().all(|p| p.x.is_finite() && p.y.is_finite()) && rest.width() > 1e-6 && rest.height() > 1e-6 && rest.min.x.is_finite() && rest.min.y.is_finite() && rest.max.x.is_finite() && rest.max.y.is_finite() +} + +/// `path` bent by the patch (both in the same space), within `tol`. `None` when the bent path +/// would be too large ([`MAX_COMMANDS`]) or the mesh isn't valid. +pub fn warp(path: &Path, mesh: &Mesh, rest: &Rect, tol: f32) -> Option { + if !valid(mesh, rest) { + return None; + } + let tol = if tol.is_finite() { tol.max(1e-4) } else { 0.05 }; + let mut out = Path::new(); + let (mut start, mut cur) = (Vec2::ZERO, Vec2::ZERO); + let line = |a: Vec2, b: Vec2| [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b]; + for c in &path.cmds { + match *c { + PathCmd::MoveTo(p) => { + out.move_to(map(mesh, rest, p)); + start = p; + cur = p; + } + PathCmd::LineTo(p) => { + segment(&mut out, &line(cur, p), true, mesh, rest, tol, 0); + cur = p; + } + PathCmd::QuadTo(q, p) => { + segment(&mut out, &[cur, cur.lerp(q, 2.0 / 3.0), p.lerp(q, 2.0 / 3.0), p], false, mesh, rest, tol, 0); + cur = p; + } + PathCmd::CubicTo(a, b, p) => { + segment(&mut out, &[cur, a, b, p], false, mesh, rest, tol, 0); + cur = p; + } + PathCmd::Close => { + // The closing edge bends too: when it no longer is straight, draw it, then + // close on the start. + if cur != start && !stays_straight(&line(cur, start), mesh, rest, tol) { + segment(&mut out, &line(cur, start), true, mesh, rest, tol, 0); + } + out.close(); + cur = start; + } + } + if out.cmds.len() > MAX_COMMANDS { + return None; + } + } + Some(out) +} + +/// Whether the line `c` (as a cubic) stays straight: its image's quarter points are on the +/// chord between its mapped ends, evenly. +fn stays_straight(c: &[Vec2; 4], mesh: &Mesh, rest: &Rect, tol: f32) -> bool { + let (a, b) = (map(mesh, rest, c[0]), map(mesh, rest, c[3])); + [0.25f32, 0.5, 0.75].iter().all(|&t| map(mesh, rest, cubic_at(c, t)).distance(a.lerp(b, t)) <= tol) +} + +/// One segment (as a cubic, `straight` when it is a line), bent and appended. +fn segment(out: &mut Path, c: &[Vec2; 4], straight: bool, mesh: &Mesh, rest: &Rect, tol: f32, depth: u32) { + let m = [map(mesh, rest, c[0]), map(mesh, rest, c[1]), map(mesh, rest, c[2]), map(mesh, rest, c[3])]; + let err = [0.25f32, 0.5, 0.75].iter().map(|&t| map(mesh, rest, cubic_at(c, t)).distance(cubic_at(&m, t))).fold(0.0f32, f32::max); + if straight && stays_straight(c, mesh, rest, tol) { + out.line_to(m[3]); + return; + } + if err <= tol || depth >= MAX_DEPTH || out.cmds.len() > MAX_COMMANDS { + out.cubic_to(m[1], m[2], m[3]); + return; + } + let (a, b) = split(c); + segment(out, &a, false, mesh, rest, tol, depth + 1); + segment(out, &b, false, mesh, rest, tol, depth + 1); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Affine; + + fn rest() -> Rect { + Rect::new(10.0, 20.0, 110.0, 70.0) + } + + /// At rest the map is the identity, and a bent path is the path itself, command for command. + #[test] + fn identity_at_rest() { + let r = rest(); + let m = rest_mesh(&r); + for p in [Vec2::new(10.0, 20.0), Vec2::new(60.0, 45.0), Vec2::new(110.0, 70.0), Vec2::new(-30.0, 200.0)] { + assert!(map(&m, &r, p).distance(p) < 1e-3, "{p:?}"); + } + let mut path = Path::rounded_rect(10.0, 20.0, 100.0, 50.0, 12.0); + path.cmds.extend(Path::star(60.0, 45.0, 20.0, 8.0, 5).cmds); + let bent = warp(&path, &m, &r, 0.01).expect("bends"); + assert_eq!(bent.cmds.len(), path.cmds.len(), "nothing is subdivided at rest"); + for (a, b) in bent.cmds.iter().zip(&path.cmds) { + assert_eq!(std::mem::discriminant(a), std::mem::discriminant(b), "lines stay lines"); + } + let (fa, fb) = (bent.flatten(&Affine::IDENTITY, 0.01), path.flatten(&Affine::IDENTITY, 0.01)); + for (pa, pb) in fa.iter().zip(&fb) { + for (x, y) in pa.points.iter().zip(&pb.points) { + assert!(x.distance(*y) < 1e-3); + } + } + } + + /// A rest boundary gives the rest interior; moving every point by the same affine map + /// moves the path by it, lines staying lines. + #[test] + fn coons_and_affine_meshes() { + let r = rest(); + let mut m = rest_mesh(&r); + let want = m; + m[5] = Vec2::ZERO; + m[10] = Vec2::new(1e3, 1e3); + coons_interior(&mut m); + for (a, b) in m.iter().zip(&want) { + assert!(a.distance(*b) < 1e-3); + } + let xf = Affine::translate(5.0, -3.0).mul(&Affine::rotate(0.4)).mul(&Affine::scale(1.5, 0.75)); + let moved: Mesh = want.map(|p| xf.apply(p)); + let path = Path::rect(20.0, 30.0, 40.0, 20.0); + let bent = warp(&path, &moved, &r, 0.01).expect("bends"); + assert!(bent.cmds.iter().all(|c| !matches!(c, PathCmd::CubicTo(..))), "an affine envelope keeps lines straight"); + let pts = bent.flatten(&Affine::IDENTITY, 0.01); + for (p, q) in pts[0].points.iter().zip(path.flatten(&xf, 0.01)[0].points.iter()) { + assert!(p.distance(*q) < 1e-2, "{p:?} vs {q:?}"); + } + } + + /// A bulged top side bends a straight top edge into a curve through the bulge, within the + /// tolerance of the exact image everywhere. + #[test] + fn bending_is_within_tolerance() { + let r = rest(); + let mut m = rest_mesh(&r); + m[1].y -= 30.0; + m[2].y -= 30.0; + coons_interior(&mut m); + let path = Path::rect(10.0, 20.0, 100.0, 50.0); + let tol = 0.05; + let bent = warp(&path, &m, &r, tol).expect("bends"); + assert!(bent.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..)))); + // The top edge's middle rose by ¾ of the handles' lift (B₁ + B₂ at ½). + let top = map(&m, &r, Vec2::new(60.0, 20.0)); + assert!((top.y - (20.0 - 22.5)).abs() < 1e-3, "{top:?}"); + // Every point of the exact image of the top edge is near the bent outline. + let poly = &bent.flatten(&Affine::IDENTITY, 0.005)[0].points; + for i in 0..=50 { + let exact = map(&m, &r, Vec2::new(10.0 + 2.0 * i as f32, 20.0)); + let d = poly.windows(2).map(|w| crate::segment_distance(exact, w[0], w[1])).fold(f32::MAX, f32::min); + assert!(d < tol * 2.0, "{i}: {d}"); + } + } + + #[test] + fn invalid_meshes_decline() { + let r = rest(); + let mut m = rest_mesh(&r); + m[3].x = f32::NAN; + assert!(warp(&Path::rect(0.0, 0.0, 1.0, 1.0), &m, &r, 0.1).is_none()); + let flat = Rect::new(0.0, 0.0, 10.0, 0.0); + assert!(warp(&Path::rect(0.0, 0.0, 1.0, 1.0), &rest_mesh(&flat), &flat, 0.1).is_none()); + } +} diff --git a/crates/geom/src/fit.rs b/crates/geom/src/fit.rs index 240b7dcc..3ca158e1 100644 --- a/crates/geom/src/fit.rs +++ b/crates/geom/src/fit.rs @@ -256,8 +256,11 @@ fn generate(pts: &[P], u: &[f64], t1: P, t2: P) -> [P; 4] { let det1 = x[0] * c[1][1] - x[1] * c[0][1]; let (mut al, mut ar) = if det.abs() > 1e-12 { (det1 / det, det0 / det) } else { (0.0, 0.0) }; let seg = len(sub(p3, p0)); + // A handle longer than the points' own length is a bad solve (a nearly closed stretch can + // send it far off): fall back, and the error check splits the stretch instead (ADR 0093). + let arc: f64 = pts.windows(2).map(|w| len(sub(w[1], w[0]))).sum(); // Schneider's fallback when the solve is degenerate or flips a handle. - if al < 1e-6 * seg || ar < 1e-6 * seg { + if al < 1e-6 * seg || ar < 1e-6 * seg || al > arc || ar > arc { al = seg / 3.0; ar = seg / 3.0; } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index e0b75dd1..9f740d0b 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -8,9 +8,12 @@ mod affine; pub mod brush; pub mod clip; pub mod edit; +pub mod envelope; pub mod morph; pub mod planar; +pub mod pressure; pub mod raw; +pub mod slice; mod fit; mod path; pub mod svg; @@ -19,7 +22,7 @@ pub mod walk; pub use affine::{Affine, Decomposed}; pub use fit::fit_curve; -pub use path::{FillRule, Path, PathCmd, Polyline, segment_distance}; +pub use path::{FillRule, POLYSTAR_MAX_SIDES, Path, PathCmd, Polyline, polystar_corners, segment_distance, star_inner_radius}; use serde::{Deserialize, Serialize}; use std::ops::{Add, Mul, Neg, Sub}; diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5c29dd2f..c1813a49 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -203,6 +203,36 @@ const MAX_SEGMENTS_PER_CURVE: usize = 1024; /// Bézier circle constant. const KAPPA: f32 = 0.552_284_8; +/// Most corners a PolyStar has on each side of its outline (sides or points). +pub const POLYSTAR_MAX_SIDES: u32 = 256; + +/// The inner radius of a star of `points` points for a point size from 0 to 1 (ADR 0080): at 1 +/// the inner corners lie on the edges of the polygon through the tips (the star is that polygon), +/// at 0 they meet in the centre (needle points), and in between the depth is proportional. Out +/// of range or not a number, the point size is clamped (or 0.5). +pub fn star_inner_radius(outer: f32, points: u32, point_size: f32) -> f32 { + let n = points.clamp(3, POLYSTAR_MAX_SIDES) as f32; + let size = if point_size.is_finite() { point_size.clamp(0.0, 1.0) } else { 0.5 }; + outer * size * (std::f32::consts::PI / n).cos() +} + +/// The corners of [`Path::polystar`], in order (clockwise on screen, y down), the first straight +/// up: `sides` of them for a polygon, `2 × sides` (tip, inner, tip, …) for a star. `sides` is +/// clamped to 3..=[`POLYSTAR_MAX_SIDES`]. +pub fn polystar_corners(cx: f32, cy: f32, radius: f32, sides: u32, star: bool, point_size: f32) -> Vec { + let n = sides.clamp(3, POLYSTAR_MAX_SIDES) as usize; + let inner = star_inner_radius(radius, sides, point_size); + let steps = if star { n * 2 } else { n }; + (0..steps) + .map(|i| { + let r = if star && i % 2 == 1 { inner } else { radius }; + // f64 so the corners of a big polygon stay where they belong. + let a = -std::f64::consts::FRAC_PI_2 + i as f64 * std::f64::consts::TAU / steps as f64; + Vec2::new(cx + r * a.cos() as f32, cy + r * a.sin() as f32) + }) + .collect() +} + impl Path { pub fn new() -> Self { Self::default() @@ -274,6 +304,22 @@ impl Path { p } + /// The PolyStar tool's outline (ADR 0080): a regular polygon of `sides` corners, or a star of + /// `sides` points whose inner corners are at [`star_inner_radius`] for `point_size`, centred + /// at `(cx, cy)` with the first corner straight up. + pub fn polystar(cx: f32, cy: f32, radius: f32, sides: u32, star: bool, point_size: f32) -> Path { + let mut p = Path::new(); + for (i, v) in polystar_corners(cx, cy, radius, sides, star, point_size).into_iter().enumerate() { + if i == 0 { + p.move_to(v); + } else { + p.line_to(v); + } + } + p.close(); + p + } + /// Star (or polygon when `inner == outer`) with `points` tips, first tip pointing up. pub fn star(cx: f32, cy: f32, outer: f32, inner: f32, points: u32) -> Path { let n = points.clamp(3, 256) as usize; @@ -499,6 +545,71 @@ pub fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 { mod tests { use super::*; + /// Shoelace area of a polygon. + fn poly_area(pts: &[Vec2]) -> f64 { + let n = pts.len(); + (0..n).map(|i| { + let (a, b) = (pts[i], pts[(i + 1) % n]); + f64::from(a.x) * f64::from(b.y) - f64::from(b.x) * f64::from(a.y) + }).sum::() * 0.5 + } + + /// ADR 0080: a regular polygon's corners are on its circle, its first straight up, and its + /// area is n/2 · r² · sin(2π/n). + #[test] + fn polystar_polygon_is_regular() { + for n in [3u32, 4, 5, 6, 8, 12, 32] { + let r = 50.0; + let pts = polystar_corners(10.0, -20.0, r, n, false, 0.3); + assert_eq!(pts.len(), n as usize); + assert!((pts[0].x - 10.0).abs() < 1e-4 && (pts[0].y - (-20.0 - r)).abs() < 1e-4, "first corner straight up: {:?}", pts[0]); + for p in &pts { + assert!(((*p - Vec2::new(10.0, -20.0)).length() - r).abs() < 1e-3); + } + let want = f64::from(n) / 2.0 * f64::from(r * r) * (std::f64::consts::TAU / f64::from(n)).sin(); + let got = poly_area(&pts); + assert!((got.abs() - want).abs() < want * 1e-5, "n {n}: {got} vs {want}"); + // Clockwise on screen (y down): positive shoelace area. + assert!(got > 0.0); + // The path is the same polygon. + let path = Path::polystar(10.0, -20.0, r, n, false, 0.3); + assert_eq!(path.cmds.len(), n as usize + 1); + } + } + + /// ADR 0080: a star's inner corners are at r · size · cos(π/n): at 1 they lie on the + /// polygon's edges (the star covers exactly the polygon), at 0 in the centre, and its area + /// is n · r · r_in · sin(π/n). + #[test] + fn polystar_star_point_size() { + let r = 80.0f32; + for n in [3u32, 5, 7, 32] { + let half = std::f64::consts::PI / f64::from(n); + for size in [0.0f32, 0.25, 0.5, 1.0] { + let pts = polystar_corners(0.0, 0.0, r, n, true, size); + assert_eq!(pts.len(), 2 * n as usize); + let inner = f64::from(r) * f64::from(size) * half.cos(); + assert!((f64::from(star_inner_radius(r, n, size)) - inner).abs() < 1e-3); + for (i, p) in pts.iter().enumerate() { + let want = if i % 2 == 0 { f64::from(r) } else { inner }; + assert!((f64::from(p.length()) - want).abs() < 1e-3, "n {n} size {size} corner {i}"); + } + let want = f64::from(n) * f64::from(r) * inner * half.sin(); + assert!((poly_area(&pts) - want).abs() <= want * 1e-4 + 1e-3, "n {n} size {size}"); + } + // Point size 1: the area of the polygon through the tips. + let full = poly_area(&polystar_corners(0.0, 0.0, r, n, true, 1.0)); + let poly = poly_area(&polystar_corners(0.0, 0.0, r, n, false, 1.0)); + assert!((full - poly).abs() < poly * 1e-5); + } + // Out of range and not a number: clamped, or the default. + assert_eq!(star_inner_radius(10.0, 5, 3.0), star_inner_radius(10.0, 5, 1.0)); + assert_eq!(star_inner_radius(10.0, 5, -1.0), 0.0); + assert_eq!(star_inner_radius(10.0, 5, f32::NAN), star_inner_radius(10.0, 5, 0.5)); + assert_eq!(polystar_corners(0.0, 0.0, 1.0, 0, false, 0.5).len(), 3); + assert_eq!(polystar_corners(0.0, 0.0, 1.0, u32::MAX, false, 0.5).len(), POLYSTAR_MAX_SIDES as usize); + } + #[test] fn flatten_rect_is_closed_polygon() { let pls = Path::rect(0.0, 0.0, 10.0, 5.0).flatten(&Affine::IDENTITY, 0.1); diff --git a/crates/geom/src/planar.rs b/crates/geom/src/planar.rs index d21de9d1..f8ec0da3 100644 --- a/crates/geom/src/planar.rs +++ b/crates/geom/src/planar.rs @@ -55,6 +55,19 @@ pub struct Piece { pub item: usize, /// Inside the cutter ([`merge_cut`]); always false from [`merge`]. pub inside: bool, + /// For a stroke piece: the stretches of its items' paths it runs along, in order, each as + /// `[from, to]` in path positions (see [`Piece::position`]); `to < from` where it runs + /// backwards. What a width profile needs to follow its stroke into each piece (ADR 0093). + /// Empty for fills. + pub spans: Vec<[f64; 2]>, +} + +impl Piece { + /// A place on an item's path as a path position: `k + t` is parameter `t` along the segment + /// that command `k` draws (a `Close` draws the closing line). + pub fn position(cmd: usize, t: f64) -> f64 { + cmd as f64 + t.clamp(0.0, 1.0) + } } #[derive(Clone, Debug, Default, PartialEq)] @@ -75,6 +88,33 @@ pub fn merge_cut(items: &[Item], cutter: &Path) -> Option { merge_with(items, Some(cutter)) } +/// The area `paths` cover together (each filled by its own rule), as one path of loops that +/// don't overlap: even-odd and non-zero fill it alike. Empty when they cover nothing; `None` +/// when there is too much to merge at once. +pub fn union(paths: &[(&Path, FillRule)]) -> Option { + let items: Vec = paths.iter().map(|&(path, fill_rule)| Item { path, fill: Some(0), fill_rule, stroke: None }).collect(); + let merged = merge(&items)?; + Some(join(merged.fills.into_iter().map(|p| p.path))) +} + +/// The part of `subject` (filled by `rule`) inside `region` (filled even-odd, such as a +/// [`union`]): a boolean intersection, exact to [`SNAP`], as one path of loops that don't +/// overlap (ADR 0080: the Brush's Paint Selection and Paint Inside). Empty when they don't +/// overlap; `None` when there is too much to merge at once. +pub fn intersect(subject: &Path, rule: FillRule, region: &Path) -> Option { + let merged = merge_cut(&[Item { path: subject, fill: Some(0), fill_rule: rule, stroke: None }], region)?; + Some(join(merged.fills.into_iter().filter(|p| p.inside).map(|p| p.path))) +} + +/// Pieces' paths, one after another. +fn join(pieces: impl Iterator) -> Path { + let mut out = Path::new(); + for p in pieces { + out.cmds.extend(p.cmds); + } + out +} + /// The item number the cutter's segments carry. const CUTTER: usize = usize::MAX; @@ -269,6 +309,15 @@ struct Seg { line: bool, item: usize, stroke: bool, + /// Its ends as path positions on its item ([`Piece::position`]). + pos: [f64; 2], +} + +impl Seg { + /// Path position of parameter `t`. + fn at(&self, t: f64) -> f64 { + self.pos[0] + (self.pos[1] - self.pos[0]) * t + } } /// Every segment of every item. A filled subpath left open gets its closing edge (unstroked). @@ -279,31 +328,32 @@ fn collect(items: &[Item]) -> Option> { continue; } let stroke = it.stroke.is_some(); - let mut push = |c: Cubic, line: bool, stroke: bool| { + let mut push = |c: Cubic, line: bool, stroke: bool, k: usize| { if !c.iter().all(|p| p.finite()) || hull_len(&c) <= 1e-9 { return; } + let k = k as f64; // A segment that comes back to where it began (a loop) is two, so no edge is a loop. if c[0].dist(c[3]) < TOL && hull_len(&c) > 2.0 * TOL { let (a, b) = split(&c, 0.5); - segs.push(Seg { c: a, line, item, stroke }); - segs.push(Seg { c: b, line, item, stroke }); + segs.push(Seg { c: a, line, item, stroke, pos: [k, k + 0.5] }); + segs.push(Seg { c: b, line, item, stroke, pos: [k + 0.5, k + 1.0] }); } else { - segs.push(Seg { c, line, item, stroke }); + segs.push(Seg { c, line, item, stroke, pos: [k, k + 1.0] }); } }; let (mut start, mut last) = (P::default(), P::default()); let (mut open, mut drawn) = (false, false); - let close = |push: &mut dyn FnMut(Cubic, bool, bool), last: P, start: P, stroked: bool| { + let close = |push: &mut dyn FnMut(Cubic, bool, bool, usize), last: P, start: P, stroked: bool, k: usize| { if last.dist(start) > 0.0 { - push(line_cubic(last, start), true, stroked); + push(line_cubic(last, start), true, stroked, k); } }; - for cmd in &it.path.cmds { + for (k, cmd) in it.path.cmds.iter().enumerate() { let to = match *cmd { PathCmd::MoveTo(p) => { if open && drawn && it.fill.is_some() { - close(&mut push, last, start, false); + close(&mut push, last, start, false, k); } start = P::of(p); last = start; @@ -312,7 +362,7 @@ fn collect(items: &[Item]) -> Option> { } PathCmd::Close => { if open { - close(&mut push, last, start, stroke); + close(&mut push, last, start, stroke, k); } last = start; (open, drawn) = (false, false); @@ -325,12 +375,12 @@ fn collect(items: &[Item]) -> Option> { } PathCmd::CubicTo(a, b, p) => ([last, P::of(a), P::of(b), P::of(p)], false), }; - push(to.0, to.1, stroke); + push(to.0, to.1, stroke, k); last = to.0[3]; (open, drawn) = (true, true); } if open && drawn && it.fill.is_some() { - close(&mut push, last, start, false); + close(&mut push, last, start, false, it.path.cmds.len()); } if segs.len() > MAX_SEGMENTS { return None; @@ -793,7 +843,7 @@ impl Map { None => { let (style, item, inside) = top.get(&g).copied().unwrap_or((0, 0, false)); piece_of.insert(g, out.fills.len()); - out.fills.push(Piece { style, path, item, inside }); + out.fills.push(Piece { style, path, item, inside, spans: Vec::new() }); } } } @@ -850,17 +900,24 @@ impl Map { let item = halves.iter().filter_map(|&h| stroke_of[h / 2]).max().unwrap_or(0); // A run along the cutter's edge counts as inside it. let inside = halves.iter().any(|&h| cut_edge[h / 2]) || halves.get(halves.len() / 2).is_some_and(|&h| cutter.covers(eval(&self.curve(h), 0.5), FillRule::EvenOdd)); - out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item, inside }); + let (path, spans) = self.emit_spans(&halves, closed, segs); + out.strokes.push(Piece { style: st, path, item, inside, spans }); } } /// A subpath along `halves`: pieces of one segment joined back, straight runs made one line. fn emit(&self, halves: &[Half], closed: bool, segs: &[Seg]) -> Path { + self.emit_spans(halves, closed, segs).0 + } + + /// [`Map::emit`], with the stretches of the items' paths the subpath runs along. + fn emit_spans(&self, halves: &[Half], closed: bool, segs: &[Seg]) -> (Path, Vec<[f64; 2]>) { let mut runs: Vec = Vec::new(); for &h in halves { let e = &self.edges[h / 2]; let (t0, t1) = if h.is_multiple_of(2) { (e.t[0], e.t[1]) } else { (e.t[1], e.t[0]) }; - let run = Run { c: self.curve(h), line: e.line, src: e.src, t: [t0, t1] }; + let spans = segs.get(e.src).map(|s| vec![[s.at(t0), s.at(t1)]]).unwrap_or_default(); + let run = Run { c: self.curve(h), line: e.line, src: e.src, t: [t0, t1], spans }; match runs.last_mut().and_then(|last| last.join(&run, segs)) { Some(j) => { if let Some(last) = runs.last_mut() { @@ -891,10 +948,35 @@ impl Map { if closed && !runs.is_empty() { path.close(); } - path + let mut spans: Vec<[f64; 2]> = Vec::new(); + for sp in runs.into_iter().flat_map(|r| r.spans) { + push_span(&mut spans, sp); + } + (path, spans) } } +/// Adds `sp` to `spans`, extending the last one when `sp` carries straight on from it. +fn push_span(spans: &mut Vec<[f64; 2]>, sp: [f64; 2]) { + if let Some(last) = spans.last_mut() + && (last[1] - sp[0]).abs() < 1e-9 + && (last[1] >= last[0]) == (sp[1] >= sp[0]) + { + last[1] = sp[1]; + return; + } + spans.push(sp); +} + +/// Two runs' spans, one after the other. +fn joined(a: &[[f64; 2]], b: &[[f64; 2]]) -> Vec<[f64; 2]> { + let mut out = a.to_vec(); + for &sp in b { + push_span(&mut out, sp); + } + out +} + struct Faces { face_of_half: Vec>, /// A point inside each face. @@ -907,6 +989,8 @@ struct Run { line: bool, src: usize, t: [f64; 2], + /// The stretches of item paths it covers ([`Piece::spans`]). + spans: Vec<[f64; 2]>, } impl Run { @@ -916,14 +1000,14 @@ impl Run { if self.src == o.src && self.t[1] == o.t[0] && forward(self) == forward(o) && self.src != usize::MAX { let s = segs.get(self.src)?; let c = pinned(&sub(&s.c, self.t[0], o.t[1]), self.line, self.c[0], o.c[3]); - return Some(Run { c, line: self.line, src: self.src, t: [self.t[0], o.t[1]] }); + return Some(Run { c, line: self.line, src: self.src, t: [self.t[0], o.t[1]], spans: joined(&self.spans, &o.spans) }); } if self.line && o.line { let (a, b, c) = (self.c[0], self.c[3], o.c[3]); let d = c.sub(a); let l = d.len(); if l > 1e-9 && (d.cross(b.sub(a)) / l).abs() < 0.01 && d.dot(b.sub(a)) > 0.0 && d.dot(c.sub(b)) > 0.0 { - return Some(Run { c: line_cubic(a, c), line: true, src: usize::MAX, t: [0.0, 0.0] }); + return Some(Run { c: line_cubic(a, c), line: true, src: usize::MAX, t: [0.0, 0.0], spans: joined(&self.spans, &o.spans) }); } } None diff --git a/crates/geom/src/planar_tests.rs b/crates/geom/src/planar_tests.rs index 6ee8526e..c4aeaf19 100644 --- a/crates/geom/src/planar_tests.rs +++ b/crates/geom/src/planar_tests.rs @@ -330,3 +330,71 @@ fn a_cutter_over_a_curve_cuts_exact_pieces() { assert!(near(inside * 4.0, all, 1.0), "{inside} of {all}"); assert_eq!(m.fills.len(), 2); } + +// ----- union and intersection (ADR 0080) -------------------------------------------------------- + +/// Two overlapping squares: the union covers 10² + 10² − 5·5, and the even-odd area of the +/// joined path agrees (no overlapping loops). +#[test] +fn union_of_overlapping_squares() { + let (a, b) = (rect(0.0, 0.0, 10.0, 10.0), rect(5.0, 5.0, 10.0, 10.0)); + let u = union(&[(&a, FillRule::NonZero), (&b, FillRule::NonZero)]).expect("merges"); + assert!((area(&u) - 175.0).abs() < 0.05, "{}", area(&u)); + assert!(u.contains(Vec2::new(12.0, 12.0), &crate::Affine::IDENTITY, FillRule::EvenOdd)); + assert!(u.contains(Vec2::new(7.0, 7.0), &crate::Affine::IDENTITY, FillRule::EvenOdd), "the overlap is covered once"); + assert!(!u.contains(Vec2::new(12.0, 2.0), &crate::Affine::IDENTITY, FillRule::EvenOdd)); + assert!(union(&[]).expect("nothing to merge").is_empty()); +} + +/// A bar across a square keeps only the part inside it; a disc inside a square with a hole +/// loses the hole. +#[test] +fn intersect_clips_to_the_region() { + let bar = rect(-20.0, 4.0, 60.0, 2.0); + let square = rect(0.0, 0.0, 10.0, 10.0); + let clipped = intersect(&bar, FillRule::NonZero, &square).expect("merges"); + assert!((area(&clipped) - 20.0).abs() < 0.05, "{}", area(&clipped)); + // Nothing in common. + let far = rect(100.0, 100.0, 5.0, 5.0); + assert!(intersect(&far, FillRule::NonZero, &square).expect("merges").is_empty()); + // A ring (square with a square hole, even-odd) clipping a square that covers it all. + let mut ring = rect(0.0, 0.0, 30.0, 30.0); + ring.cmds.extend(rect(10.0, 10.0, 10.0, 10.0).cmds); + let cover = rect(-5.0, -5.0, 40.0, 40.0); + let inside = intersect(&cover, FillRule::NonZero, &ring).expect("merges"); + assert!((area(&inside) - 800.0).abs() < 0.1, "{}", area(&inside)); + assert!(!inside.contains(Vec2::new(15.0, 15.0), &crate::Affine::IDENTITY, FillRule::EvenOdd), "the hole stays empty"); + // A circle's quarter: exact to the curve. + let disc = Path::ellipse(0.0, 0.0, 10.0, 10.0); + let quarter = intersect(&disc, FillRule::NonZero, &rect(0.0, 0.0, 20.0, 20.0)).expect("merges"); + let want = std::f32::consts::PI * 100.0 / 4.0; + assert!((area(&quarter) - want).abs() < want * 0.002, "{} vs {want}", area(&quarter)); +} + +#[test] +fn stroke_pieces_say_which_stretch_of_their_path_they_run_along() { + // A line from x 0 to 100, crossed by another at x 30 (crossings start new pieces): its two + // pieces run along positions 1.0..1.3 and 1.3..2.0 (command 1 draws it). + let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)); + let b = Path::line(Vec2::new(30.0, -50.0), Vec2::new(30.0, 50.0)); + let m = run(&[stroked(&a, None, 1), stroked(&b, None, 2)]); + let mut spans: Vec<[f64; 2]> = m.strokes.iter().filter(|p| p.item == 0).flat_map(|p| p.spans.clone()).collect(); + spans.sort_by(|x, y| x[0].min(x[1]).total_cmp(&y[0].min(y[1]))); + assert_eq!(spans.len(), 2, "{m:?}"); + let lo = |s: [f64; 2]| s[0].min(s[1]); + let hi = |s: [f64; 2]| s[0].max(s[1]); + assert!((lo(spans[0]) - 1.0).abs() < 1e-6 && (hi(spans[0]) - 1.3).abs() < 1e-3, "{spans:?}"); + assert!((lo(spans[1]) - 1.3).abs() < 1e-3 && (hi(spans[1]) - 2.0).abs() < 1e-6, "{spans:?}"); + // A polyline uncut keeps one span over all its segments, and fills carry none. + let mut z = Path::new(); + z.move_to(Vec2::new(0.0, 0.0)); + z.line_to(Vec2::new(50.0, 0.0)); + z.cubic_to(Vec2::new(70.0, 0.0), Vec2::new(90.0, 5.0), Vec2::new(100.0, 20.0)); + let r = rect(200.0, 0.0, 10.0, 10.0); + let m = run(&[stroked(&z, None, 1), fill(&r, 3)]); + assert_eq!(m.strokes.len(), 1); + let sp = &m.strokes[0].spans; + assert_eq!(sp.len(), 1, "{sp:?}"); + assert!((lo(sp[0]) - 1.0).abs() < 1e-9 && (hi(sp[0]) - 3.0).abs() < 1e-9, "{sp:?}"); + assert!(m.fills.iter().all(|f| f.spans.is_empty())); +} diff --git a/crates/geom/src/pressure.rs b/crates/geom/src/pressure.rs new file mode 100644 index 00000000..a31a315a --- /dev/null +++ b/crates/geom/src/pressure.rs @@ -0,0 +1,273 @@ +//! Pressure curves (ADR 0068): how pen pressure maps to the brush's size (and, optionally, the +//! paint's opacity). +//! +//! A curve is a few points `(input, output)` in `0..=1`, sorted by input, with one at input 0 +//! and one at input 1. Between them it follows a monotone cubic (Fritsch–Carlson): smooth, +//! through every point, never overshooting a neighbour, so the output stays in `0..=1` and a +//! rising curve never dips. It is `Copy` (a fixed array), so tool options holding it stay cheap. + +use serde::{Deserialize, Serialize}; + +/// Most points one curve keeps. +pub const MAX_CURVE_POINTS: usize = 8; +/// Points closer than this in input are one point (the last given wins). +const MERGE: f32 = 0.02; + +/// A pressure curve. Build one with [`PressureCurve::new`] (sanitizing) or a preset. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(from = "Vec<[f32; 2]>", into = "Vec<[f32; 2]>")] +pub struct PressureCurve { + n: u8, + pts: [[f32; 2]; MAX_CURVE_POINTS], +} + +/// The built-in curves: `(key, label)`. +pub const CURVE_PRESETS: [(&str, &str); 3] = [("linear", "Linear"), ("soft", "Soft"), ("firm", "Firm")]; + +impl Default for PressureCurve { + fn default() -> Self { + PressureCurve::LINEAR + } +} + +const fn fixed(a: [[f32; 2]; 3], n: u8) -> PressureCurve { + let mut pts = [[0.0; 2]; MAX_CURVE_POINTS]; + pts[0] = a[0]; + pts[1] = a[1]; + pts[2] = a[2]; + PressureCurve { n, pts } +} + +impl PressureCurve { + /// Output equals input. + pub const LINEAR: PressureCurve = fixed([[0.0, 0.0], [1.0, 1.0], [0.0, 0.0]], 2); + /// A light touch already paints wide (for a stiff pen or a light hand). + pub const SOFT: PressureCurve = fixed([[0.0, 0.0], [0.3, 0.6], [1.0, 1.0]], 3); + /// It takes a firm press to paint wide (for a soft pen or a heavy hand). + pub const FIRM: PressureCurve = fixed([[0.0, 0.0], [0.6, 0.3], [1.0, 1.0]], 3); + + /// A curve from untrusted points: non-finite ones dropped, clamped to `0..=1`, sorted, + /// merged when closer than 0.02 in input, at most [`MAX_CURVE_POINTS`], and given ends at + /// input 0 and 1 (holding the nearest point's output). No points: linear. + pub fn new(points: &[[f32; 2]]) -> PressureCurve { + let mut v: Vec<[f32; 2]> = points.iter().take(MAX_CURVE_POINTS * 8).filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| [p[0].clamp(0.0, 1.0), p[1].clamp(0.0, 1.0)]).collect(); + if v.is_empty() { + return PressureCurve::LINEAR; + } + v.sort_by(|a, b| a[0].total_cmp(&b[0])); + let mut out: Vec<[f32; 2]> = Vec::with_capacity(v.len() + 2); + for p in v { + match out.last_mut() { + Some(last) if p[0] - last[0] < MERGE => last[1] = p[1], + _ => out.push(p), + } + } + // Ends at 0 and 1: snap a point that is nearly there, else add one. + if let Some(first) = out.first_mut() { + if first[0] < MERGE { + first[0] = 0.0; + } else { + let y = first[1]; + out.insert(0, [0.0, y]); + } + } + if let Some(last) = out.last_mut() { + if last[0] > 1.0 - MERGE { + last[0] = 1.0; + } else { + let y = last[1]; + out.push([1.0, y]); + } + } + // Keep the ends and the first interior points that fit. + if out.len() > MAX_CURVE_POINTS + && let Some(end) = out.last().copied() + { + out.truncate(MAX_CURVE_POINTS - 1); + out.push(end); + } + let mut pts = [[0.0; 2]; MAX_CURVE_POINTS]; + for (slot, p) in pts.iter_mut().zip(&out) { + *slot = *p; + } + PressureCurve { n: out.len().min(MAX_CURVE_POINTS) as u8, pts } + } + + /// A built-in curve by key (`linear`, `soft`, `firm`). + pub fn preset(key: &str) -> Option { + match key { + "linear" => Some(PressureCurve::LINEAR), + "soft" => Some(PressureCurve::SOFT), + "firm" => Some(PressureCurve::FIRM), + _ => None, + } + } + + /// The built-in curve this is, if any. + pub fn preset_key(&self) -> Option<&'static str> { + CURVE_PRESETS.iter().map(|(k, _)| *k).find(|k| PressureCurve::preset(k).is_some_and(|c| c == *self)) + } + + pub fn points(&self) -> &[[f32; 2]] { + self.pts.get(..usize::from(self.n)).unwrap_or(&[]) + } + + /// The same curve with point `i` moved to `to` (the end points move only up and down) or, + /// with `i` past the end, a point added at `to`. + pub fn with_point(&self, i: usize, to: [f32; 2]) -> PressureCurve { + let mut v = self.points().to_vec(); + let last = v.len().saturating_sub(1); + match v.get_mut(i) { + Some(p) if i == 0 => p[1] = to[1], + Some(p) if i == last => p[1] = to[1], + // An interior point stays between its neighbours. + Some(p) => *p = to, + None => v.push(to), + } + PressureCurve::new(&v) + } + + /// Without interior point `i` (the ends stay). + pub fn without_point(&self, i: usize) -> PressureCurve { + let v: Vec<[f32; 2]> = self.points().iter().enumerate().filter(|(j, _)| *j != i || *j == 0 || *j + 1 == usize::from(self.n)).map(|(_, p)| *p).collect(); + PressureCurve::new(&v) + } + + /// The output at `pressure` (clamped to `0..=1`; not a number reads as full pressure). + pub fn map(&self, pressure: f32) -> f32 { + let x = if pressure.is_finite() { pressure.clamp(0.0, 1.0) } else { 1.0 }; + let p = self.points(); + let n = p.len(); + let (Some(first), Some(last)) = (p.first(), p.last()) else { return x }; + if n == 1 || x <= first[0] { + return first[1]; + } + if x >= last[0] { + return last[1]; + } + // Secant slopes, then Fritsch–Carlson tangents. + let sec = |i: usize| -> f32 { + match (p.get(i), p.get(i + 1)) { + (Some(a), Some(b)) if b[0] - a[0] > 1e-9 => (b[1] - a[1]) / (b[0] - a[0]), + _ => 0.0, + } + }; + let tangent = |i: usize| -> f32 { + if i == 0 { + return sec(0); + } + if i + 1 >= n { + return sec(n.saturating_sub(2)); + } + let (d0, d1) = (sec(i - 1), sec(i)); + if d0 * d1 <= 0.0 { + return 0.0; + } + // The weighted harmonic mean of the secants (Fritsch–Butland): monotone as it is. + let h = |j: usize| match (p.get(j), p.get(j + 1)) { + (Some(a), Some(b)) => (b[0] - a[0]).max(1e-6), + _ => 1e-6, + }; + let (h0, h1) = (h(i - 1), h(i)); + 3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1) + }; + let k = p.windows(2).position(|w| matches!(w, [a, b] if x >= a[0] && x <= b[0])).unwrap_or(0); + let (Some(a), Some(b)) = (p.get(k), p.get(k + 1)) else { return x }; + let h = b[0] - a[0]; + if h <= 1e-9 { + return b[1]; + } + let d = sec(k); + let (mut m0, mut m1) = (tangent(k), tangent(k + 1)); + // Keep the piece monotone where the data is (Fritsch–Carlson's limit). + if d == 0.0 { + m0 = 0.0; + m1 = 0.0; + } else { + let (al, be) = (m0 / d, m1 / d); + let s = al * al + be * be; + if s > 9.0 { + let t = 3.0 / s.sqrt(); + m0 = t * al * d; + m1 = t * be * d; + } + if al < 0.0 { + m0 = 0.0; + } + if be < 0.0 { + m1 = 0.0; + } + } + let t = (x - a[0]) / h; + let (t2, t3) = (t * t, t * t * t); + let y = (2.0 * t3 - 3.0 * t2 + 1.0) * a[1] + (t3 - 2.0 * t2 + t) * h * m0 + (-2.0 * t3 + 3.0 * t2) * b[1] + (t3 - t2) * h * m1; + y.clamp(0.0, 1.0) + } +} + +impl From> for PressureCurve { + fn from(v: Vec<[f32; 2]>) -> PressureCurve { + PressureCurve::new(&v) + } +} + +impl From for Vec<[f32; 2]> { + fn from(c: PressureCurve) -> Vec<[f32; 2]> { + c.points().to_vec() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_map_as_named() { + for x in [0.0, 0.1, 0.25, 0.5, 0.8, 1.0] { + assert!((PressureCurve::LINEAR.map(x) - x).abs() < 1e-5, "linear at {x}"); + } + // Soft paints wider than linear at a light touch, firm narrower; all meet at the ends. + for x in [0.1, 0.3, 0.5, 0.7, 0.9] { + assert!(PressureCurve::SOFT.map(x) > x + 0.02 && PressureCurve::FIRM.map(x) < x - 0.02, "{x}"); + } + for c in [PressureCurve::SOFT, PressureCurve::FIRM] { + assert_eq!((c.map(0.0), c.map(1.0)), (0.0, 1.0)); + assert!((c.map(0.3) - c.points()[1][1]).abs() < 1e-5 || (c.map(0.6) - c.points()[1][1]).abs() < 1e-5, "passes through its point"); + } + assert_eq!(PressureCurve::preset("soft").and_then(|c| c.preset_key()), Some("soft")); + assert_eq!(PressureCurve::new(&[[0.0, 0.2], [1.0, 0.9]]).preset_key(), None); + } + + #[test] + fn rising_curves_never_dip_or_overshoot() { + let c = PressureCurve::new(&[[0.0, 0.0], [0.1, 0.9], [0.15, 0.92], [1.0, 1.0]]); + let mut prev = -1.0; + for i in 0..=1000 { + let y = c.map(i as f32 / 1000.0); + assert!(y >= prev - 1e-6 && (0.0..=1.0).contains(&y), "at {i}: {y} after {prev}"); + prev = y; + } + } + + #[test] + fn untrusted_points_are_sanitized() { + let c = PressureCurve::new(&[[f32::NAN, 0.0], [0.5, 2.0], [0.51, 0.4], [-3.0, 0.1]]); + // (-3, 0.1) clamps to (0, 0.1); 0.5 and 0.51 merge (the last wins); an end at 1 holds. + assert_eq!(c.points(), &[[0.0, 0.1], [0.5, 0.4], [1.0, 0.4]]); + assert_eq!(PressureCurve::new(&[]), PressureCurve::LINEAR); + let many: Vec<[f32; 2]> = (0..100).map(|i| [i as f32 / 99.0, 0.5]).collect(); + let c = PressureCurve::new(&many); + assert!(c.points().len() <= MAX_CURVE_POINTS && c.points().last() == Some(&[1.0, 0.5])); + assert_eq!(c.map(f32::NAN), 0.5); + // Moving the end points only moves them up and down; adding and removing. + let c = PressureCurve::LINEAR.with_point(0, [0.7, 0.2]); + assert_eq!(c.points(), &[[0.0, 0.2], [1.0, 1.0]]); + let c = c.with_point(9, [0.5, 0.9]); + assert_eq!(c.points().len(), 3); + assert_eq!(c.without_point(1).points().len(), 2); + assert_eq!(c.without_point(0).points().len(), 3, "ends stay"); + // A file's curve round-trips. + let json = serde_json::to_string(&PressureCurve::SOFT).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), PressureCurve::SOFT); + } +} diff --git a/crates/geom/src/raw.rs b/crates/geom/src/raw.rs index e5f66f93..b1f7a057 100644 --- a/crates/geom/src/raw.rs +++ b/crates/geom/src/raw.rs @@ -180,6 +180,298 @@ pub fn anchors_at(path: &mut Path, p: Vec2, tol: f32) -> Vec { } } +// ----- points shared by several shapes (ADR 0045) ------------------------------------------------ + +/// One segment of a subpath: a cubic, and whether it is a straight line (kept a line when the path +/// is written back). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Seg { + pub c: Cubic, + pub line: bool, +} + +impl Seg { + pub fn line(a: Vec2, b: Vec2) -> Seg { + Seg { c: [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b], line: true } + } + /// The same segment run the other way. + pub fn reversed(&self) -> Seg { + Seg { c: [self.c[3], self.c[2], self.c[1], self.c[0]], line: self.line } + } +} + +/// A subpath as its segments, each starting where the one before ends. A closed one ends where +/// it starts. +#[derive(Clone, Debug, PartialEq)] +pub struct Sub { + pub segs: Vec, + pub closed: bool, +} + +/// `path` as subpaths (a `Close` that draws an edge back to the start gets that edge as a line; +/// a lone move is dropped). +pub fn subpaths(path: &Path) -> Vec { + let mut p = path.clone(); + p.close_explicitly(); + let mut out: Vec = Vec::new(); + let mut cur: Option = None; + for k in 0..p.cmds.len().min(MAX_CMDS) { + match p.cmds.get(k) { + Some(PathCmd::MoveTo(_)) => { + out.extend(cur.take().filter(|s| !s.segs.is_empty())); + cur = Some(Sub { segs: Vec::new(), closed: false }); + } + Some(PathCmd::Close) => { + if let Some(mut s) = cur.take().filter(|s| !s.segs.is_empty()) { + s.closed = true; + out.push(s); + } + } + Some(cmd) => { + if let Some(c) = segment_cubic(&p, k) { + let seg = Seg { c, line: matches!(cmd, PathCmd::LineTo(_)) }; + cur.get_or_insert_with(|| Sub { segs: Vec::new(), closed: false }).segs.push(seg); + } + } + None => break, + } + } + out.extend(cur.filter(|s| !s.segs.is_empty())); + out +} + +/// The path of `subs` (lines as lines, everything else as cubics). +pub fn from_subpaths(subs: &[Sub]) -> Path { + let mut p = Path::new(); + for s in subs { + let Some(first) = s.segs.first() else { continue }; + p.move_to(first.c[0]); + for g in &s.segs { + if g.line { + p.line_to(g.c[3]); + } else { + p.cubic_to(g.c[1], g.c[2], g.c[3]); + } + } + if s.closed { + p.close(); + } + } + p +} + +/// The segments of `subs` that start or end at `at` (within `tol`), each as the edge leaving +/// `at` (reversed when it ends there). +pub fn edges_at(subs: &[Sub], at: Vec2, tol: f32) -> Vec { + let mut out = Vec::new(); + for s in subs { + for g in &s.segs { + if g.c[0].distance(at) <= tol { + out.push(*g); + } + if g.c[3].distance(at) <= tol { + out.push(g.reversed()); + } + } + } + out +} + +/// Whether two edges leaving one anchor are the same edge: their far ends and points along them +/// within `tol`. +pub fn same_edge(a: &Seg, b: &Seg, tol: f32) -> bool { + a.c[3].distance(b.c[3]) <= tol && [0.25f32, 0.5, 0.75].iter().all(|&t| cubic_point(&a.c, t).distance(cubic_point(&b.c, t)) <= tol * 2.0) +} + +/// The edges among `edges` that are distinct ([`same_edge`]), in order. +pub fn distinct_edges(edges: impl IntoIterator, tol: f32) -> Vec { + let mut out: Vec = Vec::new(); + for e in edges { + if !out.iter().any(|x| same_edge(x, &e, tol)) { + out.push(e); + } + } + out +} + +/// The one edge in place of the edges `a` and `b` that leave an anchor: from `a`'s far end to +/// `b`'s. Two lines make a line; anything else the cubic that fits both best, keeping the +/// directions they leave their far ends in ([`Path::merge_at`]'s fit). +pub fn join(a: &Seg, b: &Seg) -> Option { + if a.line && b.line { + return Some(Seg::line(a.c[3], b.c[3])); + } + let c = crate::edit::merge_cubics(a.reversed().c, b.c)?; + Some(Seg { c, line: false }) +} + +/// The edges `a` and `b` that leave one anchor, made smooth there: their handles at the anchor on +/// one line, along the direction from `a`'s far end to `b`'s, each a third of its edge's chord +/// long ([`Path::make_smooth`]). `None` when the far ends coincide. +pub fn smooth_pair(a: &Seg, b: &Seg) -> Option<(Seg, Seg)> { + let at = a.c[0]; + let dir = (b.c[3] - a.c[3]).normalized(); + if dir == Vec2::ZERO { + return None; + } + let ha = at - dir * (at.distance(a.c[3]) / 3.0); + let hb = at + dir * (at.distance(b.c[3]) / 3.0); + let (na, nb) = (Seg { c: [at, ha, a.c[2], a.c[3]], line: false }, Seg { c: [at, hb, b.c[2], b.c[3]], line: false }); + (na.c.iter().chain(&nb.c).all(|p| p.is_finite())).then_some((na, nb)) +} + +/// `e` (leaving an anchor) with its handle at the anchor drawn in onto it: a corner there. `None` +/// when it has none to draw in (a line, or a handle already on the anchor). +pub fn corner(e: &Seg) -> Option { + (!e.line && e.c[1].distance(e.c[0]) > 1e-4).then_some(Seg { c: [e.c[0], e.c[0], e.c[2], e.c[3]], line: false }) +} + +/// Handles at one anchor lying on one line, on opposite sides, within this angle's sine (3°): a +/// smooth anchor. +const SMOOTH_SIN: f32 = 0.052; + +/// Whether the handles `h` and `k` of the anchor `a` make it smooth: both off the anchor, on one +/// line through it, on opposite sides. +pub fn smooth_at(a: Vec2, h: Vec2, k: Vec2) -> bool { + let (u, v) = (h - a, k - a); + let (lu, lv) = (u.length(), v.length()); + lu > 1e-4 && lv > 1e-4 && u.dot(v) < 0.0 && (u.cross(v) / (lu * lv)).abs() <= SMOOTH_SIN +} + +/// `k` turned about the anchor `a` so it lies opposite `h`, keeping its length (the other handle +/// of a smooth anchor while `h` is dragged). `k` itself when `h` is on the anchor. +pub fn turned_opposite(a: Vec2, h: Vec2, k: Vec2) -> Vec2 { + let dir = (h - a).normalized(); + if dir == Vec2::ZERO { + return k; + } + a - dir * a.distance(k) +} + +/// Deletes the anchor at `at` (within `tol`) from `subs`, where the drawing has the distinct +/// edges `edges` leaving it. +/// +/// * Two edges: every copy of either becomes `joined` (the edge from the first's far end to the +/// second's, see [`join`]). A run through the anchor takes it once in place of both; a line +/// ending there now runs along the whole new edge, so the drawing stays connected. +/// * One edge (the free end of lines): the segment there goes. +/// +/// Returns whether anything changed. Subpaths may be left empty or flat: see [`tidy`]. +pub fn delete_anchor(subs: &mut [Sub], at: Vec2, edges: &[Seg], joined: Option<&Seg>, tol: f32) -> bool { + let which = |e: &Seg| edges.iter().position(|x| same_edge(x, e, tol)); + let toward = |from: usize| -> Option { + // The new edge leaving the far end of edge `from` (towards the other edge's far end). + let j = joined?; + Some(if from == 0 { *j } else { j.reversed() }) + }; + let mut changed = false; + for s in subs.iter_mut() { + // Each pass takes one vertex at `at`; bounded by the segments there are. + for _ in 0..=s.segs.len() { + let Some(step) = vertex_at(s, at, tol) else { break }; + let done = match step { + Vertex::Through(v) => { + // in: segs[v - 1] arrives, out: segs[v] leaves (v ≥ 1 after rotation). + let (Some(inn), Some(out)) = (s.segs.get(v - 1).copied(), s.segs.get(v).copied()) else { break }; + match (which(&inn.reversed()), which(&out), edges.len()) { + (Some(a), Some(b), 2) if a != b => match toward(a) { + Some(n) => { + s.segs.splice(v - 1..=v, [n]); + true + } + None => false, + }, + _ => false, + } + } + Vertex::Start => match (s.segs.first().and_then(which), edges.len()) { + // The new first segment ends where the old one did. + (Some(a), 2) => match (toward(1 - a), s.segs.first_mut()) { + (Some(n), Some(first)) => { + *first = n; + true + } + _ => false, + }, + (Some(_), 1) => { + s.segs.remove(0); + true + } + _ => false, + }, + Vertex::End => { + match (s.segs.last().and_then(|g| which(&g.reversed())), edges.len()) { + (Some(a), 2) => match (toward(a), s.segs.last_mut()) { + (Some(n), Some(last)) => { + *last = n; + true + } + _ => false, + }, + (Some(_), 1) => { + s.segs.pop(); + true + } + _ => false, + } + } + }; + if !done { + break; + } + changed = true; + } + } + changed +} + +/// Where a subpath has a vertex at a point. +enum Vertex { + /// Between segments `v - 1` and `v` (a closed subpath is turned so `v ≥ 1`). + Through(usize), + /// An open subpath's start or end. + Start, + End, +} + +fn vertex_at(s: &mut Sub, at: Vec2, tol: f32) -> Option { + let n = s.segs.len(); + if n == 0 { + return None; + } + if s.closed { + let v = s.segs.iter().position(|g| g.c[0].distance(at) <= tol)?; + // Turn the loop so the vertex is not at the seam. + let turn = if v == 0 { n - 1 } else { 0 }; + s.segs.rotate_left(turn); + return Some(Vertex::Through(if v == 0 { 1 } else { v })); + } + if s.segs.first().is_some_and(|g| g.c[0].distance(at) <= tol) { + return Some(Vertex::Start); + } + if s.segs.last().is_some_and(|g| g.c[3].distance(at) <= tol) { + return Some(Vertex::End); + } + (1..n).find(|&v| s.segs.get(v).is_some_and(|g| g.c[0].distance(at) <= tol)).map(Vertex::Through) +} + +/// Drops the subpaths an edit left with nothing to show: no segments, no length, or (when +/// `filled`) a closed outline with no area. +pub fn tidy(subs: &mut Vec, filled: bool) { + subs.retain(|s| { + let pts: Vec = s.segs.iter().flat_map(|g| (0..8).map(move |i| cubic_point(&g.c, i as f32 / 8.0))).chain(s.segs.last().map(|g| g.c[3])).collect(); + let length: f32 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.distance(*b))).sum(); + if s.segs.is_empty() || length <= 1e-3 { + return false; + } + if filled && s.closed { + let area: f32 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.cross(*b))).sum::() * 0.5; + return area.abs() > 1e-3; + } + true + }); +} + #[cfg(test)] mod tests { use super::*; @@ -235,6 +527,110 @@ mod tests { assert!(anchors_at(&mut p, Vec2::new(40.0, 5.0), 0.2).is_empty()); } + fn v(x: f32, y: f32) -> Vec2 { + Vec2::new(x, y) + } + + #[test] + fn subpaths_round_trip() { + let mut p = Path::rect(0.0, 0.0, 10.0, 10.0); + p.move_to(v(20.0, 0.0)).cubic_to(v(20.0, 5.0), v(25.0, 10.0), v(30.0, 10.0)); + let subs = subpaths(&p); + assert_eq!(subs.len(), 2); + assert!(subs[0].closed && subs[0].segs.len() == 4 && subs[0].segs.iter().all(|g| g.line), "the closing edge is written out: {:?}", subs[0]); + assert!(!subs[1].closed && !subs[1].segs[0].line); + let back = subpaths(&from_subpaths(&subs)); + assert_eq!(back, subs); + } + + /// A raw rectangle as merge drawing stores it: the fill and four sides, each its own path. + fn outlined_rect() -> Vec> { + let (a, b, c, d) = (v(0.0, 0.0), v(100.0, 0.0), v(100.0, 80.0), v(0.0, 80.0)); + // The fill starts at the corner deleted below, to cover the seam. + let fill = vec![Sub { segs: vec![Seg::line(a, b), Seg::line(b, c), Seg::line(c, d), Seg::line(d, a)], closed: true }]; + let side = |p, q| vec![Sub { segs: vec![Seg::line(p, q)], closed: false }]; + vec![fill, side(a, b), side(b, c), side(c, d), side(d, a)] + } + + fn delete(shapes: &mut [Vec], at: Vec2) -> usize { + let edges = distinct_edges(shapes.iter().flat_map(|s| edges_at(s, at, 0.2)), 0.2); + let joined = if edges.len() == 2 { join(&edges[0], &edges[1]) } else { None }; + shapes.iter_mut().map(|s| delete_anchor(s, at, &edges, joined.as_ref(), 0.2)).filter(|c| *c).count() + } + + #[test] + fn deleting_a_corner_keeps_the_drawing_connected() { + let mut shapes = outlined_rect(); + let edges = distinct_edges(shapes.iter().flat_map(|s| edges_at(s, v(0.0, 0.0), 0.2)), 0.2); + assert_eq!(edges.len(), 2, "two edges meet at a corner, each in the fill and a side"); + assert_eq!(delete(&mut shapes, v(0.0, 0.0)), 3, "the fill and both sides there"); + // The fill is a triangle now, cut along the diagonal from (0, 80) to (100, 0). + let fill = &shapes[0][0]; + assert!(fill.closed && fill.segs.len() == 3 && fill.segs.iter().all(|g| g.line), "{fill:?}"); + assert!(fill.segs.iter().all(|g| g.c[0].distance(v(0.0, 0.0)) > 1.0)); + // Both sides that ended there now run along the diagonal: every anchor is shared. + let diag = Seg::line(v(0.0, 80.0), v(100.0, 0.0)); + for s in [&shapes[1], &shapes[4]] { + let g = s[0].segs[0]; + assert!(same_edge(&g, &diag, 0.01) || same_edge(&g.reversed(), &diag, 0.01), "{g:?}"); + } + let anchors: Vec = shapes.iter().flatten().flat_map(|s| s.segs.iter().flat_map(|g| [g.c[0], g.c[3]])).collect(); + for p in &anchors { + assert!(anchors.iter().filter(|q| q.distance(*p) < 1e-3).count() >= 2, "{p:?} is on one shape only"); + } + } + + #[test] + fn deleting_a_point_that_splitting_added_gives_the_curve_back() { + let arc = Seg { c: [v(0.0, 0.0), v(0.0, -60.0), v(100.0, -60.0), v(100.0, 0.0)], line: false }; + let (a, b) = (sub(&arc.c, 0.0, 0.35), sub(&arc.c, 0.35, 1.0)); + let at = a[3]; + // A fill under the arc and the arc's own stroke, both with the point. + let fill = vec![Sub { segs: vec![Seg { c: a, line: false }, Seg { c: b, line: false }, Seg::line(v(100.0, 0.0), v(0.0, 0.0))], closed: true }]; + let stroke = vec![Sub { segs: vec![Seg { c: b, line: false }.reversed(), Seg { c: a, line: false }.reversed()], closed: false }]; + let mut shapes = vec![fill, stroke]; + assert_eq!(delete(&mut shapes, at), 2); + let (f, s) = (shapes[0][0].segs[0], shapes[1][0].segs[0]); + assert_eq!((shapes[0][0].segs.len(), shapes[1][0].segs.len()), (2, 1)); + for t in [0.1f32, 0.3, 0.5, 0.7, 0.9] { + assert!(nearest(&f.c, cubic_point(&arc.c, t)).1 < 0.05, "fill off the old curve at {t}"); + } + assert!(same_edge(&f, &s.reversed(), 1e-3), "the fill and the stroke keep one edge"); + } + + #[test] + fn deleting_a_free_end_shortens_the_line_and_its_last_point_removes_it() { + let mut shapes = vec![vec![Sub { segs: vec![Seg::line(v(0.0, 0.0), v(50.0, 0.0)), Seg::line(v(50.0, 0.0), v(50.0, 50.0))], closed: false }]]; + assert_eq!(delete(&mut shapes, v(50.0, 50.0)), 1); + assert_eq!(shapes[0][0].segs.len(), 1); + assert_eq!(delete(&mut shapes, v(50.0, 0.0)), 1); + tidy(&mut shapes[0], false); + assert!(shapes[0].is_empty()); + // A triangle's fill losing a corner has no area left. + let tri = |a, b, c| vec![Sub { segs: vec![Seg::line(a, b), Seg::line(b, c), Seg::line(c, a)], closed: true }]; + let mut t = vec![tri(v(0.0, 0.0), v(10.0, 0.0), v(5.0, 9.0))]; + assert_eq!(delete(&mut t, v(5.0, 9.0)), 1); + tidy(&mut t[0], true); + assert!(t[0].is_empty(), "{:?}", t[0]); + } + + #[test] + fn smooth_and_corner_handles() { + let (a, b) = (Seg::line(v(0.0, 0.0), v(-30.0, 10.0)), Seg::line(v(0.0, 0.0), v(40.0, 10.0))); + let Some((sa, sb)) = smooth_pair(&a, &b) else { panic!("no pair") }; + assert!(smooth_at(v(0.0, 0.0), sa.c[1], sb.c[1]), "{sa:?} {sb:?}"); + assert!((sa.c[1].distance(v(0.0, 0.0)) - a.c[3].length() / 3.0).abs() < 1e-3); + assert_eq!((sa.c[3], sb.c[3]), (a.c[3], b.c[3]), "far ends stay"); + let Some(c) = corner(&sa) else { panic!("a curve has a handle") }; + assert_eq!(c.c[1], c.c[0]); + assert!(corner(&a).is_none() && corner(&c).is_none(), "nothing to draw in"); + // Dragging one handle of a smooth anchor turns the other with it, keeping its length. + let k = turned_opposite(v(0.0, 0.0), v(0.0, 10.0), v(20.0, 0.0)); + assert!(k.distance(v(0.0, -20.0)) < 1e-4, "{k:?}"); + assert!(!smooth_at(v(0.0, 0.0), v(10.0, 0.0), v(0.0, 10.0)), "a corner"); + assert!(!smooth_at(v(0.0, 0.0), v(10.0, 0.0), v(20.0, 0.1)), "same side"); + } + #[test] fn nearest_finds_the_closest_point_on_a_curve() { let c = [Vec2::new(0.0, 0.0), Vec2::new(0.0, 50.0), Vec2::new(100.0, 50.0), Vec2::new(100.0, 0.0)]; diff --git a/crates/geom/src/slice.rs b/crates/geom/src/slice.rs new file mode 100644 index 00000000..357e32bb --- /dev/null +++ b/crates/geom/src/slice.rs @@ -0,0 +1,428 @@ +//! 9-slice scaling (ADR 0055): a box cut by four guides into corners, edges and a centre, scaled +//! so the corners keep their size, the edges stretch one way and the centre both ways. +//! +//! The map is separable: each axis is three linear pieces ([`Axis`]). Within one of the nine +//! cells it is affine, so a Bézier piece that stays in one cell maps exactly by mapping its +//! control points. [`slice_path`] cuts every segment where it crosses a guide (de Casteljau at the +//! exact crossing parameters) and maps each piece with its cell's affine; at a guide both cells +//! agree, so the result stays connected. + +use crate::{Affine, Path, PathCmd, Vec2}; + +/// One axis of a 9-slice map: the source stops `[lo, a, b, hi]` (the box's edges and the two +/// guides) and where they land. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Axis { + from: [f32; 4], + to: [f32; 4], +} + +impl Axis { + /// The axis of a box `lo..hi` with guides at `a` and `b`, scaled by `k` (at least 0) about the + /// origin: the box lands where plain scaling puts it (`k·lo..k·hi`), the parts outside the + /// guides keep their size and the centre takes the rest. When the rest would be negative the + /// two outer parts share what there is, in proportion, and the centre closes. + /// + /// Guides outside the box are clamped into it (and `b` to at least `a`). `None` for an empty + /// box, a negative scale or anything not finite. + pub fn new(lo: f32, a: f32, b: f32, hi: f32, k: f32) -> Option { + if ![lo, a, b, hi, k].iter().all(|v| v.is_finite()) || hi <= lo || k < 0.0 { + return None; + } + let a = a.clamp(lo, hi); + let b = b.clamp(a, hi); + let (near, far) = (a - lo, hi - b); + let (tlo, thi) = (k * lo, k * hi); + let room = thi - tlo; + let edges = near + far; + let (near, far) = if edges > room && edges > 0.0 { (near * room / edges, far * room / edges) } else { (near, far) }; + let to = [tlo, tlo + near, thi - far, thi]; + to.iter().all(|v| v.is_finite()).then_some(Axis { from: [lo, a, b, hi], to }) + } + + /// The identity map on `lo..hi` (what an unscaled axis is). + pub fn identity(lo: f32, hi: f32) -> Axis { + Axis { from: [lo, lo, hi, hi], to: [lo, lo, hi, hi] } + } + + /// The two guides, in source space. + pub fn guides(&self) -> [f32; 2] { + [self.from[1], self.from[2]] + } + + /// Which piece `v` is in: 0 before the first guide, 1 between them, 2 after the second. + pub fn piece(&self, v: f32) -> usize { + if v < self.from[1] { + 0 + } else if v <= self.from[2] { + 1 + } else { + 2 + } + } + + /// Piece `i` as `v ↦ scale · v + offset`. The outer pieces carry on past the box's edges + /// with their own slope; a piece of no width has the slope of plain scaling (nothing lies in + /// it but its edge, which maps right either way). + pub fn linear(&self, i: usize) -> (f32, f32) { + let i = i.min(2); + let (f0, f1) = (self.from[i], self.from[i + 1]); + let (t0, t1) = (self.to[i], self.to[i + 1]); + let whole = (self.to[3] - self.to[0]) / (self.from[3] - self.from[0]).max(f32::MIN_POSITIVE); + let scale = if f1 - f0 > 1e-6 { (t1 - t0) / (f1 - f0) } else { whole }; + // Anchored where the piece starts (the outer ones at their guide, so they meet the centre). + let (anchor, at) = if i == 0 { (f1, t1) } else { (f0, t0) }; + (scale, at - scale * anchor) + } + + /// Where `v` lands. + pub fn map(&self, v: f32) -> f32 { + let (s, o) = self.linear(self.piece(v)); + s * v + o + } +} + +/// A whole 9-slice map: the horizontal and the vertical axis. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Slice9 { + pub x: Axis, + pub y: Axis, +} + +impl Slice9 { + pub fn map(&self, p: Vec2) -> Vec2 { + Vec2::new(self.x.map(p.x), self.y.map(p.y)) + } + + /// The affine map of the cell `(ix, iy)`. + pub fn cell(&self, ix: usize, iy: usize) -> Affine { + let (sx, ox) = self.x.linear(ix); + let (sy, oy) = self.y.linear(iy); + Affine { m: [sx, 0.0, 0.0, sy, ox, oy] } + } + + /// The cell a point is in. + fn cell_of(&self, p: Vec2) -> Affine { + self.cell(self.x.piece(p.x), self.y.piece(p.y)) + } +} + +/// Largest number of commands [`slice_path`] writes (a path that would grow past it is mapped +/// point by point instead, which is exact for straight edges and close for curves). +pub const MAX_SLICED_CMDS: usize = 4_000_000; + +/// `path` placed by `pre` (its own space to the box's) and then sliced by `map`: every segment cut +/// where it crosses a guide, each piece mapped by its cell's affine. Straight edges stay straight +/// within a cell, curves stay curves, fill areas stay closed (an implied closing line is drawn +/// out, since it may cross a guide). +pub fn slice_path(path: &Path, pre: &Affine, map: &Slice9) -> Path { + if path.cmds.len().saturating_mul(4) > MAX_SLICED_CMDS { + return path.transformed(pre).transformed_by(|p| map.map(p)); + } + let gx = map.x.guides(); + let gy = map.y.guides(); + let mut out = Vec::with_capacity(path.cmds.len() + 8); + let mut cur = Vec2::ZERO; + let mut start = Vec2::ZERO; + let mut ts: Vec = Vec::with_capacity(16); + for c in &path.cmds { + match *c { + PathCmd::MoveTo(p) => { + let p = pre.apply(p); + out.push(PathCmd::MoveTo(map.map(p))); + cur = p; + start = p; + } + PathCmd::LineTo(p) => { + let p = pre.apply(p); + pieces(&[cur, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::QuadTo(a, p) => { + let (a, p) = (pre.apply(a), pre.apply(p)); + pieces(&[cur, a, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::CubicTo(a, b, p) => { + let (a, b, p) = (pre.apply(a), pre.apply(b), pre.apply(p)); + pieces(&[cur, a, b, p], &gx, &gy, map, &mut ts, &mut out); + cur = p; + } + PathCmd::Close => { + if cur != start { + pieces(&[cur, start], &gx, &gy, map, &mut ts, &mut out); + } + out.push(PathCmd::Close); + cur = start; + } + } + } + Path { cmds: out } +} + +/// Writes segment `ctrl` (2, 3 or 4 control points: a line, a quadratic or a cubic) as its pieces +/// between guide crossings, each mapped by its cell. +fn pieces(ctrl: &[Vec2], gx: &[f32; 2], gy: &[f32; 2], map: &Slice9, ts: &mut Vec, out: &mut Vec) { + ts.clear(); + let xs: Vec = ctrl.iter().map(|p| p.x).collect(); + let ys: Vec = ctrl.iter().map(|p| p.y).collect(); + for g in gx { + crossings(&xs, *g, ts); + } + for g in gy { + crossings(&ys, *g, ts); + } + ts.sort_by(f32::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut t0 = 0.0; + for &t1 in ts.iter().chain(std::iter::once(&1.0)) { + if t1 - t0 < 1e-6 { + continue; + } + let part = sub(ctrl, t0, t1); + let mid = eval(ctrl, (t0 + t1) * 0.5); + let m = map.cell_of(mid); + push(&part, &m, out); + t0 = t1; + } +} + +fn push(part: &[Vec2], m: &Affine, out: &mut Vec) { + match *part { + [_, p] => out.push(PathCmd::LineTo(m.apply(p))), + [_, a, p] => out.push(PathCmd::QuadTo(m.apply(a), m.apply(p))), + [_, a, b, p] => out.push(PathCmd::CubicTo(m.apply(a), m.apply(b), m.apply(p))), + _ => {} + } +} + +/// The point at `t` (de Casteljau). +fn eval(ctrl: &[Vec2], t: f32) -> Vec2 { + let mut p = [Vec2::ZERO; 4]; + let n = ctrl.len().min(4); + p[..n].copy_from_slice(&ctrl[..n]); + for k in (1..n).rev() { + for i in 0..k { + p[i] = p[i].lerp(p[i + 1], t); + } + } + p[0] +} + +/// The piece of the curve between `t0` and `t1`, as control points of the same degree. +fn sub(ctrl: &[Vec2], t0: f32, t1: f32) -> Vec { + // Split at t1, keep the first part; then split that at t0 / t1, keep the second. + let first = split(ctrl, t1).0; + if t0 <= 0.0 { + return first; + } + let u = if t1 > 1e-12 { t0 / t1 } else { 0.0 }; + split(&first, u).1 +} + +/// De Casteljau split at `t`: the two halves. +fn split(ctrl: &[Vec2], t: f32) -> (Vec, Vec) { + // Each level is one point shorter: the first and last points of every level are the halves'. + let n = ctrl.len().min(4); + let mut work = [Vec2::ZERO; 4]; + work[..n].copy_from_slice(&ctrl[..n]); + let mut left = Vec::with_capacity(n); + let mut right = Vec::with_capacity(n); + for k in (0..n).rev() { + left.push(work[0]); + right.push(work[k]); + for i in 0..k { + work[i] = work[i].lerp(work[i + 1], t); + } + } + right.reverse(); + (left, right) +} + +/// Adds every `t` in (0, 1) where the 1-D Bézier `c` (2 to 4 coefficients) equals `v`: the curve +/// is cut where its derivative is zero into monotone runs, and each run that crosses `v` is +/// bisected. Exact to `f32`, at most three crossings per guide. +fn crossings(c: &[f32], v: f32, ts: &mut Vec) { + let f = |t: f32| bez1(c, t) - v; + let mut stops = [0.0f32; 4]; + let mut n = 0; + stops[n] = 0.0; + n += 1; + if let [x0, x1, x2, x3] = *c { + // Derivative (a quadratic) in power form: A t² + B t + C. + let (q0, q1, q2) = (3.0 * (x1 - x0), 3.0 * (x2 - x1), 3.0 * (x3 - x2)); + let (a, b, cc) = (q0 - 2.0 * q1 + q2, 2.0 * (q1 - q0), q0); + let mut roots = [f32::NAN; 2]; + if a.abs() > 1e-12 { + let disc = b * b - 4.0 * a * cc; + if disc >= 0.0 { + let s = disc.sqrt(); + roots = [(-b - s) / (2.0 * a), (-b + s) / (2.0 * a)]; + } + } else if b.abs() > 1e-12 { + roots[0] = -cc / b; + } + roots.sort_by(f32::total_cmp); + for r in roots { + if r > 0.0 && r < 1.0 && n < 3 { + stops[n] = r; + n += 1; + } + } + } else if let [x0, x1, x2] = *c { + let den = x0 - 2.0 * x1 + x2; + if den.abs() > 1e-12 { + let r = (x0 - x1) / den; + if r > 0.0 && r < 1.0 { + stops[n] = r; + n += 1; + } + } + } + stops[n] = 1.0; + n += 1; + for w in stops[..n].windows(2) { + let (mut lo, mut hi) = (w[0], w[1]); + let (flo, fhi) = (f(lo), f(hi)); + if !(flo.is_finite() && fhi.is_finite()) || flo == 0.0 || fhi == 0.0 || (flo > 0.0) == (fhi > 0.0) { + continue; + } + let rising = fhi > flo; + for _ in 0..40 { + let mid = 0.5 * (lo + hi); + if (f(mid) > 0.0) == rising { + hi = mid; + } else { + lo = mid; + } + } + let t = 0.5 * (lo + hi); + if t > 1e-6 && t < 1.0 - 1e-6 { + ts.push(t); + } + } +} + +fn bez1(c: &[f32], t: f32) -> f32 { + let u = 1.0 - t; + match *c { + [a, b] => u * a + t * b, + [a, b, d] => u * u * a + 2.0 * u * t * b + t * t * d, + [a, b, d, e] => u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * d + t * t * t * e, + _ => 0.0, + } +} + +impl Path { + /// Every point mapped by `f` (any map, not only an affine one). + pub fn transformed_by(&self, f: impl Fn(Vec2) -> Vec2) -> Path { + Path { + cmds: self + .cmds + .iter() + .map(|c| match *c { + PathCmd::MoveTo(p) => PathCmd::MoveTo(f(p)), + PathCmd::LineTo(p) => PathCmd::LineTo(f(p)), + PathCmd::QuadTo(a, p) => PathCmd::QuadTo(f(a), f(p)), + PathCmd::CubicTo(a, b, p) => PathCmd::CubicTo(f(a), f(b), f(p)), + PathCmd::Close => PathCmd::Close, + }) + .collect(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-3 + } + + #[test] + fn an_axis_keeps_its_ends_and_gives_the_centre_the_rest() { + // A 100-wide box, 10 and 10 outside the guides, scaled 3x: 300 wide, 280 in the centre. + let ax = Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(); + assert!(close(ax.map(0.0), 0.0)); + assert!(close(ax.map(10.0), 10.0)); + assert!(close(ax.map(90.0), 290.0)); + assert!(close(ax.map(100.0), 300.0)); + assert!(close(ax.map(50.0), 150.0), "the centre scales by 280 / 80"); + // About the origin, as plain scaling: a box from -50 lands on -150..150. + let ax = Axis::new(-50.0, -40.0, 40.0, 50.0, 3.0).unwrap(); + assert!(close(ax.map(-50.0), -150.0) && close(ax.map(-40.0), -140.0) && close(ax.map(50.0), 150.0)); + } + + #[test] + fn no_spare_space_shares_what_there_is_and_closes_the_centre() { + // Corners 10 + 30 = 40 of a 100 box, scaled to 20: they shrink to 5 and 15. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.2).unwrap(); + assert!(close(ax.map(10.0), 5.0) && close(ax.map(70.0), 5.0) && close(ax.map(100.0), 20.0)); + // Exactly no spare space: the centre is a line. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.4).unwrap(); + assert!(close(ax.map(10.0), 10.0) && close(ax.map(70.0), 10.0) && close(ax.map(100.0), 40.0)); + // Zero scale: everything at the origin. + let ax = Axis::new(0.0, 10.0, 70.0, 100.0, 0.0).unwrap(); + assert!(close(ax.map(0.0), 0.0) && close(ax.map(100.0), 0.0)); + // Guides outside or crossed are clamped; bad numbers give nothing. + let ax = Axis::new(0.0, -20.0, 140.0, 100.0, 2.0).unwrap(); + assert!(close(ax.map(50.0), 100.0)); + assert!(Axis::new(0.0, 10.0, 90.0, 0.0, 2.0).is_none()); + assert!(Axis::new(0.0, 10.0, 90.0, 100.0, -1.0).is_none()); + assert!(Axis::new(0.0, f32::NAN, 90.0, 100.0, 1.0).is_none()); + } + + #[test] + fn a_line_across_the_guides_is_cut_there() { + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(), y: Axis::new(0.0, 10.0, 30.0, 40.0, 1.0).unwrap() }; + let p = slice_path(&Path::line(Vec2::new(0.0, 20.0), Vec2::new(100.0, 20.0)), &Affine::IDENTITY, &map); + let pts: Vec = p + .cmds + .iter() + .filter_map(|c| match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => Some(p), + _ => None, + }) + .collect(); + assert_eq!(pts.len(), 4); + for (got, want) in pts.iter().zip([0.0, 10.0, 290.0, 300.0]) { + assert!(close(got.x, want) && close(got.y, 20.0), "{got:?} vs {want}"); + } + } + + #[test] + fn a_closing_line_is_drawn_out_so_it_bends_at_the_guides() { + // A triangle whose closing edge runs diagonally across the left guide. + let p = Path { cmds: vec![PathCmd::MoveTo(Vec2::new(0.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 0.0)), PathCmd::LineTo(Vec2::new(100.0, 40.0)), PathCmd::Close] }; + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 3.0).unwrap(), y: Axis::identity(0.0, 40.0) }; + let s = slice_path(&p, &Affine::IDENTITY, &map); + assert_eq!(s.cmds.last(), Some(&PathCmd::Close)); + // Every vertex of the result is the map of a point on the source outline. + assert!(s.cmds.len() > p.cmds.len() + 2); + } + + #[test] + fn curves_are_cut_at_exact_crossings_and_stay_on_the_mapped_curve() { + let c = [Vec2::new(0.0, 0.0), Vec2::new(30.0, 60.0), Vec2::new(70.0, -20.0), Vec2::new(100.0, 40.0)]; + let p = Path { cmds: vec![PathCmd::MoveTo(c[0]), PathCmd::CubicTo(c[1], c[2], c[3])] }; + let map = Slice9 { x: Axis::new(0.0, 25.0, 75.0, 100.0, 2.5).unwrap(), y: Axis::new(-20.0, 0.0, 20.0, 60.0, 1.5).unwrap() }; + let s = slice_path(&p, &Affine::IDENTITY, &map); + // Sample the source curve; each sample's image must lie on the sliced path (within + // flattening tolerance): the piecewise-affine image of a Bézier is the pieces' Béziers. + let flat: Vec = s.flatten(&Affine::IDENTITY, 0.01).into_iter().flat_map(|l| l.points).collect(); + for i in 0..=50 { + let q = map.map(eval(&c, i as f32 / 50.0)); + let d = flat.windows(2).map(|w| crate::segment_distance(q, w[0], w[1])).fold(f32::INFINITY, f32::min); + assert!(d < 0.1, "sample {i}: {d}"); + } + } + + #[test] + fn the_pre_transform_places_the_path_first() { + let map = Slice9 { x: Axis::new(0.0, 10.0, 90.0, 100.0, 2.0).unwrap(), y: Axis::identity(0.0, 10.0) }; + let s = slice_path(&Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), &Affine::translate(90.0, 0.0), &map); + assert_eq!(s.cmds.first(), Some(&PathCmd::MoveTo(Vec2::new(190.0, 0.0)))); + assert!(matches!(s.cmds.last(), Some(PathCmd::LineTo(p)) if close(p.x, 200.0))); + } +} diff --git a/crates/geom/src/walk.rs b/crates/geom/src/walk.rs index 2c86818f..c310ec23 100644 --- a/crates/geom/src/walk.rs +++ b/crates/geom/src/walk.rs @@ -108,6 +108,19 @@ impl CurveWalk { (b.seg as usize, ta + (b.t - ta) * f) } + /// The distance along the path to the anchor that ends path command `cmd`, or 0 for the + /// start (a command before the first segment). `None` when `cmd` ends no segment the walk + /// measured. + pub fn anchor_distance(&self, cmd: usize) -> Option { + if self.segs.first().is_some_and(|(c, _)| cmd < *c) { + return Some(0.0); + } + let k = self.segs.binary_search_by_key(&cmd, |(c, _)| *c).ok()?; + // Segment k's samples end with its anchor (t = 1). + let j = self.samples.partition_point(|x| x.seg as usize <= k); + self.samples.get(j.checked_sub(1)?).map(|x| x.s) + } + /// The path command and curve parameter at distance `s`: where to split or bend the path. pub fn locate(&self, s: f32) -> (usize, f32) { let (k, t) = self.find(s); @@ -298,6 +311,12 @@ mod tests { assert!(w.at(125.0).distance(Vec2::new(110.0, 45.0)) < 1e-3); assert!(w.tangent(125.0).distance(Vec2::new(0.0, 1.0)) < 1e-5); assert_eq!(w.locate(125.0).0, 2, "the second line is command 2"); + // Anchors by distance: the start, the corner, the end; the walk lands on them exactly. + assert_eq!(w.anchor_distance(0), Some(0.0)); + let corner = w.anchor_distance(1).unwrap(); + assert!((corner - 100.0).abs() < 1e-3 && w.at(corner) == Vec2::new(110.0, 20.0), "{corner}"); + assert_eq!(w.anchor_distance(2), Some(w.length())); + assert_eq!(w.anchor_distance(3), None); assert!((w.project(Vec2::new(130.0, 60.0)) - 140.0).abs() < 1e-2); let tail = w.tail(50.0).unwrap(); let tw = CurveWalk::new(&tail).unwrap(); diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 9a0a5325..925b51b6 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -21,5 +21,9 @@ rayon.workspace = true web-time.workspace = true thiserror.workspace = true +[dev-dependencies] +# The shaders' types, to keep them free of what a backend leaves undefined (wgpu's own naga). +naga.workspace = true + [lints] workspace = true diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index b932f0fb..881ab0fa 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -1,19 +1,21 @@ -//! GPU stage timings and parity against the CPU oracle (ADR 0019, ADR 0029, ADR 0032; numbers +//! GPU stage timings and parity against the CPU oracle (ADR 0019, 0029, 0032, 0048; numbers //! in docs/performance.md). //! //! ```sh //! cargo run --release -p anicraft-gpu --example gpu_bench //! cargo run --release -p anicraft-gpu --example gpu_bench -- --layers 50 --shapes 200 +//! cargo run --release -p anicraft-gpu --example gpu_bench -- --only onion +//! cargo run --release -p anicraft-gpu --example gpu_bench -- --check # fails past a budget //! ``` -//! Prints the adapter, then for each scene and size: CPU ms; the first slice's read-back path -//! (prepare + bin + upload, compute, copy back); the direct path the window uses (into a -//! texture, no readback): what the calling thread spends, and until the GPU has finished; the -//! stage's way (512 px tiles drawn in parallel, as the render service does, until finished); -//! the work the fine pass did; and how far the GPU's picture is from the oracle's. +//! Prints the adapter, then for each scene and size: CPU ms; then, with the tiles binned on +//! the CPU and then on the GPU (ADR 0048), the direct path the window uses (into a texture, no +//! readback): what the calling thread spends, and until the GPU has finished; the stage's way +//! (512 px tiles drawn in parallel, as the render service does, until finished); and how far +//! the GPU-binned picture is from the oracle's. -use anicraft_doc::{Bitmap, BitmapId, ColorEffect, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; +use anicraft_doc::{Bitmap, BitmapId, ColorEffect, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; use anicraft_geom::{FillRule, Path}; -use anicraft_gpu::{GpuRenderer, Output, compare_premul8}; +use anicraft_gpu::{Binning, GpuRenderer, compare_premul8}; use anicraft_geom::Affine; use anicraft_render::{View, render}; use rayon::prelude::*; @@ -52,7 +54,7 @@ fn composited() -> Document { 0 | 1 => { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { - Arc::make_mut(e).color.alpha = 0.6; + Arc::make_mut(e).color = ColorEffect::Alpha(0.6); } } } @@ -85,7 +87,7 @@ fn bitmap_layer(id: u64, n: u32, bitmaps: &[Arc], frames: u32) -> Arc Document { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { if let ElementKind::Symbol { filters, .. } = &mut Arc::make_mut(e).kind { - *filters = match i { + *filters = Vec::from_iter(match i { 0 => vec![ Filter::DropShadow { blur_x: 8.0, blur_y: 8.0, strength: 0.8, quality: 2, angle: 45.0, distance: 10.0, color: Rgba::BLACK, inner: false, knockout: false, hide_object: false }, Filter::Bevel { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, angle: 45.0, distance: 4.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side: FilterSide::Inner, knockout: false }, ], _ => vec![Filter::Glow { blur_x: 12.0, blur_y: 12.0, strength: 1.4, quality: 2, color: Rgba::new(1.0, 0.85, 0.2, 1.0), inner: false, knockout: false }], - }; + }.into_iter().map(anicraft_doc::FilterEntry::from)); } } } @@ -129,7 +131,7 @@ fn filtered() -> Document { let mut layer = bitmap_layer(91_000, 0, std::slice::from_ref(&sky), frames); let l = Arc::make_mut(&mut layer); let fill = Paint::Bitmap { bitmap: sky.id, repeat: true, matrix: Affine::scale(5.0, 5.0) }; - let shape = Shape { merge: false, path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero }; + let shape = Shape { merge: false, path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, warp: None }; if let Some(k) = l.keyframes.first_mut() { Arc::make_mut(k).elements.push(Arc::new(Element { id: ElementId(91_001), name: "sky".into(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) })); } @@ -139,7 +141,72 @@ fn filtered() -> Document { doc } +/// Onion skin as the stage composes it (ADR 0047), for the bench: no onion skin, ±5 frames +/// tinted and fading, or ±5 frames as outlines. +#[derive(Clone, Copy, PartialEq)] +enum Onion { + Off, + Tinted, + Outlines, +} + +/// Frame `frame` with ±5 onion frames, as `anicraft_engine::onion::compose` draws them with +/// the default colours, tint and fade: each frame's items under the playhead's on their own +/// layer (nearest on top), at its alpha and tint, or as hairline outlines in its colour. (The +/// engine sits beside this crate, so the bench builds the same list itself.) +fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList { + let now = evaluate(doc, frame); + if mode == Onion::Off { + return now; + } + let frames = doc.frame_count().max(1); + let (past, future) = (Rgba::hex(0x4f8dff), Rgba::hex(0x4cd07d)); + let rank: std::collections::HashMap = doc.timeline(0).layers.iter().enumerate().map(|(i, l)| (l.id, i)).collect(); + let mut dl = DisplayList::default(); + let mut part_of: Vec = Vec::new(); + for d in (1..=5u32).rev() { + for (is_past, f) in [(true, frame.checked_sub(d)), (false, Some(frame + d).filter(|f| *f < frames))] { + let Some(f) = f else { continue }; + // Fading from 0.5 next to the playhead to 0.12 at the marker; tinted at 0.8. + let alpha = 0.5 + (0.12 - 0.5) * (d - 1) as f32 / 4.0; + let color = if is_past { past } else { future }; + let mut part = evaluate(doc, f); + for item in &mut part.items { + item.color = item.color.concat(&ColorTransform::alpha(alpha).concat(&ColorTransform::tint(color, 0.8))); + if mode == Onion::Outlines && item.masks.is_none() { + item.outline = Some(color.with_alpha(alpha)); + } + } + part_of.extend(std::iter::repeat_n(part_of.last().map_or(0, |p| p + 1), part.items.len())); + dl.append(part); + } + } + let k = part_of.last().map_or(0, |p| p + 1); + part_of.extend(std::iter::repeat_n(k, now.items.len())); + dl.append(now); + // Layer by layer, bottom first; within a layer, the parts in order (a stable sort). + let mut order: Vec = (0..dl.items.len()).collect(); + order.sort_by_key(|&i| (std::cmp::Reverse(dl.items.get(i).and_then(|it| rank.get(&it.layer)).copied().unwrap_or(0)), part_of.get(i).copied().unwrap_or(0))); + let mut items: Vec> = std::mem::take(&mut dl.items).into_iter().map(Some).collect(); + dl.items = order.into_iter().filter_map(|i| items.get_mut(i).and_then(Option::take)).collect(); + dl +} + +/// Timing budgets for the stage on the GPU (docs/performance.md › Budgets), checked with +/// `--check` on a known machine: `(scene, width, what, limit in ms)`, `what` being the Auto +/// column's `direct` or `tiled` (the stage's way). +const BUDGETS: &[(&str, u32, &str, f64)] = &[ + ("1,000 shapes", 3840, "tiled", 16.7), + ("stress 50×200", 3840, "tiled", 16.7), + ("50,000 shapes", 1920, "tiled", 33.3), + ("50,000 shapes", 3840, "direct", 33.3), +]; +/// Outline mode against tinted onion skin (ADR 0048: no slower), at 1080p in stage tiles. +const OUTLINE_RATIO: f64 = 1.25; + fn main() { + let check = std::env::args().any(|a| a == "--check"); + let mut measured: Vec<(String, u32, &str, f64)> = Vec::new(); let gpu = match GpuRenderer::new() { Ok(g) => g, Err(e) => { @@ -150,95 +217,117 @@ fn main() { println!("adapter: {}", gpu.adapter); let (layers, shapes) = (arg("--layers", 50), arg("--shapes", 200)); let runs = arg("--runs", 12); - let scenes: Vec<(String, Document)> = vec![ - (format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)), - ("1,000 shapes".into(), sample::stress(5, 200, 240)), - (format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))), - ("sample".into(), sample::demo()), - ("composited sample".into(), composited()), - ("filtered sample".into(), filtered()), - ("200 bitmaps".into(), bitmaps()), + let only: Option = std::env::args().skip_while(|a| a != "--only").nth(1); + let onion_doc = sample::stress(20, 100, 48); + let plain = |name: String, doc: Document| (name, doc, Onion::Off); + let scenes: Vec<(String, Document, Onion)> = vec![ + plain(format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)), + plain("1,000 shapes".into(), sample::stress(5, 200, 240)), + plain("50,000 shapes".into(), sample::stress(250, 200, 240)), + plain(format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))), + plain("sample".into(), sample::demo()), + plain("composited sample".into(), composited()), + plain("filtered sample".into(), filtered()), + plain("200 bitmaps".into(), bitmaps()), + ("onion off 20×100".into(), onion_doc.clone(), Onion::Off), + ("onion ±5 tinted".into(), onion_doc.clone(), Onion::Tinted), + ("onion ±5 outlines".into(), onion_doc, Onion::Outlines), ]; + println!("Per scene and size: the CPU oracle, then the GPU stage with the tiles binned on the CPU, then as Binning::Auto bins them (on the GPU with --forced):"); + println!("direct = the calling thread's time with render_texture (prepare + bin + upload/submit), waited = until the GPU has finished,"); + println!("tiled = 512 px stage tiles in parallel until finished. Parity: the GPU-binned picture against the oracle (mean / max / px)."); println!( - "{:<20} {:>10} {:>8} {:>9} {:>9} {:>9} {:>7} {:>22} {:>8} {:>8} parity (mean / max / differing px)", - "scene", "size", "CPU ms", "readback", "direct", "direct+", "tiled", "prepare + bin + submit", "entries", "pieces" + "{:<20} {:>10} {:>7} | {:>7} {:>7} {:>7} {:>19} | {:>7} {:>7} {:>7} {:>19} | parity", + "scene", "size", "CPU", "direct", "waited", "tiled", "prep + bin + gpu", "direct", "waited", "tiled", "prep + bin + gpu" ); - for (name, doc) in &scenes { + for (name, doc, onion) in scenes.iter().filter(|(n, ..)| only.as_ref().is_none_or(|o| n.contains(o.as_str()))) { for scale in [1.0f32, 2.0] { let v = View::stage(doc, scale * 1920.0 / doc.stage.width as f32); let frames = doc.frame_count().max(1); - let dl0 = evaluate(doc, 0); - // Warm-up (pipeline caches, allocations). - let _ = gpu.render(&dl0, &v, Output::Premul8); - let _ = gpu.render_texture(&dl0, &v); - let _ = gpu.wait_idle(); - let _ = render(&dl0, &v); + let evaluate = |doc: &Document, f: u32| onion_list(doc, f, *onion); + let dl0 = evaluate(doc, if *onion == Onion::Off { 0 } else { 30 }); let lists: Vec<_> = (0..runs).map(|i| evaluate(doc, (i * 20) % frames)).collect(); let per = |t: Instant| t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs); + let _ = render(&dl0, &v); let t = Instant::now(); for dl in &lists { let _ = render(dl, &v); } let cpu_ms = per(t); - let t = Instant::now(); - for dl in &lists { - let _ = gpu.render(dl, &v, Output::Premul8); - } - let readback_ms = per(t); - // Direct: what the calling thread spends (the stage's cost per tile), then each frame - // waited for to the end (the latency until the window can show it). - let mut sum = [0.0f32; 3]; - let mut work = (0, 0); - let t = Instant::now(); - let mut keep = Vec::with_capacity(lists.len()); - for dl in &lists { - if let Ok(f) = gpu.render_texture(dl, &v) { - sum[0] += f.timings.prepare; - sum[1] += f.timings.bin; - sum[2] += f.timings.gpu; - work = (f.entries, f.pieces); - keep.push(f); - } - } - let direct_ms = per(t); - let _ = gpu.wait_idle(); - drop(keep); - let t = Instant::now(); - for dl in &lists { - let _ = gpu.render_texture(dl, &v); - let _ = gpu.wait_idle(); - } - let done_ms = per(t); - // The stage: 512 px tiles of the same frame, in parallel, then waited for. + // The stage's tiles: 512 px of the same frame, drawn in parallel. let tiles: Vec = (0..v.height.div_ceil(512)) .flat_map(|ty| (0..v.width.div_ceil(512)).map(move |tx| (tx, ty))) .map(|(tx, ty)| View { transform: Affine::translate(-((tx * 512) as f32), -((ty * 512) as f32)).mul(&v.transform), width: 512.min(v.width - tx * 512), height: 512.min(v.height - ty * 512), background: v.background }) .collect(); - let t = Instant::now(); - for dl in &lists { - let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture(dl, tv).ok()).collect(); + let mut cols = Vec::new(); + let mut binned_on_gpu = false; + let second = if std::env::args().any(|a| a == "--forced") { Binning::Gpu } else { Binning::Auto }; + for binning in [Binning::Cpu, second] { + // Warm-up (pipeline caches, allocations). + let _ = gpu.render_texture_with(&dl0, &v, binning); let _ = gpu.wait_idle(); + let mut sum = [0.0f32; 3]; + let t = Instant::now(); + let mut keep = Vec::with_capacity(lists.len()); + for dl in &lists { + if let Ok(f) = gpu.render_texture_with(dl, &v, binning) { + sum[0] += f.timings.prepare; + sum[1] += f.timings.bin; + sum[2] += f.timings.gpu; + binned_on_gpu |= f.gpu_binned; + keep.push(f); + } + } + let direct = per(t); + let _ = gpu.wait_idle(); + drop(keep); + let t = Instant::now(); + for dl in &lists { + let _ = gpu.render_texture_with(dl, &v, binning); + let _ = gpu.wait_idle(); + } + let waited = per(t); + let t = Instant::now(); + for dl in &lists { + let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture_with(dl, tv, binning).ok()).collect(); + let _ = gpu.wait_idle(); + } + let tiled = per(t); + let n = runs as f32; + if binning == Binning::Auto { + measured.push((name.clone(), v.width, "direct", direct)); + measured.push((name.clone(), v.width, "tiled", tiled)); + } + cols.push(format!("{direct:>7.2} {waited:>7.2} {tiled:>7.2} {:>19}", format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n))); } - let tiled_ms = per(t); - let n = runs as f32; - let parity = match (gpu.render_texture(&dl0, &v).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) { + let parity = match (gpu.render_texture_with(&dl0, &v, Binning::Gpu).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) { (Ok(g), Ok((c, _))) => compare_premul8(&g, &c.to_premul_rgba8()).map_or("size mismatch".into(), |d| format!("{:.4} / {} / {}", d.mean, d.max, d.differing)), (Err(e), _) => format!("GPU: {e}"), (_, Err(e)) => format!("CPU: {e}"), }; - println!( - "{:<20} {:>10} {:>8.2} {:>9.2} {:>9.2} {:>9.2} {:>7.2} {:>22} {:>8} {:>8} {parity}", - name, - format!("{}×{}", v.width, v.height), - cpu_ms, - readback_ms, - direct_ms, - done_ms, - tiled_ms, - format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n), - work.0, - work.1 - ); + let note = if binned_on_gpu { "" } else { " (binned on the CPU: masks, groups or few edges)" }; + println!("{:<20} {:>10} {:>7.2} | {} | {} | {parity}{note}", name, format!("{}×{}", v.width, v.height), cpu_ms, cols[0], cols[1]); } } + if !check { + return; + } + let get = |scene: &str, w: u32, what: &str| measured.iter().find(|m| m.0 == scene && m.1 == w && m.2 == what).map(|m| m.3); + let mut missed = 0; + println!(); + println!("budgets (the means above; run on a quiet machine)"); + for &(scene, w, what, limit) in BUDGETS { + let got = get(scene, w, what); + let ok = got.is_some_and(|g| g <= limit); + missed += usize::from(!ok); + println!(" {} {scene} at {w} px, {what}: {} (budget {limit} ms)", if ok { "ok " } else { "MISS" }, got.map_or("not measured".into(), |g| format!("{g:.2} ms"))); + } + let ratio = get("onion ±5 outlines", 1920, "tiled").zip(get("onion ±5 tinted", 1920, "tiled")).map(|(o, t)| o / t); + let ok = ratio.is_some_and(|r| r <= OUTLINE_RATIO); + missed += usize::from(!ok); + println!(" {} onion outlines / tinted at 1920 px, tiled: {} (budget {OUTLINE_RATIO})", if ok { "ok " } else { "MISS" }, ratio.map_or("not measured".into(), |r| format!("{r:.2}"))); + if missed > 0 { + println!("{missed} budget(s) missed"); + std::process::exit(1); + } } diff --git a/crates/gpu/src/bin.wgsl b/crates/gpu/src/bin.wgsl new file mode 100644 index 00000000..817e92ee --- /dev/null +++ b/crates/gpu/src/bin.wgsl @@ -0,0 +1,426 @@ +// AniCraft GPU stage: tile binning on the GPU (ADR 0048). +// +// The same tile lists as the CPU binning (binning.rs, the reference), from the prepared fills' +// flattened polygons, in four kinds of dispatch: +// +// 1. `count`, one invocation per row of tiles of each fill (an "op-row"): its edges split at +// tile rows and columns (binning.rs › split_edge, split_row), plus the steps where the +// outline passes from one column to another (› Track, steps), or a hairline's segments by +// reach (› hairline_tiles), counted per tile of the fill (an "op-tile"); and the backdrops: the +// directions of the pieces starting on the row's top edge, summed along the row. Each +// op-row is one invocation's alone, so nothing needs atomics and integers add up the same +// in any order: the counts and backdrops are exact. +// 2. `scan_blocks` and `scan_add`: an exclusive prefix sum of the counts (the public +// work-efficient scan: per workgroup, then the workgroups' totals, then added back), which +// places every op-tile's pieces. +// 3. `scatter`: the same walk again, writing each piece where its op-tile's pieces go, in the +// walk's order (the same every frame). +// 4. `tiles`, one invocation per tile: its fills in drawing order (the fills overlapping its +// row, from the CPU, which only needs their bounds), keeping those with pieces or a +// backdrop there, as the entries the fine pass reads. +// +// The binding layout fits the smallest devices (four storage buffers per stage): one buffer of +// inputs, one of working values (counts, backdrops, offsets, cursors, scan totals), the pieces +// (`geo`) and the fine pass's index. + +struct Params { + // tiles across, tiles down, op-rows, tiles + size: vec4, + // op-tiles, piece capacity, where the entries start in `index`, 0 + more: vec4, + // where the ops, polygons, points and op-row owners start in `input` + at: vec4, + // where the rows' fills and the rows' starts are in `input` + at2: vec4, +} + +@group(0) @binding(0) var params: Params; +@group(0) @binding(1) var input: array; +@group(0) @binding(2) var work: array; +@group(0) @binding(3) var geo: array>; +@group(0) @binding(4) var index: array; + +const T: f32 = 16.0; +// gpu_binning.rs › HAIRLINE_BIT: the op is a hairline. +const HAIRLINE_BIT: u32 = 0x80000000u; +// How far around a hairline segment its tiles are taken (binning.rs › HAIRLINE_MARGIN). +const M: f32 = 1.25; + +// What to do with a piece. +const COUNT: u32 = 0u; +const WRITE: u32 = 1u; + +struct Op { + first_poly: u32, + polys: u32, + tx0: u32, + ty0: u32, + ncols: u32, + nrows: u32, + tile_base: u32, + flags: u32, +} + +fn op_at(i: u32) -> Op { + let b = params.at.x + i * 8u; + return Op(input[b], input[b + 1u], input[b + 2u], input[b + 3u], input[b + 4u], input[b + 5u], input[b + 6u], input[b + 7u]); +} + +fn point(i: u32) -> vec2 { + let b = params.at.z + i * 2u; + return vec2(bitcast(input[b]), bitcast(input[b + 1u])); +} + +// Finite (not NaN or infinite), from the bits: comparisons with NaN may be optimized away. +fn finite(v: f32) -> bool { + return (bitcast(v) & 0x7f800000u) != 0x7f800000u; +} + +fn finite2(p: vec2) -> bool { + return finite(p.x) && finite(p.y); +} + +// The working values: counts, backdrops, offsets and cursors, `params.more.x` each. +fn counts_at(t: u32) -> u32 { + return t; +} +fn backdrop_at(t: u32) -> u32 { + return params.more.x + t; +} +fn offset_at(t: u32) -> u32 { + return 2u * params.more.x + t; +} +fn cursor_at(t: u32) -> u32 { + return 3u * params.more.x + t; +} + +// The walk of one op-row: what it is and where its pieces go. +struct Walk { + mode: u32, + // the op-tile of the row's first column + tile0: u32, + ncols: i32, + hairline: bool, + row_y0: f32, + // the row's top-left in pixels + ox: f32, +} + +// The fill's range (binning.rs › Range). +struct Rng { + xlo: f32, + xhi: f32, + ylo: f32, + yhi: f32, + ncols: i32, + nrows: i32, +} + +// binning.rs › top_crossing. +fn top_crossing(s: vec4, row_y0: f32) -> i32 { + if s.y == s.w || min(s.y, s.w) != row_y0 { + return 0; + } + return select(-1, 1, s.w > s.y); +} + +// One piece in column `col` of the walk's row (−1: left of the fill's tiles). +fn emit(w: Walk, col: i32, s: vec4) { + if w.mode == COUNT { + if col >= 0 && col < w.ncols { + let t = counts_at(w.tile0 + u32(col)); + work[t] = work[t] + 1u; + } + if !w.hairline { + let c = top_crossing(s, w.row_y0); + if c != 0 && col + 1 < w.ncols { + let t = backdrop_at(w.tile0 + u32(col + 1)); + work[t] = bitcast(bitcast(work[t]) + c); + } + } + return; + } + if col < 0 || col >= w.ncols { + return; + } + let tile = w.tile0 + u32(col); + let k = work[cursor_at(tile)]; + work[cursor_at(tile)] = k + 1u; + let at = work[offset_at(tile)] + k; + if at < params.more.y { + let ox = w.ox + f32(u32(col) * 16u); + geo[at] = vec4(s.x - ox, s.y - w.row_y0, s.z - ox, s.w - w.row_y0); + } +} + +// The polygon's last piece so far in this invocation's row, and its first (binning.rs › Track). +var tr_last: bool; +var tr_last_col: i32; +var tr_last_y: f32; +var tr_first: bool; +var tr_first_col: i32; + +// binning.rs › steps: where the outline passes from column `a` (its piece ending at height +// `y`) to column `b`, a vertical piece on each tile boundary between them, from there to the +// row's bottom. +fn steps(w: Walk, r: Rng, a: i32, y: f32, b: i32) { + if a == b { + return; + } + let top = w.row_y0; + let bottom = top + T; + if !(y > top && y < bottom) { + return; + } + let right = a < b; + let lo = min(a, b); + let hi = max(a, b); + for (var k = max(lo + 1, 0); k <= min(hi, r.ncols - 1); k++) { + let x = r.xlo + f32(k) * T; + if right { + emit(w, k, vec4(x, bottom, x, y)); + } else { + emit(w, k, vec4(x, y, x, bottom)); + } + } +} + +// A piece of the polygon in this row, in the direction of travel (column −1: left of the +// fill's tiles; `ncols`: right of them, drawing nothing): kept, and seen by the steps. +fn piece(w: Walk, r: Rng, col: i32, s: vec4) { + if col < r.ncols { + emit(w, col, s); + } + if tr_last { + steps(w, r, tr_last_col, tr_last_y, col); + } else { + tr_first = true; + tr_first_col = col; + } + tr_last = true; + tr_last_col = col; + tr_last_y = s.w; +} + +fn push(w: Walk, r: Rng, col: i32, u: vec2, v: vec2, down: bool) { + if (down && v.y <= u.y) || (!down && v.y >= u.y) { + return; + } + piece(w, r, col, vec4(u, v)); +} + +// binning.rs › split_row: a piece inside one tile row, from `s` to `e` (the edge's direction), +// split at the fill's left and right edges and at tile columns. +fn split_row(w: Walk, s: vec2, e: vec2, r: Rng) { + let down = e.y > s.y; + let dx = e.x - s.x; + let lo = min(s.x, e.x); + let hi = max(s.x, e.x); + if hi <= r.xlo && lo < r.xlo { + push(w, r, -1, s, e, down); + return; + } + if lo >= r.xhi { + push(w, r, r.ncols, s, e, down); + return; + } + let cl = i32(floor((lo - r.xlo) / T)); + if dx == 0.0 || (lo >= r.xlo && hi < r.xhi && cl == i32(floor((hi - r.xlo) / T))) { + push(w, r, clamp(cl, 0, r.ncols - 1), s, e, down); + return; + } + let kmin = max(i32(floor((lo - r.xlo) / T)) + 1, 0); + let kmax = min(i32(ceil((hi - r.xlo) / T)) - 1, r.ncols); + let count = max(kmax - kmin + 1, 0); + var prev = s; + for (var j = 0; j <= count; j++) { + var next = e; + if j != count { + let k = select(kmax - j, kmin + j, dx > 0.0); + let x = r.xlo + f32(k) * T; + if !(x > lo && x < hi) { + continue; + } + let t = clamp((x - s.x) / dx, 0.0, 1.0); + next = vec2(x, s.y + (e.y - s.y) * t); + } + let mid = 0.5 * (prev.x + next.x); + if mid < r.xlo { + push(w, r, -1, prev, next, down); + } else if mid < r.xhi { + push(w, r, clamp(i32(floor((mid - r.xlo) / T)), 0, r.ncols - 1), prev, next, down); + } else { + push(w, r, r.ncols, prev, next, down); + } + prev = next; + } +} + +// binning.rs › split_edge, for tile row `row` only. +fn split_edge(w: Walk, a: vec2, b: vec2, r: Rng, row: u32) { + if !(finite2(a) && finite2(b)) || a.y == b.y { + return; + } + let down = a.y < b.y; + let p = select(b, a, down); + let q = select(a, b, down); + let y0 = max(p.y, r.ylo); + let y1 = min(q.y, r.yhi); + if y1 <= y0 { + return; + } + let first = u32(max(floor((y0 - r.ylo) / T), 0.0)); + let last = u32(max(ceil((y1 - r.ylo) / T), 0.0)); + if row < first || row >= last { + return; + } + let dxdy = (q.x - p.x) / (q.y - p.y); + let ry0 = r.ylo + f32(row * 16u); + let ys = max(y0, ry0); + let ye = min(y1, ry0 + T); + if ye <= ys { + return; + } + let top = vec2(p.x + (ys - p.y) * dxdy, ys); + let bottom = vec2(p.x + (ye - p.y) * dxdy, ye); + if down { + split_row(w, top, bottom, r); + } else { + split_row(w, bottom, top, r); + } +} + +// binning.rs › hairline_tiles, for tile row `row` only: the segment, whole, into every column +// within reach. +fn hairline(w: Walk, a: vec2, b: vec2, r: Rng, row: u32) { + if !(finite2(a) && finite2(b)) { + return; + } + let r0 = max(floor((min(a.y, b.y) - M - r.ylo) / T), 0.0); + let r1 = min(floor((max(a.y, b.y) + M - r.ylo) / T), f32(r.nrows - 1)); + let rf = f32(row); + if !(r1 >= r0) || rf < r0 || rf > r1 { + return; + } + let top = r.ylo + rf * T; + let dx = b.x - a.x; + let dy = b.y - a.y; + var xa = min(a.x, b.x); + var xb = max(a.x, b.x); + if dy != 0.0 { + let t0 = clamp((top - M - a.y) / dy, 0.0, 1.0); + let t1 = clamp((top + T + M - a.y) / dy, 0.0, 1.0); + let u = a.x + dx * t0; + let v = a.x + dx * t1; + xa = min(u, v); + xb = max(u, v); + } + let c0 = max(floor((xa - M - r.xlo) / T), 0.0); + let c1 = min(floor((xb + M - r.xlo) / T), f32(r.ncols - 1)); + if !(c1 >= c0) { + return; + } + for (var col = i32(c0); col <= i32(c1); col++) { + emit(w, col, vec4(a, b)); + } +} + +// The invocation's index in a dispatch of 64-wide workgroups spread over x and y. +fn linear(wg: vec3, n: vec3, lid: vec3, width: u32) -> u32 { + return (wg.y * n.x + wg.x) * width + lid.x; +} + +fn walk(mode: u32, t: u32) { + if t >= params.size.z { + return; + } + let opi = input[params.at.w + t]; + let o = op_at(opi); + // This op-row's row within the fill: how far `t` is past the fill's first op-row, which + // `row_of` holds in the op's own slot of rows (op-rows are in op order). + let row = t - input[params.at.w + params.size.z + opi]; + let ylo = f32(o.ty0 * 16u); + let r = Rng(f32(o.tx0 * 16u), f32((o.tx0 + o.ncols) * 16u), ylo, f32((o.ty0 + o.nrows) * 16u), i32(o.ncols), i32(o.nrows)); + let hair = (o.flags & HAIRLINE_BIT) != 0u; + let w = Walk(mode, o.tile_base + row * o.ncols, i32(o.ncols), hair, f32((o.ty0 + row) * 16u), r.xlo); + for (var pi = 0u; pi < o.polys; pi++) { + let pb = params.at.y + (o.first_poly + pi) * 2u; + let start = input[pb]; + let n = input[pb + 1u]; + if hair { + if n == 1u { + let p = point(start); + hairline(w, p, p, r, row); + } + for (var i = 0u; i + 1u < n; i++) { + hairline(w, point(start + i), point(start + i + 1u), r, row); + } + } else if n >= 2u { + tr_last = false; + tr_first = false; + for (var i = 0u; i < n; i++) { + let a = point(start + i); + let b = point(start + select(i + 1u, 0u, i + 1u == n)); + split_edge(w, a, b, r, row); + } + if tr_last && tr_first { + steps(w, r, tr_last_col, tr_last_y, tr_first_col); + } + } + } + if mode == COUNT && !hair { + // The backdrop deltas, summed along the row. + var acc = 0; + for (var c = 0u; c < o.ncols; c++) { + let at = backdrop_at(w.tile0 + c); + acc += bitcast(work[at]); + work[at] = bitcast(acc); + } + } +} + +@compute @workgroup_size(64) +fn count(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + walk(COUNT, linear(wg, n, lid, 64u)); +} + +@compute @workgroup_size(64) +fn scatter(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + walk(WRITE, linear(wg, n, lid, 64u)); +} + +@compute @workgroup_size(64) +fn tiles(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + let t = linear(wg, n, lid, 64u); + if t >= params.size.w { + return; + } + let tx = t % params.size.x; + let ty = t / params.size.x; + let start = index[2u * t]; + let rs = params.at2.x + input[params.at2.y + ty]; + let re = params.at2.x + input[params.at2.y + ty + 1u]; + var k = 0u; + for (var i = rs; i < re; i++) { + let opi = input[i]; + let o = op_at(opi); + if tx < o.tx0 || tx >= o.tx0 + o.ncols { + continue; + } + let ot = o.tile_base + (ty - o.ty0) * o.ncols + (tx - o.tx0); + var c = work[counts_at(ot)]; + let bd = work[backdrop_at(ot)]; + if c == 0u && bd == 0u { + continue; + } + let off = min(work[offset_at(ot)], params.more.y); + c = min(c, params.more.y - off); + let e = params.more.z + (start + k) * 4u; + index[e] = opi; + index[e + 1u] = off; + index[e + 2u] = c; + index[e + 3u] = bd; + k++; + } + index[2u * t + 1u] = k; +} diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index c944a57d..7ccd8bb2 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -1,13 +1,26 @@ //! Tile binning: the CPU half of the GPU stage (ADR 0019, ADR 0029). //! //! The surface is cut into 16 × 16 pixel tiles. Every fill's edges are split at tile rows and -//! columns; each piece lands in the one tile it crosses. What a piece contributes to the tiles -//! to its right is a plain winding change per pixel row (it lies wholly to their left), so it -//! is summed into a **backdrop** of 16 values, one per pixel row, carried across the tile row -//! as in the public sparse-strips and Vello designs. A tile of a fill then needs only its own -//! pieces and its backdrop: the fine shader computes each pixel's exact area coverage from -//! those, the same integral the CPU oracle's accumulation buffer computes (ADR 0002). Tiles -//! with neither (outside the fill) get no entry; interior tiles get a backdrop and no pieces. +//! columns; each piece lands in the one tile it crosses. Everything left of a tile reaches it +//! as the fill's winding number along the tile's left edge (ADR 0048), which is +//! +//! * its **backdrop**, the winding number just below the tile's top-left corner: an integer, +//! the sum of the directions of the pieces further left that start on the tile row's top +//! edge (they are the edges crossing it), plus +//! * a step wherever the outline crosses the tile's left edge, kept as one more piece: a +//! vertical line on that edge from the crossing down to the tile's bottom, upwards where the +//! outline crosses rightwards (the winding there drops by one), downwards where it crosses +//! leftwards. +//! +//! These are the backdrops and "y-edges" of Vello's tiles (its public design notes). A tile of +//! a fill then needs only its own pieces and its backdrop: the fine shader computes each +//! pixel's exact area coverage from those, the same integral the CPU oracle's accumulation +//! buffer computes (ADR 0002). Tiles with neither (outside the fill) get no entry; interior +//! tiles get a backdrop and no pieces. Backdrops are integers, so they add up the same in any +//! order, and the GPU computes the same lists ([`crate::gpu_binning`]). +//! +//! A **hairline** (outline mode, ADR 0048) is binned by distance instead: each segment, whole, +//! into every tile with a pixel centre within its reach; the shader takes the nearest. //! //! Each tile then lists its entries in drawing order, so the shader composites every pixel in //! one pass, front to back in the display list's order. Masks and groups (ADR 0029) are more @@ -34,8 +47,14 @@ type Vec4 = [f32; 4]; /// Tile side in pixels (the shader's workgroup is one tile, one invocation per pixel). pub const TILE: u32 = 16; const T: f32 = TILE as f32; -/// "No backdrop" in an entry; "no clip" or "no group" in the tables. +/// "No clip" or "no group" in the tables. pub const NONE: u32 = u32::MAX; +/// Fill rule code of a hairline in an op header (`0` non-zero, `1` even-odd). +pub const HAIRLINE: u32 = 2; +/// How far around a hairline segment its tiles are taken (`bin.wgsl` › `M`): a pixel centre +/// within its reach is within `REACH` of a point of it, so the tile holding that centre holds a +/// point within `REACH` of the segment's box; a quarter pixel more absorbs rounding. +pub(crate) const HAIRLINE_MARGIN: f32 = anicraft_render::hairline::REACH + 0.25; /// `vec4`s of paint data per fill. pub const PAINT_VEC4S: usize = 4; /// Gradient table entries (the oracle's LUT size). @@ -59,7 +78,8 @@ const IMAGE: u32 = 4; /// Op header flag: the fill is drawn inside the current clip. pub const CLIPPED: u32 = 1; -/// Op header flag: the op is clip artwork (its coverage joins the current level's union). +/// Op header flag: the op is clip artwork (its coverage joins the current level's union; in a +/// soft mask its paint composites into the level's colour). pub const ART: u32 = 2; /// An entry whose first word has this bit is a control entry, not a fill. @@ -70,11 +90,23 @@ pub const OPEN: u32 = CTRL | 1; pub const CLOSE: u32 = CTRL | 2; /// The clip coverage starts at 1 (a new clip's chain follows). pub const MASK_RESET: u32 = CTRL | 3; -/// One level of the clip chain starts: its union of artwork coverage starts at 0. +/// `[LEVEL_BEGIN, mask mode, 0, 0]`: one level of the clip chain starts: its union of artwork +/// coverage starts at 0, or for a soft mask ([`mask_code`]) its artwork's colour starts +/// transparent. pub const LEVEL_BEGIN: u32 = CTRL | 4; -/// The level ends: the clip coverage is multiplied by its union. +/// The level ends: the clip coverage is multiplied by its union (or by the soft mask's +/// opacity or luminance, ADR 0070). pub const LEVEL_END: u32 = CTRL | 5; +/// Mask modes as the shader numbers them (`fine.wgsl` › `LEVEL_END`). +pub fn mask_code(m: anicraft_doc::MaskMode) -> u32 { + match m { + anicraft_doc::MaskMode::Coverage => 0, + anicraft_doc::MaskMode::Alpha => 1, + anicraft_doc::MaskMode::Luminance => 2, + } +} + /// Blend modes as the shader numbers them (`fine.wgsl` › `blend`). pub fn blend_code(m: BlendMode) -> u32 { match m { @@ -97,11 +129,11 @@ pub fn blend_code(m: BlendMode) -> u32 { /// A scene ready for the fine shader. /// /// * `index` (u32): `[start, count]` per tile into the entry list; then each entry as -/// `[op, first piece, pieces, backdrop]` (the backdrop's first `vec4` in `geo`, or [`NONE`]), -/// or a control entry ([`CTRL`] set); then each op's header `[kind, fill rule, ramp start in -/// paints, flags]`. +/// `[op, first piece, pieces, backdrop]` (the backdrop an `i32`), or a control entry ([`CTRL`] +/// set); then, at `ops_at`, each op's header `[kind, fill rule (or HAIRLINE), ramp start in +/// paints, flags]` ([`Binned::op_heads`]). /// * `geo` (`vec4`): pieces `(x0, y0, x1, y1)` relative to their tile's top-left, in the -/// edge's direction; then backdrops, four `vec4`s (16 rows) each. +/// edge's direction (left-edge steps included); a hairline's are its segments, whole. /// * `paints` (`vec4`): per op its colour, then the inverse paint transform and gradient, /// bitmap or layer parameters; then the gradient tables (256 premultiplied colours each); /// then (filled in on the GPU, [`Binned::layer_at`]) the filtered layers' pixels. @@ -113,6 +145,8 @@ pub struct Binned { pub index: Vec, pub entries_at: u32, pub ops_at: u32, + /// The op headers, which go at `ops_at` in the index. + pub op_heads: Vec, pub geo: Vec<[f32; 4]>, pub paints: Vec<[f32; 4]>, /// The paint buffer's whole length in `vec4`s: `paints`, then room for the layers. @@ -128,16 +162,18 @@ pub struct Binned { /// Pieces plus entries the fine pass walks, summed over tiles (each for 256 pixels): what /// bounds how long the dispatch runs. pub work: u64, + /// Binned on the GPU: `index` holds only the tile headers (`[start, 0]`, room for every + /// tile the fills' bounds cover), `geo` is empty, and the GPU computes the entries and + /// pieces from this plan (`entries` and `pieces` are then upper bounds). + pub gpu: Option, } /// A chunk of fills' share of the scene (binned in parallel; chunking keeps allocations few). #[derive(Default)] struct Local { - /// `[op, tile, first piece, pieces, backdrop or NONE]`, piece and backdrop indices local. + /// `[op, tile, first piece, pieces, backdrop]`, piece indices local. entries: Vec<[u32; 5]>, pieces: Vec<[f32; 4]>, - /// Backdrops, four `vec4`s (16 pixel rows) each. - backdrops: Vec<[f32; 4]>, } /// An edge piece inside one tile row, in absolute pixels; `col` is the tile column relative to @@ -177,6 +213,12 @@ struct RowOut { /// shader holds ([`MAX_GROUP_DEPTH`], [`MAX_CLIP_DEPTH`]) or it has more bitmaps than /// [`MAX_IMAGES`]; the caller draws it on the CPU. pub fn bin(scene: &Scene, width: u32, height: u32) -> Result { + bin_with(scene, width, height, None) +} + +/// [`bin`], or with `gpu`, a plan for binning on the GPU instead ([`Binned::gpu`]) when the +/// scene can take it and fits `gpu`'s limits ([`crate::gpu_binning`]). +pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_binning::Limits>) -> Result { if scene.groups.iter().any(|g| g.chain.len() > MAX_GROUP_DEPTH) { return Err(NeedsFull::Groups); } @@ -206,6 +248,143 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let tiles_x = width.div_ceil(TILE); let tiles_y = height.div_ceil(TILE); + // On the GPU when asked and the scene can take it (no fill in a mask or a group, for now): + // then the fills alone are the ops (no mask artwork draws). + let plan = gpu.filter(|_| scene.fills.iter().all(|f| f.clip.is_none() && f.group.is_none())).and_then(|lim| crate::gpu_binning::plan(&scene.fills, tiles_x, tiles_y, lim)); + let lists = match &plan { + Some(p) => { + ops.truncate(nf); + Lists::on_gpu(p, tiles_x, tiles_y) + } + None => cpu_lists(&ops, &tables, tiles_x, tiles_y), + }; + + // Paints: a fixed record per op, then the gradient tables, then the layers' pixels. + let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len()); + let mut ramps: Vec<[f32; 4]> = Vec::new(); + let mut images: Vec> = Vec::new(); + let ramps_at = (PAINT_VEC4S * ops.len()) as u32; + // Where each layer shown by a fill goes, after the tables (the tables' size is known first). + // Gradients' ramps, and each bitmap's colour transform (two entries). + let table_len: usize = ops + .iter() + .filter(|f| f.layer.is_none()) + .map(|f| match &f.shader { + Shader::Linear { .. } | Shader::Radial { .. } => RAMP, + Shader::Bitmap { pixels, .. } if pixels.width > 0 && pixels.height > 0 => 2, + _ => 0, + }) + .sum(); + let mut layer_at: Vec> = vec![None; scene.layers.len()]; + let mut cursor = PAINT_VEC4S * ops.len() + table_len; + for f in &ops { + let Some(l) = f.layer else { continue }; + let (Some(slot), Some(layer)) = (layer_at.get_mut(l as usize), scene.layers.get(l as usize)) else { continue }; + if slot.is_none() { + *slot = Some(cursor as u32); + cursor += layer.bounds.width() * layer.bounds.height(); + } + } + if cursor >= u32::MAX as usize { + return Err(NeedsFull::Filters); + } + let paints_len = cursor; + let mut op_heads: Vec = Vec::with_capacity(4 * ops.len()); + let u = f32::from_bits; + for (op, f) in ops.iter().enumerate() { + let rule = match f.rule { + _ if f.hairline => HAIRLINE, + FillRule::NonZero => 0, + FillRule::EvenOdd => 1, + }; + let ramp = ramps_at + ramps.len() as u32; + let layer = f.layer.and_then(|l| Some((layer_at.get(l as usize).copied().flatten()?, scene.layers.get(l as usize)?.bounds))); + let (kind, rec) = match (&f.shader, layer) { + // A layer's pixels at `at`, `w × h`, its top-left at (x0, y0) in surface pixels. + (_, Some((at, b))) => (IMAGE, [[u(at), u(b.width() as u32), u(b.height() as u32), 0.0], [u(b.x0 as u32), u(b.y0 as u32), 0.0, 0.0], [0.0; 4], [0.0; 4]]), + (_, None) if f.layer.is_some() => (SOLID, [[0.0; 4]; 4]), + (Shader::Solid(c), _) => (SOLID, [*c, [0.0; 4], [0.0; 4], [0.0; 4]]), + // A gradient's first vec4 holds what its colour slot doesn't need: the spread + // (0 pad, 1 reflect, 2 repeat) and a radial gradient's focal point (ADR 0074). + (Shader::Linear { inv, start, dir, spread, lut }, _) => { + ramps.extend_from_slice(&lut[..]); + let m = inv.m; + (LINEAR, [[spread_code(*spread), 0.0, 0.0, 0.0], [m[0], m[1], m[2], m[3]], [m[4], m[5], start.x, start.y], [dir.x, dir.y, 0.0, 0.0]]) + } + (Shader::Radial { inv, center, inv_radius, focal, spread, lut }, _) => { + ramps.extend_from_slice(&lut[..]); + let m = inv.m; + (RADIAL, [[spread_code(*spread), *focal, 0.0, 0.0], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]]) + } + // The oracle's sample of a bitmap (crates/render/src/paint.rs › sample). + (Shader::Bitmap { inv, pixels, repeat, fx, smooth }, _) => { + if pixels.width == 0 || pixels.height == 0 { + (SOLID, [[0.0; 4]; 4]) + } else { + let slot = match images.iter().position(|p| Arc::ptr_eq(p, pixels)) { + Some(i) => i, + None if images.len() < MAX_IMAGES => { + images.push(pixels.clone()); + images.len() - 1 + } + None => return Err(NeedsFull::Bitmaps), + }; + let m = inv.m; + // The colour transform (ADR 0056) rides in the ramp table: multiplies, then + // offsets, sanitized as the oracle applies them. + let fx = fx.sanitized(); + ramps.extend_from_slice(&[fx.mul, fx.add]); + // Bit 0: repeat; bit 1: the nearest pixel instead of bilinear (no smoothing). + (BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], 0.0, 0.0], [0.0; 4]]) + } + } + // `prepare_scene` never hands these over; draw nothing rather than guess. + (Shader::Image { .. }, _) => (SOLID, [[0.0; 4]; 4]), + }; + paints.extend_from_slice(&rec); + let flags = if op >= nf { + ART + } else if tables.op_clip.get(op).is_some_and(|&c| c != NONE) { + CLIPPED + } else { + 0 + }; + op_heads.extend_from_slice(&[kind, rule, ramp, flags]); + } + paints.extend_from_slice(&ramps); + if paints.len() != PAINT_VEC4S * ops.len() + table_len { + // The tables came out another size than counted; never let a layer overlap them. + return Err(NeedsFull::Filters); + } + + let Lists { index, geo, entries_at, ops_at, entries, pieces, work } = lists; + Ok(Binned { tiles_x, tiles_y, index, entries_at, ops_at, op_heads, geo, paints, paints_len, layer_at, images, entries, pieces, work, gpu: plan }) +} + +/// The tile lists (or, binned on the GPU, room for them). +struct Lists { + index: Vec, + geo: Vec<[f32; 4]>, + entries_at: u32, + ops_at: u32, + entries: usize, + pieces: usize, + work: u64, +} + +impl Lists { + /// Headers `[start, 0]` with room for every tile its fills' bounds cover; the GPU fills in + /// the entries and the counts. Entries and pieces are upper bounds. + fn on_gpu(p: &crate::gpu_binning::Plan, tiles_x: u32, tiles_y: u32) -> Lists { + let entries_at = 2 * tiles_x * tiles_y; + let ops_at = entries_at + 4 * p.op_tiles; + let work = u64::from(p.op_tiles) + u64::from(p.piece_cap); + Lists { index: p.headers.clone(), geo: Vec::new(), entries_at, ops_at, entries: p.op_tiles as usize, pieces: p.piece_cap as usize, work } + } +} + +/// The tile lists, binned on the CPU (in parallel per chunk of fills, then per tile row). +fn cpu_lists(ops: &[&Fill], tables: &Tables, tiles_x: u32, tiles_y: u32) -> Lists { let (tx, ty) = (tiles_x as usize, tiles_y as usize); // Phase 1, parallel over chunks of ops: pieces, backdrops and entries; each chunk's // entries then sorted (stably, so drawing order holds) by tile row, with row offsets. @@ -214,7 +393,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result .enumerate() .map(|(c, chunk)| { let mut out = Local::default(); - let mut scratch = Vec::new(); + let mut scratch = (Vec::new(), Track::default()); for (i, f) in chunk.iter().enumerate() { bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch); } @@ -232,20 +411,17 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result }) .collect(); - // Where each chunk's pieces and backdrops go in `geo`. + // Where each chunk's pieces go in `geo`. let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); let mut piece_at = Vec::with_capacity(locals.len()); - let mut bd_at = Vec::with_capacity(locals.len()); - let (mut p, mut b) = (0usize, pieces); + let mut p = 0usize; for (l, _) in &locals { piece_at.push(p as u32); - bd_at.push(b as u32); p += l.pieces.len(); - b += l.backdrops.len(); } // Phase 2, parallel over tile rows: each tile's stream of entries. - let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &bd_at, &tables)).collect(); + let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, tables)).collect(); let mut row_at = vec![0usize; ty + 1]; for (r, out) in rows.iter().enumerate() { row_at[r + 1] = row_at[r] + out.stream.len(); @@ -254,7 +430,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let work = rows.iter().map(|r| r.work).sum(); let entries_at = 2 * tx * ty; let ops_at = entries_at + 4 * total; - let mut index = vec![0u32; ops_at + 4 * ops.len()]; + let mut index = vec![0u32; ops_at]; // Phase 3, parallel over tile rows: headers and streams copied into place. { let (headers, rest) = index.split_at_mut(entries_at); @@ -274,136 +450,27 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result } }); } - // Pieces, then backdrops, copied in parallel into their places. - let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; b]; + // Pieces copied in parallel into their places. + let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; { - let (mut piece_dst, mut bd_dst) = geo.split_at_mut(pieces); - let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(2 * locals.len()); + let mut piece_dst = &mut geo[..]; + let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(locals.len()); for (l, _) in &locals { let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len()); jobs.push((a, &l.pieces)); piece_dst = rest; - let (a, rest) = std::mem::take(&mut bd_dst).split_at_mut(l.backdrops.len()); - jobs.push((a, &l.backdrops)); - bd_dst = rest; } jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s)); } // Tens of thousands of small buffers: free them on the pool, off the frame's path. anicraft_render::drop_in_background((locals, rows)); - // Paints: a fixed record per op, then the gradient tables, then the layers' pixels. - let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len()); - let mut ramps: Vec<[f32; 4]> = Vec::new(); - let mut images: Vec> = Vec::new(); - let ramps_at = (PAINT_VEC4S * ops.len()) as u32; - // Where each layer shown by a fill goes, after the tables (the tables' size is known first). - let table_len: usize = ops.iter().filter(|f| matches!(f.shader, Shader::Linear { .. } | Shader::Radial { .. }) && f.layer.is_none()).count() * RAMP; - let mut layer_at: Vec> = vec![None; scene.layers.len()]; - let mut cursor = PAINT_VEC4S * ops.len() + table_len; - for f in &ops { - let Some(l) = f.layer else { continue }; - let (Some(slot), Some(layer)) = (layer_at.get_mut(l as usize), scene.layers.get(l as usize)) else { continue }; - if slot.is_none() { - *slot = Some(cursor as u32); - cursor += layer.bounds.width() * layer.bounds.height(); - } - } - if cursor >= u32::MAX as usize { - return Err(NeedsFull::Filters); - } - let paints_len = cursor; - let u = f32::from_bits; - for (op, f) in ops.iter().enumerate() { - let rule = match f.rule { - FillRule::NonZero => 0, - FillRule::EvenOdd => 1, - }; - let ramp = ramps_at + ramps.len() as u32; - let layer = f.layer.and_then(|l| Some((layer_at.get(l as usize).copied().flatten()?, scene.layers.get(l as usize)?.bounds))); - let (kind, rec) = match (&f.shader, layer) { - // A layer's pixels at `at`, `w × h`, its top-left at (x0, y0) in surface pixels. - (_, Some((at, b))) => (IMAGE, [[u(at), u(b.width() as u32), u(b.height() as u32), 0.0], [u(b.x0 as u32), u(b.y0 as u32), 0.0, 0.0], [0.0; 4], [0.0; 4]]), - (_, None) if f.layer.is_some() => (SOLID, [[0.0; 4]; 4]), - (Shader::Solid(c), _) => (SOLID, [*c, [0.0; 4], [0.0; 4], [0.0; 4]]), - (Shader::Linear { inv, start, dir, lut }, _) => { - ramps.extend_from_slice(&lut[..]); - let m = inv.m; - (LINEAR, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], start.x, start.y], [dir.x, dir.y, 0.0, 0.0]]) - } - (Shader::Radial { inv, center, inv_radius, lut }, _) => { - ramps.extend_from_slice(&lut[..]); - let m = inv.m; - (RADIAL, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]]) - } - // The oracle's bilinear sample of a bitmap (crates/render/src/paint.rs › sample). - (Shader::Bitmap { inv, pixels, repeat, fx }, _) => { - if pixels.width == 0 || pixels.height == 0 { - (SOLID, [[0.0; 4]; 4]) - } else { - let slot = match images.iter().position(|p| Arc::ptr_eq(p, pixels)) { - Some(i) => i, - None if images.len() < MAX_IMAGES => { - images.push(pixels.clone()); - images.len() - 1 - } - None => return Err(NeedsFull::Bitmaps), - }; - let m = inv.m; - let (k, alpha, tint, keep) = colour_effect(fx); - (BITMAP, [[u(slot as u32), u(u32::from(*repeat)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], k, alpha], [tint[0], tint[1], tint[2], u(keep)]]) - } - } - // `prepare_scene` never hands these over; draw nothing rather than guess. - (Shader::Image { .. }, _) => (SOLID, [[0.0; 4]; 4]), - }; - paints.extend_from_slice(&rec); - let flags = if op >= nf { - ART - } else if tables.op_clip.get(op).is_some_and(|&c| c != NONE) { - CLIPPED - } else { - 0 - }; - let at = ops_at + 4 * op; - if let Some(slot) = index.get_mut(at..at + 4) { - slot.copy_from_slice(&[kind, rule, ramp, flags]); - } - } - paints.extend_from_slice(&ramps); - if paints.len() != PAINT_VEC4S * ops.len() + table_len { - // The tables came out another size than counted; never let a layer overlap them. - return Err(NeedsFull::Filters); - } - - Ok(Binned { tiles_x, tiles_y, index, entries_at: entries_at as u32, ops_at: ops_at as u32, geo, paints, paints_len, layer_at, images, entries: total, pieces, work }) -} - -/// A colour effect as the shader applies it to each bitmap tap, the same arithmetic as -/// [`anicraft_doc::ColorEffect::apply`] then `premultiply`'s sanitizing: `(tint amount, alpha, -/// tint, kept channels)`. Each straight channel `c` becomes `c + (tint − c)·k`, alpha `a·alpha`, -/// clamped to `0..=1`. A NaN the oracle would carry into a channel (and its sanitizing turn -/// into 0) is a channel left out of `kept` (bit per channel, red first) instead. -fn colour_effect(fx: &anicraft_doc::ColorEffect) -> (f32, f32, [f32; 3], u32) { - let k = fx.tint_amount.clamp(0.0, 1.0); - let alpha = fx.alpha.clamp(0.0, 1.0); - let t = [fx.tint.r, fx.tint.g, fx.tint.b]; - let mut keep = 0u32; - let mut tint = [0.0f32; 3]; - for (i, (&v, out)) in t.iter().zip(tint.iter_mut()).enumerate() { - if v.is_finite() && k.is_finite() { - keep |= 1 << i; - *out = v; - } - } - // A NaN opacity makes every channel 0 (premultiplied by a sanitized alpha of 0). - let alpha = if alpha.is_finite() { alpha } else { 0.0 }; - (if k.is_finite() { k } else { 0.0 }, alpha, tint, keep) + Lists { index, geo, entries_at: entries_at as u32, ops_at: ops_at as u32, entries: total, pieces, work } } /// Tile row `r`'s streams: per tile, its fills in drawing order with the clip and group /// entries they need. -fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u32], bd_at: &[u32], t: &Tables) -> RowOut { +fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u32], t: &Tables) -> RowOut { let first_tile = (r * tx) as u32; let slices = || { locals.iter().enumerate().map(move |(c, (l, rows))| { @@ -430,13 +497,12 @@ fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u3 let mut ae = vec![[0u32; 4]; nart]; let mut cursor: Vec<[u32; 2]> = count[..tx].to_vec(); for (c, es) in slices() { - let (p0, b0) = (piece_at.get(c).copied().unwrap_or(0), bd_at.get(c).copied().unwrap_or(0)); + let p0 = piece_at.get(c).copied().unwrap_or(0); for &[op, tile, s0, n, bd] in es { let Some(cur) = cursor.get_mut(tile.wrapping_sub(first_tile) as usize) else { continue }; let art = usize::from(op >= t.fills); let at = cur[art] as usize; cur[art] += 1; - let bd = if bd == NONE { NONE } else { b0 + bd }; let slot = if art == 1 { ae.get_mut(at) } else { fe.get_mut(at) }; if let Some(slot) = slot { *slot = [op, p0 + s0, n, bd]; @@ -489,7 +555,8 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec< } out.push([MASK_RESET, 0, 0, 0]); for &l in chain { - out.push([LEVEL_BEGIN, 0, 0, 0]); + let mode = t.scene.clips.get(l as usize).map_or(0, |c| mask_code(c.mode)); + out.push([LEVEL_BEGIN, mode, 0, 0]); out.extend_from_slice(level(l)); out.push([LEVEL_END, 0, 0, 0]); } @@ -514,30 +581,33 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec< } } -/// Splits one fill's edges into tile pieces and walks each tile row for backdrops. -fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, pieces: &mut Vec) { - let b = f.bounds; - if b.is_empty() { - return; - } - let tx0 = b.x0.max(0) as u32 / TILE; - let tx1 = (b.x1.max(0) as u32).div_ceil(TILE).min(tiles_x); - let ty0 = b.y0.max(0) as u32 / TILE; - let ty1 = (b.y1.max(0) as u32).div_ceil(TILE).min(tiles_y); - if tx1 <= tx0 || ty1 <= ty0 { - return; - } - let ncols = (tx1 - tx0) as i32; - let range = Range { ylo: (ty0 * TILE) as f32, yhi: (ty1 * TILE) as f32, xlo: (tx0 * TILE) as f32, xhi: (tx1 * TILE) as f32, ncols }; +/// Splits one fill's edges into tile pieces (with the steps where its outline crosses a tile's +/// left edge) and walks each tile row for the backdrops. +fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, (pieces, track): &mut (Vec, Track)) { + let Some(range) = Range::of(f, tiles_x, tiles_y) else { return }; pieces.clear(); - for poly in &f.polys { - let n = poly.len(); - if n < 2 { - continue; + if f.hairline { + for poly in &f.polys { + for_segments(poly, |a, b| hairline_tiles(a, b, &range, HAIRLINE_MARGIN, |row, col| pieces.push(Piece { row, col, seg: [a.x, a.y, b.x, b.y] }))); } - for i in 0..n { - let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - split_edge(a, c, &range, pieces); + } else { + for poly in &f.polys { + let n = poly.len(); + if n < 2 { + continue; + } + track.start(range.nrows as usize); + let mut keep = |p: Piece| pieces.push(p); + for i in 0..n { + let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; + split_edge(a, c, &range, |row, col, seg| { + if col < range.ncols { + keep(Piece { row, col, seg }); + } + track.see(row, Seen { col, end_y: seg[3] }, &range, &mut keep); + }); + } + track.finish(&range, &mut keep); } } if pieces.is_empty() { @@ -549,53 +619,37 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec let mut i = 0usize; while let Some(first) = pieces.get(i) { let row = first.row; - let row_y0 = ((ty0 + row) * TILE) as f32; - let mut wind = [0.0f32; 16]; - // Parts left of the fill's tiles only shift the winding. + let row_y0 = range.row_y0(row); + // Pieces left of the fill's tiles only count where they start on the row's top edge. + let mut backdrop = 0i32; while let Some(p) = pieces.get(i).filter(|p| p.row == row && p.col < 0) { - add_rows(&mut wind, &p.seg, row_y0); + backdrop += top_crossing(&p.seg, row_y0); i += 1; } - let mut last_bd: Option<(u32, [f32; 16])> = None; - for col in 0..ncols { + for col in 0..range.ncols { let start = i; while pieces.get(i).is_some_and(|p| p.row == row && p.col == col) { i += 1; } let here = pieces.get(start..i).unwrap_or(&[]); - let empty_wind = wind.iter().all(|w| w.abs() < 1e-6); - if empty_wind { - wind = [0.0; 16]; - } - if here.is_empty() && empty_wind { + if here.is_empty() && backdrop == 0 { // Nothing here; and nothing further right either once the row's pieces are used. if !pieces.get(i).is_some_and(|p| p.row == row) { break; } continue; } - let tile_x = tx0 + col as u32; - let tile = (ty0 + row) * tiles_x + tile_x; - let bd = if empty_wind { - NONE - } else { - match last_bd { - Some((k, w)) if w == wind => k, - _ => { - let k = out.backdrops.len() as u32; - out.backdrops.extend_from_slice(wind.as_chunks::<4>().0); - last_bd = Some((k, wind)); - k - } - } - }; + let tile_x = range.tx0 + col as u32; + let tile = (range.ty0 + row) * tiles_x + tile_x; let (ox, oy) = ((tile_x * TILE) as f32, row_y0); let s0 = out.pieces.len() as u32; for p in here { out.pieces.push([p.seg[0] - ox, p.seg[1] - oy, p.seg[2] - ox, p.seg[3] - oy]); - add_rows(&mut wind, &p.seg, row_y0); } - out.entries.push([op, tile, s0, here.len() as u32, bd]); + out.entries.push([op, tile, s0, here.len() as u32, backdrop as u32]); + if !f.hairline { + backdrop += here.iter().map(|p| top_crossing(&p.seg, row_y0)).sum::(); + } } // Skip whatever is left of this row (pieces right of the range never get here). while pieces.get(i).is_some_and(|p| p.row == row) { @@ -604,38 +658,75 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec } } -/// The fill's tile range, in pixels and tiles. -struct Range { - ylo: f32, - yhi: f32, - xlo: f32, - xhi: f32, - ncols: i32, -} - -/// Adds the winding a piece gives everything to its right, per pixel row of its tile row. -fn add_rows(wind: &mut [f32; 16], seg: &[f32; 4], row_y0: f32) { - let (ya, yb, dir) = if seg[1] < seg[3] { (seg[1], seg[3], 1.0) } else { (seg[3], seg[1], -1.0) }; - let r0 = ((ya - row_y0).floor().max(0.0)) as usize; - let r1 = ((yb - row_y0).ceil().min(T)) as usize; - for r in r0..r1 { - let lo = row_y0 + r as f32; - let d = yb.min(lo + 1.0) - ya.max(lo); - if d > 0.0 - && let Some(w) = wind.get_mut(r) - { - *w += dir * d; +/// The edges of a closed polygon (fills) or the segments of an open polyline (hairlines; a +/// single point is a dot). +fn for_segments(poly: &[Vec2], mut f: impl FnMut(Vec2, Vec2)) { + match poly { + [] => {} + [p] => f(*p, *p), + _ => { + for w in poly.windows(2) { + f(w[0], w[1]); + } } } } -/// Splits edge `a → b` at tile rows and columns inside the fill's range. -fn split_edge(a: Vec2, b: Vec2, r: &Range, out: &mut Vec) { +/// The direction (`1` down, `−1` up) of a piece that starts on its tile row's top edge at +/// `row_y0`, which means its edge crosses that edge; `0` for any other piece. +pub(crate) fn top_crossing(seg: &[f32; 4], row_y0: f32) -> i32 { + if seg[1] == seg[3] || seg[1].min(seg[3]) != row_y0 { + return 0; + } + if seg[3] > seg[1] { 1 } else { -1 } +} + +/// A fill's tile range, in pixels and tiles. +#[derive(Clone, Copy)] +#[derive(Debug)] +pub(crate) struct Range { + pub(crate) tx0: u32, + pub(crate) ty0: u32, + pub(crate) ylo: f32, + pub(crate) yhi: f32, + pub(crate) xlo: f32, + pub(crate) xhi: f32, + pub(crate) ncols: i32, + pub(crate) nrows: i32, +} + +impl Range { + /// The tiles `f`'s bounds cover, within the surface's; `None` when there are none. + pub(crate) fn of(f: &Fill, tiles_x: u32, tiles_y: u32) -> Option { + let b = f.bounds; + if b.is_empty() { + return None; + } + let tx0 = b.x0.max(0) as u32 / TILE; + let tx1 = (b.x1.max(0) as u32).div_ceil(TILE).min(tiles_x); + let ty0 = b.y0.max(0) as u32 / TILE; + let ty1 = (b.y1.max(0) as u32).div_ceil(TILE).min(tiles_y); + if tx1 <= tx0 || ty1 <= ty0 { + return None; + } + let (ncols, nrows) = ((tx1 - tx0) as i32, (ty1 - ty0) as i32); + Some(Range { tx0, ty0, ylo: (ty0 * TILE) as f32, yhi: (ty1 * TILE) as f32, xlo: (tx0 * TILE) as f32, xhi: (tx1 * TILE) as f32, ncols, nrows }) + } + + fn row_y0(&self, row: u32) -> f32 { + ((self.ty0 + row) * TILE) as f32 + } +} + +/// Splits edge `a → b` at tile rows and columns inside the fill's range, row by row, each row's +/// pieces in the edge's direction of travel. Parts right of the fill's tiles come as column +/// `ncols` (they draw nothing, but the steps on the tiles' left edges need to see them). +fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32, [f32; 4])) { if !(a.is_finite() && b.is_finite()) || a.y == b.y { return; } - // Work top to bottom; restore the direction when storing. - let (p, q, down) = if a.y < b.y { (a, b, true) } else { (b, a, false) }; + let down = a.y < b.y; + let (p, q) = if down { (a, b) } else { (b, a) }; let y0 = p.y.max(r.ylo); let y1 = q.y.min(r.yhi); if y1 <= y0 { @@ -652,21 +743,26 @@ fn split_edge(a: Vec2, b: Vec2, r: &Range, out: &mut Vec) { if ye <= ys { continue; } - let (xs, xe) = (x_at(ys), x_at(ye)); - split_row(row, Vec2::new(xs, ys), Vec2::new(xe, ye), down, r, out); + let (top, bottom) = (Vec2::new(x_at(ys), ys), Vec2::new(x_at(ye), ye)); + if down { + split_row(row, top, bottom, r, &mut out); + } else { + split_row(row, bottom, top, r, &mut out); + } } } -/// Splits a piece inside one tile row at the fill's left and right edges and at tile columns. -fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec) { +/// Splits a piece inside one tile row, from `s` to `e` (the edge's direction), at the fill's +/// left and right edges and at tile columns: column −1 left of the fill's tiles, `ncols` right. +fn split_row(row: u32, s: Vec2, e: Vec2, r: &Range, out: &mut impl FnMut(u32, i32, [f32; 4])) { + let down = e.y > s.y; let mut push = |col: i32, u: Vec2, v: Vec2| { - if v.y <= u.y { + if (down && v.y <= u.y) || (!down && v.y >= u.y) { return; } - let seg = if down { [u.x, u.y, v.x, v.y] } else { [v.x, v.y, u.x, u.y] }; - out.push(Piece { row, col, seg }); + out(row, col, [u.x, u.y, v.x, v.y]); }; - // Points where the piece crosses a column boundary (or the range's edges), top to bottom. + // Points where the piece crosses a column boundary (or the range's edges), in order. let dx = e.x - s.x; let at_x = |x: f32| -> Vec2 { let t = ((x - s.x) / dx).clamp(0.0, 1.0); @@ -674,12 +770,15 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec= r.xhi { - return; // wholly right of the fill's tiles: it covers none of their pixels + push(r.ncols, s, e); + return; } // Most pieces (flattened curves are short) lie inside one tile column. let cl = col_of(lo); @@ -709,11 +808,133 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec>, + first: Vec>, + touched: Vec, +} + +impl Track { + /// Ready for a polygon of a fill with `nrows` tile rows. + fn start(&mut self, nrows: usize) { + for &r in &self.touched { + if let Some(l) = self.last.get_mut(r as usize) { + *l = None; + } + if let Some(f) = self.first.get_mut(r as usize) { + *f = None; + } + } + self.touched.clear(); + if self.last.len() < nrows { + self.last.resize(nrows, None); + self.first.resize(nrows, None); + } + } + + /// The next piece of the polygon in tile row `row`; the steps between it and the row's + /// previous piece go to `out`. + fn see(&mut self, row: u32, s: Seen, r: &Range, out: &mut impl FnMut(Piece)) { + let (Some(last), Some(first)) = (self.last.get_mut(row as usize), self.first.get_mut(row as usize)) else { return }; + match *last { + Some(p) => steps(p, s, row, r, out), + None => { + *first = Some(s); + self.touched.push(row); + } + } + *last = Some(s); + } + + /// The polygon is closed: each row's last piece is followed by its first. + fn finish(&mut self, r: &Range, out: &mut impl FnMut(Piece)) { + for &row in &self.touched { + if let (Some(Some(l)), Some(Some(f))) = (self.last.get(row as usize), self.first.get(row as usize)) { + steps(*l, *f, row, r, out); + } + } + } +} + +/// The steps in the winding along the tiles' left edges between consecutive pieces `a` and `b` +/// of one tile row (ADR 0048): where the outline passes from column `a.col` to `b.col`, at the +/// height where `a` ends, each tile boundary between them gets a vertical piece on its left +/// edge from there to the row's bottom: upwards when the outline runs right (the winding left +/// of the tile drops by one), downwards when it runs left. On the row's top edge the backdrop +/// has the step already, on its bottom edge it changes nothing. +fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { + if a.col == b.col { + return; + } + let top = r.ylo + (row * TILE) as f32; + let (y, bottom) = (a.end_y, top + T); + if !(y > top && y < bottom) { + return; + } + let right = a.col < b.col; + let (lo, hi) = if right { (a.col, b.col) } else { (b.col, a.col) }; + for k in (lo + 1).max(0)..=hi.min(r.ncols - 1) { + let x = r.xlo + k as f32 * T; + let seg = if right { [x, bottom, x, y] } else { [x, y, x, bottom] }; + out(Piece { row, col: k, seg }); + } +} + +/// Every tile of the range within `margin` of segment `a → b` (rows and columns padded by it), +/// as `(row, col)` relative to the range. With [`HAIRLINE_MARGIN`], every tile with a pixel +/// centre within a hairline's reach (`bin.wgsl` › `hairline` uses the same). +pub(crate) fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, margin: f32, mut out: impl FnMut(u32, i32)) { + if !(a.is_finite() && b.is_finite()) { + return; + } + let m = margin; + let (ymin, ymax) = (a.y.min(b.y), a.y.max(b.y)); + let r0 = (((ymin - m - r.ylo) / T).floor()).max(0.0); + let r1 = (((ymax + m - r.ylo) / T).floor()).min((r.nrows - 1) as f32); + if r1 < r0 { + return; + } + let (dx, dy) = (b.x - a.x, b.y - a.y); + for row in r0 as i32..=r1 as i32 { + let top = r.ylo + row as f32 * T; + // The segment's part within the row's band, then the columns within reach of it. + let (xa, xb) = if dy == 0.0 { + (a.x.min(b.x), a.x.max(b.x)) + } else { + let t0 = ((top - m - a.y) / dy).clamp(0.0, 1.0); + let t1 = ((top + T + m - a.y) / dy).clamp(0.0, 1.0); + let (u, v) = (a.x + dx * t0, a.x + dx * t1); + (u.min(v), u.max(v)) + }; + let c0 = (((xa - m - r.xlo) / T).floor()).max(0.0); + let c1 = (((xb + m - r.xlo) / T).floor()).min((r.ncols - 1) as f32); + if c1 < c0 { + continue; + } + for col in c0 as i32..=c1 as i32 { + out(row as u32, col); + } + } +} + /// Coverage of pixel `(px, py)` (tile-relative) from one piece: the same integral the oracle's /// accumulation buffer computes. Used by tests to check the binning on the CPU. #[cfg(test)] @@ -754,3 +975,12 @@ fn avg_clamp(u0: f32, u1: f32) -> f32 { pub(crate) fn solid_of(b: &Binned, op: usize) -> anicraft_render::paint::Premul { b.paints.get(PAINT_VEC4S * op).copied().unwrap_or([0.0; 4]) } + +/// How `fine.wgsl` reads a gradient's spread. +fn spread_code(s: anicraft_doc::Spread) -> f32 { + match s { + anicraft_doc::Spread::Pad => 0.0, + anicraft_doc::Spread::Reflect => 1.0, + anicraft_doc::Spread::Repeat => 2.0, + } +} diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 60ead56f..d57b638c 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -1,14 +1,17 @@ // AniCraft GPU stage: fine rasterization (ADR 0019, ADR 0029). // // One workgroup per 16 × 16 tile, one invocation per pixel. Each pixel walks its tile's entries -// in drawing order. An entry's coverage is its backdrop (winding from edges left of the tile, -// per pixel row) plus the exact area each of the tile's edge pieces covers in the pixel: the -// same integral as the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the -// fill rule, the paint (solid, or the oracle's own 256-entry gradient table) and src-over on -// premultiplied colour, all in f32, as the oracle does. +// in drawing order. An entry's coverage is its backdrop (the winding number just below the +// tile's top-left corner, an integer; ADR 0048) plus the exact area each of the tile's edge +// pieces covers in the pixel, the steps on the tile's left edge included: the same integral as +// the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the fill rule, the +// paint (solid, or the oracle's own 256-entry gradient table) and src-over on premultiplied +// colour, all in f32, as the oracle does. A hairline (ADR 0048) is 1 − the distance from the +// pixel centre to its nearest segment (crates/render/src/hairline.rs). // // Masks and groups (ADR 0029) are control entries in the same list, mirroring the oracle's band -// compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage, levels +// compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage (a soft +// mask's, ADR 0070, composites its paint and gives its opacity or luminance), levels // multiply into the clip coverage that clipped fills are scaled by; a group pushes the colour // so far and continues on transparent, and its close blends it into the colour below at the // group's alpha, in its blend mode (the W3C separable formulas, as the oracle's `blend`). @@ -66,6 +69,7 @@ const LEVEL_END: u32 = 0x80000005u; const CLIPPED: u32 = 1u; const ART: u32 = 2u; const MAX_GROUP_DEPTH: u32 = 8u; +const HAIRLINE: u32 = 2u; // Mean of clamp(u, 0, 1) for u running linearly from u0 to u1. fn avg_clamp(u0: f32, u1: f32) -> f32 { @@ -102,6 +106,22 @@ fn piece_cover(s: vec4, px: f32, py: f32) -> f32 { return dir * (yb - ya) * avg_clamp(px + 1.0 - xa, px + 1.0 - xb); } +// Distance from `p` to the segment `s` (x0, y0, x1, y1): hairline.rs › seg_dist, step by step. +fn seg_dist(p: vec2, s: vec4) -> f32 { + let dx = s.z - s.x; + let dy = s.w - s.y; + let qx = p.x - s.x; + let qy = p.y - s.y; + let l = dx * dx + dy * dy; + var t = 0.0; + if l > 0.0 { + t = clamp((qx * dx + qy * dy) / l, 0.0, 1.0); + } + let ex = qx - dx * t; + let ey = qy - dy * t; + return sqrt(ex * ex + ey * ey); +} + fn fold(w: f32, rule: u32) -> f32 { if rule == 0u { return min(abs(w), 1.0); @@ -137,21 +157,26 @@ fn finite(v: f32) -> bool { return (bitcast(v) & 0x7f800000u) != 0x7f800000u; } +// Rust's `rem_euclid` for i32 and `n` >= 1, without `%` on a negative operand: naga writes +// WGSL's `%` as GLSL's, which leaves negative operands undefined, so on the GL backend +// (llvmpipe in the FreeBSD VM) the texel left of or above a repeating bitmap's edge, -1, came +// out wrong. The unsigned remainder is defined everywhere. +fn wrap(i: i32, n: i32) -> i32 { + let r = i32(u32(abs(i)) % u32(n)); + return select(r, select(n - r, 0, r == 0), i < 0); +} + // One bitmap tap at integer (x, y) (wrapped when repeating, then clamped to the edges as // `Pixels::at` does), through the colour effect, premultiplied. -fn tap(slot: u32, x: i32, y: i32, size: vec2, repeat: bool, fx: vec4, tint: vec4) -> vec4 { +// The colour transform (ColorTransform::apply): each straight channel `c·mul + add`, clamped. +fn tap(slot: u32, x: i32, y: i32, size: vec2, repeat: bool, mul: vec4, add: vec4) -> vec4 { var q = vec2(x, y); if repeat { - q = ((q % size) + size) % size; + q = vec2(wrap(q.x, size.x), wrap(q.y, size.y)); } q = clamp(q, vec2(0), size - vec2(1)); - let c = texel(slot, q); - let keep = bitcast(tint.w); - let k = fx.z; - var rgb = clamp(c.rgb + (tint.rgb - c.rgb) * k, vec3(0.0), vec3(1.0)); - rgb = select(vec3(0.0), rgb, vec3((keep & 1u) != 0u, (keep & 2u) != 0u, (keep & 4u) != 0u)); - let a = clamp(c.a * fx.w, 0.0, 1.0); - return vec4(rgb * a, a); + let c = clamp(texel(slot, q) * mul + add, vec4(0.0), vec4(1.0)); + return vec4(c.rgb * c.a, c.a); } // Rust's `rem_euclid` for f32. @@ -160,14 +185,18 @@ fn rem_euclid(u: f32, n: f32) -> f32 { return select(r, r + n, r < 0.0); } -// The oracle's bilinear sample of a bitmap at pixel centre `p` (paint.rs › sample). -fn bitmap(base: u32, p: vec2) -> vec4 { +// The oracle's sample of a bitmap at pixel centre `p` (paint.rs › sample): bilinear, or the +// pixel `p` falls in when the bitmap doesn't allow smoothing (flag bit 1). +fn bitmap(base: u32, ramp: u32, p: vec2) -> vec4 { let h0 = paints[base]; let m = paints[base + 1u]; let n = paints[base + 2u]; - let tint = paints[base + 3u]; + let mul = paints[ramp]; + let add = paints[ramp + 1u]; let slot = bitcast(h0.x); - let repeat = bitcast(h0.y) != 0u; + let flags = bitcast(h0.y); + let repeat = (flags & 1u) != 0u; + let nearest = (flags & 2u) != 0u; let size = vec2(i32(bitcast(h0.z)), i32(bitcast(h0.w))); let w = f32(size.x); let h = f32(size.y); @@ -182,6 +211,9 @@ fn bitmap(base: u32, p: vec2) -> vec4 { } else if u < 0.0 || v < 0.0 || u >= w || v >= h { return vec4(0.0); } + if nearest { + return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, mul, add); + } let fx_ = u - 0.5; let fy_ = v - 0.5; let x0 = floor(fx_); @@ -190,10 +222,10 @@ fn bitmap(base: u32, p: vec2) -> vec4 { let ty = fy_ - y0; let xi = i32(x0); let yi = i32(y0); - let a = tap(slot, xi, yi, size, repeat, n, tint); - let b = tap(slot, xi + 1, yi, size, repeat, n, tint); - let c = tap(slot, xi, yi + 1, size, repeat, n, tint); - let d = tap(slot, xi + 1, yi + 1, size, repeat, n, tint); + let a = tap(slot, xi, yi, size, repeat, mul, add); + let b = tap(slot, xi + 1, yi, size, repeat, mul, add); + let c = tap(slot, xi, yi + 1, size, repeat, mul, add); + let d = tap(slot, xi + 1, yi + 1, size, repeat, mul, add); let top = a + (b - a) * tx; let bottom = c + (d - c) * tx; return top + (bottom - top) * ty; @@ -220,7 +252,7 @@ fn shade(op: u32, kind: u32, ramp: u32, p: vec2, x: u32, y: u32) -> vec4, x: u32, y: u32) -> vec4(m.x * p.x + m.z * p.y + n.x, m.y * p.x + m.w * p.y + n.y); + // Spread and focal point (crates/render/src/paint.rs › Spread::apply, focal_t). + let o = paints[base]; var t: f32; if kind == 1u { t = dot(q - n.zw, g.xy); } else { - t = length(q - n.zw) * g.z; + let u = (q - n.zw) * g.z; + let f = o.y; + if f == 0.0 { + t = length(u); + } else { + let d = vec2(u.x - f, u.y); + let a = 1.0 - f * f; + let fd = f * d.x; + t = (fd + sqrt(max(fd * fd + a * dot(d, d), 0.0))) / a; + } + } + let spread = u32(o.x + 0.5); + if spread == 2u { + t = t - floor(t); + if t >= 1.0 { + t = 0.0; + } + } else if spread == 1u { + let m = t - 2.0 * floor(t * 0.5); + if m > 1.0 { + t = 2.0 - m; + } else { + t = m; + } } t = clamp(t, 0.0, 1.0); let i = u32(t * 255.0 + 0.5) & 255u; @@ -328,6 +385,10 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { var depth = 0u; var mask = 1.0; var level = 0.0; + // A soft mask's level (ADR 0070): its mode (0 coverage, 1 alpha, 2 luminance) and its + // artwork's colour so far. + var level_mode = 0u; + var level_colour = vec4(0.0); let start = index[tile * 2u]; let count = index[tile * 2u + 1u]; for (var i = 0u; i < count; i++) { @@ -349,26 +410,61 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { } } case MASK_RESET: { mask = 1.0; } - case LEVEL_BEGIN: { level = 0.0; } - case LEVEL_END: { mask *= level; } + case LEVEL_BEGIN: { + level = 0.0; + level_mode = index[e + 1u]; + level_colour = vec4(0.0); + } + case LEVEL_END: { + // The oracle's MaskMode::reveal: opacity, or luminance (sRGB coefficients). + if level_mode == 1u { + level = level_colour.a; + } else if level_mode == 2u { + level = dot(level_colour.rgb, vec3(0.2125, 0.7154, 0.0721)); + } + mask *= clamp(level, 0.0, 1.0); + } default: {} } continue; } let first = index[e + 1u]; let pieces = index[e + 2u]; - let bd = index[e + 3u]; - var w = 0.0; - if bd != NONE { - w = geo[bd + (lid.y >> 2u)][lid.y & 3u]; - } - for (var k = 0u; k < pieces; k++) { - w += piece_cover(geo[first + k], px, py); - } let h = params.at.y + op * 4u; - var cov = fold(w, index[h + 1u]); + let rule = index[h + 1u]; + var cov = 0.0; + if rule == HAIRLINE { + var d = 2.0; + let pc = vec2(px + 0.5, py + 0.5); + for (var k = 0u; k < pieces; k++) { + let sg = geo[first + k]; + // Out of reach of the segment's box: at least 1 away, so it can't be nearest + // within reach (the coverage comes out the same, without the division). + let lo = min(sg.xy, sg.zw) - vec2(1.0); + let hi = max(sg.xy, sg.zw) + vec2(1.0); + if any(pc < lo) || any(pc > hi) { + continue; + } + d = min(d, seg_dist(pc, sg)); + } + cov = clamp(1.0 - d, 0.0, 1.0); + } else { + var w = f32(bitcast(index[e + 3u])); + for (var k = 0u; k < pieces; k++) { + w += piece_cover(geo[first + k], px, py); + } + cov = fold(w, rule); + } let flags = index[h + 3u]; if (flags & ART) != 0u { + if level_mode != 0u { + // Soft mask artwork composites as drawn (the oracle's `composite`). + if cov > 1e-4 { + let s = shade(op, index[h], index[h + 2u], centre, x, y); + level_colour = s * cov + level_colour * (1.0 - s.a * cov); + } + continue; + } let k = clamp(cov, 0.0, 1.0); level = level + k - level * k; continue; diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs new file mode 100644 index 00000000..3212934a --- /dev/null +++ b/crates/gpu/src/gpu_binning.rs @@ -0,0 +1,427 @@ +//! Tile binning on the GPU (ADR 0048): the host half. +//! +//! [`crate::binning`] is the reference: it splits every fill's edges into tile pieces on the +//! CPU. Here the CPU only lays out what the GPU needs, in time proportional to the fills and +//! their points, and `bin.wgsl` does the splitting, the backdrops and the tile lists: +//! +//! * the fills' points and polygons, one flat buffer, with each fill's tile range; +//! * one GPU invocation per row of tiles of each fill (an *op-row*), and room for each tile +//! of each fill's bounds (an *op-tile*): its piece count, backdrop, place and cursor; +//! * per tile row, the fills overlapping it in drawing order, and per tile where its entries +//! go: room for every fill whose bounds cover it (the GPU keeps those with pieces or a +//! backdrop there, in order); +//! * an upper bound of the pieces, from each edge's rows and columns, so every buffer is sized +//! before the GPU runs and nothing is read back. +//! +//! The passes count, scan (prefix sum), scatter and list; their output is the same tile lists +//! as the CPU's, bit for bit in everything but rounding (a test compares them per pixel). + +use crate::binning::{HAIRLINE_MARGIN, Range, TILE, hairline_tiles}; +use anicraft_render::Fill; +use rayon::prelude::*; + +/// An op that is a hairline (`bin.wgsl` › `HAIRLINE_BIT`). +const HAIRLINE_BIT: u32 = 1 << 31; +/// `u32`s per op in the input (`bin.wgsl` › `Op`). +const OP_WORDS: usize = 8; +/// Values one scan workgroup handles (`scan.wgsl`). +const SCAN_BLOCK: u32 = 1024; + +/// When and how far the GPU bins. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// The largest buffer the device binds (bytes). + pub binding: u64, + /// Fewer edges than this bin on the CPU, where it takes less than setting up the passes. + pub min_edges: u64, +} + +/// Most edge visits the GPU's per-row passes may make (each row of a fill walks all its +/// edges): far above real scenes (the 50k-shape 4K stress frame makes about 6 M), it keeps a +/// fill with very many edges over very many rows on the CPU, which splits each edge once. +pub const MAX_VISITS: u64 = 1 << 26; + +/// What the GPU needs to bin a scene, laid out by the CPU. +pub struct Plan { + /// The ops, polygons, points, op-row owners (and each op's first op-row), the rows' fills + /// and the rows' starts, at [`Plan::at`]. + pub(crate) input: Vec, + pub(crate) at: [u32; 6], + pub(crate) op_rows: u32, + /// Tiles of the fills' bounds: the entries' room and the working values' length. + pub op_tiles: u32, + /// Room for pieces: an upper bound. + pub piece_cap: u32, + /// `[start, 0]` per tile. + pub(crate) headers: Vec, + /// Edges, and edge visits by the per-row passes. + pub edges: u64, + pub visits: u64, +} + +/// What one fill needs: its range and how much room. +struct Info { + range: Option, + polys: u32, + points: u32, + edges: u64, + pieces: u64, +} + +fn info(f: &Fill, tiles_x: u32, tiles_y: u32) -> Info { + let Some(r) = Range::of(f, tiles_x, tiles_y) else { return Info { range: None, polys: 0, points: 0, edges: 0, pieces: 0 } }; + let mut pieces = 0u64; + let mut edges = 0u64; + for poly in &f.polys { + if f.hairline { + let mut seg = |a, b| { + pieces += hairline_pieces(a, b, &r); + edges += 1; + }; + match poly.as_slice() { + [] => {} + [p] => seg(*p, *p), + _ => poly.windows(2).for_each(|w| seg(w[0], w[1])), + } + } else { + let n = poly.len(); + if n < 2 { + continue; + } + for i in 0..n { + if let (Some(&a), Some(&b)) = (poly.get(i), poly.get((i + 1) % n)) { + pieces += edge_pieces(a, b, &r); + } + } + edges += n as u64; + } + } + let points = f.polys.iter().map(Vec::len).sum::() as u32; + Info { range: Some(r), polys: f.polys.len() as u32, points, edges, pieces } +} + +/// At most how many tiles a hairline segment reaches (`binning.rs` › `hairline_tiles`), with a +/// pixel more reach than the binning's, whatever the GPU's rounding: the tiles of its padded +/// box (most segments are short), or row by row for a long one, where the box would be loose. +fn hairline_pieces(a: anicraft_geom::Vec2, b: anicraft_geom::Vec2, r: &Range) -> u64 { + if !(a.is_finite() && b.is_finite()) { + return 0; + } + let (t, m) = (TILE as f32, HAIRLINE_MARGIN + 1.0); + let span = |lo: f32, hi: f32, base: f32, n: i32| (((hi + m - base) / t).floor().min((n - 1) as f32) - ((lo - m - base) / t).floor().max(0.0) + 1.0).max(0.0); + let rows = span(a.y.min(b.y), a.y.max(b.y), r.ylo, r.nrows); + let cols = span(a.x.min(b.x), a.x.max(b.x), r.xlo, r.ncols); + if rows * cols <= 16.0 { + return (rows * cols) as u64; + } + let mut n = 0u64; + hairline_tiles(a, b, r, m, |_, _| n += 1); + n +} + +/// At most how many pieces edge `a → b` gives (`binning.rs` › `split_edge` and `steps`): one +/// per tile row it spans, one more per column boundary it crosses, a left-edge step per column +/// boundary it passes, and one for where it meets the next edge; with slack for rounding. +fn edge_pieces(a: anicraft_geom::Vec2, b: anicraft_geom::Vec2, r: &Range) -> u64 { + if !(a.is_finite() && b.is_finite()) { + return 0; + } + let t = TILE as f32; + let (y0, y1) = (a.y.min(b.y).max(r.ylo), a.y.max(b.y).min(r.yhi)); + if y1 < y0 { + return 0; + } + let rows = ((y1 - r.ylo) / t).floor() - ((y0 - r.ylo) / t).floor() + 1.0; + let (x0, x1) = (a.x.min(b.x).max(r.xlo), a.x.max(b.x).min(r.xhi)); + let cols = if x1 >= x0 { ((x1 - r.xlo) / t).floor() - ((x0 - r.xlo) / t).floor() + 1.0 } else { 1.0 }; + (rows.clamp(0.0, r.nrows as f32 + 1.0) + 2.0 * cols.clamp(0.0, r.ncols as f32 + 1.0)) as u64 + 3 +} + +/// The plan for binning `fills` (the scene's, in drawing order) on a `tiles_x × tiles_y` +/// surface; `None` when the CPU should: too few edges to be worth it, too many visits, or a +/// buffer larger than the device binds. +pub fn plan(fills: &[Fill], tiles_x: u32, tiles_y: u32, lim: &Limits) -> Option { + let infos: Vec = fills.par_iter().map(|f| info(f, tiles_x, tiles_y)).collect(); + let n = fills.len(); + let (mut polys, mut points, mut op_tiles, mut op_rows, mut pieces, mut edges, mut visits) = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64); + for i in &infos { + polys += u64::from(i.polys); + points += u64::from(i.points); + pieces += i.pieces; + edges += i.edges; + if let Some(r) = &i.range { + op_tiles += (r.ncols as u64) * (r.nrows as u64); + op_rows += r.nrows as u64; + visits += (r.nrows as u64) * i.edges; + } + } + let tiles = u64::from(tiles_x) * u64::from(tiles_y); + let words = OP_WORDS as u64 * n as u64 + 2 * polys + 2 * points + op_rows + n as u64 + op_rows + u64::from(tiles_y) + 1; + let work_words = 4 * op_tiles + 2 * op_tiles.div_ceil(u64::from(SCAN_BLOCK)) + 64; + let fits = |bytes: u64| bytes <= lim.binding; + if edges < lim.min_edges || visits > MAX_VISITS || pieces >= u64::from(u32::MAX) || op_tiles >= u64::from(u32::MAX) / 4 { + return None; + } + if !(fits(4 * words) && fits(4 * work_words) && fits(16 * pieces) && fits(4 * (2 * tiles + 4 * op_tiles + 4 * n as u64))) { + return None; + } + + // Where everything goes. + let at_ops = 0usize; + let at_polys = at_ops + OP_WORDS * n; + let at_points = at_polys + 2 * polys as usize; + let at_row_of = at_points + 2 * points as usize; + let at_row_ops = at_row_of + op_rows as usize + n; + let at_row_start = at_row_ops + op_rows as usize; + let mut input = vec![0u32; at_row_start + tiles_y as usize + 1]; + + // Per op: its first polygon, point, op-tile and op-row. + let mut firsts = Vec::with_capacity(n); + let (mut p0, mut q0, mut t0, mut r0) = (0u32, 0u32, 0u32, 0u32); + for i in &infos { + firsts.push((p0, q0, t0, r0)); + p0 += i.polys; + q0 += i.points; + if let Some(r) = &i.range { + t0 += (r.ncols * r.nrows) as u32; + r0 += r.nrows as u32; + } + } + { + let (head, rest) = input.split_at_mut(at_polys); + let (poly_words, rest) = rest.split_at_mut(at_points - at_polys); + let (point_words, rest) = rest.split_at_mut(at_row_of - at_points); + let (row_of, rest) = rest.split_at_mut(op_rows as usize); + let (row_base, rest) = rest.split_at_mut(n); + let (row_ops, row_start) = rest.split_at_mut(op_rows as usize); + // Each op's slices of the polygon and point tables, then filled in parallel. + let mut jobs: Vec = Vec::with_capacity(n); + let (mut pw, mut qw) = (poly_words, point_words); + for ((h, f), (i, first)) in head.chunks_mut(OP_WORDS).zip(fills).zip(infos.iter().zip(&firsts)) { + let (a, b) = std::mem::take(&mut pw).split_at_mut(2 * i.polys as usize); + let (c, d) = std::mem::take(&mut qw).split_at_mut(2 * i.points as usize); + pw = b; + qw = d; + jobs.push((h, a, c, f, i, *first)); + } + jobs.into_par_iter().for_each(|(h, pw, qw, f, i, (p0, q0, t0, _))| { + let (tx0, ty0, ncols, nrows) = i.range.map_or((0, 0, 0, 0), |r| (r.tx0, r.ty0, r.ncols as u32, r.nrows as u32)); + let flags = if f.hairline { HAIRLINE_BIT } else { 0 }; + h.copy_from_slice(&[p0, i.polys, tx0, ty0, ncols, nrows, t0, flags]); + let mut q = q0; + for (slot, poly) in pw.as_chunks_mut::<2>().0.iter_mut().zip(&f.polys) { + slot.copy_from_slice(&[q, poly.len() as u32]); + q += poly.len() as u32; + } + for (slot, p) in qw.as_chunks_mut::<2>().0.iter_mut().zip(f.polys.iter().flatten()) { + slot.copy_from_slice(&[p.x.to_bits(), p.y.to_bits()]); + } + }); + // Op-rows in op order: who owns each, and each op's first. + let mut k = 0usize; + for (op, (i, first)) in infos.iter().zip(&firsts).enumerate() { + if let Some(b) = row_base.get_mut(op) { + *b = first.3; + } + for _ in 0..i.range.map_or(0, |r| r.nrows) { + if let Some(o) = row_of.get_mut(k) { + *o = op as u32; + } + k += 1; + } + } + // Each tile row's fills, in drawing order (a counting sort by row). + for i in &infos { + if let Some(r) = &i.range { + for row in r.ty0..r.ty0 + r.nrows as u32 { + if let Some(c) = row_start.get_mut(row as usize + 1) { + *c += 1; + } + } + } + } + for j in 1..row_start.len() { + row_start[j] += row_start[j - 1]; + } + let mut cursor: Vec = row_start.to_vec(); + for (op, i) in infos.iter().enumerate() { + if let Some(r) = &i.range { + for row in r.ty0..r.ty0 + r.nrows as u32 { + if let Some(c) = cursor.get_mut(row as usize) + && let Some(slot) = row_ops.get_mut(*c as usize) + { + *slot = op as u32; + *c += 1; + } + } + } + } + } + // Where each tile's entries go: room for every fill whose bounds cover it (a 2D running + // sum over the bounds' corners). + let (w, h) = (tiles_x as usize + 1, tiles_y as usize + 1); + let mut cover = vec![0i64; w * h]; + for r in infos.iter().filter_map(|i| i.range) { + let (x0, y0, x1, y1) = (r.tx0 as usize, r.ty0 as usize, r.tx0 as usize + r.ncols as usize, r.ty0 as usize + r.nrows as usize); + for (x, y, d) in [(x0, y0, 1), (x1, y0, -1), (x0, y1, -1), (x1, y1, 1)] { + if let Some(c) = cover.get_mut(y * w + x) { + *c += d; + } + } + } + for y in 0..h { + for x in 0..w { + let left = if x > 0 { cover[y * w + x - 1] } else { 0 }; + let up = if y > 0 { cover[(y - 1) * w + x] } else { 0 }; + let diag = if x > 0 && y > 0 { cover[(y - 1) * w + x - 1] } else { 0 }; + cover[y * w + x] += left + up - diag; + } + } + let mut headers = vec![0u32; 2 * tiles as usize]; + let mut start = 0u64; + for ty in 0..tiles_y as usize { + for tx in 0..tiles_x as usize { + if let Some(hd) = headers.get_mut(2 * (ty * tiles_x as usize + tx)) { + *hd = start as u32; + } + start += cover.get(ty * w + tx).copied().unwrap_or(0).max(0) as u64; + } + } + if start != op_tiles { + return None; // the room per tile must add up to the op-tiles (it always does) + } + let at = [at_ops, at_polys, at_points, at_row_of, at_row_ops, at_row_start].map(|a| a as u32); + Some(Plan { input, at, op_rows: op_rows as u32, op_tiles: op_tiles as u32, piece_cap: pieces as u32, headers, edges, visits }) +} + +/// One op's share of the input to fill in: its record, polygon and point words, the fill, its +/// sizes, and its first polygon, point, op-tile and op-row. +type Job<'a> = (&'a mut [u32], &'a mut [u32], &'a mut [u32], &'a Fill, &'a Info, (u32, u32, u32, u32)); + +/// The binning pipelines (`bin.wgsl`, `scan.wgsl`). +pub(crate) struct Pipelines { + count: wgpu::ComputePipeline, + scatter: wgpu::ComputePipeline, + tiles: wgpu::ComputePipeline, + layout: wgpu::BindGroupLayout, + scan_blocks: wgpu::ComputePipeline, + scan_add: wgpu::ComputePipeline, + scan_layout: wgpu::BindGroupLayout, +} + +impl Pipelines { + pub(crate) fn new(device: &wgpu::Device) -> Pipelines { + let entry = |binding: u32, ty: wgpu::BufferBindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, count: None }; + let rw = wgpu::BufferBindingType::Storage { read_only: false }; + let bin_entries = [entry(0, wgpu::BufferBindingType::Uniform), entry(1, wgpu::BufferBindingType::Storage { read_only: true }), entry(2, rw), entry(3, rw), entry(4, rw)]; + let ([count, scatter, tiles], layout) = pipelines(device, "anicraft-bin", include_str!("bin.wgsl"), &bin_entries, ["count", "scatter", "tiles"]); + let ([scan_blocks, scan_add], scan_layout) = pipelines(device, "anicraft-scan", include_str!("scan.wgsl"), &[entry(0, wgpu::BufferBindingType::Uniform), entry(1, rw)], ["scan_blocks", "scan_add"]); + Pipelines { count, scatter, tiles, layout, scan_blocks, scan_add, scan_layout } + } +} + +/// One shader's entry points as pipelines sharing one bind group layout. +fn pipelines(device: &wgpu::Device, label: &str, src: &str, entries: &[wgpu::BindGroupLayoutEntry], points: [&str; N]) -> ([wgpu::ComputePipeline; N], wgpu::BindGroupLayout) { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(src.into()) }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: &[Some(&layout)], immediate_size: 0 }); + let pipes = points.map(|p| device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(p), layout: Some(&pl), module: &module, entry_point: Some(p), compilation_options: Default::default(), cache: None })); + (pipes, layout) +} + +/// Workgroups for `n` invocations of `width`, spread over x and y (at most 65,535 each way). +fn groups(n: u32, width: u32) -> (u32, u32) { + let g = n.div_ceil(width).max(1); + let x = g.min(65_535); + (x, g.div_ceil(x)) +} + +/// The fine pass's index and pieces, binned on the GPU into `enc` from `plan`: the index with +/// the tile headers at 0 and `op_heads` at `ops_at`. Only those are uploaded (through `queue`, +/// ahead of `enc`'s submission): the entries' room starts zeroed on the GPU. +#[allow(clippy::too_many_arguments)] +pub(crate) fn record(device: &wgpu::Device, queue: &wgpu::Queue, pipes: &Pipelines, enc: &mut wgpu::CommandEncoder, plan: &Plan, tiles_x: u32, tiles_y: u32, entries_at: u32, ops_at: u32, op_heads: &[u32]) -> Result<(wgpu::Buffer, wgpu::Buffer), String> { + use wgpu::util::DeviceExt; + let index_len = (ops_at as usize + op_heads.len()).max(4); + let index = device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * index_len as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + if !plan.headers.is_empty() && plan.headers.len() <= index_len { + queue.write_buffer(&index, 0, bytemuck::cast_slice(&plan.headers)); + } + if !op_heads.is_empty() && ops_at as usize + op_heads.len() <= index_len { + queue.write_buffer(&index, 4 * u64::from(ops_at), bytemuck::cast_slice(op_heads)); + } + let geo = device.create_buffer(&wgpu::BufferDescriptor { label: Some("geo"), size: 16 * u64::from(plan.piece_cap.max(1)), usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); + if plan.op_rows == 0 { + return Ok((index, geo)); + } + let n = plan.op_tiles; + // Counts, backdrops, offsets, cursors, then the scan's totals level by level. New buffers + // start zeroed. + let mut levels: Vec<[u32; 4]> = Vec::new(); + let (mut src, mut dst, mut len, mut sums) = (0u32, 2 * n, n, 4 * n); + loop { + let blocks = len.div_ceil(SCAN_BLOCK); + levels.push([src, dst, sums, len]); + if blocks <= 1 { + break; + } + (src, dst, len) = (sums, sums, blocks); + sums += blocks; + } + let work_len = (sums + 2) as u64; + let work = device.create_buffer(&wgpu::BufferDescriptor { label: Some("bin-work"), size: 4 * work_len, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false }); + let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("bin-input"), contents: bytemuck::cast_slice(&plan.input), usage: wgpu::BufferUsages::STORAGE }); + let tiles = tiles_x * tiles_y; + let a = plan.at; + let params: [u32; 16] = [tiles_x, tiles_y, plan.op_rows, tiles, n, plan.piece_cap, entries_at, 0, a[0], a[1], a[2], a[3], a[4], a[5], 0, 0]; + let ubuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("bin-params"), contents: bytemuck::cast_slice(¶ms), usage: wgpu::BufferUsages::UNIFORM }); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("anicraft-bin"), + layout: &pipes.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: work.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: geo.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: index.as_entire_binding() }, + ], + }); + let scans: Vec<(wgpu::BindGroup, u32)> = levels + .iter() + .map(|l| { + let u = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("scan-params"), contents: bytemuck::cast_slice(l), usage: wgpu::BufferUsages::UNIFORM }); + let b = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("anicraft-scan"), + layout: &pipes.scan_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: u.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: work.as_entire_binding() }], + }); + (b, l[3].div_ceil(SCAN_BLOCK)) + }) + .collect(); + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("anicraft-bin"), timestamp_writes: None }); + let rows = groups(plan.op_rows, 64); + pass.set_pipeline(&pipes.count); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(rows.0, rows.1, 1); + // The scan, level by level up, then each level's totals added back down. + pass.set_pipeline(&pipes.scan_blocks); + for (b, blocks) in &scans { + let g = groups(*blocks, 1); + pass.set_bind_group(0, b, &[]); + pass.dispatch_workgroups(g.0, g.1, 1); + } + pass.set_pipeline(&pipes.scan_add); + for (b, blocks) in scans.iter().rev().skip(1) { + let g = groups(*blocks, 1); + pass.set_bind_group(0, b, &[]); + pass.dispatch_workgroups(g.0, g.1, 1); + } + pass.set_pipeline(&pipes.scatter); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(rows.0, rows.1, 1); + let t = groups(tiles, 64); + pass.set_pipeline(&pipes.tiles); + pass.dispatch_workgroups(t.0, t.1, 1); + drop(pass); + Ok((index, geo)) +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index ce7251c2..43ebd905 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -2,10 +2,11 @@ //! //! Draws the same scene as the CPU oracle (`anicraft-render`) with wgpu compute: the oracle //! prepares it ([`anicraft_render::prepare_scene`]: flattening, strokes, paints and their -//! gradient tables, clips and groups), [`binning`] sorts the edges into 16 × 16 tiles on the -//! CPU, and one compute pass computes every pixel's exact area coverage and composites the -//! fills in order, inside their masks and groups (alpha and blend modes) as the oracle's band -//! compositor does. Bitmap fills are sampled from textures uploaded once per image +//! gradient tables, clips and groups), the edges are sorted into 16 × 16 tiles, on the GPU +//! ([`gpu_binning`], ADR 0048) or on the CPU ([`binning`], the reference, and the way for fills +//! in masks and groups), and one compute pass computes every pixel's exact area coverage +//! (or a hairline's distance) and composites the fills in order, inside their masks and groups +//! (alpha and blend modes) as the oracle's band compositor does. Bitmap fills are sampled from textures uploaded once per image //! ([`images`]); a filtered symbol is drawn into a layer of its own, filtered by compute passes //! that run the oracle's filter steps ([`layers`]), and composited like any fill (ADR 0032). //! The output is the oracle's within float rounding (the parity tests check mean and maximum @@ -22,6 +23,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod binning; +pub mod gpu_binning; pub mod images; mod layers; @@ -29,6 +31,7 @@ use anicraft_doc::DisplayList; use anicraft_render::{MAX_PIXELS, NeedsFull, Pixmap, RenderStats, View, paint::premultiply, prepare_scene}; #[cfg(not(target_arch = "wasm32"))] use rayon::prelude::*; +use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use web_time::Instant; use wgpu::util::DeviceExt; @@ -68,11 +71,58 @@ pub struct GpuFrame { pub pixmap: Option, pub stats: RenderStats, pub timings: Timings, - /// Tile entries and edge pieces the fine pass walked. + /// Tile entries and edge pieces the fine pass walked (when binned on the GPU, the room + /// made for them: upper bounds). pub entries: usize, pub pieces: usize, + /// Whether the GPU binned the frame's tiles ([`Binning`]). + pub gpu_binned: bool, } +/// Where a frame's edges are sorted into tiles (ADR 0048). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Binning { + /// On the GPU when the scene can take it (no fill inside a mask or a group, for now), has + /// enough edges to be worth the passes ([`AUTO_MIN_EDGES`]) and the device runs Vulkan + /// (where it was measured to win); otherwise on the CPU. + Auto, + /// Always on the CPU (the reference). + Cpu, + /// On the GPU whenever the scene can take it, however small (tests and benchmarks). + Gpu, +} + +impl Binning { + fn code(self) -> u8 { + match self { + Binning::Auto => 0, + Binning::Cpu => 1, + Binning::Gpu => 2, + } + } + + fn from_code(c: u8) -> Binning { + match c { + 1 => Binning::Cpu, + 2 => Binning::Gpu, + _ => Binning::Auto, + } + } + + /// `ANICRAFT_GPU_BINNING=cpu|gpu|auto` (for comparing them in the app); auto otherwise. + fn from_env() -> Binning { + match std::env::var("ANICRAFT_GPU_BINNING").map(|v| v.trim().to_ascii_lowercase()).as_deref() { + Ok("cpu") => Binning::Cpu, + Ok("gpu") => Binning::Gpu, + _ => Binning::Auto, + } + } +} + +/// Fewer edges than this are binned on the CPU in [`Binning::Auto`]: below it the CPU bins a +/// frame in less time than the GPU's passes take to set up (measured, docs/performance.md). +pub const AUTO_MIN_EDGES: u64 = 32_768; + /// A frame rendered into a texture on the renderer's device: premultiplied RGBA8 /// (`Rgba8Unorm`, the bytes [`Pixmap::to_premul_rgba8`] gives), sampleable, ready for the window /// to show (egui's `register_native_texture`). The work is submitted, not waited for: anything @@ -86,6 +136,7 @@ pub struct GpuTexture { pub timings: Timings, pub entries: usize, pub pieces: usize, + pub gpu_binned: bool, } /// Where a frame's time went (milliseconds, on the calling thread). @@ -93,7 +144,8 @@ pub struct GpuTexture { pub struct Timings { /// Cull, flatten, stroke and paint set-up (shared with the oracle, parallel). pub prepare: f32, - /// Tile binning (parallel per fill and per tile row) and buffer packing. + /// Tile binning on the CPU (parallel per fill and per tile row), or laying out the GPU's + /// binning (per fill), and buffer packing. pub bin: f32, /// Upload and submit; for read-back frames also the wait for the GPU and the copy back. pub gpu: f32, @@ -131,6 +183,16 @@ pub struct GpuRenderer { texture_pipeline: wgpu::ComputePipeline, texture_layout: wgpu::BindGroupLayout, filters: layers::FilterPipelines, + bins: gpu_binning::Pipelines, + /// [`Binning`], as its code. + binning: AtomicU8, + /// Why the GPU doesn't bin on this device (its self-test came back wrong); then every + /// frame bins on the CPU, and the rest of the GPU stage still runs. + no_gpu_binning: Mutex>, + /// Whether [`Binning::Auto`] bins on the GPU on this backend: on Vulkan, where it was + /// measured to win in the stage's tiles. On Direct3D 12 the passes cost more per stage tile + /// than the CPU's binning (ADR 0048), and other backends aren't measured yet. + auto_bins: bool, /// Bound where a texture slot or a buffer is unused. blank: wgpu::TextureView, /// Placeholders for a filter pass's coverage (written) and ramp (read): one buffer can't be @@ -247,7 +309,7 @@ impl GpuRenderer { } let limits = device.limits(); check(adapter, &limits, &name)?; - Self::build(device, queue, limits, name, true, Arc::new(Mutex::new(None))) + Self::build(device, queue, limits, name, info.backend, true, Arc::new(Mutex::new(None))) })) .unwrap_or_else(|_| Err(GpuError::Unavailable("the GPU driver failed while starting".into()))) } @@ -285,10 +347,10 @@ impl GpuRenderer { g.get_or_insert_with(|| format!("device lost: {msg}")); }); } - Self::build(device, queue, want, name, false, broken) + Self::build(device, queue, want, name, info.backend, false, broken) } - fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, shared: bool, broken: Arc>>) -> Result { + fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, backend: wgpu::Backend, shared: bool, broken: Arc>>) -> Result { let scopes = Scopes::push(&device); let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("anicraft-fine"), source: wgpu::ShaderSource::Wgsl(include_str!("fine.wgsl").into()) }); let entry = |binding: u32, ty: wgpu::BindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }; @@ -316,6 +378,7 @@ impl GpuRenderer { let storage_texture = wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: wgpu::TextureFormat::Rgba8Unorm, view_dimension: wgpu::TextureViewDimension::D2 }; let (texture_pipeline, texture_layout) = make("anicraft-fine-texture", entry(5, storage_texture), "main_texture"); let filters = layers::FilterPipelines::new(&device); + let bins = gpu_binning::Pipelines::new(&device); let blank = device .create_texture(&wgpu::TextureDescriptor { label: Some("anicraft-blank"), @@ -341,6 +404,10 @@ impl GpuRenderer { texture_pipeline, texture_layout, filters, + bins, + binning: AtomicU8::new(Binning::from_env().code()), + no_gpu_binning: Mutex::new(None), + auto_bins: backend == wgpu::Backend::Vulkan, blank, blank_coverage, blank_ramp, @@ -359,7 +426,7 @@ impl GpuRenderer { /// symbol within the parity target. Catches drivers that build the pipelines but compute /// garbage. fn self_test(&self) -> Result<(), GpuError> { - use anicraft_doc::{ColorEffect, DisplayItem, ElementId, Filter, Group, LayerId, Paint, Pixels, Rgba}; + use anicraft_doc::{ColorTransform, DisplayItem, ElementId, Filter, Group, LayerId, Paint, Pixels, Rgba}; use anicraft_geom::{Affine, FillRule, Path}; let item = |path: Path, fill: Paint| DisplayItem { path: Arc::new(path), @@ -367,7 +434,7 @@ impl GpuRenderer { fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::IDENTITY, layer: LayerId(0), element: ElementId(0), outline: None, @@ -376,6 +443,8 @@ impl GpuRenderer { guide: false, group: None, image: None, + smooth: true, + warp: None, }; let solid = |x: f32, c: Rgba| item(Path::rect(x, 2.0, 8.0, 16.0), Paint::Solid(c)); let mut bitmap = item(Path::rect(2.0, 18.0, 20.0, 2.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::scale(3.0, 1.0) }); @@ -384,7 +453,7 @@ impl GpuRenderer { blurred.group = Some(0); let filters = Arc::from(vec![Filter::Blur { blur_x: 3.0, blur_y: 2.0, quality: 2 }, Filter::AdjustColor { brightness: 10.0, contrast: 0.0, saturation: -50.0, hue: 30.0 }]); let groups = vec![Group { parent: None, alpha: 1.0, blend: anicraft_doc::BlendMode::Normal, filters, clip: None }]; - let dl = DisplayList { items: vec![solid(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), solid(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5)), bitmap, blurred], groups, ..Default::default() }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![solid(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), solid(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5)), bitmap, blurred], groups, ..Default::default() }; let view = View { transform: Affine::IDENTITY, width: 24, height: 20, background: Some(Rgba::WHITE) }; let (oracle, _) = anicraft_render::render(&dl, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; let oracle = oracle.to_premul_rgba8(); @@ -400,9 +469,38 @@ impl GpuRenderer { let off = d.map_or("a wrong size".to_string(), |d| format!("{} of {} pixels off, by up to {}/255{at}", d.differing, d.pixels, d.max)); Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong {how} ({off})", self.adapter))) }; - check("read back", &self.render(&dl, &view, Output::Premul8)?.premul8)?; - let t = self.render_texture(&dl, &view)?; - check("through a texture", &self.read_texture(&t)?) + check("read back", &self.render_with(&dl, &view, Output::Premul8, Binning::Cpu)?.premul8)?; + let t = self.render_texture_with(&dl, &view, Binning::Cpu)?; + check("through a texture", &self.read_texture(&t)?)?; + // Binned on the GPU (the plain fills; the bitmap and the symbol bin on the CPU): if that + // comes back wrong, only the binning stays on the CPU here. + let plain = DisplayList { clip_modes: Vec::new(), items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; + let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; + let why = match self.render_with(&plain, &view, Output::Premul8, Binning::Gpu) { + Ok(got) => match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { + Some(d) if got.gpu_binned && d.max <= 2 && d.mean <= 0.1 => None, + Some(d) if got.gpu_binned => Some(format!("{} of {} pixels off, by up to {}/255", d.differing, d.pixels, d.max)), + _ => Some("it wasn't binned on the GPU".to_string()), + }, + Err(GpuError::Device(e)) => return Err(GpuError::Unavailable(format!("{}: the GPU binning failed: {e}", self.adapter))), + Err(e) => Some(e.to_string()), + }; + *self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner) = why.map(|w| format!("{}: the self-test came back wrong binned on the GPU ({w}); binning on the CPU", self.adapter)); + Ok(()) + } + + /// Why the GPU doesn't bin on this device, if it doesn't (for Preferences and reports). + pub fn gpu_binning_off(&self) -> Option { + self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + + /// Where frames' edges are sorted into tiles from now on. + pub fn set_binning(&self, b: Binning) { + self.binning.store(b.code(), Ordering::Relaxed); + } + + pub fn binning(&self) -> Binning { + Binning::from_code(self.binning.load(Ordering::Relaxed)) } /// Whether the device has failed (lost, or an error in or outside a render); then use the @@ -415,6 +513,13 @@ impl GpuRenderer { self.broken.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(|| why.to_string()); } + /// Marks the renderer failed from outside (ADR 0092): a renderer on the window's device + /// hears of the device's loss from the window, which owns the device's callbacks. Every + /// later call refuses with `why` (the first reason given stays), and callers draw on the CPU. + pub fn fail(&self, why: &str) { + self.mark_broken(why); + } + /// Bitmaps uploaded and kept, and their bytes (at most about [`images::IMAGE_BUDGET`]). pub fn cached_images(&self) -> (usize, u64) { self.images.lock().unwrap_or_else(PoisonError::into_inner).held() @@ -423,19 +528,29 @@ impl GpuRenderer { /// Renders a display list and reads it back. [`GpuError::NeedsFull`] means "draw this one /// on the CPU". pub fn render(&self, dl: &DisplayList, view: &View, output: Output) -> Result { + self.render_with(dl, view, output, self.binning()) + } + + /// [`GpuRenderer::render`], binned as `binning` says (tests and benchmarks). + pub fn render_with(&self, dl: &DisplayList, view: &View, output: Output, binning: Binning) -> Result { self.guard(|| { - let (job, stats, mut timings, cost) = self.prepare(dl, view)?; + let (job, stats, mut timings, cost) = self.prepare(dl, view, binning)?; let t = Instant::now(); let (premul8, pixmap) = self.run_readback(&job, view, output)?; timings.gpu = ms(t); - Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: cost.entries, pieces: cost.pieces }) + Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() }) }) } /// Renders a display list into a new texture on this renderer's device (no readback). pub fn render_texture(&self, dl: &DisplayList, view: &View) -> Result { + self.render_texture_with(dl, view, self.binning()) + } + + /// [`GpuRenderer::render_texture`], binned as `binning` says (tests and benchmarks). + pub fn render_texture_with(&self, dl: &DisplayList, view: &View, binning: Binning) -> Result { self.guard(|| { - let (job, stats, mut timings, cost) = self.prepare(dl, view)?; + let (job, stats, mut timings, cost) = self.prepare(dl, view, binning)?; let t = Instant::now(); let (w, h) = (view.width, view.height); let max = self.limits.max_texture_dimension_2d; @@ -464,7 +579,7 @@ impl GpuRenderer { self.queue.submit([enc.finish()]); self.pop(scopes)?; timings.gpu = ms(t); - Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces }) + Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() }) }) } @@ -511,14 +626,14 @@ impl GpuRenderer { /// The oracle's preparation and the binning, for the scene and each filtered layer it shows /// (in parallel); checked against the limits and the device's. - fn prepare(&self, dl: &DisplayList, view: &View) -> Result<(Job, RenderStats, Timings, Cost), GpuError> { + fn prepare(&self, dl: &DisplayList, view: &View, binning: Binning) -> Result<(Job, RenderStats, Timings, Cost), GpuError> { let (w, h) = (view.width, view.height); if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { return Err(GpuError::TooLarge(format!("image {w}×{h} is outside the GPU stage's range"))); } let t0 = Instant::now(); let mut bin_ms = 0.0; - let (job, stats) = self.plan(dl, view, 0, &mut bin_ms)?; + let (job, stats) = self.plan(dl, view, 0, binning, &mut bin_ms)?; let total = ms(t0); let mut cost = Cost::default(); job.cost(&mut cost); @@ -533,10 +648,18 @@ impl GpuRenderer { } /// One scene: prepared and binned, then its shown layers planned the same way. - fn plan(&self, dl: &DisplayList, view: &View, depth: usize, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> { + fn plan(&self, dl: &DisplayList, view: &View, depth: usize, binning: Binning, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> { let (mut scene, stats) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?; let t = Instant::now(); - let binned = binning::bin(&scene, view.width, view.height).map_err(GpuError::NeedsFull)?; + let off = self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner).is_some(); + let lim = match binning { + _ if off => None, + Binning::Cpu => None, + Binning::Auto if !self.auto_bins => None, + Binning::Auto => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: AUTO_MIN_EDGES }), + Binning::Gpu => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }), + }; + let binned = binning::bin_with(&scene, view.width, view.height, lim.as_ref()).map_err(GpuError::NeedsFull)?; *bin_ms += ms(t); let shown: Vec<(u32, anicraft_render::FilterLayer)> = std::mem::take(&mut scene.layers).into_iter().zip(&binned.layer_at).filter_map(|(l, at)| Some(((*at)?, l))).collect(); // Free the prepared polygons on the pool, off this frame's path (as the oracle does). @@ -553,7 +676,7 @@ impl GpuRenderer { let shown = shown.into_iter(); let planned: Vec> = shown .map(|(at, l)| { - let (job, _) = self.plan(&l.list, &l.view, depth + 1, &mut 0.0)?; + let (job, _) = self.plan(&l.list, &l.view, depth + 1, binning, &mut 0.0)?; Ok(LayerJob { at, job: Box::new(job), view: l.view, ops: l.filters }) }) .collect(); @@ -561,11 +684,17 @@ impl GpuRenderer { Ok((Job { binned, layers }, stats)) } + /// The largest buffer the device binds. + fn binding_cap(&self) -> u64 { + self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size) + } + /// Every buffer a job binds fits what the device binds. fn check_sizes(&self, job: &Job) -> Result<(), GpuError> { - let cap = self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size); + let cap = self.binding_cap(); let b = &job.binned; - let sizes = [("tile lists", b.index.len() as u64 * 4), ("edges", b.geo.len() as u64 * 16), ("paints and layers", b.paints_len as u64 * 16)]; + let pieces = b.gpu.as_ref().map_or(b.geo.len() as u64, |p| u64::from(p.piece_cap)); + let sizes = [("tile lists", (u64::from(b.ops_at) + b.op_heads.len() as u64) * 4), ("edges", pieces * 16), ("paints and layers", b.paints_len as u64 * 16)]; for (what, n) in sizes { if n > cap { return Err(GpuError::TooLarge(format!("{what} need {} MB, more than this GPU binds ({} MB)", n >> 20, cap >> 20))); @@ -613,13 +742,34 @@ impl GpuRenderer { enc.copy_buffer_to_buffer(&img, 0, &pbuf, u64::from(l.at) * 16, 16 * n); } let views = self.images.lock().unwrap_or_else(PoisonError::into_inner).views(&self.device, &self.queue, self.limits.max_texture_dimension_2d, &b.images)?; - self.fine_pass(enc, b, &pbuf, &views, view, output, target); + let (ibuf, gbuf) = match &b.gpu { + Some(plan) => gpu_binning::record(&self.device, &self.queue, &self.bins, enc, plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?, + None => self.upload_lists(b)?, + }; + self.fine_pass(enc, b, &ibuf, &gbuf, &pbuf, &views, view, output, target); Ok(()) } + /// The CPU's tile lists and op headers, and its pieces, as buffers. + fn upload_lists(&self, b: &binning::Binned) -> Result<(wgpu::Buffer, wgpu::Buffer), GpuError> { + let len = (b.ops_at as usize + b.op_heads.len()).max(4); + let ibuf = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * len as u64, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: true }); + { + let mut m = ibuf.slice(..).get_mapped_range_mut().map_err(|e| GpuError::Device(e.to_string()))?; + write_words(&mut m, 0, &b.index); + write_words(&mut m, b.ops_at as usize, &b.op_heads); + } + ibuf.unmap(); + // Bindings can't be empty: pad to one vec4. + let pad = [[0f32; 4]]; + let geo: &[[f32; 4]] = if b.geo.is_empty() { &pad } else { &b.geo }; + let gbuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("geo"), contents: bytemuck::cast_slice(geo), usage: wgpu::BufferUsages::STORAGE }); + Ok((ibuf, gbuf)) + } + /// Uploads the binned scene and records the fine pass into `target`. #[allow(clippy::too_many_arguments)] - fn fine_pass(&self, enc: &mut wgpu::CommandEncoder, b: &binning::Binned, pbuf: &wgpu::Buffer, images: &[wgpu::TextureView], view: &View, output: Output, target: Target) { + fn fine_pass(&self, enc: &mut wgpu::CommandEncoder, b: &binning::Binned, ibuf: &wgpu::Buffer, gbuf: &wgpu::Buffer, pbuf: &wgpu::Buffer, images: &[wgpu::TextureView], view: &View, output: Output, target: Target) { let bg = view.background.map_or([0.0; 4], premultiply); let mut uniform = [0u32; 12]; uniform[..4].copy_from_slice(&[view.width, view.height, b.tiles_x, u32::from(output == Output::Float)]); @@ -627,15 +777,7 @@ impl GpuRenderer { for (u, f) in uniform[8..].iter_mut().zip(bg) { *u = f.to_bits(); } - let storage = |label: &str, bytes: &[u8]| { - // Bindings can't be empty: pad to one vec4. - let pad = [0u8; 16]; - let contents = if bytes.is_empty() { &pad[..] } else { bytes }; - self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage: wgpu::BufferUsages::STORAGE }) - }; let ubuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("params"), contents: bytemuck::cast_slice(&uniform), usage: wgpu::BufferUsages::UNIFORM }); - let ibuf = storage("index", bytemuck::cast_slice(&b.index)); - let gbuf = storage("geo", bytemuck::cast_slice(&b.geo)); let mut entries = vec![ wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: ibuf.as_entire_binding() }, @@ -695,6 +837,30 @@ impl GpuRenderer { }) } + /// The tile lists the GPU bins for `dl` (forced, however small), read back as a + /// [`binning::Binned`] like the CPU's: `None` when the scene isn't one the GPU bins. + #[cfg(test)] + pub(crate) fn gpu_lists(&self, dl: &DisplayList, view: &View) -> Result, GpuError> { + let (scene, _) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?; + let lim = gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }; + let mut b = binning::bin_with(&scene, view.width, view.height, Some(&lim)).map_err(GpuError::NeedsFull)?; + let Some(plan) = b.gpu.take() else { return Ok(None) }; + let scopes = Scopes::push(&self.device); + let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-bin-test") }); + let (ibuf, gbuf) = gpu_binning::record(&self.device, &self.queue, &self.bins, &mut enc, &plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?; + let (isize, gsize) = (ibuf.size(), gbuf.size()); + let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: isize + gsize, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + enc.copy_buffer_to_buffer(&ibuf, 0, &read, 0, isize); + enc.copy_buffer_to_buffer(&gbuf, 0, &read, isize, gsize); + self.queue.submit([enc.finish()]); + let bytes = self.map(&read, scopes)?; + let words: Vec = bytes.as_chunks::<4>().0.iter().map(|w| u32::from_le_bytes(*w)).collect(); + let n = isize as usize / 4; + b.index = words.get(..b.ops_at as usize).unwrap_or(&[]).to_vec(); + b.geo = words.get(n..).unwrap_or(&[]).as_chunks::<4>().0.iter().map(|v| v.map(f32::from_bits)).collect(); + Ok(Some(b)) + } + /// Waits for `read`'s copy, pops the error scopes and returns its bytes. fn map(&self, read: &wgpu::Buffer, scopes: Scopes) -> Result, GpuError> { let (tx, rx) = std::sync::mpsc::channel(); @@ -766,6 +932,14 @@ pub(crate) fn describe(e: &wgpu::Error) -> String { } } +/// Writes `words` at word `at` of a mapped buffer, if they fit. +pub(crate) fn write_words(m: &mut wgpu::BufferViewMut, at: usize, words: &[u32]) { + let (a, b) = (4 * at, 4 * (at + words.len())); + if !words.is_empty() && b <= m.len() { + m.slice(a..b).copy_from_slice(bytemuck::cast_slice(words)); + } +} + fn ms(t: Instant) -> f32 { t.elapsed().as_secs_f32() * 1000.0 } diff --git a/crates/gpu/src/scan.wgsl b/crates/gpu/src/scan.wgsl new file mode 100644 index 00000000..82be5c04 --- /dev/null +++ b/crates/gpu/src/scan.wgsl @@ -0,0 +1,83 @@ +// AniCraft GPU stage: the prefix sum for the GPU binning (ADR 0048, bin.wgsl). +// +// An exclusive scan of `n` values in `values` (the binning's working buffer): each workgroup +// scans 1024 of them (four per invocation, then the invocations' totals in workgroup memory) +// and leaves its total; the totals are scanned the same way, level by level, and added back. +// The public work-efficient scan (Blelloch's "Prefix sums and their applications", 1990), in +// its simplest form. + +// `src`, `dst` and the workgroups' totals (`sums`) in `work`, and how many values. +struct ScanParams { + src: u32, + dst: u32, + sums: u32, + n: u32, +} + +@group(0) @binding(0) var sp: ScanParams; +@group(0) @binding(1) var values: array; + +var sh: array; + +fn load(i: u32) -> u32 { + if i < sp.n { + return values[sp.src + i]; + } + return 0u; +} + +fn store(i: u32, v: u32) { + if i < sp.n { + values[sp.dst + i] = v; + } +} + +// Each workgroup scans 1024 values (four per invocation), exclusive, and leaves its total. +@compute @workgroup_size(256) +fn scan_blocks(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) nw: vec3, @builtin(local_invocation_id) lid: vec3) { + let block = wg.y * nw.x + wg.x; + let base = block * 1024u + lid.x * 4u; + // Four values by name, not a loop over an array: FXC (Direct3D's compiler) must unroll + // loops that index local arrays. + let v0 = load(base); + let v1 = load(base + 1u); + let v2 = load(base + 2u); + let v3 = load(base + 3u); + let total = v0 + v1 + v2 + v3; + sh[lid.x] = total; + workgroupBarrier(); + for (var off = 1u; off < 256u; off <<= 1u) { + var t = 0u; + if lid.x >= off { + t = sh[lid.x - off]; + } + workgroupBarrier(); + sh[lid.x] += t; + workgroupBarrier(); + } + let acc = sh[lid.x] - total; + store(base, acc); + store(base + 1u, acc + v0); + store(base + 2u, acc + v0 + v1); + store(base + 3u, acc + v0 + v1 + v2); + // (A dispatch spread over x and y may have a few workgroups past the end.) + if lid.x == 255u && block * 1024u < sp.n { + values[sp.sums + block] = sh[255]; + } +} + +// Adds each workgroup's scanned total to its values. +@compute @workgroup_size(256) +fn scan_add(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) nw: vec3, @builtin(local_invocation_id) lid: vec3) { + let block = wg.y * nw.x + wg.x; + if block * 1024u >= sp.n { + return; + } + let add = values[sp.sums + block]; + for (var i = 0u; i < 4u; i++) { + let at = block * 1024u + lid.x * 4u + i; + if at < sp.n { + values[sp.dst + at] += add; + } + } +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 005fcf68..0186c76f 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -7,7 +7,7 @@ use super::*; use crate::binning::{self as bn, Binned, PAINT_VEC4S, TILE, piece_cover, solid_of}; -use anicraft_doc::{BlendMode, ColorEffect, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, Paint, Rgba, Stroke, sample}; +use anicraft_doc::{BlendMode, ColorEffect, ColorTransform, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, MaskMode, Paint, Rgba, Stroke, sample}; use anicraft_geom::{Affine, FillRule, Path, Vec2}; use anicraft_render::{paint::Premul, render}; use std::sync::OnceLock; @@ -22,7 +22,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem { fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, - color: ColorEffect::default(), + color: ColorTransform::IDENTITY, layer: LayerId(0), element: ElementId(0), outline: None, @@ -31,11 +31,13 @@ fn item(path: Path, fill: Paint) -> DisplayItem { guide: false, group: None, image: None, + smooth: true, + warp: None, } } fn list(items: Vec) -> DisplayList { - DisplayList { items, ..Default::default() } + DisplayList { clip_modes: Vec::new(), items, ..Default::default() } } fn view(w: u32, h: u32, bg: Option) -> View { @@ -88,10 +90,30 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { star.fill_rule = FillRule::EvenOdd; out.push(("star", list(vec![star]), view(80, 80, Some(Rgba::WHITE)))); // Gradients under rotation and scale. - let mut lin = item(Path::rect(0.0, 0.0, 100.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(100.0, 0.0), stops: stops(&[(0.0, red), (0.5, Rgba::WHITE), (1.0, blue)]) }); + let mut lin = item(Path::rect(0.0, 0.0, 100.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), stops(&[(0.0, red), (0.5, Rgba::WHITE), (1.0, blue)]))); lin.transform = Affine::translate(70.0, 10.0).mul(&Affine::rotate(0.4)).mul(&Affine::scale(1.2, 0.8)); - let rad = item(Path::ellipse(60.0, 90.0, 50.0, 30.0), Paint::Radial { center: Vec2::new(60.0, 90.0), radius: 50.0, stops: stops(&[(0.0, Rgba::WHITE), (1.0, Rgba::new(0.0, 0.0, 0.0, 0.3))]) }); + let rad = item(Path::ellipse(60.0, 90.0, 50.0, 30.0), Paint::radial(Vec2::new(60.0, 90.0), 50.0, stops(&[(0.0, Rgba::WHITE), (1.0, Rgba::new(0.0, 0.0, 0.0, 0.3))]))); out.push(("gradients", list(vec![lin, rad]), view(180, 130, Some(Rgba::new(0.9, 0.9, 0.85, 1.0))))); + // Gradient options (ADR 0074): reflect and repeat, linear light, a focal point on a turned + // ellipse that repeats. + let three = stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]); + let mut refl = Paint::linear(Vec2::new(20.0, 0.0), Vec2::new(50.0, 0.0), three.clone()); + if let Paint::Linear { spread, linear_rgb, .. } = &mut refl { + *spread = anicraft_doc::Spread::Reflect; + *linear_rgb = true; + } + let mut rep = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(14.0, 9.0), three.clone()); + if let Paint::Linear { spread, .. } = &mut rep { + *spread = anicraft_doc::Spread::Repeat; + } + let mut foc = Paint::radial(Vec2::ZERO, 1.0, three).with_frame(&Affine::translate(140.0, 60.0).mul(&Affine::rotate(0.6)).mul(&Affine::scale(40.0, 20.0)), None); + if let Paint::Radial { focal, spread, .. } = &mut foc { + *focal = 0.6; + *spread = anicraft_doc::Spread::Repeat; + } + let mut rep_item = item(Path::rect(0.0, 60.0, 90.0, 50.0), rep); + rep_item.transform = Affine::translate(5.0, 0.0); + out.push(("gradient options", list(vec![item(Path::rect(0.0, 0.0, 90.0, 55.0), refl), rep_item, item(Path::ellipse(140.0, 60.0, 60.0, 50.0), foc)]), view(210, 120, Some(Rgba::WHITE)))); // Strokes: wide, thin (sub-pixel, faded), on open and closed paths. let mut wide = item(Path::line(Vec2::new(10.0, 20.0), Vec2::new(150.0, 70.0)), Paint::Solid(red)); wide.fill = None; @@ -124,21 +146,52 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { out.push(("styled strokes", list(vec![dashed, zig, dots]), view(160, 100, Some(Rgba::WHITE)))); // Larger than the surface on every side; colour effects (onion-skin style tint and alpha). let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red)); - huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 }; + huge.color = ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::hex(0x4cd07d), 0.7)); out.push(("off-surface", list(vec![huge]), view(100, 80, Some(Rgba::WHITE)))); + out.push(("outlines", outlined(), view(150, 110, Some(Rgba::WHITE)))); out.extend(composited_scenes()); out } +/// Outline mode (ADR 0048): hairlines along closed and open paths, crossing tiles in every +/// direction, overlapping, faded, past the surface, over a fill, and a point. +fn outlined() -> DisplayList { + let outline = |path: Path, c: Rgba, t: Affine| { + let mut i = item(path, Paint::Solid(Rgba::BLACK)); + i.outline = Some(c); + i.transform = t; + i + }; + let blue = Rgba::hex(0x4f8dff).with_alpha(0.5); + let green = Rgba::hex(0x4cd07d).with_alpha(0.8); + let mut wave = Path::default(); + wave.move_to(Vec2::new(-20.0, 90.0)); + for k in 0..12 { + wave.line_to(Vec2::new(k as f32 * 15.3, 90.0 + if k % 2 == 0 { 9.7 } else { -7.1 })); + } + list(vec![ + item(Path::rect(20.0, 20.0, 50.0, 40.0), Paint::Solid(Rgba::new(0.9, 0.8, 0.2, 1.0))), + outline(Path::ellipse(50.0, 45.0, 37.3, 29.1), blue, Affine::IDENTITY), + outline(Path::star(95.0, 50.0, 40.0, 16.0, 5), green, Affine::rotate(0.05)), + outline(Path::star(95.0, 50.0, 40.0, 16.0, 5), green, Affine::translate(0.25, 0.5)), + outline(Path::rect(16.0, 32.0, 112.0, 0.0), Rgba::BLACK, Affine::IDENTITY), + outline(Path::rect(8.5, 4.25, 133.0, 100.0), Rgba::new(0.8, 0.1, 0.1, 1.0), Affine::IDENTITY), + outline(wave, Rgba::new(0.2, 0.2, 0.2, 0.9), Affine::IDENTITY), + outline(Path::ellipse(140.0, 100.0, 60.0, 50.0), blue, Affine::IDENTITY), + outline(Path::line(Vec2::new(60.5, 70.5), Vec2::new(60.5, 70.5)), Rgba::BLACK, Affine::IDENTITY), + ]) +} + /// Masks and groups (ADR 0029): each stresses one part of the oracle's band compositor. fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { let red = Rgba::new(0.9, 0.1, 0.1, 1.0); let blue = Rgba::new(0.1, 0.2, 0.9, 0.6); let green = Rgba::new(0.2, 0.7, 0.3, 0.8); - let grad = || Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(120.0, 40.0), stops: stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]) }; + let grad = || Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(120.0, 40.0), stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)])); let mut out = Vec::new(); // A mask: a gradient seen through a circle, an unclipped shape over it, and one under it. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))], clip_parents: vec![None], groups: Vec::new(), @@ -160,10 +213,11 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { } let mut items = stripes; items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]); - out.push(("nested masks", DisplayList { items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); + out.push(("nested masks", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); // Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles // and the render bands; a top-level shape between two groups. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0), in_group(item(Path::ellipse(55.0, 40.0, 35.0, 30.0), grad()), 0), @@ -190,9 +244,10 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g)); items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g)); } - out.push(("blend modes", DisplayList { items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); + out.push(("blend modes", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); // Masks inside groups and groups inside masks, with a blend mode, on transparent. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0), in_group(item(Path::ellipse(70.0, 40.0, 30.0, 30.0), Paint::Solid(blue)), 0), @@ -208,6 +263,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { // Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides // what it clips), a group whose parent is later (top-level), a clip index past the list. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0), mask(Path::rect(0.0, 0.0, 30.0, 30.0), 0), @@ -219,6 +275,39 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { groups: vec![group(Some(1), 0.5, BlendMode::Normal), group(Some(1), 0.5, BlendMode::Difference)], }; out.push(("malformed links", dl, view(50, 50, Some(Rgba::WHITE)))); + // Soft masks (ADR 0070): an alpha gradient fading a shape out, a luminance mask with a + // stroke and overlapping faded art, and a soft mask inside a coverage one. + let fade = Paint::linear(Vec2::new(10.0, 0.0), Vec2::new(110.0, 0.0), stops(&[(0.0, Rgba::new(1.0, 1.0, 1.0, 0.0)), (1.0, Rgba::new(0.2, 0.9, 0.4, 1.0))])); + let soft_art = |path: Path, paint: Paint, clip: u32| { + let mut m = item(path, paint); + m.masks = Some(clip); + m + }; + let mut ring = soft_art(Path::ellipse(60.0, 50.0, 30.0, 26.0), Paint::Solid(Rgba::new(0.5, 0.5, 0.5, 0.7)), 1); + ring.stroke = Some(Stroke::new(Rgba::WHITE, 6.0)); + let mut faded = soft_art(Path::rect(50.0, 10.0, 60.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.2, 0.1, 1.0)), 1); + faded.color = ColorTransform::alpha(0.6); + let mut inner = soft_art(Path::rect(0.0, 0.0, 120.0, 100.0), Paint::Solid(Rgba::new(1.0, 1.0, 1.0, 0.5)), 3); + inner.clip = Some(2); + let mut dl = DisplayList { + items: vec![ + item(Path::rect(0.0, 0.0, 120.0, 100.0), Paint::Solid(Rgba::new(0.95, 0.9, 0.8, 1.0))), + clipped(item(Path::rect(0.0, 0.0, 120.0, 50.0), grad()), 0), + soft_art(Path::rect(10.0, 0.0, 100.0, 60.0), fade, 0), + clipped(item(Path::rect(0.0, 30.0, 120.0, 70.0), Paint::Solid(red)), 1), + ring, + faded, + clipped(item(Path::star(60.0, 60.0, 40.0, 15.0, 5), Paint::Solid(blue)), 3), + mask(Path::rect(20.0, 40.0, 50.0, 60.0), 2), + inner, + ], + clip_parents: vec![None, None, None, Some(2)], + ..Default::default() + }; + dl.set_clip_mode(0, MaskMode::Alpha); + dl.set_clip_mode(1, MaskMode::Luminance); + dl.set_clip_mode(3, MaskMode::Alpha); + out.push(("soft masks", dl, view(120, 100, Some(Rgba::WHITE)))); out } @@ -235,6 +324,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { let mut c = bg; let mut stack: Vec = Vec::new(); let (mut mask, mut level) = (1.0f32, 0.0f32); + let (mut level_mode, mut level_colour) = (0u32, [0.0f32; 4]); for i in 0..count { let e = b.entries_at as usize + (start + i) * 4; let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]); @@ -256,23 +346,51 @@ fn emulate(b: &Binned, v: &View) -> Vec { } bn::LEVEL_BEGIN => { level = 0.0; + level_mode = b.index[e + 1]; + level_colour = [0.0; 4]; continue; } bn::LEVEL_END => { - mask *= level; + let mode = [MaskMode::Coverage, MaskMode::Alpha, MaskMode::Luminance][level_mode as usize]; + mask *= if mode.is_soft() { mode.reveal(level_colour) } else { level }; continue; } k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"), } - let mut wnd = if bd == binning::NONE { 0.0 } else { b.geo[bd as usize + ly / 4][ly % 4] }; - for k in 0..n { - let s = b.geo[first + k]; - wnd += piece_cover(s, lx as f32, ly as f32); - } - let hd = b.ops_at as usize + op * 4; - let mut cov = if b.index[hd + 1] == 0 { wnd.abs().min(1.0) } else { let t = wnd.abs() % 2.0; if t > 1.0 { 2.0 - t } else { t } }; - let flags = b.index[hd + 3]; + let hd = op * 4; + let mut cov = entry_cover(&b.geo[first..first + n], bd, b.op_heads[hd + 1], lx, ly); + let flags = b.op_heads[hd + 3]; + let shade = || match b.op_heads[hd] { + 0 => solid_of(b, op), + kind => { + let base = op * PAINT_VEC4S; + let (m, nn, g) = (b.paints[base + 1], b.paints[base + 2], b.paints[base + 3]); + let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let q = Vec2::new(m[0] * p.x + m[2] * p.y + nn[0], m[1] * p.x + m[3] * p.y + nn[1]); + let d = q - Vec2::new(nn[2], nn[3]); + // As fine.wgsl: spread code and focal point in the first vec4. + let o = b.paints[base]; + let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { anicraft_render::paint::focal_t(d * g[2], o[1]) }; + let t = match o[0] as u32 { + 1 => anicraft_doc::Spread::Reflect.apply(t), + 2 => anicraft_doc::Spread::Repeat.apply(t), + _ => t, + }; + let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255; + b.paints[b.op_heads[hd + 2] as usize + i] + } + }; if flags & bn::ART != 0 { + if level_mode != 0 { + if cov > 1e-4 { + let s = shade(); + let sa = s[3] * cov; + for k in 0..4 { + level_colour[k] = s[k] * cov + level_colour[k] * (1.0 - sa); + } + } + continue; + } let k = cov.clamp(0.0, 1.0); level = level + k - level * k; continue; @@ -283,19 +401,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { if cov <= 1e-4 { continue; } - let s = match b.index[hd] { - 0 => solid_of(b, op), - kind => { - let base = op * PAINT_VEC4S; - let (m, nn, g) = (b.paints[base + 1], b.paints[base + 2], b.paints[base + 3]); - let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); - let q = Vec2::new(m[0] * p.x + m[2] * p.y + nn[0], m[1] * p.x + m[3] * p.y + nn[1]); - let d = q - Vec2::new(nn[2], nn[3]); - let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { d.length() * g[2] }; - let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255; - b.paints[b.index[hd + 2] as usize + i] - } - }; + let s = shade(); let sa = s[3] * cov; for k in 0..4 { c[k] = s[k] * cov + c[k] * (1.0 - sa); @@ -308,6 +414,26 @@ fn emulate(b: &Binned, v: &View) -> Vec { out } +/// An entry's coverage of pixel `(lx, ly)` of its tile, as `fine.wgsl` computes it: the +/// backdrop and its pieces under fill rule `rule`, or a hairline's distance. +fn entry_cover(pieces: &[[f32; 4]], backdrop: u32, rule: u32, lx: usize, ly: usize) -> f32 { + if rule == bn::HAIRLINE { + let p = Vec2::new(lx as f32 + 0.5, ly as f32 + 0.5); + let d = pieces.iter().fold(2.0f32, |d, s| d.min(anicraft_render::hairline::seg_dist(p, Vec2::new(s[0], s[1]), Vec2::new(s[2], s[3])))); + return (1.0 - d).clamp(0.0, 1.0); + } + let mut wnd = backdrop as i32 as f32; + for s in pieces { + wnd += piece_cover(*s, lx as f32, ly as f32); + } + if rule == 0 { + wnd.abs().min(1.0) + } else { + let t = wnd.abs() % 2.0; + if t > 1.0 { 2.0 - t } else { t } + } +} + /// `fine.wgsl` › `close_group` and `blend`, on the CPU (the oracle's formulas, written again /// from the shader's numbering). fn close_group(s: Premul, below: Premul, alpha: f32, m: u32) -> Premul { @@ -374,7 +500,7 @@ fn f32_diff(a: &[Premul], b: &[Premul]) -> (f64, f32) { /// deep, so every transform the camera adds reaches the GPU's fills. fn camera_sample() -> anicraft_doc::Document { let mut doc = sample::demo(); - let cam = anicraft_doc::Camera { center: Vec2::new(700.0, 380.0), zoom: 1.6, rotation: -0.15, tint: Rgba::hex(0x3366ff), tint_amount: 0.3 }; + let cam = anicraft_doc::Camera { center: Vec2::new(700.0, 380.0), zoom: 1.6, rotation: -0.15, color: anicraft_doc::ColorEffect::Tint { color: Rgba::hex(0x3366ff), amount: 0.3 } }; let mut layer = anicraft_doc::Layer::new(LayerId(9_000), "Camera"); layer.kind = anicraft_doc::LayerKind::Camera; let mut k = anicraft_doc::Keyframe::new(0, doc.frame_count()); @@ -402,7 +528,7 @@ fn composited_sample() -> anicraft_doc::Document { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { let e = Arc::make_mut(e); - e.color.alpha = if i == 0 { 0.6 } else { 0.5 }; + e.color = e.color.with_alpha(if i == 0 { 0.6 } else { 0.5 }); if let ElementKind::Symbol { blend, .. } = &mut e.kind && i == 0 { @@ -419,6 +545,27 @@ fn composited_sample() -> anicraft_doc::Document { doc } +/// A rounded panel with 9-slice guides, placed stretched, scaled up and turned. +fn nine_slice_sample() -> anicraft_doc::Document { + use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, ScaleGrid, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; + let mut d = anicraft_doc::Document { stage: anicraft_doc::Stage { width: 320, height: 200, ..Default::default() }, ..Default::default() }; + let mut shape = Shape::filled(Path::rounded_rect(0.0, 0.0, 60.0, 30.0, 8.0), Paint::Solid(Rgba::hex(0x2a9d8f))); + shape.stroke = Some(Stroke::new(Rgba::hex(0x264653), 2.0)); + let el = |id, transform, kind| std::sync::Arc::new(Element { id: ElementId(id), name: String::new(), transform, color: ColorEffect::default(), kind }); + let mut k = Keyframe::new(0, 1); + k.elements.push(el(2, Affine::IDENTITY, ElementKind::Shape(shape))); + let mut l = Layer::new(LayerId(3), "art"); + l.keyframes = vec![std::sync::Arc::new(k)]; + d.library.push(std::sync::Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: Some(ScaleGrid { left: 8.0, right: 52.0, top: 8.0, bottom: 22.0 }), timeline: Timeline { layers: vec![std::sync::Arc::new(l)] } })); + let inst = |id, xf| el(id, xf, ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }); + let mut k = Keyframe::new(0, 1); + k.elements.push(inst(5, Affine::translate(10.0, 10.0).mul(&Affine::scale(4.5, 1.2)))); + k.elements.push(inst(6, Affine::translate(30.0, 70.0).mul(&Affine::scale(2.0, 3.5)))); + k.elements.push(inst(7, Affine::translate(220.0, 90.0).mul(&Affine::rotate(0.5)).mul(&Affine::scale(1.5, 2.5)))); + std::sync::Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![std::sync::Arc::new(k)]; + d +} + #[test] fn binned_coverage_matches_the_oracle_on_the_cpu() { let mut all = scenes(); @@ -434,6 +581,10 @@ fn binned_coverage_matches_the_oracle_on_the_cpu() { for (f, s) in [(0u32, 0.4f32), (30, 0.6)] { all.push(("composited sample", anicraft_doc::evaluate(&comp, f), View::stage(&comp, s))); } + // A 9-sliced instance (ADR 0055) reaches the stage through evaluation: cut outlines, strokes + // at their own width. + let nine = nine_slice_sample(); + all.push(("9-slice", anicraft_doc::evaluate(&nine, 0), View::stage(&nine, 0.7))); for (name, dl, v) in all { let (scene, _) = prepare_scene(&dl, &v).unwrap(); let b = binning::bin(&scene, v.width, v.height).unwrap(); @@ -443,6 +594,22 @@ fn binned_coverage_matches_the_oracle_on_the_cpu() { } } +/// Thousands of overlapping shapes at awkward scales: edges meet tile corners and boundaries +/// within float rounding, where the backdrops and the left-edge steps must agree (ADR 0048). +#[test] +fn binned_coverage_matches_the_oracle_on_stress_frames() { + let doc = sample::stress(20, 100, 48); + for (f, s, at) in [(0u32, 1.0f32, (0.0, 0.0)), (30, 0.5, (0.0, 0.0)), (7, 2.3, (-900.0, -700.0)), (41, 0.73, (-11.5, -3.25))] { + let dl = anicraft_doc::evaluate(&doc, f); + let v = View { transform: Affine::translate(at.0, at.1).mul(&Affine::scale(s, s)), width: 1920, height: 1080, background: Some(Rgba::WHITE) }; + let (scene, _) = prepare_scene(&dl, &v).unwrap(); + let b = binning::bin(&scene, v.width, v.height).unwrap(); + let (oracle, _) = render(&dl, &v).unwrap(); + let (mean, max) = f32_diff(&emulate(&b, &v), &oracle.data); + assert!(mean < 1e-4 && max < 4e-3, "frame {f} at {s}: mean {mean:e}, max {max:e}"); + } +} + #[test] fn the_composited_sample_really_has_masks_and_groups() { let comp = composited_sample(); @@ -482,6 +649,7 @@ fn binning_shapes_the_scene_into_tiles() { // A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In // the middle tile the mask has no artwork, so the clipped fill is left out there. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0), clipped(item(Path::rect(0.0, 0.0, 40.0, 16.0), Paint::Solid(Rgba::BLACK)), 0), @@ -510,6 +678,7 @@ fn binning_shapes_the_scene_into_tiles() { #[test] fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { let deep = |n: usize| DisplayList { + clip_modes: Vec::new(), items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)], clip_parents: Vec::new(), groups: (0..n).map(|i| group(i.checked_sub(1).map(|p| p as u32), 0.9, BlendMode::Normal)).collect(), @@ -521,7 +690,7 @@ fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { let masks = |n: usize| { let mut items: Vec = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect(); items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)); - DisplayList { items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } + DisplayList { clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } }; assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok()); assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips)); @@ -549,6 +718,7 @@ fn degenerate_geometry_bins_without_trouble() { clip, group, layer: None, + hairline: false, }; // A fill naming a layer that isn't there draws nothing. let mut lost = fill(None, None); @@ -560,6 +730,39 @@ fn degenerate_geometry_bins_without_trouble() { // ----- the real GPU ---------------------------------------------------------------------------- +/// The shaders, as `pipelines` and the stage build them. +const SHADERS: [(&str, &str); 4] = [ + ("fine.wgsl", include_str!("fine.wgsl")), + ("bin.wgsl", include_str!("bin.wgsl")), + ("scan.wgsl", include_str!("scan.wgsl")), + ("filters.wgsl", include_str!("filters.wgsl")), +]; + +#[test] +fn shaders_take_no_signed_remainder() { + // naga writes WGSL's `%` on integers as GLSL's, which is undefined when an operand is + // negative: on the GL backend (llvmpipe in the FreeBSD VM) a repeating bitmap's wrap, + // `((q % size) + size) % size` at q = -1, picked the wrong texel at its edges (bitmap + // repeated: max 79). Unsigned remainders and float ones (written as `a - b * trunc(a / b)`) + // are defined on every backend. + for (name, src) in SHADERS { + let module = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(src))); + let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()) + .validate(&module) + .unwrap_or_else(|e| panic!("{name}: {e:?}")); + let functions = module.functions.iter().map(|(h, f)| (f, &info[h])); + let entries = module.entry_points.iter().enumerate().map(|(i, e)| (&e.function, info.get_entry_point(i))); + for (f, fi) in functions.chain(entries) { + for (h, e) in f.expressions.iter() { + if let naga::Expression::Binary { op: naga::BinaryOperator::Modulo, left, .. } = *e { + let kind = fi[left].ty.inner_with(&module.types).scalar_kind(); + assert_ne!(kind, Some(naga::ScalarKind::Sint), "{name}: `%` on a signed integer in {:?} ({h:?})", f.name); + } + } + } + } +} + /// One device for all tests: the graphics card, or else the software adapter (CI runners have /// lavapipe or WARP); `None` (with the reasons printed) when there is neither. /// `ANICRAFT_TEST_GPU=software` tests on the software adapter even where there is a card. @@ -657,8 +860,8 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() { }) .collect(); let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1); - it.color.alpha = 0.5; - DisplayList { items: vec![it], clip_parents: Vec::new(), groups } + it.color = ColorTransform::alpha(0.5); + DisplayList { clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups } }; let deep = nested(MAX_FILTER_DEPTH + 1); assert!(matches!(g.render(&deep, &view(12, 12, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters)))); @@ -673,6 +876,39 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() { assert!(g.broken().is_none()); } +/// ADR 0092: a device lost mid-session (here destroyed on purpose, the way a driver reset +/// takes it) never panics: every later call is an error saying why, so the stage hands the +/// frame to the CPU. A renderer told from outside (the window's device was lost) refuses too. +#[test] +fn a_lost_device_turns_every_call_into_an_error_and_says_why() { + // A device of its own: the shared one stays for the other tests. + let opened = GpuRenderer::new().or_else(|_| GpuRenderer::software()); + let Ok(g) = opened else { + eprintln!("skipping the lost-device test: no GPU"); + return; + }; + let dl = list(vec![item(Path::rect(1.0, 1.0, 6.0, 6.0), Paint::Solid(Rgba::BLACK))]); + assert!(g.render(&dl, &view(8, 8, None), Output::Premul8).is_ok()); + g.device.destroy(); + let _ = g.wait_idle(); + let first = g.render(&dl, &view(8, 8, None), Output::Premul8); + assert!(matches!(first, Err(GpuError::Device(_))), "a lost device fails the frame"); + assert!(g.broken().is_some(), "and the renderer says it is broken"); + assert!(matches!(g.render_texture(&dl, &view(8, 8, None)), Err(GpuError::Device(_)))); + // Told from outside: the first reason stays. + let why = g.broken(); + g.fail("the window's device was lost"); + assert_eq!(g.broken(), why); + // A fresh renderer told from outside refuses at once, with that reason. + if let Ok(h) = GpuRenderer::new().or_else(|_| GpuRenderer::software()) { + h.fail("the window's device was lost"); + match h.render(&dl, &view(8, 8, None), Output::Premul8) { + Err(GpuError::Device(e)) => assert!(e.contains("window's device"), "{e}"), + other => panic!("expected a device error, got {:?}", other.map(|f| f.width)), + } + } +} + #[test] fn gpu_renders_from_many_threads_at_once() { let Some(g) = gpu() else { return }; @@ -719,21 +955,41 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { ("bitmap magnified, mirrored", list(vec![bitmap_item(Path::rect(0.0, 0.0, 64.0, 48.0), &c, false, Affine { m: [-1.7, 0.0, 0.0, 1.6, 66.0, -1.3] })]), view(64, 48, white)), ("one-pixel bitmap", list(vec![bitmap_item(Path::rect(5.5, 5.5, 20.0, 20.0), &b, true, Affine::scale(7.0, 7.0))]), view(32, 32, white)), ]; - // Colour effects: tint and alpha per tap, and a NaN tint (sanitized to 0 as the oracle does). + // Colour effects: tint and alpha per tap, and a NaN multiplier (a channel of 0, as the oracle + // draws it). let mut tinted = bitmap_item(Path::rect(0.0, 0.0, 60.0, 40.0), &c, true, Affine::scale(0.7, 0.9)); - tinted.color = ColorEffect { alpha: 0.6, tint: Rgba::new(0.2, 0.9, 0.1, 1.0), tint_amount: 0.4 }; + tinted.color = ColorTransform::alpha(0.6).concat(&ColorTransform::tint(Rgba::new(0.2, 0.9, 0.1, 1.0), 0.4)); let mut nan = bitmap_item(Path::rect(30.0, 10.0, 30.0, 30.0), &a, false, Affine::scale(2.0, 2.0)); - nan.color = ColorEffect { alpha: 1.0, tint: Rgba::new(f32::NAN, 0.5, 0.5, 1.0), tint_amount: 0.3 }; - out.push(("bitmap colour effects", list(vec![tinted, nan]), view(64, 48, Some(Rgba::new(0.1, 0.1, 0.3, 1.0))))); + nan.color = ColorTransform { mul: [f32::NAN, 0.7, 0.7, 1.0], add: [0.0, 0.15, 0.15, 0.0] }; + // Advanced (ADR 0056): a negative multiplier, offsets and an alpha offset. + let mut advanced = bitmap_item(Path::rect(4.0, 20.0, 40.0, 26.0), &a, true, Affine::scale(1.3, 1.1)); + advanced.color = ColorTransform { mul: [-1.0, 0.5, 0.2, 0.6], add: [1.0, 0.1, 0.4, 0.2] }; + out.push(("bitmap colour effects", list(vec![tinted, nan, advanced]), view(64, 48, Some(Rgba::new(0.1, 0.1, 0.3, 1.0))))); // A short (malformed) buffer: transparent past its end; an empty image draws nothing. let short = Arc::new(anicraft_doc::Pixels { width: 4, height: 4, rgba: vec![200; 20] }); let empty = Arc::new(anicraft_doc::Pixels { width: 0, height: 3, rgba: Vec::new() }); out.push(("malformed bitmaps", list(vec![bitmap_item(Path::rect(0.0, 0.0, 30.0, 30.0), &short, false, Affine::scale(7.0, 7.0)), bitmap_item(Path::rect(10.0, 0.0, 10.0, 30.0), &empty, true, Affine::IDENTITY)]), view(32, 32, white))); // Inside a mask and a faded group, over a gradient. - let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(80.0, 60.0), stops: stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]) }); + let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(80.0, 60.0), stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]))); let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0); - let dl = DisplayList { items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; out.push(("bitmap masked and multiplied", dl, view(80, 60, white))); + // Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated. + let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned); + hard.smooth = false; + let mut hard_tiled = bitmap_item(Path::ellipse(50.0, 40.0, 45.0, 35.0), &c, true, Affine::scale(4.0, 3.0)); + hard_tiled.smooth = false; + out.push(("bitmaps without smoothing", list(vec![hard_tiled, hard]), view(100, 80, white))); + // Warped (ADR 0079): bent by three pins, folded a little, faded; the oracle's prepared image. + use anicraft_doc::warp::{Pin, PinId, Warp}; + let pin = |id: u64, rest: (f32, f32), at: (f32, f32)| Pin { id: PinId(id), rest: Vec2::new(rest.0, rest.1), at: Vec2::new(at.0, at.1) }; + let mut warp = Warp::new(Arc::new(Path::rect(0.0, 0.0, 40.0, 30.0)), 8); + warp.pins = vec![pin(1, (2.0, 15.0), (6.0, 20.0)), pin(2, (20.0, 15.0), (24.0, 14.0)), pin(3, (38.0, 15.0), (52.0, 40.0))]; + let mut bent = bitmap_item(warp.outline().as_ref().clone(), &c, false, Affine::IDENTITY); + bent.warp = warp.mesh().map(Arc::new); + bent.transform = Affine::scale(1.4, 1.4); + bent.color = ColorTransform::alpha(0.8); + out.push(("warped bitmap", list(vec![bent]), view(90, 72, white))); out } @@ -804,12 +1060,12 @@ fn symbol_items(g: u32) -> Vec { #[test] fn gpu_matches_the_oracle_on_every_filter() { let Some(g) = gpu() else { return }; - let backdrop = item(Path::rect(0.0, 0.0, 70.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(70.0, 0.0), stops: stops(&[(0.0, Rgba::new(0.9, 0.9, 0.8, 1.0)), (1.0, Rgba::new(0.2, 0.4, 0.5, 1.0))]) }); + let backdrop = item(Path::rect(0.0, 0.0, 70.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(70.0, 0.0), stops(&[(0.0, Rgba::new(0.9, 0.9, 0.8, 1.0)), (1.0, Rgba::new(0.2, 0.4, 0.5, 1.0))]))); let mut worst: f64 = 0.0; for (name, f) in filters_to_test() { let mut items = vec![backdrop.clone()]; items.extend(symbol_items(0)); - let dl = DisplayList { items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; + let dl = DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; // At 1:1; zoomed, so sizes scale; and panned so the layer reaches past the surface. for v in [view(70, 60, Some(Rgba::WHITE)), View { transform: Affine::scale(1.5, 1.5), width: 105, height: 90, background: None }, View { transform: Affine::translate(-20.0, -15.0), width: 40, height: 33, background: Some(Rgba::WHITE) }] { let d = assert_parity(g, name, &dl, &v); @@ -834,7 +1090,7 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { (grp.alpha, grp.blend) = (0.7, BlendMode::Multiply); let mut items = vec![bg.clone()]; items.extend(symbol_items(0)); - scenes.push(("filters in a row, faded and multiplied", DisplayList { items, clip_parents: Vec::new(), groups: vec![grp] })); + scenes.push(("filters in a row, faded and multiplied", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] })); // A filtered symbol inside a filtered symbol, inside a faded one. let mut outer = filtered_group(vec![shadow.clone()]); outer.parent = Some(0); @@ -842,22 +1098,22 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { inner.parent = Some(1); let mut items = vec![bg.clone(), in_group(item(Path::rect(4.0, 40.0, 30.0, 16.0), Paint::Solid(Rgba::new(0.9, 0.6, 0.0, 1.0))), 1)]; items.extend(symbol_items(2)); - scenes.push(("nested filtered symbols", DisplayList { items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); + scenes.push(("nested filtered symbols", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); // Masked from outside (after filtering) and inside (before). let mut clipped_grp = filtered_group(vec![glow.clone()]); clipped_grp.clip = Some(0); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(mask(Path::ellipse(36.0, 30.0, 24.0, 20.0), 0)); - scenes.push(("masked after filtering", DisplayList { items, clip_parents: vec![None], groups: vec![clipped_grp] })); + scenes.push(("masked after filtering", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] })); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(in_group(mask(Path::rect(20.0, 10.0, 16.0, 40.0), 0), 0)); - scenes.push(("masked inside the symbol", DisplayList { items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); + scenes.push(("masked inside the symbol", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); // A bitmap inside a filtered symbol. let px = pixels(9, 7, 4); let items = vec![bg.clone(), in_group(bitmap_item(Path::ellipse(40.0, 32.0, 26.0, 20.0), &px, true, Affine::scale(4.0, 4.0)), 0)]; - scenes.push(("filtered bitmap", DisplayList { items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); + scenes.push(("filtered bitmap", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); for (name, dl) in scenes { for v in [view(80, 64, white), View { transform: Affine::translate(-37.0, -5.0).mul(&Affine::scale(1.3, 1.3)), width: 48, height: 48, background: white }] { let d = assert_parity(g, name, &dl, &v); @@ -880,15 +1136,15 @@ fn filtered_sample() -> anicraft_doc::Document { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { if let ElementKind::Symbol { filters, .. } = &mut Arc::make_mut(e).kind { - *filters = match i { + *filters = Vec::from_iter(match i { 0 => vec![F::DropShadow { blur_x: 8.0, blur_y: 8.0, strength: 0.8, quality: 2, angle: 45.0, distance: 10.0, color: Rgba::BLACK, inner: false, knockout: false, hide_object: false }, F::Bevel { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, angle: 45.0, distance: 4.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side: anicraft_doc::FilterSide::Inner, knockout: false }], _ => vec![F::Glow { blur_x: 12.0, blur_y: 12.0, strength: 1.4, quality: 2, color: Rgba::new(1.0, 0.85, 0.2, 1.0), inner: false, knockout: false }], - }; + }.into_iter().map(anicraft_doc::FilterEntry::from)); } } } } - let shape = anicraft_doc::Shape { path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), merge: false, fill: Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(77), repeat: true, matrix: Affine::scale(5.0, 5.0) }), stroke: None, fill_rule: FillRule::NonZero }; + let shape = anicraft_doc::Shape { path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), merge: false, fill: Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(77), repeat: true, matrix: Affine::scale(5.0, 5.0) }), stroke: None, fill_rule: FillRule::NonZero, warp: None }; let sky = anicraft_doc::Element { id: ElementId(9_100), name: "sky".into(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) }; let frames = doc.frame_count(); let mut k = anicraft_doc::Keyframe::new(0, frames); @@ -914,3 +1170,100 @@ fn gpu_matches_the_oracle_on_the_filtered_sample() { assert_parity(g, "filtered sample tile", &dl, &tile); } } + + +// ----- binning on the GPU (ADR 0048) ---------------------------------------------------------- + +/// Scenes the GPU bins (no fill in a mask or a group): the analytic ones, the sample, stress +/// frames at awkward scales and offsets, and onion-skin style outlines over them. +fn gpu_binned_scenes() -> Vec<(String, DisplayList, View)> { + let plain = |dl: &DisplayList| dl.items.iter().all(|i| i.clip.is_none() && i.group.is_none()); + let mut out: Vec<(String, DisplayList, View)> = scenes().into_iter().filter(|(_, dl, _)| plain(dl)).map(|(n, dl, v)| (n.to_string(), dl, v)).collect(); + let demo = sample::demo(); + out.push(("sample".into(), anicraft_doc::evaluate(&demo, 13), View::stage(&demo, 0.37))); + let doc = sample::stress(20, 100, 48); + for (f, s, at) in [(0u32, 1.0f32, (0.0, 0.0)), (30, 0.5, (0.0, 0.0)), (7, 2.3, (-900.0, -700.0)), (41, 0.73, (-11.5, -3.25))] { + let dl = anicraft_doc::evaluate(&doc, f); + let v = View { transform: Affine::translate(at.0, at.1).mul(&Affine::scale(s, s)), width: 1920, height: 1080, background: Some(Rgba::WHITE) }; + out.push((format!("stress frame {f} at {s}"), dl, v)); + } + // Onion skin's outlines: the frames before and after as hairlines, under the playhead's. + let mut dl = DisplayList::default(); + for f in [25u32, 27, 33, 35] { + let mut part = anicraft_doc::evaluate(&doc, f); + for i in &mut part.items { + i.outline = Some(Rgba::hex(if f < 30 { 0x4f8dff } else { 0x4cd07d }).with_alpha(0.4)); + } + dl.append(part); + } + dl.append(anicraft_doc::evaluate(&doc, 30)); + out.push(("stress with outlined frames".into(), dl, View::stage(&doc, 0.8))); + out +} + +/// What an entry covers in each of its tile's 256 pixels. +fn entry_pixels(b: &Binned, e: usize) -> [f32; 256] { + let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]); + let rule = b.op_heads[4 * op + 1]; + let pieces = b.geo.get(first..first + n).unwrap_or(&[]); + std::array::from_fn(|i| entry_cover(pieces, bd, rule, i % 16, i / 16)) +} + +#[test] +fn gpu_binning_produces_the_cpus_tile_lists() { + let Some(g) = gpu() else { return }; + for (name, dl, v) in gpu_binned_scenes() { + let Some(gb) = g.gpu_lists(&dl, &v).unwrap() else { panic!("{name}: the GPU should bin this") }; + let (scene, _) = prepare_scene(&dl, &v).unwrap(); + let cb = binning::bin(&scene, v.width, v.height).unwrap(); + assert_eq!((gb.tiles_x, gb.tiles_y, &gb.op_heads), (cb.tiles_x, cb.tiles_y, &cb.op_heads), "{name}"); + let (mut entries, mut pieces) = (0usize, 0usize); + for t in 0..(cb.tiles_x * cb.tiles_y) as usize { + let list = |b: &Binned| -> Vec<(u32, [f32; 256])> { + let (s, n) = (b.index[2 * t] as usize, b.index[2 * t + 1] as usize); + (s..s + n).map(|i| b.entries_at as usize + 4 * i).map(|e| (b.index[e], entry_pixels(b, e))).collect() + }; + let (a, c) = (list(&gb), list(&cb)); + let ops = |l: &[(u32, [f32; 256])]| l.iter().map(|x| x.0).collect::>(); + assert_eq!(ops(&a), ops(&c), "{name}: tile {t}'s fills"); + for ((op, pa), (_, pc)) in a.iter().zip(&c) { + let worst = pa.iter().zip(pc).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(worst < 1e-3, "{name}: tile {t}, op {op}: coverage off by {worst}"); + } + entries += a.len(); + let (s, n) = (gb.index[2 * t] as usize, gb.index[2 * t + 1] as usize); + pieces += (s..s + n).map(|i| gb.index[gb.entries_at as usize + 4 * i + 2] as usize).sum::(); + } + assert_eq!(entries, cb.entries, "{name}"); + assert!(pieces <= gb.pieces && entries <= gb.entries, "{name}: within the room made for them"); + // And the fine pass's arithmetic over the GPU's lists draws the oracle's picture. + let (oracle, _) = render(&dl, &v).unwrap(); + let eg = emulate(&gb, &v); + let (mean, max) = f32_diff(&eg, &oracle.data); + assert!(mean < 1e-4 && max < 4e-3, "{name}: mean {mean:e}, max {max:e}"); + } +} + +#[test] +fn gpu_binned_frames_match_the_oracle() { + let Some(g) = gpu() else { return }; + // Where the GPU stage runs (lavapipe in CI included), its binning must too. + assert_eq!(g.gpu_binning_off(), None); + for (name, dl, v) in gpu_binned_scenes() { + let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap(); + assert!(f.gpu_binned, "{name}"); + let (oracle, _) = render(&dl, &v).unwrap(); + let d = compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap(); + assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "{name}: {d:?}"); + let t = g.render_texture_with(&dl, &v, Binning::Gpu).unwrap(); + assert!(t.gpu_binned && g.read_texture(&t).unwrap() == f.premul8, "{name}: the texture holds the read-back bytes"); + } + // Masks and groups stay on the CPU's binning, and still draw right. + for (name, dl, v) in composited_scenes() { + let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap(); + let uses = |dl: &DisplayList| dl.items.iter().any(|i| i.clip.is_some() || i.group.is_some()); + assert_eq!(f.gpu_binned, !uses(&dl), "{name}: binned on the GPU {}", f.gpu_binned); + let (oracle, _) = render(&dl, &v).unwrap(); + assert!(compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap().max <= 2, "{name}"); + } +} diff --git a/crates/guide/Cargo.toml b/crates/guide/Cargo.toml new file mode 100644 index 00000000..8ab59df6 --- /dev/null +++ b/crates/guide/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "anicraft-guide" +description = "AniCraft L0: the user guide (docs/guide) as a static HTML book, with its link checks" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true + +[dependencies] +craft-html.workspace = true +# CommonMark with GFM tables (MIT; ADR 0069). Default features off: no command-line binary. +pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } + +[lints] +workspace = true + +[dev-dependencies] +serde_json.workspace = true diff --git a/crates/guide/src/lib.rs b/crates/guide/src/lib.rs new file mode 100644 index 00000000..b1bd6dd4 --- /dev/null +++ b/crates/guide/src/lib.rs @@ -0,0 +1,476 @@ +//! AniCraft's user guide as a book (layer L0; ADR 0069). +//! +//! The chapters are Markdown in `docs/guide/`, readable on GitHub as they are. This crate builds +//! them into the bundled book: every page and picture is compiled in, so Help › User Guide works +//! offline, and [`site`] turns them into static HTML pages with one stylesheet, a chapter list +//! and previous / next links. Links between chapters are written to `.md` files and become +//! `.html` links; headings get GitHub's anchor ids, so `timeline.md#onion-skin` works in both +//! places. +//! +//! [`check`] is the book's proof-reader: every internal link and picture resolves, every anchor +//! names a heading, every page is reachable from the contents page and has one title, nothing +//! links outside the book, and there is no raw HTML. Its test keeps the committed guide honest; +//! the generated command and shortcut references are checked for freshness by the app's own +//! tests (`src/guide_reference_tests.rs`), which know the menus and keys. +//! +//! Rendering escapes raw HTML in the Markdown instead of passing it through, so a page can never +//! carry markup or script of its own. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use pulldown_cmark::{CowStr, Event, Options, Parser, Tag, TagEnd}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::path::Path; + +/// One chapter: its file under `docs/guide/` and its Markdown. +#[derive(Clone, Copy, Debug)] +pub struct Page { + pub file: &'static str, + pub markdown: &'static str, +} + +macro_rules! page { + ($f:literal) => { + Page { file: $f, markdown: include_str!(concat!("../../../docs/guide/", $f)) } + }; +} + +macro_rules! image { + ($f:literal) => { + ($f, include_bytes!(concat!("../../../docs/guide/", $f)).as_slice()) + }; +} + +/// The book in reading order. The contents page comes first; the generated references last. +pub const PAGES: &[Page] = &[ + page!("index.md"), + page!("getting-started.md"), + page!("workspace.md"), + page!("drawing.md"), + page!("symbols-and-library.md"), + page!("timeline.md"), + page!("tweens.md"), + page!("masks-guides-camera-bones.md"), + page!("text.md"), + page!("images-and-sound.md"), + page!("interactivity.md"), + page!("exporting-and-publish.md"), + page!("opening-animate-files.md"), + page!("preferences-shortcuts-accessibility.md"), + page!("plugins.md"), + page!("saved-commands.md"), + page!("working-headless.md"), + page!("using-this-guide.md"), + page!("troubleshooting-and-faq.md"), + page!("coming-from-animate.md"), + page!("reference/commands.md"), + page!("reference/shortcuts.md"), +]; + +/// The book's pictures (screenshots from `scripts/guide-shots.sh`), by their path in the book. +pub const IMAGES: &[(&str, &[u8])] = &[ + image!("images/workspace.png"), + image!("images/start-screen.png"), + image!("images/library.png"), + image!("images/onion-skin.png"), + image!("images/motion-editor.png"), + image!("images/test-movie.png"), + image!("images/publish-settings.png"), + image!("images/preferences.png"), +]; + +const STYLE: &str = include_str!("style.css"); +const SEARCH_JS: &str = include_str!("search.js"); +const VERSION: &str = env!("CARGO_PKG_VERSION"); +/// The stylesheet's path in the built book. +pub const STYLESHEET: &str = "style.css"; + +/// One file of the built book: its path (with `/`) and contents. +#[derive(Clone, Debug, PartialEq)] +pub struct SiteFile { + pub path: String, + pub bytes: Vec, +} + +/// The page a chapter becomes: `reference/commands.md` → `reference/commands.html`. +pub fn html_path(md: &str) -> String { + match md.strip_suffix(".md") { + Some(stem) => format!("{stem}.html"), + None => md.to_string(), + } +} + +/// The parser options the book is written for: CommonMark with GFM tables and strikethrough. +fn options() -> Options { + Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH +} + +/// A link target inside the book (not `https:`, `mailto:` or another scheme). +fn is_relative(url: &str) -> bool { + !url.contains(':') && !url.starts_with('/') && !url.starts_with('\\') +} + +/// `foo.md#bar` → `foo.html#bar`; other links stay as they are. +fn rewrite_link(url: &str) -> String { + if !is_relative(url) { + return url.to_string(); + } + match url.split_once('#') { + Some((path, anchor)) if path.ends_with(".md") => format!("{}#{anchor}", html_path(path)), + None if url.ends_with(".md") => html_path(url), + _ => url.to_string(), + } +} + +/// GitHub's heading anchor: lower case, spaces to `-`, letters, digits, `-` and `_` kept. +pub fn slug(heading: &str) -> String { + heading + .trim() + .chars() + .flat_map(char::to_lowercase) + .filter_map(|c| match c { + ' ' => Some('-'), + c if c.is_alphanumeric() || c == '-' || c == '_' => Some(c), + _ => None, + }) + .collect() +} + +/// A page's events, with heading ids (GitHub's, numbered on repeats), `.md` links pointing at +/// pages, and raw HTML turned into visible text. +fn events(markdown: &str) -> Vec> { + let mut out: Vec = Parser::new_ext(markdown, options()) + .map(|e| match e { + Event::Html(h) | Event::InlineHtml(h) => Event::Text(h), + Event::Start(Tag::Link { link_type, dest_url, title, id }) => Event::Start(Tag::Link { link_type, dest_url: CowStr::from(rewrite_link(&dest_url)), title, id }), + Event::Start(Tag::Image { link_type, dest_url, title, id }) => Event::Start(Tag::Image { link_type, dest_url: CowStr::from(rewrite_link(&dest_url)), title, id }), + other => other, + }) + .collect(); + let mut seen: BTreeMap = BTreeMap::new(); + let mut i = 0; + while i < out.len() { + if let Some(Event::Start(Tag::Heading { .. })) = out.get(i) { + let text = heading_text(out.get(i + 1..).unwrap_or_default()); + let id = unique_slug(&mut seen, &text); + if let Some(Event::Start(Tag::Heading { id: slot, .. })) = out.get_mut(i) { + *slot = Some(CowStr::from(id)); + } + } + i += 1; + } + out +} + +/// The text of a heading whose start event came just before `rest`. +fn heading_text(rest: &[Event]) -> String { + let mut s = String::new(); + for e in rest { + match e { + Event::End(TagEnd::Heading(_)) => break, + Event::Text(t) | Event::Code(t) => s.push_str(t), + _ => {} + } + } + s +} + +fn unique_slug(seen: &mut BTreeMap, text: &str) -> String { + let base = slug(text); + let n = seen.entry(base.clone()).or_insert(0); + let id = if *n == 0 { base } else { format!("{base}-{n}") }; + *n += 1; + id +} + +/// A page's title: its first level-one heading. +pub fn title(markdown: &str) -> String { + let mut parser = Parser::new_ext(markdown, options()); + while let Some(e) = parser.next() { + if let Event::Start(Tag::Heading { level: pulldown_cmark::HeadingLevel::H1, .. }) = e { + let rest: Vec = parser.by_ref().take_while(|e| !matches!(e, Event::End(TagEnd::Heading(_)))).collect(); + return heading_text(&rest); + } + } + String::new() +} + +fn escape(s: &str) -> String { + craft_html::escape(s) +} + +/// `../` once per folder the page is in, to reach the book's root. +fn root_prefix(file: &str) -> String { + "../".repeat(file.matches('/').count()) +} + +/// What kind of page the chrome is around (the `data-page` the search script reads). +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Chapter, + Search, +} + +/// The book's chrome around `main`: the header with the search field, the chapter list (with +/// `current` marked) and the footer. `root` climbs from the page to the book's root. +fn chrome(pages: &[Page], root: &str, title: &str, current: Option, main: &str, kind: Kind) -> String { + let mut toc = String::new(); + for (i, p) in pages.iter().enumerate() { + let here = if Some(i) == current { " aria-current=\"page\"" } else { "" }; + toc.push_str(&format!("
  • {}
  • \n", html_path(p.file), escape(&self::title(p.markdown)))); + } + let (page, index, field) = match kind { + Kind::Chapter => ("chapter", String::new(), ""), + Kind::Search => ("search", format!("\n"), " aria-describedby=\"search-status\" aria-controls=\"results\""), + }; + format!( + "\n\n\n\n\n\ + {t} · AniCraft User Guide\n\n{index}\n\n\ + Skip to the chapter\n\ +
    AniCraft User Guide {VERSION}\ +
    \ +
    \n\ +
    \n\n\ +
    \n{main}
    \n
    \n\ +
    AniCraft {VERSION} · MIT OR Apache-2.0 · AniCraft is not affiliated with or endorsed by Adobe.
    \n\ + \n\n\n", + t = escape(title), + ) +} + +/// A chapter as a complete HTML page, with the chapter list and previous / next links. +pub fn render_page(pages: &[Page], at: usize) -> String { + let Some(page) = pages.get(at) else { return String::new() }; + let root = root_prefix(page.file); + let mut body = String::new(); + pulldown_cmark::html::push_html(&mut body, events(page.markdown).into_iter()); + let link = |p: Option<&Page>, rel: &str, word: &str| { + p.map_or_else(String::new, |p| format!("{word}: {}", html_path(p.file), escape(&self::title(p.markdown)))) + }; + let prev = link(at.checked_sub(1).and_then(|i| pages.get(i)), "prev", "Previous"); + let next = link(pages.get(at + 1), "next", "Next"); + let main = format!("{body}\n"); + chrome(pages, &root, &title(page.markdown), Some(at), &main, Kind::Chapter) +} + +/// The search page (ADR 0096): the field in its header searches as you type, and the results +/// are links with their chapter and a passage (`search.js`, over `search-index.js`). +pub fn render_search_page(pages: &[Page]) -> String { + let main = "

    Search

    \n\ +

    Type a word or two to search the guide.

    \n\ + \n\ +
      \n\ +

      Every word you type must match. ↓ and ↑ move through the results, Enter opens the first one, \ + Esc clears the search, and / brings you back to the search field from any page.

      \n"; + chrome(pages, "", "Search", None, main, Kind::Search) +} + +/// A page that sends the browser on to `target` (a page of the book with its anchor). Opening a +/// `file://` page at an anchor loses the anchor on some systems, so context help opens this. +pub fn redirect_page(target: &str) -> String { + let t = escape(target); + format!( + "\n\n\n\n\n\ + AniCraft User Guide\n\n\n

      Open the AniCraft User Guide

      \n\n\n" + ) +} + +/// The search page, its script and its index in the built book (ADR 0096). +pub const SEARCH_PAGE: &str = "search.html"; +pub const SEARCH_SCRIPT: &str = "search.js"; +pub const SEARCH_INDEX: &str = "search-index.js"; +/// The page context help writes beside the book and opens ([`redirect_page`]). +pub const HELP_PAGE: &str = "help.html"; + +/// A place in the book written as a chapter link (`timeline.md#onion-skin`) as the page to open +/// (`timeline.html#onion-skin`). +pub fn target_html(target: &str) -> String { + rewrite_link(target) +} + +/// The heading a chapter link names (`timeline.md#onion-skin` → "Onion skin"; a page alone, its +/// title), or `None` when it names nothing in the book. +pub fn heading_of(pages: &[Page], target: &str) -> Option { + let (file, anchor) = target.split_once('#').map_or((target, None), |(f, a)| (f, Some(a))); + let at = pages.iter().position(|p| p.file == file)?; + let page = pages.get(at)?; + match anchor { + None => Some(title(page.markdown)), + Some(a) => search::sections(std::slice::from_ref(page)).into_iter().find(|s| s.anchor == a).map(|s| s.heading), + } +} + +/// Every place in `targets` (chapter links: `file.md` or `file.md#anchor`) that isn't a page +/// and heading of the book. Context help's map is checked with this, as the chapters' own links +/// are checked by [`check`]. +pub fn check_targets(pages: &[Page], targets: &[&str]) -> Vec { + let scans: BTreeMap<&str, Scan> = pages.iter().map(|p| (p.file, scan(p.markdown))).collect(); + let mut problems = Vec::new(); + for t in targets { + let (file, anchor) = t.split_once('#').map_or((*t, None), |(f, a)| (f, Some(a))); + match scans.get(file) { + None => problems.push(format!("{t}: {file} is not a page of the book")), + Some(s) => { + if let Some(a) = anchor + && !s.anchors.contains(a) + { + problems.push(format!("{t}: {file} has no heading #{a}")); + } + } + } + } + problems +} + +/// The whole book: one HTML page per chapter, the search page with its script and index, the +/// stylesheet and the pictures. +pub fn site() -> Vec { + let mut out: Vec = (0..PAGES.len()).filter_map(|i| PAGES.get(i).map(|p| SiteFile { path: html_path(p.file), bytes: render_page(PAGES, i).into_bytes() })).collect(); + out.push(SiteFile { path: SEARCH_PAGE.to_string(), bytes: render_search_page(PAGES).into_bytes() }); + out.push(SiteFile { path: SEARCH_SCRIPT.to_string(), bytes: SEARCH_JS.as_bytes().to_vec() }); + out.push(SiteFile { path: SEARCH_INDEX.to_string(), bytes: search::index_js(PAGES).into_bytes() }); + out.push(SiteFile { path: STYLESHEET.to_string(), bytes: STYLE.as_bytes().to_vec() }); + out.extend(IMAGES.iter().map(|(path, bytes)| SiteFile { path: (*path).to_string(), bytes: bytes.to_vec() })); + out +} + +/// Writes the book into a folder (made if needed); the number of files written. The paths are +/// the book's own (checked by [`check`]), never input. +pub fn write_site(dir: &Path) -> std::io::Result { + let files = site(); + for f in &files { + let path = f.path.split('/').fold(dir.to_path_buf(), |p, part| p.join(part)); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&path, &f.bytes)?; + } + Ok(files.len()) +} + +/// `rel` (a link written in `from`) as a path from the book's root, or `None` when it climbs +/// out of the book. +fn resolve(from: &str, rel: &str) -> Option { + let mut parts: Vec<&str> = from.split('/').collect(); + parts.pop(); + for part in rel.split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop()?; + } + p => parts.push(p), + } + } + Some(parts.join("/")) +} + +/// What a page links to and which anchors it offers. +struct Scan { + links: Vec, + images: Vec, + anchors: BTreeSet, + titles: usize, + raw_html: usize, +} + +fn scan(markdown: &str) -> Scan { + let mut s = Scan { links: Vec::new(), images: Vec::new(), anchors: BTreeSet::new(), titles: 0, raw_html: 0 }; + let raw: Vec = Parser::new_ext(markdown, options()).collect(); + for e in &raw { + match e { + Event::Start(Tag::Link { dest_url, .. }) => s.links.push(dest_url.to_string()), + Event::Start(Tag::Image { dest_url, .. }) => s.images.push(dest_url.to_string()), + Event::Start(Tag::Heading { level: pulldown_cmark::HeadingLevel::H1, .. }) => s.titles += 1, + Event::Html(_) | Event::InlineHtml(_) => s.raw_html += 1, + _ => {} + } + } + for e in events(markdown) { + if let Event::Start(Tag::Heading { id: Some(id), .. }) = e { + s.anchors.insert(id.to_string()); + } + } + s +} + +/// Everything wrong with a book: broken links, pictures or anchors, links out of the book, pages +/// the contents page can't reach, pages without exactly one title, raw HTML and unused +/// pictures. Empty when the book is sound. `pages[0]` is the contents page. +pub fn check(pages: &[Page], images: &[&str]) -> Vec { + let mut problems = Vec::new(); + let scans: BTreeMap<&str, Scan> = pages.iter().map(|p| (p.file, scan(p.markdown))).collect(); + let mut used_images = BTreeSet::new(); + let mut edges: BTreeMap<&str, Vec> = BTreeMap::new(); + for (file, s) in &scans { + if s.titles != 1 { + problems.push(format!("{file}: has {} level-one headings; a page has exactly one, its title", s.titles)); + } + if s.raw_html > 0 { + problems.push(format!("{file}: has raw HTML; the book is plain Markdown")); + } + for url in &s.links { + if !is_relative(url) { + if !url.starts_with("https://") { + problems.push(format!("{file}: link {url} is neither in the book nor https")); + } + continue; + } + let (path, anchor) = url.split_once('#').map_or((url.as_str(), None), |(p, a)| (p, Some(a))); + let target = if path.is_empty() { Some((*file).to_string()) } else { resolve(file, path) }; + let Some(target) = target else { + problems.push(format!("{file}: link {url} leaves the book")); + continue; + }; + match scans.get(target.as_str()) { + Some(t) => { + if let Some(a) = anchor + && !t.anchors.contains(a) + { + problems.push(format!("{file}: link {url}: {target} has no heading #{a}")); + } + edges.entry(file).or_default().push(target); + } + None if images.contains(&target.as_str()) => { + used_images.insert(target); + } + None => problems.push(format!("{file}: link {url}: {target} is not a page of the book")), + } + } + for url in &s.images { + match resolve(file, url).filter(|t| is_relative(url) && images.contains(&t.as_str())) { + Some(t) => { + used_images.insert(t); + } + None => problems.push(format!("{file}: picture {url} is not one of the book's pictures")), + } + } + } + for image in images { + if !used_images.contains(*image) { + problems.push(format!("{image}: no page shows it")); + } + } + // Every page reachable from the contents page. + if let Some(first) = pages.first() { + let mut reached = BTreeSet::from([first.file.to_string()]); + let mut queue = VecDeque::from([first.file.to_string()]); + while let Some(at) = queue.pop_front() { + for next in edges.get(at.as_str()).into_iter().flatten() { + if reached.insert(next.clone()) { + queue.push_back(next.clone()); + } + } + } + for p in pages { + if !reached.contains(p.file) { + problems.push(format!("{}: can't be reached from {}", p.file, first.file)); + } + } + } + problems +} + +pub mod search; + +#[cfg(test)] +mod tests; diff --git a/crates/guide/src/search.js b/crates/guide/src/search.js new file mode 100644 index 00000000..6c143ba0 --- /dev/null +++ b/crates/guide/src/search.js @@ -0,0 +1,257 @@ +// AniCraft User Guide search (ADR 0096). Works offline from a file:// folder: the index is +// search-index.js, loaded with a script tag. The ranking is a port of crates/guide/src/search.rs +// (`anicraft-cli guide search` prints the same results); keep the two in step. Results are built +// with textContent only, never as markup. +(function () { + "use strict"; + var MAX_QUERY = 200, MAX_TERMS = 8, SNIPPET = 180, LEAD = 60; + var STOP_WORDS = ["a", "an", "and", "are", "as", "at", "be", "by", "can", "do", "does", "for", "from", "how", "i", "if", "in", "is", "it", "my", "of", "on", "or", "the", "to", "what", "when", "where", "with"]; + var WORD = /[\p{Alphabetic}\p{N}]/u; + + function words(s) { + var out = [], cur = "", start = 0, chars = Array.from(s); + for (var i = 0; i < chars.length; i++) { + var c = chars[i]; + if (WORD.test(c)) { + if (cur === "") start = i; + cur += c.toLowerCase(); + } else if (cur !== "") { + out.push([start, cur]); + cur = ""; + } + } + if (cur !== "") out.push([start, cur]); + return out; + } + + function terms(query) { + var all = []; + words(Array.from(query).slice(0, MAX_QUERY).join("")).forEach(function (w) { + if (all.indexOf(w[1]) < 0) all.push(w[1]); + }); + var kept = all.filter(function (w) { return STOP_WORDS.indexOf(w) < 0; }); + return (kept.length ? kept : all).slice(0, MAX_TERMS); + } + + function len(s) { return Array.from(s).length; } + + function matchClass(q, t) { + if (q === t) return 3; + var ql = len(q), tl = len(t); + if (ql >= 2 && t.indexOf(q) === 0) return 2; + if (tl >= 3 && ql <= tl + 2 && q.indexOf(t) === 0) return 1; + return 0; + } + + function best(q, ws) { + var b = 0; + for (var i = 0; i < ws.length; i++) b = Math.max(b, matchClass(q, ws[i][1])); + return b; + } + + function phrase(ws) { + return " " + ws.map(function (w) { return w[1]; }).join(" ") + " "; + } + + function score(p, ts) { + var total = 0; + for (var i = 0; i < ts.length; i++) { + var q = ts[i], body = 0; + for (var j = 0; j < p.body.length; j++) body += matchClass(q, p.body[j][1]); + var s = 30 * best(q, p.heading) + 8 * best(q, p.title) + Math.min(body, 15); + if (s === 0) return null; + total += s; + } + if (ts.length > 1) { + var wanted = " " + ts.join(" ") + " "; + if (phrase(p.heading).indexOf(wanted) >= 0) total += 60; + else if (phrase(p.body).indexOf(wanted) >= 0) total += 20; + } + return total; + } + + function snippet(text, ts) { + var chars = Array.from(text), ws = words(text), at = 0; + for (var i = 0; i < ws.length; i++) { + if (ts.some(function (q) { return matchClass(q, ws[i][1]) > 0; })) { at = ws[i][0]; break; } + } + var start = Math.max(0, at - LEAD); + if (start > 0) { + while (start < at && chars[start - 1] !== " ") start++; + } + var end = Math.min(start + SNIPPET, chars.length); + if (end < chars.length) { + var e = end; + while (e > start + SNIPPET / 2 && chars[e] !== undefined && chars[e] !== " ") e--; + end = e; + } + var body = chars.slice(start, end).join("").trim(); + return (start > 0 ? "…" : "") + body + (end < chars.length ? "…" : ""); + } + + // The words of every section, worked out once. + var prepared = null; + function prepare(index) { + if (prepared && prepared.index === index) return prepared.list; + var titles = index.pages.map(function (p) { return words(p.t); }); + var list = index.sections.map(function (s) { + return { s: s, heading: words(s.h), title: titles[s.p] || [], body: words(s.x) }; + }); + prepared = { index: index, list: list }; + return list; + } + + // The best `limit` sections for `query`, best first: {chapter, heading, url, snippet, score}. + function search(index, query, limit) { + var ts = terms(query); + if (!ts.length || limit <= 0) return []; + var scored = []; + prepare(index).forEach(function (p, i) { + var n = score(p, ts); + if (n !== null) scored.push({ n: n, i: i, p: p }); + }); + scored.sort(function (a, b) { return b.n - a.n || a.i - b.i; }); + return scored.slice(0, limit).map(function (r) { + var s = r.p.s, page = index.pages[s.p] || { f: "", t: "" }; + return { + chapter: page.t, + heading: s.h, + url: s.l === 1 || !s.a ? page.f : page.f + "#" + s.a, + snippet: snippet(s.x, ts), + score: r.n, + terms: ts + }; + }); + } + + if (typeof module !== "undefined" && module.exports) { + module.exports = { search: search, terms: terms, words: words }; + } + if (typeof document === "undefined") return; + + // ---- In the book ---- + var LIMIT = 30; + // A page of the book from the index (search.html sits at the book's root): `page.html` or + // `page.html#anchor`, never a scheme or a path that climbs out. + var PAGE = /^[a-z0-9-]+(\/[a-z0-9-]+)*\.html(#[\p{L}\p{N}_-]*)?$/u; + + function isTyping(el) { + return el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable); + } + + // "/" anywhere in the book goes to the search field. + document.addEventListener("keydown", function (e) { + var q = document.getElementById("q"); + if (e.key === "/" && !e.ctrlKey && !e.metaKey && !e.altKey && q && !isTyping(document.activeElement)) { + e.preventDefault(); + q.focus(); + q.select(); + } + }); + + if (document.body.getAttribute("data-page") !== "search") return; + + var input = document.getElementById("q"); + var status = document.getElementById("search-status"); + var results = document.getElementById("results"); + var index = window.ANICRAFT_GUIDE_INDEX; + + // The snippet with the matching words marked. + function marked(text, ts) { + var frag = document.createDocumentFragment(), chars = Array.from(text), at = 0; + words(text).forEach(function (w) { + if (!ts.some(function (q) { return matchClass(q, w[1]) > 0; })) return; + var n = len(w[1]); + frag.appendChild(document.createTextNode(chars.slice(at, w[0]).join(""))); + var m = document.createElement("mark"); + m.textContent = chars.slice(w[0], w[0] + n).join(""); + frag.appendChild(m); + at = w[0] + n; + }); + frag.appendChild(document.createTextNode(chars.slice(at).join(""))); + return frag; + } + + function links() { + return Array.prototype.slice.call(results.querySelectorAll("a")); + } + + function run() { + var query = input.value; + while (results.firstChild) results.removeChild(results.firstChild); + if (!index) { + status.textContent = "The search index is missing. Use the chapter list instead."; + return; + } + if (!terms(query).length) { + status.textContent = "Type a word or two to search the guide."; + return; + } + var hits = search(index, query, LIMIT); + status.textContent = hits.length === 0 + ? "Nothing in the guide matches “" + query.trim() + "”." + : (hits.length === 1 ? "1 result" : hits.length + (hits.length === LIMIT ? "+ results" : " results")) + " for “" + query.trim() + "”."; + hits.forEach(function (h) { + var li = document.createElement("li"); + if (!PAGE.test(h.url)) return; + var a = document.createElement("a"); + a.setAttribute("href", h.url); + var head = document.createElement("span"); + head.className = "hit-heading"; + head.textContent = h.heading; + var chapter = document.createElement("span"); + chapter.className = "hit-chapter"; + chapter.textContent = h.chapter; + a.appendChild(head); + a.appendChild(chapter); + li.appendChild(a); + if (h.snippet) { + var p = document.createElement("p"); + p.className = "hit-snippet"; + p.appendChild(marked(h.snippet, h.terms)); + li.appendChild(p); + } + results.appendChild(li); + }); + try { + history.replaceState(null, "", "?q=" + encodeURIComponent(query)); + } catch (_) { + // Some browsers refuse to change a file:// address; the results stand all the same. + } + } + + input.addEventListener("input", run); + input.addEventListener("keydown", function (e) { + var first = links()[0]; + if (e.key === "ArrowDown" && first) { + e.preventDefault(); + first.focus(); + } else if (e.key === "Enter") { + e.preventDefault(); + if (first) first.click(); + } else if (e.key === "Escape") { + input.value = ""; + run(); + } + }); + results.addEventListener("keydown", function (e) { + var all = links(), i = all.indexOf(document.activeElement); + if (i < 0) return; + if (e.key === "ArrowDown" && i + 1 < all.length) { + e.preventDefault(); + all[i + 1].focus(); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + if (i === 0) input.focus(); + else all[i - 1].focus(); + } else if (e.key === "Escape") { + e.preventDefault(); + input.focus(); + } + }); + + var params = new URLSearchParams(location.search); + input.value = params.get("q") || ""; + run(); + input.focus(); +})(); diff --git a/crates/guide/src/search.rs b/crates/guide/src/search.rs new file mode 100644 index 00000000..01111a52 --- /dev/null +++ b/crates/guide/src/search.rs @@ -0,0 +1,318 @@ +//! Searching the book (ADR 0096). +//! +//! The book is split into sections, one per heading, each with its plain text. [`index_js`] +//! writes them into `search-index.js`, which the book's search page loads with a `"), "{} has no search field", f.path); + } + let nested = site.iter().find(|f| f.path == "reference/commands.html").expect("a nested page"); + assert!(String::from_utf8_lossy(&nested.bytes).contains("action=\"../search.html\"")); + let page = render_search_page(PAGES); + assert!(page.contains("src=\"search-index.js\"") && page.contains("role=\"status\"") && page.contains("aria-live")); + // The search script never builds markup from the index's text. + assert!(!SEARCH_JS.contains("innerHTML") && !SEARCH_JS.contains("insertAdjacentHTML") && !SEARCH_JS.contains("document.write")); + let js = search::index_js(PAGES); + assert!(js.len() < 512 * 1024, "the index is {} KB", js.len() / 1024); +} + +#[test] +fn context_help_targets_are_checked_and_named() { + assert!(check_targets(PAGES, &["timeline.md#onion-skin", "drawing.md", "reference/commands.md#file"]).is_empty()); + let problems = check_targets(PAGES, &["timeline.md#nope", "nowhere.md#x"]).join("\n"); + assert!(problems.contains("has no heading #nope") && problems.contains("nowhere.md is not a page"), "{problems}"); + assert_eq!(heading_of(PAGES, "timeline.md#onion-skin").as_deref(), Some("Onion skin")); + assert_eq!(heading_of(PAGES, "timeline.md").as_deref(), Some("The timeline")); + assert_eq!(heading_of(PAGES, "timeline.md#nope"), None); + assert_eq!(target_html("timeline.md#onion-skin"), "timeline.html#onion-skin"); + let r = redirect_page("timeline.html#a\"b"); + assert!(r.contains("url=timeline.html#a"b") && !r.contains("a\"b"), "{r}"); +} + +// Frozen pre-cutover escaping oracle; original application behavior. +fn previous_html_escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +#[test] +fn shared_html_escape_preserves_all_unicode_scalars() { + for ch in (0..=0x10ffff).filter_map(char::from_u32) { + let mut buf = [0u8; 4]; + let text = ch.encode_utf8(&mut buf); + assert_eq!(super::escape(text), previous_html_escape(text), "{ch:?}"); + } + for text in ["\n\n\n\n"); if html.len() > MAX_HTML_BYTES { diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index 7858c20f..71c3e47f 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -1,10 +1,14 @@ // AniCraft HTML canvas player: the page (ADR 0028). SPDX-License-Identifier: MIT OR Apache-2.0 // // Draws what player.js evaluates on a 2D context, steps the movie at its frame rate, -// sends the pointer to its buttons and plays its sounds with Web Audio. Drawing follows the +// sends the pointer to its buttons and plays its sounds with Web Audio; the viewer types into +// input text fields through real form elements laid over the canvas. Drawing follows the // CPU renderer (crates/render, the oracle): fills by their rule, round-joined strokes of the // stage-space width, colour effects baked into colours, a symbol that fades or blends as one -// drawn on its own layer first, and masks as the union of their fills. +// drawn on its own layer first, and masks as the union of their fills. A symbol with filters +// draws on a layer that reaches past the canvas by as far as its filters spread, and filters.js +// runs them over its pixels as the renderer does (ADR 0072); Subtract and Invert, which canvas +// 2D lacks, are composited per pixel there too. (function () { "use strict"; const data = document.getElementById("anicraft-movie"); @@ -40,7 +44,10 @@ return scratch.isPointInStroke(stagePath(path, m), x, y); }, }; - const player = new AniCraft.Player(movie, host); + // Each page load gets its own Math.random() sequence (a movie's, not for security); the + // player itself is deterministic. + const seed = Date.now() % 4294967296; + const player = new AniCraft.Player(movie, host, seed); function stagePath(path, m) { const out = new Path2D(); @@ -70,50 +77,162 @@ if (canvas.width !== bw || canvas.height !== bh) { canvas.width = bw; canvas.height = bh; - pool.length = 0; + pool.clear(); + filtered.clear(); + keptPixels = 0; } scale = bw / W; draw(); } // ----- drawing ---------------------------------------------------------------------------------- - // Offscreen layers for groups and clips, reused frame to frame. - const pool = []; - function layer() { - const c = pool.pop() || document.createElement("canvas"); - if (c.width !== canvas.width || c.height !== canvas.height) { - c.width = canvas.width; - c.height = canvas.height; + // Offscreen layers for groups and clips, reused frame to frame, by size and by whether their + // pixels are read back (filters, per-pixel blending: kept in memory, where reading is fast). + // A layer is a canvas and where its top left is on the stage canvas (`x0`, `y0`, in device + // pixels); the stage canvas is the layer at (0, 0). + const pool = new Map(); + function layer(x0, y0, w, h, read) { + const key = w + "x" + h + (read ? "r" : ""); + const free = pool.get(key); + let c = free && free.pop(); + if (!c) { + c = document.createElement("canvas"); + c.width = w; + c.height = h; } - const g = c.getContext("2d"); + const g = c.getContext("2d", read ? { willReadFrequently: true } : undefined); g.setTransform(1, 0, 0, 1, 0, 0); g.globalAlpha = 1; g.globalCompositeOperation = "source-over"; - g.clearRect(0, 0, c.width, c.height); - return { canvas: c, ctx: g }; + g.clearRect(0, 0, w, h); + return { canvas: c, ctx: g, x0: x0, y0: y0, w: w, h: h, key: key }; + } + // A layer the size and place of `l`. + function like(l, read) { + return layer(l.x0, l.y0, l.w, l.h, read); } function release(l) { - pool.push(l.canvas); + let free = pool.get(l.key); + if (!free) pool.set(l.key, (free = [])); + if (free.length < 8) free.push(l.canvas); + } + // Canvas compositing for each blend mode; Subtract and Invert are composited per pixel. + const BLEND = { normal: "source-over", layer: "source-over", multiply: "multiply", screen: "screen", overlay: "overlay", darken: "darken", lighten: "lighten", hardlight: "hard-light", add: "lighter", difference: "difference", alpha: "destination-in", erase: "destination-out" }; + const PER_PIXEL = { subtract: true, invert: true }; + // Largest layer a filtered group draws on (pixels): the renderer's limit, which every browser + // allows a canvas. + const MAX_FILTER_PIXELS = 4096 * 4096; + // How far past a `w × h` layer a filtered one may reach and stay within that (lib.rs + // `filter_setup`); a filter reaching further is cut there, off the stage. + function room(w, h) { + const s = w + h; + return Math.max(Math.floor((Math.sqrt(Math.max(s * s - 4 * (w * h - MAX_FILTER_PIXELS), 0)) - s) / 4), 0); + } + // Filtered groups' pixels by what was drawn in them (and the view), so a group that doesn't + // change between frames is filtered once. Least recently used goes first. + const filtered = new Map(); + const MAX_FILTERED = 64; + // At most this many pixels kept (about 128 MB). + const MAX_KEPT_PIXELS = 32 << 20; + let keptPixels = 0; + + // `src` (a canvas `w × h` whose top left is at `x0`, `y0`; `srcCtx` its context when its pixels + // can be read) onto layer `dst` at `alpha` in blend `mode`. + function composite(dst, src, srcCtx, x0, y0, w, h, alpha, mode) { + const g = dst.ctx; + const dx = x0 - dst.x0, dy = y0 - dst.y0; + alpha = Math.min(Math.max(alpha, 0), 1); + if (PER_PIXEL[mode] && srcCtx && alpha > 0) { + // Only where the group drew, within the layer below. + const ax = Math.max(dx, 0), ay = Math.max(dy, 0); + const bx = Math.min(dx + w, dst.w), by = Math.min(dy + h, dst.h); + if (bx <= ax || by <= ay) return; + try { + const s = srcCtx.getImageData(ax - dx, ay - dy, bx - ax, by - ay); + const r = AniCraftFilters.region(s.data, bx - ax, by - ay, 0); + if (!r) return; + const rw = r[2] - r[0], rh = r[3] - r[1]; + const part = rw === bx - ax && rh === by - ay ? s : srcCtx.getImageData(ax - dx + r[0], ay - dy + r[1], rw, rh); + const d = g.getImageData(ax + r[0], ay + r[1], rw, rh); + AniCraftFilters.blendImage(d.data, part.data, alpha, mode); + g.putImageData(d, ax + r[0], ay + r[1]); + return; + } catch (e) { + // Pixels that can't be read draw normally. + } + } + g.setTransform(1, 0, 0, 1, 0, 0); + g.globalAlpha = alpha; + g.globalCompositeOperation = BLEND[mode] || "source-over"; + g.drawImage(src, dx, dy); + g.globalAlpha = 1; + g.globalCompositeOperation = "source-over"; + } + + // A filtered group's layer `l` through its filters: a canvas cut to where its pixels can show + // (the artwork grown by the filters' reach) and where that is on the stage canvas, or null when + // nothing shows. `sig` is what was drawn on it. + function runFilters(l, grp, sig) { + const key = scale + "|" + JSON.stringify(grp.filters) + "|" + sig; + if (filtered.has(key)) { + const hit = filtered.get(key); + filtered.delete(key); + filtered.set(key, hit); + return hit; + } + let out = null; + try { + const px = l.ctx.getImageData(0, 0, l.w, l.h); + const r = AniCraftFilters.region(px.data, l.w, l.h, AniCraftFilters.reach(grp.margin, scale)); + if (r) { + const w = r[2] - r[0], h = r[3] - r[1]; + const cut = l.ctx.getImageData(r[0], r[1], w, h); + const buf = AniCraftFilters.premul(cut.data); + AniCraftFilters.apply(buf, w, h, grp.filters, scale); + AniCraftFilters.straight(buf, cut.data); + const c = document.createElement("canvas"); + c.width = w; + c.height = h; + const g = c.getContext("2d", { willReadFrequently: true }); + g.putImageData(cut, 0, 0); + out = { canvas: c, ctx: g, x0: l.x0 + r[0], y0: l.y0 + r[1], w: w, h: h }; + } + } catch (e) { + // Pixels that can't be read draw without their filters (not kept: the layer is reused). + return { canvas: l.canvas, ctx: null, x0: l.x0, y0: l.y0, w: l.w, h: l.h }; + } + filtered.set(key, out); + keptPixels += out ? out.w * out.h : 0; + while (filtered.size > MAX_FILTERED || keptPixels > MAX_KEPT_PIXELS) { + const oldest = filtered.keys().next().value; + const o = filtered.get(oldest); + keptPixels -= o ? o.w * o.h : 0; + filtered.delete(oldest); + if (oldest === key) break; + } + return out; } - // Canvas compositing for each blend mode; Subtract and Invert have none and draw normally. - const BLEND = { normal: "source-over", layer: "source-over", multiply: "multiply", screen: "screen", overlay: "overlay", darken: "darken", lighten: "lighten", hardlight: "hard-light", add: "lighter", difference: "difference", alpha: "destination-in", erase: "destination-out", subtract: "source-over", invert: "source-over" }; function paintStyle(g, f, fx) { const p = movie.paints[f]; if (!p) return null; if (p.s) return css(AniCraft.applyEffect(fx, p.s)); if (p.l || p.r) { - const gr = p.l ? g.createLinearGradient(p.l[0], p.l[1], p.l[2], p.l[3]) : g.createRadialGradient(p.r[0], p.r[1], 0, p.r[0], p.r[1], p.r[2]); + const gr = p.l ? g.createLinearGradient(p.l[0], p.l[1], p.l[2], p.l[3]) : g.createRadialGradient(p.f ? p.f[0] : p.r[0], p.f ? p.f[1] : p.r[1], 0, p.r[0], p.r[1], p.r[2]); for (const s of p.st) gr.addColorStop(s[0], css(AniCraft.applyEffect(fx, [s[1], s[2], s[3], s[4]]))); return gr; } if (p.b !== undefined) { const im = images[p.b]; if (!im || !im.complete || !im.naturalWidth) return "rgba(128,128,128,1)"; - const key = f; + // A colour effect beyond alpha draws the bitmap's pixels through it (ADR 0056), as the + // renderer does: once per bitmap and effect while the effect stays the same. + const recolour = AniCraft.recolours(fx); + const key = recolour ? f + ":" + fx.join(",") : f; let pat = patterns.get(key); if (!pat) { - pat = g.createPattern(im, p.rep ? "repeat" : "no-repeat"); + if (patterns.size > 256) patterns.clear(); + pat = g.createPattern(recolour ? recoloured(im, fx) : im, p.rep ? "repeat" : "no-repeat"); if (pat && p.m && pat.setTransform) pat.setTransform(new DOMMatrix(p.m)); patterns.set(key, pat); } @@ -122,38 +241,292 @@ return null; } + // `im`'s pixels through colour transform `fx`, on a canvas of its size. + function recoloured(im, fx) { + const c = document.createElement("canvas"); + c.width = im.naturalWidth; + c.height = im.naturalHeight; + const g = c.getContext("2d"); + g.drawImage(im, 0, 0); + let px; + try { + px = g.getImageData(0, 0, c.width, c.height); + } catch (e) { + return im; + } + const d = px.data; + for (let i = 0; i < d.length; i += 4) { + const o = AniCraft.applyEffect(fx, [d[i] / 255, d[i + 1] / 255, d[i + 2] / 255, d[i + 3] / 255]); + d[i] = Math.round(o[0] * 255); + d[i + 1] = Math.round(o[1] * 255); + d[i + 2] = Math.round(o[2] * 255); + d[i + 3] = Math.round(o[3] * 255); + } + g.putImageData(px, 0, 0); + return c; + } + + // ----- text fields (ADR 0066) ------------------------------------------------------------------ + // A field draws its background, its text cut to its box, and its border, as the renderer does. + // Its authored text is its outline (the author's fonts, as everywhere); text a script or the + // viewer changed is drawn here with the browser's fonts. An input field is a real (one + // line, or a password) or