Merge fix/text-bidi (main) into fix/text-fallback
No files matched your search
@@ -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)"
|
||||
@@ -27,6 +27,10 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -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"
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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:
|
||||
@@ -26,6 +26,10 @@ jobs:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
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
|
||||
@@ -48,7 +52,8 @@ jobs:
|
||||
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
|
||||
# The release download too (#210): what the release workflow's web job runs.
|
||||
- name: The web editor bundle and its release zip
|
||||
run: |
|
||||
scripts/build-web.sh
|
||||
ls -l web
|
||||
packaging/web/package.sh
|
||||
ls -l web dist/release
|
||||
@@ -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)
|
||||
```
|
||||
|
||||
|
||||
@@ -19,15 +19,18 @@ shaders or SDK code).
|
||||
| Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | <https://github.com/source-foundry/Hack> | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) |
|
||||
| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | <https://github.com/googlefonts/noto-emoji> | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) |
|
||||
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
|
||||
| `assets/icons/anicraft-*.svg` (19 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
|
||||
| `assets/icons/anicraft-*.svg` (28 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) | 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 | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
|
||||
| `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
| `crates/svg/fixtures/soft-masks-text-paths.svg` | SVG import test drawing (an alpha and a luminance mask, text on a path) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (37 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons, plus, trash, copy, ellipsis) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0; `plus.svg`, `trash.svg`, `copy.svg` and `ellipsis.svg` from Lucide's `main` branch, 2026-11) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
| `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) |
|
||||
| `packaging/macos/dmg/` (`background.tiff`, `dmg-layout.DS_Store`) | macOS DMG window background and Finder layout | AniCraft contributors | Original work drawn by `packaging/macos/dmg/generate.py` in the app icon's colours; layout approach as in the PhotoCraft sibling project | MIT OR Apache-2.0 |
|
||||
| `docs/guide/images/` (8 screenshots) | User guide (Help › User Guide) | AniCraft contributors | Original work: AniCraft's own screenshots, taken by `scripts/guide-shots.sh` | MIT OR Apache-2.0 |
|
||||
| `docs/images/` (screenshots and `sample-animation.gif`) | README | AniCraft contributors | Original work: AniCraft's own screenshots (`--screenshot`) and sample animation (`anicraft-cli gif`) | MIT OR Apache-2.0 |
|
||||
| Library symbol-kind marks, selection handles, timeline marks | UI | AniCraft contributors | Original work, drawn in code (`src/panels.rs`, `src/timeline.rs`, `src/stage.rs`) | MIT OR Apache-2.0 |
|
||||
| Sample animation (ball, star, sun, hills, sky) | First launch, tests, CLI `--sample` | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`) | MIT OR Apache-2.0 |
|
||||
| Interactive sample (menu, Play button, spinner) | File › New from Sample (`which: interactive`), Test Movie tests and screenshots | AniCraft contributors | Original work, generated in code (`crates/doc/src/sample.rs`, `interactive`) | MIT OR Apache-2.0 |
|
||||
| Built-in templates (Leaderboard and Rectangle banners, Social square, Storyboard 16:9, Character turnaround, Lip-sync mouth chart: guides, layers, labels and placeholder mouth shapes) | File › New from Template and the start screen (ADR 0065) | AniCraft contributors | Original work, generated in code (`crates/doc/src/templates.rs`); sizes and safe areas follow public conventions (the IAB's 728 × 90 and 300 × 250 ad units, EBU R 95's 93 % action-safe and 90 % title-safe areas), the mouth set the common phoneme groups animators use | MIT OR Apache-2.0 |
|
||||
| Colour theme | UI | AniCraft contributors | Original work (`src/theme.rs`) | MIT OR Apache-2.0 |
|
||||
| `docs/brand/artcraft-logo-white.png` | ArtCraft brand mark (wordmark, light ink for dark backgrounds) | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`), not open source |
|
||||
| `docs/brand/artcraft-logo-white.svg` | ArtCraft brand mark (wordmark, light ink for dark backgrounds) | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`), not open source |
|
||||
@@ -82,23 +85,29 @@ OR Apache-2.0) is noted in the table.
|
||||
| Tile binning on the GPU: count, prefix sum, scatter, per-tile lists | `crates/gpu/src/gpu_binning.rs`, `crates/gpu/src/bin.wgsl`, `crates/gpu/src/scan.wgsl` | The binning stages described for *Vello* (above) and Patrick Walton's *Pathfinder* (<https://github.com/servo/pathfinder>, Apache-2.0 OR MIT) design posts; the work-efficient scan of G. E. Blelloch, *Prefix Sums and Their Applications* (CMU-CS-90-190, 1990) | Our own arrangement (one invocation per row of a fill's tiles, no atomics) written from the public descriptions; no code or shaders copied (ADR 0048). |
|
||||
| Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). |
|
||||
| Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), <https://cldr.unicode.org>, Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. |
|
||||
| Stage elements as a multi-select list box; menu bar keyboard model (Alt/F10, arrows, access keys) | `src/stage_a11y.rs`, `src/menus.rs` | W3C *WAI-ARIA Authoring Practices Guide*, Listbox and Menubar patterns, <https://www.w3.org/WAI/ARIA/apg/> (W3C Software and Document License) | Keyboard behaviour learned from the published patterns; no code or text copied. |
|
||||
| Reading the desktop's contrast setting | `src/platform.rs` | *XDG Desktop Portal*, Settings interface, `org.freedesktop.appearance` `contrast` key, <https://flatpak.github.io/xdg-desktop-portal/> (LGPL documentation, read only; nothing bundled or linked) | One value read through the `gdbus` tool. |
|
||||
| Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). |
|
||||
| Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | |
|
||||
| Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. |
|
||||
| Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs`, `crates/gpu/src/fine.wgsl` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. |
|
||||
| Adjust Color filter (brightness, contrast, saturation and hue as colour matrices) | `crates/render/src/filters.rs` | Paul Haeberli, *Matrix Operations for Image Processing* (Silicon Graphics, 1993) | Public description; standard matrix operations. |
|
||||
| Colour effects (per-channel multiply and offset; brightness and tint as such transforms) | `crates/doc/src/color_effect.rs`, `crates/gpu/src/fine.wgsl`, `crates/render/src/svg.rs` | Adobe, *ActionScript 3.0 Reference: flash.geom.ColorTransform* (public documentation); W3C *Filter Effects Module Level 1*, `feColorMatrix` | Behaviour learned from the public descriptions; no code or assets used (ADR 0056). |
|
||||
| Blur, drop shadow and glow by repeated box blurs | `crates/render/src/filters.rs` | Standard image processing (repeated box filters approach a Gaussian, central limit theorem) | Public; no specific implementation followed. |
|
||||
| Bevel and Gradient Bevel by offset differences of the blurred opacity; Gradient Glow and Gradient Bevel through a colour ramp | `crates/render/src/filters.rs` | Standard image processing: embossing as the difference of an image offset along the light direction (a directional derivative; e.g. R. C. Gonzalez & R. E. Woods, *Digital Image Processing*); parameters and behaviour from Adobe's public Animate user guide and ActionScript 3.0 reference (`BevelFilter`, `GradientGlowFilter`, `GradientBevelFilter`) | Public descriptions only; no Adobe code or assets (ADR 0025). |
|
||||
| Bevel and gradient filters in SVG export (`feComposite` arithmetic, `feComponentTransfer` tables) | `crates/render/src/svg.rs` | W3C Filter Effects Module Level 1 / SVG 1.1 filters | W3C Royalty-Free Patent Policy. |
|
||||
| Timeline playback semantics for actions (stop, play, go to frame or label, next/previous frame and scene; button Up/Over/Down/Hit states; mouse events) | `crates/actions`, `crates/doc/src/player.rs` | Behaviour learned from Adobe's public *ActionScript 3.0 Reference* (`MovieClip`, `SimpleButton`, `MouseEvent`) and the public Animate user guide on buttons, plus observation (ADR 0013, ADR 0024) | Clean room: no Adobe code, SDKs or players; names used nominatively. |
|
||||
| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the action IR | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `EventDispatcher.addEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. |
|
||||
| Seeded `Math.random()` for the player (xorshift128) | `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | G. Marsaglia, "Xorshift RNGs", *Journal of Statistical Software* 8(14), 2003 (public paper); 53-bit doubles from two 32-bit outputs as the common construction | Our own implementation of a published algorithm. |
|
||||
| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the script IR, the evaluator (types, coercions, operators, `Math`, listeners for enter-frame and keys) | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `Event`, `KeyboardEvent`, `flash.ui.Keyboard`, `Math`, `EventDispatcher.addEventListener` and `removeEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. |
|
||||
| Cubic-Bézier easing (CSS model) | `crates/doc/src/easing.rs` | W3C CSS Easing Functions Level 1 | W3C Royalty-Free Patent Policy. |
|
||||
| SVG path data syntax (file format v2) | `crates/geom/src/path.rs` | W3C SVG 1.1 / 2 | W3C Royalty-Free Patent Policy. |
|
||||
| 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`, `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). |
|
||||
| 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. |
|
||||
@@ -108,17 +117,23 @@ OR Apache-2.0) is noted in the table.
|
||||
| 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). |
|
||||
| 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. |
|
||||
| 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). |
|
||||
| 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
|
||||
|
||||
|
||||
@@ -2,6 +2,508 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Drawing parity leftovers** (ADR 0080, M1).
|
||||
* **PolyStar options**: Shape (**Polygon** or **Star**), **Sides**/**Points** (3 to 32) and
|
||||
**Point size** (0 to 1; at 1 a star is the polygon through its tips) in the tool's options.
|
||||
It merges or draws objects like the other shape tools.
|
||||
* **Paint Selection** and **Paint Inside** brush modes: the paint is clipped exactly to the
|
||||
selected fills, or to the fill (or the empty area closed off) where the stroke starts, and
|
||||
never covers lines. Paint Selection keeps the selection for the next stroke.
|
||||
* **Double-click a drawing object** (or Ctrl+E) to edit it in place, as groups and symbols
|
||||
open: inside, its raw shapes merge only with each other. It closes as one drawing object
|
||||
again; opening and closing it without an edit changes nothing.
|
||||
* **Modify › Transform › Envelope**: corner and tangent handles bend the selected shapes and
|
||||
drawing objects through a Bézier patch, one undo step per drag. Like Animate, the bend is
|
||||
baked into the shapes, so there is no Delete Envelope.
|
||||
* Headless: `shape`, `sides`, `point_size` on `draw.star`; `selection` and `inside` modes on
|
||||
`draw.brush`; drawing objects on `symbol.edit`; `modify.envelope`,
|
||||
`modify.envelope_move`, `modify.envelope_close`.
|
||||
|
||||
* **Asset Warp** (M7, ADR 0079; refs #213).
|
||||
* **Added**: the **Asset Warp** tool (**Shift+Q**). Click a shape or a bitmap to pin it (the
|
||||
first pin covers it with a warp mesh), drag a pin to bend the artwork around the others,
|
||||
live, one undo step per drag; Delete removes the picked pin. Bending is rigid moving least
|
||||
squares, so the artwork stays as rigid as it can near the pins.
|
||||
* **Added**: pin poses per keyframe, tweened with classic tweens and their easing; a pin added
|
||||
later lands on every keyframe of the artwork. Properties › Asset Warp sets the mesh's
|
||||
resolution and removes pins or the whole warp (also in Modify › Asset Warp).
|
||||
* **Added**: bitmaps bend in the renderer and on the GPU stage (the same prepared image, so
|
||||
they match exactly) and in every raster export; SVG writes a bent bitmap as an image; HTML
|
||||
and Lottie report it. Warped shapes are bent outlines everywhere.
|
||||
* **Added**: commands `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`,
|
||||
`warp.remove` and `warp.info`, for scripts, plug-ins, the CLI and MCP.
|
||||
* **Swatches panel** (M1, ADR 0078).
|
||||
* **Added**: **Window › Swatches**, the document's saved colours and gradients, saved in the
|
||||
document (new documents and older files start with a default set). Click a swatch to apply
|
||||
it to the selection and the tool colour, to the stroke or the fill, whichever is active
|
||||
(the Tools panel's and Colour panel's squares choose, or the panel's own toggle); gradients
|
||||
go to the fill. Add the current colour or gradient, Duplicate, Delete, drag to reorder
|
||||
(Alt+arrows from the keyboard), names on hover, Clear and Load Default Swatches. Every
|
||||
change is one undo step.
|
||||
* **Added**: Import and Export Swatches as a small JSON swatch file, and import of GIMP `.gpl`
|
||||
palettes. Adobe's `.aco`, `.ase` and `.clr` are proprietary and not read.
|
||||
* **Added**: the colour picker shows the document's swatches, and the fill picker its gradient
|
||||
swatches.
|
||||
* **Added**: commands `swatch.list`, `swatch.add`, `swatch.remove`, `swatch.move`,
|
||||
`swatch.duplicate`, `swatch.rename`, `swatch.apply`, `swatch.clear`, `swatch.reset`,
|
||||
`swatch.import` and `swatch.export`, for scripts, the CLI and MCP (plug-ins may edit swatches
|
||||
but not read or write swatch files).
|
||||
* **Fixed**: the timeline's layer footer cut **Delete** to "Del…" at the default window size
|
||||
since docking. Its buttons are now icon buttons (New Layer, Delete, New Folder, Up, Down),
|
||||
named for screen readers, that fit at any size and in any language.
|
||||
* **Rulers, grid and guides** (ADR 0076, M1).
|
||||
* **View › Rulers** (**Ctrl+Alt+Shift+R**): rulers along the top and left of the stage, in
|
||||
pixels from its corner, following zoom and pan and marking the pointer.
|
||||
* **Guides**: drag one out of a ruler; drag it with the Selection tool to move it, or back
|
||||
onto a ruler to delete it. Each scene keeps its guides in the document. **View › Guides**:
|
||||
Show (**Ctrl+;**), Lock (**Ctrl+Alt+;**), Snap to Guides (**Ctrl+Shift+;**), Edit Guides
|
||||
(**Ctrl+Alt+Shift+G**: colour, accuracy, and every guide by position, so the keyboard can
|
||||
add, move and delete them), Add Guide and Clear Guides.
|
||||
* **Grid**: **View › Grid** › Show Grid (**Ctrl+'**), Snap to Grid (**Ctrl+Shift+'**), Edit
|
||||
Grid (**Ctrl+Alt+G**: spacing, colour, show over objects, accuracy up to Always snap).
|
||||
* **Snap to Pixels** in View › Snapping, next to Snap to Objects, Grid and Guides.
|
||||
* One snap engine for every drawing tool, the Selection tool's moves (symbols, text and
|
||||
bitmaps now snap by their box's corners and centre) and Free Transform's handles, in a
|
||||
fixed order: point, guide, line, grid, pixel.
|
||||
* Shown on the stage only, never in Test Movie or exports.
|
||||
* Headless: `view.*` commands (`view.guide_add`, `view.grid_set`, `view.guides_clear`, …)
|
||||
and `view.aids`.
|
||||
|
||||
* **A light theme** (ADR 0077, M8). Fixes #227.
|
||||
* **Preferences › Appearance › Theme** offers **Light** beside **Dark (Graphite)** and **High
|
||||
contrast**: light grey panels, near-black text, hairline-edged buttons and fields, soft
|
||||
shadows, and the timeline's mint, violet, amber and sky blocks in deeper tones made for a light
|
||||
background. Applied as you click, no restart.
|
||||
* **Follow system** now follows your system's light or dark mode as well as its
|
||||
contrast setting: Windows' app mode, macOS' Appearance, the Linux desktop's colour scheme and
|
||||
the browser's `prefers-color-scheme`. The window's title bar follows too.
|
||||
* `anicraft --theme light` (also `dark`, `high-contrast`) previews a theme for one run.
|
||||
* Every palette is checked by the contrast test (WCAG AA text, 3:1 controls and focus).
|
||||
|
||||
* **Gradient editor, the Gradient Transform tool and Lock Fill** (M1, ADR 0074; #208, #203).
|
||||
* **Added**: gradients in the colour picker. The fill's picker (the Tools panel's Fill square,
|
||||
and every Fill swatch in Properties) starts with the fill's type: None, Solid, Linear,
|
||||
Radial or Bitmap. A gradient shows a bar of colour stops (click to add, drag to move, drag
|
||||
off to remove; arrow keys and Delete on a focused stop), overflow (Extend, Reflect, Repeat),
|
||||
Linear RGB and a radial gradient's focal point, above the same swatches, mixer and hex
|
||||
field, which then set the picked stop's colour and opacity. A gradient's swatch in
|
||||
Properties shows its ramp. One picker, as Animate has one Color panel; the fill's No Colour
|
||||
is its type None.
|
||||
* **Added**: the **Gradient Transform** tool (**F**): move, turn, stretch and resize a gradient,
|
||||
move a radial gradient's focal point, and scale, turn and skew a bitmap fill. Each drag is
|
||||
one undo step.
|
||||
* **Added**: **Lock Fill** for the Paint Bucket and the Brush. Without it, gradients and bitmaps
|
||||
are fitted to each shape, as in Animate; the Eyedropper turns it on for what it picks.
|
||||
* **Added**: commands `paint.set_fill`, `paint.transform_fill` and `paint.lock_fill`, for
|
||||
scripts, the CLI and MCP.
|
||||
* **Improved**: gradients keep their overflow, Linear RGB, focal point and elliptical shape
|
||||
from Animate files and SVG drawings, on the GPU stage and in SVG export (HTML canvas draws
|
||||
them as near as canvas can). Radial gradients on skewed shapes are now drawn exactly.
|
||||
* **Dockable panels and workspaces** (M8, ADR 0075, fixes #249).
|
||||
* Drag any panel's tab to dock it on any side of the stage (the timeline above the stage, for
|
||||
example), stack it with other panels as a tab, or float it in a window of its own (inside
|
||||
the editor where a system can't open one). Docks and the lines between panel groups resize,
|
||||
groups fold, and every panel has a menu (☰, or right-click its tab) to dock, float or close
|
||||
it from the keyboard.
|
||||
* **Window** lists every panel; choosing one brings it forward, reopening it where it was.
|
||||
* **Window › Workspace**: Essentials (the layout so far), Animator and Designer, your own with
|
||||
**Save Workspace…**, and **Reset**. Where everything is is kept in your preferences.
|
||||
* New **Colour** (stroke and fill, Swap, Black and White) and **Output** (Test Movie's lines,
|
||||
kept after it closes) panels. Ctrl+F6 visits every docked panel in the order they are docked.
|
||||
* **Groups and Combine Objects** (ADR 0073, M1; issues #206, #229).
|
||||
* **Modify › Group** (**Ctrl+G**) and **Ungroup** (**Ctrl+Shift+G**): keep artwork together
|
||||
without a Library symbol. Double-click a group to edit it in place (the rest dims, the edit
|
||||
bar says `Scene 1 › Group`); groups nest; merged drawing inside a group only cuts and joins
|
||||
the shapes in that group. Ungroup puts everything back exactly where it showed. Break Apart
|
||||
on a group ungroups it.
|
||||
* **Modify › Combine Objects › Union, Intersect, Punch, Crop** on two or more selected shapes,
|
||||
with the exact geometry of merge drawing.
|
||||
* **Selection tool**: **Alt-drag** (Option-drag) to drag a copy away; **Shift** keeps a move
|
||||
horizontal, vertical or at 45°.
|
||||
* **Break Apart** on a group ungroups it; its merged drawing merges with the drawing below.
|
||||
* Animate files keep their groups (`DOMGroup` used to be flattened).
|
||||
* Headless: `modify.group`, `modify.ungroup`, `modify.combine {op}`, `symbol.edit {id}` on a
|
||||
group.
|
||||
|
||||
* **Fixed: start-up, files and display, from user reports** (M8).
|
||||
* Fixed: Flash files that opened in 0.1 no longer opening (#226). One damaged or unreadable
|
||||
part of a `.fla` (a bitmap, a sound, a library symbol) no longer stops the whole file from
|
||||
opening: the rest opens and the report says what was left out. A file double-clicked or
|
||||
opened with **Open With** that can't be opened now says why in the status bar instead of
|
||||
quietly showing the sample, and `anicraft-cli info`, `render` and the export commands open
|
||||
`.fla` and `.xfl` files too.
|
||||
* Fixed: Animate documents opening on a black stage instead of white (#163).
|
||||
* Fixed: AniCraft not opening at all on some laptops with two graphics chips, such as the
|
||||
Surface Book 2 (#207). If a way of drawing the window fails, AniCraft now tries the next one
|
||||
(on Windows: DirectX 12 on the built-in chip, then OpenGL) instead of exiting, and a start that
|
||||
crashed inside a graphics driver tries that way last next time. If nothing works, a message
|
||||
says so. A start-up log in the settings folder (`Logs/anicraft.log`) records what was tried,
|
||||
to attach to a bug report.
|
||||
* New: **Preferences › Stage › Window graphics** chooses how the window is drawn (Automatic,
|
||||
DirectX 12, Vulkan, Metal or OpenGL), for windows that flicker or flash black (#255).
|
||||
`--renderer dx12`, `vulkan` and `metal` now pick that interface; before, they all meant the
|
||||
default.
|
||||
* Fixed: the selection shading on shapes stopping part way down when zoomed in or on a big
|
||||
shape (#204). The dot pattern now covers the whole shape and its outline at any zoom, and
|
||||
costs the same however much of the screen it covers.
|
||||
* The web version's download is now built by `packaging/web/package.sh` and checked in CI; the
|
||||
README no longer suggests releases carry it yet (#210).
|
||||
* **Drawing tools and colour fixes from user reports** (M1).
|
||||
* **Fixed**: the Fill and Stroke colour squares in the Tools panel did nothing when clicked.
|
||||
They open the colour picker now, with No Colour, and recolour selected shapes (#246).
|
||||
* **Fixed**: the colour picker had no hex field. Every colour swatch's picker shows the colour
|
||||
as `#rrggbb` and takes one you type (#201).
|
||||
* **Fixed**: the colour picker had no web-safe palette. It opens on Animate's 216 web-safe
|
||||
swatches, with greys and primaries beside them and the colours you mix or type in a row
|
||||
below; **Mixer** has the full picker (#248).
|
||||
* **Fixed**: the Pencil's Properties showed a Fill swatch, though the Pencil only draws lines.
|
||||
The Pencil and the Line tool show only the stroke now (#252).
|
||||
* **Fixed**: a squiggle drawn with Object Drawing on was trapped in its object. **Modify ›
|
||||
Break Apart** (Ctrl+B) now turns a drawing object into merged drawing you can edit (#253).
|
||||
* **Fixed**: the Width tool didn't thicken a line when you dragged on it, the pointer didn't
|
||||
change, and the marker was a tiny dark box. A drag on the line widens it there, the pointer
|
||||
is a crosshair (an add pointer over a line), and the marker is a white box with handles
|
||||
(#250).
|
||||
* **Fixed**: every new line segment came with a scale gizmo whose handles couldn't be dragged,
|
||||
and a box appeared after every brush or pencil stroke. As in Animate, what you draw isn't
|
||||
left selected, and the Selection tool's box no longer shows handles that do nothing (#205,
|
||||
#243).
|
||||
* **Fixed**: Ctrl-dragging a shape's edge made a smooth curve. It adds a corner point where you
|
||||
pressed, with straight sides on a straight edge (#200).
|
||||
* **Filters, Subtract and Invert in HTML canvas export** (ADR 0072, M6). Exported web pages now
|
||||
show every filter (Drop Shadow, Blur, Glow, Bevel, Gradient Glow, Gradient Bevel and Adjust
|
||||
Color, with inner, knockout, hide object and Inner/Outer/Full) and the Subtract and Invert blend
|
||||
modes as AniCraft draws them, in every browser: the page runs a port of AniCraft's own filters
|
||||
over the symbol's pixels instead of the browser's effects, and shadows and glows reach onto the
|
||||
stage from symbols beside it. A filtered symbol that doesn't change is filtered once. Tested
|
||||
against AniCraft's renderer pixel by pixel (35 filter set-ups at three view scales, within
|
||||
1/1000) and checked in a browser. At 1080p the demo's filtered symbols cost 3.4 ms a frame while
|
||||
they change; one covering the whole frame 50 to 150 ms. The export report no longer lists them.
|
||||
* **Timeline, bones, menus and stage fixes from user reports** (M1).
|
||||
* **Fixed**: F5 with no frames selected only extended the active layer. It now extends every
|
||||
layer that has frames at or after the playhead, as in Animate, and leaves the layers that end
|
||||
before it alone (#242).
|
||||
* **Fixed**: after F5, F6 or F7 you had to select the next frame by hand. F5 now moves onto the
|
||||
frame it adds, and F6 or F7 on a keyframe makes the new keyframe on the next frame and moves
|
||||
there, so draw, F6, draw keeps going (#254). F7 on a keyframe no longer clears its drawing.
|
||||
* **Fixed**: the timeline's Frame, Keyframe and Blank buttons took a lot of room. They are icons
|
||||
now (a frame, a filled dot and a hollow dot, each with a plus), named in their tooltips (#240).
|
||||
* **Fixed**: bone chains looked broken and jumped while posing. A bone started anywhere on an
|
||||
instance now starts at the end of the bone before it, so the chain stays joined, and dragging
|
||||
a bone along its length moves it from where you grabbed it instead of snapping its end to the
|
||||
pointer (#239).
|
||||
* **Fixed**: on macOS there were no menus (no File, no Save). The title bar covered the menu
|
||||
row; it is see-through now, as designed (#247).
|
||||
* **Fixed**: you couldn't draw outside the stage; anything past its edge was hidden. The
|
||||
pasteboard now shows your artwork, as in Animate, and **Clip content outside the stage**
|
||||
(beside the zoom menu, and in the View menu) hides it again when you want (#245, #251).
|
||||
* **Soft masks and text on a path** (ADR 0070, M4).
|
||||
* **Soft masks**: Layer Properties › **Mask type** on a mask layer: *Shape* (as in Animate),
|
||||
*Alpha* (the mask's opacity reveals: a gradient to transparent fades the artwork out) or
|
||||
*Luminance* (the mask's brightness reveals: white shows, black hides). On the stage, on the
|
||||
GPU stage, in Test Movie and in every export: SVG writes a `mask`, Lottie a track matte, the
|
||||
HTML canvas composites it. `layer.set_mask` does it headless.
|
||||
* **Text on a path**: Properties › Path › **Attach to Path**, then click a shape: static text
|
||||
follows its outline (a copy of it; the shape stays). Move it along with **Offset**, put it on
|
||||
the other side with **Flip**, and **Release** it back to lines of text. The alignment says
|
||||
whether the text starts, is centred or ends at the offset. Editing the words, the font or
|
||||
the size keeps it on its path. Also Modify › Text › Attach Text to Path.
|
||||
* **SVG import**: soft masks come in as soft mask layers (luminance, or alpha with
|
||||
`mask-type: alpha`) instead of being drawn unmasked; `textPath` comes in as text on a path;
|
||||
per-character `x`, `y`, `dx`, `dy` and `rotate` are kept where they are simple.
|
||||
* **Bones inside shapes** (ADR 0071, M7).
|
||||
* The **Bone** tool now also draws bones inside a shape, so the shape itself bends like a tail
|
||||
or a tentacle. Its points follow the nearest bones, and the bend stays smooth through the
|
||||
joints. Lines keep their width, and the shape as drawn comes back exactly at rest.
|
||||
* Pose by dragging bones with the Selection tool. Poses key per frame and tween with easing,
|
||||
as symbol armatures do, and every export, Test Movie and the stage show the bend.
|
||||
* The new **Bind** tool (**Shift+M**) shows which points follow which bone, and changes it by
|
||||
click, Shift-click, Ctrl-click or a box. **Properties › Bone** counts the bone's points and
|
||||
has **Rebind All**.
|
||||
* Headless: `bone.add_in_shape`, `bone.bind`, and `bone.info` with `points`.
|
||||
* **CI on macOS and Windows** (ADR 0067, M8). Every pull request that changes code now builds,
|
||||
tests and lints the workspace on macOS (arm64) and Windows (x64) runners as well as Linux, so
|
||||
macOS-only and Windows-only code is checked before it merges. Documentation-only changes skip
|
||||
them, and a newer push cancels the older run. Their first run
|
||||
found one macOS-only failure: the screen-reader translation tests treated the macOS app
|
||||
menu's title, the product name, as untranslated.
|
||||
* **The user guide** (ADR 0069, M8).
|
||||
* **Help › User Guide** opens AniCraft's guide in your browser. It comes with the app, so it
|
||||
works offline; the web editor serves it beside the editor. It is also in the command palette.
|
||||
* Eighteen chapters written for artists, from getting started, drawing, symbols, the timeline and
|
||||
tweens to masks, the camera and bones, text, images and sound, interactivity, exporting and
|
||||
Publish, opening Animate files, preferences and accessibility, plug-ins, working headless, and
|
||||
troubleshooting, plus **Coming from Animate**, which maps Animate's panels, tools and shortcuts
|
||||
to AniCraft's.
|
||||
* A **command reference** and a **shortcut reference** (with the macOS keys beside the others),
|
||||
generated from AniCraft itself, so they always match the version you have.
|
||||
* `anicraft-cli guide --out <folder>` writes the guide as HTML pages.
|
||||
* On macOS, the fixed keys that hold a key while dragging ("Space+Drag") keep that key in their
|
||||
label.
|
||||
* **Brush library, pressure curves and the Paint Brush** (ADR 0068, M7).
|
||||
* **Window › Brush Library**: seven built-in brushes, each with a stroke preview drawn by the
|
||||
renderer: Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk (a ragged edge that
|
||||
is the same every time) and Dotted. They are all made of parameters, with no bitmaps. A click
|
||||
sets the brush in hand.
|
||||
* **Your own brushes**: Save Brush keeps the brush in hand under a name, in your preferences.
|
||||
Right-click to rename or delete one (deleting asks first). Import… and Export… move a brush
|
||||
set between computers as a small JSON file.
|
||||
* **Pressure curves**: an editor in Properties maps pen pressure to the size and, optionally,
|
||||
to the stroke's opacity. It has Linear, Soft and Firm presets, or your own points.
|
||||
* **Shaping**: tapers at the start and end, dab spacing and a rough edge, in Properties.
|
||||
* **Velocity**: without a pen, drawing faster draws thinner (off by default).
|
||||
* **Paint Brush (Y)**: draws a line in the stroke colour whose width follows the pressure and
|
||||
tapers, as a width profile you can reshape with the Width tool.
|
||||
* Headless: `brush.preset_list`, `brush.preset_save`, `brush.preset_rename`,
|
||||
`brush.preset_delete`, `brush.preset_export`, `brush.preset_import`; `preset`, `curve`,
|
||||
`pressure_size`, `pressure_opacity`, `taper_start`, `taper_end`, `spacing`, `jitter` and
|
||||
`as_stroke` on `draw.brush`.
|
||||
* Pen tilt isn't read yet: egui doesn't report it.
|
||||
|
||||
* **Dynamic and input text fields** (ADR 0066, M5).
|
||||
* **Properties › Text type**: Static, Dynamic or Input text, as in Animate. Dynamic and input
|
||||
fields have an **instance name**, a **line type** (single line, multiline, multiline no wrap,
|
||||
password), a fixed **box**, **Show border**, **Selectable** and **Max characters**.
|
||||
* **Scripts** set and read fields: `score_txt.text = "Score: " + n`, `appendText`, `.length`.
|
||||
* **Test Movie**: click an input field and type. Caret, selection with Shift and the pointer,
|
||||
Backspace, Delete, the arrows, Home, End, Enter in multiline fields, Tab to the next field,
|
||||
Select All, Copy, paste and input methods. Screen readers find fields as text inputs.
|
||||
* **HTML canvas export**: input fields are real text inputs over the movie (input methods, the
|
||||
on-screen keyboard and the clipboard work), and text that scripts set is drawn in the
|
||||
browser. Authored text is drawn exactly as in AniCraft.
|
||||
* **Animate files**: dynamic and input fields come across as fields, with their names, boxes,
|
||||
borders and line types (they used to become static text).
|
||||
* Every other export and the stage draw fields with their authored text, box and border.
|
||||
* `text.field`, `text.create {type}` and `control.test_movie` `text` and `select_all` events
|
||||
for agents and the CLI.
|
||||
* **Templates, SVG into the Library, and drops on the timeline** (ADR 0065, M8).
|
||||
* **File › New from Template** and the start screen's new **Templates** row: Leaderboard banner
|
||||
728 × 90, Rectangle banner 300 × 250, Social square 1080 × 1080 at 30 fps, Storyboard 16:9 (six
|
||||
labelled panels), Character turnaround and a Lip-sync mouth chart. Each has named layers and
|
||||
guides on a locked guide layer (they show while drawing and never export). They open as new,
|
||||
untitled documents with a drawing layer active.
|
||||
* **File › Save as Template** keeps the open document, with a picture, under a name and a
|
||||
category in your settings folder. It shows under "My templates" on the start screen, with
|
||||
Delete. Replacing or deleting a template asks first.
|
||||
* **SVG into the Library**: dropping an SVG on the Library, or File › Import › Import to Library,
|
||||
makes one graphic symbol named after the file, in the folder under the pointer.
|
||||
* **Drops on the timeline**: a sound dropped on a layer's frame goes onto that keyframe. An image
|
||||
or SVG goes onto that layer at that frame, in a new keyframe if needed. Either way it is one undo
|
||||
step, and a highlight shows the cell. Locked layers, folders and the camera say why they won't
|
||||
take it.
|
||||
* The timeline's layer footer keeps its Move Down button in every language.
|
||||
* Headless: `file.new_from_template`, `file.templates`, `file.save_as_template`,
|
||||
`file.delete_template`, and `file.drop` with `to: "timeline"`.
|
||||
* Exact drop positions from the desktop still wait for winit 0.31 (eframe 0.37 is still on 0.30).
|
||||
* **Accessibility, second pass** (ADR 0064, M8).
|
||||
* **Select on the stage from the keyboard.** With the stage focused (Ctrl+F6), Tab goes to
|
||||
its elements, and a ring shows the focused one on the artwork.
|
||||
* Tab, Shift+Tab and the arrows move between elements.
|
||||
* Enter or Space selects one; Shift+Enter or Shift+Space adds it to the selection or
|
||||
takes it out.
|
||||
* Esc goes back to the stage.
|
||||
* **Screen readers hear what is on the stage.** While the stage has focus, its elements are
|
||||
a list ("Rectangle", "Text: Hello", "ball · Graphic: Ball"), each with its layer, place,
|
||||
size, on-screen bounds and whether it is selected.
|
||||
* **The active layer's frames are a list too.** Each item reads "Frames 1–24: keyframe ·
|
||||
motion tween · label “walk”", and activating one moves the playhead there.
|
||||
* **The timeline from the keyboard.** On the focused timeline, the arrows move the playhead
|
||||
and the active layer, and each move is announced.
|
||||
* **The menu bar from the keyboard** on Windows and Linux.
|
||||
* Press and let go of Alt, or press F10. Then the arrows, Enter and Esc work as in other
|
||||
applications.
|
||||
* Alt+F, Alt+E and the rest open a menu directly. While Alt is held, each title shows its
|
||||
letter underlined.
|
||||
* **Follow system** is the new default theme. AniCraft switches to high contrast while
|
||||
Windows uses a contrast theme, macOS has Increase Contrast on, the Linux desktop asks for
|
||||
high contrast, or the browser prefers more contrast. Choosing Graphite or High contrast
|
||||
keeps that palette.
|
||||
* Headless: `element.select` takes `toggle`.
|
||||
|
||||
* **Test Movie in its own window, and opening documents on macOS** (ADR 0062, M8).
|
||||
* **Control › Test Movie** (Ctrl+Enter) now opens in a **window of its own** on the desktop,
|
||||
as in Animate. It is sized to the stage at 100 % (smaller if that wouldn't fit the
|
||||
screen), titled with the document's name, and opens where it was last. It takes the
|
||||
keyboard when it opens. **Esc** or **Ctrl+W (⌘W)** closes it, Ctrl+Enter restarts it in
|
||||
place, and the editor's Ctrl and Alt shortcuts still work from it.
|
||||
* In the web build, and wherever the system can't open another window, it floats inside the
|
||||
editor as before and says why. **Preferences › Test Movie** keeps it inside the editor if
|
||||
you prefer. On Wayland the desktop places the window, so it can't come back where it was
|
||||
(Preferences says so).
|
||||
* **macOS:** double-clicking a `.anicraft`, `.fla` or `.xfl` in Finder, dropping it on the
|
||||
Dock icon, or choosing Open With › AniCraft opens it, whether AniCraft is running or
|
||||
not. If there are unsaved changes it asks first, and the Dock's Quit asks to save too.
|
||||
This uses the small `fmv-macos-events` crate (MIT OR Apache-2.0), so AniCraft's own code
|
||||
stays free of `unsafe`. Still to be checked on a Mac (the list is in ADR 0062).
|
||||
* Windows and Linux already open a double-clicked document from the command line; a test
|
||||
now covers it.
|
||||
|
||||
* **Timeline polish** (ADR 0061, M1).
|
||||
* A **per-layer onion skin toggle** in each layer row (Alt-click: this layer only, again:
|
||||
every layer). Layers left out show only their playhead frame; Edit Multiple Frames still
|
||||
edits them.
|
||||
* **View as Outlines** draws a layer's artwork as hairlines in its colour **on the stage
|
||||
only**. Exports, Test Movie and the player draw it as it is (before, an outlined layer
|
||||
exported as outlines). The **colour chip** on the row's edge opens the layer colour.
|
||||
* **Onion skin inside a symbol edited in place** now also shows the parent timeline's frames
|
||||
around it, dimmed.
|
||||
* **Layer Height** 100 / 200 / 300 % (right-click menu), **Layer Properties** (double-click a
|
||||
layer's icon, Properties… or Modify › Timeline), and a **Frame View** menu with frame widths
|
||||
Tiny to Large and **Short** rows. Frame zoom and Frame View sit at the right end of the
|
||||
timeline's bottom bar, as in Animate, so the header fits at the default window size again
|
||||
(the tween-kind menu was cut off).
|
||||
* Headless: `layer.set_onion`, `layer.set_color`, `layer.set_height`, `layer.set_properties`,
|
||||
`layer.properties`. Saved in the document with defaults left out, so older files open as
|
||||
before. XFL import reads a layer's height.
|
||||
* **Animated PNG and animated WebP export** (ADR 0063, M4).
|
||||
* **File › Export › Export Animated PNG…** and **Export Animated WebP…** make full-colour
|
||||
animations with real transparency, for the web and chat apps, where a GIF has 256 colours
|
||||
and hard edges. WebP is lossless. Both are transparent by default; turn on the stage colour
|
||||
as background if you want it. Loop forever, play once, or play a set number of times.
|
||||
* Every frame is exactly what AniCraft renders. Frames that repeat the one before are stored
|
||||
once and shown longer, and each later frame stores only the rectangle that changed, so
|
||||
holds and small motions cost little.
|
||||
* Timing is exact: APNG delays are fractions of the frame rate (29.97 fps stays 29.97), and
|
||||
WebP's milliseconds never drift.
|
||||
* Both are in **Publish Settings** (Animated PNG, Animated WebP) with frames, scale, loop and
|
||||
background; in a browser they download. Headless: `file.export_apng`, `file.export_webp`
|
||||
and `anicraft-cli apng` / `webp`.
|
||||
* On the sample (48 frames, 1280 × 720) the APNG is 2.0 MB and the WebP 1.8 MB, against the
|
||||
GIF's 1.4 MB, which has only 256 colours; both take less time to make than the GIF.
|
||||
|
||||
* **Publish Settings and Publish** (ADR 0060, M8).
|
||||
* **File › Publish Settings** (Ctrl+Shift+F12) is a window that stays open while you work.
|
||||
It lists every format AniCraft exports (HTML canvas, animated GIF, video, Lottie, sprite
|
||||
sheet, PNG sequence, PNG, SVG, audio), each with a checkbox. The selected format shows
|
||||
its output name and the same options its File › Export command has. The settings are
|
||||
saved **in the document** and every change can be undone. Older files open with the HTML
|
||||
page on.
|
||||
* Output names are relative to the document's folder, and `{name}` stands for the
|
||||
document's name (`web/{name}.html`). Each name is checked as you type and the full path
|
||||
is shown below it. A name can't point outside the document's folder, and two formats
|
||||
can't write the same file.
|
||||
* **File › Publish** (Shift+F12) writes every format that is on, in the background. A
|
||||
window shows each format's progress and has a Cancel button. A single report then lists
|
||||
what each format wrote, skipped (video in a browser, audio with no sounds), left out
|
||||
(Lottie's and the HTML page's notes) or why it failed. One failing format doesn't stop
|
||||
the others.
|
||||
* Publishing over files that are already there asks once. After that, the files this
|
||||
session published are replaced without asking.
|
||||
* **Presets**: save the settings under a name, apply them to any document, or delete them.
|
||||
Presets are kept in your preferences.
|
||||
* In a browser, the files go to your downloads, as one ZIP when there are several.
|
||||
* Headless: `publish.settings_get`, `publish.settings_set` and `file.publish`, which returns
|
||||
the report. Publishing the sample in six formats takes 0.64 s.
|
||||
* **Files from the desktop, recent files and a start screen** (ADR 0059, M8).
|
||||
* **Drop files onto the window**: `.anicraft`, `.fla` and `.xfl` open (asking first over
|
||||
unsaved work); SVG drawings, PNG and JPEG images and WAV, Ogg and MP3 sounds dropped on the
|
||||
**stage** go onto the active layer at the playhead, centred where they were dropped, and
|
||||
dropped on the **Library** go into the folder under the pointer. One undo step per drop.
|
||||
A highlight shows where they will land; anything AniCraft can't take gets one clear
|
||||
status line. In the web editor too.
|
||||
* **File › Open Recent**: the last 10 documents opened or saved, with pinned favourites on
|
||||
top, missing files greyed out with Remove, and Clear Recent Files. Kept in the
|
||||
preferences (browser storage on the web).
|
||||
* **Start screen** when AniCraft starts without a document: New with HD, Full HD, square
|
||||
and vertical presets or a custom size and frame rate, Open, the sample animation, and the
|
||||
recent files with a picture of their first frame (captured on save). Esc goes back to the
|
||||
document; File › Start Screen brings it back; it can be switched off.
|
||||
* New commands for the CLI and MCP: `file.drop`, `file.open_recent`, `file.recent_list`,
|
||||
`prefs.recent_pin`, `prefs.recent_remove`, `prefs.recent_clear`; `file.import` takes
|
||||
`cx`/`cy` and `layer: "active"`.
|
||||
|
||||
* **Buttons, complete: sounds on button frames and hit-area editing** (ADR 0057, M5).
|
||||
* A sound on a button's **Over** or **Down** frame plays when the pointer goes over or
|
||||
presses the button, in Test Movie and in the HTML canvas page (Web Audio). As the SWF format
|
||||
keeps them, the Up frame's plays on leaving and the Hit frame's on letting go over it. A
|
||||
stream on a button frame plays as an event. Buttons stay out of the soundtrack: Export Audio
|
||||
and video are unchanged.
|
||||
* Editing a button in place, the timeline names its four frames **Up, Over, Down, Hit** (and
|
||||
widens them to fit while the button is open), and the stage draws the **Hit area**
|
||||
translucent over the other states.
|
||||
* Test Movie has a **Show hit areas** checkbox.
|
||||
* XFL and `.fla` import bring sounds whose file is in the package (WAV, Ogg Vorbis, MP3), with
|
||||
the sounds on frames that use them, buttons' states included; sounds kept only in Animate's
|
||||
own format are reported.
|
||||
* Headless: `control.test_movie` lists the sounds it started.
|
||||
* 9-slice guides switched off are now kept, and come back where they were when switched on.
|
||||
* **Find and Replace, and the Movie Explorer** (ADR 0058, M8).
|
||||
* **Edit › Find and Replace** (Ctrl+F) is a window that stays open while you work. It finds
|
||||
text in text fields, frame labels, layer names, instance names and frame scripts, with
|
||||
match case, whole word and regular expressions. It also finds fonts, colours (fills,
|
||||
gradient stops, strokes, text), symbols, sounds and bitmaps. It searches this scene and
|
||||
the symbols in it, or the whole document. Results show as you type.
|
||||
* Click a result, or press **Find Next** (F3) or Find Previous (Shift+F3), to go there: the
|
||||
scene, the frame and the item selected. A symbol opens in place through the instances
|
||||
that lead to it.
|
||||
* **Replace** replaces the current result and goes on to the next. **Replace All** is one
|
||||
undo step and asks first above 100 places. Replaced text is laid out again, colours keep
|
||||
their transparency, and a symbol is never put inside itself.
|
||||
* **Window › Movie Explorer** (Alt+F3) is a tab next to the Library. It shows scenes ›
|
||||
layers › keyframes › instances, text, sounds, bitmaps and scripts, each instance opening
|
||||
into its symbol, plus the Library's symbol definitions. A Show menu filters it by kind
|
||||
and a search keeps matching rows. Double-click a row to go there.
|
||||
* Both lists draw only the rows in view, so movies with 100,000 rows stay smooth.
|
||||
* Headless: `find.search`, `find.replace`, `find.goto` and `explorer.tree` (paged).
|
||||
Patterns use a linear-time engine with size limits.
|
||||
* **Colour effects, complete** (ADR 0056, M2).
|
||||
* **Properties › Colour effect**: Animate's Style menu (None, Brightness, Tint, Advanced,
|
||||
Alpha) with each style's controls: brightness −100..100 %, tint colour and amount,
|
||||
Advanced's multiplier and offset for red, green, blue and alpha. Every row says "mixed"
|
||||
when the selection differs, and a change sets only that value on all of them. Switching
|
||||
style keeps the look where it can (Advanced starts as exactly the effect before).
|
||||
* One exact colour transform behind every style: nested effects compose exactly (a
|
||||
brightness around a tint shows both), and the CPU renderer, the GPU stage (bitmaps
|
||||
included, pixel-identical), SVG (`feColorMatrix` on bitmaps), HTML canvas (bitmaps
|
||||
recoloured, no longer reported) and Lottie (baked into the colours) draw the same.
|
||||
* Classic tweens interpolate within a style (a brightness tween passes through 0) and across
|
||||
styles in the Advanced space, as Animate does.
|
||||
* Motion tweens key **Brightness**, **Tint** colour (red, green, blue) beside its amount, and
|
||||
the eight **Advanced** values; the Motion Editor lists the styles in use and adds others
|
||||
with **Add Colour Effect**. A tween has one colour effect style, as in Animate.
|
||||
* XFL/FLA import brings every `Color` style across (Advanced no longer keeps only its
|
||||
alpha); a new `colour` corpus package with goldens.
|
||||
* `element.set_color_effect` for the CLI, MCP and plug-ins; `element.set_alpha` now keeps
|
||||
the rest of the effect. Older files open unchanged, and None, Alpha and Tint effects are
|
||||
still written exactly as before.
|
||||
|
||||
* **9-slice scaling for symbols** (ADR 0055, M2).
|
||||
* **Enable guides for 9-slice scaling** on a symbol, in the Library's item properties or in
|
||||
Properties. A scaled instance then keeps its corners unscaled, stretches its edges one way
|
||||
and its centre both ways. Rounded buttons and panels resize without distorting, strokes
|
||||
keep their width, and rotation and skew apply after. Nested symbols, text and bitmaps
|
||||
inside scale normally, as in Animate. When there isn't room for the corners, they shrink
|
||||
together in proportion.
|
||||
* While the symbol is open for editing, its four guides are **dashed lines across the
|
||||
stage**. Drag them with the Selection tool (one undo step per drag), or type their
|
||||
positions in Properties.
|
||||
* Every export draws it from the same frames. SVG and Lottie get baked outlines. HTML canvas
|
||||
export scales such instances as a whole for now and says so in its report.
|
||||
* XFL and `.fla` import read `scaleGridLeft/Right/Top/Bottom`. Headless:
|
||||
`symbol.set_scale_grid {symbol?, on?, left?, right?, top?, bottom?}`.
|
||||
* **Frame scripts in ActionScript 3.0 run small logic** (ADR 0052, M6).
|
||||
* Typed variables (`var score:int = 0;` as Number, int, uint, Boolean, String or untyped),
|
||||
kept per timeline instance across its frame scripts as Animate timelines keep them;
|
||||
expressions (arithmetic, comparison, logic, joining text, `Math.min/max/abs/floor/ceil/
|
||||
round/random`, casts); `if`/`else`, `for`, `while` and `do` loops; functions with
|
||||
parameters and results, callable from any frame of the same timeline.
|
||||
* Scripts read properties of instances and timelines (`x`, `y`, `alpha`, `visible`,
|
||||
`rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`),
|
||||
remove listeners, and listen for `Event.ENTER_FRAME` and for keys on the stage
|
||||
(`KeyboardEvent.KEY_DOWN`/`KEY_UP`, `e.keyCode`); `e.target` and `e.currentTarget` work.
|
||||
* Test Movie sends your keys to the movie (it says so in its bar); `Math.random()` is
|
||||
seeded, so a headless `control.test_movie` with the same `seed` and events always plays the
|
||||
same; key events and `seed` there too.
|
||||
* An endless loop or an error stops only its script, with a line in Output, and the movie
|
||||
plays on. A script that uses a name no frame of its timeline declares doesn't run, and the
|
||||
Actions panel shows the name in place.
|
||||
* The HTML canvas export runs the same scripts, keys included, checked against Test Movie
|
||||
step by step.
|
||||
|
||||
* **Repeating bitmap fills on the GL backend** (M3): the GPU stage wrapped a repeating
|
||||
bitmap with a signed remainder, which GLSL leaves undefined for negative values, so on
|
||||
OpenGL (llvmpipe in the FreeBSD VM) the texels at the bitmap's left and top edges came out
|
||||
wrong. It now wraps without one, and a test keeps every shader free of signed remainders.
|
||||
* **Library and Properties polish** (ADR 0053, M2).
|
||||
* **Drag Library items onto the stage**: symbols and bitmaps land at the pointer on the
|
||||
active layer at the playhead, a sound goes onto that layer's keyframe; drag several at once.
|
||||
|
||||
@@ -6,13 +6,13 @@ 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.2.1"
|
||||
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]
|
||||
anicraft-geom = { path = "crates/geom" }
|
||||
@@ -26,9 +26,12 @@ 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" }
|
||||
# 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" }
|
||||
@@ -40,6 +43,8 @@ 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"
|
||||
# Lossless WebP frames for animated WebP export (pure Rust, MIT OR Apache-2.0; ADR 0063).
|
||||
image-webp = "0.2"
|
||||
# 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 +59,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 +110,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
|
||||
@@ -118,7 +143,7 @@ wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
# 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"] }
|
||||
|
||||
[build-dependencies]
|
||||
# Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets.
|
||||
|
||||
@@ -164,6 +164,7 @@ cargo run --release -p anicraft-cli -- render --sample --frame 12 --out frame12.
|
||||
cargo run --release -p anicraft-cli -- render-seq --sample --out-dir frames --scale 0.5
|
||||
cargo run --release -p anicraft-cli -- gif --sample --out animation.gif
|
||||
cargo run --release -p anicraft-cli -- commands # the command registry as JSON
|
||||
cargo run --release -p anicraft-cli -- guide --out guide # the user guide as HTML pages
|
||||
cargo run --release -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft
|
||||
cargo run --release -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout
|
||||
cargo test # all crates
|
||||
@@ -215,6 +216,11 @@ src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
|
||||
|
||||
No code below `src/` depends on egui, eframe or windowing libraries.
|
||||
|
||||
**New to AniCraft?** The [**user guide**](docs/guide/index.md) is written for artists: getting started, every
|
||||
workflow, a chapter for people [coming from Animate](docs/guide/coming-from-animate.md), and generated
|
||||
[command](docs/guide/reference/commands.md) and [shortcut](docs/guide/reference/shortcuts.md) references. It also
|
||||
opens offline from **Help › User Guide**.
|
||||
|
||||
Agent and contributor rules (clean room, the asset policy, no panics in shipped code) are in [`AGENTS.md`](AGENTS.md).
|
||||
[`docs/requirements.md`](docs/requirements.md) has the scope, [`docs/architecture.md`](docs/architecture.md) the design,
|
||||
[`docs/product-principles.md`](docs/product-principles.md) the design and user experience principles,
|
||||
@@ -267,7 +273,7 @@ RISC-V (riscv64): `anicraft-<ver>-linux-riscv64.tar.gz`, a tarball only.
|
||||
|
||||
| Build | File | Notes |
|
||||
|---|---|---|
|
||||
| Static site | `anicraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
|
||||
| Static site | `anicraft-web-<ver>.zip` | Not in the releases yet: build it yourself with `packaging/web/package.sh` ([docs/web.md](docs/web.md)), then host it on any static server |
|
||||
|
||||
## The Crafting Apps
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="5" cy="5" r="2.5" />
|
||||
<path d="M6.8 3.2 L13.5 13.5 L3.2 6.8" />
|
||||
<path d="M14 14 L17 9" />
|
||||
<path d="M14 14 L9 17" />
|
||||
<rect x="16.5" y="5.5" width="4" height="4" />
|
||||
<rect x="5.5" y="16.5" width="4" height="4" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 422 B |
@@ -0,0 +1,11 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="6" y="6" width="12" height="12" rx="1" />
|
||||
<path d="M6 2v2" />
|
||||
<path d="M2 6h2" />
|
||||
<path d="M18 2v2" />
|
||||
<path d="M20 6h2" />
|
||||
<path d="M6 20v2" />
|
||||
<path d="M2 18h2" />
|
||||
<path d="M18 20v2" />
|
||||
<path d="M20 18h2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 426 B |
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="7" width="14" height="14" rx="2" />
|
||||
<path d="M8 7 L8 21" />
|
||||
<path d="M11.5 7 L11.5 21" />
|
||||
<path d="M14.3 7 L14.3 21" />
|
||||
<path d="M17 7 L19.2 4.8" />
|
||||
<circle cx="20.3" cy="3.7" r="1.5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 403 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="9" cy="15" r="6" />
|
||||
<path d="M19 3v6" />
|
||||
<path d="M16 6h6" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 269 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="8" width="11" height="13" rx="2" />
|
||||
<path d="M19 3v6" />
|
||||
<path d="M16 6h6" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 288 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="9" cy="15" r="6" fill="currentColor" />
|
||||
<path d="M19 3v6" />
|
||||
<path d="M16 6h6" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 289 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="6" width="18" height="12" rx="2" />
|
||||
<circle cx="8" cy="12" r="1.5" />
|
||||
<path d="M12 12h5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 302 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 3 L15 9" />
|
||||
<path d="M12.5 7.5 L16.5 11.5" />
|
||||
<path d="M12.5 7.5 C10 8 9 10 10.5 12 C12 13.5 15 13.5 16.5 11.5" />
|
||||
<path d="M3 20 C4.5 16.5 6.5 16 8 17.5 C9.5 19 11.5 18.5 13 16" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 392 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M3 5 C8 3 14 8 21 5" />
|
||||
<path d="M3 19 C8 17 14 22 21 19" />
|
||||
<path d="M3 5 L3 19" />
|
||||
<path d="M21 5 L21 19" />
|
||||
<path d="M3 12 C7 10 10 13 12 12.5" />
|
||||
<path d="M12 5.4 C11 8 11.5 10 12 12.5 C12.5 15 11.5 17 12 19.6" />
|
||||
<circle cx="16" cy="13" r="2.5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 465 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
|
||||
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 339 B |
@@ -0,0 +1,15 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="1" />
|
||||
<circle cx="19" cy="12" r="1" />
|
||||
<circle cx="5" cy="12" r="1" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 312 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M5 12h14" />
|
||||
<path d="M12 5v14" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 256 B |
@@ -0,0 +1,17 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M10 11v6" />
|
||||
<path d="M14 11v6" />
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
|
||||
<path d="M3 6h18" />
|
||||
<path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 389 B |
@@ -0,0 +1,829 @@
|
||||
//! The script IR (ADR 0052): a small, typed form of statements and expressions that a
|
||||
//! compiled script runs as, evaluated by [`super::run`]. It is data, not code: the player (and
|
||||
//! the HTML canvas player, which reads the same IR as JSON) walks it with a fuel budget.
|
||||
//!
|
||||
//! Names are resolved when the script compiles: a function's own variables are numbered slots,
|
||||
//! the timeline's variables (`var` at the top of a frame script, shared by every frame script
|
||||
//! of that timeline, as ActionScript 3.0 timelines keep them per instance) are looked up by
|
||||
//! name, and instances are name paths from a base (the timeline, the stage, or the event's
|
||||
//! target). Calls to functions go by name to the timeline's functions, so a frame can call a
|
||||
//! function another frame of the same timeline declares.
|
||||
|
||||
use crate::{FrameRef, Property, Target};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A variable's type: what values written to it are coerced to (ECMA-262 §9, ActionScript 3.0's
|
||||
/// `int` and `uint` as ToInt32 and ToUint32).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Ty {
|
||||
/// Untyped (`*`, `Object`, or no annotation): keeps any value.
|
||||
#[default]
|
||||
Any,
|
||||
Number,
|
||||
Int,
|
||||
Uint,
|
||||
Boolean,
|
||||
String,
|
||||
}
|
||||
|
||||
impl Ty {
|
||||
/// The type an annotation names, when it is one scripts can hold.
|
||||
pub fn from_name(s: &str) -> Option<Ty> {
|
||||
Some(match s {
|
||||
"*" | "Object" => Ty::Any,
|
||||
"Number" => Ty::Number,
|
||||
"int" => Ty::Int,
|
||||
"uint" => Ty::Uint,
|
||||
"Boolean" => Ty::Boolean,
|
||||
"String" => Ty::String,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What a variable of this type holds before anything is written to it.
|
||||
pub fn default_value(self) -> Value {
|
||||
match self {
|
||||
Ty::Any => Value::Undefined,
|
||||
Ty::Number => Value::Num(f64::NAN),
|
||||
Ty::Int | Ty::Uint => Value::Num(0.0),
|
||||
Ty::Boolean => Value::Bool(false),
|
||||
Ty::String => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as this type.
|
||||
pub fn coerce(self, v: Value) -> Value {
|
||||
match self {
|
||||
Ty::Any => v,
|
||||
Ty::Number => Value::Num(v.number()),
|
||||
Ty::Int => Value::Num(f64::from(to_int32(v.number()))),
|
||||
Ty::Uint => Value::Num(f64::from(to_uint32(v.number()))),
|
||||
Ty::Boolean => Value::Bool(v.truthy()),
|
||||
Ty::String => match v {
|
||||
Value::Null | Value::Undefined => Value::Null,
|
||||
Value::Str(_) => v,
|
||||
other => Value::Str(other.text().into()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ToInt32 (ECMA-262 §9.5).
|
||||
pub fn to_int32(n: f64) -> i32 {
|
||||
let u = to_uint32(n);
|
||||
u as i32
|
||||
}
|
||||
|
||||
/// ToUint32 (ECMA-262 §9.6).
|
||||
pub fn to_uint32(n: f64) -> u32 {
|
||||
if !n.is_finite() {
|
||||
return 0;
|
||||
}
|
||||
let m = n.trunc().rem_euclid(4_294_967_296.0);
|
||||
// In 0 .. 2^32 by construction.
|
||||
if (0.0..4_294_967_296.0).contains(&m) { m as u32 } else { 0 }
|
||||
}
|
||||
|
||||
/// A value a script computes with: ActionScript's primitive values.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub enum Value {
|
||||
#[default]
|
||||
Undefined,
|
||||
Null,
|
||||
Bool(bool),
|
||||
Num(f64),
|
||||
Str(Arc<str>),
|
||||
}
|
||||
|
||||
impl PartialEq for Value {
|
||||
/// The same value (NaN is NaN): what state comparisons need, not ActionScript's `==`.
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
|
||||
(Value::Bool(a), Value::Bool(b)) => a == b,
|
||||
(Value::Num(a), Value::Num(b)) => a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan()),
|
||||
(Value::Str(a), Value::Str(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub fn str(s: &str) -> Value {
|
||||
Value::Str(s.into())
|
||||
}
|
||||
|
||||
/// ToNumber (ECMA-262 §9.3).
|
||||
pub fn number(&self) -> f64 {
|
||||
match self {
|
||||
Value::Num(n) => *n,
|
||||
Value::Bool(b) => f64::from(u8::from(*b)),
|
||||
Value::Null => 0.0,
|
||||
Value::Undefined => f64::NAN,
|
||||
Value::Str(s) => string_number(s),
|
||||
}
|
||||
}
|
||||
|
||||
/// ToBoolean (§9.2).
|
||||
pub fn truthy(&self) -> bool {
|
||||
match self {
|
||||
Value::Num(n) => *n != 0.0 && !n.is_nan(),
|
||||
Value::Str(s) => !s.is_empty(),
|
||||
Value::Bool(b) => *b,
|
||||
Value::Null | Value::Undefined => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// ToString (§9.8).
|
||||
pub fn text(&self) -> String {
|
||||
match self {
|
||||
Value::Num(n) => number_text(*n),
|
||||
Value::Str(s) => s.to_string(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Null => "null".into(),
|
||||
Value::Undefined => "undefined".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_str(&self) -> bool {
|
||||
matches!(self, Value::Str(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON form: `"u"`, `"null"`, `{"b": true}`, `{"n": 1.5}`, `{"s": "text"}`, `"nan"`,
|
||||
/// `{"inf": false}` (JSON has no NaN or infinities).
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum ValueRepr {
|
||||
U,
|
||||
Null,
|
||||
B(bool),
|
||||
N(f64),
|
||||
S(String),
|
||||
Nan,
|
||||
/// `true`: negative.
|
||||
Inf(bool),
|
||||
}
|
||||
|
||||
impl Serialize for Value {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
match self {
|
||||
Value::Undefined => ValueRepr::U,
|
||||
Value::Null => ValueRepr::Null,
|
||||
Value::Bool(b) => ValueRepr::B(*b),
|
||||
Value::Num(n) if n.is_nan() => ValueRepr::Nan,
|
||||
Value::Num(n) if n.is_infinite() => ValueRepr::Inf(*n < 0.0),
|
||||
Value::Num(n) => ValueRepr::N(*n),
|
||||
Value::Str(t) => ValueRepr::S(t.to_string()),
|
||||
}
|
||||
.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Value {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Value, D::Error> {
|
||||
Ok(match ValueRepr::deserialize(d)? {
|
||||
ValueRepr::U => Value::Undefined,
|
||||
ValueRepr::Null => Value::Null,
|
||||
ValueRepr::B(b) => Value::Bool(b),
|
||||
ValueRepr::N(n) => Value::Num(n),
|
||||
ValueRepr::S(t) => Value::Str(t.into()),
|
||||
ValueRepr::Nan => Value::Num(f64::NAN),
|
||||
ValueRepr::Inf(neg) => Value::Num(if neg { f64::NEG_INFINITY } else { f64::INFINITY }),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// White space and line terminators as ECMAScript trims them from numbers in text.
|
||||
fn js_space(c: char) -> bool {
|
||||
matches!(c, '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}')
|
||||
}
|
||||
|
||||
/// A number written as text (StringToNumber, ECMA-262 §9.3.1 as browsers read it: decimal,
|
||||
/// `Infinity`, and `0x`/`0o`/`0b` integers), or NaN.
|
||||
pub fn string_number(s: &str) -> f64 {
|
||||
let t = s.trim_matches(js_space);
|
||||
if t.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let radix = |p: &str, r: u32| -> f64 {
|
||||
if p.is_empty() || !p.chars().all(|c| c.is_digit(r)) {
|
||||
return f64::NAN;
|
||||
}
|
||||
p.chars().filter_map(|c| c.to_digit(r)).fold(0.0, |v, d| v * f64::from(r) + f64::from(d))
|
||||
};
|
||||
if let Some(p) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
|
||||
return radix(p, 16);
|
||||
}
|
||||
if let Some(p) = t.strip_prefix("0o").or_else(|| t.strip_prefix("0O")) {
|
||||
return radix(p, 8);
|
||||
}
|
||||
if let Some(p) = t.strip_prefix("0b").or_else(|| t.strip_prefix("0B")) {
|
||||
return radix(p, 2);
|
||||
}
|
||||
let (neg, body) = match t.as_bytes().first() {
|
||||
Some(b'-') => (true, t.get(1..).unwrap_or("")),
|
||||
Some(b'+') => (false, t.get(1..).unwrap_or("")),
|
||||
_ => (false, t),
|
||||
};
|
||||
if body == "Infinity" {
|
||||
return if neg { f64::NEG_INFINITY } else { f64::INFINITY };
|
||||
}
|
||||
// digits [. digits] [e[+-]digits], or . digits [e…]
|
||||
let b = body.as_bytes();
|
||||
let mut i = 0;
|
||||
let digits = |i: &mut usize| {
|
||||
let from = *i;
|
||||
while b.get(*i).is_some_and(u8::is_ascii_digit) {
|
||||
*i += 1;
|
||||
}
|
||||
*i - from
|
||||
};
|
||||
let int = digits(&mut i);
|
||||
let mut frac = 0;
|
||||
if b.get(i) == Some(&b'.') {
|
||||
i += 1;
|
||||
frac = digits(&mut i);
|
||||
}
|
||||
if int + frac == 0 {
|
||||
return f64::NAN;
|
||||
}
|
||||
if matches!(b.get(i), Some(b'e' | b'E')) {
|
||||
i += 1;
|
||||
if matches!(b.get(i), Some(b'+' | b'-')) {
|
||||
i += 1;
|
||||
}
|
||||
if digits(&mut i) == 0 {
|
||||
return f64::NAN;
|
||||
}
|
||||
}
|
||||
if i != b.len() {
|
||||
return f64::NAN;
|
||||
}
|
||||
let v: f64 = body.parse().unwrap_or(f64::NAN);
|
||||
if neg { -v } else { v }
|
||||
}
|
||||
|
||||
/// A number as ActionScript writes it (`Number.toString()`, ECMA-262 §9.8.1): integers without
|
||||
/// a point, exponents outside 1e-6 … 1e21.
|
||||
pub fn number_text(n: f64) -> String {
|
||||
if n.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
if n.is_infinite() {
|
||||
return if n > 0.0 { "Infinity".into() } else { "-Infinity".into() };
|
||||
}
|
||||
if n == 0.0 {
|
||||
return "0".into();
|
||||
}
|
||||
let a = n.abs();
|
||||
if (1e-6..1e21).contains(&a) {
|
||||
return format!("{n}");
|
||||
}
|
||||
let s = format!("{n:e}");
|
||||
match s.split_once('e') {
|
||||
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
|
||||
_ => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// Length in UTF-16 units, as ActionScript's `String.length` counts.
|
||||
pub fn text_len(s: &str) -> usize {
|
||||
s.encode_utf16().count()
|
||||
}
|
||||
|
||||
/// Where an instance path starts.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Base {
|
||||
/// The script's timeline.
|
||||
#[default]
|
||||
This,
|
||||
/// The stage (keyboard listeners live there).
|
||||
Stage,
|
||||
/// The event's `target`.
|
||||
Target,
|
||||
/// The event's `currentTarget`: the instance (or stage) listened to.
|
||||
Current,
|
||||
}
|
||||
|
||||
impl Base {
|
||||
pub fn is_this(&self) -> bool {
|
||||
*self == Base::This
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance a script names: a base and a name path from it (`hero_mc.arm_mc`, `parent`,
|
||||
/// `root.menu`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct Place {
|
||||
#[serde(default, skip_serializing_if = "Base::is_this")]
|
||||
pub base: Base,
|
||||
#[serde(default, skip_serializing_if = "Target::is_this")]
|
||||
pub path: Target,
|
||||
}
|
||||
|
||||
impl Place {
|
||||
pub fn this() -> Place {
|
||||
Place::default()
|
||||
}
|
||||
pub fn named(path: impl Into<String>) -> Place {
|
||||
Place { base: Base::This, path: Target::new(path) }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Place {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let base = match self.base {
|
||||
Base::This => "",
|
||||
Base::Stage => "stage",
|
||||
Base::Target => "e.target",
|
||||
Base::Current => "e.currentTarget",
|
||||
};
|
||||
match (base, self.path.is_this()) {
|
||||
("", _) => write!(f, "{}", self.path),
|
||||
(b, true) => f.write_str(b),
|
||||
(b, false) => write!(f, "{b}.{}", self.path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A property a script reads (of an instance or of the timeline).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Prop {
|
||||
X,
|
||||
Y,
|
||||
Alpha,
|
||||
Visible,
|
||||
Rotation,
|
||||
ScaleX,
|
||||
ScaleY,
|
||||
/// 1-based, as ActionScript counts frames.
|
||||
CurrentFrame,
|
||||
TotalFrames,
|
||||
/// The label at or before the playhead, or `null`.
|
||||
CurrentLabel,
|
||||
/// The pointer in the instance's own space.
|
||||
MouseX,
|
||||
MouseY,
|
||||
/// The instance name.
|
||||
Name,
|
||||
/// A text field's text, and its length in UTF-16 units (ADR 0066). Only as `field.text` and
|
||||
/// `field.length`: a bare `text` is a variable.
|
||||
Text,
|
||||
Length,
|
||||
}
|
||||
|
||||
impl Prop {
|
||||
pub fn from_name(s: &str) -> Option<Prop> {
|
||||
Some(match s {
|
||||
"x" => Prop::X,
|
||||
"y" => Prop::Y,
|
||||
"alpha" => Prop::Alpha,
|
||||
"visible" => Prop::Visible,
|
||||
"rotation" => Prop::Rotation,
|
||||
"scaleX" => Prop::ScaleX,
|
||||
"scaleY" => Prop::ScaleY,
|
||||
"currentFrame" => Prop::CurrentFrame,
|
||||
"totalFrames" => Prop::TotalFrames,
|
||||
"currentLabel" => Prop::CurrentLabel,
|
||||
"mouseX" => Prop::MouseX,
|
||||
"mouseY" => Prop::MouseY,
|
||||
"name" => Prop::Name,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// A property read or set as `instance.m`: those [`Prop::from_name`] knows, and a text
|
||||
/// field's `text` and `length`.
|
||||
pub fn from_member(s: &str) -> Option<Prop> {
|
||||
match s {
|
||||
"text" => Some(Prop::Text),
|
||||
"length" => Some(Prop::Length),
|
||||
_ => Prop::from_name(s),
|
||||
}
|
||||
}
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Prop::X => "x",
|
||||
Prop::Y => "y",
|
||||
Prop::Alpha => "alpha",
|
||||
Prop::Visible => "visible",
|
||||
Prop::Rotation => "rotation",
|
||||
Prop::ScaleX => "scaleX",
|
||||
Prop::ScaleY => "scaleY",
|
||||
Prop::CurrentFrame => "currentFrame",
|
||||
Prop::TotalFrames => "totalFrames",
|
||||
Prop::CurrentLabel => "currentLabel",
|
||||
Prop::MouseX => "mouseX",
|
||||
Prop::MouseY => "mouseY",
|
||||
Prop::Name => "name",
|
||||
Prop::Text => "text",
|
||||
Prop::Length => "length",
|
||||
}
|
||||
}
|
||||
/// The instance property a script may also set.
|
||||
pub fn settable(self) -> Option<Property> {
|
||||
Some(match self {
|
||||
Prop::X => Property::X,
|
||||
Prop::Y => Property::Y,
|
||||
Prop::Alpha => Property::Alpha,
|
||||
Prop::Visible => Property::Visible,
|
||||
Prop::Rotation => Property::Rotation,
|
||||
Prop::ScaleX => Property::ScaleX,
|
||||
Prop::ScaleY => Property::ScaleY,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UnOp {
|
||||
Neg,
|
||||
Plus,
|
||||
Not,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum BinOp {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Mod,
|
||||
Lt,
|
||||
Gt,
|
||||
Le,
|
||||
Ge,
|
||||
Eq,
|
||||
Ne,
|
||||
StrictEq,
|
||||
StrictNe,
|
||||
}
|
||||
|
||||
impl BinOp {
|
||||
pub fn from_token(s: &str) -> Option<BinOp> {
|
||||
Some(match s {
|
||||
"+" => BinOp::Add,
|
||||
"-" => BinOp::Sub,
|
||||
"*" => BinOp::Mul,
|
||||
"/" => BinOp::Div,
|
||||
"%" => BinOp::Mod,
|
||||
"<" => BinOp::Lt,
|
||||
">" => BinOp::Gt,
|
||||
"<=" => BinOp::Le,
|
||||
">=" => BinOp::Ge,
|
||||
"==" => BinOp::Eq,
|
||||
"!=" => BinOp::Ne,
|
||||
"===" => BinOp::StrictEq,
|
||||
"!==" => BinOp::StrictNe,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `Math` functions scripts may call.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MathFn {
|
||||
Min,
|
||||
Max,
|
||||
Abs,
|
||||
Floor,
|
||||
Ceil,
|
||||
Round,
|
||||
/// From the player's seeded generator: the same movie and events give the same numbers.
|
||||
Random,
|
||||
}
|
||||
|
||||
impl MathFn {
|
||||
pub fn from_name(s: &str) -> Option<MathFn> {
|
||||
Some(match s {
|
||||
"min" => MathFn::Min,
|
||||
"max" => MathFn::Max,
|
||||
"abs" => MathFn::Abs,
|
||||
"floor" => MathFn::Floor,
|
||||
"ceil" => MathFn::Ceil,
|
||||
"round" => MathFn::Round,
|
||||
"random" => MathFn::Random,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// How many arguments it takes (`None`: any number).
|
||||
pub fn arity(self) -> Option<usize> {
|
||||
match self {
|
||||
MathFn::Min | MathFn::Max => None,
|
||||
MathFn::Random => Some(0),
|
||||
MathFn::Abs | MathFn::Floor | MathFn::Ceil | MathFn::Round => Some(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What an assignment writes to.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "k", rename_all = "snake_case")]
|
||||
pub enum LValue {
|
||||
/// A function's own variable (or parameter).
|
||||
Local { i: u16 },
|
||||
/// A variable of the timeline.
|
||||
Var { n: String },
|
||||
/// An instance property.
|
||||
Prop { at: Place, p: Property },
|
||||
/// A text field's text (`field.text = …`, `field.appendText(…)` as `+=`).
|
||||
Text { at: Place },
|
||||
}
|
||||
|
||||
/// An expression.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "e", rename_all = "snake_case")]
|
||||
pub enum Expr {
|
||||
Lit { v: Value },
|
||||
Local { i: u16 },
|
||||
Var { n: String },
|
||||
Get { at: Place, p: Prop },
|
||||
/// The keyboard event's `keyCode`.
|
||||
Key,
|
||||
/// The event a listener handles, passed on to a function's event parameter.
|
||||
Event,
|
||||
Un { op: UnOp, x: Box<Expr> },
|
||||
Bin { op: BinOp, a: Box<Expr>, b: Box<Expr> },
|
||||
/// `a && b`, `a || b` (the operand's value, as ECMAScript gives it).
|
||||
And { a: Box<Expr>, b: Box<Expr> },
|
||||
Or { a: Box<Expr>, b: Box<Expr> },
|
||||
Cond { c: Box<Expr>, a: Box<Expr>, b: Box<Expr> },
|
||||
Math { f: MathFn, args: Vec<Expr> },
|
||||
/// A call to a function of the timeline, by name.
|
||||
Call { f: String, args: Vec<Expr> },
|
||||
/// Whether two names are the same instance (`e.currentTarget == btn_a`); `ne` negates.
|
||||
Same { a: Place, b: Place, ne: bool },
|
||||
/// `to = v` or `to op= v`; its value is what was written.
|
||||
Set { to: LValue, op: Option<BinOp>, v: Box<Expr> },
|
||||
/// `++` / `--` (`d` is +1 or -1); `post`: the value before.
|
||||
Step { to: LValue, d: i8, post: bool },
|
||||
/// `int(x)`, `Number(x)`, `String(x)`, `Boolean(x)`, `uint(x)`.
|
||||
Cast { t: Ty, x: Box<Expr> },
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
pub fn lit(v: Value) -> Expr {
|
||||
Expr::Lit { v }
|
||||
}
|
||||
}
|
||||
|
||||
/// A timeline method.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Method {
|
||||
Stop,
|
||||
Play,
|
||||
GotoAndPlay,
|
||||
GotoAndStop,
|
||||
NextFrame,
|
||||
PrevFrame,
|
||||
NextScene,
|
||||
PrevScene,
|
||||
}
|
||||
|
||||
impl Method {
|
||||
pub fn from_name(s: &str) -> Option<Method> {
|
||||
Some(match s {
|
||||
"stop" => Method::Stop,
|
||||
"play" => Method::Play,
|
||||
"gotoAndPlay" => Method::GotoAndPlay,
|
||||
"gotoAndStop" => Method::GotoAndStop,
|
||||
"nextFrame" => Method::NextFrame,
|
||||
"prevFrame" => Method::PrevFrame,
|
||||
"nextScene" => Method::NextScene,
|
||||
"prevScene" => Method::PrevScene,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Method::Stop => "stop",
|
||||
Method::Play => "play",
|
||||
Method::GotoAndPlay => "gotoAndPlay",
|
||||
Method::GotoAndStop => "gotoAndStop",
|
||||
Method::NextFrame => "nextFrame",
|
||||
Method::PrevFrame => "prevFrame",
|
||||
Method::NextScene => "nextScene",
|
||||
Method::PrevScene => "prevScene",
|
||||
}
|
||||
}
|
||||
/// The action it is, at a frame (go-tos) and scene.
|
||||
pub fn action(self, target: Target, frame: FrameRef, scene: Option<String>) -> crate::Action {
|
||||
use crate::Action as A;
|
||||
match self {
|
||||
Method::Stop => A::Stop { target },
|
||||
Method::Play => A::Play { target },
|
||||
Method::GotoAndPlay => A::GotoAndPlay { target, frame, scene },
|
||||
Method::GotoAndStop => A::GotoAndStop { target, frame, scene },
|
||||
Method::NextFrame => A::NextFrame { target },
|
||||
Method::PrevFrame => A::PrevFrame { target },
|
||||
Method::NextScene => A::NextScene,
|
||||
Method::PrevScene => A::PrevScene,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An event a listener waits for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ListenEvent {
|
||||
Click,
|
||||
Press,
|
||||
Release,
|
||||
Over,
|
||||
Out,
|
||||
/// `Event.ENTER_FRAME`: every frame, playing or not.
|
||||
EnterFrame,
|
||||
/// `KeyboardEvent.KEY_DOWN` / `KEY_UP` on the stage.
|
||||
KeyDown,
|
||||
KeyUp,
|
||||
}
|
||||
|
||||
impl ListenEvent {
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
ListenEvent::Click => "click",
|
||||
ListenEvent::Press => "press",
|
||||
ListenEvent::Release => "release",
|
||||
ListenEvent::Over => "over",
|
||||
ListenEvent::Out => "out",
|
||||
ListenEvent::EnterFrame => "enter_frame",
|
||||
ListenEvent::KeyDown => "key_down",
|
||||
ListenEvent::KeyUp => "key_up",
|
||||
}
|
||||
}
|
||||
/// The pointer event it is, for mouse listeners.
|
||||
pub fn mouse(self) -> Option<crate::ButtonEvent> {
|
||||
use crate::ButtonEvent as B;
|
||||
Some(match self {
|
||||
ListenEvent::Click => B::Click,
|
||||
ListenEvent::Press => B::Press,
|
||||
ListenEvent::Release => B::Release,
|
||||
ListenEvent::Over => B::Over,
|
||||
ListenEvent::Out => B::Out,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn from_mouse(b: crate::ButtonEvent) -> ListenEvent {
|
||||
use crate::ButtonEvent as B;
|
||||
match b {
|
||||
B::Click => ListenEvent::Click,
|
||||
B::Press => ListenEvent::Press,
|
||||
B::Release => ListenEvent::Release,
|
||||
B::Over => ListenEvent::Over,
|
||||
B::Out => ListenEvent::Out,
|
||||
}
|
||||
}
|
||||
pub fn is_key(self) -> bool {
|
||||
matches!(self, ListenEvent::KeyDown | ListenEvent::KeyUp)
|
||||
}
|
||||
}
|
||||
|
||||
/// The function a listener runs.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FuncRef {
|
||||
/// A function of the timeline, by name.
|
||||
Named(String),
|
||||
/// A function written in place: the index in the enclosing code's `inner` list.
|
||||
Inline(u16),
|
||||
}
|
||||
|
||||
/// A statement, with the line it starts on (for messages).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Stmt {
|
||||
pub l: u32,
|
||||
#[serde(flatten)]
|
||||
pub s: S,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "s", rename_all = "snake_case")]
|
||||
pub enum S {
|
||||
/// An expression for its effect.
|
||||
Do { x: Expr },
|
||||
If { c: Expr, a: Vec<Stmt>, b: Vec<Stmt> },
|
||||
/// `while (c)`, `for (; c; next)` (`first`: the condition is tested before the body) and
|
||||
/// `do … while (c)`.
|
||||
Loop {
|
||||
c: Option<Expr>,
|
||||
body: Vec<Stmt>,
|
||||
next: Option<Expr>,
|
||||
first: bool,
|
||||
},
|
||||
Break,
|
||||
Continue,
|
||||
Return { v: Option<Expr> },
|
||||
/// A timeline method on an instance; `args` are the frame and the scene, when it takes them.
|
||||
Act { at: Place, m: Method, args: Vec<Expr> },
|
||||
Trace { args: Vec<Expr> },
|
||||
/// `addEventListener` (`add`) or `removeEventListener`.
|
||||
Listen { at: Place, ev: ListenEvent, f: FuncRef, add: bool },
|
||||
}
|
||||
|
||||
/// A parameter.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Param {
|
||||
pub t: Ty,
|
||||
/// The value when a call leaves it out.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub d: Option<Value>,
|
||||
/// It is the event (typed `…Event`): its fields read the event the listener handles.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub ev: bool,
|
||||
}
|
||||
|
||||
/// A function: its parameters, its own variables (parameters first, each slot's type), what it
|
||||
/// returns and its body.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Function {
|
||||
pub name: String,
|
||||
pub line: u32,
|
||||
pub params: Vec<Param>,
|
||||
pub locals: Vec<Ty>,
|
||||
/// `None`: `void`, or no result.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ret: Option<Ty>,
|
||||
pub body: Vec<Stmt>,
|
||||
/// Functions written in place inside it (listeners).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub inner: Vec<Arc<Function>>,
|
||||
}
|
||||
|
||||
impl Function {
|
||||
/// Whether the function's first parameter takes an event (it can be a listener).
|
||||
pub fn takes_event(&self) -> bool {
|
||||
let required = self.params.iter().filter(|p| p.d.is_none()).count();
|
||||
required <= 1 && self.params.first().is_some_and(|p| p.ev || p.t == Ty::Any)
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyboard key codes ActionScript names (`Keyboard.LEFT`, …): the public `flash.ui.Keyboard`
|
||||
/// constants scripts compare `e.keyCode` with.
|
||||
pub fn key_code(name: &str) -> Option<u32> {
|
||||
let one = |s: &str| {
|
||||
let mut c = s.chars();
|
||||
match (c.next(), c.next()) {
|
||||
(Some(ch), None) => Some(ch),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if let Some(c) = one(name).filter(char::is_ascii_uppercase) {
|
||||
return Some(u32::from(c));
|
||||
}
|
||||
if let Some(d) = name.strip_prefix("NUMBER_").and_then(one).and_then(|c| c.to_digit(10)) {
|
||||
return Some(48 + d);
|
||||
}
|
||||
if let Some(d) = name.strip_prefix("NUMPAD_").and_then(one).and_then(|c| c.to_digit(10)) {
|
||||
return Some(96 + d);
|
||||
}
|
||||
if let Some(n) = name.strip_prefix('F').and_then(|n| n.parse::<u32>().ok()).filter(|n| (1..=15).contains(n)) {
|
||||
return Some(111 + n);
|
||||
}
|
||||
Some(match name {
|
||||
"BACKSPACE" => 8,
|
||||
"TAB" => 9,
|
||||
"ENTER" => 13,
|
||||
"SHIFT" => 16,
|
||||
"CONTROL" => 17,
|
||||
"ALTERNATE" => 18,
|
||||
"CAPS_LOCK" => 20,
|
||||
"ESCAPE" => 27,
|
||||
"SPACE" => 32,
|
||||
"PAGE_UP" => 33,
|
||||
"PAGE_DOWN" => 34,
|
||||
"END" => 35,
|
||||
"HOME" => 36,
|
||||
"LEFT" => 37,
|
||||
"UP" => 38,
|
||||
"RIGHT" => 39,
|
||||
"DOWN" => 40,
|
||||
"INSERT" => 45,
|
||||
"DELETE" => 46,
|
||||
"NUMPAD_MULTIPLY" => 106,
|
||||
"NUMPAD_ADD" => 107,
|
||||
"NUMPAD_ENTER" => 108,
|
||||
"NUMPAD_SUBTRACT" => 109,
|
||||
"NUMPAD_DECIMAL" => 110,
|
||||
"NUMPAD_DIVIDE" => 111,
|
||||
"SEMICOLON" => 186,
|
||||
"EQUAL" => 187,
|
||||
"COMMA" => 188,
|
||||
"MINUS" => 189,
|
||||
"PERIOD" => 190,
|
||||
"SLASH" => 191,
|
||||
"BACKQUOTE" => 192,
|
||||
"LEFTBRACKET" => 219,
|
||||
"BACKSLASH" => 220,
|
||||
"RIGHTBRACKET" => 221,
|
||||
"QUOTE" => 222,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1,29 +1,40 @@
|
||||
//! The ActionScript 3.0 timeline subset (ADR 0013 tier 2): a hand-written lexer and
|
||||
//! recursive-descent parser, and a lowering to the action IR.
|
||||
//! The ActionScript 3.0 subset (ADR 0013 tiers 2 and 2.5): a hand-written lexer and
|
||||
//! recursive-descent parser, a lowering to a small typed script IR ([`ir`]), and the evaluator
|
||||
//! that runs it ([`run`]) over the player.
|
||||
//!
|
||||
//! What runs is what most Animate frame scripts do: `stop()`, `play()`, `gotoAndPlay` and
|
||||
//! `gotoAndStop` by frame number or label (and scene), `nextFrame()`, `prevFrame()`,
|
||||
//! `nextScene()` and `prevScene()`, on this timeline or on instance-name paths
|
||||
//! (`hero_mc.gotoAndStop("run")`, `MovieClip(this.parent).play()`); mouse listeners
|
||||
//! (`btn.addEventListener(MouseEvent.CLICK, onClick)` with `function onClick(e:MouseEvent):void
|
||||
//! { … }` made of those calls, or an inline function); `trace` of literals and their `+`; and
|
||||
//! setting `x`, `y`, `alpha`, `visible`, `rotation`, `scaleX` and `scaleY` on named instances to
|
||||
//! values. A function declared in the script and called from it runs in place.
|
||||
//! What runs is what Animate frame scripts do: timeline control (`stop()`, `play()`,
|
||||
//! `gotoAndPlay`/`gotoAndStop` by frame or label and scene, `nextFrame()` … on this timeline or
|
||||
//! on instance-name paths); **typed variables** (`var n:int = 0;` as Number, int, uint, Boolean,
|
||||
//! String or untyped), kept per timeline instance across its frame scripts as ActionScript 3.0
|
||||
//! timelines keep them; **expressions** (arithmetic, comparison, logic, joining text,
|
||||
//! `Math.min/max/abs/floor/ceil/round/random`, `int(…)` and the other casts); `if`/`else`,
|
||||
//! `for`, `while` and `do` loops; **reading properties** of named instances and of the
|
||||
//! timeline (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`,
|
||||
//! `totalFrames`, `currentLabel`, `mouseX/Y`, `name`); setting the instance ones; functions
|
||||
//! with parameters and results, called from any frame script of the same timeline; listeners
|
||||
//! (`addEventListener` and `removeEventListener`) for mouse events on buttons and movie clips,
|
||||
//! `Event.ENTER_FRAME`, and `KeyboardEvent.KEY_DOWN`/`KEY_UP` on the stage with `e.keyCode`;
|
||||
//! `e.target` and `e.currentTarget`; and `trace`.
|
||||
//!
|
||||
//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all:
|
||||
//! nothing is ever half-run. Calls that would reach outside the movie (`navigateToURL`,
|
||||
//! `fscommand`, `ExternalInterface`) are ignored and listed as notes.
|
||||
//! Anything else is a [`Problem`] with its line and column, and the script doesn't run at all.
|
||||
//! Calls that would reach outside the movie (`navigateToURL`, `fscommand`, `ExternalInterface`)
|
||||
//! are ignored and listed as notes. A compiled script names the variables and functions it
|
||||
//! uses from other frames ([`Compiled::free`]); the timeline must declare them
|
||||
//! ([`Decls::problems`]) or the script doesn't run either.
|
||||
//!
|
||||
//! Learned from the ECMAScript 3rd edition standard (ECMA-262) and Adobe's public ActionScript
|
||||
//! 3.0 language reference; no Adobe code. Everything is bounded: source length, token count,
|
||||
//! nesting depth, inlining depth, actions, listeners and problems.
|
||||
//! nesting depth, listeners and problems here; fuel, call depth and text length when it runs.
|
||||
|
||||
pub mod ir;
|
||||
mod lex;
|
||||
mod lower;
|
||||
mod parse;
|
||||
pub mod run;
|
||||
|
||||
use crate::{Action, ButtonEvent, Target};
|
||||
use ir::{Function, Ty};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Longest script that runs, in bytes (far more than frame scripts written by hand).
|
||||
@@ -32,8 +43,6 @@ pub const MAX_RUN_BYTES: usize = 256 * 1024;
|
||||
pub const MAX_TOKENS: usize = 65_536;
|
||||
/// Deepest nesting of statements and expressions.
|
||||
pub const MAX_DEPTH: usize = 64;
|
||||
/// Deepest chain of calls to the script's own functions.
|
||||
pub const MAX_INLINE_DEPTH: usize = 16;
|
||||
/// Most listeners one script adds.
|
||||
pub const MAX_LISTENERS: usize = 64;
|
||||
/// Most problems reported for one script.
|
||||
@@ -73,53 +82,95 @@ impl std::fmt::Display for Problem {
|
||||
}
|
||||
}
|
||||
|
||||
/// A mouse listener a script adds: when `event` happens on `target` (a button or movie clip,
|
||||
/// named from the script's timeline), `actions` run on the script's timeline.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Listener {
|
||||
#[serde(default, skip_serializing_if = "Target::is_this")]
|
||||
pub target: Target,
|
||||
pub event: ButtonEvent,
|
||||
/// The function's name (`function at line 7` for an inline one): adding the same function
|
||||
/// for the same event again changes nothing, as in ActionScript.
|
||||
pub function: String,
|
||||
pub actions: Arc<Vec<Action>>,
|
||||
/// A name a script uses that it doesn't declare: a variable or function of another frame
|
||||
/// script of the same timeline.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Free {
|
||||
pub name: String,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
/// Called (a function), or read and written (a variable).
|
||||
pub call: bool,
|
||||
}
|
||||
|
||||
impl Listener {
|
||||
pub fn describe(&self) -> String {
|
||||
let body = if self.actions.is_empty() { "nothing".to_string() } else { self.actions.iter().map(Action::describe).collect::<Vec<_>>().join("; ") };
|
||||
format!("On {} ({}): {body}", self.event.key(), self.target)
|
||||
}
|
||||
}
|
||||
|
||||
/// One step of a script, in source order.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ScriptOp {
|
||||
Action(Action),
|
||||
Listen(Listener),
|
||||
}
|
||||
|
||||
impl ScriptOp {
|
||||
pub fn describe(&self) -> String {
|
||||
match self {
|
||||
ScriptOp::Action(a) => a.describe(),
|
||||
ScriptOp::Listen(l) => l.describe(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A script that runs: its steps, and what in it is ignored.
|
||||
/// A script that runs.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Compiled {
|
||||
pub ops: Vec<ScriptOp>,
|
||||
/// The top-level statements, in order.
|
||||
pub body: Vec<ir::Stmt>,
|
||||
/// Functions written in place at the top level (listeners).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub inner: Vec<Arc<Function>>,
|
||||
/// The functions it declares (the timeline's, callable from its other frames).
|
||||
pub functions: Vec<Arc<Function>>,
|
||||
/// The variables it declares (the timeline's), with their types.
|
||||
pub vars: Vec<(String, Ty)>,
|
||||
/// Names it uses from other frames of the timeline.
|
||||
pub free: Vec<Free>,
|
||||
/// Calls that are ignored (they would reach outside the movie, or do nothing here).
|
||||
pub notes: Vec<Problem>,
|
||||
/// Statements it holds, functions included (for "runs, N steps").
|
||||
pub steps: usize,
|
||||
}
|
||||
|
||||
/// Compiles ActionScript 3.0 source to the action IR, or says why it doesn't run (the
|
||||
/// problems sorted by position, at most [`MAX_PROBLEMS`]).
|
||||
/// A timeline's declarations: every function and variable its frame scripts declare (the
|
||||
/// first one of a name, in frame order, top layer first), as ActionScript 3.0 makes them
|
||||
/// members of the timeline.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Decls {
|
||||
pub functions: BTreeMap<String, Arc<Function>>,
|
||||
pub vars: BTreeMap<String, Ty>,
|
||||
}
|
||||
|
||||
impl Decls {
|
||||
/// From the timeline's compiled scripts, in frame order (top layer first within a frame).
|
||||
pub fn build<'a>(scripts: impl IntoIterator<Item = &'a Compiled>) -> Decls {
|
||||
let mut d = Decls::default();
|
||||
for c in scripts {
|
||||
for f in &c.functions {
|
||||
d.functions.entry(f.name.clone()).or_insert_with(|| f.clone());
|
||||
}
|
||||
for (n, t) in &c.vars {
|
||||
d.vars.entry(n.clone()).or_insert(*t);
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Why `c` can't run on a timeline with these declarations: a name from another frame that
|
||||
/// the timeline doesn't declare, or a declaration another frame already makes differently.
|
||||
pub fn problems(&self, c: &Compiled) -> Vec<Problem> {
|
||||
let mut out = Vec::new();
|
||||
for f in &c.free {
|
||||
let pos = Pos { line: f.line, column: f.column };
|
||||
let known = if f.call { self.functions.contains_key(&f.name) } else { self.vars.contains_key(&f.name) };
|
||||
if !known {
|
||||
let msg = match (f.call, self.functions.contains_key(&f.name) || self.vars.contains_key(&f.name)) {
|
||||
(true, true) => format!("`{}` is a variable, not a function", f.name),
|
||||
(false, true) => format!("`{}` is a function; call it, as in `{}()`", f.name, f.name),
|
||||
(true, false) => format!("`{}` isn't a function of this timeline (declare it in one of its frame scripts)", f.name),
|
||||
(false, false) => format!("`{}` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)", f.name),
|
||||
};
|
||||
out.push(Problem::at(pos, msg));
|
||||
}
|
||||
}
|
||||
for f in &c.functions {
|
||||
if self.functions.get(&f.name).is_some_and(|g| !Arc::ptr_eq(f, g) && **f != **g) {
|
||||
out.push(Problem::at(Pos { line: f.line, column: 1 }, format!("`{}` is also declared on another frame of this timeline", f.name)));
|
||||
}
|
||||
}
|
||||
for (n, t) in &c.vars {
|
||||
if self.vars.get(n).is_some_and(|u| u != t) {
|
||||
out.push(Problem::whole(format!("`{n}` is declared with another type on another frame of this timeline")));
|
||||
}
|
||||
}
|
||||
out.truncate(MAX_PROBLEMS);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Compiles ActionScript 3.0 source to the script IR, or says why it doesn't run (the problems
|
||||
/// sorted by position, at most [`MAX_PROBLEMS`]).
|
||||
pub fn compile(src: &str) -> Result<Compiled, Vec<Problem>> {
|
||||
if src.len() > MAX_RUN_BYTES {
|
||||
return Err(vec![Problem::whole(format!("the script is longer than {} KiB, the most that runs", MAX_RUN_BYTES / 1024))]);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! The parser: tokens to a syntax tree, by recursive descent (the grammar of ECMA-262 3rd
|
||||
//! edition §11–14, with ActionScript 3.0's type annotations, `import`, `as`, `is`, rest
|
||||
//! parameters and `for each`). It reads more of the language than AniCraft runs, so lowering
|
||||
//! can say exactly which construct isn't run and where; what it reads but never runs (loop
|
||||
//! headers, `switch` and `try` bodies) is skipped by balanced brackets. Bounded: nesting
|
||||
//! can say exactly which construct isn't run and where; what it reads but never runs (`for in`
|
||||
//! heads, `switch` and `try` bodies) is skipped by balanced brackets. Bounded: nesting
|
||||
//! deeper than [`super::MAX_DEPTH`] is a problem, not a stack overflow.
|
||||
|
||||
use super::lex::{Tok, Token};
|
||||
@@ -47,7 +47,9 @@ pub enum E {
|
||||
pub struct Param {
|
||||
pub name: String,
|
||||
pub pos: Pos,
|
||||
pub default: bool,
|
||||
/// The type annotation as written (`int`, `MouseEvent`, `*`), when there is one.
|
||||
pub ty: Option<(String, Pos)>,
|
||||
pub default: Option<Expr>,
|
||||
pub rest: bool,
|
||||
}
|
||||
|
||||
@@ -56,9 +58,20 @@ pub struct Func {
|
||||
pub name: Option<String>,
|
||||
pub pos: Pos,
|
||||
pub params: Vec<Param>,
|
||||
/// The result type as written (`void`, `int`), when there is one.
|
||||
pub ret: Option<(String, Pos)>,
|
||||
pub body: Vec<Stmt>,
|
||||
}
|
||||
|
||||
/// One name of a `var` (or `const`) statement.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VarDecl {
|
||||
pub name: String,
|
||||
pub pos: Pos,
|
||||
pub ty: Option<(String, Pos)>,
|
||||
pub init: Option<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Stmt {
|
||||
pub pos: Pos,
|
||||
@@ -71,8 +84,15 @@ pub enum S {
|
||||
Import,
|
||||
Function(Func),
|
||||
/// `var`, `const`.
|
||||
Var(&'static str),
|
||||
Var(&'static str, Vec<VarDecl>),
|
||||
If(Expr, Vec<Stmt>, Vec<Stmt>),
|
||||
/// `for (init; cond; update) body` (`init` a `var` statement or an expression).
|
||||
For(Option<Box<Stmt>>, Option<Expr>, Option<Expr>, Vec<Stmt>),
|
||||
While(Expr, Vec<Stmt>),
|
||||
DoWhile(Vec<Stmt>, Expr),
|
||||
/// `break` and `continue` (without a label).
|
||||
Break,
|
||||
Continue,
|
||||
Return(Option<Expr>),
|
||||
Block(Vec<Stmt>),
|
||||
Empty,
|
||||
@@ -228,12 +248,83 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `: Type` (read and dropped: `*`, `void`, `a.b.C`, `Vector.<T>`).
|
||||
fn annotation(&mut self) -> R<()> {
|
||||
/// `: Type` (`*`, `void`, `a.b.C`, `Vector.<T>`), as written.
|
||||
fn annotation(&mut self) -> R<Option<(String, Pos)>> {
|
||||
if !self.eat(":") {
|
||||
return Ok(());
|
||||
return Ok(None);
|
||||
}
|
||||
self.type_name()
|
||||
let pos = self.pos();
|
||||
let start = self.i;
|
||||
self.type_name()?;
|
||||
let text: String = self
|
||||
.toks
|
||||
.get(start..self.i)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|t| match &t.tok {
|
||||
Tok::Name(n) => n.clone(),
|
||||
Tok::Punct(p) => (*p).to_string(),
|
||||
_ => String::new(),
|
||||
})
|
||||
.collect();
|
||||
Ok(Some((text, pos)))
|
||||
}
|
||||
|
||||
/// The names of a `var` statement after the keyword.
|
||||
fn var_list(&mut self) -> R<Vec<VarDecl>> {
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let (name, pos) = self.name("a variable name")?;
|
||||
let ty = self.annotation()?;
|
||||
let init = if self.eat("=") { Some(self.assign()?) } else { None };
|
||||
out.push(VarDecl { name, pos, ty, init });
|
||||
if !self.eat(",") {
|
||||
return Ok(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `( init ; cond ; update )` after `for`, or `None` for `for … in` (read, not run).
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn for_head(&mut self) -> R<Option<(Option<Box<Stmt>>, Option<Expr>, Option<Expr>)>> {
|
||||
let open = self.i;
|
||||
self.expect("(", "after `for`")?;
|
||||
let pos = self.pos();
|
||||
let init = if self.is(";") {
|
||||
None
|
||||
} else if self.is_word("var") || self.is_word("const") {
|
||||
let w = if self.is_word("var") { "var" } else { "const" };
|
||||
self.i += 1;
|
||||
let list = self.var_list()?;
|
||||
if self.is_word("in") || list.iter().any(|d| matches!(&d.init, Some(Expr { kind: E::Binary("in", ..), .. }))) {
|
||||
self.i = open;
|
||||
self.skip_group()?;
|
||||
return Ok(None);
|
||||
}
|
||||
Some(Box::new(Stmt { pos, kind: S::Var(w, list) }))
|
||||
} else {
|
||||
let e = self.expr()?;
|
||||
if matches!(e.kind, E::Binary("in", ..)) {
|
||||
self.i = open;
|
||||
self.skip_group()?;
|
||||
return Ok(None);
|
||||
}
|
||||
Some(Box::new(Stmt { pos, kind: S::Expr(e) }))
|
||||
};
|
||||
self.expect(";", "after the loop's start")?;
|
||||
let cond = if self.is(";") { None } else { Some(self.expr()?) };
|
||||
self.expect(";", "after the loop's condition")?;
|
||||
let update = if self.is(")") { None } else { Some(self.expr()?) };
|
||||
self.expect(")", "to close the loop's head")?;
|
||||
Ok(Some((init, cond, update)))
|
||||
}
|
||||
|
||||
/// `( expr )`
|
||||
fn paren(&mut self, what: &str) -> R<Expr> {
|
||||
self.expect("(", what)?;
|
||||
let e = self.expr()?;
|
||||
self.expect(")", "after the condition")?;
|
||||
Ok(e)
|
||||
}
|
||||
|
||||
fn type_name(&mut self) -> R<()> {
|
||||
@@ -323,18 +414,9 @@ impl<'a> Parser<'a> {
|
||||
"var" | "const" => {
|
||||
let w = if w == "var" { "var" } else { "const" };
|
||||
self.i += 1;
|
||||
loop {
|
||||
self.name("a variable name")?;
|
||||
self.annotation()?;
|
||||
if self.eat("=") {
|
||||
self.assign()?;
|
||||
}
|
||||
if !self.eat(",") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let list = self.var_list()?;
|
||||
self.end()?;
|
||||
S::Var(w)
|
||||
S::Var(w, list)
|
||||
}
|
||||
"if" => {
|
||||
self.i += 1;
|
||||
@@ -353,14 +435,20 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
"for" => {
|
||||
self.i += 1;
|
||||
self.eat_word("each");
|
||||
self.skip_group()?;
|
||||
S::Other("for", self.body()?)
|
||||
if self.eat_word("each") {
|
||||
self.skip_group()?;
|
||||
S::Other("for each", self.body()?)
|
||||
} else {
|
||||
match self.for_head()? {
|
||||
Some((init, cond, update)) => S::For(init, cond, update, self.body()?),
|
||||
None => S::Other("for in", self.body()?),
|
||||
}
|
||||
}
|
||||
}
|
||||
"while" => {
|
||||
self.i += 1;
|
||||
self.skip_group()?;
|
||||
S::Other("while", self.body()?)
|
||||
let c = self.paren("after `while`")?;
|
||||
S::While(c, self.body()?)
|
||||
}
|
||||
"do" => {
|
||||
self.i += 1;
|
||||
@@ -368,9 +456,9 @@ impl<'a> Parser<'a> {
|
||||
if !self.eat_word("while") {
|
||||
return Err(self.unexpected("`while` after the `do` body"));
|
||||
}
|
||||
self.skip_group()?;
|
||||
let c = self.paren("after `while`")?;
|
||||
self.end()?;
|
||||
S::Other("do", b)
|
||||
S::DoWhile(b, c)
|
||||
}
|
||||
"with" => {
|
||||
self.i += 1;
|
||||
@@ -408,11 +496,17 @@ impl<'a> Parser<'a> {
|
||||
_ => "throw",
|
||||
};
|
||||
self.i += 1;
|
||||
if !(self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl()) {
|
||||
let bare = self.is(";") || self.is("}") || matches!(self.tok(), Tok::Eof) || self.nl();
|
||||
if !bare {
|
||||
self.expr()?;
|
||||
}
|
||||
self.end()?;
|
||||
S::Other(w, Vec::new())
|
||||
match (w, bare) {
|
||||
("break", true) => S::Break,
|
||||
("continue", true) => S::Continue,
|
||||
("throw", _) => S::Other("throw", Vec::new()),
|
||||
_ => S::Other("labelled break", Vec::new()),
|
||||
}
|
||||
}
|
||||
// Applications, not timeline scripts (ADR 0013 tier 3).
|
||||
"package" | "class" | "interface" | "namespace" | "use" | "include" | "default" => {
|
||||
@@ -454,21 +548,18 @@ impl<'a> Parser<'a> {
|
||||
loop {
|
||||
let rest = self.eat("...");
|
||||
let (n, p) = self.name("a parameter name")?;
|
||||
self.annotation()?;
|
||||
let default = self.eat("=");
|
||||
if default {
|
||||
self.assign()?;
|
||||
}
|
||||
params.push(Param { name: n, pos: p, default, rest });
|
||||
let ty = self.annotation()?;
|
||||
let default = if self.eat("=") { Some(self.assign()?) } else { None };
|
||||
params.push(Param { name: n, pos: p, ty, default, rest });
|
||||
if self.eat(")") {
|
||||
break;
|
||||
}
|
||||
self.expect(",", "or `)` after the parameter")?;
|
||||
}
|
||||
}
|
||||
self.annotation()?;
|
||||
let ret = self.annotation()?;
|
||||
let body = self.block()?;
|
||||
Ok(Func { name, pos, params, body })
|
||||
Ok(Func { name, pos, params, ret, body })
|
||||
}
|
||||
|
||||
/// An expression (`a, b` included).
|
||||
@@ -534,29 +625,44 @@ impl<'a> Parser<'a> {
|
||||
];
|
||||
let Some(ops) = LEVELS.get(level) else { return self.unary() };
|
||||
let mut lhs = self.binary(level + 1)?;
|
||||
loop {
|
||||
// Each operator in a row nests the tree one deeper: it counts toward the depth limit,
|
||||
// so what runs the tree can't recurse without bound.
|
||||
let mut chain = 0;
|
||||
let r = loop {
|
||||
let op = match self.tok() {
|
||||
Tok::Punct(p) if ops.contains(p) => ops.iter().find(|o| *o == p).copied(),
|
||||
Tok::Name(n) if ops.contains(&n.as_str()) => ops.iter().find(|o| **o == n.as_str()).copied(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(op) = op else { return Ok(lhs) };
|
||||
let Some(op) = op else { break Ok(lhs) };
|
||||
chain += 1;
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
break Err(Problem::at(self.pos(), format!("this expression has too many operators in a row (code nests at most {MAX_DEPTH} levels deep)")));
|
||||
}
|
||||
self.i += 1;
|
||||
// The right side of `as` and `is` is a type.
|
||||
let rhs = if matches!(op, "as" | "is") {
|
||||
let pos = self.pos();
|
||||
let start = self.i;
|
||||
self.type_name()?;
|
||||
if let Err(e) = self.type_name() {
|
||||
break Err(e);
|
||||
}
|
||||
let name = match self.toks.get(start..self.i) {
|
||||
Some([Token { tok: Tok::Name(n), .. }]) => n.clone(),
|
||||
_ => "*".into(),
|
||||
};
|
||||
Expr { pos, kind: E::Name(name) }
|
||||
} else {
|
||||
self.binary(level + 1)?
|
||||
match self.binary(level + 1) {
|
||||
Ok(e) => e,
|
||||
Err(e) => break Err(e),
|
||||
}
|
||||
};
|
||||
lhs = Expr { pos: lhs.pos, kind: E::Binary(op, Box::new(lhs), Box::new(rhs)) };
|
||||
}
|
||||
};
|
||||
self.depth -= chain;
|
||||
r
|
||||
}
|
||||
|
||||
fn unary(&mut self) -> R<Expr> {
|
||||
|
||||
@@ -0,0 +1,538 @@
|
||||
//! Running the script IR (ADR 0052): a small tree-walking evaluator over a
|
||||
//! [`World`] (the player, which knows the movie). It is deterministic (the only random numbers
|
||||
//! come from the world's seeded generator) and bounded: every statement and expression costs
|
||||
//! fuel, text has a length limit, calls a depth limit. When fuel runs out or something can't
|
||||
//! be done (a name that isn't there, a value of the wrong kind), the run stops where it is,
|
||||
//! as an ActionScript error stops a script, and says why; what it did before stays done.
|
||||
//!
|
||||
//! The HTML canvas player (`player.js`) mirrors this file step for step.
|
||||
|
||||
use super::ir::*;
|
||||
use crate::{FrameRef, MAX_FRAME, MAX_LABEL_CHARS, MAX_TRACE_CHARS, Property};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Fuel one frame script (or one listener call) may use.
|
||||
pub const FUEL_PER_RUN: u64 = 100_000;
|
||||
/// Deepest chain of calls.
|
||||
pub const MAX_CALL_DEPTH: usize = 16;
|
||||
/// Longest text a script makes, in UTF-16 units.
|
||||
pub const MAX_TEXT: usize = 16_384;
|
||||
|
||||
/// Why a run stopped before its end.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Stop {
|
||||
/// It used its fuel (an endless loop, most likely).
|
||||
Fuel,
|
||||
/// Something couldn't be done, at `line`.
|
||||
Error { line: u32, message: String },
|
||||
/// The world stopped everything (a per-frame budget ran out); it already said why.
|
||||
Halt,
|
||||
}
|
||||
|
||||
impl Stop {
|
||||
pub fn describe(&self) -> String {
|
||||
match self {
|
||||
Stop::Fuel => format!("it ran more than {FUEL_PER_RUN} steps (an endless loop?)"),
|
||||
Stop::Error { line, message } if *line > 0 => format!("line {line}: {message}"),
|
||||
Stop::Error { message, .. } => message.clone(),
|
||||
Stop::Halt => "the frame's budget ran out".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a running script talks to. Errors stop the run (`Err(message)`); actions that can't
|
||||
/// find their instance write a line to Output and the script goes on, as before (tier 2).
|
||||
pub trait World {
|
||||
/// A timeline action, on the instance `base` starts from (`action`'s target is the name path).
|
||||
fn act(&mut self, base: Base, action: &crate::Action) -> Result<(), Option<String>>;
|
||||
/// Reads a property.
|
||||
fn get(&mut self, at: &Place, p: Prop) -> Result<Value, String>;
|
||||
/// Sets an instance property.
|
||||
fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option<String>>;
|
||||
/// Sets a text field's text (ADR 0066).
|
||||
fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option<String>>;
|
||||
fn trace(&mut self, line: String);
|
||||
/// A timeline variable's value, and writing one (the world knows its type).
|
||||
fn read(&mut self, name: &str) -> Result<Value, String>;
|
||||
fn write(&mut self, name: &str, v: Value) -> Result<(), String>;
|
||||
/// The timeline's function by that name.
|
||||
fn function(&mut self, name: &str) -> Option<Arc<Function>>;
|
||||
/// Adds (or removes) a listener; `name` is how it is known (adding the same again does
|
||||
/// nothing).
|
||||
fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc<Function>, add: bool) -> Result<(), Option<String>>;
|
||||
/// The next number from the movie's seeded generator, in [0, 1).
|
||||
fn random(&mut self) -> f64;
|
||||
/// Whether two names are one instance.
|
||||
fn same(&mut self, a: &Place, b: &Place) -> Result<bool, String>;
|
||||
/// The keyboard event's key code.
|
||||
fn key_code(&mut self) -> Result<f64, String>;
|
||||
}
|
||||
|
||||
/// The error of a world call: `None` means the world halted (and said so).
|
||||
fn lift(line: u32, e: Option<String>) -> Stop {
|
||||
match e {
|
||||
Some(message) => Stop::Error { line, message },
|
||||
None => Stop::Halt,
|
||||
}
|
||||
}
|
||||
|
||||
enum Flow {
|
||||
Normal,
|
||||
Break,
|
||||
Continue,
|
||||
Return(Value),
|
||||
}
|
||||
|
||||
struct Frame<'f> {
|
||||
locals: Vec<Value>,
|
||||
/// Each local's type (a write coerces to it).
|
||||
types: &'f [Ty],
|
||||
inner: &'f [Arc<Function>],
|
||||
}
|
||||
|
||||
struct Vm<'w> {
|
||||
w: &'w mut dyn World,
|
||||
fuel: u64,
|
||||
depth: usize,
|
||||
line: u32,
|
||||
}
|
||||
|
||||
type R<T> = Result<T, Stop>;
|
||||
|
||||
/// Runs a frame script's top-level statements; returns the fuel used and how it ended.
|
||||
pub fn run_script(w: &mut dyn World, body: &[Stmt], inner: &[Arc<Function>], fuel: u64) -> (u64, Result<(), Stop>) {
|
||||
let mut vm = Vm { w, fuel, depth: 0, line: 0 };
|
||||
let mut frame = Frame { locals: Vec::new(), types: &[], inner };
|
||||
let r = vm.block(body, &mut frame).map(|_| ());
|
||||
(fuel - vm.fuel, r)
|
||||
}
|
||||
|
||||
/// Calls a listener's function with the event (its first parameter).
|
||||
pub fn run_listener(w: &mut dyn World, f: &Arc<Function>, fuel: u64) -> (u64, Result<(), Stop>) {
|
||||
let mut vm = Vm { w, fuel, depth: 0, line: f.line };
|
||||
let r = vm.call(f, &[Expr::Event], &mut Frame { locals: Vec::new(), types: &[], inner: &[] }).map(|_| ());
|
||||
(fuel - vm.fuel, r)
|
||||
}
|
||||
|
||||
/// JavaScript's `Math.round`: the nearest integer, halves toward +∞.
|
||||
pub fn round(x: f64) -> f64 {
|
||||
if !x.is_finite() {
|
||||
return x;
|
||||
}
|
||||
let f = x.floor();
|
||||
if x - f >= 0.5 { f + 1.0 } else { f }
|
||||
}
|
||||
|
||||
/// Math.min / Math.max: NaN wins, no arguments give ±Infinity.
|
||||
fn min_max(vals: &[f64], max: bool) -> f64 {
|
||||
let mut out = if max { f64::NEG_INFINITY } else { f64::INFINITY };
|
||||
for &v in vals {
|
||||
if v.is_nan() {
|
||||
return f64::NAN;
|
||||
}
|
||||
if (max && v > out) || (!max && v < out) {
|
||||
out = v;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `==` (ECMA-262 §11.9.3) over primitives.
|
||||
pub fn loose_eq(a: &Value, b: &Value) -> bool {
|
||||
use Value as V;
|
||||
match (a, b) {
|
||||
(V::Undefined | V::Null, V::Undefined | V::Null) => true,
|
||||
(V::Undefined | V::Null, _) | (_, V::Undefined | V::Null) => false,
|
||||
(V::Num(x), V::Num(y)) => x == y,
|
||||
(V::Str(x), V::Str(y)) => x == y,
|
||||
(V::Bool(x), V::Bool(y)) => x == y,
|
||||
(V::Num(x), V::Str(_)) => *x == b.number(),
|
||||
(V::Str(_), V::Num(y)) => a.number() == *y,
|
||||
(V::Bool(_), _) => loose_eq(&V::Num(a.number()), b),
|
||||
(_, V::Bool(_)) => loose_eq(a, &V::Num(b.number())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `===` (§11.9.6).
|
||||
pub fn strict_eq(a: &Value, b: &Value) -> bool {
|
||||
use Value as V;
|
||||
match (a, b) {
|
||||
(V::Num(x), V::Num(y)) => x == y,
|
||||
(V::Undefined, V::Undefined) | (V::Null, V::Null) => true,
|
||||
(V::Str(x), V::Str(y)) => x == y,
|
||||
(V::Bool(x), V::Bool(y)) => x == y,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `<` (§11.8.5): text by UTF-16 units, the rest as numbers; `None` when a NaN is involved.
|
||||
fn compare(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
|
||||
if let (Value::Str(x), Value::Str(y)) = (a, b) {
|
||||
return Some(x.encode_utf16().cmp(y.encode_utf16()));
|
||||
}
|
||||
a.number().partial_cmp(&b.number())
|
||||
}
|
||||
|
||||
/// Text cut to [`MAX_TRACE_CHARS`] UTF-16 units (never through a surrogate pair), with `…`.
|
||||
pub fn trace_line(s: String) -> String {
|
||||
let units: Vec<u16> = s.encode_utf16().collect();
|
||||
if units.len() <= MAX_TRACE_CHARS {
|
||||
return s;
|
||||
}
|
||||
let mut n = MAX_TRACE_CHARS;
|
||||
if units.get(n - 1).is_some_and(|u| (0xd800..0xdc00).contains(u)) {
|
||||
n -= 1;
|
||||
}
|
||||
let mut out = String::from_utf16_lossy(units.get(..n).unwrap_or(&[]));
|
||||
out.push('…');
|
||||
out
|
||||
}
|
||||
|
||||
impl Vm<'_> {
|
||||
fn tick(&mut self, n: u64) -> R<()> {
|
||||
if self.fuel < n {
|
||||
self.fuel = 0;
|
||||
return Err(Stop::Fuel);
|
||||
}
|
||||
self.fuel -= n;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn err<T>(&self, message: impl Into<String>) -> R<T> {
|
||||
Err(Stop::Error { line: self.line, message: message.into() })
|
||||
}
|
||||
|
||||
fn block(&mut self, list: &[Stmt], fr: &mut Frame<'_>) -> R<Flow> {
|
||||
for s in list {
|
||||
match self.stmt(s, fr)? {
|
||||
Flow::Normal => {}
|
||||
other => return Ok(other),
|
||||
}
|
||||
}
|
||||
Ok(Flow::Normal)
|
||||
}
|
||||
|
||||
fn stmt(&mut self, st: &Stmt, fr: &mut Frame<'_>) -> R<Flow> {
|
||||
self.tick(1)?;
|
||||
self.line = st.l;
|
||||
match &st.s {
|
||||
S::Do { x } => {
|
||||
self.expr(x, fr)?;
|
||||
}
|
||||
S::If { c, a, b } => {
|
||||
let c = self.expr(c, fr)?.truthy();
|
||||
return self.block(if c { a } else { b }, fr);
|
||||
}
|
||||
S::Loop { c, body, next, first } => {
|
||||
let mut test = *first;
|
||||
loop {
|
||||
if test && let Some(c) = c {
|
||||
self.line = st.l;
|
||||
if !self.expr(c, fr)?.truthy() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
test = true;
|
||||
// A loop with nothing in it still costs fuel.
|
||||
self.tick(1)?;
|
||||
match self.block(body, fr)? {
|
||||
Flow::Break => break,
|
||||
Flow::Return(v) => return Ok(Flow::Return(v)),
|
||||
Flow::Normal | Flow::Continue => {}
|
||||
}
|
||||
if let Some(n) = next {
|
||||
self.line = st.l;
|
||||
self.expr(n, fr)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
S::Break => return Ok(Flow::Break),
|
||||
S::Continue => return Ok(Flow::Continue),
|
||||
S::Return { v } => {
|
||||
let v = match v {
|
||||
Some(v) => self.expr(v, fr)?,
|
||||
None => Value::Undefined,
|
||||
};
|
||||
return Ok(Flow::Return(v));
|
||||
}
|
||||
S::Act { at, m, args } => {
|
||||
let frame = match args.first() {
|
||||
Some(a) => Some(self.expr(a, fr)?),
|
||||
None => None,
|
||||
};
|
||||
let scene = match args.get(1) {
|
||||
Some(a) => Some(self.expr(a, fr)?),
|
||||
None => None,
|
||||
};
|
||||
self.line = st.l;
|
||||
let frame = match frame {
|
||||
None => FrameRef::default(),
|
||||
Some(Value::Str(s)) if label_ok(&s) => FrameRef::Label(s.to_string()),
|
||||
Some(Value::Num(n)) if n.fract() == 0.0 && (1.0..=f64::from(MAX_FRAME) + 1.0).contains(&n) => FrameRef::Number(n as u32 - 1),
|
||||
Some(v) => return self.err(format!("`{}` needs a frame number from 1 or a label, not {}", m.name(), shown(&v))),
|
||||
};
|
||||
let scene = match scene {
|
||||
None | Some(Value::Null | Value::Undefined) => None,
|
||||
Some(Value::Str(s)) if label_ok(&s) => Some(s.to_string()),
|
||||
Some(v) => return self.err(format!("the scene is its name, not {}", shown(&v))),
|
||||
};
|
||||
let action = m.action(at.path.clone(), frame, scene);
|
||||
self.w.act(at.base, &action).map_err(|e| lift(st.l, e))?;
|
||||
}
|
||||
S::Trace { args } => {
|
||||
let mut parts = Vec::with_capacity(args.len());
|
||||
for a in args {
|
||||
parts.push(self.expr(a, fr)?.text());
|
||||
}
|
||||
self.w.trace(trace_line(parts.join(" ")));
|
||||
}
|
||||
S::Listen { at, ev, f, add } => {
|
||||
let func = match f {
|
||||
FuncRef::Named(n) => match self.w.function(n) {
|
||||
Some(f) => f,
|
||||
None => return self.err(format!("there's no function `{n}` on this timeline")),
|
||||
},
|
||||
FuncRef::Inline(i) => match fr.inner.get(usize::from(*i)) {
|
||||
Some(f) => f.clone(),
|
||||
None => return self.err("the listener's function is missing"),
|
||||
},
|
||||
};
|
||||
self.w.listen(at, *ev, &func, *add).map_err(|e| lift(st.l, e))?;
|
||||
}
|
||||
}
|
||||
Ok(Flow::Normal)
|
||||
}
|
||||
|
||||
fn text(&mut self, s: String) -> R<Value> {
|
||||
let n = text_len(&s);
|
||||
if n > MAX_TEXT {
|
||||
return self.err(format!("this text would be longer than {MAX_TEXT} characters"));
|
||||
}
|
||||
// Making text costs fuel for its length, so a loop building text can't run long.
|
||||
self.tick(n as u64 / 64)?;
|
||||
Ok(Value::Str(s.into()))
|
||||
}
|
||||
|
||||
fn binary(&mut self, op: BinOp, a: Value, b: Value) -> R<Value> {
|
||||
use std::cmp::Ordering::*;
|
||||
Ok(match op {
|
||||
BinOp::Add if a.is_str() || b.is_str() => return self.text(a.text() + &b.text()),
|
||||
BinOp::Add => Value::Num(a.number() + b.number()),
|
||||
BinOp::Sub => Value::Num(a.number() - b.number()),
|
||||
BinOp::Mul => Value::Num(a.number() * b.number()),
|
||||
BinOp::Div => Value::Num(a.number() / b.number()),
|
||||
BinOp::Mod => Value::Num(a.number() % b.number()),
|
||||
BinOp::Lt => Value::Bool(compare(&a, &b) == Some(Less)),
|
||||
BinOp::Gt => Value::Bool(compare(&a, &b) == Some(Greater)),
|
||||
BinOp::Le => Value::Bool(matches!(compare(&a, &b), Some(Less | Equal))),
|
||||
BinOp::Ge => Value::Bool(matches!(compare(&a, &b), Some(Greater | Equal))),
|
||||
BinOp::Eq => Value::Bool(loose_eq(&a, &b)),
|
||||
BinOp::Ne => Value::Bool(!loose_eq(&a, &b)),
|
||||
BinOp::StrictEq => Value::Bool(strict_eq(&a, &b)),
|
||||
BinOp::StrictNe => Value::Bool(!strict_eq(&a, &b)),
|
||||
})
|
||||
}
|
||||
|
||||
fn load(&mut self, to: &LValue, fr: &Frame<'_>) -> R<Value> {
|
||||
match to {
|
||||
LValue::Local { i } => Ok(fr.locals.get(usize::from(*i)).cloned().unwrap_or_default()),
|
||||
LValue::Var { n } => self.w.read(n).map_err(|message| Stop::Error { line: self.line, message }),
|
||||
LValue::Prop { at, p } => {
|
||||
let prop = match p {
|
||||
Property::X => Prop::X,
|
||||
Property::Y => Prop::Y,
|
||||
Property::Alpha => Prop::Alpha,
|
||||
Property::Visible => Prop::Visible,
|
||||
Property::Rotation => Prop::Rotation,
|
||||
Property::ScaleX => Prop::ScaleX,
|
||||
Property::ScaleY => Prop::ScaleY,
|
||||
};
|
||||
self.w.get(at, prop).map_err(|message| Stop::Error { line: self.line, message })
|
||||
}
|
||||
LValue::Text { at } => self.w.get(at, Prop::Text).map_err(|message| Stop::Error { line: self.line, message }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `v`; the value is what the place holds after (a typed variable's coercion).
|
||||
fn store(&mut self, to: &LValue, v: Value, fr: &mut Frame<'_>) -> R<Value> {
|
||||
match to {
|
||||
LValue::Local { i } => {
|
||||
let ty = fr.types.get(usize::from(*i)).copied().unwrap_or_default();
|
||||
let v = ty.coerce(v);
|
||||
if let Some(slot) = fr.locals.get_mut(usize::from(*i)) {
|
||||
*slot = v.clone();
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
LValue::Var { n } => {
|
||||
self.w.write(n, v).map_err(|message| Stop::Error { line: self.line, message })?;
|
||||
self.w.read(n).map_err(|message| Stop::Error { line: self.line, message })
|
||||
}
|
||||
LValue::Prop { at, p } => {
|
||||
let n = v.number();
|
||||
if !n.is_finite() {
|
||||
return self.err(format!("`{}` is set to a number, not {}", prop_name(*p), shown(&v)));
|
||||
}
|
||||
self.w.set(at, *p, n).map_err(|e| lift(self.line, e))?;
|
||||
Ok(v)
|
||||
}
|
||||
LValue::Text { at } => {
|
||||
if matches!(v, Value::Null | Value::Undefined) {
|
||||
return self.err(format!("`text` is set to text, not {}", v.text()));
|
||||
}
|
||||
self.w.set_text(at, v.text()).map_err(|e| lift(self.line, e))?;
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn expr(&mut self, e: &Expr, fr: &mut Frame<'_>) -> R<Value> {
|
||||
self.tick(1)?;
|
||||
Ok(match e {
|
||||
Expr::Lit { v } => v.clone(),
|
||||
Expr::Local { i } => fr.locals.get(usize::from(*i)).cloned().unwrap_or_default(),
|
||||
Expr::Var { n } => self.w.read(n).map_err(|message| Stop::Error { line: self.line, message })?,
|
||||
Expr::Get { at, p } => self.w.get(at, *p).map_err(|message| Stop::Error { line: self.line, message })?,
|
||||
Expr::Key => Value::Num(self.w.key_code().map_err(|message| Stop::Error { line: self.line, message })?),
|
||||
Expr::Event => return self.err("the event can only be passed to a function's event parameter"),
|
||||
Expr::Un { op, x } => {
|
||||
let v = self.expr(x, fr)?;
|
||||
match op {
|
||||
UnOp::Neg => Value::Num(-v.number()),
|
||||
UnOp::Plus => Value::Num(v.number()),
|
||||
UnOp::Not => Value::Bool(!v.truthy()),
|
||||
}
|
||||
}
|
||||
Expr::Bin { op, a, b } => {
|
||||
let a = self.expr(a, fr)?;
|
||||
let b = self.expr(b, fr)?;
|
||||
return self.binary(*op, a, b);
|
||||
}
|
||||
Expr::And { a, b } => {
|
||||
let a = self.expr(a, fr)?;
|
||||
if a.truthy() { self.expr(b, fr)? } else { a }
|
||||
}
|
||||
Expr::Or { a, b } => {
|
||||
let a = self.expr(a, fr)?;
|
||||
if a.truthy() { a } else { self.expr(b, fr)? }
|
||||
}
|
||||
Expr::Cond { c, a, b } => {
|
||||
if self.expr(c, fr)?.truthy() {
|
||||
self.expr(a, fr)?
|
||||
} else {
|
||||
self.expr(b, fr)?
|
||||
}
|
||||
}
|
||||
Expr::Math { f, args } => {
|
||||
let mut v = Vec::with_capacity(args.len());
|
||||
for a in args {
|
||||
v.push(self.expr(a, fr)?.number());
|
||||
}
|
||||
let x = v.first().copied().unwrap_or(f64::NAN);
|
||||
Value::Num(match f {
|
||||
MathFn::Min => min_max(&v, false),
|
||||
MathFn::Max => min_max(&v, true),
|
||||
MathFn::Abs => x.abs(),
|
||||
MathFn::Floor => x.floor(),
|
||||
MathFn::Ceil => x.ceil(),
|
||||
MathFn::Round => round(x),
|
||||
MathFn::Random => self.w.random(),
|
||||
})
|
||||
}
|
||||
Expr::Call { f, args } => {
|
||||
let Some(func) = self.w.function(f) else { return self.err(format!("there's no function `{f}` on this timeline")) };
|
||||
let line = self.line;
|
||||
let v = self.call(&func, args, fr)?;
|
||||
self.line = line;
|
||||
v
|
||||
}
|
||||
Expr::Same { a, b, ne } => {
|
||||
let same = self.w.same(a, b).map_err(|message| Stop::Error { line: self.line, message })?;
|
||||
Value::Bool(same != *ne)
|
||||
}
|
||||
Expr::Set { to, op, v } => {
|
||||
let new = match op {
|
||||
None => self.expr(v, fr)?,
|
||||
Some(op) => {
|
||||
let old = self.load(to, fr)?;
|
||||
let rhs = self.expr(v, fr)?;
|
||||
self.binary(*op, old, rhs)?
|
||||
}
|
||||
};
|
||||
return self.store(to, new, fr);
|
||||
}
|
||||
Expr::Step { to, d, post } => {
|
||||
let old = Value::Num(self.load(to, fr)?.number());
|
||||
let new = Value::Num(old.number() + f64::from(*d));
|
||||
let stored = self.store(to, new, fr)?;
|
||||
if *post { old } else { stored }
|
||||
}
|
||||
Expr::Cast { t, x } => {
|
||||
let v = self.expr(x, fr)?;
|
||||
t.coerce(v)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Calls `f` with `args` evaluated in the caller's frame.
|
||||
fn call(&mut self, f: &Arc<Function>, args: &[Expr], caller: &mut Frame<'_>) -> R<Value> {
|
||||
if self.depth >= MAX_CALL_DEPTH {
|
||||
return self.err(format!("functions call each other more than {MAX_CALL_DEPTH} deep"));
|
||||
}
|
||||
let required = f.params.iter().filter(|p| p.d.is_none()).count();
|
||||
if args.len() < required || args.len() > f.params.len() {
|
||||
let want = if required == f.params.len() { format!("{required}") } else { format!("{required} to {}", f.params.len()) };
|
||||
return self.err(format!("`{}` takes {want} argument{}, not {}", f.name, if f.params.len() == 1 { "" } else { "s" }, args.len()));
|
||||
}
|
||||
let mut locals: Vec<Value> = f.locals.iter().map(|t| t.default_value()).collect();
|
||||
for (i, p) in f.params.iter().enumerate() {
|
||||
let v = match args.get(i) {
|
||||
Some(Expr::Event) if p.ev || p.t == Ty::Any => Value::Null,
|
||||
Some(Expr::Event) => return self.err("the event can only be passed to a function's event parameter"),
|
||||
Some(a) => self.expr(a, caller)?,
|
||||
None => p.d.clone().unwrap_or_default(),
|
||||
};
|
||||
if let Some(slot) = locals.get_mut(i) {
|
||||
*slot = p.t.coerce(v);
|
||||
}
|
||||
}
|
||||
self.depth += 1;
|
||||
self.line = f.line;
|
||||
let mut fr = Frame { locals, types: &f.locals, inner: &f.inner };
|
||||
let flow = self.block(&f.body, &mut fr);
|
||||
self.depth -= 1;
|
||||
let v = match flow? {
|
||||
Flow::Return(v) => v,
|
||||
_ => Value::Undefined,
|
||||
};
|
||||
Ok(match f.ret {
|
||||
Some(t) => t.coerce(v),
|
||||
None => Value::Undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn label_ok(s: &str) -> bool {
|
||||
let n = s.chars().count();
|
||||
(1..=MAX_LABEL_CHARS).contains(&n) && !s.chars().any(char::is_control) && s.chars().any(|c| !c.is_whitespace())
|
||||
}
|
||||
|
||||
/// A value as a message names it.
|
||||
fn shown(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Str(s) => format!("\"{}\"", s.chars().take(40).collect::<String>()),
|
||||
other => other.text(),
|
||||
}
|
||||
}
|
||||
|
||||
fn prop_name(p: Property) -> &'static str {
|
||||
match p {
|
||||
Property::X => "x",
|
||||
Property::Y => "y",
|
||||
Property::Alpha => "alpha",
|
||||
Property::Visible => "visible",
|
||||
Property::Rotation => "rotation",
|
||||
Property::ScaleX => "scaleX",
|
||||
Property::ScaleY => "scaleY",
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,13 @@
|
||||
use super::ir::*;
|
||||
use super::run::{self, Stop, World};
|
||||
use super::*;
|
||||
use crate::{Action, ButtonEvent, FrameRef, Property, Target};
|
||||
use crate::{Action, FrameRef, Property};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn ok(src: &str) -> Compiled {
|
||||
compile(src).unwrap_or_else(|p| panic!("{src:?} didn't compile: {p:?}"))
|
||||
}
|
||||
|
||||
fn actions(src: &str) -> Vec<Action> {
|
||||
ok(src)
|
||||
.ops
|
||||
.into_iter()
|
||||
.map(|o| match o {
|
||||
ScriptOp::Action(a) => a,
|
||||
ScriptOp::Listen(l) => panic!("unexpected listener {l:?}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The first problem: (line, column, message).
|
||||
fn err(src: &str) -> (u32, u32, String) {
|
||||
match compile(src) {
|
||||
@@ -27,99 +19,273 @@ fn err(src: &str) -> (u32, u32, String) {
|
||||
}
|
||||
}
|
||||
|
||||
fn t(s: &str) -> Target {
|
||||
Target::new(s)
|
||||
/// A movie in miniature: one timeline with its variables and functions, instances with
|
||||
/// properties, and a log of everything the script did.
|
||||
#[derive(Default)]
|
||||
struct Mock {
|
||||
decls: Decls,
|
||||
vars: BTreeMap<String, Value>,
|
||||
props: BTreeMap<(String, &'static str), f64>,
|
||||
log: Vec<String>,
|
||||
rng: u32,
|
||||
key: Option<f64>,
|
||||
frame: u32,
|
||||
/// Text fields' text, by name.
|
||||
texts: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeline_calls_lower_to_actions() {
|
||||
let a = actions("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();");
|
||||
assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }, Action::NextFrame { target: t("") }, Action::PrevFrame { target: t("") }, Action::NextScene, Action::PrevScene]);
|
||||
// Frames are 1-based in ActionScript, 0-based in the IR; strings are labels.
|
||||
let a = actions(r#"gotoAndStop(1); gotoAndPlay("run"); gotoAndPlay(12, "Scene 2"); gotoAndStop('end', null); gotoAndStop(2 + 3);"#);
|
||||
assert_eq!(
|
||||
a,
|
||||
vec![
|
||||
Action::GotoAndStop { target: t(""), frame: FrameRef::Number(0), scene: None },
|
||||
Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("run".into()), scene: None },
|
||||
Action::GotoAndPlay { target: t(""), frame: FrameRef::Number(11), scene: Some("Scene 2".into()) },
|
||||
Action::GotoAndStop { target: t(""), frame: FrameRef::Label("end".into()), scene: None },
|
||||
Action::GotoAndStop { target: t(""), frame: FrameRef::Number(4), scene: None },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_paths_become_targets() {
|
||||
let a = actions("hero_mc.gotoAndStop(\"run\");\nthis.hero_mc.arm_mc.play();\nMovieClip(parent).stop();\nMovieClip(this.parent.parent).nextFrame();\nMovieClip(root).menu.play();\n(root as MovieClip).stop();\nhero_mc.root.stop();\nObject(parent).door.prevFrame();");
|
||||
let targets: Vec<String> = a.iter().map(|a| a.target().map(|t| t.0.clone()).unwrap_or_default()).collect();
|
||||
assert_eq!(targets, ["hero_mc", "hero_mc.arm_mc", "parent", "parent.parent", "root.menu", "root", "root", "parent.door"]);
|
||||
assert!(a.iter().all(|x| x.check().is_ok()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_are_set_to_values() {
|
||||
let a = actions("hero_mc.x = 100;\nhero_mc.y = -20.5;\nhero_mc.alpha = .5;\nhero_mc.visible = false;\ndoor.rotation = 45;\ndoor.scaleX = 2; door.scaleY = 1.5\nalpha = 0.25;");
|
||||
assert_eq!(
|
||||
a,
|
||||
vec![
|
||||
Action::SetProperty { target: t("hero_mc"), property: Property::X, value: 100.0 },
|
||||
Action::SetProperty { target: t("hero_mc"), property: Property::Y, value: -20.5 },
|
||||
Action::SetProperty { target: t("hero_mc"), property: Property::Alpha, value: 0.5 },
|
||||
Action::SetProperty { target: t("hero_mc"), property: Property::Visible, value: 0.0 },
|
||||
Action::SetProperty { target: t("door"), property: Property::Rotation, value: 45.0 },
|
||||
Action::SetProperty { target: t("door"), property: Property::ScaleX, value: 2.0 },
|
||||
Action::SetProperty { target: t("door"), property: Property::ScaleY, value: 1.5 },
|
||||
Action::SetProperty { target: t(""), property: Property::Alpha, value: 0.25 },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_writes_literals_and_their_sums_as_actionscript_does() {
|
||||
let msgs: Vec<String> = actions(r#"trace("hello"); trace('a' + 1 + 2); trace(1 + 2 + "a"); trace(0.1, true, null, undefined); trace(1e21, 1e-7, -0, 5 / 2, 7 % 4); trace(); trace("tab\there é \x41");"#)
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
Action::Trace { message } => message,
|
||||
other => panic!("{other:?}"),
|
||||
impl World for Mock {
|
||||
fn act(&mut self, base: Base, a: &Action) -> Result<(), Option<String>> {
|
||||
if let Action::GotoAndStop { frame: FrameRef::Number(n), .. } = a {
|
||||
self.frame = *n;
|
||||
}
|
||||
self.log.push(format!("{base:?} {}", a.describe()));
|
||||
Ok(())
|
||||
}
|
||||
fn get(&mut self, at: &Place, p: Prop) -> Result<Value, String> {
|
||||
if at.path.0 == "ghost" {
|
||||
return Err("no instance named “ghost” here".into());
|
||||
}
|
||||
Ok(match p {
|
||||
Prop::CurrentFrame => Value::Num(f64::from(self.frame + 1)),
|
||||
Prop::Name => Value::str(&at.to_string()),
|
||||
Prop::Visible => Value::Bool(true),
|
||||
Prop::Text | Prop::Length => {
|
||||
let t = self.texts.get(&at.path.0).ok_or_else(|| format!("“{at}” isn't a text field"))?;
|
||||
if p == Prop::Text { Value::str(t) } else { Value::Num(text_len(t) as f64) }
|
||||
}
|
||||
p => Value::Num(self.props.get(&(at.path.0.clone(), p.name())).copied().unwrap_or(0.0)),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(msgs, ["hello", "a12", "3a", "0.1 true null undefined", "1e+21 1e-7 0 2.5 3", "", "tab\there é A"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_lower_to_handlers_with_their_bodies() {
|
||||
let src = "import flash.events.MouseEvent;\n\nstop();\nplay_btn.addEventListener(MouseEvent.CLICK, onPlay);\n\nfunction onPlay(e:MouseEvent):void {\n\tgotoAndPlay(\"walk\"); // on\n\ttrace(\"go\");\n}\nmenu.btn.addEventListener(MouseEvent.ROLL_OVER, function (event:MouseEvent):void { MovieClip(event.currentTarget).gotoAndStop(2); });\naddEventListener(\"mouseDown\", onPlay);";
|
||||
let c = ok(src);
|
||||
assert_eq!(c.ops.len(), 4);
|
||||
assert_eq!(c.ops[0], ScriptOp::Action(Action::Stop { target: t("") }));
|
||||
let ScriptOp::Listen(l) = &c.ops[1] else { panic!("{:?}", c.ops[1]) };
|
||||
assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("play_btn", ButtonEvent::Click, "onPlay"));
|
||||
assert_eq!(*l.actions, vec![Action::GotoAndPlay { target: t(""), frame: FrameRef::Label("walk".into()), scene: None }, Action::Trace { message: "go".into() }]);
|
||||
let ScriptOp::Listen(l) = &c.ops[2] else { panic!() };
|
||||
// `currentTarget` is the instance listened to, named from the script's timeline.
|
||||
assert_eq!((l.target.0.as_str(), l.event, l.function.as_str()), ("menu.btn", ButtonEvent::Over, "function at line 10"));
|
||||
assert_eq!(*l.actions, vec![Action::GotoAndStop { target: t("menu.btn"), frame: FrameRef::Number(1), scene: None }]);
|
||||
let ScriptOp::Listen(l) = &c.ops[3] else { panic!() };
|
||||
assert_eq!((l.target.is_this(), l.event), (true, ButtonEvent::Press));
|
||||
assert!(l.describe().starts_with("On press (this): Go to “walk” and play"), "{}", l.describe());
|
||||
for (k, e) in [("MOUSE_UP", ButtonEvent::Release), ("ROLL_OUT", ButtonEvent::Out), ("MOUSE_OVER", ButtonEvent::Over), ("MOUSE_OUT", ButtonEvent::Out)] {
|
||||
let c = ok(&format!("b.addEventListener(MouseEvent.{k}, f, false, 0, true); function f(e) {{}}"));
|
||||
assert!(matches!(&c.ops[0], ScriptOp::Listen(l) if l.event == e), "{k}");
|
||||
}
|
||||
fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option<String>> {
|
||||
let name = Prop::from_name(match p {
|
||||
Property::X => "x",
|
||||
Property::Y => "y",
|
||||
Property::Alpha => "alpha",
|
||||
Property::Visible => "visible",
|
||||
Property::Rotation => "rotation",
|
||||
Property::ScaleX => "scaleX",
|
||||
Property::ScaleY => "scaleY",
|
||||
})
|
||||
.map_or("?", Prop::name);
|
||||
self.props.insert((at.path.0.clone(), name), v);
|
||||
Ok(())
|
||||
}
|
||||
fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option<String>> {
|
||||
if !self.texts.contains_key(&at.path.0) {
|
||||
return Err(Some(format!("“{at}” isn't a text field")));
|
||||
}
|
||||
self.log.push(format!("text {at} = {text}"));
|
||||
self.texts.insert(at.path.0.clone(), text);
|
||||
Ok(())
|
||||
}
|
||||
fn trace(&mut self, line: String) {
|
||||
self.log.push(line);
|
||||
}
|
||||
fn read(&mut self, name: &str) -> Result<Value, String> {
|
||||
match self.vars.get(name) {
|
||||
Some(v) => Ok(v.clone()),
|
||||
None => self.decls.vars.get(name).map(|t| t.default_value()).ok_or_else(|| format!("`{name}` isn't defined")),
|
||||
}
|
||||
}
|
||||
fn write(&mut self, name: &str, v: Value) -> Result<(), String> {
|
||||
let t = *self.decls.vars.get(name).ok_or_else(|| format!("`{name}` isn't defined"))?;
|
||||
self.vars.insert(name.to_string(), t.coerce(v));
|
||||
Ok(())
|
||||
}
|
||||
fn function(&mut self, name: &str) -> Option<Arc<Function>> {
|
||||
self.decls.functions.get(name).cloned()
|
||||
}
|
||||
fn listen(&mut self, at: &Place, ev: ListenEvent, f: &Arc<Function>, add: bool) -> Result<(), Option<String>> {
|
||||
self.log.push(format!("{} {} {at} {}", if add { "listen" } else { "unlisten" }, ev.key(), f.name));
|
||||
Ok(())
|
||||
}
|
||||
fn random(&mut self) -> f64 {
|
||||
self.rng = self.rng.wrapping_mul(1_103_515_245).wrapping_add(12345);
|
||||
f64::from(self.rng >> 8) / f64::from(1u32 << 24)
|
||||
}
|
||||
fn same(&mut self, a: &Place, b: &Place) -> Result<bool, String> {
|
||||
Ok(a == b)
|
||||
}
|
||||
fn key_code(&mut self) -> Result<f64, String> {
|
||||
self.key.ok_or_else(|| "there's no keyboard event here".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Compiles and runs `src` on a fresh timeline; the log and how the run ended.
|
||||
fn exec(src: &str) -> (Vec<String>, Result<(), Stop>, Mock) {
|
||||
let c = ok(src);
|
||||
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
|
||||
assert!(m.decls.problems(&c).is_empty(), "{:?}", m.decls.problems(&c));
|
||||
let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
|
||||
(std::mem::take(&mut m.log), r, m)
|
||||
}
|
||||
|
||||
fn lines(src: &str) -> Vec<String> {
|
||||
let (log, r, _) = exec(src);
|
||||
assert_eq!(r, Ok(()), "{src}: {log:?}");
|
||||
log
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_functions_run_where_they_are_called() {
|
||||
let a = actions("function go(n:int = 1):void { gotoAndStop(3); return; trace(\"never\"); }\ngo();\nfunction twice() { go(); go(); }\ntwice();");
|
||||
assert_eq!(a.len(), 3, "{a:?}");
|
||||
assert!(a.iter().all(|x| matches!(x, Action::GotoAndStop { frame: FrameRef::Number(2), .. })));
|
||||
fn timeline_calls_run_as_actions() {
|
||||
let a = lines("stop();\nplay()\nthis.nextFrame();\nprevFrame();\nnextScene(); prevScene();\ngotoAndStop(1); gotoAndPlay(\"run\"); gotoAndPlay(12, \"Scene 2\"); gotoAndStop('end', null); gotoAndStop(2 + 3);");
|
||||
assert_eq!(a, ["This Stop", "This Play", "This Next frame", "This Previous frame", "This Next scene", "This Previous scene", "This Go to frame 1 and stop", "This Go to “run” and play", "This Go to frame 12 in “Scene 2” and play", "This Go to “end” and stop", "This Go to frame 5 and stop"]);
|
||||
let a = lines("hero_mc.gotoAndStop(\"run\");\nthis.hero_mc.arm_mc.play();\nMovieClip(parent).stop();\nMovieClip(this.parent.parent).nextFrame();\nMovieClip(root).menu.play();\n(root as MovieClip).stop();\nhero_mc.root.stop();\nObject(parent).door.prevFrame();");
|
||||
assert_eq!(a, ["This Go to “run” and stop (hero_mc)", "This Play (hero_mc.arm_mc)", "This Stop (parent)", "This Next frame (parent.parent)", "This Play (root.menu)", "This Stop (root)", "This Stop (root)", "This Previous frame (parent.door)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_variables_coerce_as_actionscript_does() {
|
||||
let a = lines(
|
||||
"var n:int = 7.9; var u:uint = -1; var num:Number = \"2.5\"; var b:Boolean = \"no\"; var s:String = 12; var z:String; var any = \"x\";\n\
|
||||
var big:int = 2147483647; big = big + 1;\n\
|
||||
var nan:Number; var none:int;\n\
|
||||
trace(n, u, num, b, s, z, any, big, nan, none);\n\
|
||||
n += 0.7; n++; ++n; trace(n, n++ + n, --n);",
|
||||
);
|
||||
assert_eq!(a, ["7 4294967295 2.5 true 12 null x -2147483648 NaN 0", "9 19 9"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expressions_follow_ecmascript() {
|
||||
let a = lines(
|
||||
r#"trace(1 + 2 * 3 - 4 / 8, 7 % 3, -7 % 3, 1 / 0, -1 / 0, 0 / 0);
|
||||
trace("a" + 1 + 2, 1 + 2 + "a", "5" * "2", "x" - 1, true + 1, null + 1, undefined + 1);
|
||||
trace(1 < 2, "b" < "a", "10" < "9", 10 < "9", NaN < 1, NaN >= 1, 2 >= 2);
|
||||
trace(1 == "1", 1 === "1", null == undefined, null === undefined, 0 == false, "" == 0, NaN == NaN, "a" != "b");
|
||||
trace(0 || "x", 1 && "y", !0, !"", true ? "t" : "f", null || undefined);
|
||||
trace(int("12px"), int(" 0x1F "), Number(""), Number("1e3"), String(null), Boolean("false"), uint(-2), Number("Infinity"), Number("infinity"));
|
||||
trace(Math.min(3, 1, 2), Math.max(), Math.min(1, NaN), Math.abs(-4.5), Math.floor(-1.5), Math.ceil(1.2), Math.round(2.5), Math.round(-2.5), Math.round(-0.4), Math.PI > 3.14);"#,
|
||||
);
|
||||
assert_eq!(
|
||||
a,
|
||||
[
|
||||
"6.5 1 -1 Infinity -Infinity NaN",
|
||||
"a12 3a 10 NaN 2 1 NaN",
|
||||
"true false true false false false true",
|
||||
"true false true false true true false true",
|
||||
"x y true true t undefined",
|
||||
"0 31 0 1000 null true 4294967294 Infinity NaN",
|
||||
"1 -Infinity NaN 4.5 -2 2 3 -2 0 true",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn if_else_and_loops_run_with_break_and_continue() {
|
||||
let a = lines(
|
||||
"var total:int = 0;\n\
|
||||
for (var i:int = 0; i < 10; i++) { if (i == 2) continue; if (i > 5) break; total += i; }\n\
|
||||
trace(total, i);\n\
|
||||
var k:int = 3; while (k > 0) { k--; } trace(k);\n\
|
||||
do { k++; } while (k < 2); trace(k);\n\
|
||||
do { k = 100; } while (false); trace(k);\n\
|
||||
if (k > 50) trace(\"big\"); else if (k > 5) trace(\"mid\"); else trace(\"small\");\n\
|
||||
for (;;) { break; } trace(\"out\");",
|
||||
);
|
||||
assert_eq!(a, ["13 6", "0", "2", "100", "big", "out"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn functions_take_parameters_return_values_and_recurse() {
|
||||
let a = lines(
|
||||
"function add(a:int, b:int = 10):int { return a + b; }\n\
|
||||
function fact(n:Number):Number { if (n <= 1) return 1; return n * fact(n - 1); }\n\
|
||||
function hello(who:String):void { trace(\"hi \" + who); return; trace(\"never\"); }\n\
|
||||
function untyped(x) { return x; }\n\
|
||||
trace(add(1, 2), add(5), add(1.9, 0.9), fact(5), untyped(\"u\"), hello(\"you\"));\n\
|
||||
function loopy():int { var s:int; for (var j:int = 0; j < 4; j++) s += j; return s; } trace(loopy(), loopy());",
|
||||
);
|
||||
assert_eq!(a, ["hi you", "3 15 1 120 u undefined", "6 6"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_are_read_and_set() {
|
||||
let (log, r, m) = exec("hero.x = 10; hero.x += 5; hero.alpha = .5; trace(hero.x, hero.alpha, hero.name, currentFrame, this.currentFrame, hero.visible);\ngotoAndStop(4); trace(currentFrame);\nhero.rotation = hero.x * 2;");
|
||||
assert_eq!(r, Ok(()));
|
||||
assert_eq!(log, ["15 0.5 hero 1 1 true", "This Go to frame 4 and stop", "4"]);
|
||||
assert_eq!(m.props.get(&("hero".into(), "rotation")), Some(&30.0));
|
||||
// Reading an instance that isn't there stops the script there.
|
||||
let (log, r, _) = exec("trace(\"a\");\ntrace(ghost.x);\ntrace(\"b\");");
|
||||
assert_eq!(log, ["a"]);
|
||||
assert_eq!(r, Err(Stop::Error { line: 2, message: "no instance named “ghost” here".into() }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_name_their_events_and_functions() {
|
||||
let c = ok("import flash.events.*;\nbtn.addEventListener(MouseEvent.CLICK, go);\naddEventListener(Event.ENTER_FRAME, tick);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { if (e.keyCode == Keyboard.LEFT) trace(\"left\"); });\nbtn.removeEventListener(MouseEvent.CLICK, go);\nfunction go(e:MouseEvent):void { MovieClip(e.currentTarget).gotoAndStop(2); trace(e.target.name); }\nfunction tick(e:Event):void {}\nhero.addEventListener(\"mouseOver\", go, false, 0, true);");
|
||||
assert_eq!(c.inner.len(), 1);
|
||||
assert_eq!(c.functions.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["go", "tick"]);
|
||||
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
|
||||
let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
|
||||
assert_eq!(r, Ok(()));
|
||||
assert_eq!(m.log, ["listen click btn go", "listen enter_frame this tick", "listen key_down stage function at line 4, column 48", "unlisten click btn go", "listen over hero go"]);
|
||||
// The listener functions: the event's key code, target and current target.
|
||||
m.log.clear();
|
||||
m.key = Some(37.0);
|
||||
let key = c.inner[0].clone();
|
||||
assert_eq!(run::run_listener(&mut m, &key, 1000).1, Ok(()));
|
||||
let go = c.functions[0].clone();
|
||||
assert_eq!(run::run_listener(&mut m, &go, 1000).1, Ok(()));
|
||||
assert_eq!(m.log, ["left", "Current Go to frame 2 and stop", "e.target"]);
|
||||
// Keyboard listeners belong on the stage; elsewhere they are ignored and noted.
|
||||
let c = ok("addEventListener(KeyboardEvent.KEY_UP, f); function f(e) {}");
|
||||
assert!(c.body.is_empty() && c.notes[0].message.starts_with("keys go to the stage"), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_from_other_frames_link_through_the_timeline() {
|
||||
let frame1 = ok("var score:int = 0;\nfunction addPoints(n:int):void { score += n; }\nfunction shout():String { return \"score \" + score; }");
|
||||
let frame5 = ok("addPoints(3);\nscore = score * 2;\ntrace(shout(), lives);");
|
||||
assert_eq!(frame5.free.iter().map(|f| (f.name.as_str(), f.call)).collect::<Vec<_>>(), [("addPoints", true), ("score", false), ("shout", true), ("lives", false)]);
|
||||
let d = Decls::build([&frame1, &frame5]);
|
||||
let p = d.problems(&frame5);
|
||||
assert_eq!(p.len(), 1, "{p:?}");
|
||||
assert_eq!((p[0].line, p[0].column), (3, 16));
|
||||
assert!(p[0].message.starts_with("`lives` isn't a variable of this timeline"), "{}", p[0].message);
|
||||
let ok5 = ok("addPoints(3);\nscore = score * 2;\ntrace(shout());");
|
||||
let d = Decls::build([&frame1, &ok5]);
|
||||
assert!(d.problems(&ok5).is_empty() && d.problems(&frame1).is_empty());
|
||||
let mut m = Mock { decls: d, ..Mock::default() };
|
||||
for c in [&frame1, &ok5] {
|
||||
assert_eq!(run::run_script(&mut m, &c.body, &c.inner, 10_000).1, Ok(()));
|
||||
}
|
||||
assert_eq!(m.log, ["score 6"]);
|
||||
// A function declared on two frames, or a variable with two types, is a problem.
|
||||
let again = ok("function shout():String { return \"again\"; }\nvar score:String;");
|
||||
let d = Decls::build([&frame1, &again]);
|
||||
assert_eq!(d.problems(&again).len(), 2, "{:?}", d.problems(&again));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fuel_stops_an_endless_loop_cleanly() {
|
||||
let c = ok("trace(\"before\");\nwhile (true) {}\ntrace(\"after\");");
|
||||
let mut m = Mock::default();
|
||||
let (used, r) = run::run_script(&mut m, &c.body, &c.inner, 5_000);
|
||||
assert_eq!((used, r), (5_000, Err(Stop::Fuel)));
|
||||
assert_eq!(m.log, ["before"]);
|
||||
// Recursion is bounded by depth, text by length, and both stop the run.
|
||||
let (_, r, _) = exec("function f(n:int):int { return f(n + 1); } f(0);");
|
||||
assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("more than 16 deep")), "{r:?}");
|
||||
let (_, r, _) = exec("var s:String = \"x\"; while (true) s = s + s;");
|
||||
assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("longer than 16384")), "{r:?}");
|
||||
// Building text costs fuel for its length.
|
||||
let c = ok("var s:String = \"\"; for (var i:int = 0; i < 100000; i++) s = s + \"ab\";");
|
||||
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
|
||||
assert_eq!(run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN).1, Err(Stop::Fuel));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_comes_from_the_world() {
|
||||
let a = lines("var r:Number = Math.random(); trace(r >= 0 && r < 1, Math.floor(Math.random() * 6) + 1 <= 6);");
|
||||
assert_eq!(a, ["true true"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_outside_the_movie_are_ignored_and_noted() {
|
||||
let c = ok("navigateToURL(new URLRequest(\"https://example.com\"), \"_blank\");\nflash.net.navigateToURL(x);\nExternalInterface.call(\"f\");\nfscommand(\"quit\");\nbtn.buttonMode = true;\nstop();");
|
||||
assert_eq!(c.ops, vec![ScriptOp::Action(Action::Stop { target: t("") })]);
|
||||
assert_eq!(c.body.len(), 1);
|
||||
let lines: Vec<u32> = c.notes.iter().map(|n| n.line).collect();
|
||||
assert_eq!(lines, [1, 2, 3, 4, 5]);
|
||||
assert!(c.notes[0].message.contains("navigateToURL") && c.notes[0].message.contains("ignored"), "{:?}", c.notes);
|
||||
@@ -127,50 +293,52 @@ fn calls_outside_the_movie_are_ignored_and_noted() {
|
||||
|
||||
#[test]
|
||||
fn comments_white_space_and_semicolons_are_read_as_actionscript_does() {
|
||||
// Line and block comments, CR LF line ends, no semicolons, a BOM, empty statements.
|
||||
let a = actions("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\"");
|
||||
assert_eq!(a, vec![Action::Stop { target: t("") }, Action::Play { target: t("") }]);
|
||||
let a = lines("\u{feff}/* a\r\n block */ stop() // done\r\n;;\r\n{ play() }\r\n\"use strict\"");
|
||||
assert_eq!(a, ["This Stop", "This Play"]);
|
||||
assert_eq!(err("stop() play()"), (1, 8, "expected `;` or a new line, found `play`".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_problem_says_where_it_is() {
|
||||
let cases: &[(&str, u32, u32, &str)] = &[
|
||||
("stop();\nif (x) { play(); }", 2, 1, "`if` statements aren't supported yet"),
|
||||
("var n:int = 0;", 1, 1, "variables (`var`) aren't supported yet"),
|
||||
(" for (var i = 0; i < 3; i++) {}", 1, 3, "`for` loops aren't supported yet"),
|
||||
("while (true) stop();", 1, 1, "`while` loops aren't supported yet"),
|
||||
(" for each (var v in list) {}", 1, 3, "`for each` loops aren't supported yet"),
|
||||
("for (var k in o) {}", 1, 1, "`for in` loops aren't supported yet"),
|
||||
("switch (x) { case 1: stop(); }", 1, 1, "`switch` statements aren't supported yet"),
|
||||
("hero.x += 5;", 1, 1, "`+=` reads a value first"),
|
||||
("var a:Array = [];", 1, 7, "variables of type `Array` aren't supported yet"),
|
||||
("var x:int = 1;", 1, 5, "`x` is already a name of the timeline"),
|
||||
("hero.width = 5;", 1, 1, "setting `width` isn't supported yet"),
|
||||
("score = 5;", 1, 1, "setting `score` isn't supported: variables"),
|
||||
("foo();", 1, 1, "`foo` isn't declared in this frame script"),
|
||||
("currentFrame = 5;", 1, 1, "`currentFrame` can only be read"),
|
||||
("hero.addChild(x);", 1, 1, "calling `addChild` isn't supported"),
|
||||
("gotoAndStop(0);", 1, 13, "a frame number is a whole number from 1"),
|
||||
("gotoAndStop(1.5);", 1, 13, "a frame number is a whole number"),
|
||||
("gotoAndStop(frame);", 1, 13, "reading `frame` isn't supported"),
|
||||
("gotoAndStop();", 1, 1, "`gotoAndStop` takes a frame"),
|
||||
("stop(1);", 1, 1, "`stop()` takes no arguments"),
|
||||
("hero.nextScene();", 1, 1, "call `nextScene()` in the main timeline's own script"),
|
||||
("trace(hero.x);", 1, 7, "reading properties isn't supported"),
|
||||
("trace([1]);", 1, 7, "only values written out"),
|
||||
("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "the stage isn't supported"),
|
||||
("b.addEventListener(Event.ENTER_FRAME, f); function f(e) {}", 1, 20, "listening for Event.ENTER_FRAME isn't supported yet"),
|
||||
("b.addEventListener(MouseEvent.CLICK, nope);", 1, 38, "`nope` isn't a function declared"),
|
||||
("trace(hero.width);", 1, 7, "reading `width` isn't supported yet"),
|
||||
("trace([1]);", 1, 7, "arrays aren't supported yet"),
|
||||
("trace(stage.stageWidth);", 1, 7, "`stage.stageWidth` isn't supported yet"),
|
||||
("stage.addEventListener(MouseEvent.CLICK, f); function f(e) {}", 1, 1, "mouse listeners on the stage"),
|
||||
("b.addEventListener(Event.RESIZE, f); function f(e) {}", 1, 20, "listening for Event.RESIZE isn't supported yet"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f() { stop(); }", 1, 42, "a listener function takes the event"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f, true); function f(e) {}", 1, 41, "capture-phase listeners"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { trace(e.target.name); }", 1, 64, "reading the event `e`"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { e.target.play(); }", 1, 58, "`target` can be a part inside"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f(e) { c.addEventListener(MouseEvent.CLICK, f); }", 1, 58, "adding a listener from inside a listener"),
|
||||
("b.removeEventListener(MouseEvent.CLICK, f);", 1, 1, "removing listeners isn't supported yet"),
|
||||
("function f() { f(); } f();", 1, 16, "`f` calls itself"),
|
||||
("b.addEventListener(MouseEvent.CLICK, f); function f(e:MouseEvent) { trace(e.stageX); }", 1, 75, "reading the event's `stageX`"),
|
||||
("b.removeEventListener(MouseEvent.CLICK, function (e) {});", 1, 41, "a function written in place can't be removed"),
|
||||
("function stop() {}", 1, 1, "a function named `stop` would hide"),
|
||||
("function f() {} function f() {}", 1, 17, "`f` is declared twice"),
|
||||
("function f() { function g() {} } f();", 1, 16, "functions declared inside functions"),
|
||||
("function f(n) { n.play(); } f(1);", 1, 17, "reading the parameter `n`"),
|
||||
("function f(a:int, n) { n.play(); } f(1, 2);", 1, 24, "`n` is a variable, not an instance"),
|
||||
("function f(a:int) {} f();", 1, 22, "`f` takes 1 argument, not 0"),
|
||||
("function f(...rest) {}", 1, 15, "rest parameters"),
|
||||
("var n:int; n.play();", 1, 12, "`n` is a variable, not an instance"),
|
||||
("var s:String = \"ab\"; trace(s.length);", 1, 28, "reading `length` of a value"),
|
||||
("hero_mc[\"arm\"].play();", 1, 1, "this isn't an instance"),
|
||||
("hero_mc.x = \"10\";", 1, 13, "`x` is set to a number"),
|
||||
("hero_mc.x = 1 / 0;", 1, 13, "the value must be a finite number"),
|
||||
("trace(new Date());", 1, 7, "`new` isn't supported yet"),
|
||||
("trace(1 & 2);", 1, 7, "the `&` operator isn't supported yet"),
|
||||
("var n:int; n <<= 2;", 1, 12, "`<<=` isn't supported yet"),
|
||||
("break;", 1, 1, "`break` is only for loops here"),
|
||||
("trace(stop());", 1, 7, "`stop()` gives no value"),
|
||||
("trace(Math.sqrt(4));", 1, 7, "`Math.sqrt` isn't supported yet"),
|
||||
("trace(Keyboard.WIGGLE);", 1, 7, "`Keyboard.WIGGLE` isn't a key"),
|
||||
("package { }", 1, 1, "`package` belongs to class files"),
|
||||
("class Hero {}", 1, 1, "`class` belongs to class files"),
|
||||
("public function f() {}", 1, 1, "`public` declarations belong to classes"),
|
||||
@@ -183,9 +351,8 @@ fn every_problem_says_where_it_is() {
|
||||
("stop(); #", 1, 9, "unexpected character '#'"),
|
||||
("var re = /ab+c/;", 1, 10, "regular expressions aren't supported"),
|
||||
("1 = 2;", 1, 3, "the left side of this assignment can't be assigned to"),
|
||||
("x++;", 1, 1, "`++` and `--` read a value first"),
|
||||
("é.play();", 1, 1, "`é` isn't an instance name AniCraft can address"),
|
||||
("\tstop();\n\t\tif (a) {}", 2, 3, "`if` statements"),
|
||||
("\tstop();\n\t\twith (a) {}", 2, 3, "`with` statements"),
|
||||
];
|
||||
for (src, line, col, msg) in cases {
|
||||
let (l, c, m) = err(src);
|
||||
@@ -195,19 +362,34 @@ fn every_problem_says_where_it_is() {
|
||||
|
||||
#[test]
|
||||
fn every_problem_is_listed_and_nothing_half_runs() {
|
||||
let p = compile("stop();\nvar a = 1;\nif (a) {}\nplay();\nhero.width = 3;").unwrap_err();
|
||||
let p = compile("stop();\nvar a:Array;\nswitch (a) {}\nplay();\nhero.width = 3;").unwrap_err();
|
||||
let at: Vec<(u32, u32)> = p.iter().map(|p| (p.line, p.column)).collect();
|
||||
assert_eq!(at, [(2, 1), (3, 1), (5, 1)]);
|
||||
assert_eq!(p[0].to_string(), "line 2, column 1: variables (`var`) aren't supported yet");
|
||||
let many: String = (0..200).map(|i| format!("var v{i} = {i};\n")).collect();
|
||||
assert_eq!(at, [(2, 7), (3, 1), (5, 1)]);
|
||||
let many: String = (0..200).map(|i| format!("hero.w{i} = {i};\n")).collect();
|
||||
assert_eq!(compile(&many).unwrap_err().len(), MAX_PROBLEMS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_text_matches_actionscript() {
|
||||
for (n, s) in [(0.0, "0"), (-0.0, "0"), (5.0, "5"), (-3.25, "-3.25"), (0.1 + 0.2, "0.30000000000000004"), (1e21, "1e+21"), (1.5e-7, "1.5e-7"), (123456789012.0, "123456789012"), (f64::NAN, "NaN"), (f64::NEG_INFINITY, "-Infinity"), (0.000001, "0.000001")] {
|
||||
assert_eq!(lower::number_text(n), s, "{n}");
|
||||
assert_eq!(number_text(n), s, "{n}");
|
||||
}
|
||||
for (s, n) in [("", 0.0), (" 12 ", 12.0), ("1e3", 1000.0), (".5", 0.5), ("5.", 5.0), ("-0x10", f64::NAN), ("0x10", 16.0), ("0b101", 5.0), ("+Infinity", f64::INFINITY), ("inf", f64::NAN), ("1_0", f64::NAN), ("\u{a0}7\u{feff}", 7.0), ("1e", f64::NAN), ("-", f64::NAN)] {
|
||||
let v = string_number(s);
|
||||
assert!(v == n || (v.is_nan() && n.is_nan()), "{s:?}: {v}");
|
||||
}
|
||||
assert_eq!((to_int32(4_294_967_296.0 + 5.0), to_int32(-1.5), to_uint32(-1.0), to_int32(f64::NAN)), (5, -1, 4_294_967_295, 0));
|
||||
assert_eq!((run::round(0.49999999999999994), run::round(-0.5), run::round(1.5)), (0.0, 0.0, 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ir_reads_and_writes_as_json() {
|
||||
let c = ok("var n:Number = NaN; var s:String = \"a\"; if (n != n) trace(s + 1, -Infinity); function f(e:MouseEvent = null):void {} btn.addEventListener(MouseEvent.CLICK, f);");
|
||||
let v = serde_json::to_value(&c).unwrap();
|
||||
let back: Compiled = serde_json::from_value(v.clone()).unwrap();
|
||||
assert_eq!(back, c);
|
||||
let text = v.to_string();
|
||||
assert!(text.contains("\"nan\"") && text.contains("{\"inf\":false}") && text.contains("\"s\":\"if\""), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -218,25 +400,41 @@ fn limits_are_problems_not_crashes() {
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
let deep = format!("trace({}1);", "-".repeat(100_000));
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
let deep = format!("{}1;", "a = ".repeat(10_000));
|
||||
let deep = format!("var a; {}1;", "a = ".repeat(10_000));
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
// A long row of operators would make a deep tree; it counts as nesting.
|
||||
let long = format!("trace({}1);", "1 + ".repeat(10_000));
|
||||
let m = err(&long).2;
|
||||
assert!(m.contains("too many operators in a row") || m.contains("nested more than"), "{m}");
|
||||
let deep = format!("b.addEventListener(\"click\", {}", "function (e) { ".repeat(5_000));
|
||||
assert!(err(&deep).2.contains("nested more than"));
|
||||
let long = "stop();".repeat(MAX_RUN_BYTES / 7 + 1);
|
||||
assert!(err(&long).2.contains("longer than 256 KiB"));
|
||||
let tokens = ";".repeat(MAX_TOKENS + 1);
|
||||
assert!(err(&tokens).2.contains("tokens"));
|
||||
let steps = "stop();".repeat(crate::MAX_ACTIONS + 1);
|
||||
assert!(err(&steps).2.contains("at most 256 steps"));
|
||||
// Calls that fan out are bounded, however deep they could go.
|
||||
let mut src = String::from("function f0() { stop(); }\n");
|
||||
for i in 1..16 {
|
||||
src.push_str(&format!("function f{i}() {{ {} }}\n", format!("f{}(); ", i - 1).repeat(8)));
|
||||
}
|
||||
|
||||
/// The deepest code the limits allow runs in a small stack: calls 16 deep, each as nested as
|
||||
/// the parser lets code be.
|
||||
#[test]
|
||||
fn the_deepest_allowed_code_fits_a_small_stack() {
|
||||
let nest = |depth: usize| format!("{}n{}", "(1 + ".repeat(depth), ")".repeat(depth));
|
||||
let mut src = String::from("function f0(n:int):int { return n; }\n");
|
||||
for i in 1..20 {
|
||||
src.push_str(&format!("function f{i}(n:int):int {{ return f{}({}); }}\n", i - 1, nest(18)));
|
||||
}
|
||||
src.push_str("f15();");
|
||||
let t0 = std::time::Instant::now();
|
||||
assert!(compile(&src).is_err());
|
||||
assert!(t0.elapsed().as_secs_f32() < 5.0);
|
||||
src.push_str("trace(f19(0));");
|
||||
let c = ok(&src);
|
||||
let r = std::thread::Builder::new()
|
||||
.stack_size(512 * 1024)
|
||||
.spawn(move || {
|
||||
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
|
||||
run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN).1
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("deep")), "{r:?}");
|
||||
}
|
||||
|
||||
/// A small deterministic generator (no clock, no randomness crate).
|
||||
@@ -256,20 +454,25 @@ impl Rng {
|
||||
|
||||
#[test]
|
||||
fn hostile_input_never_panics_and_ends_quickly() {
|
||||
const PIECES: [&str; 64] = [
|
||||
"stop", "play", "gotoAndStop", "(", ")", "{", "}", "[", "]", ";", ",", ".", "\n", " ", "\"a", "\"", "'", "\\", "/*", "*/", "//", "1", "0x", "1e", ".5", "e", "function", "f", "e:MouseEvent", ":void", "addEventListener", "MouseEvent.CLICK", "=", "+", "-", "!", "?", ":", "if", "else", "var", "for", "new", "this", "parent", "root", "MovieClip", "as", "trace", "x", "alpha", "é", "\u{0}", "\r", "\t", "<", ">", "...", "::", "..", ".<", "return", "import", "@",
|
||||
const PIECES: [&str; 80] = [
|
||||
"stop", "play", "gotoAndStop", "(", ")", "{", "}", "[", "]", ";", ",", ".", "\n", " ", "\"a", "\"", "'", "\\", "/*", "*/", "//", "1", "0x", "1e", ".5", "e", "function", "f", "e:MouseEvent", ":void", "addEventListener", "MouseEvent.CLICK", "=", "+", "-", "!", "?", ":", "if", "else", "var", "for", "new", "this", "parent", "root", "MovieClip", "as", "trace", "x", "alpha", "é", "\u{0}", "\r", "\t", "<", ">", "...", "::", "..", ".<", "return", "import", "@", "while", "do", "break", "continue", "int", "n", "++", "+=", "==", "&&", "||", "Math.random()", "e.keyCode", "stage", "Event.ENTER_FRAME", "removeEventListener",
|
||||
];
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let t0 = std::time::Instant::now();
|
||||
let mut compiled = 0;
|
||||
for _ in 0..4_000 {
|
||||
for _ in 0..5_000 {
|
||||
let n = rng.next() as usize % 80;
|
||||
let src: String = (0..n).map(|_| rng.pick(&PIECES)).collect();
|
||||
if compile(&src).is_ok() {
|
||||
if let Ok(c) = compile(&src) {
|
||||
compiled += 1;
|
||||
// What compiles runs, within its fuel, whatever it is.
|
||||
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
|
||||
let _ = run::run_script(&mut m, &c.body, &c.inner, 2_000);
|
||||
for f in &c.functions {
|
||||
let _ = run::run_listener(&mut m, f, 2_000);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Raw bytes as text, too.
|
||||
for _ in 0..1_000 {
|
||||
let n = rng.next() as usize % 200;
|
||||
let bytes: Vec<u8> = (0..n).map(|_| rng.next() as u8).collect();
|
||||
@@ -286,8 +489,65 @@ fn compiles_once_per_script() {
|
||||
let b: *const crate::CompileResult = s.compiled();
|
||||
assert!(std::ptr::eq(a, b));
|
||||
assert!(s.runs());
|
||||
// A copy compiles on its own (its text may change); equality ignores the cache.
|
||||
let c = s.clone();
|
||||
assert_eq!(c, s);
|
||||
assert!(!crate::SourceScript::new(crate::Language::ActionScript1or2, "stop();").runs());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_lines_are_cut_at_whole_characters() {
|
||||
let long = "é".repeat(2000);
|
||||
let cut = run::trace_line(long);
|
||||
assert_eq!(cut.chars().count(), crate::MAX_TRACE_CHARS + 1);
|
||||
let emoji = format!("{}{}", "a".repeat(crate::MAX_TRACE_CHARS - 1), "😀".repeat(5));
|
||||
assert_eq!(run::trace_line(emoji).encode_utf16().count(), crate::MAX_TRACE_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_budget_runs_quickly() {
|
||||
let c = ok("var n:int = 0; var s:Number = 0; while (true) { n++; s += Math.abs(n % 7 - 3) * 0.5; }");
|
||||
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
|
||||
let t0 = std::time::Instant::now();
|
||||
let (used, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
|
||||
let ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
eprintln!("{used} fuel in {ms:.2} ms");
|
||||
assert_eq!(r, Err(Stop::Fuel));
|
||||
assert!(ms < 500.0, "{ms} ms");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_set_append_and_read_text_fields() {
|
||||
let src = r#"
|
||||
var n:int = 3;
|
||||
score_txt.text = "Score: " + n;
|
||||
score_txt.appendText("!");
|
||||
score_txt.text += "?";
|
||||
trace(score_txt.text, score_txt.length);
|
||||
panel.name_txt.text = String(score_txt.length * 2);
|
||||
var text:String = "a variable named text";
|
||||
trace(text);
|
||||
"#;
|
||||
let c = ok(src);
|
||||
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
|
||||
m.texts.insert("score_txt".into(), String::new());
|
||||
m.texts.insert("panel.name_txt".into(), "x".into());
|
||||
let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
|
||||
assert_eq!(r, Ok(()));
|
||||
assert_eq!(m.texts["score_txt"], "Score: 3!?");
|
||||
assert_eq!(m.texts["panel.name_txt"], "20");
|
||||
assert!(m.log.contains(&"Score: 3!? 10".to_string()), "{:?}", m.log);
|
||||
assert!(m.log.contains(&"a variable named text".to_string()), "a bare `text` stays a variable");
|
||||
// Setting null stops the script with a message; `this.text` and the stage aren't fields.
|
||||
let (_, r, _) = {
|
||||
let c = ok("score_txt.text = null;");
|
||||
let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() };
|
||||
m.texts.insert("score_txt".into(), String::new());
|
||||
let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN);
|
||||
((), r, ())
|
||||
};
|
||||
assert!(matches!(r, Err(Stop::Error { ref message, .. }) if message.contains("not null")), "{r:?}");
|
||||
assert!(err("this.text = 'x';").2.contains("isn't a text field"));
|
||||
assert!(err("stage.text = 'x';").2.contains("text field") || err("stage.text = 'x';").2.contains("stage"));
|
||||
assert!(err("a_txt.appendText();").2.contains("one argument"));
|
||||
assert!(err("a_txt.length = 3;").2.contains("can only be read"));
|
||||
}
|
||||
@@ -19,6 +19,7 @@ anicraft-doc.workspace = true
|
||||
anicraft-engine.workspace = true
|
||||
anicraft-render.workspace = true
|
||||
anicraft-geom.workspace = true
|
||||
anicraft-guide.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -18,10 +18,14 @@ USAGE:
|
||||
anicraft-cli render <file|--sample> --out <frame.png> [--frame N] [--scale S]
|
||||
anicraft-cli render-seq <file|--sample> --out-dir <dir> [--from A] [--to B] [--scale S]
|
||||
anicraft-cli gif <file|--sample> --out <anim.gif> [--from A] [--to B] [--scale S] [--overwrite yes]
|
||||
anicraft-cli apng|webp <file|--sample> --out <anim.png|anim.webp> [--from A] [--to B] [--scale S]
|
||||
[--loop forever|N] [--background yes] [--overwrite yes]
|
||||
full colour with real transparency (WebP: lossless)
|
||||
anicraft-cli commands
|
||||
anicraft-cli run <file|--sample> <script.json> [--save <out.anicraft>]
|
||||
anicraft-cli exec <file|--sample> <command.id> [<json-params>] [--save <out.anicraft>]
|
||||
anicraft-cli new --out <file.anicraft> [--width W] [--height H] [--fps F]
|
||||
anicraft-cli guide --out <folder> writes the user guide as HTML pages (open index.html)
|
||||
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 +77,12 @@ pub fn open_session(src: Option<&str>) -> Result<Session, String> {
|
||||
match src {
|
||||
None => Ok(Session::default()),
|
||||
Some("--sample") => Ok(Session::new(anicraft_doc::sample::demo())),
|
||||
// An Animate document imports as File › Open does (#226), untitled.
|
||||
Some(p) if anicraft_engine::is_animate(std::path::Path::new(p)) => {
|
||||
let mut s = Session::default();
|
||||
s.execute("file.open", &serde_json::json!({"path": p})).map_err(|e| e.to_string())?;
|
||||
Ok(s)
|
||||
}
|
||||
Some(p) => {
|
||||
let doc = format::load(std::path::Path::new(p)).map_err(|e| format!("{p}: {e}"))?;
|
||||
let mut s = Session::new(doc);
|
||||
@@ -120,6 +130,12 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
let list: Vec<Value> = commands().iter().map(|c| c.to_json()).collect();
|
||||
serde_json::to_string_pretty(&list).map_err(|e| e.to_string())
|
||||
}
|
||||
// The user guide as the static HTML book Help › User Guide opens (ADR 0069).
|
||||
"guide" => {
|
||||
let out = a.flag("out").ok_or("guide needs --out <folder>")?;
|
||||
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 +164,11 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
}
|
||||
exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string())
|
||||
}
|
||||
"gif" => {
|
||||
let mut s = session(&a, Some(src.ok_or("gif needs a file or --sample")?))?;
|
||||
let out = a.flag("out").ok_or("gif needs --out <anim.gif>")?;
|
||||
"gif" | "apng" | "webp" => {
|
||||
let mut s = session(&a, Some(src.ok_or(format!("{cmd} needs a file or --sample"))?))?;
|
||||
let cmd = cmd.as_str();
|
||||
let ext = if cmd == "apng" { "png" } else { cmd };
|
||||
let out = a.flag("out").ok_or(format!("{cmd} needs --out <anim.{ext}>"))?;
|
||||
let mut p = json!({"path": out});
|
||||
if let Some(f) = one_based(&a, "from")? {
|
||||
p["from"] = json!(f);
|
||||
@@ -164,7 +182,16 @@ pub fn run(argv: &[String]) -> Result<String, String> {
|
||||
if a.flag("overwrite").is_some_and(|v| v == "yes" || v == "true") {
|
||||
p["confirm"] = json!(true);
|
||||
}
|
||||
exec(&mut s, "file.export_gif", &p).map(|v| v.to_string())
|
||||
if cmd != "gif" {
|
||||
match a.flag("loop") {
|
||||
None | Some("forever") => {}
|
||||
Some(n) => p["loop"] = json!(n.parse::<u32>().map_err(|_| format!("--loop is forever or how many times it plays, not '{n}'"))?),
|
||||
}
|
||||
if a.flag("background").is_some_and(|v| v == "yes" || v == "true") {
|
||||
p["background"] = json!(true);
|
||||
}
|
||||
}
|
||||
exec(&mut s, &format!("file.export_{cmd}"), &p).map(|v| v.to_string())
|
||||
}
|
||||
"new" => {
|
||||
let mut s = Session::default();
|
||||
@@ -457,6 +484,17 @@ pub fn serve<R: BufRead, W: Write>(s: &mut Session, input: R, out: &mut W) -> st
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #226: `info`, `render` and the other subcommands take an Animate document as File › Open
|
||||
/// does (an import, untitled), not only `.anicraft` files.
|
||||
#[test]
|
||||
fn subcommands_open_animate_documents() {
|
||||
let xfl = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../xfl/tests/corpus/shapes/shapes.xfl");
|
||||
let s = open_session(Some(&xfl.display().to_string())).unwrap();
|
||||
assert!(s.path.is_none() && !s.doc.timeline(0).layers.is_empty());
|
||||
let info = run(&["info".to_string(), xfl.display().to_string()]).unwrap();
|
||||
assert!(info.contains("\"layers\""), "{info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_round_trip() {
|
||||
let mut s = Session::default();
|
||||
@@ -566,5 +604,6 @@ mod tests {
|
||||
assert!(run(&["bogus".into()]).is_err());
|
||||
assert!(run(&["info".into()]).is_err());
|
||||
assert!(run(&["commands".into()]).unwrap().contains("timeline.insert_keyframe"));
|
||||
assert!(run(&["guide".into()]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Drawing aids saved with the document (ADR 0076): each scene's guides, and how the grid and
|
||||
//! the guides look. Whether they show and snap is the editor's (`anicraft_engine::ViewAids`):
|
||||
//! a working preference, like Snap to Objects, not part of the artwork. None of this is ever
|
||||
//! rendered into a picture or an export; the editor's stage draws it.
|
||||
|
||||
use crate::Rgba;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Which way a guide runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum GuideAxis {
|
||||
/// A horizontal line at `y = at` (dragged from the top ruler).
|
||||
Horizontal,
|
||||
/// A vertical line at `x = at` (dragged from the left ruler).
|
||||
Vertical,
|
||||
}
|
||||
|
||||
impl GuideAxis {
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
GuideAxis::Horizontal => "horizontal",
|
||||
GuideAxis::Vertical => "vertical",
|
||||
}
|
||||
}
|
||||
/// `horizontal`/`h` or `vertical`/`v`.
|
||||
pub fn parse(s: &str) -> Option<GuideAxis> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"horizontal" | "h" => Some(GuideAxis::Horizontal),
|
||||
"vertical" | "v" => Some(GuideAxis::Vertical),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A guide: a line across the whole stage and pasteboard, in stage pixels from the stage's
|
||||
/// top-left corner.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Guide {
|
||||
pub axis: GuideAxis,
|
||||
pub at: f32,
|
||||
}
|
||||
|
||||
/// Most guides one scene keeps.
|
||||
pub const MAX_GUIDES: usize = 1_000;
|
||||
/// Farthest a guide may be from the stage's corner, in stage pixels (well past any pasteboard).
|
||||
pub const GUIDE_REACH: f32 = 100_000.0;
|
||||
/// The grid's spacing range, in stage pixels.
|
||||
pub const GRID_MIN: f32 = 1.0;
|
||||
pub const GRID_MAX: f32 = 4_096.0;
|
||||
|
||||
impl Guide {
|
||||
/// A guide with its position kept in range; `None` for a position that isn't a number.
|
||||
pub fn new(axis: GuideAxis, at: f32) -> Option<Guide> {
|
||||
at.is_finite().then(|| Guide { axis, at: at.clamp(-GUIDE_REACH, GUIDE_REACH) })
|
||||
}
|
||||
}
|
||||
|
||||
/// How the grid looks (View › Grid › Edit Grid).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Grid {
|
||||
/// Between vertical lines, in stage pixels.
|
||||
pub spacing_x: f32,
|
||||
/// Between horizontal lines, in stage pixels.
|
||||
pub spacing_y: f32,
|
||||
pub color: Rgba,
|
||||
/// Drawn over the artwork; off (the default, as in Animate) it shows under it, on the stage.
|
||||
pub over_objects: bool,
|
||||
}
|
||||
|
||||
impl Default for Grid {
|
||||
fn default() -> Self {
|
||||
Grid { spacing_x: 20.0, spacing_y: 20.0, color: Rgba::hex(0x949494), over_objects: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
/// Spacing clamped to [`GRID_MIN`]..=[`GRID_MAX`] (non-numbers back to the default).
|
||||
pub fn sanitized(self) -> Grid {
|
||||
let sp = |v: f32| if v.is_finite() { v.clamp(GRID_MIN, GRID_MAX) } else { 20.0 };
|
||||
Grid { spacing_x: sp(self.spacing_x), spacing_y: sp(self.spacing_y), color: self.color.sanitized(), over_objects: self.over_objects }
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid and the guides' looks, saved with the document.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Aids {
|
||||
pub grid: Grid,
|
||||
pub guide_color: Rgba,
|
||||
}
|
||||
|
||||
impl Default for Aids {
|
||||
fn default() -> Self {
|
||||
Aids { grid: Grid::default(), guide_color: Rgba::hex(0x3ec8f0) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Aids {
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == Aids::default()
|
||||
}
|
||||
pub fn sanitized(self) -> Aids {
|
||||
Aids { grid: self.grid.sanitized(), guide_color: self.guide_color.sanitized() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Guides from a file kept to numbers in range, at most [`MAX_GUIDES`].
|
||||
pub fn sanitize_guides(guides: &mut Vec<Guide>) {
|
||||
guides.retain(|g| g.at.is_finite());
|
||||
guides.truncate(MAX_GUIDES);
|
||||
for g in guides.iter_mut() {
|
||||
g.at = g.at.clamp(-GUIDE_REACH, GUIDE_REACH);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hostile_values_are_kept_in_range() {
|
||||
let mut g = vec![Guide { axis: GuideAxis::Vertical, at: f32::NAN }, Guide { axis: GuideAxis::Horizontal, at: 1e30 }];
|
||||
g.extend(std::iter::repeat_n(Guide { axis: GuideAxis::Vertical, at: 3.0 }, MAX_GUIDES + 5));
|
||||
sanitize_guides(&mut g);
|
||||
assert_eq!(g.len(), MAX_GUIDES);
|
||||
assert_eq!(g[0], Guide { axis: GuideAxis::Horizontal, at: GUIDE_REACH });
|
||||
let grid = Grid { spacing_x: 0.0, spacing_y: f32::INFINITY, ..Grid::default() }.sanitized();
|
||||
assert_eq!((grid.spacing_x, grid.spacing_y), (GRID_MIN, 20.0));
|
||||
assert_eq!(Guide::new(GuideAxis::Vertical, f32::NAN), None);
|
||||
assert_eq!(GuideAxis::parse(" V "), Some(GuideAxis::Vertical));
|
||||
assert_eq!(GuideAxis::parse("diagonal"), None);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@
|
||||
//! joint's limits. It works on joint angles directly, so limits are a clamp per step and the
|
||||
//! result is a pose by construction.
|
||||
|
||||
use crate::skin::{self, Skin};
|
||||
use crate::{Element, ElementId, Keyframe, Layer};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -111,6 +112,11 @@ impl Bone {
|
||||
pub struct Armature {
|
||||
#[serde(default)]
|
||||
pub bones: Vec<Bone>,
|
||||
/// A shape armature (ADR 0071): the bones are inside this shape and bend its outline. Its
|
||||
/// bones join joint nodes (ids that are no element) instead of instances; see
|
||||
/// [`crate::skin`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub skin: Option<Skin>,
|
||||
}
|
||||
|
||||
impl Armature {
|
||||
@@ -118,6 +124,12 @@ impl Armature {
|
||||
self.bones.is_empty()
|
||||
}
|
||||
|
||||
/// The shape a shape armature's bones are inside (ADR 0071); `None` for an armature of
|
||||
/// symbol instances.
|
||||
pub fn skin_shape(&self) -> Option<ElementId> {
|
||||
self.skin.as_ref().map(|s| s.shape)
|
||||
}
|
||||
|
||||
pub fn bone(&self, id: BoneId) -> Option<&Bone> {
|
||||
self.bones.iter().find(|b| b.id == id)
|
||||
}
|
||||
@@ -152,8 +164,12 @@ impl Armature {
|
||||
out
|
||||
}
|
||||
|
||||
/// The instances no bone moves (one for an armature made with the Bone tool).
|
||||
/// The instances no bone moves (one for an armature made with the Bone tool; a shape
|
||||
/// armature's shape).
|
||||
pub fn roots(&self) -> Vec<ElementId> {
|
||||
if let Some(s) = self.skin_shape() {
|
||||
return vec![s];
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for b in &self.bones {
|
||||
if self.bone_into(b.parent).is_none() && !out.contains(&b.parent) {
|
||||
@@ -210,8 +226,12 @@ impl Armature {
|
||||
kept.push(b);
|
||||
}
|
||||
// Order: a bone after the bone moving its parent. What never gets placed is a cycle.
|
||||
// A shape armature's bones all hang from its shape.
|
||||
let children: HashSet<ElementId> = kept.iter().map(|b| b.child).collect();
|
||||
let mut placed: HashSet<ElementId> = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect();
|
||||
let mut placed: HashSet<ElementId> = match self.skin_shape() {
|
||||
Some(s) => HashSet::from([s]),
|
||||
None => kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(),
|
||||
};
|
||||
let mut ordered = Vec::with_capacity(kept.len());
|
||||
let mut rest = kept;
|
||||
loop {
|
||||
@@ -227,7 +247,8 @@ impl Armature {
|
||||
}
|
||||
ordered.truncate(MAX_BONES);
|
||||
self.bones = ordered;
|
||||
self.bones != before
|
||||
let skin_changed = skin::sanitize(self);
|
||||
self.bones != before || skin_changed
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,19 +317,21 @@ impl Pose {
|
||||
}
|
||||
|
||||
/// `R(angle)` about point `j`.
|
||||
fn turn_about(j: Vec2, angle: f32) -> Affine {
|
||||
pub(crate) fn turn_about(j: Vec2, angle: f32) -> Affine {
|
||||
Affine::translate(j.x, j.y).mul(&Affine::rotate(angle)).mul(&Affine::translate(-j.x, -j.y))
|
||||
}
|
||||
|
||||
/// Forward kinematics: the transform (in the layer's space) of every instance in `elements`
|
||||
/// once `pose` turns the armature's joints. A root keeps its own transform; a child is placed
|
||||
/// from its parent: `R_joint(angle) · parent · rest`. An instance whose parent isn't on the
|
||||
/// keyframe keeps its own transform.
|
||||
/// keyframe keeps its own transform. A shape armature's joint nodes (ADR 0071) are placed
|
||||
/// the same way from the shape's transform.
|
||||
pub fn place(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> HashMap<ElementId, Affine> {
|
||||
let mut world: HashMap<ElementId, Affine> = elements.iter().map(|e| (e.id, e.transform)).collect();
|
||||
let nodes = arm.skin.is_some();
|
||||
for b in &arm.bones {
|
||||
let Some(wp) = world.get(&b.parent).copied() else { continue };
|
||||
if !world.contains_key(&b.child) {
|
||||
if !nodes && !world.contains_key(&b.child) {
|
||||
continue;
|
||||
}
|
||||
let j = wp.apply(b.head);
|
||||
@@ -320,12 +343,15 @@ pub fn place(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> HashMap<
|
||||
world
|
||||
}
|
||||
|
||||
/// Puts the instances of `elements` where `pose` has them (copy-on-write: only instances that
|
||||
/// move are cloned). Returns whether any moved.
|
||||
/// Puts the instances of `elements` where `pose` has them, and bends a shape armature's shape
|
||||
/// (copy-on-write: only what changes is cloned). Returns whether anything changed.
|
||||
pub fn apply(arm: &Armature, elements: &mut [Arc<Element>], pose: &Pose) -> bool {
|
||||
if arm.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if arm.skin.is_some() {
|
||||
return skin::apply(arm, elements, pose);
|
||||
}
|
||||
let world = place(arm, elements, pose);
|
||||
let mut moved = false;
|
||||
for e in elements.iter_mut() {
|
||||
@@ -372,7 +398,8 @@ pub struct BoneAt {
|
||||
/// Every bone's joint and end with the instances in `elements` placed as they show (posed:
|
||||
/// what [`crate::evaluate_layer_elements`] gives on an armature layer).
|
||||
pub fn bones_at(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> Vec<BoneAt> {
|
||||
let world: HashMap<ElementId, Affine> = elements.iter().map(|e| (e.id, e.transform)).collect();
|
||||
// A shape armature's joint nodes are no elements: forward kinematics places them.
|
||||
let world: HashMap<ElementId, Affine> = if arm.skin.is_some() { place(arm, elements, pose) } else { elements.iter().map(|e| (e.id, e.transform)).collect() };
|
||||
arm.bones
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
@@ -382,6 +409,15 @@ pub fn bones_at(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> Vec<B
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Layer point `p` in the space of the instance (or joint node) bone `id` moves, with the
|
||||
/// armature posed by `pose`: the `local` for [`solve`] that makes the grabbed point follow a drag
|
||||
/// from where it is, so grabbing a bone along its length never snaps its end to the pointer.
|
||||
pub fn grab_point(arm: &Armature, elements: &[Arc<Element>], pose: &Pose, id: BoneId, p: Vec2) -> Option<Vec2> {
|
||||
let child = arm.bone(id)?.child;
|
||||
let q = place(arm, elements, pose).get(&child)?.inverse()?.apply(p);
|
||||
(q.x.is_finite() && q.y.is_finite()).then_some(q)
|
||||
}
|
||||
|
||||
/// What a solve came to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Solved {
|
||||
|
||||
@@ -26,7 +26,7 @@ fn bone(id: BoneId, parent: ElementId, child: ElementId) -> Bone {
|
||||
/// joint), the hand from 300; the hand's end at 400. The arm and hand reach 200 px from the
|
||||
/// shoulder joint at (200, 100).
|
||||
fn chain() -> (Armature, Vec<Arc<Element>>) {
|
||||
let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)] };
|
||||
let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)], skin: None };
|
||||
(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);
|
||||
@@ -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, skin: None };
|
||||
let last = BoneId(5000 + n as u64 - 1);
|
||||
let reach = 100.0 * n as f32;
|
||||
for k in 0..12 {
|
||||
|
||||
@@ -222,6 +222,7 @@ pub(crate) mod base64_bytes {
|
||||
}
|
||||
}
|
||||
|
||||
pub use base64_bytes::decode as base64_decode;
|
||||
pub use base64_bytes::encode as base64_encode;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
//! 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.
|
||||
|
||||
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};
|
||||
|
||||
/// Smallest and largest camera zoom (5 % to 2,000 %).
|
||||
@@ -55,13 +55,17 @@ 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) }
|
||||
// The camera's colour effect is a tint (ADR 0027); other styles leave the view as it is.
|
||||
let (tint, amount) = match el.color {
|
||||
ColorEffect::Tint { color, amount } => (color.sanitized(), fin(amount, 0.0).clamp(0.0, 1.0)),
|
||||
_ => (Rgba::WHITE, 0.0),
|
||||
};
|
||||
Camera { center, zoom, rotation, tint, tint_amount: amount }
|
||||
}
|
||||
|
||||
/// 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: ColorEffect::Tint { color: self.tint, amount: self.tint_amount }, kind: ElementKind::Camera }
|
||||
}
|
||||
|
||||
/// The camera on the stage: `T(centre) · R(rotation) · S(zoom)`.
|
||||
@@ -70,8 +74,8 @@ 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 {
|
||||
ColorTransform::tint(self.tint, self.tint_amount)
|
||||
}
|
||||
|
||||
/// Stage space → output space for a layer `depth` pixels behind the stage: the camera's
|
||||
@@ -219,7 +223,7 @@ mod tests {
|
||||
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!((MIN_ZOOM..=MAX_ZOOM).contains(&c.zoom));
|
||||
|
||||
@@ -70,8 +70,7 @@ fn camera_rotation_and_tint_apply_to_the_whole_view() {
|
||||
// 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.
|
||||
|
||||
@@ -0,0 +1,526 @@
|
||||
//! Colour effects (ADR 0056): what Animate's Properties calls an instance's colour effect
|
||||
//! *style* (None, Brightness, Tint, Advanced, Alpha), and the one colour transform every style
|
||||
//! is (a multiply and an offset per channel).
|
||||
//!
|
||||
//! An element stores its [`ColorEffect`] as authored, so Properties shows the style and values
|
||||
//! the artist chose (a tint keeps its colour at 0 %). Everything that draws works on its
|
||||
//! [`ColorTransform`]: nested instances, the camera and onion skin compose their transforms
|
||||
//! exactly (`concat` is the composition of the two maps), and every renderer applies the same
|
||||
//! arithmetic to straight colour: `c ↦ clamp(c·multiply + offset, 0, 1)`.
|
||||
//!
|
||||
//! Brightness `b` is a tint towards white (`b > 0`) or black (`b < 0`) by `|b|`; a tint of
|
||||
//! colour `t` by amount `k` multiplies each colour channel by `1 − k` and adds `k·t`; alpha
|
||||
//! multiplies the alpha channel; Advanced is the transform itself (Animate's per-channel
|
||||
//! percent and −255..255 offset, here as fractions: offset 1 is 255).
|
||||
|
||||
use crate::Rgba;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
/// A colour transform on straight (not premultiplied) colour: channel `i` (red, green, blue,
|
||||
/// alpha) becomes `clamp(c·mul[i] + add[i], 0, 1)`. Offsets are fractions of the full range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ColorTransform {
|
||||
pub mul: [f32; 4],
|
||||
pub add: [f32; 4],
|
||||
}
|
||||
|
||||
impl Default for ColorTransform {
|
||||
fn default() -> Self {
|
||||
ColorTransform::IDENTITY
|
||||
}
|
||||
}
|
||||
|
||||
/// Animate's Advanced ranges: multipliers −100..=100 %, offsets −255..=255.
|
||||
pub const ADVANCED_MUL: std::ops::RangeInclusive<f32> = -1.0..=1.0;
|
||||
pub const ADVANCED_ADD: std::ops::RangeInclusive<f32> = -1.0..=1.0;
|
||||
|
||||
fn fin(v: f32, or: f32) -> f32 {
|
||||
if v.is_finite() { v } else { or }
|
||||
}
|
||||
|
||||
impl ColorTransform {
|
||||
pub const IDENTITY: ColorTransform = ColorTransform { mul: [1.0; 4], add: [0.0; 4] };
|
||||
|
||||
/// Multiplies alpha by `a`.
|
||||
pub fn alpha(a: f32) -> ColorTransform {
|
||||
ColorTransform { mul: [1.0, 1.0, 1.0, a], add: [0.0; 4] }
|
||||
}
|
||||
/// Mixes colour `t` in by `k` (alpha untouched).
|
||||
pub fn tint(t: Rgba, k: f32) -> ColorTransform {
|
||||
let j = 1.0 - k;
|
||||
ColorTransform { mul: [j, j, j, 1.0], add: [k * t.r, k * t.g, k * t.b, 0.0] }
|
||||
}
|
||||
/// Brightness `b` in −1..=1: a tint towards white or black by `|b|`.
|
||||
pub fn brightness(b: f32) -> ColorTransform {
|
||||
if b >= 0.0 { ColorTransform::tint(Rgba::WHITE, b) } else { ColorTransform::tint(Rgba::BLACK, -b) }
|
||||
}
|
||||
|
||||
pub fn is_identity(&self) -> bool {
|
||||
*self == ColorTransform::IDENTITY
|
||||
}
|
||||
|
||||
/// `self` applied after `inner`: the effect of `inner` nested inside `self`. Exact (no clamp
|
||||
/// between the two), so composing then applying is applying one then the other on colours
|
||||
/// that stay in range.
|
||||
pub fn concat(&self, inner: &ColorTransform) -> ColorTransform {
|
||||
let mut out = ColorTransform::IDENTITY;
|
||||
for i in 0..4 {
|
||||
out.mul[i] = self.mul[i] * inner.mul[i];
|
||||
out.add[i] = self.mul[i] * inner.add[i] + self.add[i];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn lerp(&self, o: &ColorTransform, t: f32) -> ColorTransform {
|
||||
let mut out = ColorTransform::IDENTITY;
|
||||
for i in 0..4 {
|
||||
out.mul[i] = anicraft_geom::lerp(self.mul[i], o.mul[i], t);
|
||||
out.add[i] = anicraft_geom::lerp(self.add[i], o.add[i], t);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Non-finite values drawn as a channel of 0 (as a NaN colour always was).
|
||||
pub fn sanitized(&self) -> ColorTransform {
|
||||
let mut out = *self;
|
||||
for i in 0..4 {
|
||||
if !(out.mul[i].is_finite() && out.add[i].is_finite()) {
|
||||
out.mul[i] = 0.0;
|
||||
out.add[i] = 0.0;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The transform applied to straight colour `c`, clamped to `0..=1` (NaN to 0).
|
||||
pub fn apply(&self, c: Rgba) -> Rgba {
|
||||
let f = self.sanitized();
|
||||
let ch = |v: f32, i: usize| {
|
||||
let x = fin(v, 0.0) * f.mul[i] + f.add[i];
|
||||
if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }
|
||||
};
|
||||
Rgba::new(ch(c.r, 0), ch(c.g, 1), ch(c.b, 2), ch(c.a, 3))
|
||||
}
|
||||
|
||||
/// The alpha multiplier when alpha is only multiplied (no alpha offset): what can fade a
|
||||
/// whole group at once.
|
||||
pub fn alpha_factor(&self) -> Option<f32> {
|
||||
(self.add[3] == 0.0).then(|| fin(self.mul[3], 0.0).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// The same transform with alpha untouched.
|
||||
pub fn without_alpha(&self) -> ColorTransform {
|
||||
let mut out = *self;
|
||||
out.mul[3] = 1.0;
|
||||
out.add[3] = 0.0;
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether colour channels change (anything beyond alpha).
|
||||
pub fn changes_colour(&self) -> bool {
|
||||
self.mul[..3].iter().any(|m| *m != 1.0) || self.add[..3].iter().any(|a| *a != 0.0)
|
||||
}
|
||||
|
||||
/// The alpha multiplier as an opacity estimate `0..=1` (picking, outlines).
|
||||
pub fn opacity(&self) -> f32 {
|
||||
fin(self.mul[3] + self.add[3], 0.0).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour effect styles of Properties' Style menu, in menu order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ColorStyle {
|
||||
None,
|
||||
Brightness,
|
||||
Tint,
|
||||
Advanced,
|
||||
Alpha,
|
||||
}
|
||||
|
||||
impl ColorStyle {
|
||||
pub const ALL: [ColorStyle; 5] = [ColorStyle::None, ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha];
|
||||
|
||||
/// The name used in files and commands.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
ColorStyle::None => "none",
|
||||
ColorStyle::Brightness => "brightness",
|
||||
ColorStyle::Tint => "tint",
|
||||
ColorStyle::Advanced => "advanced",
|
||||
ColorStyle::Alpha => "alpha",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ColorStyle::None => "None",
|
||||
ColorStyle::Brightness => "Brightness",
|
||||
ColorStyle::Tint => "Tint",
|
||||
ColorStyle::Advanced => "Advanced",
|
||||
ColorStyle::Alpha => "Alpha",
|
||||
}
|
||||
}
|
||||
pub fn from_key(s: &str) -> Option<ColorStyle> {
|
||||
let s = s.trim().to_ascii_lowercase();
|
||||
ColorStyle::ALL.into_iter().find(|x| x.key() == s)
|
||||
}
|
||||
}
|
||||
|
||||
/// An element's colour effect, as authored: one style and its values. Draw it through
|
||||
/// [`ColorEffect::transform`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default)]
|
||||
pub enum ColorEffect {
|
||||
#[default]
|
||||
None,
|
||||
/// Brightness −1..=1 (−100..=100 %).
|
||||
Brightness(f32),
|
||||
/// Tint colour (opaque) and amount 0..=1.
|
||||
Tint { color: Rgba, amount: f32 },
|
||||
/// Per-channel multiply and offset (Animate's Advanced).
|
||||
Advanced(ColorTransform),
|
||||
/// Alpha multiplier 0..=1.
|
||||
Alpha(f32),
|
||||
}
|
||||
|
||||
impl ColorEffect {
|
||||
pub fn style(&self) -> ColorStyle {
|
||||
match self {
|
||||
ColorEffect::None => ColorStyle::None,
|
||||
ColorEffect::Brightness(_) => ColorStyle::Brightness,
|
||||
ColorEffect::Tint { .. } => ColorStyle::Tint,
|
||||
ColorEffect::Advanced(_) => ColorStyle::Advanced,
|
||||
ColorEffect::Alpha(_) => ColorStyle::Alpha,
|
||||
}
|
||||
}
|
||||
|
||||
/// What it does to colour (its values clamped into the style's range first).
|
||||
pub fn transform(&self) -> ColorTransform {
|
||||
match self.sanitized() {
|
||||
ColorEffect::None => ColorTransform::IDENTITY,
|
||||
ColorEffect::Brightness(b) => ColorTransform::brightness(b),
|
||||
ColorEffect::Tint { color, amount } => ColorTransform::tint(color, amount),
|
||||
ColorEffect::Advanced(t) => t,
|
||||
ColorEffect::Alpha(a) => ColorTransform::alpha(a),
|
||||
}
|
||||
}
|
||||
|
||||
/// The values clamped into each style's range, non-finite ones to the style's rest value.
|
||||
pub fn sanitized(&self) -> ColorEffect {
|
||||
match *self {
|
||||
ColorEffect::None => ColorEffect::None,
|
||||
ColorEffect::Brightness(b) => ColorEffect::Brightness(fin(b, 0.0).clamp(-1.0, 1.0)),
|
||||
ColorEffect::Tint { color, amount } => ColorEffect::Tint { color: color.sanitized().with_alpha(1.0), amount: fin(amount, 0.0).clamp(0.0, 1.0) },
|
||||
ColorEffect::Advanced(t) => {
|
||||
let mut o = t;
|
||||
for i in 0..4 {
|
||||
o.mul[i] = fin(t.mul[i], 1.0).clamp(*ADVANCED_MUL.start(), *ADVANCED_MUL.end());
|
||||
o.add[i] = fin(t.add[i], 0.0).clamp(*ADVANCED_ADD.start(), *ADVANCED_ADD.end());
|
||||
}
|
||||
ColorEffect::Advanced(o)
|
||||
}
|
||||
ColorEffect::Alpha(a) => ColorEffect::Alpha(fin(a, 1.0).clamp(0.0, 1.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The alpha multiplier the effect has (1 for styles that leave alpha alone).
|
||||
pub fn alpha(&self) -> f32 {
|
||||
self.transform().mul[3]
|
||||
}
|
||||
|
||||
/// The effect with its alpha multiplier set to `a`, the rest kept (what ActionScript's
|
||||
/// `alpha` and `element.set_alpha` do): None and Alpha become Alpha(a); Advanced keeps
|
||||
/// its other channels; Brightness and Tint become Advanced when `a` isn't 1.
|
||||
pub fn with_alpha(&self, a: f32) -> ColorEffect {
|
||||
match *self {
|
||||
ColorEffect::None | ColorEffect::Alpha(_) => ColorEffect::Alpha(a),
|
||||
ColorEffect::Advanced(mut t) => {
|
||||
t.mul[3] = a;
|
||||
ColorEffect::Advanced(t)
|
||||
}
|
||||
ColorEffect::Brightness(_) | ColorEffect::Tint { .. } if a == 1.0 => *self,
|
||||
ColorEffect::Brightness(_) | ColorEffect::Tint { .. } => {
|
||||
let mut t = self.transform();
|
||||
t.mul[3] = a;
|
||||
ColorEffect::Advanced(t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The effect in `style`, as close to this one as that style can be: Advanced is exactly
|
||||
/// this transform; Alpha keeps the alpha multiplier; a tint keeps its colour; Brightness and
|
||||
/// Tint otherwise start where they change nothing (the look doesn't jump when the style
|
||||
/// changes, except to None).
|
||||
pub fn to_style(&self, style: ColorStyle) -> ColorEffect {
|
||||
if self.style() == style {
|
||||
return *self;
|
||||
}
|
||||
match style {
|
||||
ColorStyle::None => ColorEffect::None,
|
||||
ColorStyle::Advanced => ColorEffect::Advanced(self.transform()),
|
||||
ColorStyle::Alpha => ColorEffect::Alpha(fin(self.alpha(), 1.0).clamp(0.0, 1.0)),
|
||||
ColorStyle::Brightness => ColorEffect::Brightness(0.0),
|
||||
ColorStyle::Tint => ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 },
|
||||
}
|
||||
}
|
||||
|
||||
/// `inner` nested inside `self` as one effect (Break Apart): the other when either is None,
|
||||
/// alphas multiplied, else the composed transform as Advanced.
|
||||
pub fn nested(&self, inner: &ColorEffect) -> ColorEffect {
|
||||
match (self, inner) {
|
||||
(ColorEffect::None, x) | (x, ColorEffect::None) => *x,
|
||||
(ColorEffect::Alpha(a), ColorEffect::Alpha(b)) => ColorEffect::Alpha(a * b),
|
||||
(o, i) => ColorEffect::Advanced(o.transform().concat(&i.transform())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Alpha `a`, or None at full opacity.
|
||||
pub fn opacity(a: f32) -> ColorEffect {
|
||||
if a < 1.0 { ColorEffect::Alpha(a) } else { ColorEffect::None }
|
||||
}
|
||||
|
||||
/// The classic tween between two effects: within one style its values travel (a tint's
|
||||
/// colour and amount); None meets any style as that style's rest value; any other change of
|
||||
/// style travels in the Advanced space (multiplies and offsets), as in Animate.
|
||||
pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect {
|
||||
use anicraft_geom::lerp;
|
||||
let rest = |s: ColorStyle| ColorEffect::None.to_style(s);
|
||||
let (a, b) = match (self, o) {
|
||||
(ColorEffect::None, ColorEffect::None) => return ColorEffect::None,
|
||||
(ColorEffect::None, x) if x.style() != ColorStyle::Advanced => (rest(x.style()), *x),
|
||||
(x, ColorEffect::None) if x.style() != ColorStyle::Advanced => (*x, rest(x.style())),
|
||||
(x, y) => (*x, *y),
|
||||
};
|
||||
// A tint meeting None keeps its colour all the way.
|
||||
let (a, b) = match (a, b) {
|
||||
(ColorEffect::Tint { amount, .. }, ColorEffect::Tint { color, amount: k }) if self.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }),
|
||||
(ColorEffect::Tint { color, amount }, ColorEffect::Tint { amount: k, .. }) if o.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }),
|
||||
p => p,
|
||||
};
|
||||
match (a, b) {
|
||||
(ColorEffect::Brightness(x), ColorEffect::Brightness(y)) => ColorEffect::Brightness(lerp(x, y, t)),
|
||||
(ColorEffect::Alpha(x), ColorEffect::Alpha(y)) => ColorEffect::Alpha(lerp(x, y, t)),
|
||||
(ColorEffect::Tint { color: c1, amount: k1 }, ColorEffect::Tint { color: c2, amount: k2 }) => ColorEffect::Tint { color: c1.lerp(c2, t), amount: lerp(k1, k2, t) },
|
||||
(x, y) => ColorEffect::Advanced(x.transform().lerp(&y.transform(), t)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The effect several families make together (a motion tween keying more than one, or an
|
||||
/// older file's alpha with a tint): the one family when only one is in use, else Advanced
|
||||
/// with them composed (alpha outermost, then brightness, tint, advanced).
|
||||
pub fn compose(alpha: Option<f32>, brightness: Option<f32>, tint: Option<(Rgba, f32)>, advanced: Option<ColorTransform>) -> ColorEffect {
|
||||
let n = usize::from(alpha.is_some()) + usize::from(brightness.is_some()) + usize::from(tint.is_some()) + usize::from(advanced.is_some());
|
||||
if n == 1 {
|
||||
if let Some(a) = alpha {
|
||||
return ColorEffect::Alpha(a);
|
||||
}
|
||||
if let Some(b) = brightness {
|
||||
return ColorEffect::Brightness(b);
|
||||
}
|
||||
if let Some((color, amount)) = tint {
|
||||
return ColorEffect::Tint { color, amount };
|
||||
}
|
||||
if let Some(t) = advanced {
|
||||
return ColorEffect::Advanced(t);
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
return ColorEffect::None;
|
||||
}
|
||||
let mut t = advanced.unwrap_or(ColorTransform::IDENTITY);
|
||||
if let Some((c, k)) = tint {
|
||||
t = ColorTransform::tint(c, k).concat(&t);
|
||||
}
|
||||
if let Some(b) = brightness {
|
||||
t = ColorTransform::brightness(b).concat(&t);
|
||||
}
|
||||
if let Some(a) = alpha {
|
||||
t = ColorTransform::alpha(a).concat(&t);
|
||||
}
|
||||
ColorEffect::Advanced(t)
|
||||
}
|
||||
}
|
||||
|
||||
// ----- files ---------------------------------------------------------------------------------
|
||||
//
|
||||
// Every effect is written with the fields older AniCraft files have (`alpha`, `tint`,
|
||||
// `tint_amount`: the look as near as they can say it), so None, Alpha and Tint effects are
|
||||
// written exactly as before. `style` (and `brightness`, `multiply`, `offset`) are added only
|
||||
// when those fields alone would read back as something else. A file without `style` reads as
|
||||
// it always looked: a tint, an alpha, both (Advanced), or none.
|
||||
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
}
|
||||
fn white() -> Rgba {
|
||||
Rgba::WHITE
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Wire {
|
||||
#[serde(default = "one")]
|
||||
alpha: f32,
|
||||
#[serde(default = "white")]
|
||||
tint: Rgba,
|
||||
#[serde(default)]
|
||||
tint_amount: f32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
style: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
brightness: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
multiply: Option<[f32; 4]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
offset: Option<[f32; 4]>,
|
||||
}
|
||||
|
||||
/// What the legacy fields alone say.
|
||||
fn legacy(alpha: f32, tint: Rgba, amount: f32) -> ColorEffect {
|
||||
// Older builds clamped these where they drew them.
|
||||
let (alpha, amount) = (fin(alpha, 1.0).clamp(0.0, 1.0), fin(amount, 0.0).clamp(0.0, 1.0));
|
||||
let a = (alpha != 1.0).then_some(alpha);
|
||||
let t = (amount != 0.0).then_some((tint, amount));
|
||||
ColorEffect::compose(a, None, t, None)
|
||||
}
|
||||
|
||||
impl Serialize for ColorEffect {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
let mut w = Wire { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0, style: None, brightness: None, multiply: None, offset: None };
|
||||
match *self {
|
||||
ColorEffect::None => {}
|
||||
ColorEffect::Alpha(a) => w.alpha = a,
|
||||
ColorEffect::Tint { color, amount } => (w.tint, w.tint_amount) = (color, amount),
|
||||
ColorEffect::Brightness(b) => {
|
||||
(w.tint, w.tint_amount) = (if b >= 0.0 { Rgba::WHITE } else { Rgba::BLACK }, b.abs());
|
||||
w.brightness = Some(b);
|
||||
}
|
||||
ColorEffect::Advanced(t) => {
|
||||
w.alpha = t.mul[3];
|
||||
(w.multiply, w.offset) = (Some(t.mul), Some(t.add));
|
||||
}
|
||||
}
|
||||
if legacy(w.alpha, w.tint, w.tint_amount) != *self {
|
||||
w.style = Some(self.style().key().to_string());
|
||||
}
|
||||
w.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ColorEffect {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let w = Wire::deserialize(d)?;
|
||||
let fx = match w.style.as_deref().and_then(ColorStyle::from_key) {
|
||||
None => legacy(w.alpha, w.tint, w.tint_amount),
|
||||
Some(ColorStyle::None) => ColorEffect::None,
|
||||
Some(ColorStyle::Alpha) => ColorEffect::Alpha(w.alpha),
|
||||
Some(ColorStyle::Tint) => ColorEffect::Tint { color: w.tint, amount: w.tint_amount },
|
||||
Some(ColorStyle::Brightness) => ColorEffect::Brightness(w.brightness.unwrap_or(0.0)),
|
||||
Some(ColorStyle::Advanced) => ColorEffect::Advanced(ColorTransform { mul: w.multiply.unwrap_or([1.0; 4]), add: w.offset.unwrap_or([0.0; 4]) }),
|
||||
};
|
||||
Ok(fx.sanitized())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn close(a: Rgba, b: Rgba) -> bool {
|
||||
(a.r - b.r).abs() < 1e-5 && (a.g - b.g).abs() < 1e-5 && (a.b - b.b).abs() < 1e-5 && (a.a - b.a).abs() < 1e-5
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_are_the_transforms_animate_documents() {
|
||||
let c = Rgba::new(0.4, 0.2, 0.8, 1.0);
|
||||
// Brightness +60 %: towards white; −50 %: towards black.
|
||||
assert!(close(ColorEffect::Brightness(0.6).transform().apply(c), Rgba::new(0.4 * 0.4 + 0.6, 0.2 * 0.4 + 0.6, 0.8 * 0.4 + 0.6, 1.0)));
|
||||
assert!(close(ColorEffect::Brightness(-0.5).transform().apply(c), Rgba::new(0.2, 0.1, 0.4, 1.0)));
|
||||
// Tint 25 % red.
|
||||
let t = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.25 }.transform().apply(c);
|
||||
assert!(close(t, Rgba::new(0.4 * 0.75 + 0.25, 0.15, 0.6, 1.0)));
|
||||
// Advanced: red ×50 %, green +51 (0.2), alpha ×80 % −25.5 (−0.1); clamped.
|
||||
let adv = ColorTransform { mul: [0.5, 1.0, 1.0, 0.8], add: [0.0, 0.2, 0.5, -0.1] };
|
||||
assert!(close(adv.apply(c), Rgba::new(0.2, 0.4, 1.0, 0.7)));
|
||||
assert!(close(ColorEffect::Alpha(0.3).transform().apply(c), c.with_alpha(0.3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composition_is_exact() {
|
||||
let outer = ColorTransform::tint(Rgba::new(0.0, 0.5, 1.0, 1.0), 0.4);
|
||||
let inner = ColorTransform { mul: [0.5, -0.2, 0.9, 0.7], add: [0.1, 0.6, 0.0, 0.05] };
|
||||
let c = Rgba::new(0.3, 0.6, 0.2, 0.9);
|
||||
assert!(close(outer.concat(&inner).apply(c), outer.apply(inner.apply(c))));
|
||||
assert_eq!(ColorTransform::IDENTITY.concat(&inner), inner);
|
||||
assert_eq!(inner.concat(&ColorTransform::IDENTITY), inner);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_draws_a_zero_channel() {
|
||||
let t = ColorTransform { mul: [f32::NAN, 1.0, 1.0, 1.0], add: [0.0; 4] };
|
||||
assert_eq!(t.apply(Rgba::WHITE), Rgba::new(0.0, 1.0, 1.0, 1.0));
|
||||
assert_eq!(ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN }.sanitized(), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tweens_within_a_style_and_across_styles() {
|
||||
let red = Rgba::new(1.0, 0.0, 0.0, 1.0);
|
||||
let blue = Rgba::new(0.0, 0.0, 1.0, 1.0);
|
||||
assert_eq!(ColorEffect::Alpha(1.0).lerp(&ColorEffect::Alpha(0.0), 0.25), ColorEffect::Alpha(0.75));
|
||||
assert_eq!(ColorEffect::None.lerp(&ColorEffect::Brightness(-1.0), 0.5), ColorEffect::Brightness(-0.5));
|
||||
assert_eq!(ColorEffect::None.lerp(&ColorEffect::Tint { color: red, amount: 1.0 }, 0.5), ColorEffect::Tint { color: red, amount: 0.5 });
|
||||
assert_eq!(ColorEffect::Tint { color: red, amount: 1.0 }.lerp(&ColorEffect::Tint { color: blue, amount: 1.0 }, 0.5), ColorEffect::Tint { color: Rgba::new(0.5, 0.0, 0.5, 1.0), amount: 1.0 });
|
||||
// A style change travels in the advanced space: halfway between the two transforms.
|
||||
let a = ColorEffect::Tint { color: red, amount: 1.0 };
|
||||
let b = ColorEffect::Alpha(0.5);
|
||||
let mid = a.lerp(&b, 0.5);
|
||||
assert_eq!(mid.style(), ColorStyle::Advanced);
|
||||
assert_eq!(mid.transform(), a.transform().lerp(&b.transform(), 0.5));
|
||||
// The ends look like the keyframes.
|
||||
assert_eq!(a.lerp(&b, 0.0).transform(), a.transform());
|
||||
assert_eq!(a.lerp(&b, 1.0).transform(), b.transform());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_changes_keep_the_look_where_they_can() {
|
||||
let fx = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.4 };
|
||||
assert_eq!(fx.to_style(ColorStyle::Advanced).transform(), fx.transform());
|
||||
assert_eq!(ColorEffect::Alpha(0.3).to_style(ColorStyle::Advanced).alpha(), 0.3);
|
||||
assert_eq!(ColorEffect::Advanced(ColorTransform::alpha(0.3)).to_style(ColorStyle::Alpha), ColorEffect::Alpha(0.3));
|
||||
assert!(fx.to_style(ColorStyle::Brightness).transform().is_identity());
|
||||
assert_eq!(fx.with_alpha(0.5).transform(), ColorTransform::alpha(0.5).concat(&fx.transform()));
|
||||
assert_eq!(fx.with_alpha(1.0), fx);
|
||||
assert_eq!(ColorEffect::None.with_alpha(0.2), ColorEffect::Alpha(0.2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_files_read_as_they_looked_and_simple_effects_write_as_before() {
|
||||
let read = |s: &str| serde_json::from_str::<ColorEffect>(s).unwrap();
|
||||
let white = r#""tint":{"r":1.0,"g":1.0,"b":1.0,"a":1.0}"#;
|
||||
assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#)), ColorEffect::None);
|
||||
assert_eq!(read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#)), ColorEffect::Alpha(0.5));
|
||||
assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.25}}"#)), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.25 });
|
||||
let both = read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.25}}"#));
|
||||
assert_eq!(both.transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::WHITE, 0.25)));
|
||||
// Byte for byte as before.
|
||||
assert_eq!(serde_json::to_string(&ColorEffect::None).unwrap(), format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#));
|
||||
assert_eq!(serde_json::to_string(&ColorEffect::Alpha(0.5)).unwrap(), format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#));
|
||||
for fx in [
|
||||
ColorEffect::None,
|
||||
ColorEffect::Alpha(1.0),
|
||||
ColorEffect::Alpha(0.25),
|
||||
ColorEffect::Brightness(-0.5),
|
||||
ColorEffect::Brightness(0.0),
|
||||
ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.0 },
|
||||
ColorEffect::Tint { color: Rgba::new(0.0, 0.5, 1.0, 1.0), amount: 0.75 },
|
||||
ColorEffect::Advanced(ColorTransform { mul: [0.5, -1.0, 1.0, 0.75], add: [0.25, 0.0, -0.5, 0.125] }),
|
||||
ColorEffect::Advanced(ColorTransform::IDENTITY),
|
||||
] {
|
||||
let json = serde_json::to_string(&fx).unwrap();
|
||||
assert_eq!(read(&json), fx, "{json}");
|
||||
}
|
||||
// Brightness still reads, in older builds, as the tint it looks like.
|
||||
let json = serde_json::to_string(&ColorEffect::Brightness(-0.5)).unwrap();
|
||||
assert!(json.contains(r#""tint_amount":0.5"#) && json.contains(r#""style":"brightness""#), "{json}");
|
||||
// Out-of-range values in a file are clamped; an unknown style reads as the legacy fields.
|
||||
assert_eq!(read(r#"{"style":"brightness","brightness":7}"#), ColorEffect::Brightness(1.0));
|
||||
assert_eq!(read(r#"{"style":"sepia","alpha":0.5}"#), ColorEffect::Alpha(0.5));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Timeline evaluation: `(document, frame) -> DisplayList`. Pure, deterministic, no caching.
|
||||
|
||||
use crate::camera::Camera;
|
||||
use crate::nine_slice::Slicing;
|
||||
use crate::player::PlayerState;
|
||||
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
|
||||
use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, MaskMode, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
|
||||
use anicraft_geom::walk::PathWalk;
|
||||
use anicraft_geom::{Affine, FillRule, Path};
|
||||
use std::borrow::Cow;
|
||||
@@ -20,7 +21,8 @@ pub struct DisplayItem {
|
||||
pub fill: Option<Paint>,
|
||||
pub stroke: Option<Stroke>,
|
||||
pub fill_rule: FillRule,
|
||||
pub color: ColorEffect,
|
||||
/// The colour transform of every instance around it, composed (ADR 0056).
|
||||
pub color: ColorTransform,
|
||||
/// The top-level layer and element this item came from (for picking).
|
||||
pub layer: LayerId,
|
||||
pub element: ElementId,
|
||||
@@ -28,11 +30,13 @@ pub struct DisplayItem {
|
||||
pub outline: Option<Rgba>,
|
||||
/// Drawn only inside this clip (an index into [`DisplayList::clip_parents`]).
|
||||
pub clip: Option<u32>,
|
||||
/// Mask artwork: not drawn; its fill area (strokes and opacity ignored) forms this clip.
|
||||
/// Mask artwork: not drawn; it forms this clip: its fill area (strokes and opacity
|
||||
/// ignored), or for a soft clip ([`DisplayList::clip_mode`]) its opacity or brightness as
|
||||
/// drawn.
|
||||
pub masks: Option<u32>,
|
||||
/// Guide artwork: shown while editing, never in output.
|
||||
pub guide: bool,
|
||||
/// The innermost group this item fades with (see [`DisplayList::groups`]); `color.alpha`
|
||||
/// The innermost group this item fades with (see [`DisplayList::groups`]); `color`
|
||||
/// leaves out the groups' opacity.
|
||||
pub group: Option<u32>,
|
||||
/// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied).
|
||||
@@ -40,6 +44,10 @@ pub struct DisplayItem {
|
||||
/// Whether `image` is filtered between its pixels (the bitmap's Allow Smoothing, ADR 0050);
|
||||
/// off, each pixel is a hard-edged square.
|
||||
pub smooth: bool,
|
||||
/// A warped bitmap fill (ADR 0079): the mesh, in the item's local space, that carries the
|
||||
/// image as drawn (`rest`) to where it shows (`shown`); renderers draw the image through
|
||||
/// its triangles. `None` for everything else (a warped shape's path is already bent).
|
||||
pub warp: Option<Arc<crate::warp::WarpMesh>>,
|
||||
}
|
||||
|
||||
/// Back-to-front list of shapes.
|
||||
@@ -49,6 +57,9 @@ pub struct DisplayList {
|
||||
/// One entry per clip: the enclosing clip it is intersected with. A parent always has a
|
||||
/// lower index than its children. A clip with no mask artwork hides everything in it.
|
||||
pub clip_parents: Vec<Option<u32>>,
|
||||
/// How each clip's artwork reveals (ADR 0070), by clip index. Sparse: a clip past its end
|
||||
/// is [`MaskMode::Coverage`], so lists that don't care leave it empty.
|
||||
pub clip_modes: Vec<MaskMode>,
|
||||
/// Groups that fade as one: a symbol instance with an opacity below 1 composites its
|
||||
/// items together, then blends the result at `alpha`, so overlapping parts don't show
|
||||
/// through each other. A group's items are one unbroken run of `items`, nested runs for
|
||||
@@ -70,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 };
|
||||
@@ -105,6 +134,9 @@ impl DisplayList {
|
||||
let gbase = self.groups.len() as u32;
|
||||
let gshift = |g: Option<u32>| g.map(|g| g + gbase);
|
||||
self.clip_parents.extend(other.clip_parents.into_iter().map(shift));
|
||||
for (i, m) in other.clip_modes.into_iter().enumerate() {
|
||||
self.set_clip_mode(base + i as u32, m);
|
||||
}
|
||||
self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) }));
|
||||
self.items.extend(other.items.into_iter().map(|mut i| {
|
||||
i.clip = shift(i.clip);
|
||||
@@ -176,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
|
||||
}
|
||||
@@ -258,7 +291,14 @@ fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>)
|
||||
fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option<Element> {
|
||||
let kind = match (&a.kind, &b.kind) {
|
||||
(ElementKind::Shape(sa), ElementKind::Shape(sb)) => {
|
||||
let path = if Arc::ptr_eq(&sa.path, &sb.path) && 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())
|
||||
@@ -273,12 +313,33 @@ 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 })
|
||||
}
|
||||
(ElementKind::Symbol { symbol: s1, .. }, ElementKind::Symbol { symbol: s2, .. }) if s1 == s2 => a.kind.clone(),
|
||||
// Text tweens its placement and colour effect; the words stay the first keyframe's.
|
||||
(ElementKind::Text(_), ElementKind::Text(_)) => a.kind.clone(),
|
||||
(ElementKind::Camera, ElementKind::Camera) => ElementKind::Camera,
|
||||
// A group tweens its placement and colour effect, and its members pair by order, layer by
|
||||
// layer, tweening as they would on their own (ADR 0073); a member without a partner holds.
|
||||
(ElementKind::Group { members: ma }, ElementKind::Group { members: mb }) => {
|
||||
let mut members = ma.clone();
|
||||
for (la, lb) in members.layers.iter_mut().zip(&mb.layers) {
|
||||
let (Some(ka), Some(kb)) = (la.keyframe_at(0), lb.keyframe_at(0)) else { continue };
|
||||
let els: Vec<Arc<Element>> = ka.elements.iter().enumerate().map(|(i, x)| kb.elements.get(i).and_then(|y| interpolate(x, y, 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();
|
||||
@@ -293,11 +354,14 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft
|
||||
struct Ctx {
|
||||
/// Local → stage transform and colour effect of the enclosing instance.
|
||||
xf: Affine,
|
||||
color: ColorEffect,
|
||||
color: ColorTransform,
|
||||
depth: usize,
|
||||
/// The top-level layer and element everything inside belongs to (for picking).
|
||||
root: Option<(LayerId, ElementId)>,
|
||||
outline: Option<Rgba>,
|
||||
/// The stage as edited (ADR 0061): layers in outline mode are drawn as outlines. Off for
|
||||
/// the movie (every export, the player): View as Outlines is an editing aid.
|
||||
stage: bool,
|
||||
/// The clip everything inside is drawn within.
|
||||
clip: Option<u32>,
|
||||
/// Set while evaluating mask artwork: everything inside forms this clip.
|
||||
@@ -309,16 +373,20 @@ struct Ctx {
|
||||
/// The camera the scene's layers are seen through (main timeline only; each layer's
|
||||
/// transform comes from it and the layer's depth, and `xf` is ignored).
|
||||
camera: Option<Camera>,
|
||||
/// The 9-slice scaling of the instance whose timeline this is (ADR 0055): its own shapes go
|
||||
/// through it, in place of the scale in `xf`. Not passed on to nested symbols.
|
||||
slice: Option<Slicing>,
|
||||
}
|
||||
|
||||
impl Ctx {
|
||||
fn top(xf: Affine) -> Ctx {
|
||||
Ctx { xf, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None }
|
||||
Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None }
|
||||
}
|
||||
|
||||
/// A main timeline seen through `camera`: its tint colours everything.
|
||||
fn through(camera: Option<Camera>) -> Ctx {
|
||||
let mut cx = Ctx::top(Affine::IDENTITY);
|
||||
cx.stage = false;
|
||||
if let Some(c) = camera {
|
||||
cx.color = c.color();
|
||||
cx.camera = Some(c);
|
||||
@@ -357,7 +425,7 @@ pub fn guide_walk(guide: &Layer, frame: u32) -> Option<PathWalk> {
|
||||
}
|
||||
PathWalk::new(&pts)
|
||||
}
|
||||
ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera => None,
|
||||
ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -388,8 +456,10 @@ 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);
|
||||
@@ -413,104 +483,278 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
|
||||
// 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 });
|
||||
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.
|
||||
let layer_xf = cx.camera.map_or(cx.xf, |c| c.view(&doc.stage, layer.depth));
|
||||
let lc = LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf };
|
||||
for el in elements.iter() {
|
||||
// In the player, a symbol instance has its own path, and maybe properties a script set.
|
||||
let child = match (&el.kind, play) {
|
||||
(ElementKind::Symbol { .. }, Some(p)) => Some(p.child(el.id)),
|
||||
_ => None,
|
||||
eval_element(doc, cx, &lc, el, out, play);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer an element is drawn on, as [`eval_element`] needs it.
|
||||
#[derive(Clone, Copy)]
|
||||
struct LayerCtx<'a> {
|
||||
layer: &'a Layer,
|
||||
frame: u32,
|
||||
/// The first frame of the keyframe the element is on.
|
||||
kf_start: u32,
|
||||
clip: Option<u32>,
|
||||
masks: Option<u32>,
|
||||
guide: bool,
|
||||
outline: Option<Rgba>,
|
||||
/// The layer's space (and, inside a group, the group's) to stage space.
|
||||
xf: Affine,
|
||||
}
|
||||
|
||||
fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: &mut DisplayList, play: Option<&Play<'_>>) {
|
||||
let LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf } = *lc;
|
||||
// In the player, a symbol instance has its own path, and maybe properties a script set.
|
||||
let child = match (&el.kind, play) {
|
||||
(ElementKind::Symbol { .. }, Some(p)) => Some(p.child(el.id)),
|
||||
// So is a dynamic or input text field (ADR 0066).
|
||||
(ElementKind::Text(t), Some(p)) if t.field.is_some() => Some(p.child(el.id)),
|
||||
_ => None,
|
||||
};
|
||||
let set;
|
||||
let el: &Element = match child.as_ref().and_then(|c| c.state.props.get(&c.path)) {
|
||||
Some(ov) if !ov.shown() => return,
|
||||
Some(ov) => {
|
||||
set = ov.apply(el);
|
||||
&set
|
||||
}
|
||||
None => el,
|
||||
};
|
||||
let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id));
|
||||
let xf = layer_xf.mul(&el.transform);
|
||||
let fx = el.color.transform();
|
||||
let color = cx.color.concat(&fx);
|
||||
match &el.kind {
|
||||
ElementKind::Shape(s) => {
|
||||
// Inside a 9-slice instance, the shape's outline is cut and mapped (bitmap
|
||||
// fills scale normally, as in Animate).
|
||||
let sliced = cx.slice.filter(|_| !matches!(s.fill, Some(Paint::Bitmap { .. }))).map(|sl| sliced_shape(s, &el.transform, &sl));
|
||||
let is_sliced = sliced.is_some();
|
||||
let (path, transform, fill, stroke) = match sliced {
|
||||
Some(x) => x,
|
||||
None => (s.path.clone(), xf, s.fill.clone(), s.stroke.clone()),
|
||||
};
|
||||
let set;
|
||||
let el: &Element = match child.as_ref().and_then(|c| c.state.props.get(&c.path)) {
|
||||
Some(ov) if !ov.shown() => continue,
|
||||
Some(ov) => {
|
||||
set = ov.apply(el);
|
||||
&set
|
||||
out.items.push(DisplayItem {
|
||||
path,
|
||||
transform,
|
||||
fill,
|
||||
stroke,
|
||||
fill_rule: s.fill_rule,
|
||||
color,
|
||||
layer: root_layer,
|
||||
element: root_el,
|
||||
outline: layer_outline,
|
||||
clip,
|
||||
masks,
|
||||
guide,
|
||||
group: cx.group,
|
||||
image: match &s.fill {
|
||||
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels),
|
||||
_ => None,
|
||||
},
|
||||
smooth: match &s.fill {
|
||||
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing),
|
||||
_ => true,
|
||||
},
|
||||
// A bitmap bent by its warp is drawn through the mesh (ADR 0079).
|
||||
warp: match &s.fill {
|
||||
Some(Paint::Bitmap { .. }) if !is_sliced => s.live_warp().filter(|w| !w.at_rest()).and_then(crate::warp::Warp::mesh).map(Arc::new),
|
||||
_ => None,
|
||||
},
|
||||
});
|
||||
}
|
||||
ElementKind::Text(t) => {
|
||||
let item = |path: Arc<Path>, transform: Affine, fill: Option<Paint>, stroke: Option<Stroke>, clip: Option<u32>, masks: Option<u32>| DisplayItem {
|
||||
path,
|
||||
transform,
|
||||
fill,
|
||||
stroke,
|
||||
fill_rule: FillRule::NonZero,
|
||||
color,
|
||||
layer: root_layer,
|
||||
element: root_el,
|
||||
outline: layer_outline,
|
||||
clip,
|
||||
masks,
|
||||
guide,
|
||||
group: cx.group,
|
||||
image: None,
|
||||
smooth: true,
|
||||
warp: None,
|
||||
};
|
||||
match &t.field {
|
||||
// Mask artwork: a field's text masks; its box and border don't.
|
||||
Some(f) if masks.is_none() => {
|
||||
let live = child.as_ref().map(|c| (c.state.fields.get(&c.path), c.state.focus.as_deref() == Some(c.path.as_slice())));
|
||||
field_items(t, f, live, xf, clip, out, item);
|
||||
}
|
||||
None => el,
|
||||
};
|
||||
let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id));
|
||||
let xf = layer_xf.mul(&el.transform);
|
||||
let color = cx.color.concat(&el.color);
|
||||
match &el.kind {
|
||||
ElementKind::Shape(s) => out.items.push(DisplayItem {
|
||||
path: s.path.clone(),
|
||||
transform: xf,
|
||||
fill: s.fill.clone(),
|
||||
stroke: s.stroke.clone(),
|
||||
fill_rule: s.fill_rule,
|
||||
color,
|
||||
layer: root_layer,
|
||||
element: root_el,
|
||||
outline: layer_outline,
|
||||
clip,
|
||||
masks,
|
||||
guide,
|
||||
group: cx.group,
|
||||
image: match &s.fill {
|
||||
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels),
|
||||
_ => None,
|
||||
},
|
||||
smooth: match &s.fill {
|
||||
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing),
|
||||
_ => true,
|
||||
},
|
||||
}),
|
||||
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,
|
||||
smooth: true,
|
||||
}),
|
||||
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() || !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 });
|
||||
let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx };
|
||||
(cx.color.concat(&inner), Some(gid))
|
||||
} else {
|
||||
(color, cx.group)
|
||||
};
|
||||
// A symbol with 9-slice guides, scaled: its shapes are sliced (ADR 0055).
|
||||
let slice = crate::nine_slice::slicing(doc, sym, &el.transform).map(|s| Slicing { post: layer_xf.mul(&s.post), ..s });
|
||||
let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, stage: cx.stage, clip, masks, guide, group, camera: None, slice };
|
||||
eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The highlight behind selected text in a focused field.
|
||||
pub const SELECTION: Rgba = Rgba::new(0.62, 0.78, 1.0, 1.0);
|
||||
|
||||
/// A dynamic or input field's items (ADR 0066): its background, its text cut to its box, the
|
||||
/// selection and caret when it has the keyboard, and its border. `live` is its state in the
|
||||
/// player (and whether it is focused); without one, it shows its authored outline.
|
||||
fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option<&crate::field::FieldState>, bool)>, xf: Affine, clip: Option<u32>, out: &mut DisplayList, item: impl Fn(Arc<Path>, Affine, Option<Paint>, Option<Stroke>, Option<u32>, Option<u32>) -> DisplayItem) {
|
||||
let (w, h) = (t.box_width.max(0.0), t.box_height.max(0.0));
|
||||
let rect = Arc::new(Path::rect(0.0, 0.0, w, h));
|
||||
if f.background {
|
||||
out.items.push(item(rect.clone(), xf, Some(Paint::Solid(f.background_color)), None, clip, None));
|
||||
}
|
||||
// The box clips what is inside it.
|
||||
let inner = out.clip_parents.len() as u32;
|
||||
out.clip_parents.push(clip);
|
||||
out.items.push(item(rect.clone(), xf, Some(Paint::Solid(Rgba::BLACK)), None, clip, Some(inner)));
|
||||
let (state, focused) = live.unwrap_or((None, false));
|
||||
let scroll = state.map_or(anicraft_geom::Vec2::ZERO, |s| s.scroll);
|
||||
let text_xf = xf.mul(&Affine::translate(-scroll.x, -scroll.y));
|
||||
let look = state.and_then(|s| s.look.as_deref());
|
||||
// The selection, under the text.
|
||||
if let (true, Some(st), Some(look)) = (focused, state, look) {
|
||||
let (a, b) = st.selection();
|
||||
if a != b {
|
||||
for (row, l) in look.lines.iter().enumerate() {
|
||||
let (from, to) = (a.max(l.start), b.min(l.end));
|
||||
if from > to || (from == to && !(a <= l.end && b > l.end)) {
|
||||
continue;
|
||||
}
|
||||
let (x0, x1) = (l.x_at(from), if b > l.end { l.x_at(l.end) + t.size * 0.25 } else { l.x_at(to) });
|
||||
let y = row as f32 * look.line_height;
|
||||
let r = Path::rect(crate::FIELD_GUTTER + x0, crate::FIELD_GUTTER + y, (x1 - x0).max(0.0), look.line_height);
|
||||
out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(SELECTION)), None, Some(inner), None));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The text: laid out by the player when it changed, else the authored outline (a field whose
|
||||
// text changed but couldn't be laid out shows none).
|
||||
let outline = match (state.and_then(|s| s.text.as_ref()), look) {
|
||||
(_, Some(l)) => Some(l.outline.clone()),
|
||||
(None, None) => Some(t.outline.clone()),
|
||||
(Some(_), None) => None,
|
||||
};
|
||||
if let Some(path) = outline {
|
||||
out.items.push(item(path, text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None));
|
||||
}
|
||||
// The caret, in an input field with the keyboard and nothing selected.
|
||||
if let (true, Some(st), crate::TextKind::Input) = (focused, state, f.kind)
|
||||
&& st.caret == st.anchor
|
||||
{
|
||||
let (at, lh) = look.map_or((anicraft_geom::Vec2::ZERO, t.size * 1.2), |l| (l.caret_at(st.caret), l.line_height));
|
||||
let r = Path::rect(crate::FIELD_GUTTER + at.x - 0.5, crate::FIELD_GUTTER + at.y, 1.0, lh);
|
||||
out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None));
|
||||
}
|
||||
if f.border {
|
||||
let mut s = Stroke::new(f.border_color, 1.0);
|
||||
s.style.join = crate::Join::Miter;
|
||||
out.items.push(item(rect, xf, None, Some(s), clip, None));
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape inside a 9-slice instance (ADR 0055): its outline placed by its own transform, then
|
||||
/// cut at the guides and mapped piecewise; drawn by the instance's transform without its scale.
|
||||
/// The stroke keeps its width (times the shape's own scale inside the symbol); gradients follow
|
||||
/// the map, their size the shape's own scale times the instance's.
|
||||
fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc<Path>, Affine, Option<Paint>, Option<Stroke>) {
|
||||
let path = Arc::new(anicraft_geom::slice::slice_path(&s.path, own, &sl.map));
|
||||
let k = own.mean_scale();
|
||||
let stroke = s.stroke.as_ref().map(|st| if (k - 1.0).abs() > 1e-6 { st.scaled(k) } else { st.clone() });
|
||||
let at = |p: anicraft_geom::Vec2| sl.map.map(own.apply(p));
|
||||
let size = k * sl.scale.mean_scale();
|
||||
let fill = s.fill.as_ref().map(|f| {
|
||||
let mut f = f.clone();
|
||||
match &mut f {
|
||||
Paint::Linear { start, end, .. } => {
|
||||
*start = at(*start);
|
||||
*end = at(*end);
|
||||
}
|
||||
Paint::Radial { center, radius, matrix, .. } => {
|
||||
// The ring's shape (its matrix's linear part) stays, round the mapped centre.
|
||||
let c = at(matrix.apply(*center));
|
||||
let l = Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] };
|
||||
if *matrix != Affine::IDENTITY {
|
||||
*matrix = Affine::translate(c.x, c.y).mul(&l).mul(&Affine::translate(-c.x, -c.y));
|
||||
}
|
||||
*center = c;
|
||||
*radius *= size;
|
||||
}
|
||||
Paint::Solid(_) | Paint::Bitmap { .. } => {}
|
||||
}
|
||||
f
|
||||
});
|
||||
(path, sl.post, fill, stroke)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "eval_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use crate::{Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind};
|
||||
use crate::{ColorEffect, Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind};
|
||||
|
||||
fn shape_el(id: u64, x: f32) -> Element {
|
||||
Element {
|
||||
@@ -85,7 +85,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() {
|
||||
},
|
||||
);
|
||||
tl.layers.push(Arc::new(layer));
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, timeline: tl }));
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "loop".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: tl }));
|
||||
push(
|
||||
layer0(&mut d),
|
||||
0,
|
||||
@@ -93,7 +93,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() {
|
||||
id: ElementId(60),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(100.0, 0.0),
|
||||
color: ColorEffect { alpha: 0.5, ..Default::default() },
|
||||
color: ColorEffect::Alpha(0.5),
|
||||
kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() },
|
||||
},
|
||||
);
|
||||
@@ -101,7 +101,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() {
|
||||
assert_eq!(dl.items.len(), MAX_SYMBOL_DEPTH);
|
||||
assert_eq!(dl.items[0].transform.translation().x, 100.0);
|
||||
// The instance's opacity is its group's: it fades as one.
|
||||
assert_eq!((dl.items[0].color.alpha, dl.effective_alpha(&dl.items[0])), (1.0, 0.5));
|
||||
assert_eq!((dl.items[0].color.mul[3], dl.effective_alpha(&dl.items[0])), (1.0, 0.5));
|
||||
assert_eq!(dl.groups.len(), 1);
|
||||
assert!(dl.items.iter().all(|i| i.element == ElementId(60)));
|
||||
}
|
||||
@@ -140,7 +140,7 @@ fn masks_inside_symbols_nest_in_the_instance_clip() {
|
||||
// The main timeline's masked layer holds an instance of a symbol that has its own mask.
|
||||
let mut d = mask_doc();
|
||||
let sid = SymbolId(99);
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, timeline: mask_doc().timeline(0).clone() }));
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "masked inside".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: mask_doc().timeline(0).clone() }));
|
||||
let inst = Element {
|
||||
id: ElementId(60),
|
||||
name: String::new(),
|
||||
@@ -156,6 +156,27 @@ fn masks_inside_symbols_nest_in_the_instance_clip() {
|
||||
assert_eq!(inner, vec![(Some(0), None), (Some(1), None), (Some(1), None), (Some(0), Some(1))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_soft_mask_layer_gives_its_clip_its_mode() {
|
||||
let mut d = mask_doc();
|
||||
assert_eq!((evaluate(&d, 0).clip_mode(0), evaluate(&d, 0).clip_modes.len()), (crate::MaskMode::Coverage, 0), "coverage stays implicit");
|
||||
Arc::make_mut(&mut d.timeline_mut(0).layers[0]).mask_mode = crate::MaskMode::Luminance;
|
||||
let dl = evaluate(&d, 0);
|
||||
assert_eq!(dl.clip_mode(0), crate::MaskMode::Luminance);
|
||||
// Appended lists keep their modes on their renumbered clips.
|
||||
let mut a = evaluate(&mask_doc(), 0);
|
||||
a.append(dl);
|
||||
assert_eq!((a.clip_mode(0), a.clip_mode(1)), (crate::MaskMode::Coverage, crate::MaskMode::Luminance));
|
||||
// The mode is saved only when it isn't coverage, and older files (without it) open as coverage.
|
||||
let json = serde_json::to_string(&*d.timeline(0).layers[0]).unwrap();
|
||||
assert!(json.contains("\"mask_mode\":\"luminance\""), "{json}");
|
||||
let plain = serde_json::to_string(&*mask_doc().timeline(0).layers[0]).unwrap();
|
||||
assert!(!plain.contains("mask_mode"));
|
||||
let back: Layer = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.mask_mode, crate::MaskMode::Luminance);
|
||||
assert_eq!(serde_json::from_str::<Layer>(&plain).unwrap().mask_mode, crate::MaskMode::Coverage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appending_lists_renumbers_clips() {
|
||||
let d = mask_doc();
|
||||
@@ -295,7 +316,7 @@ fn movie_clips_play_their_own_timeline_graphics_keep_step_buttons_hold_up() {
|
||||
})
|
||||
.collect();
|
||||
let mut d = Document::default();
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, timeline: Timeline { layers: vec![Arc::new(st)] } }));
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(st)] } }));
|
||||
// The same instance on two keyframes back to back (frames 0–4 and 5–11), moved on the second.
|
||||
let inst = |x: f32| Element {
|
||||
id: ElementId(60),
|
||||
@@ -352,7 +373,7 @@ fn a_motion_tween_drives_each_property_on_its_own_curve() {
|
||||
let d = motion_doc();
|
||||
let at = |f| {
|
||||
let dl = evaluate(&d, f);
|
||||
(dl.items[0].transform.translation().x, dl.items[0].color.alpha)
|
||||
(dl.items[0].transform.translation().x, dl.items[0].color.mul[3])
|
||||
};
|
||||
assert_eq!(at(0), (0.0, 1.0));
|
||||
// X eases in over 0..12 (a quarter of the way at half time); alpha runs linearly over 0..23.
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//! Text fields while a movie plays (ADR 0066): what a dynamic or input field holds, where its
|
||||
//! caret and selection are, and the editing that keys and the pointer do to it.
|
||||
//!
|
||||
//! Everything here is pure data and pure functions, like the rest of the player: the same field,
|
||||
//! look and keys always give the same text, caret and selection. Laying text out needs the
|
||||
//! fonts, which live a layer above (`anicraft-text`), so the player asks its host for a
|
||||
//! [`FieldLook`] whenever a field's text changes and keeps it in the state; drawing a state then
|
||||
//! needs nothing else.
|
||||
|
||||
use crate::{FIELD_GUTTER, LineType, MAX_FIELD_CHARS, TextBlock, TextField, TextKind};
|
||||
use anicraft_geom::{Path, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// One laid-out line's characters and caret places (indices count `char`s of the shown text).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct CaretLine {
|
||||
/// The first character on the line and the boundary after its last.
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
/// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending; `x` from
|
||||
/// the text's left edge (the box's, less the gutter).
|
||||
pub stops: Vec<(u32, f32)>,
|
||||
}
|
||||
|
||||
impl CaretLine {
|
||||
/// The caret's x at boundary `i`.
|
||||
pub fn x_at(&self, i: u32) -> f32 {
|
||||
let mut x = self.stops.first().map_or(0.0, |s| s.1);
|
||||
for &(c, sx) in &self.stops {
|
||||
if c > i {
|
||||
break;
|
||||
}
|
||||
x = sx;
|
||||
}
|
||||
x
|
||||
}
|
||||
|
||||
/// The boundary nearest `x`.
|
||||
pub fn index_at(&self, x: f32) -> u32 {
|
||||
let mut best = (self.start, f32::INFINITY);
|
||||
for &(c, sx) in &self.stops {
|
||||
let d = (sx - x).abs();
|
||||
if d < best.1 {
|
||||
best = (c, d);
|
||||
}
|
||||
}
|
||||
best.0.clamp(self.start, self.end)
|
||||
}
|
||||
}
|
||||
|
||||
/// A field's text laid out: its outline (in the box's space, the gutter applied, as a text
|
||||
/// block's outline is) and where the caret can stand.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FieldLook {
|
||||
pub outline: Arc<Path>,
|
||||
/// Top line first; never empty.
|
||||
pub lines: Arc<[CaretLine]>,
|
||||
/// From one line's top to the next's.
|
||||
pub line_height: f32,
|
||||
/// The laid-out text's size (it may be bigger than the box, which clips it).
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
impl FieldLook {
|
||||
/// The line holding boundary `i`: the last that starts at or before it.
|
||||
pub fn line_of(&self, i: u32) -> usize {
|
||||
let mut at = 0;
|
||||
for (n, l) in self.lines.iter().enumerate() {
|
||||
if l.start <= i {
|
||||
at = n;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The caret's place at boundary `i`: x from the text's left, and the line's top.
|
||||
pub fn caret_at(&self, i: u32) -> Vec2 {
|
||||
let n = self.line_of(i);
|
||||
let x = self.lines.get(n).map_or(0.0, |l| l.x_at(i));
|
||||
Vec2::new(x, n as f32 * self.line_height)
|
||||
}
|
||||
|
||||
/// The boundary nearest a point in the text's space.
|
||||
pub fn index_at(&self, p: Vec2) -> u32 {
|
||||
let h = self.line_height.max(1e-3);
|
||||
let row = if p.y.is_finite() { (p.y / h).floor().max(0.0) as usize } else { 0 };
|
||||
let row = row.min(self.lines.len().saturating_sub(1));
|
||||
self.lines.get(row).map_or(0, |l| l.index_at(p.x))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a field holds while the movie plays.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct FieldState {
|
||||
/// Its text once a script or the viewer changed it; `None`: the timeline's own (so a
|
||||
/// keyframe with other words still shows them).
|
||||
pub text: Option<String>,
|
||||
/// The text laid out (the host's work); `None` while it shows the authored outline.
|
||||
pub look: Option<Arc<FieldLook>>,
|
||||
/// The caret and the other end of the selection (character boundaries; equal: nothing
|
||||
/// selected).
|
||||
pub caret: u32,
|
||||
pub anchor: u32,
|
||||
/// How far the text has scrolled to keep the caret in view (pixels, never negative).
|
||||
pub scroll: Vec2,
|
||||
}
|
||||
|
||||
impl FieldState {
|
||||
/// The field's text: what was set, or the block's own.
|
||||
pub fn value<'a>(&'a self, block: &'a TextBlock) -> &'a str {
|
||||
self.text.as_deref().unwrap_or(&block.text)
|
||||
}
|
||||
|
||||
/// The selected range, low end first.
|
||||
pub fn selection(&self) -> (u32, u32) {
|
||||
(self.caret.min(self.anchor), self.caret.max(self.anchor))
|
||||
}
|
||||
|
||||
/// The selected text.
|
||||
pub fn selected(&self, block: &TextBlock) -> String {
|
||||
let (a, b) = self.selection();
|
||||
slice(self.value(block), a, b).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte offset of character boundary `i` in `s` (its end when past it).
|
||||
pub fn byte_at(s: &str, i: u32) -> usize {
|
||||
s.char_indices().nth(i as usize).map_or(s.len(), |(b, _)| b)
|
||||
}
|
||||
|
||||
/// The characters of `s` from boundary `a` to `b`.
|
||||
pub fn slice(s: &str, a: u32, b: u32) -> &str {
|
||||
let (x, y) = (byte_at(s, a.min(b)), byte_at(s, a.max(b)));
|
||||
s.get(x..y).unwrap_or("")
|
||||
}
|
||||
|
||||
/// Characters in `s`, as boundaries count them.
|
||||
pub fn chars(s: &str) -> u32 {
|
||||
s.chars().count().min(u32::MAX as usize) as u32
|
||||
}
|
||||
|
||||
/// Text a script sets, as a field keeps it: at most [`MAX_FIELD_CHARS`] characters, with `\r`
|
||||
/// and `\r\n` (ActionScript's line ends) as line breaks.
|
||||
pub fn fit(field: &TextField, text: &str) -> String {
|
||||
let _ = field;
|
||||
text.replace("\r\n", "\n").replace('\r', "\n").chars().take(MAX_FIELD_CHARS).collect()
|
||||
}
|
||||
|
||||
/// What an editing key does (the ActionScript key codes the player receives).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Edit {
|
||||
Left,
|
||||
Right,
|
||||
Up,
|
||||
Down,
|
||||
Home,
|
||||
End,
|
||||
Backspace,
|
||||
Delete,
|
||||
Enter,
|
||||
SelectAll,
|
||||
}
|
||||
|
||||
impl Edit {
|
||||
/// The edit a key code makes, if any.
|
||||
pub fn from_key(code: u32) -> Option<Edit> {
|
||||
Some(match code {
|
||||
37 => Edit::Left,
|
||||
39 => Edit::Right,
|
||||
38 => Edit::Up,
|
||||
40 => Edit::Down,
|
||||
36 => Edit::Home,
|
||||
35 => Edit::End,
|
||||
8 => Edit::Backspace,
|
||||
46 => Edit::Delete,
|
||||
13 => Edit::Enter,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What an edit changed.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Changed {
|
||||
pub text: bool,
|
||||
pub caret: bool,
|
||||
}
|
||||
|
||||
/// A focused field being edited: its block (style and authored text), its state, and whether
|
||||
/// the viewer may change the text (input fields) or only select it.
|
||||
pub struct Editor<'a> {
|
||||
pub block: &'a TextBlock,
|
||||
pub field: &'a TextField,
|
||||
pub st: &'a mut FieldState,
|
||||
}
|
||||
|
||||
impl Editor<'_> {
|
||||
fn len(&self) -> u32 {
|
||||
chars(self.st.value(self.block))
|
||||
}
|
||||
|
||||
fn editable(&self) -> bool {
|
||||
self.field.kind == TextKind::Input
|
||||
}
|
||||
|
||||
/// Replaces the selection with `s` (typed characters, a paste or a line break).
|
||||
pub fn insert(&mut self, s: &str) -> Changed {
|
||||
if !self.editable() {
|
||||
return Changed::default();
|
||||
}
|
||||
let one = !self.field.lines.multiline();
|
||||
let mut add: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !one)).collect();
|
||||
let (a, b) = self.st.selection();
|
||||
let value = self.st.value(self.block).to_string();
|
||||
let kept = chars(&value) - (b - a);
|
||||
let room = if self.field.max_chars > 0 { self.field.max_chars.saturating_sub(kept) } else { u32::MAX };
|
||||
let room = room.min((MAX_FIELD_CHARS as u32).saturating_sub(kept));
|
||||
if chars(&add) > room {
|
||||
add = add.chars().take(room as usize).collect();
|
||||
}
|
||||
if add.is_empty() && a == b {
|
||||
return Changed::default();
|
||||
}
|
||||
let mut next = String::with_capacity(value.len() + add.len());
|
||||
next.push_str(slice(&value, 0, a));
|
||||
next.push_str(&add);
|
||||
next.push_str(slice(&value, b, u32::MAX));
|
||||
let caret = a + chars(&add);
|
||||
self.st.text = Some(next);
|
||||
self.st.caret = caret;
|
||||
self.st.anchor = caret;
|
||||
Changed { text: true, caret: true }
|
||||
}
|
||||
|
||||
/// One editing key; `shift` extends the selection with caret moves.
|
||||
pub fn key(&mut self, e: Edit, shift: bool, look: Option<&FieldLook>) -> Changed {
|
||||
let len = self.len();
|
||||
let (a, b) = self.st.selection();
|
||||
let moved = |st: &mut FieldState, to: u32, shift: bool| {
|
||||
st.caret = to.min(len);
|
||||
if !shift {
|
||||
st.anchor = st.caret;
|
||||
}
|
||||
Changed { text: false, caret: true }
|
||||
};
|
||||
match e {
|
||||
Edit::SelectAll => {
|
||||
self.st.anchor = 0;
|
||||
self.st.caret = len;
|
||||
Changed { text: false, caret: true }
|
||||
}
|
||||
Edit::Left if !shift && a != b => moved(self.st, a, false),
|
||||
Edit::Right if !shift && a != b => moved(self.st, b, false),
|
||||
Edit::Left => {
|
||||
let to = self.st.caret.saturating_sub(1);
|
||||
moved(self.st, to, shift)
|
||||
}
|
||||
Edit::Right => {
|
||||
let to = self.st.caret.saturating_add(1);
|
||||
moved(self.st, to, shift)
|
||||
}
|
||||
Edit::Home | Edit::End | Edit::Up | Edit::Down => {
|
||||
let Some(look) = look else {
|
||||
let to = if matches!(e, Edit::Home | Edit::Up) { 0 } else { len };
|
||||
return moved(self.st, to, shift);
|
||||
};
|
||||
let n = look.line_of(self.st.caret);
|
||||
let line = look.lines.get(n);
|
||||
let to = match e {
|
||||
Edit::Home => line.map_or(0, |l| l.start),
|
||||
Edit::End => line.map_or(len, |l| l.end),
|
||||
_ => {
|
||||
let x = line.map_or(0.0, |l| l.x_at(self.st.caret));
|
||||
let target = if e == Edit::Up { n.checked_sub(1) } else { Some(n + 1).filter(|m| *m < look.lines.len()) };
|
||||
match target.and_then(|m| look.lines.get(m)) {
|
||||
Some(l) => l.index_at(x),
|
||||
None if e == Edit::Up => 0,
|
||||
None => len,
|
||||
}
|
||||
}
|
||||
};
|
||||
moved(self.st, to, shift)
|
||||
}
|
||||
Edit::Backspace | Edit::Delete if !self.editable() => Changed::default(),
|
||||
Edit::Backspace | Edit::Delete if a != b => self.insert(""),
|
||||
Edit::Backspace => {
|
||||
if a == 0 {
|
||||
return Changed::default();
|
||||
}
|
||||
self.st.anchor = a - 1;
|
||||
self.insert("")
|
||||
}
|
||||
Edit::Delete => {
|
||||
if b >= len {
|
||||
return Changed::default();
|
||||
}
|
||||
self.st.anchor = a;
|
||||
self.st.caret = b + 1;
|
||||
self.insert("")
|
||||
}
|
||||
Edit::Enter if self.field.lines.multiline() => self.insert("\n"),
|
||||
Edit::Enter => Changed::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer at `p` (the text's space): pressed (`extend`: dragging from an earlier press).
|
||||
pub fn point(&mut self, p: Vec2, extend: bool, look: Option<&FieldLook>) -> Changed {
|
||||
let i = look.map_or(self.len(), |l| l.index_at(p + self.st.scroll)).min(self.len());
|
||||
self.st.caret = i;
|
||||
if !extend {
|
||||
self.st.anchor = i;
|
||||
}
|
||||
Changed { text: false, caret: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the caret in view: scrolls the text so the caret's line fits in the box's height and
|
||||
/// (when lines don't wrap) the caret in its width.
|
||||
pub fn scroll_to_caret(block: &TextBlock, field: &TextField, st: &mut FieldState) {
|
||||
let Some(look) = st.look.clone() else {
|
||||
st.scroll = Vec2::ZERO;
|
||||
return;
|
||||
};
|
||||
let view = Vec2::new((block.box_width - 2.0 * FIELD_GUTTER).max(1.0), (block.box_height - 2.0 * FIELD_GUTTER).max(1.0));
|
||||
let c = look.caret_at(st.caret);
|
||||
let mut s = st.scroll;
|
||||
if field.lines != LineType::Multiline {
|
||||
if c.x - s.x > view.x {
|
||||
s.x = c.x - view.x;
|
||||
}
|
||||
if c.x < s.x {
|
||||
s.x = c.x;
|
||||
}
|
||||
} else {
|
||||
s.x = 0.0;
|
||||
}
|
||||
if c.y + look.line_height - s.y > view.y {
|
||||
s.y = c.y + look.line_height - view.y;
|
||||
}
|
||||
if c.y < s.y {
|
||||
s.y = c.y;
|
||||
}
|
||||
// Never past the text's end.
|
||||
s.x = s.x.min((look.width - view.x).max(0.0)).max(0.0);
|
||||
s.y = s.y.min((look.height - view.y).max(0.0)).max(0.0);
|
||||
st.scroll = if s.x.is_finite() && s.y.is_finite() { s } else { Vec2::ZERO };
|
||||
}
|
||||
|
||||
/// A look for tests: every character `cw` wide and `lh` tall (a square per visible one), lines
|
||||
/// broken at `\n` and, with `wrap`, after as many characters as fit.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option<f32>) -> FieldLook {
|
||||
let per = wrap.map(|w| ((w / cw).floor() as u32).max(1));
|
||||
let mut lines = Vec::new();
|
||||
let mut outline = Path::new();
|
||||
let (mut start, mut col, mut stops, mut width) = (0u32, 0u32, vec![(0u32, 0.0f32)], 0.0f32);
|
||||
let mut i = 0u32;
|
||||
for c in text.chars() {
|
||||
if c == '\n' {
|
||||
lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) });
|
||||
i += 1;
|
||||
(start, col) = (i, 0);
|
||||
stops.push((i, 0.0));
|
||||
continue;
|
||||
}
|
||||
if per.is_some_and(|p| col == p) {
|
||||
lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) });
|
||||
(start, col) = (i, 0);
|
||||
stops.push((i, 0.0));
|
||||
}
|
||||
if !c.is_whitespace() {
|
||||
let r = Path::rect(FIELD_GUTTER + col as f32 * cw + 1.0, FIELD_GUTTER + lines.len() as f32 * lh + 1.0, cw - 2.0, lh - 2.0);
|
||||
outline.cmds.extend(r.cmds);
|
||||
}
|
||||
col += 1;
|
||||
i += 1;
|
||||
stops.push((i, col as f32 * cw));
|
||||
width = width.max(col as f32 * cw);
|
||||
}
|
||||
lines.push(CaretLine { start, end: i, stops });
|
||||
let n = lines.len();
|
||||
FieldLook { outline: Arc::new(outline), lines: lines.into(), line_height: lh, width, height: n as f32 * lh }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "field_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,182 @@
|
||||
use super::*;
|
||||
use crate::{Rgba, TextAlign};
|
||||
|
||||
fn block(text: &str, f: TextField) -> TextBlock {
|
||||
TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f), on_path: None }
|
||||
}
|
||||
|
||||
/// Runs edits on a field as the player does: each change of text lays it out again (10 px per
|
||||
/// character, 10 px lines) and keeps the caret in view.
|
||||
struct Rig {
|
||||
block: TextBlock,
|
||||
field: TextField,
|
||||
st: FieldState,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new(text: &str, kind: TextKind, lines: LineType) -> Rig {
|
||||
let field = TextField { lines, ..TextField::new(kind) };
|
||||
let mut r = Rig { block: block(text, field.clone()), field, st: FieldState::default() };
|
||||
r.relayout();
|
||||
r
|
||||
}
|
||||
fn relayout(&mut self) {
|
||||
let shown = self.field.shown(self.st.value(&self.block));
|
||||
self.st.look = Some(Arc::new(mono_look(&shown, 10.0, 10.0, self.field.wrap_width(self.block.box_width))));
|
||||
scroll_to_caret(&self.block, &self.field, &mut self.st);
|
||||
}
|
||||
fn apply(&mut self, ch: Changed) {
|
||||
if ch.text {
|
||||
self.relayout();
|
||||
} else {
|
||||
scroll_to_caret(&self.block, &self.field, &mut self.st);
|
||||
}
|
||||
}
|
||||
fn ed(&mut self) -> (Editor<'_>, Option<Arc<FieldLook>>) {
|
||||
let look = self.st.look.clone();
|
||||
(Editor { block: &self.block, field: &self.field, st: &mut self.st }, look)
|
||||
}
|
||||
fn key(&mut self, e: Edit, shift: bool) -> &mut Self {
|
||||
let (mut ed, look) = self.ed();
|
||||
let ch = ed.key(e, shift, look.as_deref());
|
||||
self.apply(ch);
|
||||
self
|
||||
}
|
||||
fn typed(&mut self, s: &str) -> &mut Self {
|
||||
for c in s.chars() {
|
||||
let (mut ed, _) = self.ed();
|
||||
let ch = ed.insert(&c.to_string());
|
||||
self.apply(ch);
|
||||
}
|
||||
self
|
||||
}
|
||||
fn click(&mut self, x: f32, y: f32, extend: bool) -> &mut Self {
|
||||
let (mut ed, look) = self.ed();
|
||||
let ch = ed.point(Vec2::new(x, y), extend, look.as_deref());
|
||||
self.apply(ch);
|
||||
self
|
||||
}
|
||||
fn text(&self) -> &str {
|
||||
self.st.value(&self.block)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_moves_the_caret_and_keys_edit_around_it() {
|
||||
let mut r = Rig::new("", TextKind::Input, LineType::Single);
|
||||
r.typed("hello");
|
||||
assert_eq!((r.text(), r.st.caret, r.st.anchor), ("hello", 5, 5));
|
||||
r.key(Edit::Left, false).key(Edit::Left, false).typed("X");
|
||||
assert_eq!((r.text(), r.st.caret), ("helXlo", 4));
|
||||
r.key(Edit::Backspace, false);
|
||||
assert_eq!((r.text(), r.st.caret), ("hello", 3));
|
||||
r.key(Edit::Delete, false);
|
||||
assert_eq!((r.text(), r.st.caret), ("helo", 3));
|
||||
r.key(Edit::Home, false);
|
||||
assert_eq!(r.st.caret, 0);
|
||||
r.key(Edit::Backspace, false);
|
||||
assert_eq!(r.text(), "helo", "nothing before the caret");
|
||||
r.key(Edit::End, false).key(Edit::Delete, false);
|
||||
assert_eq!((r.text(), r.st.caret), ("helo", 4), "nothing after it");
|
||||
// Enter types nothing in a one-line field; control characters never go in.
|
||||
r.key(Edit::Enter, false).typed("\u{7}\t");
|
||||
assert_eq!(r.text(), "helo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_selects_and_typing_replaces_the_selection() {
|
||||
let mut r = Rig::new("abcdef", TextKind::Input, LineType::Single);
|
||||
r.click(20.0, 5.0, false);
|
||||
assert_eq!(r.st.caret, 2, "a click puts the caret at the nearest boundary");
|
||||
r.key(Edit::Right, true).key(Edit::Right, true);
|
||||
assert_eq!(r.st.selection(), (2, 4));
|
||||
assert_eq!(r.st.selected(&r.block), "cd");
|
||||
// An arrow without Shift collapses the selection to its side.
|
||||
r.key(Edit::Left, false);
|
||||
assert_eq!((r.st.caret, r.st.anchor), (2, 2));
|
||||
r.key(Edit::End, true);
|
||||
assert_eq!(r.st.selection(), (2, 6));
|
||||
r.typed("Z");
|
||||
assert_eq!((r.text(), r.st.caret), ("abZ", 3));
|
||||
// Dragging extends from where the press was; Backspace deletes the selection.
|
||||
r.click(0.0, 5.0, false).click(19.0, 5.0, true);
|
||||
assert_eq!(r.st.selection(), (0, 2));
|
||||
r.key(Edit::Backspace, false);
|
||||
assert_eq!((r.text(), r.st.caret), ("Z", 0));
|
||||
r.key(Edit::SelectAll, false);
|
||||
assert_eq!(r.st.selection(), (0, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiline_fields_take_enter_and_move_between_lines() {
|
||||
let mut r = Rig::new("", TextKind::Input, LineType::MultilineNoWrap);
|
||||
r.typed("abc").key(Edit::Enter, false).typed("de");
|
||||
assert_eq!(r.text(), "abc\nde");
|
||||
assert_eq!(r.st.caret, 6);
|
||||
r.key(Edit::Up, false);
|
||||
assert_eq!(r.st.caret, 2, "up keeps the column");
|
||||
r.key(Edit::End, false);
|
||||
assert_eq!(r.st.caret, 3);
|
||||
r.key(Edit::Down, false);
|
||||
assert_eq!(r.st.caret, 6, "down to the shorter line's end");
|
||||
r.key(Edit::Down, false);
|
||||
assert_eq!(r.st.caret, 6, "down from the last line goes to the end");
|
||||
r.key(Edit::Up, false).key(Edit::Up, false);
|
||||
assert_eq!(r.st.caret, 0, "up from the first line goes to the start");
|
||||
// Clicking on the second line.
|
||||
r.click(17.0, 14.0, false);
|
||||
assert_eq!(r.st.caret, 6, "x 17 on line 2 is nearest the boundary after d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_chars_and_passwords() {
|
||||
let mut r = Rig::new("", TextKind::Input, LineType::Password);
|
||||
r.field.max_chars = 4;
|
||||
r.typed("secret");
|
||||
assert_eq!(r.text(), "secr", "at most max_chars");
|
||||
let shown = r.field.shown(r.text());
|
||||
assert_eq!(shown, "****");
|
||||
// A paste is cut to the room left, and single-line fields drop its line breaks.
|
||||
let mut r = Rig::new("ab", TextKind::Input, LineType::Single);
|
||||
r.field.max_chars = 6;
|
||||
r.key(Edit::End, false);
|
||||
let (mut ed, _) = r.ed();
|
||||
let ch = ed.insert("c\nd\nefgh");
|
||||
r.apply(ch);
|
||||
assert_eq!(r.text(), "abcdef");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_fields_select_but_never_change() {
|
||||
let mut r = Rig::new("read only", TextKind::Dynamic, LineType::Single);
|
||||
r.typed("x").key(Edit::Backspace, false).key(Edit::Delete, false);
|
||||
assert_eq!(r.text(), "read only");
|
||||
assert!(r.st.text.is_none(), "untouched");
|
||||
r.key(Edit::SelectAll, false);
|
||||
assert_eq!(r.st.selected(&r.block), "read only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_line_fields_scroll_to_keep_the_caret_in_view() {
|
||||
// The box shows 50 px of text (54 less the gutters): five characters.
|
||||
let mut r = Rig::new("", TextKind::Input, LineType::Single);
|
||||
r.typed("abcdefgh");
|
||||
assert_eq!(r.st.scroll.x, 30.0, "the caret at 80 px shows at the right edge");
|
||||
r.key(Edit::Home, false);
|
||||
assert_eq!(r.st.scroll.x, 0.0);
|
||||
// Multiline: lines wrap and it scrolls down instead (the box shows two 10 px lines).
|
||||
let mut r = Rig::new("", TextKind::Input, LineType::Multiline);
|
||||
r.typed("aaaaabbbbbccccc");
|
||||
assert_eq!(r.st.look.as_ref().map(|l| l.lines.len()), Some(3));
|
||||
assert_eq!((r.st.scroll.x, r.st.scroll.y), (0.0, 10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_text_is_capped_and_takes_actionscript_line_ends() {
|
||||
let f = TextField::new(TextKind::Dynamic);
|
||||
assert_eq!(fit(&f, "a\rb\r\nc"), "a\nb\nc");
|
||||
assert_eq!(chars(&fit(&f, &"x".repeat(MAX_FIELD_CHARS + 10))), MAX_FIELD_CHARS as u32);
|
||||
assert_eq!(slice("héllo", 1, 3), "él");
|
||||
assert_eq!(slice("héllo", 4, 99), "o");
|
||||
assert_eq!(byte_at("héllo", 2), 3);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Gradient options, fill frames and fitting (ADR 0074).
|
||||
|
||||
use super::*;
|
||||
|
||||
fn stops() -> Vec<GradientStop> {
|
||||
vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }]
|
||||
}
|
||||
|
||||
fn near(a: &Affine, b: &Affine) -> bool {
|
||||
a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() <= 1e-4 * x.abs().max(y.abs()).max(1.0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_maps_positions_onto_the_ramp() {
|
||||
for (t, pad, reflect, repeat) in [(-0.25, 0.0, 0.25, 0.75), (0.0, 0.0, 0.0, 0.0), (0.4, 0.4, 0.4, 0.4), (1.25, 1.0, 0.75, 0.25), (2.5, 1.0, 0.5, 0.5), (-1.5, 0.0, 0.5, 0.5)] {
|
||||
assert!((Spread::Pad.apply(t) - pad).abs() < 1e-6, "pad {t}");
|
||||
assert!((Spread::Reflect.apply(t) - reflect).abs() < 1e-6, "reflect {t}");
|
||||
assert!((Spread::Repeat.apply(t) - repeat).abs() < 1e-6, "repeat {t}");
|
||||
}
|
||||
for s in Spread::ALL {
|
||||
assert_eq!(s.apply(f32::NAN), 0.0);
|
||||
assert!((0.0..=1.0).contains(&s.apply(f32::INFINITY)));
|
||||
assert_eq!(Spread::from_key(s.key()), Some(s));
|
||||
}
|
||||
assert_eq!(Spread::from_key("pad"), Some(Spread::Pad));
|
||||
assert_eq!(Spread::from_key("mirror"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_round_trip_for_every_fill_kind() {
|
||||
// Linear: x from start to end, y square to it at the same length.
|
||||
let lin = Paint::linear(Vec2::new(10.0, 20.0), Vec2::new(30.0, 20.0), stops());
|
||||
let f = lin.frame(None).unwrap();
|
||||
assert!(near(&f, &Affine { m: [10.0, 0.0, 0.0, 10.0, 20.0, 20.0] }), "{f:?}");
|
||||
assert_eq!(lin.with_frame(&f, None), lin);
|
||||
// Radial: a circle stays a plain circle, with no matrix.
|
||||
let rad = Paint::radial(Vec2::new(5.0, 6.0), 4.0, stops());
|
||||
let f = rad.frame(None).unwrap();
|
||||
assert!(near(&f, &Affine { m: [4.0, 0.0, 0.0, 4.0, 5.0, 6.0] }));
|
||||
assert_eq!(rad.with_frame(&f, None), rad);
|
||||
// A turned ellipse keeps its centre and its x axis's length as the radius.
|
||||
let ell = Affine::translate(50.0, 40.0).mul(&Affine::rotate(0.5)).mul(&Affine::scale(30.0, 10.0));
|
||||
let p = rad.with_frame(&ell, None);
|
||||
match &p {
|
||||
Paint::Radial { center, radius, matrix, .. } => {
|
||||
assert!(center.distance(Vec2::new(50.0, 40.0)) < 1e-4);
|
||||
assert!((radius - 30.0).abs() < 1e-4);
|
||||
assert!(near(&matrix.mul(&Affine::translate(center.x, center.y)), &Affine::translate(center.x, center.y).mul(&Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] })), "the matrix turns about the centre");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(near(&p.frame(None).unwrap(), &ell));
|
||||
// Bitmap: the box onto one copy of the image.
|
||||
let bmp = Paint::Bitmap { bitmap: BitmapId(1), repeat: true, matrix: Affine::translate(3.0, 4.0).mul(&Affine::scale(2.0, 2.0)) };
|
||||
let f = bmp.frame(Some((10.0, 6.0))).unwrap();
|
||||
assert!(f.apply(Vec2::new(-1.0, -1.0)).distance(Vec2::new(3.0, 4.0)) < 1e-4, "top-left of the image");
|
||||
assert!(f.apply(Vec2::new(1.0, 1.0)).distance(Vec2::new(23.0, 16.0)) < 1e-4, "bottom-right");
|
||||
assert_eq!(bmp.frame(None), None, "a bitmap needs its size");
|
||||
assert!(near(&match bmp.with_frame(&f, Some((10.0, 6.0))) {
|
||||
Paint::Bitmap { matrix, .. } => matrix,
|
||||
_ => Affine::IDENTITY,
|
||||
}, &Affine::translate(3.0, 4.0).mul(&Affine::scale(2.0, 2.0))));
|
||||
// Solid colours have no frame; a frame that isn't finite changes nothing.
|
||||
assert_eq!(Paint::Solid(Rgba::WHITE).frame(None), None);
|
||||
assert_eq!(rad.with_frame(&Affine { m: [f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0] }, None), rad);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_gradients_follow_any_transform_exactly() {
|
||||
// A skew turns the circle into a tilted ellipse: the frame is carried exactly, focal point
|
||||
// and all.
|
||||
let mut rad = Paint::radial(Vec2::new(10.0, 0.0), 5.0, stops());
|
||||
if let Paint::Radial { focal, .. } = &mut rad {
|
||||
*focal = 0.5;
|
||||
}
|
||||
let skew = Affine { m: [1.0, 0.0, 0.7, 2.0, 3.0, -1.0] };
|
||||
let moved = rad.transformed(&skew);
|
||||
assert!(near(&moved.frame(None).unwrap(), &skew.mul(&rad.frame(None).unwrap())));
|
||||
assert!(matches!(moved, Paint::Radial { focal, .. } if focal == 0.5));
|
||||
// A plain move keeps a plain circle.
|
||||
assert!(matches!(rad.transformed(&Affine::translate(4.0, 4.0)), Paint::Radial { matrix, .. } if matrix == Affine::IDENTITY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fitting_places_a_fill_on_the_shape() {
|
||||
let b = Rect { min: Vec2::new(0.0, 0.0), max: Vec2::new(200.0, 100.0) };
|
||||
match Paint::linear(Vec2::ZERO, Vec2::new(1.0, 1.0), stops()).fitted(&b) {
|
||||
Paint::Linear { start, end, .. } => assert_eq!((start, end), (Vec2::new(0.0, 50.0), Vec2::new(200.0, 50.0))),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
match Paint::radial(Vec2::ZERO, 1.0, stops()).fitted(&b) {
|
||||
Paint::Radial { center, radius, matrix, .. } => assert_eq!((center, radius, matrix), (Vec2::new(100.0, 50.0), 100.0, Affine::IDENTITY)),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let bmp = Paint::Bitmap { bitmap: BitmapId(2), repeat: false, matrix: Affine::scale(3.0, 3.0) };
|
||||
assert_eq!(bmp.fitted(&b), Paint::Bitmap { bitmap: BitmapId(2), repeat: true, matrix: Affine::IDENTITY });
|
||||
// Stops and options stay; an empty box changes nothing.
|
||||
let mut rep = Paint::linear(Vec2::ZERO, Vec2::new(1.0, 0.0), stops());
|
||||
if let Paint::Linear { spread, linear_rgb, .. } = &mut rep {
|
||||
*spread = Spread::Repeat;
|
||||
*linear_rgb = true;
|
||||
}
|
||||
assert!(matches!(rep.fitted(&b), Paint::Linear { spread: Spread::Repeat, linear_rgb: true, .. }));
|
||||
assert_eq!(rep.fitted(&Rect::EMPTY), rep);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_files_open_and_plain_gradients_are_stored_as_before() {
|
||||
let old = r#"{"Radial":{"center":{"x":1.0,"y":2.0},"radius":3.0,"stops":[{"offset":0.0,"color":{"r":0.0,"g":0.0,"b":0.0,"a":1.0}}]}}"#;
|
||||
let p: Paint = serde_json::from_str(old).unwrap();
|
||||
assert!(matches!(p, Paint::Radial { spread: Spread::Pad, linear_rgb: false, focal, matrix, .. } if focal == 0.0 && matrix == Affine::IDENTITY));
|
||||
let back = serde_json::to_string(&p).unwrap();
|
||||
assert!(!back.contains("spread") && !back.contains("focal") && !back.contains("matrix") && !back.contains("linear_rgb"), "{back}");
|
||||
// Set options are written, and read back.
|
||||
let mut q = Paint::linear(Vec2::ZERO, Vec2::new(1.0, 0.0), stops());
|
||||
if let Paint::Linear { spread, linear_rgb, .. } = &mut q {
|
||||
*spread = Spread::Reflect;
|
||||
*linear_rgb = true;
|
||||
}
|
||||
let text = serde_json::to_string(&q).unwrap();
|
||||
assert!(text.contains("\"spread\":\"reflect\"") && text.contains("\"linear_rgb\":true"), "{text}");
|
||||
assert_eq!(serde_json::from_str::<Paint>(&text).unwrap(), q);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_gradients_tween_through_their_frames() {
|
||||
let a = Paint::radial(Vec2::ZERO, 10.0, stops());
|
||||
let b = a.with_frame(&Affine::translate(100.0, 0.0).mul(&Affine::scale(30.0, 10.0)), None);
|
||||
let mid = a.lerp(&b, 0.5);
|
||||
assert!(near(&mid.frame(None).unwrap(), &Affine { m: [20.0, 0.0, 0.0, 10.0, 50.0, 0.0] }), "{mid:?}");
|
||||
}
|
||||
@@ -323,7 +323,8 @@ impl Document {
|
||||
/// symbols). Items used nowhere are left out.
|
||||
pub fn library_uses(&self) -> HashMap<LibraryItem, usize> {
|
||||
let mut uses: HashMap<LibraryItem, usize> = HashMap::new();
|
||||
for tl in self.timelines() {
|
||||
// (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
|
||||
@@ -388,7 +389,7 @@ impl Document {
|
||||
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, timeline };
|
||||
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);
|
||||
@@ -453,8 +454,15 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Calls `f` once per Library reference on each keyframe of `tl`: symbol instances, bitmap
|
||||
/// fills and the keyframe's sound.
|
||||
/// 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 {
|
||||
@@ -465,6 +473,7 @@ pub fn visit_refs(tl: &Timeline, mut f: impl FnMut(LibraryItem)) {
|
||||
f(LibraryItem::Bitmap(*bitmap));
|
||||
}
|
||||
}
|
||||
ElementKind::Group { members } => visit_refs_in(members, f, depth + 1),
|
||||
ElementKind::Text(_) | ElementKind::Camera => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ fn add_symbol(d: &mut Document, name: &str, inside: &[SymbolId]) -> SymbolId {
|
||||
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, timeline: Timeline { layers: vec![Arc::new(layer)] } }));
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -21,7 +21,7 @@
|
||||
//! 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, Easing, Rgba};
|
||||
use anicraft_geom::edit::ANCHOR;
|
||||
use anicraft_geom::walk::CurveWalk;
|
||||
use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2};
|
||||
@@ -35,7 +35,7 @@ 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.
|
||||
/// pixels, percent, degrees, and 0–255 for colour channels and offsets (as Animate shows them).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Property {
|
||||
@@ -49,13 +49,64 @@ 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,
|
||||
}
|
||||
|
||||
/// How many properties there are.
|
||||
pub const PROPERTIES: usize = 20;
|
||||
|
||||
impl Property {
|
||||
pub const ALL: [Property; 8] = [Property::X, Property::Y, Property::ScaleX, Property::ScaleY, Property::Rotation, Property::Skew, Property::Alpha, Property::Tint];
|
||||
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`…).
|
||||
pub fn key(self) -> &'static str {
|
||||
@@ -67,7 +118,19 @@ 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",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,24 +143,49 @@ 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",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unit(self) -> &'static str {
|
||||
match self {
|
||||
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.
|
||||
pub fn group(self) -> &'static str {
|
||||
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 and transform).
|
||||
pub fn style(self) -> Option<ColorStyle> {
|
||||
match self {
|
||||
Property::X | Property::Y => "Position",
|
||||
Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => "Transform",
|
||||
Property::Alpha | Property::Tint => "Colour effect",
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +196,7 @@ impl Property {
|
||||
"scaley" => "scale_y",
|
||||
"rotate" => "rotation",
|
||||
"opacity" => "alpha",
|
||||
"tint_amount" => "tint",
|
||||
other => other,
|
||||
};
|
||||
Property::ALL.into_iter().find(|p| p.key() == s)
|
||||
@@ -121,6 +210,9 @@ impl Property {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +221,7 @@ impl Property {
|
||||
}
|
||||
|
||||
fn is_transform(self) -> bool {
|
||||
!matches!(self, Property::Alpha | Property::Tint)
|
||||
self.style().is_none()
|
||||
}
|
||||
|
||||
fn clamp(self, v: f32) -> f32 {
|
||||
@@ -140,13 +232,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)
|
||||
@@ -891,15 +1027,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.is_transform()) {
|
||||
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<ColorStyle> {
|
||||
let mut out: Vec<ColorStyle> = 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) {
|
||||
@@ -1083,7 +1233,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]
|
||||
@@ -1167,7 +1317,7 @@ mod tests {
|
||||
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!(!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);
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! 9-slice scaling of symbol instances (ADR 0055), as part of evaluation.
|
||||
//!
|
||||
//! A symbol with a [`ScaleGrid`] is drawn so that scaling an instance keeps the corners outside
|
||||
//! its guides unscaled: the instance's transform is decomposed (`T · R · Skew · S`), and instead
|
||||
//! of `S` the symbol's own shapes go through the 9-slice map of its box scaled by `S`
|
||||
//! ([`anicraft_geom::slice`]); translation, rotation and skew apply after. Strokes keep their
|
||||
//! width. Nested symbols, text and bitmap fills inside scale normally, as in Animate.
|
||||
|
||||
use crate::{Document, ElementKind, LayerKind, ScaleGrid, Symbol};
|
||||
use anicraft_geom::slice::{Axis, Slice9};
|
||||
use anicraft_geom::{Affine, Rect};
|
||||
|
||||
/// How a sliced instance's shapes are drawn (see the module docs).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Slicing {
|
||||
/// Symbol space to sliced space.
|
||||
pub map: Slice9,
|
||||
/// The instance's transform without its scale: sliced space to the parent's space.
|
||||
pub post: Affine,
|
||||
/// The scale left out of `post` (what plain scaling would have applied).
|
||||
pub scale: Affine,
|
||||
}
|
||||
|
||||
/// Instance scale this close to 1 on both axes draws the symbol as it is.
|
||||
const UNSCALED: f32 = 1e-4;
|
||||
|
||||
/// The box 9-slice scaling divides: the control-point bounds of everything on the symbol's
|
||||
/// keyframes (guide layers left out), so the box doesn't move as the symbol plays. Strokes don't
|
||||
/// widen it: they keep their width.
|
||||
pub fn symbol_box(doc: &Document, sym: &Symbol) -> Rect {
|
||||
let mut r = Rect::EMPTY;
|
||||
for layer in sym.timeline.layers.iter().filter(|l| !matches!(l.kind, LayerKind::Guide | LayerKind::Folder | LayerKind::Camera)) {
|
||||
for k in &layer.keyframes {
|
||||
for e in &k.elements {
|
||||
let b = match &e.kind {
|
||||
ElementKind::Shape(s) => s.path.bounds().transformed(&e.transform),
|
||||
_ => e.bounds(doc),
|
||||
};
|
||||
if b.min.x.is_finite() && b.max.x.is_finite() && b.min.y.is_finite() && b.max.y.is_finite() {
|
||||
r = r.union(&b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The slicing of an instance of `sym` placed by `transform`, or `None` when it draws normally:
|
||||
/// no guides, no scale to absorb, or nothing to divide.
|
||||
pub(crate) fn slicing(doc: &Document, sym: &Symbol, transform: &Affine) -> Option<Slicing> {
|
||||
let grid = sym.scale_grid.filter(|g| g.check().is_ok())?;
|
||||
let d = transform.decompose();
|
||||
let (sx, sy) = (d.sx, d.sy.abs());
|
||||
if ((sx - 1.0).abs() < UNSCALED && (sy - 1.0).abs() < UNSCALED) || !sx.is_finite() || !sy.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let b = symbol_box(doc, sym);
|
||||
if b.is_empty() {
|
||||
return None;
|
||||
}
|
||||
map_for(&grid, &b, sx, sy).map(|map| {
|
||||
// `transform` is T·R·K·S; S = scale(sx, ±sy). Keep a flip in `post` (sliced magnitudes).
|
||||
let flip = if d.sy < 0.0 { -1.0 } else { 1.0 };
|
||||
let rest = anicraft_geom::Decomposed { sx: 1.0, sy: flip, ..d }.compose();
|
||||
Slicing { map, post: rest, scale: Affine::scale(sx, sy) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an instance of `sym` placed by `transform` is drawn 9-sliced (exporters that place
|
||||
/// symbols themselves say when they can't).
|
||||
pub fn slices(doc: &Document, sym: &Symbol, transform: &Affine) -> bool {
|
||||
slicing(doc, sym, transform).is_some()
|
||||
}
|
||||
|
||||
/// The 9-slice map of box `b` with guides `grid`, scaled by `sx`, `sy` (both at least 0). An
|
||||
/// axis with no extent (a symbol only a line high) scales plainly.
|
||||
pub fn map_for(grid: &ScaleGrid, b: &Rect, sx: f32, sy: f32) -> Option<Slice9> {
|
||||
let axis = |lo: f32, a: f32, c: f32, hi: f32, k: f32| if hi > lo { Axis::new(lo, a, c, hi, k) } else { Axis::new(lo, lo, lo + 1.0, lo + 1.0, k) };
|
||||
Some(Slice9 { x: axis(b.min.x, grid.left, grid.right, b.max.x, sx)?, y: axis(b.min.y, grid.top, grid.bottom, b.max.y, sy)? })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "nine_slice_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,171 @@
|
||||
//! 9-slice scaling (ADR 0055), analytically: what evaluation draws for a scaled instance.
|
||||
|
||||
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, ScaleGrid, Shape, Symbol, SymbolId, SymbolKind, Timeline, evaluate};
|
||||
use anicraft_geom::{Affine, Path, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
const SYM: SymbolId = SymbolId(900);
|
||||
|
||||
fn el(id: u64, transform: Affine, kind: ElementKind) -> Element {
|
||||
Element { id: ElementId(id), name: String::new(), transform, color: ColorEffect::default(), kind }
|
||||
}
|
||||
|
||||
fn instance(of: SymbolId, transform: Affine) -> Element {
|
||||
el(1, transform, ElementKind::Symbol { symbol: of, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() })
|
||||
}
|
||||
|
||||
/// A 100×40 rounded rectangle (corner radius 10) at the symbol's origin, guides 10 in from each
|
||||
/// edge, with `extra` inside it, and one instance of it on the stage placed by `xf`.
|
||||
fn doc(xf: Affine, grid: Option<ScaleGrid>, extra: Vec<Element>) -> Document {
|
||||
let mut d = Document::default();
|
||||
let mut shape = Shape::filled(Path::rounded_rect(0.0, 0.0, 100.0, 40.0, 10.0), Paint::Solid(Rgba::BLACK));
|
||||
shape.stroke = Some(crate::Stroke::new(Rgba::WHITE, 2.0));
|
||||
let mut k = Keyframe::new(0, 1);
|
||||
k.elements.push(Arc::new(el(2, Affine::IDENTITY, ElementKind::Shape(shape))));
|
||||
k.elements.extend(extra.into_iter().map(Arc::new));
|
||||
let mut layer = Layer::new(LayerId(901), "art");
|
||||
layer.keyframes = vec![Arc::new(k)];
|
||||
d.library.push(Arc::new(Symbol { id: SYM, name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: grid, timeline: Timeline { layers: vec![Arc::new(layer)] } }));
|
||||
let mut k = Keyframe::new(0, 1);
|
||||
k.elements.push(Arc::new(instance(SYM, xf)));
|
||||
Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k)];
|
||||
d
|
||||
}
|
||||
|
||||
const GRID: ScaleGrid = ScaleGrid { left: 10.0, right: 90.0, top: 10.0, bottom: 30.0 };
|
||||
|
||||
/// The stage-space outline of the first item, finely flattened.
|
||||
fn outline(d: &Document) -> Vec<Vec2> {
|
||||
let dl = evaluate(d, 0);
|
||||
let it = &dl.items[0];
|
||||
it.path.flatten(&it.transform, 0.005).into_iter().flat_map(|l| l.points).collect()
|
||||
}
|
||||
|
||||
/// How far `p` is from the polyline `pts` (closed).
|
||||
fn dist(pts: &[Vec2], p: Vec2) -> f32 {
|
||||
let n = pts.len();
|
||||
(0..n).map(|i| anicraft_geom::segment_distance(p, pts[i], pts[(i + 1) % n])).fold(f32::INFINITY, f32::min)
|
||||
}
|
||||
|
||||
/// A point on the source corner arc of the rounded rectangle, `a` radians round the corner
|
||||
/// centred at `c`.
|
||||
fn arc(c: Vec2, a: f32) -> Vec2 {
|
||||
c + Vec2::new(a.cos(), a.sin()) * 10.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rounded_rect_scaled_3x_keeps_its_corner_radii_exact() {
|
||||
let d = doc(Affine::scale(3.0, 3.0), Some(GRID), Vec::new());
|
||||
let pts = outline(&d);
|
||||
// The box lands where plain scaling puts it: 0..300 by 0..120.
|
||||
let (lo, hi) = pts.iter().fold((Vec2::new(f32::MAX, f32::MAX), Vec2::new(f32::MIN, f32::MIN)), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))));
|
||||
assert!((lo.x).abs() < 1e-3 && (lo.y).abs() < 1e-3 && (hi.x - 300.0).abs() < 1e-3 && (hi.y - 120.0).abs() < 1e-3, "{lo:?} {hi:?}");
|
||||
// Each corner is the same radius-10 arc, moved to its corner of the bigger box.
|
||||
let corners = [(Vec2::new(10.0, 10.0), Vec2::ZERO, 180.0f32), (Vec2::new(90.0, 10.0), Vec2::new(200.0, 0.0), 270.0), (Vec2::new(90.0, 30.0), Vec2::new(200.0, 80.0), 0.0), (Vec2::new(10.0, 30.0), Vec2::new(0.0, 80.0), 90.0)];
|
||||
for (c, shift, from) in corners {
|
||||
for i in 0..=8 {
|
||||
let a = (from + i as f32 * 90.0 / 8.0).to_radians();
|
||||
let want = arc(c, a) + shift;
|
||||
let d = dist(&pts, want);
|
||||
assert!(d < 0.02, "corner at {c:?}, {i}/8: {d}");
|
||||
// And the arc's centre is still 10 from it: the radius is exact, not stretched.
|
||||
assert!(((want - (c + shift)).length() - 10.0).abs() < 1e-3);
|
||||
}
|
||||
}
|
||||
// Without guides, the same instance is a plain 3× scale (corners radius 30).
|
||||
let plain = evaluate(&doc(Affine::scale(3.0, 3.0), None, Vec::new()), 0);
|
||||
assert_eq!(plain.items[0].transform, Affine::scale(3.0, 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_centre_scales_by_the_remainder_and_edges_one_way() {
|
||||
// 2× wide, 1.5× high: 200 × 60. The centre is 200 − 20 = 180 wide (80 → 180) and
|
||||
// 60 − 20 = 40 high (20 → 40).
|
||||
let d = doc(Affine::scale(2.0, 1.5), Some(GRID), Vec::new());
|
||||
let it = &evaluate(&d, 0).items[0];
|
||||
let map = |p: Vec2| it.transform.apply(p);
|
||||
let pts = outline(&d);
|
||||
// The middle of the top edge (50, 0) lands at (100, 0); of the left edge (0, 20) at (0, 30).
|
||||
assert!(dist(&pts, Vec2::new(100.0, 0.0)) < 1e-3);
|
||||
assert!(dist(&pts, Vec2::new(0.0, 30.0)) < 1e-3);
|
||||
// The straight top edge runs from x = 10 to x = 190 (the corners are 10 each).
|
||||
assert!(dist(&pts, Vec2::new(10.0, 0.0)) < 1e-3 && dist(&pts, Vec2::new(190.0, 0.0)) < 1e-3);
|
||||
// The stroke keeps its width (no scale is left in the item's transform).
|
||||
assert_eq!(map(Vec2::new(1.0, 0.0)) - map(Vec2::ZERO), Vec2::new(1.0, 0.0));
|
||||
assert_eq!(it.stroke.as_ref().map(|s| s.width), Some(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_spare_space_clamps_the_corners_and_closes_the_centre() {
|
||||
// 0.1× wide: 10 across, less than the corners' 20. They share it (5 each) and the centre is
|
||||
// a line; nothing turns inside out.
|
||||
let d = doc(Affine::scale(0.1, 1.0), Some(GRID), Vec::new());
|
||||
let pts = outline(&d);
|
||||
assert!(pts.iter().all(|p| p.x >= -1e-3 && p.x <= 10.0 + 1e-3), "{pts:?}");
|
||||
assert!(dist(&pts, Vec2::new(5.0, 0.0)) < 1e-3);
|
||||
// Exactly no spare space (0.2× → 20 across): corners full size, the centre a line.
|
||||
let pts = outline(&doc(Affine::scale(0.2, 1.0), Some(GRID), Vec::new()));
|
||||
assert!(dist(&pts, arc(Vec2::new(10.0, 10.0), 225f32.to_radians())) < 0.02);
|
||||
assert!(pts.iter().all(|p| p.x <= 20.0 + 1e-3));
|
||||
// Zero scale: everything on one line, still finite.
|
||||
let pts = outline(&doc(Affine::scale(0.0, 1.0), Some(GRID), Vec::new()));
|
||||
assert!(pts.iter().all(|p| p.x.abs() < 1e-3 && p.y.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_skew_and_flips_apply_after_slicing() {
|
||||
let rot = 30f32.to_radians();
|
||||
let xf = Affine::translate(400.0, 300.0).mul(&Affine::rotate(rot)).mul(&Affine::scale(3.0, 3.0));
|
||||
let d = doc(xf, Some(GRID), Vec::new());
|
||||
let it = &evaluate(&d, 0).items[0];
|
||||
// The item's transform is the instance's translation and rotation, with no scale.
|
||||
let expect = Affine::translate(400.0, 300.0).mul(&Affine::rotate(rot));
|
||||
assert!(it.transform.m.iter().zip(expect.m).all(|(a, b)| (a - b).abs() < 1e-4), "{:?}", it.transform);
|
||||
// The sliced corner (the top-right arc, moved by 200) turns with the instance.
|
||||
let pts = outline(&d);
|
||||
let want = expect.apply(arc(Vec2::new(90.0, 10.0), 315f32.to_radians()) + Vec2::new(200.0, 0.0));
|
||||
assert!(dist(&pts, want) < 0.02);
|
||||
// A horizontal flip slices by the magnitude, then mirrors.
|
||||
let flip = doc(Affine::scale(3.0, -3.0), Some(GRID), Vec::new());
|
||||
let it = &evaluate(&flip, 0).items[0];
|
||||
assert!((it.transform.determinant() + 1.0).abs() < 1e-4);
|
||||
let pts = outline(&flip);
|
||||
assert!(dist(&pts, Vec2::new(300.0, -120.0)).is_finite() && pts.iter().all(|p| p.y <= 1e-3 && p.y >= -120.0 - 1e-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unscaled_instances_and_nested_symbols_draw_as_they_are() {
|
||||
// At scale 1 nothing is cut: the symbol's own path is drawn, shared.
|
||||
let d = doc(Affine::translate(5.0, 5.0), Some(GRID), Vec::new());
|
||||
let dl = evaluate(&d, 0);
|
||||
let ElementKind::Shape(s) = &d.symbol(SYM).unwrap().timeline.layers[0].keyframes[0].elements[0].kind else { panic!("the panel is a shape") };
|
||||
let sym_path = s.path.clone();
|
||||
assert!(Arc::ptr_eq(&dl.items[0].path, &sym_path));
|
||||
// A nested symbol inside scales normally: its item carries the whole 3× scale.
|
||||
let mut d = doc(Affine::scale(3.0, 3.0), Some(GRID), vec![instance(SymbolId(950), Affine::translate(50.0, 20.0))]);
|
||||
let mut k = Keyframe::new(0, 1);
|
||||
k.elements.push(Arc::new(el(3, Affine::IDENTITY, ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::WHITE))))));
|
||||
let mut l = Layer::new(LayerId(951), "dot");
|
||||
l.keyframes = vec![Arc::new(k)];
|
||||
d.library.push(Arc::new(Symbol { id: SymbolId(950), name: "Dot".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(l)] } }));
|
||||
let dl = evaluate(&d, 0);
|
||||
let dot = dl.items.iter().find(|i| i.path.bounds().width() == 4.0).unwrap();
|
||||
assert_eq!(dot.transform, Affine::scale(3.0, 3.0).mul(&Affine::translate(50.0, 20.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_guides_and_scales_never_break_evaluation() {
|
||||
for grid in [
|
||||
ScaleGrid { left: 90.0, right: 10.0, top: 10.0, bottom: 30.0 },
|
||||
ScaleGrid { left: f32::NAN, right: 10.0, top: 10.0, bottom: 30.0 },
|
||||
ScaleGrid { left: -1e9, right: 1e9, top: -5.0, bottom: 500.0 },
|
||||
ScaleGrid { left: 50.0, right: 50.0, top: 20.0, bottom: 20.0 },
|
||||
] {
|
||||
for xf in [Affine::scale(3.0, 3.0), Affine::scale(1e-30, 1e30), Affine::scale(f32::INFINITY, 1.0), Affine { m: [0.0, 0.0, 0.0, 0.0, 1.0, 1.0] }] {
|
||||
let dl = evaluate(&doc(xf, Some(grid), Vec::new()), 0);
|
||||
for it in &dl.items {
|
||||
let _ = it.path.flatten(&it.transform, 0.25);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,10 +41,17 @@ pub fn build_table(doc: &Document) -> Vec<Arc<Path>> {
|
||||
for layer in &tl.layers {
|
||||
for k in &layer.keyframes {
|
||||
for e in &k.elements {
|
||||
// A warped shape's outline as drawn (ADR 0079) is written once too.
|
||||
if let ElementKind::Shape(s) = &e.kind
|
||||
&& let Some(w) = &s.warp
|
||||
&& seen.insert(Arc::as_ptr(&w.rest) as usize, ()).is_none()
|
||||
{
|
||||
out.push(w.rest.clone());
|
||||
}
|
||||
let path = match &e.kind {
|
||||
ElementKind::Shape(s) => &s.path,
|
||||
ElementKind::Text(t) => &t.outline,
|
||||
ElementKind::Symbol { .. } | ElementKind::Camera => continue,
|
||||
ElementKind::Symbol { .. } | ElementKind::Camera | ElementKind::Group { .. } => continue,
|
||||
};
|
||||
if seen.insert(Arc::as_ptr(path) as usize, ()).is_none() {
|
||||
out.push(path.clone());
|
||||
|
||||
@@ -33,7 +33,7 @@ fn layer(id: u64, keys: Vec<Arc<Keyframe>>) -> Arc<Layer> {
|
||||
}
|
||||
|
||||
fn symbol(id: u64, kind: SymbolKind, layers: Vec<Arc<Layer>>) -> Arc<Symbol> {
|
||||
Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, timeline: Timeline { layers } })
|
||||
Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers } })
|
||||
}
|
||||
|
||||
fn doc(root: Vec<Arc<Layer>>, library: Vec<Arc<Symbol>>) -> Document {
|
||||
@@ -342,6 +342,97 @@ fn entered_keyframes_start_their_sounds_in_clips_and_graphics_with_layer_volumes
|
||||
assert_eq!(started(&start(&m, &mut NoScripts)), vec![(1, 1.0), (3, 0.0)]);
|
||||
}
|
||||
|
||||
// ----- Sounds on button frames (ADR 0057) --------------------------------------------------------
|
||||
|
||||
/// [`button_doc`] with a sound on each state frame (ids 10 Up, 11 Over, 12 Down, 13 Hit; Over's
|
||||
/// a stream), on a layer at half volume, the button on a layer at half volume too.
|
||||
fn sounding_button() -> Document {
|
||||
use crate::SoundSync::{Event, Stream};
|
||||
let mut d = button_doc();
|
||||
let art = |id| vec![rect(id, 0.0, 0.0, 10.0, 10.0)];
|
||||
let mut sounds = (*layer(34, vec![with_sound(kf(0, 1, vec![], vec![], ""), 10, Event), with_sound(kf(1, 1, vec![], vec![], ""), 11, Stream), with_sound(kf(2, 1, vec![], vec![], ""), 12, Event), with_sound(kf(3, 1, vec![], vec![], ""), 13, Event)])).clone();
|
||||
sounds.volume = 0.5;
|
||||
let states = layer(31, vec![kf(0, 1, art(32), vec![], ""), kf(1, 1, art(32), vec![], ""), kf(2, 1, art(32), vec![], ""), kf(3, 1, vec![rect(33, 0.0, 0.0, 100.0, 100.0)], vec![], "")]);
|
||||
d.library = vec![symbol(300, SymbolKind::Button, vec![Arc::new(sounds), states])];
|
||||
Arc::make_mut(&mut d.timeline_mut(0).layers[1]).volume = 0.5;
|
||||
let tone: Vec<f32> = (0..800).map(|i| (i as f32 * 0.1).sin() * 0.5).collect();
|
||||
for id in 10..14 {
|
||||
let data = anicraft_audio::wav::encode(8000, 1, &tone, anicraft_audio::wav::Bits::Float32);
|
||||
d.sounds.push(Arc::new(crate::Sound::from_data(crate::SoundId(id), format!("s{id}.wav"), data).expect("a WAV")));
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_button_plays_the_sound_of_the_state_it_enters() {
|
||||
let d = sounding_button();
|
||||
let at = |x, y| Vec2::new(x, y);
|
||||
let s = start(&d, &mut NoScripts);
|
||||
assert!(s.sounds.is_empty(), "a button on the stage is silent until the pointer comes");
|
||||
// Over: the Over frame's sound, as an event (a button frame has no span to stream over), at
|
||||
// the volumes of both layers.
|
||||
let s = step(&d, &s.state, &[Event::Move(at(150.0, 150.0))], &mut NoScripts);
|
||||
assert_eq!(started(&s), vec![(11, 0.25)]);
|
||||
assert_eq!(s.sounds[0].sound.sync, crate::SoundSync::Event);
|
||||
// Moving about inside it plays nothing more.
|
||||
let s = step(&d, &s.state, &[Event::Move(at(160.0, 150.0))], &mut NoScripts);
|
||||
assert!(s.sounds.is_empty());
|
||||
// Pressed: Down's. Released over it: Hit's (the SWF format's Down → Over sound).
|
||||
let s = input(&d, &s.state, &[Event::Down(at(160.0, 150.0))], &mut NoScripts);
|
||||
assert_eq!(started(&s), vec![(12, 0.25)]);
|
||||
let s = input(&d, &s.state, &[Event::Up(at(160.0, 150.0))], &mut NoScripts);
|
||||
assert_eq!(started(&s), vec![(13, 0.25)]);
|
||||
// Left: Up's.
|
||||
let s = step(&d, &s.state, &[Event::Leave], &mut NoScripts);
|
||||
assert_eq!(started(&s), vec![(10, 0.25)]);
|
||||
// Arriving and pressing in one event: Over's, then Down's.
|
||||
let s = input(&d, &s.state, &[Event::Down(at(150.0, 150.0))], &mut NoScripts);
|
||||
assert_eq!(started(&s), vec![(11, 0.25), (12, 0.25)]);
|
||||
// Dragged off while pressed, back on and released off: nothing (no state with a sound).
|
||||
let s = input(&d, &s.state, &[Event::Move(at(400.0, 400.0)), Event::Move(at(150.0, 150.0)), Event::Move(at(400.0, 400.0)), Event::Up(at(400.0, 400.0))], &mut NoScripts);
|
||||
assert!(s.sounds.is_empty(), "{:?}", started(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn button_sounds_follow_the_frames_a_button_has_and_stay_out_of_the_soundtrack() {
|
||||
// A two-frame button (Up and Over): pressing it shows Over still, and plays nothing.
|
||||
let mut d = sounding_button();
|
||||
let short = Timeline { layers: d.library[0].timeline.layers.iter().map(|l| {
|
||||
let mut l = (**l).clone();
|
||||
l.keyframes.truncate(2);
|
||||
Arc::new(l)
|
||||
}).collect() };
|
||||
Arc::make_mut(&mut d.library[0]).timeline = short;
|
||||
let s = start(&d, &mut NoScripts);
|
||||
// Its Up frame is its hit area (10 × 10 at 100, 100).
|
||||
let s = input(&d, &s.state, &[Event::Move(Vec2::new(105.0, 105.0)), Event::Down(Vec2::new(105.0, 105.0))], &mut NoScripts);
|
||||
assert_eq!(started(&s), vec![(11, 0.25)]);
|
||||
// The mix and every export leave buttons out: they only sound under the pointer.
|
||||
assert!(crate::sound::voices(&sounding_button(), 48_000).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hit_overlay_is_the_area_the_pointer_finds() {
|
||||
let d = button_doc();
|
||||
let s = start(&d, &mut NoScripts);
|
||||
let tint = Rgba::new(1.0, 0.0, 0.0, 1.0);
|
||||
let dl = hit_overlay(&d, &s.state, tint, 0.4);
|
||||
// One area: the Hit frame's 100 × 100 square at (100, 100), tinted, in one group at 40 %.
|
||||
assert_eq!(dl.items.len(), 1);
|
||||
assert_eq!(dl.groups.first().map(|g| g.alpha), Some(0.4));
|
||||
let i = &dl.items[0];
|
||||
assert_eq!((i.color, i.group), (ColorTransform::tint(tint, 1.0), Some(0)));
|
||||
assert_eq!(i.color.apply(Rgba::new(0.1, 0.6, 0.9, 0.8)), Rgba::new(1.0, 0.0, 0.0, 0.8), "every colour becomes the tint, its alpha kept");
|
||||
for p in [Vec2::new(101.0, 101.0), Vec2::new(199.0, 150.0), Vec2::new(50.0, 50.0), Vec2::new(201.0, 150.0)] {
|
||||
assert_eq!(i.path.contains(p, &i.transform, i.fill_rule), hit(&d, &s.state, p).is_some(), "{p:?}");
|
||||
}
|
||||
// A hidden button has no area; a movie without buttons none at all.
|
||||
assert!(hit_overlay(&doc(vec![], vec![]), &PlayerState::default(), tint, 0.4).items.is_empty());
|
||||
assert_eq!(hit_frame(4), 3);
|
||||
assert_eq!(hit_frame(3), 0);
|
||||
assert_eq!(hit_frame(0), 0);
|
||||
}
|
||||
|
||||
// ----- ActionScript (ADR 0013 tier 2) -----------------------------------------------------------
|
||||
|
||||
/// `k` with a kept ActionScript 3.0 script in place of its actions.
|
||||
@@ -353,7 +444,7 @@ fn as3(k: Arc<Keyframe>, src: &str) -> Arc<Keyframe> {
|
||||
|
||||
/// The state without the listeners scripts add (hand-made actions use handlers instead).
|
||||
fn lean(st: &PlayerState) -> PlayerState {
|
||||
PlayerState { listeners: BTreeMap::new(), ..st.clone() }
|
||||
PlayerState { listeners: BTreeMap::new(), seq: 0, ..st.clone() }
|
||||
}
|
||||
|
||||
/// Plays both documents through the same pointer events and asserts the same movie: state and
|
||||
@@ -403,7 +494,7 @@ fn actionscript_and_hand_made_actions_play_the_same_movie() {
|
||||
|
||||
#[test]
|
||||
fn a_script_outside_the_subset_does_not_run_at_all() {
|
||||
let d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nif (true) { play(); }")])], vec![]);
|
||||
let d = doc(vec![layer(1, vec![as3(kf(0, 10, vec![], vec![], ""), "stop();\ntrace(\"half\");\nswitch (1) { }")])], vec![]);
|
||||
let s = run(&d, 3);
|
||||
assert!(s.state.root.playing && s.output.is_empty(), "nothing of it ran: {:?}", s.output);
|
||||
assert_eq!(s.state.root.frame, 3);
|
||||
@@ -448,3 +539,275 @@ fn next_scene_in_a_movie_clip_script_stays_in_its_clip() {
|
||||
assert_eq!(s.state.scene, 0);
|
||||
assert_eq!(s.output, ["Next scene: a movie clip's timeline has one scene; call it in the main timeline's script"]);
|
||||
}
|
||||
|
||||
// ----- ActionScript small logic (ADR 0052) ---------------------------------------------
|
||||
|
||||
/// A one-layer main timeline of `frames` frames with scripts on some of them, and `extra` layers.
|
||||
fn scripted(frames: u32, scripts: &[(u32, &str)], extra: Vec<Arc<Layer>>, library: Vec<Arc<Symbol>>) -> Document {
|
||||
let mut keys = Vec::new();
|
||||
let mut starts: Vec<u32> = scripts.iter().map(|(f, _)| *f).collect();
|
||||
starts.push(frames);
|
||||
for (i, (f, src)) in scripts.iter().enumerate() {
|
||||
let end = starts.get(i + 1).copied().unwrap_or(frames);
|
||||
keys.push(if src.is_empty() { kf(*f, end - f, vec![], vec![], "") } else { as3(kf(*f, end - f, vec![], vec![], ""), src) });
|
||||
}
|
||||
let mut layers = vec![layer(1, keys)];
|
||||
layers.extend(extra);
|
||||
doc(layers, library)
|
||||
}
|
||||
|
||||
fn outputs(d: &Document, steps: usize) -> Vec<String> {
|
||||
let mut s = start(d, &mut NoScripts);
|
||||
let mut out = s.output.clone();
|
||||
for _ in 0..steps {
|
||||
s = step(d, &s.state, &[], &mut NoScripts);
|
||||
out.extend(s.output.iter().cloned());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeline_variables_and_functions_live_across_frames() {
|
||||
let d = scripted(4, &[(0, "var score:int = 10;\nfunction bump(k:int):int { score += k; return score; }\ntrace(\"start \" + score + \" \" + level);"), (2, "trace(bump(5), bump(1.9), level);\nlevel = \"two\";"), (3, "trace(level);\nvar level:String = \"one\"; trace(level); stop();")], vec![], vec![]);
|
||||
// `level` is declared on frame 4 but is the timeline's from the start (null until set).
|
||||
assert_eq!(outputs(&d, 5), ["start 10 null", "15 16 null", "two", "one"]);
|
||||
let s = run(&d, 5);
|
||||
assert_eq!(s.state.vars.get(&Vec::new()).and_then(|v| v.get("score")), Some(&Value::Num(16.0)));
|
||||
// A script that uses a name no frame declares doesn't run at all.
|
||||
let d = scripted(3, &[(0, "trace(\"one\");"), (1, "trace(\"two\"); trace(nobody);")], vec![], vec![]);
|
||||
assert_eq!(outputs(&d, 2), ["one"]);
|
||||
assert_eq!(link_problems(&d, TimelineRef::Root, d.scenes[0].timeline.layers[0].keyframes[1].script.as_ref().and_then(FrameScript::source).unwrap().compiled().as_ref().unwrap())[0].message, "`nobody` isn't a variable of this timeline (declare it with `var` in one of its frame scripts)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_movie_clip_instance_keeps_its_own_variables() {
|
||||
// A two-frame clip counts its loops; two instances count apart, and one that leaves the
|
||||
// stage and comes back starts again.
|
||||
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![as3(kf(0, 2, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], ""), "var n:int; n++; trace(name + \" \" + n);")])]);
|
||||
let a = layer(2, vec![kf(0, 8, vec![inst(3, 100, "a", 0.0, 0.0, vec![])], vec![], "")]);
|
||||
let b = layer(3, vec![kf(0, 3, vec![inst(4, 100, "b", 50.0, 0.0, vec![])], vec![], ""), kf(3, 2, vec![], vec![], ""), kf(5, 3, vec![inst(5, 100, "b", 50.0, 0.0, vec![])], vec![], "")]);
|
||||
let d = scripted(8, &[(0, "")], vec![a, b], vec![clip]);
|
||||
let out = outputs(&d, 6);
|
||||
assert_eq!(out, ["a 1", "b 1", "a 2", "b 2", "a 3", "b 1", "a 4"], "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_frame_listeners_run_every_frame_until_removed() {
|
||||
let src = "var t:int = 0;\nstop();\naddEventListener(Event.ENTER_FRAME, tick);\nfunction tick(e:Event):void {\n t++;\n trace(\"tick \" + t + \" on \" + currentFrame + \" of \" + totalFrames);\n if (t == 3) { removeEventListener(Event.ENTER_FRAME, tick); gotoAndStop(2); }\n}";
|
||||
let d = scripted(3, &[(0, src), (1, "trace(\"frame 2 runs after the listener\");")], vec![], vec![]);
|
||||
assert_eq!(outputs(&d, 5), ["tick 1 on 1 of 3", "tick 2 on 1 of 3", "tick 3 on 1 of 3", "frame 2 runs after the listener"]);
|
||||
assert!(run(&d, 5).state.listeners.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_reach_the_stage_listeners_with_their_codes() {
|
||||
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 1, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "")])]);
|
||||
let src = "stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, down);\nstage.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent):void { trace(\"up \" + e.keyCode); });\nfunction down(e:KeyboardEvent):void {\n if (e.keyCode == Keyboard.RIGHT) hero.x += 10;\n else if (e.keyCode == Keyboard.LEFT) hero.x -= 10;\n trace(e.keyCode, hero.x, e.target == stage);\n}";
|
||||
let d = scripted(2, &[(0, src)], vec![layer(2, vec![kf(0, 2, vec![inst(3, 100, "hero", 30.0, 40.0, vec![])], vec![], "")])], vec![clip]);
|
||||
let s = start(&d, &mut NoScripts);
|
||||
assert_eq!(s.state.stage.len(), 2);
|
||||
let s = step(&d, &s.state, &[Event::KeyDown(39), Event::KeyDown(39), Event::KeyUp(39)], &mut NoScripts);
|
||||
assert_eq!(s.output, ["39 40 true", "39 50 true", "up 39"]);
|
||||
// Between frames too.
|
||||
let s = input(&d, &s.state, &[Event::KeyDown(37)], &mut NoScripts);
|
||||
assert_eq!(s.output, ["37 40 true"]);
|
||||
assert_eq!(s.state.props.get(&vec![ElementId(3)]).and_then(|o| o.x), Some(40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_read_instance_and_timeline_properties() {
|
||||
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 3, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "walk")])]);
|
||||
let mut hero = (*inst(3, 100, "hero", 30.0, 40.0, vec![])).clone();
|
||||
hero.transform = Affine::translate(30.25, 40.0).mul(&Affine::scale(2.0, 0.5));
|
||||
hero.color = crate::ColorEffect::Alpha(0.3);
|
||||
let src = "stop();\ntrace(hero.x, hero.y, hero.scaleX, hero.scaleY, hero.rotation, hero.alpha, hero.visible, hero.name);\ntrace(hero.currentFrame, hero.totalFrames, hero.currentLabel, currentFrame, totalFrames, currentLabel, this.name);\nhero.x = 0.1; hero.alpha = hero.alpha + 0.2; hero.visible = false;\ntrace(hero.x, hero.alpha, hero.visible);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { trace(mouseX, mouseY, hero.mouseX, stage.mouseY); });";
|
||||
let k = as3(kf(0, 2, vec![], vec![], "intro"), src);
|
||||
let mut hk = Keyframe::new(0, 2);
|
||||
hk.elements = vec![Arc::new(hero)];
|
||||
let d = doc(vec![layer(1, vec![k]), layer(2, vec![Arc::new(hk)])], vec![clip]);
|
||||
let s = start(&d, &mut NoScripts);
|
||||
assert_eq!(s.output, ["30.25 40 2 0.5 0 0.3 true hero", "1 3 walk 1 2 intro root1", "0.1 0.5 false"]);
|
||||
let s = input(&d, &s.state, &[Event::Move(Vec2::new(50.5, 60.0)), Event::Leave, Event::KeyDown(32)], &mut NoScripts);
|
||||
// The pointer's last place stays after it leaves; a clip sees it in its own space.
|
||||
assert_eq!(s.output, ["50.5 60 25.2 60"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_numbers_are_seeded_and_repeat() {
|
||||
let src = "trace(Math.random(), Math.floor(Math.random() * 6) + 1);";
|
||||
let d = scripted(2, &[(0, src)], vec![], vec![]);
|
||||
let a = start_seeded(&d, 7, &mut NoScripts).output;
|
||||
let b = start_seeded(&d, 7, &mut NoScripts).output;
|
||||
let c = start_seeded(&d, 8, &mut NoScripts).output;
|
||||
assert_eq!(a, b);
|
||||
assert_ne!(a, c);
|
||||
// The generator itself: in [0, 1), and spread out.
|
||||
let mut r = Rng::seeded(DEFAULT_SEED);
|
||||
let v: Vec<f64> = (0..10_000).map(|_| r.next_f64()).collect();
|
||||
assert!(v.iter().all(|x| (0.0..1.0).contains(x)));
|
||||
let mean = v.iter().sum::<f64>() / v.len() as f64;
|
||||
assert!((mean - 0.5).abs() < 0.02, "{mean}");
|
||||
assert_eq!(start(&d, &mut NoScripts).output, start_seeded(&d, DEFAULT_SEED, &mut NoScripts).output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_endless_loop_stops_its_script_and_the_movie_plays_on() {
|
||||
let d = scripted(3, &[(0, "trace(\"a\");\nwhile (true) { }\ntrace(\"never\");"), (1, "trace(\"frame 2\");")], vec![], vec![]);
|
||||
let s = start(&d, &mut NoScripts);
|
||||
assert_eq!(s.output, ["a", "Script on frame 1 of the main timeline stopped: it ran more than 100000 steps (an endless loop?)"]);
|
||||
let s = step(&d, &s.state, &[], &mut NoScripts);
|
||||
assert_eq!((s.state.root.frame, s.output.as_slice()), (1, ["frame 2".to_string()].as_slice()));
|
||||
// A runtime error stops only its script.
|
||||
let d = scripted(2, &[(0, "trace(\"x\");\ntrace(ghost.x);\ntrace(\"y\");")], vec![], vec![]);
|
||||
assert_eq!(start(&d, &mut NoScripts).output, ["x", "Script on frame 1 of the main timeline stopped: line 2: no instance named “ghost” here"]);
|
||||
// Many listeners that each loop share one step's fuel; the step ends with one message.
|
||||
let mut src = String::from("stop();\n");
|
||||
for i in 0..15 {
|
||||
src.push_str(&format!("addEventListener(Event.ENTER_FRAME, function (e:Event):void {{ var n:int = {i}; while (true) n++; }});\n"));
|
||||
}
|
||||
let d = scripted(2, &[(0, &src)], vec![], vec![]);
|
||||
let s = step(&d, &start(&d, &mut NoScripts).state, &[], &mut NoScripts);
|
||||
assert_eq!(s.output.iter().filter(|l| l.ends_with("(an endless loop?)")).count(), 10, "{:?}", s.output);
|
||||
assert!(s.output.last().is_some_and(|l| l.starts_with("Stopped running actions this frame: scripts ran more than 1000000 steps")), "{:?}", s.output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_know_their_target_and_current_target() {
|
||||
let mut d = button_doc();
|
||||
{
|
||||
let tl = d.timeline_mut(0);
|
||||
let l0 = Arc::make_mut(&mut tl.layers[0]);
|
||||
l0.keyframes[0] = as3(l0.keyframes[0].clone(), "stop();\ngo.addEventListener(MouseEvent.CLICK, clicked);\nfunction clicked(e:MouseEvent):void { trace(e.target.name, e.currentTarget == go, e.target != stage, e.currentTarget.x); report(e); }\nfunction report(ev:MouseEvent):void { trace(\"from \" + ev.currentTarget.name); }");
|
||||
let k = Arc::make_mut(&mut Arc::make_mut(&mut tl.layers[1]).keyframes[0]);
|
||||
if let ElementKind::Symbol { events, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind {
|
||||
events.clear();
|
||||
}
|
||||
}
|
||||
let p = Vec2::new(150.0, 150.0);
|
||||
let s = step(&d, &start(&d, &mut NoScripts).state, &[Event::Move(p), Event::Down(p), Event::Up(p)], &mut NoScripts);
|
||||
assert_eq!(s.output, ["go true true 100", "from go"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripted_play_is_deterministic() {
|
||||
let src = "var n:Number = 0;\naddEventListener(Event.ENTER_FRAME, function (e:Event):void { n += Math.random(); if (n > 2) { trace(n); n = 0; } });";
|
||||
let d = scripted(4, &[(0, src)], vec![], vec![]);
|
||||
let play = || {
|
||||
let mut s = start_seeded(&d, 3, &mut NoScripts);
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..40 {
|
||||
s = step(&d, &s.state, &[Event::KeyDown(65)], &mut NoScripts);
|
||||
out.extend(s.output.clone());
|
||||
}
|
||||
(s.state, out)
|
||||
};
|
||||
let (a, b) = (play(), play());
|
||||
assert!(!a.1.is_empty());
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
// ----- text fields (ADR 0066) ---------------------------------------------------------------
|
||||
|
||||
/// A host that lays fields out in a 10 px monospace (the fonts live above this crate).
|
||||
struct Mono;
|
||||
|
||||
impl ScriptHost for Mono {
|
||||
fn run(&mut self, _: &PluginScript, _: &ScriptContext<'_>) -> ScriptRun {
|
||||
ScriptRun::default()
|
||||
}
|
||||
fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option<FieldLook> {
|
||||
let f = block.field.as_ref()?;
|
||||
Some(crate::field::mono_look(shown, 10.0, 10.0, f.wrap_width(block.box_width)))
|
||||
}
|
||||
}
|
||||
|
||||
fn field(id: u64, name: &str, text: &str, kind: TextKind, x: f32, y: f32) -> Arc<Element> {
|
||||
let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }), on_path: None };
|
||||
Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) })
|
||||
}
|
||||
|
||||
fn field_doc(script: &str) -> Document {
|
||||
let fields = vec![field(5, "score_txt", "0", TextKind::Dynamic, 10.0, 10.0), field(6, "name_txt", "", TextKind::Input, 10.0, 50.0), field(7, "", "", TextKind::Input, 10.0, 90.0)];
|
||||
doc(vec![layer(1, vec![as3(kf(0, 1, fields, vec![], ""), script)])], vec![])
|
||||
}
|
||||
|
||||
fn text_of(st: &PlayerState, id: u64) -> Option<String> {
|
||||
st.fields.get(&vec![ElementId(id)]).and_then(|f| f.text.clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_set_and_read_dynamic_text() {
|
||||
let d = field_doc("stop();\nvar n:int = 0;\nscore_txt.text = \"Score: \" + n;\nscore_txt.appendText(\"!\");\ntrace(score_txt.text, score_txt.length, name_txt.text == \"\");\nscore_txt.x = 20;\nghost_txt.text = \"x\";");
|
||||
let s = start(&d, &mut Mono);
|
||||
assert_eq!(text_of(&s.state, 5).as_deref(), Some("Score: 0!"));
|
||||
assert!(s.output.contains(&"Score: 0! 9 true".to_string()), "{:?}", s.output);
|
||||
assert!(s.output.iter().any(|l| l.contains("no instance named “ghost_txt”")), "{:?}", s.output);
|
||||
// Laid out by the host, drawn in place of the authored outline, where the script moved it.
|
||||
let look = s.state.fields.get(&vec![ElementId(5)]).and_then(|f| f.look.clone()).expect("laid out");
|
||||
assert_eq!(look.lines[0].end, 9);
|
||||
let dl = evaluate_player(&d, &s.state);
|
||||
assert!(dl.items.iter().any(|i| Arc::ptr_eq(&i.path, &look.outline) && i.transform.m[4] == 20.0));
|
||||
// Without a host that can lay out, the text is still set and read; it draws only its box.
|
||||
let s2 = start(&d, &mut NoScripts);
|
||||
assert_eq!(text_of(&s2.state, 5).as_deref(), Some("Score: 0!"));
|
||||
// Static text and other instances aren't fields.
|
||||
let d = field_doc("hero.text = \"x\";");
|
||||
assert!(start(&d, &mut Mono).output.iter().any(|l| l.contains("no instance named “hero”")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_viewer_types_into_input_fields_and_scripts_read_it() {
|
||||
let d = field_doc("stop();\nstage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);\nfunction onKey(e:KeyboardEvent):void {\n if (e.keyCode == Keyboard.ENTER) { score_txt.text = \"Hello, \" + name_txt.text; }\n}");
|
||||
let mut h = Mono;
|
||||
let s = start(&d, &mut h);
|
||||
// A click in the input field gives it the keyboard; typing goes in, editing keys edit.
|
||||
let mut ev = vec![Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0))];
|
||||
ev.extend("Adx".chars().map(Event::Char));
|
||||
ev.extend([Event::KeyDown(8), Event::KeyDown(37), Event::Char('a'), Event::KeyDown(35), Event::Char('!')]);
|
||||
let s = input(&d, &s.state, &ev, &mut h);
|
||||
assert_eq!(s.state.focus, Some(vec![ElementId(6)]));
|
||||
assert_eq!(text_of(&s.state, 6).as_deref(), Some("Aad!"));
|
||||
// Shift+Home selects; typing replaces it; Enter reaches the stage's key listener too.
|
||||
let s = input(&d, &s.state, &[Event::KeyDown(16), Event::KeyDown(36), Event::KeyUp(16), Event::Char('B'), Event::Char('o'), Event::KeyDown(13)], &mut h);
|
||||
assert_eq!(text_of(&s.state, 6).as_deref(), Some("Bo"));
|
||||
assert_eq!(text_of(&s.state, 5).as_deref(), Some("Hello, Bo"));
|
||||
// The focused field draws its caret; a click elsewhere takes the keyboard away.
|
||||
let caret = |st: &PlayerState| evaluate_player(&d, st).items.iter().filter(|i| i.fill.is_some() && i.masks.is_none() && i.path.bounds().width() <= 1.01 && i.path.bounds().height() > 5.0).count();
|
||||
assert_eq!(caret(&s.state), 1);
|
||||
let s = input(&d, &s.state, &[Event::Down(Vec2::new(300.0, 300.0)), Event::Up(Vec2::new(300.0, 300.0)), Event::Char('z')], &mut h);
|
||||
assert_eq!(s.state.focus, None);
|
||||
assert_eq!(text_of(&s.state, 6).as_deref(), Some("Bo"), "no field, no typing");
|
||||
assert_eq!(caret(&s.state), 0);
|
||||
// A dynamic field takes no typing; Tab goes from input field to input field.
|
||||
let s = input(&d, &s.state, &[Event::Down(Vec2::new(20.0, 15.0)), Event::Up(Vec2::new(20.0, 15.0)), Event::Char('q')], &mut h);
|
||||
assert_eq!(s.state.focus, Some(vec![ElementId(5)]), "a selectable dynamic field can be focused");
|
||||
assert_eq!(text_of(&s.state, 5).as_deref(), Some("Hello, Bo"));
|
||||
let s = input(&d, &s.state, &[Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0)), Event::KeyDown(9)], &mut h);
|
||||
assert_eq!(s.state.focus, Some(vec![ElementId(7)]));
|
||||
let s = input(&d, &s.state, &[Event::KeyDown(9)], &mut h);
|
||||
assert_eq!(s.state.focus, Some(vec![ElementId(6)]), "Tab wraps round");
|
||||
assert_eq!(s.state.fields.get(&vec![ElementId(6)]).map(|f| f.selection()), Some((0, 2)), "and selects the field's text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fields_draw_their_box_and_the_authored_text_everywhere() {
|
||||
let d = field_doc("");
|
||||
// The authoring frame and the player draw the authored outline, a border, inside a clip.
|
||||
for dl in [evaluate(&d, 0), evaluate_player(&d, &start(&d, &mut NoScripts).state)] {
|
||||
let texts = dl.items.iter().filter(|i| i.path.bounds() == Path::rect(2.0, 2.0, 8.0, 8.0).bounds() && i.masks.is_none()).count();
|
||||
assert_eq!(texts, 3);
|
||||
assert_eq!(dl.items.iter().filter(|i| i.stroke.is_some()).count(), 3, "three borders");
|
||||
assert_eq!(dl.items.iter().filter(|i| i.masks.is_some()).count(), 3, "each box clips its text");
|
||||
assert_eq!(dl.clip_parents.len(), 3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_is_deterministic() {
|
||||
let d = field_doc("stop();");
|
||||
let ev: Vec<Event> = [Event::Down(Vec2::new(30.0, 55.0)), Event::Up(Vec2::new(30.0, 55.0))].into_iter().chain("deterministic".chars().map(Event::Char)).chain([Event::KeyDown(16), Event::KeyDown(37), Event::KeyDown(37), Event::Char('X')]).collect();
|
||||
let a = step(&d, &start(&d, &mut Mono).state, &ev, &mut Mono);
|
||||
let b = step(&d, &start(&d, &mut Mono).state, &ev, &mut Mono);
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(text_of(&a.state, 6).as_deref(), Some("deterministX"));
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
//! Publish Settings (ADR 0060): which formats File › Publish writes, each with its options and
|
||||
//! output name, kept in the document as Animate keeps them.
|
||||
//!
|
||||
//! Every format is always present, in the fixed order Publish runs them; a format is on or off.
|
||||
//! Outputs are templates relative to the document's folder: `{name}` is the document's file name
|
||||
//! without its extension. A file written before publish settings existed has none and gets
|
||||
//! [`PublishProfile::default`] (the HTML canvas page on, the rest off) the first time it opens.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The formats File › Publish can write, in the order it writes them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PublishFormat {
|
||||
Html,
|
||||
Gif,
|
||||
Apng,
|
||||
Webp,
|
||||
Video,
|
||||
Lottie,
|
||||
SpriteSheet,
|
||||
PngSequence,
|
||||
Png,
|
||||
Svg,
|
||||
Audio,
|
||||
}
|
||||
|
||||
impl PublishFormat {
|
||||
/// Every format, in the order Publish runs them.
|
||||
pub const ALL: [PublishFormat; 11] = [
|
||||
PublishFormat::Html,
|
||||
PublishFormat::Gif,
|
||||
PublishFormat::Apng,
|
||||
PublishFormat::Webp,
|
||||
PublishFormat::Video,
|
||||
PublishFormat::Lottie,
|
||||
PublishFormat::SpriteSheet,
|
||||
PublishFormat::PngSequence,
|
||||
PublishFormat::Png,
|
||||
PublishFormat::Svg,
|
||||
PublishFormat::Audio,
|
||||
];
|
||||
|
||||
/// The stable key used by commands and the file format.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
PublishFormat::Html => "html",
|
||||
PublishFormat::Gif => "gif",
|
||||
PublishFormat::Apng => "apng",
|
||||
PublishFormat::Webp => "webp",
|
||||
PublishFormat::Video => "video",
|
||||
PublishFormat::Lottie => "lottie",
|
||||
PublishFormat::SpriteSheet => "sprite_sheet",
|
||||
PublishFormat::PngSequence => "png_sequence",
|
||||
PublishFormat::Png => "png",
|
||||
PublishFormat::Svg => "svg",
|
||||
PublishFormat::Audio => "audio",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_key(key: &str) -> Option<PublishFormat> {
|
||||
PublishFormat::ALL.into_iter().find(|f| f.key() == key)
|
||||
}
|
||||
|
||||
/// The English name of the format (translated where it is drawn).
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
PublishFormat::Html => "HTML canvas",
|
||||
PublishFormat::Gif => "Animated GIF",
|
||||
PublishFormat::Apng => "Animated PNG",
|
||||
PublishFormat::Webp => "Animated WebP",
|
||||
PublishFormat::Video => "Video",
|
||||
PublishFormat::Lottie => "Lottie",
|
||||
PublishFormat::SpriteSheet => "Sprite sheet",
|
||||
PublishFormat::PngSequence => "PNG sequence",
|
||||
PublishFormat::Png => "PNG image",
|
||||
PublishFormat::Svg => "SVG image",
|
||||
PublishFormat::Audio => "Audio",
|
||||
}
|
||||
}
|
||||
|
||||
/// The output a new profile gives the format.
|
||||
pub fn default_output(self) -> &'static str {
|
||||
match self {
|
||||
PublishFormat::Html => "{name}.html",
|
||||
PublishFormat::Gif => "{name}.gif",
|
||||
// Not {name}.png: the PNG image has that.
|
||||
PublishFormat::Apng => "{name}_animated.png",
|
||||
PublishFormat::Webp => "{name}.webp",
|
||||
PublishFormat::Video => "{name}.webm",
|
||||
PublishFormat::Lottie => "{name}.json",
|
||||
PublishFormat::SpriteSheet => "{name}_sheet.png",
|
||||
PublishFormat::PngSequence => "{name}_frames",
|
||||
PublishFormat::Png => "{name}.png",
|
||||
PublishFormat::Svg => "{name}.svg",
|
||||
PublishFormat::Audio => "{name}.wav",
|
||||
}
|
||||
}
|
||||
|
||||
/// The file extensions the output may end in (none for the PNG sequence: a folder).
|
||||
pub fn extensions(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
PublishFormat::Html => &["html", "htm"],
|
||||
PublishFormat::Gif => &["gif"],
|
||||
PublishFormat::Apng => &["png", "apng"],
|
||||
PublishFormat::Webp => &["webp"],
|
||||
PublishFormat::Video => &["webm", "mp4"],
|
||||
PublishFormat::Lottie => &["json"],
|
||||
PublishFormat::SpriteSheet | PublishFormat::Png => &["png"],
|
||||
PublishFormat::PngSequence => &[],
|
||||
PublishFormat::Svg => &["svg"],
|
||||
PublishFormat::Audio => &["wav"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest output template, in characters.
|
||||
pub const MAX_OUTPUT_CHARS: usize = 512;
|
||||
/// Longest HTML page title, in characters.
|
||||
pub const MAX_TITLE_CHARS: usize = 256;
|
||||
/// Largest export scale.
|
||||
pub const MAX_PUBLISH_SCALE: f32 = 8.0;
|
||||
/// Most plays an animated PNG or WebP's loop count says (WebP stores it in 16 bits).
|
||||
pub const MAX_PLAYS: u32 = 65_535;
|
||||
|
||||
/// Movie frames to publish (every scene in order, 0-based): `None` ends are the movie's ends.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct FrameRange {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub from: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub to: Option<u32>,
|
||||
}
|
||||
|
||||
macro_rules! format_settings {
|
||||
($(#[$meta:meta])* $name:ident, $format:expr, $enabled:expr, { $($(#[$fmeta:meta])* $field:ident : $ty:ty = $default:expr),* $(,)? }) => {
|
||||
$(#[$meta])*
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct $name {
|
||||
/// Publish writes this format.
|
||||
pub enabled: bool,
|
||||
/// A path relative to the document's folder; `{name}` is the document's name.
|
||||
pub output: String,
|
||||
$($(#[$fmeta])* pub $field: $ty,)*
|
||||
}
|
||||
impl Default for $name {
|
||||
fn default() -> Self {
|
||||
$name { enabled: $enabled, output: $format.default_output().to_string(), $($field: $default,)* }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
format_settings!(
|
||||
/// The movie as one web page (`file.export_html`, ADR 0028).
|
||||
HtmlSettings, PublishFormat::Html, true, {
|
||||
/// The page's title; empty: the output's file name.
|
||||
title: String = String::new(),
|
||||
sound: bool = true,
|
||||
fit: bool = true,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// An animated GIF (`file.export_gif`).
|
||||
GifSettings, PublishFormat::Gif, false, {
|
||||
range: FrameRange = FrameRange::default(),
|
||||
scale: f32 = 1.0,
|
||||
#[serde(rename = "loop")]
|
||||
looping: bool = true,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// An animated PNG: full colour, real alpha (`file.export_apng`, ADR 0063).
|
||||
ApngSettings, PublishFormat::Apng, false, {
|
||||
range: FrameRange = FrameRange::default(),
|
||||
scale: f32 = 1.0,
|
||||
/// How many times it plays; 0: forever.
|
||||
#[serde(rename = "loop")]
|
||||
plays: u32 = 0,
|
||||
/// The stage colour behind it; off: transparent.
|
||||
background: bool = false,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// An animated WebP, lossless (`file.export_webp`, ADR 0063).
|
||||
WebpSettings, PublishFormat::Webp, false, {
|
||||
range: FrameRange = FrameRange::default(),
|
||||
scale: f32 = 1.0,
|
||||
/// How many times it plays; 0: forever.
|
||||
#[serde(rename = "loop")]
|
||||
plays: u32 = 0,
|
||||
/// The stage colour behind it; off: transparent.
|
||||
background: bool = false,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// WebM or MP4 through the user's ffmpeg (`file.export_video`).
|
||||
VideoSettings, PublishFormat::Video, false, {
|
||||
range: FrameRange = FrameRange::default(),
|
||||
scale: f32 = 1.0,
|
||||
audio: bool = true,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// A Lottie animation (`file.export_lottie`).
|
||||
LottieSettings, PublishFormat::Lottie, false, {
|
||||
range: FrameRange = FrameRange::default(),
|
||||
background: bool = false,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// A sprite sheet and its JSON frame map (`file.export_sprite_sheet`).
|
||||
SpriteSheetSettings, PublishFormat::SpriteSheet, false, {
|
||||
range: FrameRange = FrameRange::default(),
|
||||
scale: f32 = 1.0,
|
||||
/// 0: as square as it can be.
|
||||
columns: u32 = 0,
|
||||
padding: u32 = 0,
|
||||
background: bool = false,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// One PNG per frame in a folder (`file.export_png_sequence`).
|
||||
PngSequenceSettings, PublishFormat::PngSequence, false, {
|
||||
range: FrameRange = FrameRange::default(),
|
||||
scale: f32 = 1.0,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// One frame as a PNG (`file.export_png`).
|
||||
PngSettings, PublishFormat::Png, false, {
|
||||
/// The movie frame (0-based, every scene in order).
|
||||
frame: u32 = 0,
|
||||
scale: f32 = 1.0,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// One frame as an SVG (`file.export_svg`).
|
||||
SvgSettings, PublishFormat::Svg, false, {
|
||||
/// The movie frame (0-based, every scene in order).
|
||||
frame: u32 = 0,
|
||||
}
|
||||
);
|
||||
format_settings!(
|
||||
/// The movie's soundtrack as a WAV (`file.export_audio`).
|
||||
AudioSettings, PublishFormat::Audio, false, {
|
||||
range: FrameRange = FrameRange::default(),
|
||||
rate: u32 = 44_100,
|
||||
/// 16, 24, or 32 (float).
|
||||
bits: u32 = 16,
|
||||
}
|
||||
);
|
||||
|
||||
/// What File › Publish writes: every format with its options (ADR 0060).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct PublishProfile {
|
||||
pub html: HtmlSettings,
|
||||
pub gif: GifSettings,
|
||||
pub apng: ApngSettings,
|
||||
pub webp: WebpSettings,
|
||||
pub video: VideoSettings,
|
||||
pub lottie: LottieSettings,
|
||||
pub sprite_sheet: SpriteSheetSettings,
|
||||
pub png_sequence: PngSequenceSettings,
|
||||
pub png: PngSettings,
|
||||
pub svg: SvgSettings,
|
||||
pub audio: AudioSettings,
|
||||
}
|
||||
|
||||
fn clean_scale(s: f32) -> f32 {
|
||||
if s.is_finite() && s > 0.0 { s.min(MAX_PUBLISH_SCALE) } else { 1.0 }
|
||||
}
|
||||
|
||||
fn clip(s: &mut String, max: usize) {
|
||||
if s.chars().count() > max {
|
||||
*s = s.chars().take(max).collect();
|
||||
}
|
||||
}
|
||||
|
||||
impl PublishProfile {
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == PublishProfile::default()
|
||||
}
|
||||
|
||||
/// Whether Publish writes `f`, and its output template.
|
||||
pub fn target(&self, f: PublishFormat) -> (bool, &str) {
|
||||
match f {
|
||||
PublishFormat::Html => (self.html.enabled, &self.html.output),
|
||||
PublishFormat::Gif => (self.gif.enabled, &self.gif.output),
|
||||
PublishFormat::Apng => (self.apng.enabled, &self.apng.output),
|
||||
PublishFormat::Webp => (self.webp.enabled, &self.webp.output),
|
||||
PublishFormat::Video => (self.video.enabled, &self.video.output),
|
||||
PublishFormat::Lottie => (self.lottie.enabled, &self.lottie.output),
|
||||
PublishFormat::SpriteSheet => (self.sprite_sheet.enabled, &self.sprite_sheet.output),
|
||||
PublishFormat::PngSequence => (self.png_sequence.enabled, &self.png_sequence.output),
|
||||
PublishFormat::Png => (self.png.enabled, &self.png.output),
|
||||
PublishFormat::Svg => (self.svg.enabled, &self.svg.output),
|
||||
PublishFormat::Audio => (self.audio.enabled, &self.audio.output),
|
||||
}
|
||||
}
|
||||
|
||||
/// `f`'s on/off switch and output template, to change.
|
||||
pub fn target_mut(&mut self, f: PublishFormat) -> (&mut bool, &mut String) {
|
||||
match f {
|
||||
PublishFormat::Html => (&mut self.html.enabled, &mut self.html.output),
|
||||
PublishFormat::Gif => (&mut self.gif.enabled, &mut self.gif.output),
|
||||
PublishFormat::Apng => (&mut self.apng.enabled, &mut self.apng.output),
|
||||
PublishFormat::Webp => (&mut self.webp.enabled, &mut self.webp.output),
|
||||
PublishFormat::Video => (&mut self.video.enabled, &mut self.video.output),
|
||||
PublishFormat::Lottie => (&mut self.lottie.enabled, &mut self.lottie.output),
|
||||
PublishFormat::SpriteSheet => (&mut self.sprite_sheet.enabled, &mut self.sprite_sheet.output),
|
||||
PublishFormat::PngSequence => (&mut self.png_sequence.enabled, &mut self.png_sequence.output),
|
||||
PublishFormat::Png => (&mut self.png.enabled, &mut self.png.output),
|
||||
PublishFormat::Svg => (&mut self.svg.enabled, &mut self.svg.output),
|
||||
PublishFormat::Audio => (&mut self.audio.enabled, &mut self.audio.output),
|
||||
}
|
||||
}
|
||||
|
||||
/// The formats that are on, in publishing order.
|
||||
pub fn enabled(&self) -> Vec<PublishFormat> {
|
||||
PublishFormat::ALL.into_iter().filter(|f| self.target(*f).0).collect()
|
||||
}
|
||||
|
||||
/// Brings every value into range, so whatever a file holds, publishing can run: scales in
|
||||
/// (0, 8], a known sample rate and bit depth, bounded text.
|
||||
pub fn sanitize(&mut self) {
|
||||
for f in PublishFormat::ALL {
|
||||
let (_, output) = self.target_mut(f);
|
||||
clip(output, MAX_OUTPUT_CHARS);
|
||||
if output.trim().is_empty() {
|
||||
*output = f.default_output().to_string();
|
||||
}
|
||||
}
|
||||
clip(&mut self.html.title, MAX_TITLE_CHARS);
|
||||
for s in [&mut self.gif.scale, &mut self.apng.scale, &mut self.webp.scale, &mut self.video.scale, &mut self.sprite_sheet.scale, &mut self.png_sequence.scale, &mut self.png.scale] {
|
||||
*s = clean_scale(*s);
|
||||
}
|
||||
self.sprite_sheet.padding = self.sprite_sheet.padding.min(256);
|
||||
self.apng.plays = self.apng.plays.min(MAX_PLAYS);
|
||||
self.webp.plays = self.webp.plays.min(MAX_PLAYS);
|
||||
self.sprite_sheet.columns = self.sprite_sheet.columns.min(10_000);
|
||||
self.audio.rate = self.audio.rate.clamp(8_000, 192_000);
|
||||
if !matches!(self.audio.bits, 16 | 24 | 32) {
|
||||
self.audio.bits = 16;
|
||||
}
|
||||
for r in [&mut self.gif.range, &mut self.apng.range, &mut self.webp.range, &mut self.video.range, &mut self.lottie.range, &mut self.sprite_sheet.range, &mut self.png_sequence.range, &mut self.audio.range] {
|
||||
if let (Some(a), Some(b)) = (r.from, r.to)
|
||||
&& b < a
|
||||
{
|
||||
*r = FrameRange { from: Some(b), to: Some(a) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keys_round_trip_and_defaults_are_distinct() {
|
||||
for f in PublishFormat::ALL {
|
||||
assert_eq!(PublishFormat::from_key(f.key()), Some(f));
|
||||
}
|
||||
let p = PublishProfile::default();
|
||||
assert_eq!(p.enabled(), vec![PublishFormat::Html], "a new document publishes its web page");
|
||||
let mut outs: Vec<&str> = PublishFormat::ALL.iter().map(|f| p.target(*f).1).collect();
|
||||
outs.sort_unstable();
|
||||
outs.dedup();
|
||||
assert_eq!(outs.len(), PublishFormat::ALL.len(), "no two formats write the same file by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_round_trips_and_missing_fields_default() {
|
||||
let mut p = PublishProfile::default();
|
||||
p.gif.enabled = true;
|
||||
p.gif.scale = 0.5;
|
||||
p.gif.looping = false;
|
||||
p.gif.range = FrameRange { from: Some(2), to: Some(9) };
|
||||
p.html.title = "Walk".into();
|
||||
p.audio.bits = 24;
|
||||
let text = serde_json::to_string(&p).unwrap();
|
||||
assert!(text.contains("\"loop\":false") && text.contains("\"enabled\":true"), "{text}");
|
||||
let back: PublishProfile = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(back, p);
|
||||
// A profile from an older build, with fields and formats missing.
|
||||
let partial: PublishProfile = serde_json::from_str(r#"{"gif": {"enabled": true}}"#).unwrap();
|
||||
assert!(partial.gif.enabled && partial.html.enabled);
|
||||
assert_eq!(partial.gif.output, "{name}.gif");
|
||||
assert_eq!(partial.gif.scale, 1.0);
|
||||
assert_eq!((partial.apng.plays, partial.webp.background, partial.webp.enabled), (0, false, false), "formats newer than the file get their defaults");
|
||||
let mut q = PublishProfile::default();
|
||||
q.apng.plays = 3;
|
||||
q.webp.background = true;
|
||||
let text = serde_json::to_string(&q).unwrap();
|
||||
assert!(text.contains("\"apng\"") && text.contains("\"loop\":3"), "{text}");
|
||||
assert_eq!(serde_json::from_str::<PublishProfile>(&text).unwrap(), q);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_brings_everything_into_range() {
|
||||
let mut p = PublishProfile::default();
|
||||
p.gif.scale = f32::NAN;
|
||||
p.png.scale = 1e9;
|
||||
p.audio.rate = 5;
|
||||
p.audio.bits = 7;
|
||||
p.sprite_sheet.padding = u32::MAX;
|
||||
p.webp.plays = u32::MAX;
|
||||
p.video.output = " ".into();
|
||||
p.html.title = "x".repeat(10_000);
|
||||
p.lottie.range = FrameRange { from: Some(9), to: Some(2) };
|
||||
p.sanitize();
|
||||
assert_eq!((p.gif.scale, p.png.scale, p.audio.rate, p.audio.bits, p.sprite_sheet.padding), (1.0, MAX_PUBLISH_SCALE, 8_000, 16, 256));
|
||||
assert_eq!(p.video.output, "{name}.webm");
|
||||
assert_eq!(p.webp.plays, MAX_PLAYS);
|
||||
assert_eq!(p.html.title.chars().count(), MAX_TITLE_CHARS);
|
||||
assert_eq!(p.lottie.range, FrameRange { from: Some(2), to: Some(9) });
|
||||
}
|
||||
}
|
||||
@@ -41,19 +41,19 @@ fn key(start: u32, duration: u32, elements: Vec<Arc<Element>>, tween: Option<Eas
|
||||
|
||||
/// Builds the demo document: a bouncing ball, a spinning star, a pulsing sun over hills.
|
||||
pub fn demo() -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), 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()), 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;
|
||||
@@ -101,7 +101,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 +132,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 +147,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(), library_tree: Default::default(), 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()), next_id: 1 };
|
||||
const LEN: u32 = 36;
|
||||
let solid = |c: u32| Paint::Solid(Rgba::hex(c));
|
||||
|
||||
@@ -161,7 +161,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 +175,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 +211,7 @@ pub fn interactive() -> Document {
|
||||
/// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens.
|
||||
/// Every element keeps one `Arc<Path>` across its keyframes, as a real tweened shape does.
|
||||
pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), 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()), 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 +249,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();
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
//! Shape armatures (ADR 0071): bones drawn inside one shape, whose outline bends with them.
|
||||
//!
|
||||
//! A shape armature is an [`Armature`] with a [`Skin`]. Its bones join *joint nodes* instead of
|
||||
//! symbol instances: the root bones start on the shape itself (its element id) and every other
|
||||
//! bone starts on the node of the bone it hangs from. A node is a frame that the bone into it
|
||||
//! turns; at rest every node's frame is the shape's own local space, so a bone's head and tail
|
||||
//! are points of the shape as it was drawn, and a node's transform under a pose is the bone's
|
||||
//! **skinning matrix**. Forward and inverse kinematics are ADR 0043's ([`crate::armature::place`],
|
||||
//! [`crate::armature::solve`]): nothing about posing is new.
|
||||
//!
|
||||
//! The skin keeps the outline as it was drawn (`rest`) and one [`Binding`] per anchor of it
|
||||
//! (every `MoveTo`, `LineTo`, `QuadTo` and `CubicTo` end, in path order): the bones the anchor
|
||||
//! follows and how much. Automatic binding ([`auto_binding`]) weighs each bone by the inverse
|
||||
//! fourth power of the anchor's distance to the bone's segment, keeps the strongest
|
||||
//! [`MAX_INFLUENCES`] and normalises them to sum to 1; the Bind tool (`bone.bind`) overrides
|
||||
//! anchors by hand. The posed outline ([`deform`]) is linear blend skinning: each anchor moves
|
||||
//! by the weighted sum of its bones' matrices, and each handle by the blend of the anchor it
|
||||
//! belongs to, so curves stay smooth through a bend. Stroke width is drawn after the outline
|
||||
//! (the shape's own transform is untouched), so strokes keep their width.
|
||||
//!
|
||||
//! Linear blend skinning is the standard method (N. Magnenat-Thalmann, R. Laperrière and
|
||||
//! D. Thalmann, *Joint-dependent local deformations for hand animation and object grasping*,
|
||||
//! Graphics Interface 1988; J. P. Lewis, M. Cordner and N. Fong, *Pose space deformation*,
|
||||
//! SIGGRAPH 2000, §2, which names it skeleton subspace deformation).
|
||||
|
||||
use crate::armature::{Armature, BoneId, Pose};
|
||||
use crate::{Element, ElementId, ElementKind};
|
||||
use anicraft_geom::{Affine, Path, PathCmd, Vec2, segment_distance};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Most bones one anchor follows.
|
||||
pub const MAX_INFLUENCES: usize = 4;
|
||||
/// Most anchors a shape with bones may have (a hand-drawn shape has tens to a few thousand).
|
||||
pub const MAX_SKIN_POINTS: usize = 20_000;
|
||||
/// Distances below this count as this (px), so an anchor on a bone has a finite weight.
|
||||
const NEAR: f32 = 0.5;
|
||||
/// A bone whose share is below this after normalising is dropped from the anchor.
|
||||
const FAINT: f32 = 0.01;
|
||||
|
||||
/// One bone's share of an anchor: `[bone, weight]` in files.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Influence(pub BoneId, pub f32);
|
||||
|
||||
/// The bones one anchor follows. Weights are positive and sum to 1; an anchor with none stays
|
||||
/// where it was drawn.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Binding {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub bones: Vec<Influence>,
|
||||
/// Set with the Bind tool: automatic binding (after adding or removing a bone) leaves it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub manual: bool,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
/// The share bone `b` has of this anchor (0 when it doesn't follow it).
|
||||
pub fn weight(&self, b: BoneId) -> f32 {
|
||||
self.bones.iter().find(|i| i.0 == b).map_or(0.0, |i| i.1)
|
||||
}
|
||||
|
||||
/// Keeps positive, finite weights of bones in `keep` (one each, the strongest
|
||||
/// [`MAX_INFLUENCES`]) and scales them to sum to 1. Returns whether anything changed.
|
||||
pub fn normalize(&mut self, keep: impl Fn(BoneId) -> bool) -> bool {
|
||||
let before = self.bones.clone();
|
||||
let mut seen = Vec::with_capacity(self.bones.len());
|
||||
self.bones.retain(|i| i.1.is_finite() && i.1 > 0.0 && keep(i.0) && !seen.contains(&i.0) && {
|
||||
seen.push(i.0);
|
||||
true
|
||||
});
|
||||
self.bones.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
self.bones.truncate(MAX_INFLUENCES);
|
||||
let sum: f32 = self.bones.iter().map(|i| i.1).sum();
|
||||
if sum > 0.0 && sum.is_finite() {
|
||||
for i in &mut self.bones {
|
||||
i.1 /= sum;
|
||||
}
|
||||
} else {
|
||||
self.bones.clear();
|
||||
}
|
||||
self.bones != before
|
||||
}
|
||||
}
|
||||
|
||||
/// How a shape is bound to its armature's bones.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Skin {
|
||||
/// The shape the bones are inside (an element of the armature layer's keyframes).
|
||||
pub shape: ElementId,
|
||||
/// The outline as it was drawn, in the shape's local space: the pose of every bone at 0.
|
||||
pub rest: Arc<Path>,
|
||||
/// One per anchor of `rest`, in path order.
|
||||
#[serde(default)]
|
||||
pub points: Vec<Binding>,
|
||||
}
|
||||
|
||||
impl Skin {
|
||||
/// A skin for `shape` drawn as `rest`, its anchors not yet bound.
|
||||
pub fn new(shape: ElementId, rest: Arc<Path>) -> Skin {
|
||||
let points = vec![Binding::default(); anchors(&rest).len()];
|
||||
Skin { shape, rest, points }
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors of `path` in order: every command's end point.
|
||||
pub fn anchors(path: &Path) -> Vec<Vec2> {
|
||||
path.cmds
|
||||
.iter()
|
||||
.filter_map(|c| match *c {
|
||||
PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p),
|
||||
PathCmd::Close => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where every bone of a shape armature lies as drawn, in the shape's space: its joint and end.
|
||||
pub fn rest_segments(arm: &Armature) -> Vec<(BoneId, Vec2, Vec2)> {
|
||||
// Every node's rest frame is the shape's space (`rest` is the identity for shape bones), so
|
||||
// composing the rests places each bone; a hand-edited file with other rests still works.
|
||||
let mut node: HashMap<ElementId, Affine> = HashMap::new();
|
||||
let root = arm.skin.as_ref().map(|s| s.shape);
|
||||
arm.bones
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
let wp = if Some(b.parent) == root { Affine::IDENTITY } else { *node.get(&b.parent)? };
|
||||
let wc = wp.mul(&b.rest);
|
||||
node.insert(b.child, wc);
|
||||
Some((b.id, wp.apply(b.head), wc.apply(b.tail)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Automatic binding of an anchor at `p` (the shape's space, as drawn): each bone weighs
|
||||
/// `1 / max(d, 0.5)⁴` where `d` is the distance from `p` to the bone's segment; the strongest
|
||||
/// [`MAX_INFLUENCES`] are kept, faint ones (under 1 %) dropped, and the rest sum to 1. An anchor
|
||||
/// near one bone follows it alone; one near a joint shares it between the bones that meet
|
||||
/// there, so the outline bends smoothly. Empty only without bones.
|
||||
pub fn auto_binding(segments: &[(BoneId, Vec2, Vec2)], p: Vec2) -> Binding {
|
||||
let mut bones: Vec<Influence> = segments
|
||||
.iter()
|
||||
.map(|&(id, a, b)| {
|
||||
let d = segment_distance(p, a, b).max(NEAR);
|
||||
Influence(id, 1.0 / (d * d * d * d))
|
||||
})
|
||||
.filter(|i| i.1.is_finite() && i.1 > 0.0)
|
||||
.collect();
|
||||
// Weighed relative to the nearest bone, so a far-away shape keeps finite numbers.
|
||||
let top = bones.iter().map(|i| i.1).fold(0.0f32, f32::max);
|
||||
if top > 0.0 {
|
||||
for i in &mut bones {
|
||||
i.1 /= top;
|
||||
}
|
||||
}
|
||||
let mut out = Binding { bones, manual: false };
|
||||
out.normalize(|_| true);
|
||||
let before = out.bones.len();
|
||||
out.bones.retain(|i| i.1 >= FAINT);
|
||||
if out.bones.len() != before {
|
||||
out.normalize(|_| true);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Binds every anchor not bound by hand afresh (after the bones changed), and repairs the hand
|
||||
/// bound ones: bones that went away leave them, and one left with none goes back to automatic
|
||||
/// (an anchor unbound by hand on purpose stays unbound). Keeps one binding per anchor.
|
||||
pub fn rebind(arm: &mut Armature) {
|
||||
let segments = rest_segments(arm);
|
||||
let ids: Vec<BoneId> = arm.bones.iter().map(|b| b.id).collect();
|
||||
let Some(skin) = arm.skin.as_mut() else { return };
|
||||
let pts = anchors(&skin.rest);
|
||||
skin.points.resize(pts.len(), Binding::default());
|
||||
for (b, &p) in skin.points.iter_mut().zip(&pts) {
|
||||
if b.manual {
|
||||
let had = !b.bones.is_empty();
|
||||
b.normalize(|id| ids.contains(&id));
|
||||
if !had || !b.bones.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
*b = auto_binding(&segments, p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every bone's skinning matrix under `pose`: how the pose moves the shape's space near it (the
|
||||
/// identity at rest, exactly).
|
||||
pub fn matrices(arm: &Armature, pose: &Pose) -> HashMap<BoneId, Affine> {
|
||||
let Some(skin) = &arm.skin else { return HashMap::new() };
|
||||
let mut node: HashMap<ElementId, Affine> = HashMap::new();
|
||||
node.insert(skin.shape, Affine::IDENTITY);
|
||||
let mut out = HashMap::with_capacity(arm.bones.len());
|
||||
for b in &arm.bones {
|
||||
let Some(wp) = node.get(&b.parent).copied() else { continue };
|
||||
let a = b.allow(pose.angle(b.id));
|
||||
let wc = if a == 0.0 { wp.mul(&b.rest) } else { crate::armature::turn_about(wp.apply(b.head), a).mul(&wp.mul(&b.rest)) };
|
||||
if wc.is_finite() {
|
||||
node.insert(b.child, wc);
|
||||
out.insert(b.id, wc);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The blend of `binding`'s bone matrices; `None` when it doesn't move (no bones, or every one
|
||||
/// of them at rest), so a point at rest is kept bit for bit.
|
||||
fn blend(binding: &Binding, m: &HashMap<BoneId, Affine>) -> Option<Affine> {
|
||||
let mut moved = false;
|
||||
let mut acc = [0.0f32; 6];
|
||||
let mut total = 0.0f32;
|
||||
for &Influence(b, w) in &binding.bones {
|
||||
let x = m.get(&b).copied().unwrap_or(Affine::IDENTITY);
|
||||
moved |= x != Affine::IDENTITY;
|
||||
for (a, v) in acc.iter_mut().zip(x.m) {
|
||||
*a += w * v;
|
||||
}
|
||||
total += w;
|
||||
}
|
||||
if !moved || total <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// Weights sum to 1; dividing keeps a hand-edited file's rounding from scaling the shape.
|
||||
Some(Affine { m: acc.map(|v| v / total) })
|
||||
}
|
||||
|
||||
fn mix(a: Option<Affine>, b: Option<Affine>) -> Option<Affine> {
|
||||
match (a, b) {
|
||||
(None, None) => None,
|
||||
(a, b) => {
|
||||
let (a, b) = (a.unwrap_or(Affine::IDENTITY), b.unwrap_or(Affine::IDENTITY));
|
||||
let mut m = [0.0f32; 6];
|
||||
for (i, v) in m.iter_mut().enumerate() {
|
||||
*v = 0.5 * (a.m.get(i).copied().unwrap_or(0.0) + b.m.get(i).copied().unwrap_or(0.0));
|
||||
}
|
||||
Some(Affine { m })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline `pose` bends the skin's shape into (the shape's space): linear blend skinning of
|
||||
/// every anchor, each cubic handle moving with the anchor it leaves or enters and a quadratic's
|
||||
/// control with the mean of its two ends. At rest (or where no bound bone turned) points are
|
||||
/// exactly as drawn.
|
||||
pub fn deform(arm: &Armature, pose: &Pose) -> Option<Arc<Path>> {
|
||||
let skin = arm.skin.as_ref()?;
|
||||
let m = matrices(arm, pose);
|
||||
if m.values().all(|x| *x == Affine::IDENTITY) {
|
||||
return Some(skin.rest.clone());
|
||||
}
|
||||
let none = Binding::default();
|
||||
let mut idx = 0usize;
|
||||
let at = |i: usize| blend(skin.points.get(i).unwrap_or(&none), &m);
|
||||
let on = |x: Option<Affine>, p: Vec2| x.map_or(p, |x| x.apply(p));
|
||||
let mut prev: Option<Affine> = None;
|
||||
let mut cmds = Vec::with_capacity(skin.rest.cmds.len());
|
||||
for c in &skin.rest.cmds {
|
||||
let next = match *c {
|
||||
PathCmd::Close => {
|
||||
cmds.push(PathCmd::Close);
|
||||
continue;
|
||||
}
|
||||
_ => at(idx),
|
||||
};
|
||||
idx += 1;
|
||||
cmds.push(match *c {
|
||||
PathCmd::MoveTo(p) => PathCmd::MoveTo(on(next, p)),
|
||||
PathCmd::LineTo(p) => PathCmd::LineTo(on(next, p)),
|
||||
PathCmd::QuadTo(q, p) => PathCmd::QuadTo(on(mix(prev, next), q), on(next, p)),
|
||||
PathCmd::CubicTo(c1, c2, p) => PathCmd::CubicTo(on(prev, c1), on(next, c2), on(next, p)),
|
||||
PathCmd::Close => PathCmd::Close,
|
||||
});
|
||||
prev = next;
|
||||
}
|
||||
Some(Arc::new(Path { cmds }))
|
||||
}
|
||||
|
||||
/// Puts the skin's shape in `elements` in the outline `pose` bends it into (copy-on-write).
|
||||
/// Returns whether it changed.
|
||||
pub fn apply(arm: &Armature, elements: &mut [Arc<Element>], pose: &Pose) -> bool {
|
||||
let Some(skin) = &arm.skin else { return false };
|
||||
let Some(e) = elements.iter_mut().find(|e| e.id == skin.shape) else { return false };
|
||||
let ElementKind::Shape(s) = &e.kind else { return false };
|
||||
let Some(path) = deform(arm, pose) else { return false };
|
||||
if Arc::ptr_eq(&s.path, &path) || *s.path == *path {
|
||||
return false;
|
||||
}
|
||||
if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind {
|
||||
s.path = path;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The points of a shape armature's shape in `elements` (evaluated: posed), in point order, in
|
||||
/// the layer's space: the anchors of its outline as it shows.
|
||||
pub fn points_shown(arm: &Armature, elements: &[Arc<Element>]) -> Vec<Vec2> {
|
||||
let Some(skin) = &arm.skin else { return Vec::new() };
|
||||
elements
|
||||
.iter()
|
||||
.find(|e| e.id == skin.shape)
|
||||
.and_then(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => Some(anchors(&sh.path).into_iter().map(|p| e.transform.apply(p)).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Repairs a loaded skin against its armature: the rest outline within [`MAX_SKIN_POINTS`]
|
||||
/// anchors (else the skin goes), one binding per anchor, weights of bones that exist, positive
|
||||
/// and summing to 1; unbound automatic anchors are bound. Returns whether anything changed.
|
||||
pub fn sanitize(arm: &mut Armature) -> bool {
|
||||
let Some(skin) = &arm.skin else { return false };
|
||||
let n = anchors(&skin.rest).len();
|
||||
if n > MAX_SKIN_POINTS || arm.bones.iter().any(|b| b.child == skin.shape) {
|
||||
arm.skin = None;
|
||||
return true;
|
||||
}
|
||||
let before = arm.skin.clone();
|
||||
let ids: Vec<BoneId> = arm.bones.iter().map(|b| b.id).collect();
|
||||
let segments = rest_segments(arm);
|
||||
let Some(skin) = arm.skin.as_mut() else { return false };
|
||||
let pts = anchors(&skin.rest);
|
||||
skin.points.resize(n, Binding::default());
|
||||
for (b, &p) in skin.points.iter_mut().zip(&pts) {
|
||||
b.normalize(|id| ids.contains(&id));
|
||||
if b.bones.is_empty() && !b.manual {
|
||||
*b = auto_binding(&segments, p);
|
||||
}
|
||||
}
|
||||
arm.skin != before
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "skin_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,301 @@
|
||||
//! 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 { id, name: String::new(), parent, child, head, tail, rest: Affine::IDENTITY, limits: None, pinned: false }
|
||||
}
|
||||
|
||||
/// A tail 200 px long and 20 px thick along y = 0 (anchors every 25 px along both edges), with
|
||||
/// a cubic tip, drawn at (100, 100) on the stage; two bones along its middle meet at x = 100.
|
||||
fn outline() -> Path {
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(0.0, -10.0));
|
||||
for i in 1..=8 {
|
||||
p.line_to(Vec2::new(25.0 * i as f32, -10.0));
|
||||
}
|
||||
p.cubic_to(Vec2::new(215.0, -10.0), Vec2::new(215.0, 10.0), Vec2::new(200.0, 10.0));
|
||||
for i in (0..8).rev() {
|
||||
p.line_to(Vec2::new(25.0 * i as f32, 10.0));
|
||||
}
|
||||
p.close();
|
||||
p
|
||||
}
|
||||
|
||||
fn rig() -> (Armature, Vec<Arc<Element>>) {
|
||||
let path = Arc::new(outline());
|
||||
let mut arm = Armature {
|
||||
bones: vec![bone(B1, TAIL, N1, Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)), bone(B2, N1, N2, Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0))],
|
||||
skin: Some(Skin::new(TAIL, path.clone())),
|
||||
};
|
||||
rebind(&mut arm);
|
||||
let shape = Shape { path, ..Shape::filled(Path::new(), Paint::Solid(Rgba::BLACK)) }.with_stroke(Rgba::BLACK, 3.0);
|
||||
let el = Arc::new(Element { id: TAIL, name: String::new(), transform: Affine::translate(100.0, 100.0), color: ColorEffect::default(), kind: ElementKind::Shape(shape) });
|
||||
(arm, vec![el])
|
||||
}
|
||||
|
||||
fn path_of(els: &[Arc<Element>]) -> Arc<Path> {
|
||||
match &els[0].kind {
|
||||
ElementKind::Shape(s) => s.path.clone(),
|
||||
_ => panic!("not a shape"),
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: Vec2, b: Vec2, tol: f32) -> bool {
|
||||
a.distance(b) <= tol
|
||||
}
|
||||
|
||||
/// `p` turned by `a` about `j`.
|
||||
fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 {
|
||||
let (s, c) = a.sin_cos();
|
||||
let d = p - j;
|
||||
Vec2::new(j.x + d.x * c - d.y * s, j.y + d.x * s + d.y * c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_weights_sum_to_one_and_follow_the_nearest_bone() {
|
||||
let (arm, _) = rig();
|
||||
let skin = arm.skin.as_ref().unwrap();
|
||||
let pts = anchors(&skin.rest);
|
||||
assert_eq!(skin.points.len(), pts.len(), "one binding per anchor");
|
||||
for (b, p) in skin.points.iter().zip(&pts) {
|
||||
let sum: f32 = b.bones.iter().map(|i| i.1).sum();
|
||||
assert!((sum - 1.0).abs() < 1e-5, "{p:?}: weights sum to {sum}");
|
||||
assert!(b.bones.len() <= MAX_INFLUENCES && b.bones.iter().all(|i| i.1 > 0.0));
|
||||
}
|
||||
// Far along each bone an anchor follows it alone; at the joint the two share it equally.
|
||||
let at = |x: f32| skin.points.iter().zip(&pts).find(|(_, p)| **p == Vec2::new(x, -10.0)).map(|(b, _)| b.clone()).unwrap();
|
||||
assert_eq!(at(25.0).bones, vec![Influence(B1, 1.0)]);
|
||||
assert_eq!(at(175.0).bones, vec![Influence(B2, 1.0)]);
|
||||
let joint = at(100.0);
|
||||
assert!((joint.weight(B1) - 0.5).abs() < 1e-5 && (joint.weight(B2) - 0.5).abs() < 1e-5, "{joint:?}");
|
||||
// In between the nearer bone weighs more.
|
||||
let near = at(125.0);
|
||||
assert!(near.weight(B2) > near.weight(B1) && near.weight(B1) > 0.0, "{near:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rest_pose_reproduces_the_shape_exactly() {
|
||||
let (arm, mut els) = rig();
|
||||
let drawn = path_of(&els);
|
||||
// No pose, and a pose that lists every bone at 0.
|
||||
for pose in [Pose::default(), Pose(vec![crate::JointAngle { bone: B1, angle: 0.0 }, crate::JointAngle { bone: B2, angle: 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))) };
|
||||
let t = std::time::Instant::now();
|
||||
rebind(&mut arm);
|
||||
let bind = t.elapsed();
|
||||
let pose = Pose(arm.bones.iter().map(|b| crate::JointAngle { bone: b.id, angle: 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:?}");
|
||||
}
|
||||
@@ -445,7 +445,7 @@ fn sounding_symbols(doc: &Document) -> HashSet<SymbolId> {
|
||||
if k.sound.is_some() && set.insert(sym.id) {
|
||||
queue.push(sym.id);
|
||||
}
|
||||
for el in &k.elements {
|
||||
for el in crate::expand_groups(&k.elements).iter() {
|
||||
if let ElementKind::Symbol { symbol, .. } = &el.kind {
|
||||
shown_in.entry(*symbol).or_default().push(sym.id);
|
||||
}
|
||||
@@ -485,7 +485,8 @@ impl<'a> Layout<'a> {
|
||||
if let Some(fs) = &k.sound {
|
||||
self.sound(fs, k, st, gain);
|
||||
}
|
||||
for el in &k.elements {
|
||||
// (A symbol inside a group plays as if it were on the group's layer, ADR 0073.)
|
||||
for el in crate::expand_groups(&k.elements).iter() {
|
||||
if matches!(&el.kind, ElementKind::Symbol { symbol, .. } if self.sounding.contains(symbol)) {
|
||||
self.instance(layer, k, el, st, gain, depth);
|
||||
}
|
||||
@@ -565,7 +566,7 @@ impl<'a> Layout<'a> {
|
||||
let enters = pa == s0 || (pa == st.l0 && st.enters);
|
||||
self.looped(tl, g, (pa - s0) % len, n, len, enters, gain, depth);
|
||||
}
|
||||
// Buttons wait for the pointer: their sounds are not in this slice (ADR 0039).
|
||||
// Buttons sound only under the pointer, in the interactive player (ADR 0057).
|
||||
(SymbolKind::Button, _) => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ fn nested(kind: SymbolKind, len: u32, inner: &[(u32, u32, Option<FrameSound>)],
|
||||
// Pad the symbol's timeline to `len` frames with a second, silent layer.
|
||||
let mut pad = Layer::new(LayerId(11), "pad");
|
||||
pad.keyframes = vec![Arc::new(Keyframe::new(0, len))];
|
||||
d.library.push(Arc::new(Symbol { linkage: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } }));
|
||||
d.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(50), name: "S".into(), kind, timeline: Timeline { layers: vec![Arc::new(il), Arc::new(pad)] } }));
|
||||
let mut l = Layer::new(LayerId(1), "outer");
|
||||
l.keyframes = instances
|
||||
.iter()
|
||||
@@ -347,7 +347,7 @@ fn start_skips_a_playing_sound_and_stop_cuts_it() {
|
||||
fn scenes_play_in_order_guides_are_silent_and_missing_sounds_are_skipped() {
|
||||
let mut d = doc_with(&[(0, 3, with(SoundSync::Event, 1, false))], vec![ramp_sound(7, 100)]);
|
||||
let first = d.scenes[0].clone();
|
||||
d.scenes.insert(0, Arc::new(Scene { name: "Intro".into(), timeline: first.timeline.clone() }));
|
||||
d.scenes.insert(0, Arc::new(Scene { name: "Intro".into(), timeline: first.timeline.clone(), guides: Vec::new() }));
|
||||
assert_eq!(spans(&voices(&d, 8000)), vec![(VoiceKind::Event, 0, 100), (VoiceKind::Event, 3000, 3100)]);
|
||||
Arc::make_mut(&mut d.timeline_mut(0).layers[0]).kind = LayerKind::Guide;
|
||||
assert_eq!(voices(&d, 8000).len(), 1, "guide layers are not exported, so not heard");
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! The document's swatches (ADR 0078): saved colours and gradients, as Animate keeps them per
|
||||
//! document in its Swatches panel.
|
||||
//!
|
||||
//! A swatch is a colour (with alpha) or a gradient's ramp and options, never its geometry: a
|
||||
//! gradient swatch poured on a shape is fitted to it, as a new gradient is. A new document
|
||||
//! starts with [`default_set`]; a document file that has no swatches (every file before ADR
|
||||
//! 0078) opens with that set too, and the set is not written while it is unchanged.
|
||||
//!
|
||||
//! GIMP palettes (`.gpl`, an open plain-text format) import through [`parse_gpl`].
|
||||
|
||||
use crate::{GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Spread, is_false, is_zero};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Most swatches a document keeps (Animate's panel holds a few hundred at most).
|
||||
pub const MAX_SWATCHES: usize = 1024;
|
||||
/// Longest swatch name, in characters.
|
||||
pub const MAX_SWATCH_NAME: usize = 128;
|
||||
|
||||
/// One saved colour or gradient.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Swatch {
|
||||
/// Shown on hover (empty: the colour's hex).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub name: String,
|
||||
pub paint: SwatchPaint,
|
||||
}
|
||||
|
||||
/// What a swatch holds.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum SwatchPaint {
|
||||
Solid {
|
||||
color: Rgba,
|
||||
},
|
||||
Linear {
|
||||
stops: Vec<GradientStop>,
|
||||
#[serde(default, skip_serializing_if = "Spread::is_pad")]
|
||||
spread: Spread,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
linear_rgb: bool,
|
||||
},
|
||||
Radial {
|
||||
stops: Vec<GradientStop>,
|
||||
#[serde(default, skip_serializing_if = "Spread::is_pad")]
|
||||
spread: Spread,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
linear_rgb: bool,
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
focal: f32,
|
||||
},
|
||||
}
|
||||
|
||||
impl SwatchPaint {
|
||||
/// The swatch of a fill: its colour, or its gradient's ramp and options (where it lies is
|
||||
/// left behind). `None` for a bitmap fill, which a swatch can't hold.
|
||||
pub fn from_paint(p: &Paint) -> Option<SwatchPaint> {
|
||||
match p {
|
||||
Paint::Solid(c) => Some(SwatchPaint::Solid { color: *c }),
|
||||
Paint::Linear { stops, spread, linear_rgb, .. } => Some(SwatchPaint::Linear { stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb }),
|
||||
Paint::Radial { stops, spread, linear_rgb, focal, .. } => Some(SwatchPaint::Radial { stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb, focal: *focal }),
|
||||
Paint::Bitmap { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its colour, or its gradient's first stop.
|
||||
pub fn primary_color(&self) -> Rgba {
|
||||
match self {
|
||||
SwatchPaint::Solid { color } => *color,
|
||||
SwatchPaint::Linear { stops, .. } | SwatchPaint::Radial { stops, .. } => stops.first().map_or(Rgba::BLACK, |s| s.color),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stops(&self) -> Option<&[GradientStop]> {
|
||||
match self {
|
||||
SwatchPaint::Solid { .. } => None,
|
||||
SwatchPaint::Linear { stops, .. } | SwatchPaint::Radial { stops, .. } => Some(stops),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_gradient(&self) -> bool {
|
||||
!matches!(self, SwatchPaint::Solid { .. })
|
||||
}
|
||||
|
||||
/// The key `paint.set_fill` and swatch files use for its kind.
|
||||
pub fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
SwatchPaint::Solid { .. } => "solid",
|
||||
SwatchPaint::Linear { .. } => "linear",
|
||||
SwatchPaint::Radial { .. } => "radial",
|
||||
}
|
||||
}
|
||||
|
||||
/// Repaired: colours in range, 2 to [`MAX_GRADIENT_STOPS`] stops in order, the focal point
|
||||
/// in range. `None` when it can't be (a gradient with fewer than two stops).
|
||||
pub fn sanitized(&self) -> Option<SwatchPaint> {
|
||||
let stops = |s: &[GradientStop]| -> Option<Vec<GradientStop>> {
|
||||
if s.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut v: Vec<GradientStop> = s.iter().take(MAX_GRADIENT_STOPS).map(|g| GradientStop { offset: if g.offset.is_finite() { g.offset.clamp(0.0, 1.0) } else { 0.0 }, color: g.color.sanitized() }).collect();
|
||||
v.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
Some(v)
|
||||
};
|
||||
Some(match self {
|
||||
SwatchPaint::Solid { color } => SwatchPaint::Solid { color: color.sanitized() },
|
||||
SwatchPaint::Linear { stops: s, spread, linear_rgb } => SwatchPaint::Linear { stops: stops(s)?, spread: *spread, linear_rgb: *linear_rgb },
|
||||
SwatchPaint::Radial { stops: s, spread, linear_rgb, focal } => SwatchPaint::Radial { stops: stops(s)?, spread: *spread, linear_rgb: *linear_rgb, focal: if focal.is_finite() { focal.clamp(-MAX_FOCAL, MAX_FOCAL) } else { 0.0 } },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Swatch {
|
||||
pub fn new(name: &str, paint: SwatchPaint) -> Swatch {
|
||||
Swatch { name: clean_name(name), paint }
|
||||
}
|
||||
pub fn solid(c: Rgba) -> Swatch {
|
||||
Swatch { name: String::new(), paint: SwatchPaint::Solid { color: c } }
|
||||
}
|
||||
/// Repaired (see [`SwatchPaint::sanitized`]), its name trimmed and bounded.
|
||||
pub fn sanitized(&self) -> Option<Swatch> {
|
||||
Some(Swatch { name: clean_name(&self.name), paint: self.paint.sanitized()? })
|
||||
}
|
||||
}
|
||||
|
||||
/// A swatch name: one line, trimmed, at most [`MAX_SWATCH_NAME`] characters.
|
||||
pub fn clean_name(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_control()).take(MAX_SWATCH_NAME).collect::<String>().trim().to_string()
|
||||
}
|
||||
|
||||
fn stop(offset: f32, rgb: u32) -> GradientStop {
|
||||
GradientStop { offset, color: Rgba::hex(rgb) }
|
||||
}
|
||||
|
||||
/// A new document's swatches: greys from black to white, the primaries and secondaries (the
|
||||
/// picker's web-safe palette has the rest), then seven gradients.
|
||||
pub fn default_set() -> Vec<Swatch> {
|
||||
let colours = [0x000000, 0x333333, 0x666666, 0x999999, 0xcccccc, 0xffffff, 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0x00ffff, 0xff00ff];
|
||||
let mut v: Vec<Swatch> = colours.iter().map(|c| Swatch::solid(Rgba::hex(*c))).collect();
|
||||
let linear = |stops| SwatchPaint::Linear { stops, spread: Spread::Pad, linear_rgb: false };
|
||||
let radial = |stops| SwatchPaint::Radial { stops, spread: Spread::Pad, linear_rgb: false, focal: 0.0 };
|
||||
v.extend([
|
||||
Swatch::new("Black to white", linear(vec![stop(0.0, 0x000000), stop(1.0, 0xffffff)])),
|
||||
Swatch::new("White to black", radial(vec![stop(0.0, 0xffffff), stop(1.0, 0x000000)])),
|
||||
Swatch::new("Red ball", radial(vec![stop(0.0, 0xff8080), stop(1.0, 0x990000)])),
|
||||
Swatch::new("Green ball", radial(vec![stop(0.0, 0x80ff80), stop(1.0, 0x006600)])),
|
||||
Swatch::new("Blue ball", radial(vec![stop(0.0, 0x80b0ff), stop(1.0, 0x000099)])),
|
||||
Swatch::new("Spectrum", linear(vec![stop(0.0, 0xff0000), stop(0.2, 0xffff00), stop(0.4, 0x00ff00), stop(0.6, 0x00ffff), stop(0.8, 0x0000ff), stop(1.0, 0xff00ff)])),
|
||||
Swatch::new("Gold", linear(vec![stop(0.0, 0xfff2a8), stop(0.5, 0xd4a017), stop(1.0, 0x7a5200)])),
|
||||
]);
|
||||
v
|
||||
}
|
||||
|
||||
/// Whether `v` is exactly the default set (then a document file leaves it out).
|
||||
pub fn is_default_set(v: &[Swatch]) -> bool {
|
||||
let d = default_set();
|
||||
v.len() == d.len() && v.iter().zip(&d).all(|(a, b)| a == b)
|
||||
}
|
||||
|
||||
/// Largest palette file read, in bytes.
|
||||
pub const MAX_PALETTE_BYTES: usize = 1 << 20;
|
||||
|
||||
/// Reads a GIMP palette (`.gpl`): a `GIMP Palette` line, optional `Name:` and `Columns:`
|
||||
/// lines and `#` comments, then one colour per line, `R G B` (0 to 255) and an optional name.
|
||||
/// Lines that aren't colours are skipped; at most [`MAX_SWATCHES`] colours are read. The
|
||||
/// palette's own name comes back with the colours.
|
||||
pub fn parse_gpl(text: &str) -> Result<(String, Vec<Swatch>), String> {
|
||||
if text.len() > MAX_PALETTE_BYTES {
|
||||
return Err("the palette file is too large".into());
|
||||
}
|
||||
let mut lines = text.lines();
|
||||
let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim();
|
||||
if first != "GIMP Palette" {
|
||||
return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into());
|
||||
}
|
||||
let mut name = String::new();
|
||||
let mut out = Vec::new();
|
||||
for line in lines {
|
||||
let l = line.trim();
|
||||
if l.is_empty() || l.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = l.strip_prefix("Name:") {
|
||||
name = clean_name(n);
|
||||
continue;
|
||||
}
|
||||
if l.starts_with("Columns:") || l.starts_with("Channels:") {
|
||||
continue;
|
||||
}
|
||||
let mut parts = l.split_whitespace();
|
||||
let channel = |s: Option<&str>| s.and_then(|v| v.parse::<u16>().ok()).filter(|v| *v <= 255).map(|v| f32::from(v) / 255.0);
|
||||
let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue };
|
||||
let rest: Vec<&str> = parts.collect();
|
||||
let label = rest.join(" ");
|
||||
// GIMP names unnamed colours "Untitled"; the hex says more.
|
||||
let label = if label == "Untitled" { String::new() } else { label };
|
||||
out.push(Swatch::new(&label, SwatchPaint::Solid { color: Rgba::new(r, g, b, 1.0) }));
|
||||
if out.len() >= MAX_SWATCHES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("the palette has no colours in it".into());
|
||||
}
|
||||
Ok((name, out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_default_set_is_valid_and_recognised() {
|
||||
let d = default_set();
|
||||
assert_eq!(d.len(), 19);
|
||||
assert!(is_default_set(&d));
|
||||
assert!(d.iter().all(|s| s.sanitized().as_ref() == Some(s)), "nothing to repair");
|
||||
assert_eq!(d.iter().filter(|s| s.paint.is_gradient()).count(), 7);
|
||||
let mut other = d.clone();
|
||||
other.swap(0, 1);
|
||||
assert!(!is_default_set(&other));
|
||||
assert!(!is_default_set(&[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatches_are_repaired() {
|
||||
let bad = Swatch { name: " a\nb ".into(), paint: SwatchPaint::Radial { stops: vec![GradientStop { offset: 2.0, color: Rgba::new(f32::NAN, 9.0, -1.0, 1.0) }, GradientStop { offset: -1.0, color: Rgba::WHITE }], spread: Spread::Pad, linear_rgb: false, focal: 5.0 } };
|
||||
let s = bad.sanitized().unwrap();
|
||||
assert_eq!(s.name, "ab");
|
||||
let SwatchPaint::Radial { stops, focal, .. } = &s.paint else { panic!() };
|
||||
assert_eq!((stops[0].offset, stops[1].offset), (0.0, 1.0), "in order and in range");
|
||||
assert_eq!(stops[1].color, Rgba::new(0.0, 1.0, 0.0, 1.0));
|
||||
assert_eq!(*focal, MAX_FOCAL);
|
||||
let one = Swatch { name: String::new(), paint: SwatchPaint::Linear { stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }], spread: Spread::Pad, linear_rgb: false } };
|
||||
assert!(one.sanitized().is_none(), "a gradient needs two stops");
|
||||
assert_eq!(clean_name(&"x".repeat(500)).chars().count(), MAX_SWATCH_NAME);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_keeps_a_fills_ramp_not_its_geometry() {
|
||||
let p = Paint::linear(crate::Vec2::new(5.0, 5.0), crate::Vec2::new(50.0, 5.0), vec![stop(0.0, 0xff0000), stop(1.0, 0x0000ff)]);
|
||||
let s = SwatchPaint::from_paint(&p).unwrap();
|
||||
assert_eq!(s.kind(), "linear");
|
||||
assert_eq!(s.primary_color(), Rgba::hex(0xff0000));
|
||||
assert!(SwatchPaint::from_paint(&Paint::Bitmap { bitmap: crate::BitmapId(1), repeat: true, matrix: crate::Affine::IDENTITY }).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gimp_palettes_are_read() {
|
||||
let text = "GIMP Palette\nName: Brand\nColumns: 4\n# a comment\n255 0 0\tCrimson red\n 0 128 255 Untitled\n300 0 0 too bright\nnot a colour\n\n10 20 30\n";
|
||||
let (name, sw) = parse_gpl(text).unwrap();
|
||||
assert_eq!(name, "Brand");
|
||||
assert_eq!(sw.len(), 3);
|
||||
assert_eq!(sw[0].name, "Crimson red");
|
||||
assert_eq!(sw[0].paint, SwatchPaint::Solid { color: Rgba::hex(0xff0000) });
|
||||
assert_eq!(sw[1].name, "", "GIMP's Untitled shows as the hex");
|
||||
assert_eq!(sw[2].paint.primary_color().to_hex(), "#0a141e");
|
||||
// A byte-order mark and Windows line ends are fine.
|
||||
assert!(parse_gpl("\u{feff}GIMP Palette\r\n1 2 3\r\n").is_ok());
|
||||
for bad in ["", "JASC-PAL\n0 0 0", "GIMP Palette\nName: empty\n", "GIMP Palette\n1 2\n"] {
|
||||
assert!(parse_gpl(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
let many = format!("GIMP Palette\n{}", "1 2 3\n".repeat(MAX_SWATCHES + 10));
|
||||
assert_eq!(parse_gpl(&many).unwrap().1.len(), MAX_SWATCHES, "bounded");
|
||||
assert!(parse_gpl(&"x".repeat(MAX_PALETTE_BYTES + 1)).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
//! The templates AniCraft ships with (ADR 0065): small documents built by code, so nothing
|
||||
//! binary is committed and every line of them is original work. Each sets up a stage size and
|
||||
//! frame rate, named layers ready to draw on, and guides on a locked guide layer (shown while
|
||||
//! editing, never in output). They open as new, untitled documents (`file.new_from_template`).
|
||||
|
||||
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, SymbolKind, Timeline};
|
||||
use anicraft_geom::{Affine, Path, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A built-in template: its id (for commands), name and category (English; the shell
|
||||
/// translates them where they are drawn), what it is for, and how it is built.
|
||||
pub struct Template {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
pub category: &'static str,
|
||||
pub description: &'static str,
|
||||
pub build: fn() -> Document,
|
||||
}
|
||||
|
||||
/// Every built-in template, in the order the start screen shows them.
|
||||
pub static TEMPLATES: [Template; 6] = [
|
||||
Template { id: "banner-728x90", name: "Leaderboard banner", category: "Advertising", description: "A 728 × 90 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer", build: banner_728x90 },
|
||||
Template { id: "banner-300x250", name: "Rectangle banner", category: "Advertising", description: "A 300 × 250 web banner at 24 fps, 15 seconds long, with its safe area on a guide layer", build: banner_300x250 },
|
||||
Template { id: "social-square", name: "Social square", category: "Social", description: "A 1080 × 1080 post at 30 fps, 15 seconds long, with a safe margin and thirds on a guide layer", build: social_square },
|
||||
Template { id: "storyboard", name: "Storyboard 16:9", category: "Storyboard", description: "Six 2-second panels at 1920 × 1080, labelled Panel 1 to 6, with action- and title-safe areas", build: storyboard },
|
||||
Template { id: "character-turnaround", name: "Character turnaround", category: "Character", description: "Front, three-quarter, side and back views side by side, on head-height guides eight heads tall", build: turnaround },
|
||||
Template { id: "lip-sync", name: "Lip-sync mouth chart", category: "Character", description: "A Mouth graphic symbol with ten labelled mouth shapes to redraw, placed on a face guide", build: lip_sync },
|
||||
];
|
||||
|
||||
/// The built-in template with this id.
|
||||
pub fn find(id: &str) -> Option<&'static Template> {
|
||||
TEMPLATES.iter().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
/// The colour guides are drawn in (the guide layer's colour too, so the stage shows them alike).
|
||||
const GUIDE: u32 = 0x4fa3ff;
|
||||
/// A second, quieter guide colour for secondary lines.
|
||||
const GUIDE_SOFT: u32 = 0x9cc8ff;
|
||||
|
||||
fn blank(width: u32, height: u32, fps: f32) -> Document {
|
||||
let mut d = Document { stage: Stage { width, height, fps, background: Rgba::WHITE }, ..Document::default() };
|
||||
d.timeline_mut(0).layers.clear();
|
||||
d
|
||||
}
|
||||
|
||||
fn element(d: &mut Document, name: &str, transform: Affine, shape: Shape) -> Arc<Element> {
|
||||
Arc::new(Element { id: ElementId(d.alloc_id()), name: name.into(), transform, color: ColorEffect::default(), kind: ElementKind::Shape(shape) })
|
||||
}
|
||||
|
||||
/// A stroked line from `a` to `b`.
|
||||
fn line(d: &mut Document, name: &str, a: (f32, f32), b: (f32, f32), color: u32, width: f32) -> Arc<Element> {
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(a.0, a.1)).line_to(Vec2::new(b.0, b.1));
|
||||
element(d, name, Affine::IDENTITY, Shape { path: Arc::new(p), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false, warp: None })
|
||||
}
|
||||
|
||||
/// A stroked rectangle outline, `(x, y, w, h)`.
|
||||
fn outline(d: &mut Document, name: &str, (x, y, w, h): (f32, f32, f32, f32), color: u32, width: f32) -> Arc<Element> {
|
||||
element(d, name, Affine::IDENTITY, Shape { path: Arc::new(Path::rect(x, y, w, h)), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false, warp: None })
|
||||
}
|
||||
|
||||
/// A layer holding `elements` in one keyframe `frames` long.
|
||||
fn layer(d: &mut Document, name: &str, kind: LayerKind, color: u32, frames: u32, elements: Vec<Arc<Element>>) -> Arc<Layer> {
|
||||
let mut l = Layer::new(LayerId(d.alloc_id()), name);
|
||||
l.kind = kind;
|
||||
l.color = Rgba::hex(color);
|
||||
// Guides stay put while drawing over them.
|
||||
l.locked = kind == LayerKind::Guide;
|
||||
let mut k = Keyframe::new(0, frames.max(1));
|
||||
k.elements = elements;
|
||||
l.keyframes = vec![Arc::new(k)];
|
||||
Arc::new(l)
|
||||
}
|
||||
|
||||
/// Drawing layers, empty, top first.
|
||||
fn drawing_layers(d: &mut Document, names: &[&str], frames: u32) -> Vec<Arc<Layer>> {
|
||||
let palette = [0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65];
|
||||
names.iter().enumerate().map(|(i, n)| layer(d, n, LayerKind::Normal, palette[i % palette.len()], frames, Vec::new())).collect()
|
||||
}
|
||||
|
||||
/// A banner: the safe area (inset by a tenth of the short edge) and the edge on a guide layer,
|
||||
/// layers for the call to action, text and artwork, and a soft background.
|
||||
fn banner(width: u32, height: u32) -> Document {
|
||||
const FRAMES: u32 = 24 * 15;
|
||||
let mut d = blank(width, height, 24.0);
|
||||
let (w, h) = (width as f32, height as f32);
|
||||
let m = (w.min(h) * 0.1).round();
|
||||
let guides = vec![outline(&mut d, "Safe area", (m, m, w - 2.0 * m, h - 2.0 * m), GUIDE, 1.0), outline(&mut d, "Edge", (0.5, 0.5, w - 1.0, h - 1.0), GUIDE_SOFT, 1.0)];
|
||||
let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)];
|
||||
layers.extend(drawing_layers(&mut d, &["Call to action", "Text", "Artwork"], FRAMES));
|
||||
let bg = element(&mut d, "background", Affine::IDENTITY, Shape::filled(Path::rect(0.0, 0.0, w, h), Paint::Solid(Rgba::hex(0xeef2f7))));
|
||||
let mut back = layer(&mut d, "Background", LayerKind::Normal, 0x7e57c2, FRAMES, vec![bg]);
|
||||
Arc::make_mut(&mut back).locked = true;
|
||||
layers.push(back);
|
||||
d.timeline_mut(0).layers = layers;
|
||||
d
|
||||
}
|
||||
|
||||
fn banner_728x90() -> Document {
|
||||
banner(728, 90)
|
||||
}
|
||||
|
||||
fn banner_300x250() -> Document {
|
||||
banner(300, 250)
|
||||
}
|
||||
|
||||
/// A square post: a safe margin, the thirds and the centre on a guide layer.
|
||||
fn social_square() -> Document {
|
||||
const FRAMES: u32 = 30 * 15;
|
||||
let mut d = blank(1080, 1080, 30.0);
|
||||
let s = 1080.0;
|
||||
let m = 60.0;
|
||||
let mut guides = vec![outline(&mut d, "Safe margin", (m, m, s - 2.0 * m, s - 2.0 * m), GUIDE, 2.0)];
|
||||
for (i, t) in [s / 3.0, s * 2.0 / 3.0].into_iter().enumerate() {
|
||||
guides.push(line(&mut d, &format!("Third {}", i + 1), (t, 0.0), (t, s), GUIDE_SOFT, 1.0));
|
||||
guides.push(line(&mut d, &format!("Third {}", i + 3), (0.0, t), (s, t), GUIDE_SOFT, 1.0));
|
||||
}
|
||||
guides.push(line(&mut d, "Centre", (s / 2.0 - 20.0, s / 2.0), (s / 2.0 + 20.0, s / 2.0), GUIDE, 2.0));
|
||||
guides.push(line(&mut d, "Centre", (s / 2.0, s / 2.0 - 20.0), (s / 2.0, s / 2.0 + 20.0), GUIDE, 2.0));
|
||||
let mut layers = vec![layer(&mut d, "Safe area", LayerKind::Guide, GUIDE, FRAMES, guides)];
|
||||
layers.extend(drawing_layers(&mut d, &["Text", "Artwork", "Background"], FRAMES));
|
||||
d.timeline_mut(0).layers = layers;
|
||||
d
|
||||
}
|
||||
|
||||
/// A storyboard for 16:9: the action-safe (93 %) and title-safe (90 %) areas and the centre on a
|
||||
/// guide layer, and a Panels layer of six labelled 2-second keyframes (an animatic as it plays).
|
||||
fn storyboard() -> Document {
|
||||
const PANEL: u32 = 48;
|
||||
const PANELS: u32 = 6;
|
||||
let mut d = blank(1920, 1080, 24.0);
|
||||
let (w, h) = (1920.0, 1080.0);
|
||||
let safe = |d: &mut Document, name: &str, keep: f32, color: u32| {
|
||||
let (mx, my) = (w * (1.0 - keep) / 2.0, h * (1.0 - keep) / 2.0);
|
||||
outline(d, name, (mx, my, w - 2.0 * mx, h - 2.0 * my), color, 2.0)
|
||||
};
|
||||
let guides = vec![
|
||||
safe(&mut d, "Action safe", 0.93, GUIDE),
|
||||
safe(&mut d, "Title safe", 0.90, GUIDE_SOFT),
|
||||
line(&mut d, "Centre", (w / 2.0 - 30.0, h / 2.0), (w / 2.0 + 30.0, h / 2.0), GUIDE, 2.0),
|
||||
line(&mut d, "Centre", (w / 2.0, h / 2.0 - 30.0), (w / 2.0, h / 2.0 + 30.0), GUIDE, 2.0),
|
||||
];
|
||||
let total = PANEL * PANELS;
|
||||
let guide = layer(&mut d, "Safe areas", LayerKind::Guide, GUIDE, total, guides);
|
||||
let notes = layer(&mut d, "Notes", LayerKind::Normal, 0xffd54a, total, Vec::new());
|
||||
let mut panels = Layer::new(LayerId(d.alloc_id()), "Panels");
|
||||
panels.color = Rgba::hex(0xff6b4a);
|
||||
panels.keyframes = (0..PANELS)
|
||||
.map(|i| {
|
||||
let mut k = Keyframe::new(i * PANEL, PANEL);
|
||||
k.label = format!("Panel {}", i + 1);
|
||||
Arc::new(k)
|
||||
})
|
||||
.collect();
|
||||
d.timeline_mut(0).layers = vec![guide, notes, Arc::new(panels)];
|
||||
d
|
||||
}
|
||||
|
||||
/// A turnaround: five views side by side (a centre line each) on horizontal lines a head
|
||||
/// apart, eight heads from the top of the head to the ground, and a layer per view.
|
||||
fn turnaround() -> Document {
|
||||
let mut d = blank(1920, 1080, 24.0);
|
||||
let (left, right, top, ground) = (60.0, 1860.0, 120.0, 960.0);
|
||||
let head = (ground - top) / 8.0;
|
||||
let mut guides = Vec::new();
|
||||
for i in 0..=8 {
|
||||
let y = top + head * i as f32;
|
||||
let (color, width) = if i == 0 || i == 8 { (GUIDE, 2.0) } else { (GUIDE_SOFT, 1.0) };
|
||||
let name = match i {
|
||||
0 => "Top of head".to_string(),
|
||||
8 => "Ground".to_string(),
|
||||
n => format!("Head {n}"),
|
||||
};
|
||||
guides.push(line(&mut d, &name, (left, y), (right, y), color, width));
|
||||
}
|
||||
let views = ["Front", "Three-quarter", "Side", "Three-quarter back", "Back"];
|
||||
let col = (right - left) / views.len() as f32;
|
||||
for (i, v) in views.iter().enumerate() {
|
||||
let x = left + col * (i as f32 + 0.5);
|
||||
guides.push(line(&mut d, v, (x, top - 30.0), (x, ground + 30.0), GUIDE, 1.5));
|
||||
}
|
||||
let mut layers = vec![layer(&mut d, "Turnaround guides", LayerKind::Guide, GUIDE, 1, guides)];
|
||||
layers.extend(drawing_layers(&mut d, &views, 1));
|
||||
d.timeline_mut(0).layers = layers;
|
||||
d
|
||||
}
|
||||
|
||||
/// The mouth shapes of a lip-sync chart, as frame labels and placeholder shapes to redraw.
|
||||
pub const MOUTHS: [&str; 10] = ["Rest", "AI", "E", "O", "U", "CDGKNRSThYZ", "FV", "L", "MBP", "WQ"];
|
||||
|
||||
/// A lip-sync chart: a Mouth graphic symbol with a labelled keyframe per mouth shape (each with
|
||||
/// a simple placeholder), placed at Single Frame on a face guide, so each keyframe of the Mouth
|
||||
/// layer picks a shape by its first frame.
|
||||
fn lip_sync() -> Document {
|
||||
const FRAMES: u32 = 24;
|
||||
let mut d = blank(1280, 720, 24.0);
|
||||
let lips = Rgba::hex(0x8e3b46);
|
||||
let mouth = |path: Path| Shape::filled(path, Paint::Solid(lips)).with_stroke(Rgba::hex(0x5a1f28), 3.0);
|
||||
let shapes = [
|
||||
mouth(Path::rounded_rect(-50.0, -4.0, 100.0, 8.0, 4.0)),
|
||||
mouth(Path::ellipse(0.0, 0.0, 55.0, 35.0)),
|
||||
mouth(Path::ellipse(0.0, 0.0, 60.0, 20.0)),
|
||||
mouth(Path::ellipse(0.0, 0.0, 35.0, 40.0)),
|
||||
mouth(Path::ellipse(0.0, 0.0, 22.0, 26.0)),
|
||||
mouth(Path::rounded_rect(-55.0, -14.0, 110.0, 28.0, 12.0)),
|
||||
mouth(Path::rounded_rect(-50.0, -10.0, 100.0, 20.0, 8.0)),
|
||||
mouth(Path::ellipse(0.0, 0.0, 45.0, 30.0)),
|
||||
mouth(Path::rounded_rect(-50.0, -3.0, 100.0, 6.0, 3.0)),
|
||||
mouth(Path::ellipse(0.0, 0.0, 18.0, 20.0)),
|
||||
];
|
||||
let sym_id = SymbolId(d.alloc_id());
|
||||
let mut inner = Layer::new(LayerId(d.alloc_id()), "Mouth");
|
||||
inner.color = Rgba::hex(0xff6b4a);
|
||||
let mut keys = Vec::with_capacity(shapes.len());
|
||||
for (i, (label, shape)) in MOUTHS.iter().zip(shapes).enumerate() {
|
||||
let mut k = Keyframe::new(i as u32, 1);
|
||||
k.label = (*label).to_string();
|
||||
k.elements = vec![element(&mut d, &format!("{label} mouth"), Affine::IDENTITY, shape)];
|
||||
keys.push(Arc::new(k));
|
||||
}
|
||||
inner.keyframes = keys;
|
||||
d.library.push(Arc::new(Symbol { id: sym_id, name: "Mouth".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, scale_grid_kept: None, timeline: Timeline { layers: vec![Arc::new(inner)] } }));
|
||||
let (cx, cy) = (640.0, 340.0);
|
||||
let face = element(&mut d, "Head", Affine::IDENTITY, Shape { path: Arc::new(Path::ellipse(cx, cy, 200.0, 250.0)), fill: None, stroke: Some(Stroke::new(Rgba::hex(GUIDE), 2.0)), fill_rule: Default::default(), merge: false, warp: None });
|
||||
let guides = vec![
|
||||
face,
|
||||
line(&mut d, "Eye line", (cx - 200.0, cy), (cx + 200.0, cy), GUIDE_SOFT, 1.0),
|
||||
line(&mut d, "Centre line", (cx, cy - 250.0), (cx, cy + 250.0), GUIDE_SOFT, 1.0),
|
||||
line(&mut d, "Mouth line", (cx - 120.0, cy + 130.0), (cx + 120.0, cy + 130.0), GUIDE_SOFT, 1.0),
|
||||
];
|
||||
let instance = Arc::new(Element {
|
||||
id: ElementId(d.alloc_id()),
|
||||
name: "mouth".into(),
|
||||
transform: Affine::translate(cx, cy + 130.0),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: crate::BlendMode::Normal, filters: Vec::new(), events: Vec::new() },
|
||||
});
|
||||
let layers = vec![
|
||||
layer(&mut d, "Face guide", LayerKind::Guide, GUIDE, FRAMES, guides),
|
||||
layer(&mut d, "Mouth", LayerKind::Normal, 0xff6b4a, FRAMES, vec![instance]),
|
||||
layer(&mut d, "Head", LayerKind::Normal, 0x66bb6a, FRAMES, Vec::new()),
|
||||
];
|
||||
d.timeline_mut(0).layers = layers;
|
||||
d
|
||||
}
|
||||
|
||||
/// A copy of `doc` with its guide layers drawn as artwork, their lines `widen` times as wide: a
|
||||
/// template's picture shows its guides (which output never does), and a small picture needs
|
||||
/// them wider to see them.
|
||||
pub fn with_guides_shown(doc: &Document, widen: f32) -> Document {
|
||||
let widen = if widen.is_finite() { widen.clamp(1.0, 16.0) } else { 1.0 };
|
||||
let show = |tl: &mut Timeline| {
|
||||
for l in &mut tl.layers {
|
||||
if l.kind != LayerKind::Guide {
|
||||
continue;
|
||||
}
|
||||
let l = Arc::make_mut(l);
|
||||
l.kind = LayerKind::Normal;
|
||||
for k in &mut l.keyframes {
|
||||
for e in &mut Arc::make_mut(k).elements {
|
||||
if let ElementKind::Shape(sh) = &e.kind
|
||||
&& let Some(st) = &sh.stroke
|
||||
{
|
||||
let mut sh = sh.clone();
|
||||
sh.stroke = Some(Stroke { width: st.width * widen, ..st.clone() });
|
||||
Arc::make_mut(e).kind = ElementKind::Shape(sh);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut d = doc.clone();
|
||||
for scene in &mut d.scenes {
|
||||
show(&mut Arc::make_mut(scene).timeline);
|
||||
}
|
||||
for sym in &mut d.library {
|
||||
show(&mut Arc::make_mut(sym).timeline);
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_template_builds_a_consistent_document() {
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
for t in &TEMPLATES {
|
||||
assert!(ids.insert(t.id), "{} is listed once", t.id);
|
||||
assert!(find(t.id).is_some_and(|f| std::ptr::eq(f, t)));
|
||||
let d = (t.build)();
|
||||
assert!(d.stage.width > 0 && d.stage.height > 0 && d.stage.fps > 0.0, "{}", t.id);
|
||||
let tl = d.timeline(0);
|
||||
assert!(tl.layers.len() >= 3, "{}: named layers to draw on", t.id);
|
||||
assert!(tl.layers.iter().any(|l| l.kind == LayerKind::Guide && l.locked), "{}: a locked guide layer", t.id);
|
||||
// Ids are unique and below `next_id`, so editing never reuses one.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut check = |id: u64| assert!(id < d.next_id && seen.insert(id), "{}: id {id}", t.id);
|
||||
for l in &tl.layers {
|
||||
check(l.id.0);
|
||||
l.keyframes.iter().flat_map(|k| k.elements.iter()).for_each(|e| check(e.id.0));
|
||||
}
|
||||
for s in &d.library {
|
||||
check(s.id.0);
|
||||
}
|
||||
// Guides never render; the picture with them shown is not blank.
|
||||
assert!(crate::evaluate(&d, 0).items.iter().all(|i| i.guide || tl.layer(i.layer).is_some_and(|l| l.kind != LayerKind::Guide)));
|
||||
assert!(crate::evaluate(&with_guides_shown(&d, 4.0), 0).items.iter().any(|i| !i.guide), "{}", t.id);
|
||||
}
|
||||
// The sizes the task asks for.
|
||||
let size = |id: &str| find(id).map(|t| (t.build)().stage).map(|s| (s.width, s.height, s.fps));
|
||||
assert_eq!(size("banner-728x90"), Some((728, 90, 24.0)));
|
||||
assert_eq!(size("banner-300x250"), Some((300, 250, 24.0)));
|
||||
assert_eq!(size("social-square"), Some((1080, 1080, 30.0)));
|
||||
assert_eq!(size("storyboard"), Some((1920, 1080, 24.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_storyboard_and_mouth_chart_are_labelled() {
|
||||
let d = storyboard();
|
||||
let panels = d.timeline(0).layers.iter().find(|l| l.name == "Panels").map(|l| l.keyframes.iter().map(|k| k.label.clone()).collect::<Vec<_>>());
|
||||
assert_eq!(panels.map(|p| p.len()), Some(6));
|
||||
assert_eq!(d.timeline(0).frame_count(), 6 * 48);
|
||||
let d = lip_sync();
|
||||
let labels: Vec<String> = d.library.first().map(|s| s.timeline.layers.iter().flat_map(|l| l.keyframes.iter().map(|k| k.label.clone())).collect()).unwrap_or_default();
|
||||
assert_eq!(labels, MOUTHS.map(str::to_string).to_vec());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,641 @@
|
||||
//! Asset Warp (ADR 0079): a deformation mesh over a shape or a bitmap, bent by pins.
|
||||
//!
|
||||
//! A [`Warp`] sits on a [`Shape`] (a bitmap on the stage is a shape filled with its image). It
|
||||
//! keeps the artwork's outline as it was drawn (`rest`), a mesh **resolution**, and the
|
||||
//! **pins**: each a point of the artwork as drawn (`rest`) and where it is now (`at`), both in
|
||||
//! the shape's own space. The mesh is not stored: it is a grid over the rest outline's bounds,
|
||||
//! `resolution` cells along the longer side (square-ish cells, each split into two triangles,
|
||||
//! the diagonals alternating so the grid has no preferred direction), so it is always the same
|
||||
//! for the same artwork.
|
||||
//!
|
||||
//! **Deformation** is the rigid moving-least-squares deformation of S. Schaefer, T. McPhail and
|
||||
//! J. Warren, *Image deformation using moving least squares* (SIGGRAPH 2006, §2.3), evaluated at
|
||||
//! the mesh's vertices: each vertex `v` moves by the rotation and translation that best carry
|
||||
//! the pins near it (weighted `1 / |p − v|²`) to where they are. It interpolates the pins
|
||||
//! exactly, is as rigid as possible locally (no shear, no scale), is a closed form per vertex
|
||||
//! (no solver, no iterations, nothing to converge), and depends only on the pins, so it is
|
||||
//! deterministic and its cost is bounded: vertices × pins. Between vertices the mesh is
|
||||
//! piecewise affine, so a bitmap is drawn as textured triangles and a shape's outline maps
|
||||
//! through the same triangles: the shape and the bitmap bend the same way.
|
||||
//!
|
||||
//! **The outline.** Straight edges are split where they cross the mesh's edges, so a line
|
||||
//! maps exactly to the mesh's image of it (a bitmap's outline is exactly the mesh's border).
|
||||
//! Curves are split into pieces no longer than half a cell, each end mapped through the mesh
|
||||
//! and each handle by the triangle of the end it belongs to, so curves stay smooth. **At rest**
|
||||
//! (every pin where it was placed) the outline is the drawing, bit for bit: the very `Arc` of
|
||||
//! the rest path.
|
||||
//!
|
||||
//! **The file holds what shows.** Commands write the bent outline into the shape's `path` and
|
||||
//! its fingerprint into `shown`. A shape whose path no longer has that fingerprint was edited
|
||||
//! by another tool since: its warp is stale, [`Shape::live_warp`] ignores it, and the next warp
|
||||
//! command starts again from the shape as it now is ([`Warp::rebased`]). Pins tween between
|
||||
//! keyframes with the keyframe's easing (as bone poses do, ADR 0043): `evaluate` blends the
|
||||
//! pins and bends the rest outline, so a tween never accumulates drift.
|
||||
|
||||
use crate::Shape;
|
||||
use anicraft_geom::{Path, PathCmd, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Fewest and most cells along the mesh's longer side, and the resolution a new warp has.
|
||||
pub const MIN_RESOLUTION: u32 = 2;
|
||||
pub const MAX_RESOLUTION: u32 = 48;
|
||||
pub const DEFAULT_RESOLUTION: u32 = 12;
|
||||
/// Most pins on one warp.
|
||||
pub const MAX_PINS: usize = 128;
|
||||
/// Most anchors a warped outline may have (Optimize first beyond it).
|
||||
pub const MAX_WARP_POINTS: usize = 20_000;
|
||||
/// Most commands a bent outline may have; past it curves and lines are not split.
|
||||
const MAX_BENT_CMDS: usize = 400_000;
|
||||
/// Most pieces one curve is split into.
|
||||
const MAX_SPLIT: usize = 32;
|
||||
/// Largest artwork a warp covers (local units on either side).
|
||||
pub const MAX_EXTENT: f32 = 1_000_000.0;
|
||||
/// Two pins closer than this (local units, as drawn) are one place.
|
||||
pub const PIN_SPACING: f32 = 0.5;
|
||||
|
||||
/// Unique id of a pin within a document (from the document's id counter).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct PinId(pub u64);
|
||||
|
||||
/// A pin: a point of the artwork as drawn, and where it is now (the shape's space).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Pin {
|
||||
pub id: PinId,
|
||||
pub rest: Vec2,
|
||||
pub at: Vec2,
|
||||
}
|
||||
|
||||
fn default_resolution() -> u32 {
|
||||
DEFAULT_RESOLUTION
|
||||
}
|
||||
|
||||
/// A warp mesh on a shape (see the module docs).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Warp {
|
||||
/// The outline as it was drawn, in the shape's space.
|
||||
#[serde(with = "crate::path_table")]
|
||||
pub rest: Arc<Path>,
|
||||
/// Cells along the mesh's longer side ([`MIN_RESOLUTION`]..=[`MAX_RESOLUTION`]).
|
||||
#[serde(default = "default_resolution")]
|
||||
pub resolution: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub pins: Vec<Pin>,
|
||||
/// Fingerprint of the outline the warp gave the shape ([`fingerprint`]).
|
||||
#[serde(default)]
|
||||
pub shown: u64,
|
||||
}
|
||||
|
||||
impl PartialEq for Warp {
|
||||
fn eq(&self, o: &Warp) -> bool {
|
||||
crate::arc_eq(&self.rest, &o.rest) && self.resolution == o.resolution && self.pins == o.pins && self.shown == o.shown
|
||||
}
|
||||
}
|
||||
|
||||
/// The deformation mesh as drawn: every vertex as drawn (`rest`) and bent (`shown`), and the
|
||||
/// triangles (indices into both), in the shape's space, in drawing order.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WarpMesh {
|
||||
pub rest: Vec<Vec2>,
|
||||
pub shown: Vec<Vec2>,
|
||||
pub tris: Vec<[u32; 3]>,
|
||||
}
|
||||
|
||||
/// The mesh's grid: `nx × ny` cells from `min` to `max`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Grid {
|
||||
pub min: Vec2,
|
||||
pub max: Vec2,
|
||||
pub nx: u32,
|
||||
pub ny: u32,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
/// The grid over `rest`'s control-point bounds with `resolution` cells along the longer side
|
||||
/// (an extent under 1 unit is widened to 1, about its middle). `None` for an empty or
|
||||
/// unbounded outline.
|
||||
pub fn of(rest: &Path, resolution: u32) -> Option<Grid> {
|
||||
let b = rest.bounds();
|
||||
if !(b.min.is_finite() && b.max.is_finite()) || b.max.x < b.min.x || b.max.y < b.min.y {
|
||||
return None;
|
||||
}
|
||||
if b.min.x.abs().max(b.min.y.abs()).max(b.max.x.abs()).max(b.max.y.abs()) > MAX_EXTENT {
|
||||
return None;
|
||||
}
|
||||
let widen = |lo: f32, hi: f32| if hi - lo < 1.0 { ((lo + hi) * 0.5 - 0.5, (lo + hi) * 0.5 + 0.5) } else { (lo, hi) };
|
||||
let (x0, x1) = widen(b.min.x, b.max.x);
|
||||
let (y0, y1) = widen(b.min.y, b.max.y);
|
||||
let (w, h) = (x1 - x0, y1 - y0);
|
||||
let r = resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION);
|
||||
let size = w.max(h) / r as f32;
|
||||
let cells = |len: f32| {
|
||||
let n = (len / size).ceil();
|
||||
if n.is_finite() { (n as u32).clamp(1, r) } else { 1 }
|
||||
};
|
||||
Some(Grid { min: Vec2::new(x0, y0), max: Vec2::new(x1, y1), nx: cells(w), ny: cells(h) })
|
||||
}
|
||||
|
||||
/// The x of column line `i` (exactly the bounds at either end).
|
||||
pub fn x(&self, i: u32) -> f32 {
|
||||
if i >= self.nx { self.max.x } else { self.min.x + (self.max.x - self.min.x) * i as f32 / self.nx as f32 }
|
||||
}
|
||||
|
||||
/// The y of row line `j`.
|
||||
pub fn y(&self, j: u32) -> f32 {
|
||||
if j >= self.ny { self.max.y } else { self.min.y + (self.max.y - self.min.y) * j as f32 / self.ny as f32 }
|
||||
}
|
||||
|
||||
/// Vertices, row by row: `(nx + 1) × (ny + 1)`.
|
||||
pub fn vertices(&self) -> Vec<Vec2> {
|
||||
let mut out = Vec::with_capacity(((self.nx + 1) * (self.ny + 1)) as usize);
|
||||
for j in 0..=self.ny {
|
||||
for i in 0..=self.nx {
|
||||
out.push(Vec2::new(self.x(i), self.y(j)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn vertex(&self, i: u32, j: u32) -> u32 {
|
||||
j * (self.nx + 1) + i
|
||||
}
|
||||
|
||||
/// Whether cell `(i, j)`'s diagonal runs from its top-left to its bottom-right corner (else
|
||||
/// from its top-right to its bottom-left): they alternate like a chequerboard.
|
||||
fn falling(i: u32, j: u32) -> bool {
|
||||
(i + j).is_multiple_of(2)
|
||||
}
|
||||
|
||||
/// The two triangles of cell `(i, j)`, as vertex indices.
|
||||
fn cell_tris(&self, i: u32, j: u32) -> [[u32; 3]; 2] {
|
||||
let (a, b, c, d) = (self.vertex(i, j), self.vertex(i + 1, j), self.vertex(i, j + 1), self.vertex(i + 1, j + 1));
|
||||
if Grid::falling(i, j) { [[a, b, d], [a, d, c]] } else { [[a, b, c], [b, d, c]] }
|
||||
}
|
||||
|
||||
/// Every triangle, cell by cell, row by row.
|
||||
pub fn triangles(&self) -> Vec<[u32; 3]> {
|
||||
let mut out = Vec::with_capacity((2 * self.nx * self.ny) as usize);
|
||||
for j in 0..self.ny {
|
||||
for i in 0..self.nx {
|
||||
out.extend(self.cell_tris(i, j));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The cell `p` falls in (clamped to the grid, so points just outside use the edge cells).
|
||||
fn cell(&self, p: Vec2) -> (u32, u32) {
|
||||
let at = |v: f32, lo: f32, hi: f32, n: u32| {
|
||||
let k = ((v - lo) / (hi - lo) * n as f32).floor();
|
||||
if k.is_finite() { (k.max(0.0) as u32).min(n - 1) } else { 0 }
|
||||
};
|
||||
(at(p.x, self.min.x, self.max.x, self.nx), at(p.y, self.min.y, self.max.y, self.ny))
|
||||
}
|
||||
|
||||
/// The triangle (vertex indices) of the grid that holds `p`.
|
||||
pub fn locate(&self, p: Vec2) -> [u32; 3] {
|
||||
let (i, j) = self.cell(p);
|
||||
let [t0, t1] = self.cell_tris(i, j);
|
||||
let (x0, y0) = (self.x(i), self.y(j));
|
||||
let (cw, ch) = ((self.x(i + 1) - x0).max(1e-12), (self.y(j + 1) - y0).max(1e-12));
|
||||
let (u, v) = ((p.x - x0) / cw, (p.y - y0) / ch);
|
||||
let first = if Grid::falling(i, j) { u >= v } else { u + v <= 1.0 };
|
||||
if first { t0 } else { t1 }
|
||||
}
|
||||
|
||||
/// The parameters in `(0, 1)` where the segment `a → b` crosses an edge of the mesh, in
|
||||
/// order: column and row lines, then each cell's diagonal.
|
||||
fn crossings(&self, a: Vec2, b: Vec2, out: &mut Vec<f32>) {
|
||||
out.clear();
|
||||
let d = b - a;
|
||||
if d.x != 0.0 {
|
||||
for i in 1..self.nx {
|
||||
let t = (self.x(i) - a.x) / d.x;
|
||||
if t > 0.0 && t < 1.0 {
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if d.y != 0.0 {
|
||||
for j in 1..self.ny {
|
||||
let t = (self.y(j) - a.y) / d.y;
|
||||
if t > 0.0 && t < 1.0 {
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(f32::total_cmp);
|
||||
out.dedup_by(|x, y| (*x - *y).abs() < 1e-6);
|
||||
// Inside each cell the segment may still cross the cell's diagonal.
|
||||
let mut diag = Vec::new();
|
||||
let mut t0 = 0.0f32;
|
||||
for &t1 in out.iter().chain(std::iter::once(&1.0)) {
|
||||
let mid = a + d * ((t0 + t1) * 0.5);
|
||||
let (i, j) = self.cell(mid);
|
||||
let (p, q) = if Grid::falling(i, j) { (Vec2::new(self.x(i), self.y(j)), Vec2::new(self.x(i + 1), self.y(j + 1))) } else { (Vec2::new(self.x(i + 1), self.y(j)), Vec2::new(self.x(i), self.y(j + 1))) };
|
||||
let e = q - p;
|
||||
let den = d.cross(e);
|
||||
if den.abs() > 1e-12 {
|
||||
let t = (p - a).cross(e) / den;
|
||||
if t > t0 + 1e-6 && t < t1 - 1e-6 {
|
||||
diag.push(t);
|
||||
}
|
||||
}
|
||||
t0 = t1;
|
||||
}
|
||||
out.extend(diag);
|
||||
out.sort_by(f32::total_cmp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Barycentric coordinates of `p` in triangle `(a, b, c)` (extrapolated outside it); `None` for
|
||||
/// a triangle with no area.
|
||||
fn barycentric(a: Vec2, b: Vec2, c: Vec2, p: Vec2) -> Option<(f32, f32, f32)> {
|
||||
let det = (b - a).cross(c - a);
|
||||
if det.abs() <= 1e-12 || det.is_nan() {
|
||||
return None;
|
||||
}
|
||||
let l1 = (p - a).cross(c - a) / det;
|
||||
let l2 = (b - a).cross(p - a) / det;
|
||||
Some((1.0 - l1 - l2, l1, l2))
|
||||
}
|
||||
|
||||
/// The rigid moving-least-squares deformation (Schaefer et al. 2006, §2.3) of `v` by pins
|
||||
/// `(from, to)`, with weights `1 / |from − v|²`: the rotation and translation that best carry
|
||||
/// the pins near `v` where they go, applied to `v`. A point on a pin goes with it; with one pin
|
||||
/// everything moves with it; with none nothing moves. Computed in `f64`.
|
||||
pub fn mls_rigid(pins: &[(Vec2, Vec2)], v: Vec2) -> Vec2 {
|
||||
if pins.is_empty() {
|
||||
return v;
|
||||
}
|
||||
let (vx, vy) = (f64::from(v.x), f64::from(v.y));
|
||||
let (mut sw, mut px, mut py, mut qx, mut qy) = (0.0f64, 0.0, 0.0, 0.0, 0.0);
|
||||
let mut ws = Vec::with_capacity(pins.len());
|
||||
for &(p, q) in pins {
|
||||
let (dx, dy) = (f64::from(p.x) - vx, f64::from(p.y) - vy);
|
||||
let d2 = dx * dx + dy * dy;
|
||||
if d2 < 1e-12 {
|
||||
return q;
|
||||
}
|
||||
let w = 1.0 / d2;
|
||||
ws.push(w);
|
||||
sw += w;
|
||||
px += w * f64::from(p.x);
|
||||
py += w * f64::from(p.y);
|
||||
qx += w * f64::from(q.x);
|
||||
qy += w * f64::from(q.y);
|
||||
}
|
||||
if !(sw > 0.0 && sw.is_finite()) {
|
||||
return v;
|
||||
}
|
||||
let (px, py, qx, qy) = (px / sw, py / sw, qx / sw, qy / sw);
|
||||
// The best rotation: its cosine and sine are the weighted dot and cross of the centred pins.
|
||||
let (mut dot, mut cross) = (0.0f64, 0.0f64);
|
||||
for (&(p, q), &w) in pins.iter().zip(&ws) {
|
||||
let (ax, ay) = (f64::from(p.x) - px, f64::from(p.y) - py);
|
||||
let (bx, by) = (f64::from(q.x) - qx, f64::from(q.y) - qy);
|
||||
dot += w * (ax * bx + ay * by);
|
||||
cross += w * (ax * by - ay * bx);
|
||||
}
|
||||
let r = dot.hypot(cross);
|
||||
let (c, s) = if r > 1e-18 && r.is_finite() { (dot / r, cross / r) } else { (1.0, 0.0) };
|
||||
let (dx, dy) = (vx - px, vy - py);
|
||||
let out = Vec2::new((qx + c * dx - s * dy) as f32, (qy + s * dx + c * dy) as f32);
|
||||
if out.is_finite() { out } else { v }
|
||||
}
|
||||
|
||||
/// A fingerprint of `path`'s commands and coordinates (FNV-1a over their bits): how a warp
|
||||
/// knows the outline is still the one it gave the shape.
|
||||
pub fn fingerprint(path: &Path) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
let mut eat = |bits: u32| {
|
||||
for b in bits.to_le_bytes() {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
};
|
||||
for c in &path.cmds {
|
||||
let (tag, pts): (u32, [Option<Vec2>; 3]) = match *c {
|
||||
PathCmd::MoveTo(p) => (1, [Some(p), None, None]),
|
||||
PathCmd::LineTo(p) => (2, [Some(p), None, None]),
|
||||
PathCmd::QuadTo(a, p) => (3, [Some(a), Some(p), None]),
|
||||
PathCmd::CubicTo(a, b, p) => (4, [Some(a), Some(b), Some(p)]),
|
||||
PathCmd::Close => (5, [None, None, None]),
|
||||
};
|
||||
eat(tag);
|
||||
for p in pts.into_iter().flatten() {
|
||||
eat(p.x.to_bits());
|
||||
eat(p.y.to_bits());
|
||||
}
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// How many anchors (command ends) `path` has.
|
||||
pub fn anchor_count(path: &Path) -> usize {
|
||||
path.cmds.iter().filter(|c| !matches!(c, PathCmd::Close)).count()
|
||||
}
|
||||
|
||||
/// The bent mesh: the grid's vertices as drawn and where the pins carry them.
|
||||
struct Bent {
|
||||
grid: Grid,
|
||||
rest: Vec<Vec2>,
|
||||
shown: Vec<Vec2>,
|
||||
}
|
||||
|
||||
impl Bent {
|
||||
fn at(&self, i: u32) -> (Vec2, Vec2) {
|
||||
let i = i as usize;
|
||||
(self.rest.get(i).copied().unwrap_or_default(), self.shown.get(i).copied().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// `p` (as drawn) mapped through triangle `tri`'s affine map (extrapolated outside it).
|
||||
fn through(&self, tri: [u32; 3], p: Vec2) -> Vec2 {
|
||||
let [(ra, sa), (rb, sb), (rc, sc)] = tri.map(|i| self.at(i));
|
||||
match barycentric(ra, rb, rc, p) {
|
||||
Some((l0, l1, l2)) => {
|
||||
let out = sa * l0 + sb * l1 + sc * l2;
|
||||
if out.is_finite() { out } else { p }
|
||||
}
|
||||
None => p + (sa - ra),
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` (as drawn) where the mesh carries it, and the triangle that did.
|
||||
fn map(&self, p: Vec2) -> (Vec2, [u32; 3]) {
|
||||
let tri = self.grid.locate(p);
|
||||
(self.through(tri, p), tri)
|
||||
}
|
||||
}
|
||||
|
||||
impl Warp {
|
||||
/// A warp of the outline `rest` with no pins.
|
||||
pub fn new(rest: Arc<Path>, resolution: u32) -> Warp {
|
||||
let shown = fingerprint(&rest);
|
||||
Warp { rest, resolution: resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION), pins: Vec::new(), shown }
|
||||
}
|
||||
|
||||
/// Every pin where it was placed: the artwork shows as drawn.
|
||||
pub fn at_rest(&self) -> bool {
|
||||
self.pins.iter().all(|p| p.at == p.rest)
|
||||
}
|
||||
|
||||
pub fn pin(&self, id: PinId) -> Option<&Pin> {
|
||||
self.pins.iter().find(|p| p.id == id)
|
||||
}
|
||||
|
||||
pub fn grid(&self) -> Option<Grid> {
|
||||
Grid::of(&self.rest, self.resolution)
|
||||
}
|
||||
|
||||
fn bent(&self) -> Option<Bent> {
|
||||
let grid = self.grid()?;
|
||||
let rest = grid.vertices();
|
||||
let pins: Vec<(Vec2, Vec2)> = self.pins.iter().map(|p| (p.rest, p.at)).collect();
|
||||
let shown = if self.at_rest() { rest.clone() } else { rest.iter().map(|&v| mls_rigid(&pins, v)).collect() };
|
||||
Some(Bent { grid, rest, shown })
|
||||
}
|
||||
|
||||
/// The mesh as it shows (`None` for an outline with no extent).
|
||||
pub fn mesh(&self) -> Option<WarpMesh> {
|
||||
let b = self.bent()?;
|
||||
Some(WarpMesh { tris: b.grid.triangles(), rest: b.rest, shown: b.shown })
|
||||
}
|
||||
|
||||
/// Where point `p` of the artwork as drawn shows now.
|
||||
pub fn map(&self, p: Vec2) -> Vec2 {
|
||||
if self.at_rest() {
|
||||
return p;
|
||||
}
|
||||
self.bent().map_or(p, |b| b.map(p).0)
|
||||
}
|
||||
|
||||
/// The point of the artwork as drawn that shows at `p` (the topmost triangle there, as the
|
||||
/// mesh draws); `None` off the mesh.
|
||||
pub fn unmap(&self, p: Vec2) -> Option<Vec2> {
|
||||
let b = self.bent()?;
|
||||
if self.at_rest() {
|
||||
return (p.x >= b.grid.min.x && p.x <= b.grid.max.x && p.y >= b.grid.min.y && p.y <= b.grid.max.y).then_some(p);
|
||||
}
|
||||
let tris = b.grid.triangles();
|
||||
for tri in tris.iter().rev() {
|
||||
let [(ra, sa), (rb, sb), (rc, sc)] = tri.map(|i| b.at(i));
|
||||
let Some((l0, l1, l2)) = barycentric(sa, sb, sc, p) else { continue };
|
||||
let eps = -1e-4;
|
||||
if l0 >= eps && l1 >= eps && l2 >= eps {
|
||||
let r = ra * l0 + rb * l1 + rc * l2;
|
||||
return r.is_finite().then_some(r);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The outline as the pins bend it (the rest path itself, shared, at rest).
|
||||
pub fn outline(&self) -> Arc<Path> {
|
||||
if self.at_rest() {
|
||||
return self.rest.clone();
|
||||
}
|
||||
match self.bent() {
|
||||
Some(b) => Arc::new(bend(&self.rest, &b)),
|
||||
None => self.rest.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is the outline this warp last gave its shape.
|
||||
pub fn shows(&self, path: &Path) -> bool {
|
||||
fingerprint(path) == self.shown
|
||||
}
|
||||
|
||||
/// The warp of `path` (the shape as it now is, edited since by another tool), its pins kept
|
||||
/// where they show: they are its new rest, so nothing moves.
|
||||
pub fn rebased(&self, path: Arc<Path>) -> Warp {
|
||||
let mut w = Warp::new(path, self.resolution);
|
||||
w.pins = self.pins.iter().map(|p| Pin { id: p.id, rest: p.at, at: p.at }).collect();
|
||||
w
|
||||
}
|
||||
|
||||
/// This warp's pins blended `t` of the way to `o`'s (pins pair by id; one without a partner
|
||||
/// holds). `None` unless both bend the same artwork on the same mesh.
|
||||
pub fn lerp(&self, o: &Warp, t: f32) -> Option<Warp> {
|
||||
if !(crate::arc_eq(&self.rest, &o.rest) && self.resolution == o.resolution) {
|
||||
return None;
|
||||
}
|
||||
let mut w = self.clone();
|
||||
for p in &mut w.pins {
|
||||
if let Some(q) = o.pin(p.id) {
|
||||
p.at = p.at.lerp(q.at, t);
|
||||
}
|
||||
}
|
||||
Some(w)
|
||||
}
|
||||
|
||||
/// Repairs a loaded warp: the resolution in range, finite pins (one per id, at most
|
||||
/// [`MAX_PINS`]). `false` when nothing usable is left (no extent, too many points): the
|
||||
/// shape keeps the outline it shows.
|
||||
pub fn sanitize(&mut self) -> bool {
|
||||
if self.grid().is_none() || anchor_count(&self.rest) > MAX_WARP_POINTS {
|
||||
return false;
|
||||
}
|
||||
self.resolution = self.resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION);
|
||||
let near = |v: Vec2| v.is_finite() && v.x.abs() <= MAX_EXTENT && v.y.abs() <= MAX_EXTENT;
|
||||
let mut seen = Vec::with_capacity(self.pins.len());
|
||||
self.pins.retain(|p| {
|
||||
let keep = near(p.rest) && near(p.at) && !seen.contains(&p.id);
|
||||
seen.push(p.id);
|
||||
keep
|
||||
});
|
||||
self.pins.truncate(MAX_PINS);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
/// The shape's warp while its outline is still the one the warp gave it.
|
||||
pub fn live_warp(&self) -> Option<&Warp> {
|
||||
self.warp.as_deref().filter(|w| w.shows(&self.path))
|
||||
}
|
||||
|
||||
/// Sets the shape's warp to `w` and its outline to what `w` bends it into.
|
||||
pub fn set_warp(&mut self, mut w: Warp) {
|
||||
let path = w.outline();
|
||||
w.shown = fingerprint(&path);
|
||||
self.path = path;
|
||||
self.warp = Some(Arc::new(w));
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits cubic `(p0, c1, c2, p3)` at `t`.
|
||||
fn split_cubic(p0: Vec2, c1: Vec2, c2: Vec2, p3: Vec2, t: f32) -> ([Vec2; 4], [Vec2; 4]) {
|
||||
let (a, b, c) = (p0.lerp(c1, t), c1.lerp(c2, t), c2.lerp(p3, t));
|
||||
let (d, e) = (a.lerp(b, t), b.lerp(c, t));
|
||||
let f = d.lerp(e, t);
|
||||
([p0, a, d, f], [f, e, c, p3])
|
||||
}
|
||||
|
||||
fn split_quad(p0: Vec2, c: Vec2, p2: Vec2, t: f32) -> ([Vec2; 3], [Vec2; 3]) {
|
||||
let (a, b) = (p0.lerp(c, t), c.lerp(p2, t));
|
||||
let m = a.lerp(b, t);
|
||||
([p0, a, m], [m, b, p2])
|
||||
}
|
||||
|
||||
/// How many pieces a curve with control polygon length `len` is split into.
|
||||
fn pieces(len: f32, step: f32) -> usize {
|
||||
let n = (len / step).ceil();
|
||||
if n.is_finite() { (n as usize).clamp(1, MAX_SPLIT) } else { 1 }
|
||||
}
|
||||
|
||||
/// `rest` bent through the mesh (see the module docs).
|
||||
fn bend(rest: &Path, b: &Bent) -> Path {
|
||||
let g = &b.grid;
|
||||
let step = (((g.max.x - g.min.x) / g.nx as f32).min((g.max.y - g.min.y) / g.ny as f32) * 0.5).max(1e-3);
|
||||
// Splitting is skipped past the command budget (each anchor still maps through the mesh).
|
||||
let split = rest.cmds.len().saturating_mul(MAX_SPLIT) <= MAX_BENT_CMDS || estimate(rest, g, step) <= MAX_BENT_CMDS;
|
||||
let mut out: Vec<PathCmd> = Vec::with_capacity(rest.cmds.len() * 4);
|
||||
let mut ts = Vec::new();
|
||||
let mut cur = Vec2::ZERO;
|
||||
let mut start = Vec2::ZERO;
|
||||
// The last anchor's triangle: a cubic's first handle moves with it.
|
||||
let mut cur_tri = g.locate(cur);
|
||||
let line = |out: &mut Vec<PathCmd>, a: Vec2, p: Vec2, ts: &mut Vec<f32>| {
|
||||
if split {
|
||||
g.crossings(a, p, ts);
|
||||
for &t in ts.iter() {
|
||||
out.push(PathCmd::LineTo(b.map(a.lerp(p, t)).0));
|
||||
}
|
||||
}
|
||||
let (q, tri) = b.map(p);
|
||||
out.push(PathCmd::LineTo(q));
|
||||
tri
|
||||
};
|
||||
for c in &rest.cmds {
|
||||
match *c {
|
||||
PathCmd::MoveTo(p) => {
|
||||
let (q, tri) = b.map(p);
|
||||
out.push(PathCmd::MoveTo(q));
|
||||
(cur, start, cur_tri) = (p, p, tri);
|
||||
}
|
||||
PathCmd::LineTo(p) => {
|
||||
cur_tri = line(&mut out, cur, p, &mut ts);
|
||||
cur = p;
|
||||
}
|
||||
PathCmd::QuadTo(c, p) => {
|
||||
let n = if split { pieces(cur.distance(c) + c.distance(p), step) } else { 1 };
|
||||
let mut rest_q = [cur, c, p];
|
||||
for k in 0..n {
|
||||
let left = n - k;
|
||||
let (piece, tail) = if left > 1 { split_quad(rest_q[0], rest_q[1], rest_q[2], 1.0 / left as f32) } else { (rest_q, rest_q) };
|
||||
let (q, tri) = b.map(piece[2]);
|
||||
out.push(PathCmd::QuadTo(b.map(piece[1]).0, q));
|
||||
cur_tri = tri;
|
||||
rest_q = tail;
|
||||
}
|
||||
cur = p;
|
||||
}
|
||||
PathCmd::CubicTo(c1, c2, p) => {
|
||||
let n = if split { pieces(cur.distance(c1) + c1.distance(c2) + c2.distance(p), step) } else { 1 };
|
||||
let mut rest_c = [cur, c1, c2, p];
|
||||
for k in 0..n {
|
||||
let left = n - k;
|
||||
let (piece, tail) = if left > 1 { split_cubic(rest_c[0], rest_c[1], rest_c[2], rest_c[3], 1.0 / left as f32) } else { (rest_c, rest_c) };
|
||||
let (q, tri) = b.map(piece[3]);
|
||||
out.push(PathCmd::CubicTo(b.through(cur_tri, piece[1]), b.through(tri, piece[2]), q));
|
||||
cur_tri = tri;
|
||||
rest_c = tail;
|
||||
}
|
||||
cur = p;
|
||||
}
|
||||
PathCmd::Close => {
|
||||
// The closing edge is a straight line too: split it like one.
|
||||
if cur != start {
|
||||
if split {
|
||||
g.crossings(cur, start, &mut ts);
|
||||
for &t in &ts {
|
||||
out.push(PathCmd::LineTo(b.map(cur.lerp(start, t)).0));
|
||||
}
|
||||
}
|
||||
let (q, tri) = b.map(start);
|
||||
out.push(PathCmd::LineTo(q));
|
||||
cur_tri = tri;
|
||||
}
|
||||
out.push(PathCmd::Close);
|
||||
cur = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
Path { cmds: out }
|
||||
}
|
||||
|
||||
/// A cheap upper bound of the bent outline's commands.
|
||||
fn estimate(rest: &Path, g: &Grid, step: f32) -> usize {
|
||||
let lines = (g.nx + g.ny) as usize * 2 + 1;
|
||||
let mut cur = Vec2::ZERO;
|
||||
let mut n = 0usize;
|
||||
for c in &rest.cmds {
|
||||
n = n.saturating_add(match *c {
|
||||
PathCmd::MoveTo(p) => {
|
||||
cur = p;
|
||||
1
|
||||
}
|
||||
PathCmd::LineTo(p) => {
|
||||
cur = p;
|
||||
lines
|
||||
}
|
||||
PathCmd::QuadTo(a, p) => {
|
||||
let k = pieces(cur.distance(a) + a.distance(p), step);
|
||||
cur = p;
|
||||
k
|
||||
}
|
||||
PathCmd::CubicTo(a, b, p) => {
|
||||
let k = pieces(cur.distance(a) + a.distance(b) + b.distance(p), step);
|
||||
cur = p;
|
||||
k
|
||||
}
|
||||
PathCmd::Close => lines + 1,
|
||||
});
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "warp_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,244 @@
|
||||
use super::*;
|
||||
use crate::{Easing, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, Tween, evaluate_layer_elements};
|
||||
use anicraft_geom::Affine;
|
||||
|
||||
fn pin(id: u64, rest: (f32, f32), at: (f32, f32)) -> Pin {
|
||||
Pin { id: PinId(id), rest: Vec2::new(rest.0, rest.1), at: Vec2::new(at.0, at.1) }
|
||||
}
|
||||
|
||||
fn blob() -> Arc<Path> {
|
||||
Arc::new(Path::ellipse(100.0, 50.0, 100.0, 50.0))
|
||||
}
|
||||
|
||||
fn anchors(p: &Path) -> Vec<Vec2> {
|
||||
p.cmds
|
||||
.iter()
|
||||
.filter_map(|c| match *c {
|
||||
PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p),
|
||||
PathCmd::Close => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rest_pose_reproduces_the_artwork_exactly() {
|
||||
let rest = blob();
|
||||
let mut w = Warp::new(rest.clone(), 12);
|
||||
// No pins, then pins exactly where they were placed: the very path, shared.
|
||||
assert!(Arc::ptr_eq(&w.outline(), &rest));
|
||||
w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (190.0, 50.0), (190.0, 50.0))];
|
||||
assert!(w.at_rest());
|
||||
assert!(Arc::ptr_eq(&w.outline(), &rest));
|
||||
assert_eq!(w.map(Vec2::new(33.3, 12.5)), Vec2::new(33.3, 12.5));
|
||||
assert_eq!(w.mesh().map(|m| m.rest == m.shown), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mls_interpolates_pins_and_is_rigid_with_one_or_two() {
|
||||
// One pin: everything moves with it.
|
||||
let one = [(Vec2::new(0.0, 0.0), Vec2::new(5.0, -3.0))];
|
||||
assert_eq!(mls_rigid(&one, Vec2::new(40.0, 40.0)), Vec2::new(45.0, 37.0));
|
||||
// Two pins turned a quarter turn about their middle: every point turns with them.
|
||||
let two = [(Vec2::new(-10.0, 0.0), Vec2::new(0.0, -10.0)), (Vec2::new(10.0, 0.0), Vec2::new(0.0, 10.0))];
|
||||
for v in [Vec2::new(3.0, 7.0), Vec2::new(-20.0, 4.0), Vec2::new(0.0, 0.0)] {
|
||||
let f = mls_rigid(&two, v);
|
||||
let want = Vec2::new(-v.y, v.x);
|
||||
assert!(f.distance(want) < 1e-3, "{v:?} → {f:?}, want {want:?}");
|
||||
}
|
||||
// On a pin: exactly its target.
|
||||
assert_eq!(mls_rigid(&two, Vec2::new(10.0, 0.0)), Vec2::new(0.0, 10.0));
|
||||
assert_eq!(mls_rigid(&[], Vec2::new(1.0, 2.0)), Vec2::new(1.0, 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_moved_pin_moves_nearby_points_most() {
|
||||
let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 300.0, 100.0)), 12);
|
||||
// Three pins along the strip; the right one is pulled down.
|
||||
w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (150.0, 50.0), (150.0, 50.0)), pin(3, (290.0, 50.0), (290.0, 90.0))];
|
||||
let moved = |x: f32| w.map(Vec2::new(x, 50.0)).distance(Vec2::new(x, 50.0));
|
||||
let (near, mid, far) = (moved(270.0), moved(200.0), moved(40.0));
|
||||
assert!(near > mid && mid > far, "{near} > {mid} > {far}");
|
||||
assert!(near > 25.0 && far < 3.0, "near {near}, far {far}");
|
||||
// The pins themselves are where they were put (to within the mesh's interpolation).
|
||||
for p in &w.pins {
|
||||
assert!(w.map(p.rest).distance(p.at) < 1.5, "{p:?} → {:?}", w.map(p.rest));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deformation_is_as_rigid_as_possible() {
|
||||
// Rigidity: how much each triangle's map stretches or shears (its singular values' distance
|
||||
// from 1). A pure turn of the pins turns the mesh rigidly; a bend stays near rigid.
|
||||
let distortion = |w: &Warp| {
|
||||
let m = w.mesh().unwrap_or_else(unreachable_mesh);
|
||||
let mut worst = 0.0f32;
|
||||
for t in &m.tris {
|
||||
let [a, b, c] = t.map(|i| i as usize);
|
||||
let (r0, r1, r2) = (m.rest[a], m.rest[b], m.rest[c]);
|
||||
let (s0, s1, s2) = (m.shown[a], m.shown[b], m.shown[c]);
|
||||
// The linear part J with J·(r1 − r0, r2 − r0) = (s1 − s0, s2 − s0).
|
||||
let (e1, e2, f1, f2) = (r1 - r0, r2 - r0, s1 - s0, s2 - s0);
|
||||
let det = e1.cross(e2);
|
||||
let inv = [e2.y / det, -e2.x / det, -e1.y / det, e1.x / det];
|
||||
let j = [f1.x * inv[0] + f2.x * inv[2], f1.x * inv[1] + f2.x * inv[3], f1.y * inv[0] + f2.y * inv[2], f1.y * inv[1] + f2.y * inv[3]];
|
||||
let (p, q, r, s) = (j[0], j[1], j[2], j[3]);
|
||||
let e = (p * p + q * q + r * r + s * s) * 0.5;
|
||||
let d = (p * s - q * r).abs();
|
||||
let disc = (e * e - d * d).max(0.0).sqrt();
|
||||
let (big, small) = ((e + disc).sqrt(), (e - disc).max(0.0).sqrt());
|
||||
worst = worst.max((big - 1.0).abs()).max((small - 1.0).abs());
|
||||
}
|
||||
worst
|
||||
};
|
||||
let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 200.0, 100.0)), 10);
|
||||
let turn = Affine::translate(100.0, 50.0).mul(&Affine::rotate(0.6)).mul(&Affine::translate(-100.0, -50.0));
|
||||
w.pins = [(20.0, 20.0), (180.0, 30.0), (100.0, 90.0)].iter().enumerate().map(|(i, &(x, y))| Pin { id: PinId(i as u64), rest: Vec2::new(x, y), at: turn.apply(Vec2::new(x, y)) }).collect();
|
||||
assert!(distortion(&w) < 1e-3, "a turn is rigid: {}", distortion(&w));
|
||||
// A bend: one end of a strip turned down by 30°.
|
||||
w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (100.0, 50.0), (100.0, 50.0)), pin(3, (190.0, 50.0), (178.0, 95.0))];
|
||||
let d = distortion(&w);
|
||||
assert!(d < 0.25, "a bend stays near rigid: {d}");
|
||||
}
|
||||
|
||||
fn unreachable_mesh() -> WarpMesh {
|
||||
WarpMesh { rest: Vec::new(), shown: Vec::new(), tris: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn straight_edges_follow_the_mesh_exactly() {
|
||||
// A bitmap's outline is a rectangle: bent, it is exactly the mesh's border.
|
||||
let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 120.0, 60.0)), 6);
|
||||
w.pins = vec![pin(1, (0.0, 0.0), (0.0, 0.0)), pin(2, (120.0, 60.0), (150.0, 90.0))];
|
||||
let m = w.mesh().unwrap_or_else(unreachable_mesh);
|
||||
let g = w.grid().unwrap_or(Grid { min: Vec2::ZERO, max: Vec2::ZERO, nx: 1, ny: 1 });
|
||||
assert_eq!((g.nx, g.ny), (6, 3));
|
||||
let pts = anchors(&w.outline());
|
||||
// Every border vertex of the mesh is on the bent outline.
|
||||
for (i, v) in m.rest.iter().enumerate() {
|
||||
let border = v.x == 0.0 || v.y == 0.0 || v.x == 120.0 || v.y == 60.0;
|
||||
if border {
|
||||
assert!(pts.iter().any(|p| p.distance(m.shown[i]) < 1e-3), "border vertex {v:?} missing");
|
||||
}
|
||||
}
|
||||
// And the outline has no point the border doesn't (straight lines between them).
|
||||
assert_eq!(pts.len(), 2 * (6 + 3) + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curves_split_and_stay_close_to_the_true_deformation() {
|
||||
let mut w = Warp::new(blob(), 16);
|
||||
w.pins = vec![pin(1, (0.0, 50.0), (0.0, 50.0)), pin(2, (100.0, 50.0), (100.0, 50.0)), pin(3, (200.0, 50.0), (190.0, 100.0))];
|
||||
let bent = w.outline();
|
||||
assert!(bent.cmds.len() > blob().cmds.len());
|
||||
// Points of the bent outline lie near where the exact MLS deformation puts the drawn curve.
|
||||
let pins: Vec<(Vec2, Vec2)> = w.pins.iter().map(|p| (p.rest, p.at)).collect();
|
||||
let truth: Vec<Vec2> = (0..400).map(|i| {
|
||||
let a = i as f32 / 400.0 * std::f32::consts::TAU;
|
||||
mls_rigid(&pins, Vec2::new(100.0 + 100.0 * a.cos(), 50.0 + 50.0 * a.sin()))
|
||||
}).collect();
|
||||
for p in anchors(&bent) {
|
||||
let d = truth.iter().map(|t| t.distance(p)).fold(f32::MAX, f32::min);
|
||||
assert!(d < 2.0, "{p:?} is {d} from the true curve");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmap_finds_the_drawn_point() {
|
||||
let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 200.0, 100.0)), 8);
|
||||
w.pins = vec![pin(1, (20.0, 50.0), (20.0, 50.0)), pin(2, (180.0, 50.0), (200.0, 80.0))];
|
||||
for p in [Vec2::new(50.0, 30.0), Vec2::new(150.0, 70.0), Vec2::new(190.0, 10.0)] {
|
||||
let shown = w.map(p);
|
||||
let back = w.unmap(shown).unwrap_or(Vec2::new(f32::NAN, 0.0));
|
||||
assert!(back.distance(p) < 1e-2, "{p:?} → {shown:?} → {back:?}");
|
||||
}
|
||||
assert_eq!(w.unmap(Vec2::new(-500.0, 0.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_and_bounded() {
|
||||
let mut w = Warp::new(blob(), 1000);
|
||||
assert_eq!(w.resolution, MAX_RESOLUTION);
|
||||
w.pins = (0..MAX_PINS as u64).map(|i| pin(i, (i as f32, 50.0), (i as f32 + 3.0, 50.0 + (i % 7) as f32))).collect();
|
||||
let (a, b) = (w.outline(), w.outline());
|
||||
assert_eq!(fingerprint(&a), fingerprint(&b));
|
||||
let m = w.mesh().unwrap_or_else(unreachable_mesh);
|
||||
assert!(m.rest.len() <= ((MAX_RESOLUTION + 1) * (MAX_RESOLUTION + 1)) as usize);
|
||||
// Tiny, flat and enormous artwork never fails.
|
||||
for p in [Path::line(Vec2::new(0.0, 0.0), Vec2::new(0.0, 0.0)), Path::line(Vec2::new(0.0, 5.0), Vec2::new(300.0, 5.0)), Path::rect(0.0, 0.0, 1e7, 1.0), Path::default()] {
|
||||
let mut w = Warp::new(Arc::new(p), 12);
|
||||
w.pins = vec![pin(1, (0.0, 5.0), (40.0, 9.0)), pin(2, (100.0, 5.0), (100.0, 5.0))];
|
||||
let out = w.outline();
|
||||
assert!(out.cmds.iter().all(|c| match *c {
|
||||
PathCmd::MoveTo(p) | PathCmd::LineTo(p) => p.is_finite(),
|
||||
_ => true,
|
||||
}));
|
||||
}
|
||||
// Hostile pins are dropped on load; the rest stays.
|
||||
let mut h = Warp::new(blob(), 0);
|
||||
h.pins = vec![pin(1, (f32::NAN, 0.0), (0.0, 0.0)), pin(2, (1.0, 1.0), (2.0, 2.0)), pin(2, (3.0, 3.0), (3.0, 3.0))];
|
||||
assert!(h.sanitize());
|
||||
assert_eq!(h.pins.len(), 1);
|
||||
assert_eq!(h.resolution, MIN_RESOLUTION);
|
||||
}
|
||||
|
||||
fn warped_layer(at_end: (f32, f32), easing: Easing) -> (Layer, Warp) {
|
||||
let mut shape = Shape::filled(Path::rect(0.0, 0.0, 200.0, 100.0), Paint::Solid(Rgba::hex(0x3080ff)));
|
||||
let mut w = Warp::new(shape.path.clone(), 8);
|
||||
w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (190.0, 50.0), (190.0, 50.0))];
|
||||
shape.set_warp(w.clone());
|
||||
let el = |s: Shape| Arc::new(Element { id: ElementId(5), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Shape(s) });
|
||||
let mut end = shape.clone();
|
||||
let mut w2 = w.clone();
|
||||
if let Some(p) = w2.pins.get_mut(1) {
|
||||
p.at = Vec2::new(at_end.0, at_end.1);
|
||||
}
|
||||
end.set_warp(w2);
|
||||
let mut layer = Layer::new(LayerId(1), "Art");
|
||||
let mut a = Keyframe::new(0, 10);
|
||||
a.elements = vec![el(shape)];
|
||||
a.tween = Some(Tween { easing, ..Default::default() });
|
||||
let mut b = Keyframe::new(10, 1);
|
||||
b.elements = vec![el(end)];
|
||||
layer.keyframes = vec![Arc::new(a), Arc::new(b)];
|
||||
(layer, w)
|
||||
}
|
||||
|
||||
fn shape_at(layer: &Layer, frame: u32) -> Shape {
|
||||
let (_, els) = evaluate_layer_elements(layer, frame).unwrap_or((0, std::borrow::Cow::Owned(Vec::new())));
|
||||
match els.first().map(|e| &e.kind) {
|
||||
Some(ElementKind::Shape(s)) => s.clone(),
|
||||
_ => Shape::filled(Path::default(), Paint::Solid(Rgba::BLACK)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pins_tween_between_keyframes() {
|
||||
let (layer, w) = warped_layer((190.0, 150.0), Easing::Linear);
|
||||
let mid = shape_at(&layer, 5);
|
||||
let mw = mid.live_warp().cloned().unwrap_or_else(|| w.clone());
|
||||
// Halfway the pulled pin is halfway, and the outline is the mesh bent by the halfway pins.
|
||||
assert_eq!(mw.pin(PinId(2)).map(|p| p.at), Some(Vec2::new(190.0, 100.0)));
|
||||
let mut want = w.clone();
|
||||
if let Some(p) = want.pins.get_mut(1) {
|
||||
p.at = Vec2::new(190.0, 100.0);
|
||||
}
|
||||
assert_eq!(*mid.path, *want.outline());
|
||||
// At the keyframes: exactly what they hold.
|
||||
assert!(Arc::ptr_eq(&shape_at(&layer, 0).path, &w.rest));
|
||||
// Easing applies to the pins as it does to bone poses.
|
||||
let (eased, _) = warped_layer((190.0, 150.0), Easing::QuadIn);
|
||||
let ep = shape_at(&eased, 5).live_warp().and_then(|w| w.pin(PinId(2)).map(|p| p.at.y)).unwrap_or(0.0);
|
||||
assert!(ep < 100.0 && ep > 50.0, "{ep}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_edited_by_another_tool_drops_out_of_its_warp() {
|
||||
let (layer, _) = warped_layer((190.0, 150.0), Easing::Linear);
|
||||
let mut s = shape_at(&layer, 10);
|
||||
assert!(s.live_warp().is_some());
|
||||
s.path = Arc::new(s.path.transformed(&Affine::translate(1.0, 0.0)));
|
||||
assert!(s.live_warp().is_none());
|
||||
let w = s.warp.as_deref().cloned().unwrap_or_else(|| Warp::new(blob(), 4)).rebased(s.path.clone());
|
||||
// Rebased, nothing moves: the edited outline is the new rest and the pins stay where they show.
|
||||
assert!(w.at_rest() && w.pins.iter().any(|p| p.rest == Vec2::new(190.0, 150.0)));
|
||||
}
|
||||
@@ -21,10 +21,12 @@ thiserror.workspace = true
|
||||
rayon.workspace = true
|
||||
web-time.workspace = true
|
||||
gif.workspace = true
|
||||
# Animated PNG frames (ADR 0063; already in the tree through the renderer).
|
||||
png.workspace = true
|
||||
image-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).
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
//! 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 whole `VP8L` chunk).
|
||||
struct Encoded {
|
||||
rect: Rect,
|
||||
over: bool,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The frame rate as a fraction `p / q` frames per second: 24 → 24/1, 29.97 → 2997/100,
|
||||
/// 23.976 → 2997/125. Rates no small fraction matches are taken to a thousandth.
|
||||
pub fn fps_ratio(fps: f32) -> (u64, u64) {
|
||||
let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 24.0 };
|
||||
for q in 1..=1001u64 {
|
||||
let p = (fps * q as f64).round();
|
||||
if p >= 1.0 && (p / q as f64 - fps).abs() <= fps * 1e-6 {
|
||||
return (p as u64, q);
|
||||
}
|
||||
}
|
||||
let p = ((fps * 1000.0).round() as u64).max(1);
|
||||
let g = gcd(p, 1000);
|
||||
(p / g, 1000 / g)
|
||||
}
|
||||
|
||||
fn gcd(mut a: u64, mut b: u64) -> u64 {
|
||||
while b != 0 {
|
||||
(a, b) = (b, a % b);
|
||||
}
|
||||
a.max(1)
|
||||
}
|
||||
|
||||
/// When frame `t` (from the first exported) starts, in whole milliseconds, rounded from the
|
||||
/// exact time at `p / q` fps.
|
||||
pub fn start_ms(t: u64, (p, q): (u64, u64)) -> u64 {
|
||||
let p = u128::from(p.max(1));
|
||||
((2 * u128::from(t) * 1000 * u128::from(q) + p) / (2 * p)) as u64
|
||||
}
|
||||
|
||||
/// The APNG delays (numerator, denominator in seconds) of a frame shown from frame `start` for
|
||||
/// `count` frames: one exact fraction, or more when it is longer than one `fcTL` holds.
|
||||
pub fn apng_delays(start: u64, count: u64, (p, q): (u64, u64)) -> Vec<(u16, u16)> {
|
||||
let mut out = Vec::new();
|
||||
if let Ok(den) = u16::try_from(p) {
|
||||
// `count` frames last count·q/p s; pieces of at most 65535/q frames always fit.
|
||||
let most = (u64::from(u16::MAX) / q.max(1)).max(1);
|
||||
let mut left = count;
|
||||
while left > 0 {
|
||||
let m = left.min(most);
|
||||
let (num, g) = (m * q, gcd(m * q, p));
|
||||
out.push((u16::try_from(num / g).unwrap_or(u16::MAX), u16::try_from(u64::from(den) / g).unwrap_or(den)));
|
||||
left -= m;
|
||||
}
|
||||
} else {
|
||||
// A rate with a huge denominator: milliseconds, rounded from each frame's start.
|
||||
let mut ms = start_ms(start + count, (p, q)) - start_ms(start, (p, q));
|
||||
while ms > 0 {
|
||||
let m = ms.min(u64::from(u16::MAX));
|
||||
out.push((m as u16, 1000));
|
||||
ms -= m;
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push((0, 1));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The WebP durations (milliseconds) of a frame shown from frame `start` for `count` frames:
|
||||
/// one, or more when it is longer than one `ANMF` holds.
|
||||
pub fn webp_durations(start: u64, count: u64, ratio: (u64, u64)) -> Vec<u32> {
|
||||
let mut ms = start_ms(start + count, ratio).saturating_sub(start_ms(start, ratio));
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let m = ms.min(MAX_WEBP_MS);
|
||||
out.push(m as u32);
|
||||
ms -= m;
|
||||
if ms == 0 {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest rectangle holding every pixel where RGBA8 images `a` and `b` (`w` × `h`) differ,
|
||||
/// or `None` when they are the same.
|
||||
pub fn changed(a: &[u8], b: &[u8], w: u32, h: u32) -> Option<Rect> {
|
||||
let stride = w as usize * 4;
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0u32, 0u32);
|
||||
for y in 0..h {
|
||||
let at = y as usize * stride;
|
||||
let (Some(ra), Some(rb)) = (a.get(at..at + stride), b.get(at..at + stride)) else { break };
|
||||
if ra == rb {
|
||||
continue;
|
||||
}
|
||||
let (pa, pb) = (ra.as_chunks::<4>().0, rb.as_chunks::<4>().0);
|
||||
let first = pa.iter().zip(pb).position(|(u, v)| u != v).unwrap_or(0) as u32;
|
||||
let last = pa.iter().zip(pb).rposition(|(u, v)| u != v).unwrap_or(0) as u32;
|
||||
x0 = x0.min(first);
|
||||
x1 = x1.max(last);
|
||||
y0 = y0.min(y);
|
||||
y1 = y;
|
||||
}
|
||||
(y0 != u32::MAX).then(|| Rect { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 })
|
||||
}
|
||||
|
||||
/// Rectangle `r` of RGBA8 image `px` (`w` wide).
|
||||
fn crop(px: &[u8], w: u32, r: Rect) -> Vec<u8> {
|
||||
let stride = w as usize * 4;
|
||||
let mut out = Vec::with_capacity(r.w as usize * r.h as usize * 4);
|
||||
for y in r.y..r.y + r.h {
|
||||
let at = y as usize * stride + r.x as usize * 4;
|
||||
if let Some(row) = px.get(at..at + r.w as usize * 4) {
|
||||
out.extend_from_slice(row);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What frame `cur` writes after frame `before` (none: it is the first, and covers the canvas):
|
||||
/// the region, whether it blends over, and its pixels.
|
||||
fn region(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> (Rect, bool, Vec<u8>) {
|
||||
let full = Rect { x: 0, y: 0, w, h };
|
||||
let Some(before) = before else { return (full, false, cur.to_vec()) };
|
||||
let mut r = changed(before, cur, w, h).unwrap_or(full);
|
||||
match kind {
|
||||
Kind::Webp => {
|
||||
// Frame offsets are stored halved: the region starts on an even pixel.
|
||||
let (ex, ey) = (r.x & !1, r.y & !1);
|
||||
r = Rect { x: ex, y: ey, w: r.w + (r.x - ex), h: r.h + (r.y - ey) };
|
||||
(r, false, crop(cur, w, r))
|
||||
}
|
||||
Kind::Apng => {
|
||||
let (old, new) = (crop(before, w, r), crop(cur, w, r));
|
||||
let (po, pn) = (old.as_chunks::<4>().0, new.as_chunks::<4>().0);
|
||||
if po.iter().zip(pn).all(|(o, n)| o == n || n[3] == 255) {
|
||||
// Every changed pixel is opaque: blend over, unchanged pixels transparent.
|
||||
let mut px = Vec::with_capacity(new.len());
|
||||
for (o, n) in po.iter().zip(pn) {
|
||||
px.extend_from_slice(if o == n { &[0, 0, 0, 0] } else { n });
|
||||
}
|
||||
(r, true, px)
|
||||
} else {
|
||||
(r, false, new)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A standalone PNG's image data: its `IDAT` chunks' contents, joined.
|
||||
fn idat(png: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = 8usize;
|
||||
while let Some(head) = png.get(at..at + 8) {
|
||||
let len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize;
|
||||
let data = png.get(at + 8..at + 8 + len).ok_or_else(|| EngineError::Format("the PNG encoder wrote a short chunk".into()))?;
|
||||
if &head[4..8] == b"IDAT" {
|
||||
out.extend_from_slice(data);
|
||||
}
|
||||
at += 12 + len;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A RIFF file's first chunk named `id`, whole (header, data and padding).
|
||||
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..at + whole).or_else(|| riff.get(at..at + 8 + len));
|
||||
}
|
||||
at += whole;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Compresses `px` (`w` × `h` RGBA8) as one frame's data.
|
||||
fn compress(kind: Kind, px: &[u8], w: u32, h: u32) -> Result<Vec<u8>> {
|
||||
let fail = |e: String| EngineError::Format(format!("{} frame: {e}", kind.name()));
|
||||
match kind {
|
||||
Kind::Apng => {
|
||||
let mut buf = Vec::new();
|
||||
{
|
||||
let mut enc = png::Encoder::new(&mut buf, w, h);
|
||||
enc.set_color(png::ColorType::Rgba);
|
||||
enc.set_depth(png::BitDepth::Eight);
|
||||
enc.set_adaptive_filter(png::AdaptiveFilterType::Adaptive);
|
||||
enc.set_compression(png::Compression::Best);
|
||||
let mut wr = enc.write_header().map_err(|e| fail(e.to_string()))?;
|
||||
wr.write_image_data(px).map_err(|e| fail(e.to_string()))?;
|
||||
}
|
||||
idat(&buf)
|
||||
}
|
||||
Kind::Webp => {
|
||||
if px.len() != w as usize * h as usize * 4 {
|
||||
return Err(fail("the frame has the wrong size".into()));
|
||||
}
|
||||
let mut buf = Vec::new();
|
||||
image_webp::WebPEncoder::new(&mut buf).encode(px, w, h, image_webp::ColorType::Rgba8).map_err(|e| fail(e.to_string()))?;
|
||||
riff_chunk(&buf, b"VP8L").map(<[u8]>::to_vec).ok_or_else(|| fail("the WebP encoder wrote no lossless image".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> Result<Encoded> {
|
||||
let (rect, over, px) = region(kind, before, cur, w, h);
|
||||
Ok(Encoded { rect, over, data: compress(kind, &px, rect.w, rect.h)? })
|
||||
}
|
||||
|
||||
/// A frame that changes nothing (one transparent pixel blended over the top-left corner): how
|
||||
/// a delay too long for one frame header goes on.
|
||||
fn still(kind: Kind) -> Result<Encoded> {
|
||||
Ok(Encoded { rect: Rect { x: 0, y: 0, w: 1, h: 1 }, over: true, data: compress(kind, &[0, 0, 0, 0], 1, 1)? })
|
||||
}
|
||||
|
||||
// ----- the files ---------------------------------------------------------------------------
|
||||
|
||||
fn png_chunk(out: &mut Vec<u8>, id: &[u8; 4], data: &[u8]) -> Result<()> {
|
||||
let len = u32::try_from(data.len()).ok().filter(|l| *l < 1 << 31).ok_or_else(|| EngineError::Format("an animated PNG frame is too large".into()))?;
|
||||
out.extend_from_slice(&len.to_be_bytes());
|
||||
let from = out.len();
|
||||
out.extend_from_slice(id);
|
||||
out.extend_from_slice(data);
|
||||
let crc = anicraft_xfl::zip::crc32(out.get(from..).unwrap_or(&[]));
|
||||
out.extend_from_slice(&crc.to_be_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The APNG file: frames with their delays (the first frame is the default image).
|
||||
fn apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> Result<Vec<u8>> {
|
||||
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
let mut ihdr = Vec::with_capacity(13);
|
||||
ihdr.extend_from_slice(&w.to_be_bytes());
|
||||
ihdr.extend_from_slice(&h.to_be_bytes());
|
||||
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA, deflate, adaptive filters, no interlace
|
||||
png_chunk(&mut out, b"IHDR", &ihdr)?;
|
||||
let count = u32::try_from(frames.len()).map_err(|_| EngineError::Format("too many frames".into()))?;
|
||||
let mut actl = count.to_be_bytes().to_vec();
|
||||
actl.extend_from_slice(&plays.to_be_bytes());
|
||||
png_chunk(&mut out, b"acTL", &actl)?;
|
||||
let mut seq = 0u32;
|
||||
for (k, (f, (num, den))) in frames.iter().enumerate() {
|
||||
let mut fctl = Vec::with_capacity(26);
|
||||
for v in [seq, f.rect.w, f.rect.h, f.rect.x, f.rect.y] {
|
||||
fctl.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
fctl.extend_from_slice(&num.to_be_bytes());
|
||||
fctl.extend_from_slice(&den.to_be_bytes());
|
||||
fctl.extend_from_slice(&[0, u8::from(f.over)]); // dispose: none; blend: source or over
|
||||
png_chunk(&mut out, b"fcTL", &fctl)?;
|
||||
seq += 1;
|
||||
if k == 0 {
|
||||
png_chunk(&mut out, b"IDAT", &f.data)?;
|
||||
} else {
|
||||
let mut fdat = Vec::with_capacity(f.data.len() + 4);
|
||||
fdat.extend_from_slice(&seq.to_be_bytes());
|
||||
fdat.extend_from_slice(&f.data);
|
||||
png_chunk(&mut out, b"fdAT", &fdat)?;
|
||||
seq += 1;
|
||||
}
|
||||
}
|
||||
png_chunk(&mut out, b"IEND", &[])?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn le24(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_le_bytes()[..3]);
|
||||
}
|
||||
|
||||
fn riff_push(out: &mut Vec<u8>, id: &[u8; 4], data: &[u8]) -> Result<()> {
|
||||
let len = u32::try_from(data.len()).map_err(|_| EngineError::Format("an animated WebP frame is too large".into()))?;
|
||||
out.extend_from_slice(id);
|
||||
out.extend_from_slice(&len.to_le_bytes());
|
||||
out.extend_from_slice(data);
|
||||
if len & 1 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The animated WebP file: frames with their durations. `background` is the stage colour as
|
||||
/// the `ANIM` background (RGBA), or transparent.
|
||||
fn webp_file(w: u32, h: u32, plays: u32, alpha: bool, background: [u8; 4], frames: &[(&Encoded, u32)]) -> Result<Vec<u8>> {
|
||||
let mut body = b"WEBP".to_vec();
|
||||
let mut vp8x = vec![if alpha { 0x10 | 0x02 } else { 0x02 }, 0, 0, 0];
|
||||
le24(&mut vp8x, w - 1);
|
||||
le24(&mut vp8x, h - 1);
|
||||
riff_push(&mut body, b"VP8X", &vp8x)?;
|
||||
let [r, g, b, a] = background;
|
||||
let mut anim = vec![b, g, r, a];
|
||||
anim.extend_from_slice(&u16::try_from(plays).unwrap_or(u16::MAX).to_le_bytes());
|
||||
riff_push(&mut body, b"ANIM", &anim)?;
|
||||
for (f, ms) in frames {
|
||||
let mut anmf = Vec::with_capacity(16 + f.data.len());
|
||||
le24(&mut anmf, f.rect.x / 2);
|
||||
le24(&mut anmf, f.rect.y / 2);
|
||||
le24(&mut anmf, f.rect.w - 1);
|
||||
le24(&mut anmf, f.rect.h - 1);
|
||||
le24(&mut anmf, *ms);
|
||||
anmf.push(if f.over { 0 } else { 0x02 }); // blending: alpha-blend or replace; dispose: none
|
||||
anmf.extend_from_slice(&f.data);
|
||||
riff_push(&mut body, b"ANMF", &anmf)?;
|
||||
}
|
||||
let mut out = Vec::with_capacity(body.len() + 8);
|
||||
riff_push(&mut out, b"RIFF", &body)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ----- the command -------------------------------------------------------------------------
|
||||
|
||||
/// How many times it plays: `loop` true (or absent) forever (0), false once, or a count.
|
||||
pub(crate) fn plays(p: &Value) -> Result<u32> {
|
||||
match p.get("loop") {
|
||||
None | Some(Value::Null) | Some(Value::Bool(true)) => Ok(0),
|
||||
Some(Value::Bool(false)) => Ok(1),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|n| *n <= MAX_PLAYS)
|
||||
.ok_or_else(|| EngineError::Param(format!("param 'loop' must be true (forever), false (once) or how many times it plays (0 is forever, at most {MAX_PLAYS})"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `file.export_apng` and `file.export_webp`.
|
||||
pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
// The whole movie: every scene in order.
|
||||
let last = s.doc.frame_count().saturating_sub(1);
|
||||
let from = opt_u32(p, "from")?.unwrap_or(0).min(last);
|
||||
let to = opt_u32(p, "to")?.unwrap_or(last).min(last);
|
||||
if to < from {
|
||||
return Err(EngineError::Param("'to' must not be before 'from'".into()));
|
||||
}
|
||||
let scale = crate::cmds_file::scale_param(p)?;
|
||||
let plays = plays(p)?;
|
||||
let background = opt_bool(p, "background")?.unwrap_or(false);
|
||||
let mut view = View::stage(&s.doc, scale);
|
||||
if !background {
|
||||
view.background = None;
|
||||
}
|
||||
let (w, h) = (view.width.max(1), view.height.max(1));
|
||||
if kind == Kind::Webp && (w > MAX_WEBP_EDGE || h > MAX_WEBP_EDGE) {
|
||||
return Err(EngineError::Param(format!("WebP frames are at most {MAX_WEBP_EDGE} px per side; lower 'scale'")));
|
||||
}
|
||||
let n = u64::from(to - from) + 1;
|
||||
if n * u64::from(w) * u64::from(h) > MAX_ANIM_PIXELS {
|
||||
return Err(EngineError::Param(format!("that {} would be too large ({n} frames at {w}×{h}); lower 'scale' or the frame range", kind.name())));
|
||||
}
|
||||
let doc = &s.doc;
|
||||
let job = s.job.as_deref();
|
||||
let started = web_time::Instant::now();
|
||||
let batch = (BATCH_PIXELS / (u64::from(w) * u64::from(h))).clamp(2, 16) as usize;
|
||||
// Each distinct frame: its first frame (from 0) and how many frames it shows for.
|
||||
let mut shown: Vec<(u64, u64)> = Vec::new();
|
||||
let mut encoded: Vec<Encoded> = Vec::new();
|
||||
let mut prev: Option<Vec<u8>> = None;
|
||||
let frames: Vec<u32> = (from..=to).collect();
|
||||
for (b, chunk) in frames.chunks(batch).enumerate() {
|
||||
let images: Vec<Vec<u8>> = chunk
|
||||
.par_iter()
|
||||
.map(|&f| {
|
||||
let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?;
|
||||
crate::publish::tick(job, 1)?;
|
||||
Ok(pm.to_rgba8())
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
// A frame like the one before it only lengthens that frame's delay.
|
||||
let mut fresh: Vec<usize> = Vec::new();
|
||||
let mut last_seen: Option<&[u8]> = prev.as_deref();
|
||||
for (i, img) in images.iter().enumerate() {
|
||||
match shown.last_mut() {
|
||||
Some((_, count)) if last_seen == Some(img.as_slice()) => *count += 1,
|
||||
_ => {
|
||||
shown.push(((b * batch + i) as u64, 1));
|
||||
fresh.push(i);
|
||||
}
|
||||
}
|
||||
last_seen = Some(img.as_slice());
|
||||
}
|
||||
let made = (0..fresh.len())
|
||||
.into_par_iter()
|
||||
.map(|k| {
|
||||
let cur = fresh.get(k).and_then(|&i| images.get(i)).ok_or_else(|| EngineError::Format("lost a frame".into()))?;
|
||||
let before = match k.checked_sub(1) {
|
||||
None => prev.as_deref(),
|
||||
Some(j) => fresh.get(j).and_then(|&i| images.get(i)).map(Vec::as_slice),
|
||||
};
|
||||
encode(kind, before, cur, w, h)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
encoded.extend(made);
|
||||
if let Some(&i) = fresh.last() {
|
||||
prev = images.into_iter().nth(i);
|
||||
}
|
||||
}
|
||||
let ratio = fps_ratio(doc.stage.fps);
|
||||
let pad = still(kind)?;
|
||||
let bytes = match kind {
|
||||
Kind::Apng => {
|
||||
let mut list: Vec<(&Encoded, (u16, u16))> = Vec::new();
|
||||
for (e, &(start, count)) in encoded.iter().zip(&shown) {
|
||||
for (k, d) in apng_delays(start, count, ratio).into_iter().enumerate() {
|
||||
list.push((if k == 0 { e } else { &pad }, d));
|
||||
}
|
||||
}
|
||||
apng_file(w, h, plays, &list)?
|
||||
}
|
||||
Kind::Webp => {
|
||||
let mut list: Vec<(&Encoded, u32)> = Vec::new();
|
||||
for (e, &(start, count)) in encoded.iter().zip(&shown) {
|
||||
for (k, d) in webp_durations(start, count, ratio).into_iter().enumerate() {
|
||||
list.push((if k == 0 { e } else { &pad }, d));
|
||||
}
|
||||
}
|
||||
let padded = list.len() > encoded.len();
|
||||
let c = s.doc.stage.background.sanitized();
|
||||
let q = |v: f32| (v * 255.0).round() as u8;
|
||||
let bg = if background { [q(c.r), q(c.g), q(c.b), 255] } else { [0; 4] };
|
||||
webp_file(w, h, plays, !background || padded, bg, &list)?
|
||||
}
|
||||
};
|
||||
crate::vfs::write(&path, &bytes)?;
|
||||
Ok(json!({
|
||||
"written": path.display().to_string(),
|
||||
"frames": n,
|
||||
"stored_frames": encoded.len(),
|
||||
"bytes": bytes.len(),
|
||||
"width": w,
|
||||
"height": h,
|
||||
"loop": plays,
|
||||
"ms": started.elapsed().as_millis() as u64,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "anim_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,347 @@
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use anicraft_doc::sample;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-anim-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// What the CPU renderer draws for movie frames `from..=to`, as straight RGBA8.
|
||||
fn renders(doc: &anicraft_doc::Document, from: u32, to: u32, scale: f32, background: bool) -> Vec<Vec<u8>> {
|
||||
let mut view = View::stage(doc, scale);
|
||||
if !background {
|
||||
view.background = None;
|
||||
}
|
||||
(from..=to).map(|f| render(&anicraft_doc::evaluate(doc, f), &view).unwrap().0.to_rgba8()).collect()
|
||||
}
|
||||
|
||||
/// An APNG decoded as a player shows it (the APNG specification's compositing): each frame's
|
||||
/// canvas, its delay (num, den), its region and blend op, and the play count.
|
||||
struct ApngFrame {
|
||||
canvas: Vec<u8>,
|
||||
delay: (u16, u16),
|
||||
rect: Rect,
|
||||
over: bool,
|
||||
}
|
||||
|
||||
struct Apng {
|
||||
frames: Vec<ApngFrame>,
|
||||
plays: u32,
|
||||
size: (u32, u32),
|
||||
}
|
||||
|
||||
fn decode_apng(bytes: &[u8]) -> Apng {
|
||||
let dec = png::Decoder::new(std::io::Cursor::new(bytes));
|
||||
let mut reader = dec.read_info().unwrap();
|
||||
let info = reader.info();
|
||||
let (w, h) = (info.width, info.height);
|
||||
let actl = info.animation_control.expect("an acTL chunk");
|
||||
assert_eq!((info.color_type, info.bit_depth), (png::ColorType::Rgba, png::BitDepth::Eight));
|
||||
let mut canvas = vec![0u8; (w * h * 4) as usize];
|
||||
let mut frames = Vec::new();
|
||||
let mut buf = vec![0u8; reader.output_buffer_size()];
|
||||
for _ in 0..actl.num_frames {
|
||||
let out = reader.next_frame(&mut buf).unwrap();
|
||||
let fc = *reader.info().frame_control().expect("an fcTL per frame");
|
||||
assert_eq!(fc.dispose_op, png::DisposeOp::None);
|
||||
let over = fc.blend_op == png::BlendOp::Over;
|
||||
let r = Rect { x: fc.x_offset, y: fc.y_offset, w: fc.width, h: fc.height };
|
||||
assert_eq!((out.width, out.height), (r.w, r.h));
|
||||
assert!(r.x + r.w <= w && r.y + r.h <= h);
|
||||
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: actl.num_plays, size: (w, h) }
|
||||
}
|
||||
|
||||
/// The frames an APNG shows, one per movie frame at `ratio` fps (each delay is a whole number
|
||||
/// of movie frames, exactly).
|
||||
fn apng_movie(a: &Apng, (p, q): (u64, u64)) -> Vec<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
for f in &a.frames {
|
||||
let (num, den) = (u64::from(f.delay.0), u64::from(f.delay.1));
|
||||
// num/den s = k·q/p s
|
||||
assert_eq!((num * p) % (den * q), 0, "a delay of {num}/{den} s is not a whole number of frames at {p}/{q} fps");
|
||||
for _ in 0..num * p / (den * q) {
|
||||
out.push(f.canvas.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A WebP decoded as a player shows it: each frame's canvas and duration.
|
||||
/// An animated WebP's frames (canvas, milliseconds), loop count, size and whether it has alpha.
|
||||
struct Webp {
|
||||
frames: Vec<(Vec<u8>, u32)>,
|
||||
looping: image_webp::LoopCount,
|
||||
size: (u32, u32),
|
||||
alpha: bool,
|
||||
}
|
||||
|
||||
fn decode_webp(bytes: &[u8]) -> Webp {
|
||||
let mut dec = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
assert!(dec.is_animated());
|
||||
let (w, h) = dec.dimensions();
|
||||
let alpha = dec.has_alpha();
|
||||
let mut buf = vec![0u8; dec.output_buffer_size().unwrap()];
|
||||
let mut frames = Vec::new();
|
||||
for _ in 0..dec.num_frames() {
|
||||
let ms = dec.read_frame(&mut buf).unwrap();
|
||||
let rgba = if alpha { buf.clone() } else { buf.chunks(3).flat_map(|c| [c[0], c[1], c[2], 255]).collect() };
|
||||
frames.push((rgba, ms));
|
||||
}
|
||||
Webp { frames, looping: dec.loop_count(), size: (w, h), alpha }
|
||||
}
|
||||
|
||||
/// The frames a WebP shows, one per movie frame: the frame showing when each starts.
|
||||
fn webp_movie(frames: &[(Vec<u8>, u32)], n: u64, ratio: (u64, u64)) -> Vec<Vec<u8>> {
|
||||
let mut starts = Vec::new();
|
||||
let mut t = 0u64;
|
||||
for (_, ms) in frames {
|
||||
starts.push(t);
|
||||
t += u64::from(*ms);
|
||||
}
|
||||
assert_eq!(t, start_ms(n, ratio), "the running time is exact to the millisecond");
|
||||
(0..n).map(|f| {
|
||||
let at = start_ms(f, ratio);
|
||||
let i = starts.iter().rposition(|s| *s <= at).unwrap();
|
||||
frames[i].0.clone()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same(got: &[Vec<u8>], want: &[Vec<u8>], what: &str) {
|
||||
assert_eq!(got.len(), want.len(), "{what}: frame count");
|
||||
for (k, (g, w)) in got.iter().zip(want).enumerate() {
|
||||
assert!(g == w, "{what}: frame {} differs from the CPU renderer", k + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// A ball that holds still for 10 frames, jumps, and holds 6 more: 16 frames, 2 pictures.
|
||||
fn holds() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.ellipse", json!({"x": 40, "y": 40, "w": 60, "h": 60}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 10}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "element.translate", json!({"dx": 200, "dy": 30}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 15}));
|
||||
run(&mut s, "timeline.insert_frame", json!({}));
|
||||
assert_eq!(s.frame_count(), 16);
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_rates_are_exact_fractions() {
|
||||
assert_eq!(fps_ratio(24.0), (24, 1));
|
||||
assert_eq!(fps_ratio(29.97), (2997, 100));
|
||||
assert_eq!(fps_ratio(23.976), (2997, 125));
|
||||
assert_eq!(fps_ratio(12.5), (25, 2));
|
||||
assert_eq!(fps_ratio(f32::NAN), (24, 1));
|
||||
assert_eq!(fps_ratio(-3.0), (24, 1));
|
||||
// Millisecond starts round from the exact time, so the error never adds up.
|
||||
assert_eq!(start_ms(24, (24, 1)), 1000);
|
||||
assert_eq!(start_ms(1, (30, 1)), 33);
|
||||
assert_eq!(start_ms(2, (30, 1)), 67);
|
||||
assert_eq!(start_ms(2997, (2997, 100)), 100_000);
|
||||
assert_eq!(webp_durations(0, 3, (30, 1)), vec![100]);
|
||||
let total: u32 = (0..30).flat_map(|i| webp_durations(i, 1, (30, 1))).sum();
|
||||
assert_eq!(total, 1000);
|
||||
// APNG delays are fractions of the frame rate, reduced.
|
||||
assert_eq!(apng_delays(0, 1, (24, 1)), vec![(1, 24)]);
|
||||
assert_eq!(apng_delays(0, 6, (24, 1)), vec![(1, 4)]);
|
||||
assert_eq!(apng_delays(5, 2, (2997, 100)), vec![(200, 2997)]);
|
||||
// Longer than one fcTL holds: more pieces, adding up exactly.
|
||||
let long = apng_delays(0, 200_000, (2997, 100));
|
||||
assert!(long.len() > 1);
|
||||
let frames: u64 = long.iter().map(|&(n, d)| u64::from(n) * 2997 / (u64::from(d) * 100)).sum();
|
||||
assert_eq!(frames, 200_000);
|
||||
// A rate with a huge denominator falls back to milliseconds, still adding up.
|
||||
let odd = (100_003, 1000);
|
||||
let ms: u64 = apng_delays(0, 1000, odd).iter().map(|&(n, d)| {
|
||||
assert_eq!(d, 1000);
|
||||
u64::from(n)
|
||||
}).sum();
|
||||
assert_eq!(ms, start_ms(1000, odd));
|
||||
let hours = webp_durations(0, 100_000, (1, 1));
|
||||
assert_eq!(hours.iter().map(|&m| u64::from(m)).sum::<u64>(), 100_000_000);
|
||||
assert!(hours.iter().all(|&m| u64::from(m) <= MAX_WEBP_MS) && hours.len() > 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_changed_rectangle_is_tight() {
|
||||
let (w, h) = (8u32, 6u32);
|
||||
let a = vec![0u8; (w * h * 4) as usize];
|
||||
assert_eq!(changed(&a, &a, w, h), None);
|
||||
let mut b = a.clone();
|
||||
b[((2 * w + 3) * 4 + 1) as usize] = 9; // (3, 2)
|
||||
b[((4 * w + 6) * 4 + 3) as usize] = 9; // (6, 4)
|
||||
assert_eq!(changed(&a, &b, w, h), Some(Rect { x: 3, y: 2, w: 4, h: 3 }));
|
||||
// WebP regions start on even pixels; APNG's stay tight.
|
||||
let (r, over, px) = region(Kind::Webp, Some(&a), &b, w, h);
|
||||
assert_eq!((r, over, px.len()), (Rect { x: 2, y: 2, w: 5, h: 3 }, false, 5 * 3 * 4));
|
||||
let (r, over, _) = region(Kind::Apng, Some(&a), &b, w, h);
|
||||
assert_eq!((r, over), (Rect { x: 3, y: 2, w: 4, h: 3 }, false), "semi-transparent changes replace");
|
||||
let mut c = a.clone();
|
||||
c[((2 * w + 3) * 4) as usize..((2 * w + 3) * 4 + 4) as usize].copy_from_slice(&[1, 2, 3, 255]);
|
||||
let (r, over, px) = region(Kind::Apng, Some(&a), &c, w, h);
|
||||
assert_eq!((r, over, px), (Rect { x: 3, y: 2, w: 1, h: 1 }, true, vec![1, 2, 3, 255]), "opaque changes blend over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apng_frames_match_the_renderer_exactly() {
|
||||
let dir = tmp("apng");
|
||||
let mut s = Session::new(sample::demo());
|
||||
for background in [false, true] {
|
||||
let path = dir.join(format!("walk-{background}.png"));
|
||||
let v = run(&mut s, "file.export_apng", json!({"path": path.display().to_string(), "scale": 0.25, "to": 23, "background": background}));
|
||||
assert_eq!(v["frames"], 24);
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert_eq!(v["bytes"], bytes.len());
|
||||
let a = decode_apng(&bytes);
|
||||
assert_eq!(a.plays, 0, "loops forever by default");
|
||||
let want = renders(&s.doc, 0, 23, 0.25, background);
|
||||
assert_eq!(a.size, (320, 180));
|
||||
same(&apng_movie(&a, fps_ratio(s.doc.stage.fps)), &want, "APNG");
|
||||
// Frames after the first cover only what changed.
|
||||
assert!(a.frames.iter().skip(1).any(|f| f.rect.w * f.rect.h < 320 * 180), "dirty rectangles");
|
||||
if background {
|
||||
assert!(a.frames.iter().skip(1).all(|f| f.over), "opaque frames blend over");
|
||||
}
|
||||
// The default image is the first frame, and a plain PNG reader sees it.
|
||||
let first = png::Decoder::new(std::io::Cursor::new(&bytes)).read_info().unwrap().info().frame_control.unwrap();
|
||||
assert_eq!((first.width, first.height, first.x_offset, first.y_offset), (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, looping, size, alpha } = decode_webp(&bytes);
|
||||
assert_eq!((size, alpha), ((320, 180), !background));
|
||||
assert_eq!(looping, image_webp::LoopCount::Forever);
|
||||
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, looping, .. } = decode_webp(&std::fs::read(&webp).unwrap());
|
||||
assert_eq!(frames.len(), 2);
|
||||
assert_eq!(looping, image_webp::LoopCount::Times(std::num::NonZeroU16::new(1).unwrap()));
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
//! 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, 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,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in presets: `(key, name)`, in the order the library shows them.
|
||||
pub const BUILTIN: [(&str, &str); 7] = [
|
||||
("pencil", "Pencil"),
|
||||
("ink_pen", "Ink Pen"),
|
||||
("calligraphy", "Flat Calligraphy"),
|
||||
("round_taper", "Round Taper"),
|
||||
("marker", "Marker"),
|
||||
("chalk", "Chalk"),
|
||||
("dotted", "Dotted"),
|
||||
];
|
||||
|
||||
/// 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.",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// A built-in preset by key.
|
||||
pub fn builtin(key: &str) -> Option<BrushPreset> {
|
||||
let (_, name) = BUILTIN.iter().find(|(k, _)| *k == key)?;
|
||||
let d = BrushPreset { name: (*name).to_string(), ..BrushPreset::default() };
|
||||
Some(match key {
|
||||
"pencil" => BrushPreset { size: 3.0, smoothing: 30.0, curve: PressureCurve::FIRM, taper_start: 5.0, taper_end: 5.0, ..d },
|
||||
"ink_pen" => BrushPreset { size: 6.0, smoothing: 60.0, curve: PressureCurve::SOFT, taper_start: 12.0, taper_end: 18.0, ..d },
|
||||
"calligraphy" => BrushPreset { size: 18.0, angle: 45.0, roundness: 15.0, smoothing: 50.0, ..d },
|
||||
"round_taper" => BrushPreset { size: 14.0, smoothing: 55.0, taper_start: 35.0, taper_end: 35.0, ..d },
|
||||
"marker" => BrushPreset { size: 16.0, shape: Shape::Square, angle: 30.0, roundness: 45.0, smoothing: 40.0, pressure_size: false, ..d },
|
||||
"chalk" => BrushPreset { size: 20.0, roundness: 80.0, angle: 20.0, smoothing: 40.0, jitter: 18.0, ..d },
|
||||
"dotted" => BrushPreset { size: 8.0, smoothing: 60.0, pressure_size: false, spacing: 220.0, ..d },
|
||||
_ => 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
|
||||
}
|
||||
|
||||
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 }.sanitized()
|
||||
}
|
||||
|
||||
/// The tip's size factor input at a measured pressure: the curve's output when pressure
|
||||
/// drives the size, else full.
|
||||
pub fn size_pressure(&self, pressure: f32) -> f32 {
|
||||
if self.pressure_size { self.curve.map(pressure) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// The settings without the name, as command params (what `draw.brush` takes).
|
||||
pub fn params(&self) -> Value {
|
||||
let mut v = serde_json::to_value(self).unwrap_or_default();
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.remove("name");
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// This preset with any settings `p` gives instead (the params of `draw.brush` and
|
||||
/// `brush.preset_save`). Refuses values out of range.
|
||||
pub fn with_params(&self, p: &Value) -> Result<BrushPreset> {
|
||||
let mut b = self.clone();
|
||||
let r = crate::cmds_brush::ranged;
|
||||
b.size = r(p, "size", crate::cmds_brush::SIZE_RANGE, b.size)?;
|
||||
b.shape = match opt_str(p, "shape")? {
|
||||
None => b.shape,
|
||||
Some("round") => Shape::Round,
|
||||
Some("square") => Shape::Square,
|
||||
Some(other) => return Err(EngineError::Param(format!("unknown tip shape '{other}' (round or square)"))),
|
||||
};
|
||||
if let Some(a) = opt_f32(p, "angle")? {
|
||||
if !a.is_finite() || a.abs() > 1e6 {
|
||||
return Err(EngineError::Param("param 'angle' must be a finite number of degrees".into()));
|
||||
}
|
||||
b.angle = a;
|
||||
}
|
||||
b.roundness = r(p, "roundness", 5.0..=100.0, b.roundness)?;
|
||||
b.smoothing = r(p, "smoothing", 0.0..=100.0, b.smoothing)?;
|
||||
if let Some(c) = curve_param(p, "curve")? {
|
||||
b.curve = c;
|
||||
}
|
||||
b.pressure_size = opt_bool(p, "pressure_size")?.unwrap_or(b.pressure_size);
|
||||
b.pressure_opacity = opt_bool(p, "pressure_opacity")?.unwrap_or(b.pressure_opacity);
|
||||
b.taper_start = r(p, "taper_start", 0.0..=50.0, b.taper_start)?;
|
||||
b.taper_end = r(p, "taper_end", 0.0..=50.0, b.taper_end)?;
|
||||
b.spacing = r(p, "spacing", 0.0..=1000.0, b.spacing)?;
|
||||
if b.spacing > 0.0 && b.spacing < 5.0 {
|
||||
return Err(EngineError::Param("param 'spacing' must be 0 (a continuous stroke) or from 5 to 1000 %".into()));
|
||||
}
|
||||
b.jitter = r(p, "jitter", 0.0..=50.0, b.jitter)?;
|
||||
Ok(b)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `curve` param: a preset name (`linear`, `soft`, `firm`) or `[[pressure, output], ..]`
|
||||
/// (both 0..1).
|
||||
pub fn curve_param(p: &Value, key: &str) -> Result<Option<PressureCurve>> {
|
||||
let bad = || EngineError::Param(format!("param '{key}' must be linear, soft, firm or a list of [pressure, output] pairs from 0 to 1"));
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(k)) => PressureCurve::preset(k).map(Some).ok_or_else(bad),
|
||||
Some(Value::Array(list)) => {
|
||||
if list.is_empty() || list.len() > 64 {
|
||||
return Err(bad());
|
||||
}
|
||||
let pts = list
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let xy = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?;
|
||||
let n = |i: usize| xy.get(i).and_then(Value::as_f64).map(|f| f as f32).filter(|f| f.is_finite() && (-1e-3..=1.001).contains(f)).ok_or_else(bad);
|
||||
Ok([n(0)?, n(1)?])
|
||||
})
|
||||
.collect::<Result<Vec<[f32; 2]>>>()?;
|
||||
Ok(Some(PressureCurve::new(&pts)))
|
||||
}
|
||||
Some(_) => Err(bad()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A name as kept: trimmed, one line, at most [`MAX_NAME`] characters; `None` when empty.
|
||||
pub fn clean_name(s: &str) -> Option<String> {
|
||||
let one: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
let t: String = one.trim().chars().take(MAX_NAME).collect();
|
||||
let t = t.trim().to_string();
|
||||
(!t.is_empty()).then_some(t)
|
||||
}
|
||||
|
||||
/// Whether two names are the same preset (case doesn't matter).
|
||||
fn same_name(a: &str, b: &str) -> bool {
|
||||
a.trim().to_lowercase() == b.trim().to_lowercase()
|
||||
}
|
||||
|
||||
/// Whether `name` is a built-in preset's (by key or by name).
|
||||
pub fn is_builtin_name(name: &str) -> bool {
|
||||
BUILTIN.iter().any(|(k, n)| same_name(k, name) || same_name(n, name))
|
||||
}
|
||||
|
||||
/// The user's own presets, in the order they were saved.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct BrushLibrary {
|
||||
user: Vec<BrushPreset>,
|
||||
}
|
||||
|
||||
/// A brush set file.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct BrushFile {
|
||||
format: String,
|
||||
version: u32,
|
||||
brushes: Vec<Value>,
|
||||
}
|
||||
|
||||
impl BrushLibrary {
|
||||
pub fn user(&self) -> &[BrushPreset] {
|
||||
&self.user
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.user.is_empty()
|
||||
}
|
||||
|
||||
/// A library from untrusted entries (preferences, a file): bad entries and names skipped,
|
||||
/// values clamped, names made unique, at most [`MAX_USER_PRESETS`].
|
||||
pub fn from_values(values: impl IntoIterator<Item = Value>) -> BrushLibrary {
|
||||
let mut lib = BrushLibrary::default();
|
||||
for v in values.into_iter().take(MAX_USER_PRESETS * 4) {
|
||||
if let Ok(p) = serde_json::from_value::<BrushPreset>(v) {
|
||||
let _ = lib.add_unique(p);
|
||||
}
|
||||
}
|
||||
lib
|
||||
}
|
||||
|
||||
/// The same library with every entry sanitized (after deserializing preferences).
|
||||
pub fn sanitized(self) -> BrushLibrary {
|
||||
BrushLibrary::from_values(self.user.into_iter().filter_map(|p| serde_json::to_value(p).ok()))
|
||||
}
|
||||
|
||||
/// A preset by built-in key, built-in name or the user's name (case doesn't matter; the
|
||||
/// user's own win only where no built-in has the name, which saving refuses anyway).
|
||||
pub fn find(&self, name: &str) -> Option<BrushPreset> {
|
||||
if let Some((k, _)) = BUILTIN.iter().find(|(k, n)| *k == name || same_name(n, name)) {
|
||||
return builtin(k);
|
||||
}
|
||||
self.user.iter().find(|p| same_name(&p.name, name)).cloned()
|
||||
}
|
||||
|
||||
pub fn position(&self, name: &str) -> Option<usize> {
|
||||
self.user.iter().position(|p| same_name(&p.name, name))
|
||||
}
|
||||
|
||||
/// Saves `p` under its name, replacing the user's preset of that name. Returns whether it
|
||||
/// replaced one.
|
||||
pub fn save(&mut self, p: BrushPreset) -> Result<bool> {
|
||||
let p = p.sanitized();
|
||||
let name = clean_name(&p.name).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?;
|
||||
if is_builtin_name(&name) {
|
||||
return Err(EngineError::Param(format!("'{name}' is a built-in brush; save yours under another name")));
|
||||
}
|
||||
let p = BrushPreset { name, ..p };
|
||||
if let Some(i) = self.position(&p.name)
|
||||
&& let Some(slot) = self.user.get_mut(i)
|
||||
{
|
||||
*slot = p;
|
||||
return Ok(true);
|
||||
}
|
||||
if self.user.len() >= MAX_USER_PRESETS {
|
||||
return Err(EngineError::State(format!("you have {MAX_USER_PRESETS} brushes already; delete some first")));
|
||||
}
|
||||
self.user.push(p);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Adds `p`, renaming it ("Ink 2", "Ink 3", ..) if the name is taken. Returns its name.
|
||||
pub fn add_unique(&mut self, p: BrushPreset) -> Result<String> {
|
||||
let p = p.sanitized();
|
||||
let base = clean_name(&p.name).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?;
|
||||
let taken = |lib: &BrushLibrary, n: &str| is_builtin_name(n) || lib.position(n).is_some();
|
||||
let mut name = base.clone();
|
||||
let mut k = 2;
|
||||
while taken(self, &name) {
|
||||
if k > MAX_USER_PRESETS + 10 {
|
||||
return Err(EngineError::State("too many brushes of that name".into()));
|
||||
}
|
||||
let suffix = format!(" {k}");
|
||||
name = format!("{}{suffix}", base.chars().take(MAX_NAME.saturating_sub(suffix.chars().count())).collect::<String>().trim_end());
|
||||
k += 1;
|
||||
}
|
||||
if self.user.len() >= MAX_USER_PRESETS {
|
||||
return Err(EngineError::State(format!("you have {MAX_USER_PRESETS} brushes already; delete some first")));
|
||||
}
|
||||
self.user.push(BrushPreset { name: name.clone(), ..p });
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
pub fn rename(&mut self, name: &str, to: &str) -> Result<String> {
|
||||
let i = self.position(name).ok_or_else(|| EngineError::Param(format!("you have no brush named '{name}'")))?;
|
||||
let to = clean_name(to).ok_or_else(|| EngineError::Param("a brush needs a name".into()))?;
|
||||
if is_builtin_name(&to) {
|
||||
return Err(EngineError::Param(format!("'{to}' is a built-in brush's name")));
|
||||
}
|
||||
if self.position(&to).is_some_and(|j| j != i) {
|
||||
return Err(EngineError::Param(format!("you already have a brush named '{to}'")));
|
||||
}
|
||||
if let Some(p) = self.user.get_mut(i) {
|
||||
p.name = to.clone();
|
||||
}
|
||||
Ok(to)
|
||||
}
|
||||
|
||||
pub fn delete(&mut self, name: &str) -> Result<BrushPreset> {
|
||||
let i = self.position(name).ok_or_else(|| EngineError::Param(format!("you have no brush named '{name}'")))?;
|
||||
Ok(self.user.remove(i))
|
||||
}
|
||||
|
||||
/// A brush set file holding `presets`.
|
||||
pub fn file_json(presets: &[BrushPreset]) -> String {
|
||||
let f = BrushFile { format: FILE_FORMAT.into(), version: FILE_VERSION, brushes: presets.iter().filter_map(|p| serde_json::to_value(p).ok()).collect() };
|
||||
serde_json::to_string_pretty(&f).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The presets in a brush set file (bad entries skipped; values clamped).
|
||||
pub fn parse_file(text: &str) -> Result<Vec<BrushPreset>> {
|
||||
let f: BrushFile = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("not a brush set file: {e}")))?;
|
||||
if f.format != FILE_FORMAT {
|
||||
return Err(EngineError::Param(format!("not a brush set file (its format is '{}')", f.format.chars().take(40).collect::<String>())));
|
||||
}
|
||||
if f.version > FILE_VERSION {
|
||||
return Err(EngineError::Param(format!("this brush set is version {}, newer than this AniCraft reads ({FILE_VERSION})", f.version)));
|
||||
}
|
||||
Ok(f.brushes.into_iter().take(MAX_USER_PRESETS * 4).filter_map(|v| serde_json::from_value::<BrushPreset>(v).ok()).map(BrushPreset::sanitized).filter(|p| !p.name.is_empty()).collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn builtins_are_named_and_in_range() {
|
||||
for (key, name) in BUILTIN {
|
||||
let p = builtin(key).unwrap();
|
||||
assert_eq!(p.name, name);
|
||||
assert_eq!(p.clone().sanitized(), p, "{key} is already in range");
|
||||
assert!(!builtin_hint(key).is_empty());
|
||||
}
|
||||
assert_eq!(BrushPreset::default().shaping(), Shaping::default(), "the plain brush shapes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_renaming_and_deleting() {
|
||||
let mut lib = BrushLibrary::default();
|
||||
assert!(!lib.save(BrushPreset { name: " My ink \n".into(), size: 1e9, ..BrushPreset::default() }).unwrap());
|
||||
assert_eq!(lib.user()[0].name, "My ink");
|
||||
assert_eq!(lib.user()[0].size, 2000.0, "clamped");
|
||||
assert!(lib.save(BrushPreset { name: "my INK".into(), size: 4.0, ..BrushPreset::default() }).unwrap(), "same name replaces");
|
||||
assert_eq!(lib.user().len(), 1);
|
||||
assert!(lib.save(BrushPreset { name: "Chalk".into(), ..BrushPreset::default() }).is_err(), "a built-in's name");
|
||||
assert!(lib.save(BrushPreset { name: " ".into(), ..BrushPreset::default() }).is_err());
|
||||
assert_eq!(lib.add_unique(BrushPreset { name: "My ink".into(), ..BrushPreset::default() }).unwrap(), "My ink 2");
|
||||
assert_eq!(lib.add_unique(BrushPreset { name: "chalk".into(), ..BrushPreset::default() }).unwrap(), "chalk 2");
|
||||
assert_eq!(lib.rename("my ink 2", "Wet").unwrap(), "Wet");
|
||||
assert!(lib.rename("Wet", "My Ink").is_err() && lib.rename("Wet", "Marker").is_err() && lib.rename("nope", "x").is_err());
|
||||
assert_eq!(lib.find("wet").map(|p| p.name), Some("Wet".into()));
|
||||
assert_eq!(lib.find("ink_pen").map(|p| p.name), Some("Ink Pen".into()));
|
||||
assert_eq!(lib.find("ink pen").map(|p| p.size), Some(6.0));
|
||||
assert_eq!(lib.delete("WET").unwrap().name, "Wet");
|
||||
assert!(lib.delete("Wet").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_set_files_round_trip_and_reject_junk() {
|
||||
let mine = vec![BrushPreset { name: "A".into(), curve: PressureCurve::SOFT, jitter: 12.0, ..BrushPreset::default() }, builtin("dotted").unwrap()];
|
||||
let text = BrushLibrary::file_json(&mine);
|
||||
assert_eq!(BrushLibrary::parse_file(&text).unwrap(), mine);
|
||||
assert!(BrushLibrary::parse_file("{}").is_err());
|
||||
assert!(BrushLibrary::parse_file(r#"{"format": "other", "version": 1, "brushes": []}"#).is_err());
|
||||
assert!(BrushLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 99, "brushes": []}"#).is_err());
|
||||
// Bad entries are skipped, out-of-range values clamped, older files without the newer
|
||||
// fields read with defaults.
|
||||
let got = BrushLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 1, "brushes": [7, {"name": ""}, {"name": "Old", "size": -4, "spacing": 2, "curve": [[0.5, 9]]}]}"#).unwrap();
|
||||
assert_eq!(got.len(), 1);
|
||||
assert_eq!((got[0].size, got[0].spacing, got[0].smoothing), (0.1, 5.0, 50.0));
|
||||
assert_eq!(got[0].curve.points(), &[[0.0, 1.0], [0.5, 1.0], [1.0, 1.0]]);
|
||||
// Preferences: the library as a list.
|
||||
let lib = BrushLibrary::from_values(serde_json::from_str::<Vec<Value>>(&serde_json::to_string(&mine).unwrap()).unwrap());
|
||||
assert_eq!(lib.user().len(), 2);
|
||||
assert_eq!(lib.user()[1].name, "Dotted 2", "a built-in's name is renamed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_override_a_preset() {
|
||||
let p = builtin("calligraphy").unwrap();
|
||||
let q = p.with_params(&serde_json::json!({"size": 30, "curve": "firm", "taper_end": 20})).unwrap();
|
||||
assert_eq!((q.size, q.curve, q.taper_end, q.roundness), (30.0, PressureCurve::FIRM, 20.0, 15.0));
|
||||
let q = p.with_params(&serde_json::json!({"curve": [[0, 0.2], [1, 0.8]]})).unwrap();
|
||||
assert_eq!(q.curve.map(0.0), 0.2);
|
||||
for bad in [serde_json::json!({"curve": "wobbly"}), serde_json::json!({"curve": [[0, 2]]}), serde_json::json!({"curve": []}), serde_json::json!({"spacing": 2}), serde_json::json!({"jitter": 60}), serde_json::json!({"shape": "star"})] {
|
||||
assert!(p.with_params(&bad).is_err(), "{bad}");
|
||||
}
|
||||
// The params name every setting and read back as the same preset.
|
||||
let back = BrushPreset::default().with_params(&p.params()).unwrap();
|
||||
assert_eq!(BrushPreset { name: p.name.clone(), ..back }, p);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! The brush library, pressure curves and the Paint Brush (ADR 0068).
|
||||
|
||||
use crate::Session;
|
||||
use crate::brush_library::BUILTIN;
|
||||
use anicraft_doc::{ElementKind, Shape};
|
||||
use anicraft_geom::Affine;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn blank() -> Session {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.object_drawing", json!({"on": true}));
|
||||
s
|
||||
}
|
||||
|
||||
fn shapes(s: &Session) -> Vec<Shape> {
|
||||
s.visible_elements()
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => Some(sh.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn area(sh: &Shape) -> f32 {
|
||||
sh.path
|
||||
.flatten(&Affine::IDENTITY, 0.01)
|
||||
.iter()
|
||||
.map(|pl| {
|
||||
let n = pl.points.len();
|
||||
((0..n).map(|i| pl.points[i].cross(pl.points[(i + 1) % n])).sum::<f32>() * 0.5).abs()
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// A 400-unit wave with the pressure swelling from 0.3 to 1 and back.
|
||||
fn wave() -> Vec<[f32; 3]> {
|
||||
(0..=80)
|
||||
.map(|i| {
|
||||
let t = i as f32 / 80.0;
|
||||
[100.0 + 400.0 * t, 200.0 + 30.0 * (t * std::f32::consts::TAU).sin(), 0.3 + 0.7 * (t * std::f32::consts::PI).sin()]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The wave's length (polyline).
|
||||
fn wave_length() -> f32 {
|
||||
wave().windows(2).map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt()).sum()
|
||||
}
|
||||
|
||||
fn painted(preset: &str, extra: Value) -> (Shape, Value) {
|
||||
let mut s = blank();
|
||||
let mut p = json!({"points": wave(), "preset": preset, "color": "#203040"});
|
||||
if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) {
|
||||
o.extend(e.clone());
|
||||
}
|
||||
let r = run(&mut s, "draw.brush", p);
|
||||
let all = shapes(&s);
|
||||
assert_eq!(all.len(), 1, "{preset}: one shape");
|
||||
(all[0].clone(), r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preset_paints_within_its_area_bounds() {
|
||||
let len = wave_length();
|
||||
// (key, least, most) area as a part of length × size: what each preset's settings allow.
|
||||
let bounds = [
|
||||
("pencil", 0.4, 0.65), // a firm curve thins the light parts; short tapers
|
||||
("ink_pen", 0.7, 0.9), // a soft curve keeps it wide; tapered ends
|
||||
("calligraphy", 0.45, 0.7), // a 15 % flat nib: thick and thin by direction
|
||||
("round_taper", 0.55, 0.75), // swells from a point and back
|
||||
("marker", 0.75, 0.95), // a square chisel at 45 %, no pressure
|
||||
("chalk", 0.35, 0.55), // its edge worn in
|
||||
// Dots 2.2 sizes apart, each a quarter π of size²: π / 8.8 = 0.357 of length × size.
|
||||
("dotted", 0.33, 0.38),
|
||||
];
|
||||
assert_eq!(bounds.len(), BUILTIN.len(), "every built-in has bounds");
|
||||
for (key, lo, hi) in bounds {
|
||||
let b = crate::brush_library::builtin(key).unwrap();
|
||||
let (sh, _) = painted(key, json!({}));
|
||||
let a = area(&sh) / (len * b.size);
|
||||
assert!((lo..=hi).contains(&a), "{key}: {a:.3} of length × size, want {lo}..{hi}");
|
||||
assert!(sh.stroke.is_none() && sh.fill.is_some(), "{key} paints a fill");
|
||||
}
|
||||
// Dots are separate loops; chalk's edge is ragged (many more anchors than a plain stroke).
|
||||
let (dots, _) = painted("dotted", json!({}));
|
||||
let loops = dots.path.cmds.iter().filter(|c| matches!(c, anicraft_geom::PathCmd::MoveTo(_))).count();
|
||||
let want = (wave_length() / (8.0 * 2.2)).floor() as usize + 1;
|
||||
assert!(loops.abs_diff(want) <= 2, "{loops} dots, about {want}");
|
||||
let (chalk, _) = painted("chalk", json!({}));
|
||||
let (plain, _) = painted("chalk", json!({"jitter": 0}));
|
||||
assert!(chalk.path.anchors().len() > 2 * plain.path.anchors().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_points_and_settings_give_identical_outlines() {
|
||||
for (key, _) in BUILTIN {
|
||||
for as_stroke in [false, true] {
|
||||
let (a, _) = painted(key, json!({"as_stroke": as_stroke}));
|
||||
let (b, _) = painted(key, json!({"as_stroke": as_stroke}));
|
||||
assert_eq!(a.path, b.path, "{key} as_stroke {as_stroke}");
|
||||
assert_eq!(a.stroke, b.stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressure_curves_map_before_the_size() {
|
||||
// A steady half pressure: soft paints wider than linear, firm narrower.
|
||||
let pts: Vec<[f32; 3]> = (0..=40).map(|i| [100.0 + i as f32 * 10.0, 100.0, 0.5]).collect();
|
||||
let area_with = |curve: Value| {
|
||||
let mut s = blank();
|
||||
run(&mut s, "draw.brush", json!({"points": pts, "size": 20, "curve": curve}));
|
||||
area(&shapes(&s)[0])
|
||||
};
|
||||
let (lin, soft, firm) = (area_with(json!("linear")), area_with(json!("soft")), area_with(json!("firm")));
|
||||
// Linear: factor 0.1 + 0.9 × 0.5 = 0.55 of 20 across 400.
|
||||
assert!((lin - 400.0 * 11.0).abs() / (400.0 * 11.0) < 0.06, "{lin}");
|
||||
assert!(soft > lin * 1.15 && firm < lin * 0.85, "{soft} {lin} {firm}");
|
||||
// A curve of points: flat at 1 paints full size at any pressure.
|
||||
let full = area_with(json!([[0, 1], [1, 1]]));
|
||||
assert!((full - 400.0 * 20.0).abs() / (400.0 * 20.0) < 0.06, "{full}");
|
||||
// Pressure off: full size too.
|
||||
let mut s = blank();
|
||||
run(&mut s, "draw.brush", json!({"points": pts, "size": 20, "pressure_size": false}));
|
||||
assert!((area(&shapes(&s)[0]) - full).abs() < full * 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressure_can_set_the_opacity() {
|
||||
let pts: Vec<[f32; 3]> = (0..=10).map(|i| [i as f32 * 10.0, 50.0, 0.4]).collect();
|
||||
let mut s = blank();
|
||||
run(&mut s, "draw.brush", json!({"points": pts, "pressure_opacity": true, "color": "#ff0000"}));
|
||||
let Some(anicraft_doc::Paint::Solid(c)) = shapes(&s)[0].fill else { panic!("solid") };
|
||||
assert!((c.a - 0.4).abs() < 1e-3, "{}", c.a);
|
||||
// A mouse (no pressure) paints opaque.
|
||||
run(&mut s, "draw.brush", json!({"points": [[0, 100], [100, 100]], "pressure_opacity": true}));
|
||||
let Some(anicraft_doc::Paint::Solid(c)) = shapes(&s)[1].fill else { panic!("solid") };
|
||||
assert_eq!(c.a, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_paint_brush_draws_a_width_profiled_stroke() {
|
||||
let mut s = blank();
|
||||
s.style.stroke = anicraft_doc::Rgba::hex(0x123456);
|
||||
let r = run(&mut s, "draw.brush", json!({"points": wave(), "size": 16, "as_stroke": true, "taper_end": 30}));
|
||||
assert_eq!(r["kind"], "paint_brush");
|
||||
let sh = &shapes(&s)[0];
|
||||
assert!(sh.fill.is_none(), "a line, not a fill");
|
||||
let st = sh.stroke.as_ref().unwrap();
|
||||
assert_eq!((st.width, st.color), (16.0, anicraft_doc::Rgba::hex(0x123456)), "the brush's size in the stroke colour");
|
||||
let prof = st.profile.as_ref().expect("pressure and a taper make a profile");
|
||||
let n = prof.points().len();
|
||||
assert!((3..=anicraft_doc::MAX_WIDTH_POINTS).contains(&n), "{n} width points");
|
||||
assert_eq!(r["width_points"], n);
|
||||
// Thin at the light start, full in the middle, tapered to a point at the end.
|
||||
let (l0, _) = prof.at(0.0);
|
||||
let (lm, rm) = prof.at(0.5);
|
||||
let (l1, _) = prof.at(1.0);
|
||||
assert!(l0 < 0.5 && lm > 0.9 && (lm - rm).abs() < 1e-6 && l1 < 0.1, "{l0} {lm} {l1}");
|
||||
// The Width tool edits it afterwards.
|
||||
let id = r["element"].as_u64().unwrap();
|
||||
run(&mut s, "stroke.set_width_point", json!({"id": id, "t": 0.5, "left": 3, "right": 3}));
|
||||
let sh = &shapes(&s)[0];
|
||||
assert!(sh.stroke.as_ref().and_then(|st| st.profile.as_ref()).is_some_and(|p| p.at(0.5).0 > 2.9));
|
||||
// A mouse stroke with no taper is a plain line of one width (it merges off Object Drawing).
|
||||
let mut s = blank();
|
||||
run(&mut s, "draw.object_drawing", json!({"on": false}));
|
||||
let r = run(&mut s, "draw.brush", json!({"points": [[0, 0], [50, 10], [100, 0]], "as_stroke": true}));
|
||||
assert_eq!(r["merged"], true);
|
||||
assert!(shapes(&s).iter().all(|sh| sh.stroke.as_ref().is_none_or(|st| st.profile.is_none())));
|
||||
// One point is no line.
|
||||
assert!(blank().execute("draw.brush", &json!({"points": [[5, 5]], "as_stroke": true})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_brushes_are_saved_listed_renamed_and_deleted() {
|
||||
let mut s = blank();
|
||||
let v = run(&mut s, "brush.preset_list", json!({}));
|
||||
assert_eq!(v["presets"].as_array().map(Vec::len), Some(BUILTIN.len()));
|
||||
assert_eq!(v["presets"][0]["key"], "pencil");
|
||||
let v = run(&mut s, "brush.preset_save", json!({"name": "Wet Ink", "from": "ink_pen", "size": 9, "curve": [[0, 0], [0.5, 0.8], [1, 1]]}));
|
||||
assert_eq!((v["name"].as_str(), v["replaced"].as_bool()), (Some("Wet Ink"), Some(false)));
|
||||
let list = run(&mut s, "brush.preset_list", json!({}));
|
||||
let mine = &list["presets"][BUILTIN.len()];
|
||||
assert_eq!((mine["name"].as_str(), mine["builtin"].as_bool(), mine["size"].as_f64(), mine["taper_end"].as_f64()), (Some("Wet Ink"), Some(false), Some(9.0), Some(18.0)), "from the ink pen, size changed");
|
||||
// Painting with it by name equals painting with its settings.
|
||||
run(&mut s, "draw.brush", json!({"points": wave(), "preset": "wet ink"}));
|
||||
let mut t = blank();
|
||||
run(&mut t, "draw.brush", json!({"points": wave(), "preset": "ink_pen", "size": 9, "curve": [[0, 0], [0.5, 0.8], [1, 1]]}));
|
||||
assert_eq!(shapes(&s)[0].path, shapes(&t)[0].path);
|
||||
assert!(s.execute("draw.brush", &json!({"points": wave(), "preset": "nope"})).is_err());
|
||||
// Brushes aren't the document's: saving and renaming leave it as it is.
|
||||
let doc = s.doc.clone();
|
||||
run(&mut s, "brush.preset_rename", json!({"name": "Wet Ink", "to": "Dry Ink"}));
|
||||
run(&mut s, "brush.preset_save", json!({"name": "Spare"}));
|
||||
run(&mut s, "brush.preset_delete", json!({"name": "Spare", "confirm": true}));
|
||||
assert!(s.doc == doc);
|
||||
assert!(s.execute("brush.preset_save", &json!({"name": "Marker"})).is_err(), "built-in names are taken");
|
||||
// Deleting can't be undone, so it asks first.
|
||||
assert!(s.confirmation("brush.preset_delete", &json!({"name": "dry ink"})).is_some_and(|c| c.irreversible));
|
||||
assert!(s.confirmation("brush.preset_delete", &json!({"name": "nope"})).is_none());
|
||||
assert!(s.execute("brush.preset_delete", &json!({"name": "Dry Ink"})).is_err(), "needs confirm");
|
||||
run(&mut s, "brush.preset_delete", json!({"name": "Dry Ink", "confirm": true}));
|
||||
assert!(s.brushes.is_empty());
|
||||
// They survive New and Open.
|
||||
run(&mut s, "brush.preset_save", json!({"name": "Keep"}));
|
||||
s.replace_document(anicraft_doc::Document::default(), None);
|
||||
assert_eq!(s.brushes.user().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_sets_export_and_import_as_json() {
|
||||
crate::vfs::use_memory();
|
||||
let mut s = blank();
|
||||
assert!(s.execute("brush.preset_export", &json!({"path": "none.json"})).is_err(), "nothing of yours yet");
|
||||
run(&mut s, "brush.preset_save", json!({"name": "Grit", "from": "chalk", "jitter": 30}));
|
||||
run(&mut s, "brush.preset_save", json!({"name": "Dots", "from": "dotted", "spacing": 150}));
|
||||
let v = run(&mut s, "brush.preset_export", json!({"path": "set.json"}));
|
||||
assert_eq!(v["brushes"], 2);
|
||||
let text = crate::vfs::read_to_string(std::path::Path::new("set.json")).unwrap();
|
||||
assert!(text.contains("\"format\": \"anicraft-brushes\"") && text.contains("\"Grit\""));
|
||||
// Exporting over the file asks first.
|
||||
assert!(s.confirmation("brush.preset_export", &json!({"path": "set.json"})).is_some_and(|c| c.irreversible));
|
||||
// Another computer: the set comes in whole; names already there get a number.
|
||||
let mut t = blank();
|
||||
run(&mut t, "brush.preset_save", json!({"name": "Grit"}));
|
||||
let v = run(&mut t, "brush.preset_import", json!({"path": "set.json"}));
|
||||
assert_eq!(v["imported"], json!(["Grit 2", "Dots"]));
|
||||
assert_eq!(t.brushes.find("Grit 2").map(|b| b.jitter), Some(30.0));
|
||||
// Built-ins can be exported by name too.
|
||||
let v = run(&mut s, "brush.preset_export", json!({"path": "two.json", "names": ["chalk", "Dots"], "confirm": true}));
|
||||
assert_eq!(v["brushes"], 2);
|
||||
// Junk is refused.
|
||||
crate::vfs::put(std::path::Path::new("junk.json"), b"{\"format\": 3}".to_vec()).unwrap();
|
||||
for bad in [json!({"path": "junk.json"}), json!({"path": "missing.json"}), json!({})] {
|
||||
assert!(t.execute("brush.preset_import", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plug_ins_may_list_brushes_but_not_change_them() {
|
||||
use crate::cmds_plugin::plugin_may_call;
|
||||
assert!(plugin_may_call("brush.preset_list").is_ok());
|
||||
for id in ["brush.preset_save", "brush.preset_rename", "brush.preset_delete", "brush.preset_export", "brush.preset_import"] {
|
||||
assert!(plugin_may_call(id).is_err(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_are_drawn_by_the_renderer() {
|
||||
for (key, _) in BUILTIN {
|
||||
let b = crate::brush_library::builtin(key).unwrap();
|
||||
for as_stroke in [false, true] {
|
||||
let px = crate::cmds_brush::preview(&b, as_stroke, 160, 48, 2.0, anicraft_doc::Rgba::hex(0x000000)).unwrap();
|
||||
let rgba = px.to_premul_rgba8();
|
||||
let inked = rgba.chunks(4).filter(|p| p[3] > 128).count();
|
||||
assert!(inked > 60, "{key} as_stroke {as_stroke}: {inked} pixels");
|
||||
assert!(rgba.chunks(4).filter(|p| p[3] == 0).count() > inked, "{key}: mostly transparent");
|
||||
}
|
||||
}
|
||||
assert!(crate::cmds_brush::preview(&crate::brush_library::BrushPreset::default(), false, 2, 2, 1.0, anicraft_doc::Rgba::hex(0)).is_err());
|
||||
}
|
||||
|
||||
/// Measured numbers for ADR 0068: `cargo test --release -p anicraft-engine preset_timings -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn preset_timings() {
|
||||
for (key, _) in BUILTIN {
|
||||
for as_stroke in [false, true] {
|
||||
let mut ms: Vec<f64> = (0..15)
|
||||
.map(|_| {
|
||||
let mut s = blank();
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "draw.brush", json!({"points": wave(), "preset": key, "as_stroke": as_stroke}));
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
})
|
||||
.collect();
|
||||
ms.sort_by(f64::total_cmp);
|
||||
let (sh, _) = painted(key, json!({"as_stroke": as_stroke}));
|
||||
eprintln!("{key:12} stroke {as_stroke:5}: median {:6.2} ms, {} anchors", ms[7], sh.path.anchors().len());
|
||||
}
|
||||
}
|
||||
let b = crate::brush_library::builtin("chalk").unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..10 {
|
||||
crate::cmds_brush::preview(&b, false, 300, 80, 2.0, anicraft_doc::Rgba::hex(0)).unwrap();
|
||||
}
|
||||
eprintln!("chalk preview 300x80: {:.2} ms each", t.elapsed().as_secs_f64() * 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simplified_profiles_stay_close_and_small() {
|
||||
let pts: Vec<(f32, f32)> = (0..256).map(|i| i as f32 / 255.0).map(|t| (t, 0.5 + 0.4 * (t * 9.0).sin())).collect();
|
||||
let kept = crate::cmds_brush::simplify_profile(&pts, 0.015, 64);
|
||||
assert!(kept.len() <= 64 && kept.len() > 8, "{}", kept.len());
|
||||
assert_eq!((kept.first(), kept.last()), (pts.first(), pts.last()));
|
||||
let noisy: Vec<(f32, f32)> = (0..256).map(|i| (i as f32 / 255.0, if i % 2 == 0 { 0.1 } else { 1.0 })).collect();
|
||||
assert!(crate::cmds_brush::simplify_profile(&noisy, 0.015, 64).len() <= 64);
|
||||
}
|
||||
@@ -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]]}),
|
||||
|
||||
@@ -17,11 +17,11 @@ use std::sync::Arc;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y}]} plays the movie with its actions and frame scripts from the first frame; returns the output and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn),
|
||||
c("control.test_movie", "Test Movie", "Control", Some("Ctrl+Enter"), "{frames?: steps to play (default 10 s of frames, at most 10,000), events?: [{tick, type: move|down|up|click|leave, x, y} or {tick, type: key_down|key_up|key, key: code|letter|LEFT…}], seed?: Math.random()'s seed (default 0)} plays the movie with its actions and frame scripts from the first frame; returns the output, the sounds it started ({tick, sound, name, sync, gain}; buttons' as the pointer changes their state) and where it ended (the app opens the Test Movie window)", false, test_movie as crate::RunFn),
|
||||
c("actions.set", "Set Actions", "", None, "{actions: [{op: stop|play|goto_and_play|goto_and_stop|next_frame|prev_frame|next_scene|prev_scene|trace|set_property, target?, frame?, scene?, message?, property?, value?}] | plugin: id, entry?, symbol?: id (a movie clip's timeline), layer?, frame?} sets what the keyframe at the frame runs; or {element, event: click|press|release|over|out, actions} sets an instance's event handler. An empty list clears it", true, set),
|
||||
c("actions.clear", "Clear Actions", "", None, "{symbol?, layer?, frame?} clears the keyframe's actions; {element, event?} clears an instance's handlers (one event, or all)", true, clear),
|
||||
c("actions.list", "List Actions", "", None, "{} every keyframe with actions or a frame script and every instance with event handlers, in every scene and symbol", false, list),
|
||||
c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance for actions", true, set_name),
|
||||
c("instance.set_name", "Instance Name", "", None, "{element?: id (default: the selected instance), name: letters, digits, _ or $, not starting with a digit; \"\" clears} names a movie clip or button instance, or a dynamic or input text field, for actions and scripts", true, set_name),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ pub(crate) enum Scope {
|
||||
/// A timeline commands address: a scene's (the one being edited) or a library symbol's.
|
||||
fn timeline_mut(s: &mut Session, symbol: Option<SymbolId>, scope: Scope) -> Result<&mut Timeline> {
|
||||
match symbol {
|
||||
None => Ok(crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)),
|
||||
None => crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing),
|
||||
Some(id) => {
|
||||
let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?;
|
||||
if scope == Scope::Runs && sym.kind != SymbolKind::MovieClip {
|
||||
@@ -232,7 +232,14 @@ fn set_name(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Param(format!("“{name}” can't be an instance name: use letters, digits, _ or $ (no spaces), not starting with a digit, at most {} characters", actions::MAX_NAME_CHARS)));
|
||||
}
|
||||
let e = instance_mut(s, p)?.clone();
|
||||
interactive_kind(s, &e)?;
|
||||
// Dynamic and input text fields take names too (ADR 0066); static text has none.
|
||||
match &e.kind {
|
||||
ElementKind::Text(t) if t.field.is_some() => {}
|
||||
ElementKind::Text(_) => return Err(EngineError::State("static text has no instance name: make it dynamic or input text first (Properties › Text type)".into())),
|
||||
_ => {
|
||||
interactive_kind(s, &e)?;
|
||||
}
|
||||
}
|
||||
let el = instance_mut(s, p)?;
|
||||
el.name = name.clone();
|
||||
Ok(json!({"element": el.id.0, "name": name}))
|
||||
@@ -241,6 +248,8 @@ fn set_name(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Most steps and events of a headless test.
|
||||
const MAX_TEST_STEPS: u32 = 10_000;
|
||||
const MAX_TEST_EVENTS: usize = 10_000;
|
||||
/// Most started sounds `control.test_movie` lists (the rest are counted).
|
||||
const MAX_TEST_SOUNDS: usize = 10_000;
|
||||
|
||||
fn test_movie(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fps = s.doc.stage.fps.max(1.0);
|
||||
@@ -259,16 +268,34 @@ fn test_movie(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Some(_) => return Err(EngineError::Param("param 'events' must be a list".into())),
|
||||
}
|
||||
let seed = opt_u64(p, "seed")?.unwrap_or(anicraft_doc::player::DEFAULT_SEED);
|
||||
let mut runner = ScriptRunner::new(&s.plugins);
|
||||
let mut movie = Movie::start(&s.doc, &mut runner);
|
||||
let mut movie = Movie::start_seeded(&s.doc, seed, &mut runner);
|
||||
// The sounds the movie started (buttons' under the pointer too, ADR 0057), in order.
|
||||
let mut sounds: Vec<Value> = Vec::new();
|
||||
let mut more = 0usize;
|
||||
let mut heard = |movie: &mut Movie, doc: &anicraft_doc::Document| {
|
||||
for (tick, st) in movie.take_sounds() {
|
||||
if sounds.len() >= MAX_TEST_SOUNDS {
|
||||
more += 1;
|
||||
continue;
|
||||
}
|
||||
let name = doc.sound(st.sound.sound).map(|x| x.name.clone());
|
||||
sounds.push(json!({"tick": tick, "sound": st.sound.sound.0, "name": name, "sync": st.sound.sync.key(), "gain": st.gain}));
|
||||
}
|
||||
};
|
||||
heard(&mut movie, &s.doc);
|
||||
for tick in 1..=u64::from(frames) {
|
||||
let events: Vec<_> = timed.iter().filter(|(t, _)| *t == tick).flat_map(|(_, e)| e.iter().copied()).collect();
|
||||
movie.step(&s.doc, &events, &mut runner);
|
||||
heard(&mut movie, &s.doc);
|
||||
}
|
||||
let nodes = anicraft_doc::player::tree(&s.doc, &movie.state);
|
||||
Ok(json!({
|
||||
"steps": frames,
|
||||
"output": movie.output.iter().map(|(t, l)| json!({"tick": t, "line": l})).collect::<Vec<_>>(),
|
||||
"sounds": sounds,
|
||||
"more_sounds": more,
|
||||
"state": state_view(&s.doc, &movie.state, &nodes, None),
|
||||
"script_runs": runner.runs,
|
||||
"script_fuel": runner.fuel_used,
|
||||
|
||||
@@ -12,6 +12,7 @@ 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::skin::{self, Binding, Influence, MAX_SKIN_POINTS, Skin};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Rgba, Tween, evaluate_layer_elements};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
@@ -23,16 +24,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c(
|
||||
"bone.add",
|
||||
"Add Bone",
|
||||
"{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint, stage px; default the end of the bone into `from`, else its registration point), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)",
|
||||
"{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint on a root instance, stage px, default its registration point; from an instance that hangs from a bone the joint is always that bone's end, so chains stay joined), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)",
|
||||
true,
|
||||
add as crate::RunFn,
|
||||
),
|
||||
c(
|
||||
"bone.add_in_shape",
|
||||
"Add Bone in Shape",
|
||||
"{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone); the shape's points are bound to the nearest bones",
|
||||
true,
|
||||
add_in_shape,
|
||||
),
|
||||
c("bone.bind", "Bind Points", "{bone, points?: [point index…] (default every point; see bone.info with points), mode?: \"only\" (the points follow just this bone; default) | \"add\" (they share it with the bones they follow) | \"remove\" | \"auto\" (back to automatic binding)} → {bone, changed, bound (how many points the bone moves)}. A shape armature's binding: which points of the shape follow which bone", true, bind),
|
||||
c("bone.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.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.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), joint angle and limits (°), pinned; 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),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -119,6 +128,32 @@ fn rebake(layer: &mut Layer) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A new armature layer at `index` holding `arm` and `elements` on one pose that spans from the
|
||||
/// keyframe of `from` at the playhead to the end of the timeline (a classic tween on it, so
|
||||
/// poses keyed later tween).
|
||||
fn armature_layer(s: &mut Session, from: LayerId, index: usize, elements: Vec<Arc<Element>>, arm: Armature) -> Result<LayerId> {
|
||||
let (start, end) = s.timeline().layer(from).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end()));
|
||||
let end = end.max(s.frame_count());
|
||||
if s.timeline().layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let lid = LayerId(s.doc.alloc_id());
|
||||
let mut layer = Layer::new(lid, fresh_name(s, "Armature_"));
|
||||
layer.kind = LayerKind::Armature;
|
||||
// Bones show in the layer colour: a green that reads on light and dark artwork.
|
||||
layer.color = Rgba::hex(0x2fb67c);
|
||||
layer.armature = Some(Arc::new(arm));
|
||||
let mut k = Keyframe::new(start, end.saturating_sub(start).max(1));
|
||||
k.elements = elements;
|
||||
k.tween = Some(Tween::default());
|
||||
layer.keyframes = vec![Arc::new(k)];
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?;
|
||||
layer.parent = tl.container_at(index, LayerKind::Armature);
|
||||
tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer));
|
||||
tl.repair_masks();
|
||||
Ok(lid)
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let req = |k: &str| opt_u64(p, k)?.map(ElementId).ok_or_else(|| EngineError::Param(format!("param '{k}' (an instance id) is required")));
|
||||
let (from, to) = (req("from")?, req("to")?);
|
||||
@@ -158,10 +193,12 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (wf, wt) = (f.el.transform, t.el.transform);
|
||||
let singular = || EngineError::State("an instance scaled to nothing can't hold a bone".into());
|
||||
let (inv_f, inv_t) = (wf.inverse().ok_or_else(singular)?, wt.inverse().ok_or_else(singular)?);
|
||||
// The joint: given, else the end of the bone into `from` (a chain joins end to start), else
|
||||
// its registration point.
|
||||
// The joint. An instance that already hangs from a bone has one joint, that bone's end: every
|
||||
// bone from it starts there, wherever on the instance the drag began, so the chain stays
|
||||
// joined end to start and turns about the joints it shows, as in Animate (#239). A root's
|
||||
// bones start where given (a torso's shoulders and hips), else at its registration point.
|
||||
let into_from = fa.as_ref().and_then(|a| a.bone_into(from)).map(|b| wf.apply(b.tail));
|
||||
let head = head.or(into_from).unwrap_or(wf.translation());
|
||||
let head = into_from.or(head).unwrap_or(wf.translation());
|
||||
let tail = tail.unwrap_or(wt.translation());
|
||||
let rest = inv_f.mul(&wt);
|
||||
if !rest.is_finite() || rest.inverse().is_none() {
|
||||
@@ -184,30 +221,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
f.layer
|
||||
}
|
||||
None => {
|
||||
// The first bone: both instances move to a new armature layer above them, whose one
|
||||
// pose spans from their keyframe to the end of the timeline.
|
||||
let (start, end) = s.timeline().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.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(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 = 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();
|
||||
lid
|
||||
let arm = Armature { bones: vec![bone], skin: None };
|
||||
armature_layer(s, f.layer, f.index.min(t.index), vec![f.el.clone(), t.el.clone()], arm)?
|
||||
}
|
||||
};
|
||||
s.layer = lid;
|
||||
@@ -229,7 +246,10 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut left = (*arm).clone();
|
||||
left.bones.retain(|b| !gone.contains(&b.id));
|
||||
let dissolve = left.is_empty();
|
||||
let freed: Vec<ElementId> = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() };
|
||||
// A shape armature's bones move no instances: only without bones does its shape go.
|
||||
let skinned = arm.skin.is_some();
|
||||
skin::rebind(&mut left);
|
||||
let freed: Vec<ElementId> = if dissolve { arm.members() } else if skinned { Vec::new() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() };
|
||||
let tl = s.timeline();
|
||||
let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
@@ -244,7 +264,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut k = Keyframe::new(start, end.saturating_sub(start).max(1));
|
||||
k.elements = shown;
|
||||
freed_layer.keyframes = vec![Arc::new(k)];
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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 +277,15 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
l.armature = Some(Arc::new(left));
|
||||
rebake(l);
|
||||
tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer));
|
||||
if !skinned {
|
||||
tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer));
|
||||
}
|
||||
}
|
||||
tl.repair_masks();
|
||||
s.layer = if dissolve { new_id } else { lid };
|
||||
s.selection.clear();
|
||||
Ok(json!({"removed": gone.iter().map(|b| b.0).collect::<Vec<_>>(), "freed": freed.iter().map(|e| e.0).collect::<Vec<_>>(), "layer": new_id.0, "armature_removed": dissolve}))
|
||||
let layer = if dissolve || !skinned { new_id } else { lid };
|
||||
Ok(json!({"removed": gone.iter().map(|b| b.0).collect::<Vec<_>>(), "freed": freed.iter().map(|e| e.0).collect::<Vec<_>>(), "layer": layer.0, "armature_removed": dissolve}))
|
||||
}
|
||||
|
||||
fn set_limits(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -411,6 +434,7 @@ fn solve(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
|
||||
let only = opt_u64(p, "layer")?.map(LayerId);
|
||||
let 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]);
|
||||
@@ -435,11 +459,179 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"angle": deg(b.allow(pose.angle(b.id))),
|
||||
"min": b.limits.map(|l| deg(l.min)), "max": b.limits.map(|l| deg(l.max)),
|
||||
"pinned": b.pinned,
|
||||
"points": arm.skin.as_ref().map(|k| k.points.iter().filter(|x| x.weight(b.id) > 0.0).count()),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::<Vec<_>>(), "poses": poses(l), "bones": bones}))
|
||||
let mut out = json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::<Vec<_>>(), "poses": poses(l), "bones": bones, "shape": arm.skin_shape().map(|e| e.0)});
|
||||
if with_points && let Some(k) = &arm.skin {
|
||||
out["points"] = json!(skin::points_shown(arm, &els).iter().zip(&k.points).map(|(at, b)| json!({"at": pt(*at), "bones": b.bones.iter().map(|i| json!([i.0.0, i.1])).collect::<Vec<_>>(), "manual": b.manual})).collect::<Vec<_>>());
|
||||
}
|
||||
Some(out)
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"frame": frame, "armatures": list}))
|
||||
}
|
||||
|
||||
fn add_in_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let shape = opt_u64(p, "shape")?.map(ElementId);
|
||||
let parent = opt_u64(p, "parent")?.map(BoneId);
|
||||
let head = opt_point(p, "head")?;
|
||||
let tail = opt_point(p, "tail")?.ok_or_else(|| EngineError::Param("param 'tail' ([x, y], stage px: where the bone ends) is required".into()))?;
|
||||
let name = opt_str(p, "name")?.unwrap_or("").trim().to_string();
|
||||
if name.len() > MAX_NAME {
|
||||
return Err(EngineError::Param(format!("param 'name' must be at most {MAX_NAME} bytes")));
|
||||
}
|
||||
let frame = s.frame;
|
||||
// The armature the bone joins (none yet for the first bone), the shape, the node the bone
|
||||
// starts on, and its joint on the stage.
|
||||
let (existing, found, from, head) = match (parent, shape) {
|
||||
(Some(b), _) => {
|
||||
let (lid, arm) = find_bone(s, b)?;
|
||||
let sh = arm.skin_shape().ok_or_else(|| EngineError::State("that bone joins symbol instances: continue it with bone.add".into()))?;
|
||||
if shape.is_some_and(|x| x != sh) {
|
||||
return Err(EngineError::Param("that bone is in another shape".into()));
|
||||
}
|
||||
let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("the armature's shape isn't on the stage at frame {}", frame + 1)))?;
|
||||
let node = arm.bone(b).map(|x| x.child).ok_or_else(|| EngineError::State("no such bone".into()))?;
|
||||
let end = s.timeline().layer(lid).and_then(|l| {
|
||||
let (_, els) = evaluate_layer_elements(l, frame)?;
|
||||
let pose = armature::pose_at(l, frame).unwrap_or_default();
|
||||
armature::bones_at(&arm, &els, &pose).into_iter().find(|g| g.id == b).map(|g| g.tail)
|
||||
});
|
||||
let head = head.or(end).ok_or_else(|| EngineError::State(format!("the bone isn't on the stage at frame {}", frame + 1)))?;
|
||||
(Some((lid, arm)), f, node, head)
|
||||
}
|
||||
(None, Some(sh)) => {
|
||||
let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("no shape with id {} on the stage at frame {}", sh.0, frame + 1)))?;
|
||||
let ElementKind::Shape(shp) = &f.el.kind else {
|
||||
return Err(EngineError::State("bones inside a shape need a shape: for symbol instances, drag from one to another (bone.add)".into()));
|
||||
};
|
||||
let head = head.ok_or_else(|| EngineError::Param("param 'head' ([x, y], stage px: where the bone starts, inside the shape) is required".into()))?;
|
||||
let existing = match f.kind {
|
||||
LayerKind::Normal => None,
|
||||
LayerKind::Armature => {
|
||||
let arm = s.timeline().layer(f.layer).and_then(|l| l.armature.clone()).filter(|a| a.skin_shape() == Some(sh)).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?;
|
||||
Some((f.layer, arm))
|
||||
}
|
||||
_ => return Err(EngineError::State("bones go inside shapes on normal layers (not on guide or mask layers)".into())),
|
||||
};
|
||||
// A bone starts inside the shape (on its fill, or on its line).
|
||||
let reach = shp.stroke.as_ref().map_or(0.0, |k| k.width * 0.5 * f.el.transform.mean_scale()) + 2.0;
|
||||
let inside = (shp.fill.is_some() && shp.path.contains(head, &f.el.transform, shp.fill_rule)) || shp.path.distance_to_edge(head, &f.el.transform) <= reach;
|
||||
if !inside {
|
||||
return Err(EngineError::State("start the bone inside the shape".into()));
|
||||
}
|
||||
(existing, f, sh, head)
|
||||
}
|
||||
(None, None) => return Err(EngineError::Param("give 'shape' (the shape's id, for the first bone) or 'parent' (a bone to continue from)".into())),
|
||||
};
|
||||
unlocked(s, found.layer)?;
|
||||
if head.distance(tail) < 1.0 {
|
||||
return Err(EngineError::Param("a bone needs a length: drag from its joint to its end".into()));
|
||||
}
|
||||
let ElementKind::Shape(shp) = &found.el.kind else { return Err(EngineError::State("that isn't a shape".into())) };
|
||||
// The node the bone starts on, as placed at the playhead: the bone's points go back through
|
||||
// it to the shape as drawn (a new bone is at rest in every pose).
|
||||
let node = match &existing {
|
||||
Some((lid, arm)) => {
|
||||
let l = s.timeline().layer(*lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let (_, els) = evaluate_layer_elements(l, frame).ok_or_else(|| EngineError::State("the armature isn't on this frame".into()))?;
|
||||
let pose = armature::pose_at(l, frame).unwrap_or_default();
|
||||
armature::place(arm, &els, &pose).get(&from).copied()
|
||||
}
|
||||
None => Some(found.el.transform),
|
||||
};
|
||||
let inv = node.and_then(|m| m.inverse()).ok_or_else(|| EngineError::State("a shape scaled to nothing can't hold a bone".into()))?;
|
||||
let (h, t) = (inv.apply(head), inv.apply(tail));
|
||||
if !(h.x.is_finite() && h.y.is_finite() && t.x.is_finite() && t.y.is_finite()) {
|
||||
return Err(EngineError::State("a shape scaled to nothing can't hold a bone".into()));
|
||||
}
|
||||
if existing.as_ref().is_some_and(|(_, a)| a.bones.len() >= MAX_BONES) {
|
||||
return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones")));
|
||||
}
|
||||
if existing.is_none() && skin::anchors(&shp.path).len() > MAX_SKIN_POINTS {
|
||||
return Err(EngineError::State(format!("bones go inside shapes of at most {MAX_SKIN_POINTS} points: simplify it first (Modify › Shape › Optimize)")));
|
||||
}
|
||||
let id = BoneId(s.doc.alloc_id());
|
||||
let child = ElementId(s.doc.alloc_id());
|
||||
let bone = Bone { id, name, parent: from, child, head: h, tail: t, rest: Affine::IDENTITY, limits: None, pinned: false };
|
||||
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())) };
|
||||
skin::rebind(&mut arm);
|
||||
take_off(s, found.layer, found.el.id)?;
|
||||
(armature_layer(s, found.layer, found.index, vec![Arc::new(el)], arm)?, true)
|
||||
}
|
||||
};
|
||||
s.layer = lid;
|
||||
s.selection.clear();
|
||||
let bound = s.timeline().layer(lid).and_then(|l| l.armature.as_ref()).and_then(|a| a.skin.as_ref()).map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count());
|
||||
Ok(json!({"bone": id.0, "layer": lid.0, "created": created, "points": bound}))
|
||||
}
|
||||
|
||||
fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = bone_param(p)?;
|
||||
let mode = opt_str(p, "mode")?.unwrap_or("only");
|
||||
if !matches!(mode, "only" | "add" | "remove" | "auto") {
|
||||
return Err(EngineError::Param("param 'mode' must be \"only\", \"add\", \"remove\" or \"auto\"".into()));
|
||||
}
|
||||
let (lid, arm) = find_bone(s, id)?;
|
||||
unlocked(s, lid)?;
|
||||
let n = arm.skin.as_ref().map(|k| k.points.len()).ok_or_else(|| EngineError::State("that bone joins symbol instances: only bones inside a shape bind its points".into()))?;
|
||||
let bad = || EngineError::Param(format!("param 'points' must be a list of point indices below {n} (see bone.info with points)"));
|
||||
let points: Vec<usize> = match p.get("points") {
|
||||
None | Some(Value::Null) => (0..n).collect(),
|
||||
Some(Value::Array(a)) if a.len() <= MAX_SKIN_POINTS => a.iter().map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n).ok_or_else(bad)).collect::<Result<_>>()?,
|
||||
Some(_) => return Err(bad()),
|
||||
};
|
||||
let mut arm = (*arm).clone();
|
||||
let segments = skin::rest_segments(&arm);
|
||||
let Some(k) = arm.skin.as_mut() else { return Err(EngineError::State("that bone isn't inside a shape".into())) };
|
||||
let anchors = skin::anchors(&k.rest);
|
||||
let mut changed = 0usize;
|
||||
for i in points {
|
||||
let (Some(b), Some(&at)) = (k.points.get_mut(i), anchors.get(i)) else { continue };
|
||||
let next = match mode {
|
||||
"only" => Binding { bones: vec![Influence(id, 1.0)], manual: true },
|
||||
"add" if b.weight(id) > 0.0 => continue,
|
||||
"add" => {
|
||||
// An equal share with the bones the point already follows.
|
||||
let share = 1.0 / (b.bones.len() + 1) as f32;
|
||||
let mut x = Binding { bones: b.bones.iter().map(|i| Influence(i.0, i.1 * (1.0 - share))).collect(), manual: true };
|
||||
x.bones.push(Influence(id, share));
|
||||
x.normalize(|_| true);
|
||||
x
|
||||
}
|
||||
"remove" => {
|
||||
let mut x = Binding { bones: b.bones.iter().copied().filter(|i| i.0 != id).collect(), manual: true };
|
||||
x.normalize(|_| true);
|
||||
x
|
||||
}
|
||||
_ => skin::auto_binding(&segments, at),
|
||||
};
|
||||
if *b != next {
|
||||
*b = next;
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
let bound = k.points.iter().filter(|b| b.weight(id) > 0.0).count();
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
l.armature = Some(Arc::new(arm));
|
||||
rebake(l);
|
||||
Ok(json!({"bone": id.0, "changed": changed, "bound": bound}))
|
||||
}
|
||||
@@ -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, Tip, TipShape, centre_stroke, outline_shaped};
|
||||
use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![CommandSpec {
|
||||
id: "draw.brush",
|
||||
label: "Brush Stroke",
|
||||
menu: "",
|
||||
shortcut: None,
|
||||
params: "{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), mode?: normal|fills|behind (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas), color? (default: the fill colour), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}",
|
||||
mutates: true,
|
||||
run: draw_brush,
|
||||
}]
|
||||
let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run };
|
||||
vec![
|
||||
c(
|
||||
"draw.brush",
|
||||
"Brush Stroke",
|
||||
"{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (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), 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? (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,6 +92,49 @@ impl PaintMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where Paint Selection and Paint Inside may paint (ADR 0080).
|
||||
enum Region {
|
||||
/// Inside this outline (keyframe space, even-odd).
|
||||
Clip(Path),
|
||||
/// Only empty areas: Paint Inside started on open, empty stage (as Paint Behind).
|
||||
Empty,
|
||||
/// Nowhere, and why.
|
||||
Nowhere(&'static str),
|
||||
}
|
||||
|
||||
const TOO_MUCH: &str = "there is too much artwork there to paint inside at once; paint a smaller area";
|
||||
|
||||
/// The region a clipped paint mode paints in: the union of the selected shapes' fills on the
|
||||
/// active layer (Paint Selection), or the topmost fill under `start` there, else the empty area
|
||||
/// the lines and fills close off around it (Paint Inside). Merged paint lies under drawing
|
||||
/// objects, so off Object Drawing only raw fills count (an object is edited inside it).
|
||||
fn paint_region(s: &mut Session, mode: PaintMode, start: Vec2, object: bool) -> Result<Region> {
|
||||
let els = s.editable_keyframe()?.elements.clone();
|
||||
let filled = |e: &Element| match &e.kind {
|
||||
ElementKind::Shape(sh) if sh.fill.is_some() && (object || sh.merge) => Some((sh.path.transformed(&e.transform), sh.fill_rule)),
|
||||
_ => None,
|
||||
};
|
||||
let too_much = || EngineError::State(TOO_MUCH.into());
|
||||
if mode == PaintMode::Selection {
|
||||
let here = s.layer;
|
||||
let picked: Vec<(Path, FillRule)> = els.iter().filter(|e| s.selection.contains(here, e.id)).filter_map(|e| filled(e)).collect();
|
||||
if picked.is_empty() {
|
||||
return Ok(Region::Nowhere(if s.selection.on(here).is_empty() { "select the fills to paint inside first" } else { "the selection has no fills to paint inside" }));
|
||||
}
|
||||
let refs: Vec<(&Path, FillRule)> = picked.iter().map(|(p, r)| (p, *r)).collect();
|
||||
return Ok(Region::Clip(planar::union(&refs).ok_or_else(too_much)?));
|
||||
}
|
||||
let on = els.iter().rev().find_map(|e| filled(e).filter(|(p, r)| p.contains(start, &Affine::IDENTITY, *r)));
|
||||
if let Some((path, rule)) = on {
|
||||
// The fill's own rule, as even-odd loops.
|
||||
return Ok(Region::Clip(planar::union(&[(&path, rule)]).ok_or_else(too_much)?));
|
||||
}
|
||||
Ok(match merge::enclosed_area(&els, start) {
|
||||
Some(area) => Region::Clip(area),
|
||||
None => Region::Empty,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn samples(p: &Value) -> Result<Vec<Sample>> {
|
||||
let bad = || EngineError::Param("param 'points' must be a list of [x, y] or [x, y, pressure]".into());
|
||||
let list = p.get("points").and_then(Value::as_array).ok_or_else(bad)?;
|
||||
@@ -132,49 +195,335 @@ pub(crate) fn tip(p: &Value) -> Result<Tip> {
|
||||
Ok(Tip { shape, size, angle, roundness: roundness / 100.0 })
|
||||
}
|
||||
|
||||
/// The brush a command paints with: its `preset` (or the plain brush) with the params' own
|
||||
/// settings on top.
|
||||
pub fn brush_param(s: &Session, p: &Value) -> Result<BrushPreset> {
|
||||
let base = match opt_str(p, "preset")? {
|
||||
Some(name) => s.brushes.find(name).ok_or_else(|| EngineError::Param(format!("no brush named '{name}' (brush.preset_list lists them)")))?,
|
||||
None => BrushPreset::default(),
|
||||
};
|
||||
base.with_params(p)
|
||||
}
|
||||
|
||||
/// The stroke's opacity factor when pressure drives it: the average mapped pressure.
|
||||
pub fn pressure_opacity(b: &BrushPreset, pts: &[Sample]) -> f32 {
|
||||
if !b.pressure_opacity || pts.is_empty() {
|
||||
return 1.0;
|
||||
}
|
||||
(pts.iter().map(|x| b.curve.map(x.pressure)).sum::<f32>() / pts.len() as f32).clamp(0.05, 1.0)
|
||||
}
|
||||
|
||||
fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = bounded_samples(p)?;
|
||||
let tip = tip(p)?;
|
||||
let b = brush_param(s, p)?;
|
||||
let tip = b.tip();
|
||||
let size = tip.size;
|
||||
let smoothing = ranged(p, "smoothing", 0.0..=100.0, 50.0)?;
|
||||
let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false);
|
||||
let unit = ranged(p, "unit", 0.001..=1000.0, 1.0)?;
|
||||
let mode_key = opt_str(p, "mode")?.unwrap_or("normal");
|
||||
let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills or behind)")))?;
|
||||
let color = opt_color(p, "color")?.unwrap_or(s.style.fill);
|
||||
let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills, behind, selection or inside)")))?;
|
||||
let color = opt_color(p, "color")?.unwrap_or(if as_stroke { s.style.stroke } else { s.style.fill });
|
||||
let color = Rgba { a: color.a * pressure_opacity(&b, &pts), ..color };
|
||||
let object = object_param(s, p)?;
|
||||
// Pressure through the curve (ADR 0068) before it sizes the tip.
|
||||
let pts: Vec<Sample> = pts.iter().map(|x| Sample { at: x.at, pressure: b.size_pressure(x.pressure) }).collect();
|
||||
|
||||
// Smoothing and accuracy are screen distances, so a stroke looks the same at any zoom: at 50
|
||||
// the centre line may wander 3.3 screen points from the hand, at 0 a third of a point.
|
||||
// The outline is fitted within a third of a screen point, or a hundredth of the size for
|
||||
// small brushes (so a small dab is still round).
|
||||
let path = outline(&pts, &tip, unit * (0.3 + smoothing * 0.06), (unit * 0.35).min(size * 0.01));
|
||||
let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(size * 0.01));
|
||||
if as_stroke {
|
||||
return paint_stroke(s, &pts, &b, smoothing, tol, color, object);
|
||||
}
|
||||
let start = pts.first().map_or(Vec2::ZERO, |x| x.at);
|
||||
let mut path = outline_shaped(&pts, &tip, &b.shaping(), smoothing, tol);
|
||||
if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) {
|
||||
return Err(EngineError::Param("the stroke is too small to paint".into()));
|
||||
}
|
||||
// Paint Selection and Paint Inside (ADR 0080): the outline clipped to the region, then
|
||||
// merged as usual. Nothing changes when nothing is painted (no keyframe made, no step).
|
||||
let mut order = mode.order();
|
||||
// Paint Selection keeps the selection: the region, to select again after the merge.
|
||||
let mut kept_region: Option<Path> = None;
|
||||
if matches!(mode, PaintMode::Selection | PaintMode::Inside) {
|
||||
let before = s.doc.clone();
|
||||
let region = paint_region(s, mode, start, object);
|
||||
let clipped = match region {
|
||||
Ok(Region::Clip(r)) => {
|
||||
let c = planar::intersect(&path, FillRule::EvenOdd, &r).ok_or_else(|| EngineError::State(TOO_MUCH.into()));
|
||||
kept_region = (mode == PaintMode::Selection).then_some(r);
|
||||
Some(c)
|
||||
}
|
||||
Ok(Region::Empty) => None,
|
||||
Ok(Region::Nowhere(why)) => {
|
||||
s.doc = before;
|
||||
return Ok(json!({"painted": false, "mode": mode.key(), "elements": [], "reason": why}));
|
||||
}
|
||||
Err(e) => Some(Err(e)),
|
||||
};
|
||||
match clipped {
|
||||
None => order = Order::Behind,
|
||||
Some(Err(e)) => {
|
||||
s.doc = before;
|
||||
return Err(e);
|
||||
}
|
||||
Some(Ok(p)) if !p.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) => {
|
||||
s.doc = before;
|
||||
let why = if mode == PaintMode::Selection { "the stroke doesn't reach the selected fills" } else { "nothing to paint there" };
|
||||
return Ok(json!({"painted": false, "mode": mode.key(), "elements": [], "reason": why}));
|
||||
}
|
||||
Some(Ok(p)) => path = p,
|
||||
}
|
||||
}
|
||||
let c = path.bounds().center();
|
||||
let local = path.transformed(&Affine::translate(-c.x, -c.y));
|
||||
// A gradient or bitmap in the fill swatch paints too, locked or fitted (ADR 0074), unless a
|
||||
// colour was given or pressure sets the opacity.
|
||||
let fill = match &s.style.fill_paint {
|
||||
Some(_) if p.get("color").is_none_or(Value::is_null) && color.a >= 1.0 => s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()),
|
||||
_ => Paint::Solid(color),
|
||||
};
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: Affine::translate(c.x, c.y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(path.transformed(&Affine::translate(-c.x, -c.y))), fill: Some(Paint::Solid(color)), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }),
|
||||
};
|
||||
if s.editable_keyframe()?.elements.len() >= 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
}
|
||||
if object {
|
||||
let kf = s.editable_keyframe()?;
|
||||
match mode {
|
||||
match order {
|
||||
// Behind everything on the layer.
|
||||
PaintMode::Behind => kf.elements.insert(0, Arc::new(el)),
|
||||
PaintMode::Normal | PaintMode::Fills => kf.elements.push(Arc::new(el)),
|
||||
Order::Behind => kf.elements.insert(0, Arc::new(el)),
|
||||
Order::Top | Order::UnderLines => kf.elements.push(Arc::new(el)),
|
||||
}
|
||||
// Paint Selection: the selected objects stay selected, for the next stroke.
|
||||
if kept_region.is_none() {
|
||||
s.select_only([id]);
|
||||
}
|
||||
s.select_only([id]);
|
||||
return Ok(json!({"element": id.0, "elements": [id.0], "mode": mode.key(), "merged": false}));
|
||||
}
|
||||
let merged = merge::merge_in_order(s, vec![el], mode.order())?;
|
||||
s.select_only(merged);
|
||||
let ids: Vec<u64> = s.selection.id_list();
|
||||
let merged = merge::merge_in_order(s, vec![el], order)?;
|
||||
let ids: Vec<u64> = merged.iter().map(|e| e.0).collect();
|
||||
match &kept_region {
|
||||
// Paint Selection: what lies in the region (the selected fills' pieces and the paint)
|
||||
// stays selected, for the next stroke.
|
||||
Some(region) => {
|
||||
let inside = pieces_in(s, region);
|
||||
s.select_only(inside);
|
||||
}
|
||||
None => s.select_only(merged),
|
||||
}
|
||||
Ok(json!({"element": ids.first(), "elements": ids, "mode": mode.key(), "merged": true}))
|
||||
}
|
||||
|
||||
/// The raw fills on the active keyframe that cover part of `region` (keyframe space, even-odd).
|
||||
fn pieces_in(s: &mut Session, region: &Path) -> Vec<ElementId> {
|
||||
let Ok(kf) = s.editable_keyframe() else { return Vec::new() };
|
||||
let bounds = region.bounds();
|
||||
kf.elements
|
||||
.iter()
|
||||
.filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_some() && !sh.path.bounds().transformed(&e.transform).intersect(&bounds).is_empty()))
|
||||
.filter(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => planar::intersect(&sh.path.transformed(&e.transform), sh.fill_rule, region).is_some_and(|p| !p.is_empty()),
|
||||
_ => false,
|
||||
})
|
||||
.map(|e| e.id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Width points a Paint Brush stroke's profile is simplified from (evenly along its length).
|
||||
const PROFILE_SAMPLES: usize = 256;
|
||||
/// How closely the simplified profile follows the brush's widths (a factor of the size).
|
||||
const PROFILE_TOLERANCE: f32 = 0.015;
|
||||
|
||||
/// The Paint Brush (ADR 0068): the smoothed centre line as a stroke of the brush's size in the
|
||||
/// stroke colour, its width profile following the pressure and tapers, so the Width tool edits
|
||||
/// it afterwards. A stroke of one width is a plain line and merges like the Pencil's.
|
||||
fn paint_stroke(s: &mut Session, pts: &[Sample], b: &BrushPreset, smoothing: f32, tol: f32, color: Rgba, object: bool) -> Result<Value> {
|
||||
let (path, factors) = centre_stroke(pts, &b.shaping(), smoothing, tol * 0.25, PROFILE_SAMPLES);
|
||||
if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) {
|
||||
return Err(EngineError::Param("the stroke is too short to draw a line".into()));
|
||||
}
|
||||
let kept = simplify_profile(&factors, PROFILE_TOLERANCE, MAX_WIDTH_POINTS);
|
||||
let profile = WidthProfile::new(kept.iter().map(|(t, f)| WidthPoint::new(*t, *f, *f)).collect());
|
||||
let stroke = Stroke::new(color, b.size).with_profile(profile);
|
||||
let c = path.bounds().center();
|
||||
let mut v = add_shape(s, "paint_brush", path.transformed(&Affine::translate(-c.x, -c.y)), c, None, Some(stroke), object)?;
|
||||
v["width_points"] = json!(kept.len());
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The fewest of `pts` (`(t, factor)`, sorted) that stay within `tol` of the rest by straight
|
||||
/// lines between them (Ramer–Douglas–Peucker), widening the tolerance until at most `max` are
|
||||
/// kept. The ends always stay.
|
||||
pub fn simplify_profile(pts: &[(f32, f32)], tol: f32, max: usize) -> Vec<(f32, f32)> {
|
||||
let n = pts.len();
|
||||
if n <= 2 {
|
||||
return pts.to_vec();
|
||||
}
|
||||
let mut tol = tol.max(1e-4);
|
||||
for _ in 0..12 {
|
||||
let mut keep = vec![false; n];
|
||||
if let Some(k) = keep.first_mut() {
|
||||
*k = true;
|
||||
}
|
||||
if let Some(k) = keep.last_mut() {
|
||||
*k = true;
|
||||
}
|
||||
let mut stack = vec![(0usize, n - 1)];
|
||||
while let Some((a, z)) = stack.pop() {
|
||||
let (Some(pa), Some(pz)) = (pts.get(a), pts.get(z)) else { continue };
|
||||
let mut worst = (0.0f32, a);
|
||||
for i in a + 1..z {
|
||||
let Some(q) = pts.get(i) else { continue };
|
||||
let t = if pz.0 - pa.0 > 1e-9 { (q.0 - pa.0) / (pz.0 - pa.0) } else { 0.0 };
|
||||
let d = (q.1 - (pa.1 + (pz.1 - pa.1) * t)).abs();
|
||||
if d > worst.0 {
|
||||
worst = (d, i);
|
||||
}
|
||||
}
|
||||
if worst.0 > tol {
|
||||
if let Some(k) = keep.get_mut(worst.1) {
|
||||
*k = true;
|
||||
}
|
||||
stack.push((a, worst.1));
|
||||
stack.push((worst.1, z));
|
||||
}
|
||||
}
|
||||
let out: Vec<(f32, f32)> = pts.iter().zip(&keep).filter(|(_, k)| **k).map(|(p, _)| *p).collect();
|
||||
if out.len() <= max.max(2) {
|
||||
return out;
|
||||
}
|
||||
tol *= 1.6;
|
||||
}
|
||||
// Still too many (a wildly varying pressure): evenly spaced points.
|
||||
let m = max.max(2);
|
||||
(0..m).filter_map(|i| pts.get(i * (n - 1) / (m - 1))).copied().collect()
|
||||
}
|
||||
|
||||
// ----- the brush library (ADR 0068) ---------------------------------------------------------
|
||||
|
||||
fn preset_json(p: &BrushPreset, key: Option<&str>) -> Value {
|
||||
let mut v = p.params();
|
||||
v["name"] = json!(p.name);
|
||||
v["builtin"] = json!(key.is_some());
|
||||
if let Some(k) = key {
|
||||
v["key"] = json!(k);
|
||||
v["hint"] = json!(builtin_hint(k));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn preset_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut list: Vec<Value> = BUILTIN.iter().filter_map(|(k, _)| builtin(k).map(|p| preset_json(&p, Some(k)))).collect();
|
||||
list.extend(s.brushes.user().iter().map(|p| preset_json(p, None)));
|
||||
Ok(json!({"presets": list, "yours": s.brushes.user().len()}))
|
||||
}
|
||||
|
||||
fn preset_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_req(p, "name")?;
|
||||
let base = match opt_str(p, "from")? {
|
||||
Some(from) => s.brushes.find(from).ok_or_else(|| EngineError::Param(format!("no brush named '{from}'")))?,
|
||||
None => BrushPreset::default(),
|
||||
};
|
||||
let b = BrushPreset { name: name.to_string(), ..base.with_params(p)? };
|
||||
let replaced = s.brushes.save(b)?;
|
||||
let saved = clean_name(name).and_then(|n| s.brushes.position(&n)).and_then(|i| s.brushes.user().get(i)).map(|x| x.name.clone());
|
||||
Ok(json!({"name": saved, "replaced": replaced, "yours": s.brushes.user().len()}))
|
||||
}
|
||||
|
||||
fn preset_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let to = s.brushes.rename(str_req(p, "name")?, str_req(p, "to")?)?;
|
||||
Ok(json!({"name": to}))
|
||||
}
|
||||
|
||||
fn preset_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let gone = s.brushes.delete(str_req(p, "name")?)?;
|
||||
Ok(json!({"deleted": gone.name, "yours": s.brushes.user().len()}))
|
||||
}
|
||||
|
||||
fn preset_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = std::path::PathBuf::from(str_req(p, "path")?);
|
||||
let chosen: Vec<BrushPreset> = match p.get("names") {
|
||||
None | Some(Value::Null) => s.brushes.user().to_vec(),
|
||||
Some(Value::Array(names)) => names
|
||||
.iter()
|
||||
.take(MAX_USER_PRESETS * 2)
|
||||
.map(|n| {
|
||||
let n = n.as_str().ok_or_else(|| EngineError::Param("param 'names' must be a list of brush names".into()))?;
|
||||
s.brushes.find(n).ok_or_else(|| EngineError::Param(format!("no brush named '{n}'")))
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
Some(_) => return Err(EngineError::Param("param 'names' must be a list of brush names".into())),
|
||||
};
|
||||
if chosen.is_empty() {
|
||||
return Err(EngineError::State("there are no brushes of your own to export yet (save one first)".into()));
|
||||
}
|
||||
let text = BrushLibrary::file_json(&chosen);
|
||||
crate::vfs::write(&path, text.as_bytes())?;
|
||||
Ok(json!({"written": path.display().to_string(), "brushes": chosen.len(), "bytes": text.len()}))
|
||||
}
|
||||
|
||||
fn preset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = std::path::PathBuf::from(str_req(p, "path")?);
|
||||
if crate::vfs::len(&path)? > MAX_FILE_BYTES {
|
||||
return Err(EngineError::Param(format!("{} is too large to be a brush set", path.display())));
|
||||
}
|
||||
let found = BrushLibrary::parse_file(&crate::vfs::read_to_string(&path)?)?;
|
||||
if found.is_empty() {
|
||||
return Err(EngineError::Param("the brush set has no brushes in it".into()));
|
||||
}
|
||||
let mut names = Vec::with_capacity(found.len());
|
||||
for b in found {
|
||||
match s.brushes.add_unique(b) {
|
||||
Ok(n) => names.push(n),
|
||||
Err(e) if names.is_empty() => return Err(e),
|
||||
// The library filled up part way: say what came in.
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
Ok(json!({"imported": names, "yours": s.brushes.user().len()}))
|
||||
}
|
||||
|
||||
/// Where a preview's stroke runs on a `w` × `h` area: an S across it, the pressure swelling
|
||||
/// in the middle (so pressure, curves and tapers show).
|
||||
pub fn preview_points(w: f32, h: f32) -> Vec<[f32; 3]> {
|
||||
(0..=48)
|
||||
.map(|i| {
|
||||
let t = i as f32 / 48.0;
|
||||
let x = w * (0.1 + 0.8 * t);
|
||||
let y = h * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin());
|
||||
[x, y, 0.25 + 0.75 * (t * std::f32::consts::PI).sin()]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A brush's stroke preview, drawn by the CPU renderer on a transparent `w` × `h` image (in
|
||||
/// pixels; `scale` pixels per point): the preview stroke in `color`, the brush's size kept
|
||||
/// where it fits (between 2 and 40 % of the height). `as_stroke` previews the Paint Brush.
|
||||
pub fn preview(preset: &BrushPreset, as_stroke: bool, w: u32, h: u32, scale: f32, color: Rgba) -> Result<anicraft_render::Pixmap> {
|
||||
let scale = if scale.is_finite() { scale.clamp(0.25, 8.0) } else { 1.0 };
|
||||
let (pw, ph) = (w as f32 / scale, h as f32 / scale);
|
||||
if !(pw >= 8.0 && ph >= 8.0 && w <= 4096 && h <= 4096) {
|
||||
return Err(EngineError::Param("a brush preview is 8 to 4096 pixels across".into()));
|
||||
}
|
||||
let mut doc = anicraft_doc::Document::default();
|
||||
doc.stage.width = pw.ceil() as u32;
|
||||
doc.stage.height = ph.ceil() as u32;
|
||||
let mut scratch = Session::new(doc);
|
||||
let mut params = BrushPreset { size: preset.size.clamp(2.0, (ph * 0.4).max(2.0)), ..preset.clone() }.params();
|
||||
params["points"] = json!(preview_points(pw, ph));
|
||||
params["color"] = json!(format!("#{:02x}{:02x}{:02x}", (color.r.clamp(0.0, 1.0) * 255.0).round() as u8, (color.g.clamp(0.0, 1.0) * 255.0).round() as u8, (color.b.clamp(0.0, 1.0) * 255.0).round() as u8));
|
||||
params["object"] = json!(true);
|
||||
params["as_stroke"] = json!(as_stroke);
|
||||
scratch.execute("draw.brush", ¶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)
|
||||
}
|
||||
@@ -65,7 +65,7 @@ fn add(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut k = Keyframe::new(0, frames);
|
||||
k.elements.push(Arc::new(Camera::rest(&s.doc.stage).to_element(el)));
|
||||
layer.keyframes = vec![Arc::new(k)];
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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;
|
||||
@@ -75,7 +75,7 @@ fn add(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn remove(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let id = camera_layer(s).ok_or_else(no_camera)?;
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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 {
|
||||
@@ -167,7 +167,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Selection, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, 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<CommandSpec> {
|
||||
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", 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 (the `snap` params of element.translate, raw.move_point, raw.move_handle and draw.snap 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,24 +23,34 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}),
|
||||
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.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} 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.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's effect is a tint", 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_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 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? (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"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))),
|
||||
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,9 +108,9 @@ 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<Paint>, stroke: Option<Stroke>, object: bool) -> Result<Value> {
|
||||
// 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)));
|
||||
// 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 && crate::merge::can_merge(stroke.as_ref());
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
@@ -108,7 +118,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2,
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
@@ -200,6 +233,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<LayerId> = match opt_u64(p, "layer")?.map(LayerId) {
|
||||
@@ -224,11 +258,17 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
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()
|
||||
@@ -266,7 +306,7 @@ fn pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 +317,7 @@ fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 +380,7 @@ fn shapes_mut(s: &mut Session) -> Result<Vec<&mut Shape>> {
|
||||
.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 +401,7 @@ fn set_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"ok": true}))
|
||||
}
|
||||
|
||||
fn set_stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn set_stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let remove = p.get("color").is_some_and(Value::is_null);
|
||||
let color = opt_color(p, "color")?;
|
||||
let width = opt_f32(p, "width")?;
|
||||
@@ -401,11 +441,86 @@ fn set_alpha(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Param("param 'alpha' must be between 0 and 1".into()));
|
||||
}
|
||||
for e in s.selected_elements_mut()? {
|
||||
e.color.alpha = a;
|
||||
e.color = e.color.with_alpha(a);
|
||||
}
|
||||
Ok(json!({"alpha": a}))
|
||||
}
|
||||
|
||||
/// 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),
|
||||
];
|
||||
|
||||
fn set_color_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<ColorStyle> = 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
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 Err(EngineError::Param("give a style, or a value to set".into())),
|
||||
(None, [one]) => Some(*one),
|
||||
(None, _) => return Err(EngineError::Param("these values belong to different styles: give one style's values".into())),
|
||||
};
|
||||
let mut first = None;
|
||||
for e in s.selected_elements_mut()? {
|
||||
let target = style.unwrap_or(e.color.style());
|
||||
if matches!(e.kind, ElementKind::Camera) && !matches!(target, ColorStyle::Tint | ColorStyle::None) {
|
||||
return Err(EngineError::State("the camera's colour effect is a tint".into()));
|
||||
}
|
||||
let mut fx = e.color.to_style(target);
|
||||
if let ColorEffect::Tint { color, .. } = &mut fx
|
||||
&& let Some(t) = tint
|
||||
{
|
||||
*color = t.with_alpha(1.0);
|
||||
}
|
||||
for &(i, v) in &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;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
e.color = fx.sanitized();
|
||||
first.get_or_insert(e.color);
|
||||
}
|
||||
Ok(first.map_or(Value::Null, |fx| crate::color_effect_json(&fx)))
|
||||
}
|
||||
|
||||
/// Most filters on one instance.
|
||||
const MAX_FILTERS: usize = 16;
|
||||
|
||||
@@ -555,6 +670,66 @@ fn set_symbol_kind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"symbol": ids.first().map(|i| i.0), "symbols": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "kind": format!("{kind:?}")}))
|
||||
}
|
||||
|
||||
/// The symbol a command means: `symbol`, else the selected instance's.
|
||||
fn selected_symbol(s: &Session, p: &Value) -> Result<SymbolId> {
|
||||
Ok(match opt_u64(p, "symbol")? {
|
||||
Some(id) => SymbolId(id),
|
||||
None => {
|
||||
// The symbol of the selected instance.
|
||||
let (layer, sel) = s.selection.first().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?;
|
||||
s.elements_on(layer)
|
||||
.iter()
|
||||
.find(|e| e.id == sel)
|
||||
.and_then(|e| match e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => Some(symbol),
|
||||
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<Value> {
|
||||
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.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<Value> {
|
||||
let name: String = str_req(p, "name")?.chars().take(128).collect();
|
||||
for e in s.selected_elements_mut()? {
|
||||
@@ -703,7 +878,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
inner.push(Arc::new(layer));
|
||||
}
|
||||
s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, 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);
|
||||
}
|
||||
@@ -721,7 +896,21 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut fresh_ids = Vec::new();
|
||||
let kf_elements: Vec<Arc<Element>> = 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)
|
||||
@@ -733,6 +922,25 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
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;
|
||||
@@ -750,16 +958,19 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
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()}))
|
||||
}
|
||||
@@ -771,7 +982,7 @@ const MAX_PLACE: usize = 1_000;
|
||||
/// 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.
|
||||
fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let items: Vec<LibraryItem> = 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()))?;
|
||||
@@ -873,6 +1084,7 @@ fn place_bitmap(s: &mut Session, bitmap: anicraft_doc::BitmapId, x: f32, y: f32)
|
||||
stroke: None,
|
||||
fill_rule: anicraft_geom::FillRule::NonZero,
|
||||
merge: false,
|
||||
warp: None,
|
||||
}),
|
||||
};
|
||||
s.editable_keyframe()?.elements.push(Arc::new(el));
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Vec<PathBuf>> {
|
||||
let list: Vec<PathBuf> = 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::<Result<_>>()?
|
||||
}
|
||||
(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<Value> {
|
||||
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::<Vec<_>>(), "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<Value> {
|
||||
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<anicraft_doc::ElementId> { 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::<Vec<_>>(), "items": items, "layers": 0, "files": files.len(), "layer": layer.0, "frame": frame, "keyframe_made": made}))
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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<Arc<Element>>,
|
||||
/// Each mesh used, with the shapes it made (the first is the rest mesh and the originals).
|
||||
states: Vec<(Mesh, Vec<Arc<Element>>)>,
|
||||
/// 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<crate::history::StateId>,
|
||||
}
|
||||
|
||||
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<Element>]) -> Option<Mesh> {
|
||||
let now: Vec<Option<&Arc<Element>>> = 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::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// 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<Element>]) -> 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<Value> {
|
||||
let here = s.layer;
|
||||
let sel = s.selection.on(here);
|
||||
let els = s.elements_on(here);
|
||||
let picked: Vec<Arc<Element>> = 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<Mesh> {
|
||||
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<Element> {
|
||||
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<Value> {
|
||||
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<Arc<Element>> = 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::<Result<_>>()?;
|
||||
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<Value> {
|
||||
let Some(env) = s.envelope.take() else { return Ok(json!({"closed": false})) };
|
||||
let ids: Vec<ElementId> = 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}))
|
||||
}
|
||||
@@ -247,7 +247,7 @@ fn faucet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 {
|
||||
@@ -283,7 +283,7 @@ fn erase_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let (scene, frame) = (s.scene, s.frame);
|
||||
let mut erased = 0;
|
||||
for (id, _) in &layers {
|
||||
let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).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();
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<u32> {
|
||||
@@ -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<Value> {
|
||||
pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
// 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());
|
||||
@@ -184,9 +216,11 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 +233,11 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<f32> {
|
||||
pub(crate) fn scale_param(p: &Value) -> Result<f32> {
|
||||
match opt_f32(p, "scale")? {
|
||||
None => Ok(1.0),
|
||||
Some(v) if v > 0.0 && v <= 8.0 => Ok(v),
|
||||
@@ -233,7 +268,7 @@ 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<Value> {
|
||||
pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 +292,20 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 +317,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 +332,13 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<anicraft_doc::ElementId> = 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());
|
||||
@@ -331,6 +384,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 +397,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
cl.keyframes = keys(els);
|
||||
stack.push(cl);
|
||||
}
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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 +423,74 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// An SVG drawing read from `path` (size-checked), with at least one shape.
|
||||
pub(crate) fn read_svg(path: &std::path::Path) -> Result<anicraft_svg::SvgImport> {
|
||||
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<Value> {
|
||||
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<anicraft_svg::ImportedElement>| -> Vec<Arc<anicraft_doc::Element>> {
|
||||
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<Arc<anicraft_doc::Element>>| {
|
||||
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<Arc<Layer>> = 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<u8>) -> Result<anicraft_svg::SvgImport> {
|
||||
@@ -383,6 +505,7 @@ fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec<u8>) -> 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 +562,16 @@ fn export_sprite_sheet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Frames render in parallel, then go onto the sheet in order.
|
||||
let doc = &s.doc;
|
||||
let frames: Vec<anicraft_render::Pixmap> = (from..=to).into_par_iter().map(|f| render(&anicraft_doc::evaluate(doc, f), &view).map(|(pm, _)| pm)).collect::<std::result::Result<_, _>>()?;
|
||||
// A publish counts the frames, and stops between them when cancelled (ADR 0060).
|
||||
let job = s.job.as_deref();
|
||||
let frames: Vec<anicraft_render::Pixmap> = (from..=to)
|
||||
.into_par_iter()
|
||||
.map(|f| {
|
||||
let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?;
|
||||
crate::publish::tick(job, 1)?;
|
||||
Ok(pm)
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
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 +699,7 @@ fn export_video(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
text
|
||||
});
|
||||
let doc = &s.doc;
|
||||
let job = s.job.as_deref();
|
||||
let mut written = 0u32;
|
||||
let mut failure: Option<EngineError> = None;
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
@@ -585,11 +718,22 @@ fn export_video(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
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 +760,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// 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<u32> = (from..=to).collect();
|
||||
for batch in frames.chunks(64) {
|
||||
@@ -624,6 +769,7 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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()}))
|
||||
}
|
||||
@@ -723,6 +869,7 @@ fn export_gif(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// 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<gif::Frame<'static>> = (from..to.saturating_add(1))
|
||||
.into_par_iter()
|
||||
@@ -732,6 +879,7 @@ fn export_gif(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut rgba = pm.to_rgba8();
|
||||
let mut frame = gif::Frame::from_rgba_speed(w, h, &mut rgba, 10);
|
||||
frame.delay = delay;
|
||||
crate::publish::tick(job, 1)?;
|
||||
Ok(frame)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
@@ -145,7 +145,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The pasted keys are its frames (no stray blank frame at 1).
|
||||
l.keyframes.clear();
|
||||
}
|
||||
crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).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<Value> {
|
||||
}
|
||||
keys.push(Arc::new(k));
|
||||
}
|
||||
let Some(layer) = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).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)?;
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Value> {
|
||||
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<Arc<Element>> = 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<Value> {
|
||||
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<ElementId> = 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<usize> = 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<ElementId> = members.iter().filter(|m| m.1).map(|m| m.0).collect();
|
||||
let mut selected: Vec<ElementId> = 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<Value> {
|
||||
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<Item = &'a Path>) -> 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<Path> {
|
||||
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<anicraft_doc::Paint>, stroke: Option<anicraft_doc::Stroke>, 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<Arc<Element>>) -> Option<Element> {
|
||||
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<Path> = 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<Value> {
|
||||
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<Element>)> = 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<Element>)> = Vec::new();
|
||||
match op {
|
||||
Op::Union => {
|
||||
let raw: Vec<Element> = shapes.iter().filter_map(|(_, e)| shape(e).map(|sh| as_raw(e, &sh))).collect();
|
||||
let parts: Vec<Part> = 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<Arc<Element>> = 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<usize> = 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::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// 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<Vec<anicraft_geom::Vec2>> = 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::<f64>() * 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
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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, as in Animate), 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<LayerId> {
|
||||
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<Value> {
|
||||
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<u64> = 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<Value> {
|
||||
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<Option<u8>> {
|
||||
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<Value> {
|
||||
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<Option<MaskMode>> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
let id = layer_id(s, p)?;
|
||||
// Every param is read (and checked) before anything changes.
|
||||
let name: Option<String> = 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<Value> {
|
||||
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;
|
||||
@@ -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<Value> {
|
||||
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<_>>(), 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}");
|
||||
}
|
||||
}
|
||||
@@ -182,7 +182,7 @@ fn new_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"folder": id.0, "name": name}))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let e = entry_of(p)?;
|
||||
if !s.doc.has_entry(e) {
|
||||
return Err(EngineError::State(format!("the Library has no {}", describe(e))));
|
||||
@@ -284,13 +284,19 @@ pub(crate) fn deletion(s: &Session, entries: &[LibraryEntry]) -> (Vec<LibraryIte
|
||||
/// 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<LibraryItem>) -> 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<LibraryItem>, 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 => false,
|
||||
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));
|
||||
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)) {
|
||||
@@ -302,6 +308,11 @@ fn strip(tl: &mut Timeline, gone: &HashSet<LibraryItem>) -> usize {
|
||||
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
|
||||
@@ -412,29 +423,14 @@ fn swap_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// 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<Value> {
|
||||
let to = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?);
|
||||
let Some(new) = s.doc.bitmap(to).map(|b| (b.name.clone(), b.width as f32, b.height as f32)) else {
|
||||
if s.doc.bitmap(to).is_none() {
|
||||
return Err(EngineError::State(format!("no bitmap with id {}", to.0)));
|
||||
};
|
||||
}
|
||||
let sizes: std::collections::HashMap<BitmapId, (String, f32, f32)> = 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()? {
|
||||
let ElementKind::Shape(sh) = &mut e.kind else { continue };
|
||||
let Some(Paint::Bitmap { bitmap, repeat, matrix }) = &mut sh.fill else { continue };
|
||||
let old = *bitmap;
|
||||
*bitmap = to;
|
||||
swapped += 1;
|
||||
if old == to {
|
||||
continue;
|
||||
}
|
||||
if let Some((name, w, h)) = sizes.get(&old)
|
||||
&& !*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);
|
||||
}
|
||||
if swap_bitmap_of(e, to, &sizes) {
|
||||
swapped += 1;
|
||||
}
|
||||
}
|
||||
if swapped == 0 {
|
||||
@@ -443,6 +439,32 @@ fn swap_bitmap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<BitmapId, (String, f32, f32)>) -> 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;
|
||||
|
||||
@@ -68,17 +68,19 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
fn symbol_refs(e: &Element) -> Option<SymbolId> {
|
||||
/// The symbols `e` places: itself, or what is inside it as a group (ADR 0073).
|
||||
fn symbol_refs(e: &Element) -> Vec<SymbolId> {
|
||||
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<Arc<Symbol>> {
|
||||
let mut seen: HashSet<SymbolId> = HashSet::new();
|
||||
let mut stack: Vec<SymbolId> = roots.iter().filter_map(symbol_refs).collect();
|
||||
let mut stack: Vec<SymbolId> = 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 {
|
||||
@@ -87,7 +89,7 @@ pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec<Arc<Symbol>
|
||||
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());
|
||||
@@ -183,7 +185,7 @@ fn layer_targets(s: &mut Session, src: &[(LayerId, String)]) -> Result<Vec<Layer
|
||||
k.duration = s.frame_count().max(1);
|
||||
}
|
||||
layer.color = crate::cmds_timeline::layer_color(count + 1);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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);
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
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, Pin, PinError, Property, Props};
|
||||
use anicraft_doc::{Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
@@ -23,7 +23,7 @@ use std::sync::Arc;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("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), 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, its anchors pinned to frames (pins) and where the object is", false, info),
|
||||
@@ -75,7 +75,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) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).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 };
|
||||
@@ -111,7 +111,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;
|
||||
@@ -120,8 +120,8 @@ 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.style().is_none());
|
||||
let tracks_color = m.tracks.iter().any(|t| t.property.style().is_some());
|
||||
let mut base = after;
|
||||
// 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) {
|
||||
@@ -131,8 +131,9 @@ 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);
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
// 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<Value> {
|
||||
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<Value> {
|
||||
}
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
&& 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<Value> {
|
||||
}
|
||||
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<GradientStop> {
|
||||
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<Option<Vec<GradientStop>>> {
|
||||
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<Rgba>,
|
||||
stops: Option<Vec<GradientStop>>,
|
||||
spread: Option<Spread>,
|
||||
linear_rgb: Option<bool>,
|
||||
focal: Option<f32>,
|
||||
bitmap: Option<BitmapId>,
|
||||
}
|
||||
|
||||
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<Paint> {
|
||||
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<GradientStop>, 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<Value> { 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<Option<f32>> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
let sel: std::collections::HashSet<ElementId> = 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<Affine> {
|
||||
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<Option<Vec2>> {
|
||||
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<Affine> {
|
||||
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<f32> {
|
||||
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<f32> {
|
||||
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<Value> {
|
||||
let focal = opt_focal(p)?;
|
||||
let only = opt_u64(p, "element")?.map(ElementId);
|
||||
let targets: std::collections::HashSet<ElementId> = 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<Value> {
|
||||
let on = opt_bool(p, "on")?.unwrap_or(!s.style.lock_fill);
|
||||
s.style.lock_fill = on;
|
||||
Ok(json!({"on": on}))
|
||||
}
|
||||
@@ -130,6 +130,7 @@ fn shape_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Shape, Affine
|
||||
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())),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,16 +31,31 @@ 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"];
|
||||
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" | "frames.cut" | "frames.copy" | "frames.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"),
|
||||
// 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"),
|
||||
"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"),
|
||||
},
|
||||
@@ -78,7 +93,7 @@ fn document_view(s: &Session) -> Value {
|
||||
.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,
|
||||
@@ -126,7 +141,8 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result<Value, String>
|
||||
"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) => {
|
||||
@@ -146,6 +162,10 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result<Value, String>
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -364,7 +364,7 @@ fn shared_points(s: &mut Session, at: Vec2) -> Result<Vec<(ElementId, usize)>> {
|
||||
fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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)? {
|
||||
@@ -398,7 +398,7 @@ fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => 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()?;
|
||||
@@ -440,23 +440,9 @@ fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ----- 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)]
|
||||
@@ -492,30 +478,35 @@ fn targets(els: &[Arc<Element>], 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<Element>], 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<Element>], 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 {
|
||||
@@ -526,19 +517,23 @@ fn snap_point(els: &[Arc<Element>], 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))
|
||||
}
|
||||
|
||||
/// Where a point drawn at `p` snaps (the Line, Rectangle, Oval, PolyStar and Pen tools, ADR
|
||||
/// 0045): the nearest anchor within `radius`, else the nearest point on a line or fill edge, of
|
||||
/// what the stage shows near it.
|
||||
pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32) -> Option<(Vec2, SnapTo)> {
|
||||
/// 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() {
|
||||
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;
|
||||
}
|
||||
@@ -551,14 +546,23 @@ pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32) -> Option<(Vec2, Sna
|
||||
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)));
|
||||
}
|
||||
snap_to(&t, p, radius).map(|(q, k, _)| (q, k))
|
||||
resolve(s, p, 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`.
|
||||
/// 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<Vec2>) -> Option<(Vec2, Vec2, SnapTo)> {
|
||||
let mut own: Vec<Vec2> = 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)));
|
||||
@@ -575,12 +579,15 @@ pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option<Vec2>) -> Op
|
||||
return None;
|
||||
}
|
||||
// What stays put on the layers the selection is on (ADR 0044).
|
||||
let rest: Vec<Arc<Element>> = 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<Arc<Element>> = 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))
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Snap Point",
|
||||
"",
|
||||
None,
|
||||
"{x, y, snap} where a point drawn at (x, y) snaps while Snap to Objects is on: the nearest anchor within `snap` stage units, else the nearest point on a line or fill edge; returns {x, y, snapped: {x, y, to} | null}",
|
||||
"{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,
|
||||
),
|
||||
@@ -238,8 +238,9 @@ fn convert_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn snap_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0));
|
||||
Ok(match snap_drawn(s, at, radius) {
|
||||
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}),
|
||||
})
|
||||
|
||||
@@ -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<RecentFile>,
|
||||
}
|
||||
|
||||
/// 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<Vec<u8>> {
|
||||
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<usize> {
|
||||
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<RecentFile>, Vec<RecentFile>) = 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<CommandSpec> {
|
||||
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<PathBuf> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
let files: Vec<Value> = 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<String> {
|
||||
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::<RecentFiles>(raw).unwrap().sanitized();
|
||||
assert_eq!(paths(&r), ["*a", "b"]);
|
||||
let many: Vec<RecentFile> = (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))
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ pub(crate) fn target_scene(s: &Session, p: &Value) -> Result<usize> {
|
||||
}
|
||||
|
||||
/// 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));
|
||||
@@ -127,7 +127,7 @@ fn duplicate_scene(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<FrameScript>) -> 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<SymbolId>) -> Option<TimelineRef> {
|
||||
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<TimelineRef>, c: &CompileResult) -> Vec<Problem> {
|
||||
match (which, c) {
|
||||
(Some(w), Ok(c)) => link_problems(doc, w, c),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn check(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = str_req(p, "text")?;
|
||||
if text.len() > actions::MAX_SOURCE_BYTES {
|
||||
@@ -62,10 +83,11 @@ fn check(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
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::<Vec<_>>());
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 {
|
||||
|
||||
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Value> {
|
||||
pub(crate) fn import_to_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
if is_sound(&path) {
|
||||
let id = add_sound(s, &path, opt_str(p, "name")?)?;
|
||||
@@ -115,7 +115,11 @@ fn import_to_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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,
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// 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<Option<Swatch>> {
|
||||
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<usize> {
|
||||
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<Swatch> {
|
||||
Arc::make_mut(&mut s.doc.swatches)
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let v: Vec<Value> = 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<Swatch> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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::<Vec<_>>()});
|
||||
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<Vec<Swatch>> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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()}))
|
||||
}
|
||||
@@ -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:
|
||||
//! `<folder>/<category>/<name>.anicraft` and `<name>.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<CommandSpec> {
|
||||
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 <folder>/<category>/<name>.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.
|
||||
fn clean_name(raw: &str, what: &str) -> Result<String> {
|
||||
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<PathBuf> {
|
||||
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<PathBuf>,
|
||||
}
|
||||
|
||||
/// The user's templates, by category then name (ignoring case).
|
||||
pub fn user_templates(folder: &Path) -> Vec<UserTemplate> {
|
||||
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<Vec<u8>> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
let builtin: Vec<Value> = 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<Value> = 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<PathBuf> {
|
||||
template_path(Path::new(str_req(p, "folder")?), category(p)?, str_req(p, "name")?)
|
||||
}
|
||||
|
||||
fn save_as_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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()}))
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
//! 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;
|
||||
@@ -32,9 +40,21 @@ impl Default for TextStyle {
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
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))),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -130,22 +150,355 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option<f32>) -> 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<anicraft_text::Layout, anicraft_text::TextError> {
|
||||
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<String>)> {
|
||||
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<String>, 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<f32>) -> Result<(TextBlock, Option<String>, 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<String>, 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<Value> {
|
||||
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<ElementId> = 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<Path> = 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<Value> {
|
||||
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<Option<TextKind>> {
|
||||
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<Value> {
|
||||
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<Option<f32>> {
|
||||
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::<String>());
|
||||
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<Value> {
|
||||
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());
|
||||
@@ -158,21 +511,23 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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;
|
||||
}
|
||||
@@ -194,5 +549,5 @@ fn fonts(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// 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<Path> = 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 }
|
||||
}
|
||||
@@ -9,10 +9,10 @@ use std::sync::Arc;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("timeline.insert_frame", "Frame", "Insert/Timeline", Some("F5"), "{layer? | layers?: [..], frame?, count?}", true, insert_frame as crate::RunFn),
|
||||
c("timeline.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.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),
|
||||
@@ -58,7 +58,7 @@ fn toggle_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ty = if is_mask { "normal" } else { "mask" };
|
||||
set_type(s, id, ty)?;
|
||||
if !is_mask {
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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)
|
||||
@@ -100,7 +100,7 @@ fn add_motion_guide(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(k) = guide.keyframe_mut(0) {
|
||||
k.duration = s.frame_count().max(1);
|
||||
}
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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 +126,8 @@ fn set_layer_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(layer_type_json(s, id))
|
||||
}
|
||||
|
||||
fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> {
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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,7 +161,7 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn layer_type_json(s: &Session, id: LayerId) -> Value {
|
||||
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);
|
||||
@@ -232,19 +232,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<Value> {
|
||||
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::<Vec<_>>()});
|
||||
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<LayerId> {
|
||||
let tl = s.timeline();
|
||||
let ids: Vec<LayerId> = 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<()> {
|
||||
@@ -353,7 +388,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
// 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 +428,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
}
|
||||
|
||||
fn insert_keyframe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 +436,38 @@ fn insert_keyframe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
insert_keyframe_at(layer, frame, true)?;
|
||||
}
|
||||
}
|
||||
Ok(json!({"keyframe": frame}))
|
||||
advanced(s, p, frame)
|
||||
}
|
||||
|
||||
fn insert_blank_keyframe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<u32> {
|
||||
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<Value> {
|
||||
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
|
||||
@@ -656,8 +714,9 @@ fn new_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// 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<Value> {
|
||||
@@ -688,7 +747,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result<Value> {
|
||||
k.duration = s.frame_count().max(1);
|
||||
}
|
||||
layer.color = layer_color(n);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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;
|
||||
@@ -709,7 +768,7 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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;
|
||||
@@ -774,7 +833,7 @@ fn select_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// 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<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
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)) {
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Value> {
|
||||
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::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn accuracy(p: &Value, grid: bool) -> Result<Option<Accuracy>> {
|
||||
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<Option<f32>> {
|
||||
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<Value> {
|
||||
// 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<Value> {
|
||||
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<Guide>> {
|
||||
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<f32> {
|
||||
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<usize> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
let n = s.guides().len();
|
||||
if n > 0 {
|
||||
guides_mut(s)?.clear();
|
||||
}
|
||||
Ok(json!({"cleared": n}))
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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<ElementId> {
|
||||
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<Element>)> {
|
||||
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<u32> {
|
||||
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<Warp> {
|
||||
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<T>(s: &mut Session, layer: LayerId, frame: u32, id: ElementId, edit: impl FnOnce(&mut Shape, &Affine) -> Result<T>) -> Result<T> {
|
||||
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<u32>, id: ElementId, rest: &Arc<Path>, resolution: u32, mut f: impl FnMut(&mut Warp, &mut Shape)) -> Result<usize> {
|
||||
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<Element>| 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<u32> {
|
||||
s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).map(|k| k.start)
|
||||
}
|
||||
|
||||
fn resolution_param(p: &Value) -> Result<Option<u32>> {
|
||||
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<u32>) -> 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<Arc<Path>> = 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<Element>| 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<Value> {
|
||||
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<Vec2> {
|
||||
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<Value> {
|
||||
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<PinId> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> = 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,
|
||||
}))
|
||||
}
|
||||