mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-28 09:09:32 +01:00
chore: merge main into fix/backlog-timeline-panels
This commit is contained in:
commit
d8a2e32203
73 files changed
+4156
-427
No files matched your search
@@ -63,42 +63,42 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119
|
||||
## This repository
|
||||
<!-- craft-agents:end -->
|
||||
|
||||
AniCraft is an open-source, native, clean-room 2D animation studio (Adobe Animate class), written in Rust only (egui/eframe UI). The product name is written **AniCraft**; machine names are lowercase (`anicraft-*`). `docs/` has the design: ADRs in `docs/adr/`, UI guidelines, the prioritised backlog and status in `docs/roadmap.md` (a guideline, not a timeline: ADR 0125), and parity with the reference app in `docs/parity.md`.
|
||||
AniCraft is an open-source, native, clean-room 2D animation studio in Rust only (egui/eframe UI). The product name is written **AniCraft**; machine names are lowercase (`anicraft-*`). The design is in `docs/`: ADRs in `docs/adr/`, UI guidelines, the backlog and status in `docs/roadmap.md` (a guideline, not a timeline: ADR 0125), and parity in `docs/parity.md`.
|
||||
|
||||
## Workspace map
|
||||
|
||||
```text
|
||||
crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing
|
||||
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)
|
||||
crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009)
|
||||
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/guide/serve/mcp
|
||||
src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
|
||||
crates/geom L0 Vec2, Affine, Rect, Path, flattening, hit testing
|
||||
crates/xml L0 Bounded XML reader shared by the XFL and SVG importers
|
||||
crates/plugins L0 Sandboxed WebAssembly plug-ins: wasmi host, ABI v1, limits (ADR 0017)
|
||||
crates/audio L0 WAV, Ogg Vorbis and MP3 decoding, mixing, resampling, peaks (ADR 0020)
|
||||
crates/actions L0 Timeline action IR, button events, frame scripts (ADR 0024)
|
||||
crates/guide L0 docs/guide as a bundled HTML book, with link checks (ADR 0069)
|
||||
crates/doc L1 Document model, easing, timeline evaluation, player, sample scene
|
||||
crates/text L1 System fonts, shaping, line layout into outlines (ADR 0012)
|
||||
crates/render L2 CPU oracle renderer (coverage, paints, strokes, PNG)
|
||||
crates/xfl L2 XFL/FLA import with its own XML and zip readers (ADR 0009)
|
||||
crates/svg L2 SVG import; clips and masks become mask layers
|
||||
crates/engine L3 Session, undo, command registry, .anicraft format
|
||||
crates/gpu L3 wgpu stage renderer, the default (ADR 0019, 0029, 0032)
|
||||
crates/cli L4 anicraft-cli, including serve and mcp
|
||||
src/ L5 egui shell: app, menus, stage, timeline, panels, theme
|
||||
```
|
||||
|
||||
A crate depends only on lower layers, and nothing below `src/` uses egui, eframe or winit. `src/architecture_tests.rs` checks both, and that this map lists every crate with its layer (a new crate needs a row here and in its `LAYERS` table).
|
||||
A crate depends only on lower layers; nothing below `src/` uses egui, eframe or winit. `src/architecture_tests.rs` checks both, and that this map lists every crate with its layer (a new crate needs a row here and in its `LAYERS` table).
|
||||
|
||||
## Conventions
|
||||
|
||||
- New behaviour is a `CommandSpec` in `crates/engine/src/cmds_*.rs`; menus and shortcuts come from the registry. `panic_hunt_every_command` fuzzes every command. A new command namespace needs a plug-in policy (`plugin_may_call` in `crates/engine/src/cmds_plugin.rs`).
|
||||
- Commands read and write files through `engine::vfs`, never `std::fs`: `vfs` is where an agent's automation roots are applied (ADR 0124, `engine::access`). A command that takes a path gets a row in `access::PATH_PARAMS` (`every_command_with_a_path_parameter_is_listed` checks it), and code that hands a path to something else (ffmpeg, another crate's reader) calls `access::check` first.
|
||||
- `doc::evaluate` is pure: time is a function, and animation never mutates the document. The CPU renderer in `crates/render` is the oracle the GPU renderer is tested against.
|
||||
- Text goes through `theme::Type` roles (`guidelines_tests` checks it; `docs/ui-guidelines.md`). Interface text uses `tr!`, `trn!` and `tr_noop!` (ADR 0040, `docs/localisation.md`; check with `--lang pseudo`). The app-local craft-i18n catalog parser stays until ADR 0040's cutover.
|
||||
- OS-specific code lives in `src/platform.rs`; shortcut text goes through `platform::shortcut_label`.
|
||||
- `unsafe_code = "forbid"`; no workspace module allows `unsafe`. The plug-in SDK in `examples/plugins/sdk` is outside the workspace and uses `unsafe` for the WebAssembly host calls.
|
||||
- `deny.toml` is the dependency policy (permissive licences; craft-libs is the one allowed Git source, pinned by `rev`). Assets get a row in `ATTRIBUTION.md` with licence text under `licenses/`; fonts come from craft-fonts through `CRAFT_FONTS_DIR`. Legal notes: `docs/legal/compliance.md`.
|
||||
- `scripts/git-hooks` refuses commits on `main` (`git config core.hooksPath scripts/git-hooks`). Branches are `feat/`, `fix/`, `docs/` or `m<N>/<topic>`; commit subjects use conventional prefixes (`feat(render): ...`), and milestone work ends them with `(M5)`. Credits: `AUTHORS.md`.
|
||||
- Build footprint settings (one `target/`, incremental off): `docs/development.md`.
|
||||
- New behaviour is a `CommandSpec` in `crates/engine/src/cmds_*.rs`; menus and shortcuts come from the registry, and `panic_hunt_every_command` fuzzes every command. A new namespace needs a plug-in policy (`plugin_may_call` in `cmds_plugin.rs`).
|
||||
- Commands use `engine::vfs`, never `std::fs`: it applies an agent's automation roots (ADR 0124, `engine::access`). A command with a path parameter gets a row in `access::PATH_PARAMS` (checked by `every_command_with_a_path_parameter_is_listed`); code handing a path to something else (ffmpeg, another crate's reader) calls `access::check` first.
|
||||
- `doc::evaluate` is pure: animation never mutates the document. `crates/render` is the oracle the GPU renderer is tested against.
|
||||
- Text uses `theme::Type` roles (`guidelines_tests`; `docs/ui-guidelines.md`). Interface text uses `tr!`, `trn!` and `tr_noop!` (ADR 0040, `docs/localisation.md`; check with `--lang pseudo`); the app-local craft-i18n catalog parser stays until ADR 0040's cutover.
|
||||
- OS-specific code is in `src/platform.rs`; shortcut text goes through `platform::shortcut_label`.
|
||||
- `unsafe_code = "forbid"`: no workspace module allows `unsafe`. The plug-in SDK in `examples/plugins/sdk` is outside the workspace and uses it for WebAssembly host calls.
|
||||
- `deny.toml` is the dependency policy (permissive licences; craft-libs, pinned by `rev`, is the one Git source). Assets get an `ATTRIBUTION.md` row with licence text in `licenses/`; fonts come from craft-fonts via `CRAFT_FONTS_DIR`. Legal notes: `docs/legal/compliance.md`.
|
||||
- `scripts/git-hooks` refuses commits on `main` (`git config core.hooksPath scripts/git-hooks`). Branches are `feat/`, `fix/`, `docs/` or `m<N>/<topic>`; subjects use conventional prefixes (`feat(render): ...`), and milestone work ends with `(M5)`. Credits: `AUTHORS.md`.
|
||||
- Build footprint (one `target/`, incremental off): `docs/development.md`.
|
||||
|
||||
## Checks
|
||||
|
||||
For the crates you changed: `cargo clippy -p <crate> --all-targets -- -D warnings` and `cargo test -p <crate>`. For the shell, `cargo test` and `cargo clippy --all-targets`. When dependencies change: `cargo deny check licenses bans sources`. For UI changes: `cargo run -- --screenshot shots/now.png` and look at the PNG.
|
||||
For the crates you changed: `cargo clippy -p <crate> --all-targets -- -D warnings` and `cargo test -p <crate>`. For the shell: `cargo test` and `cargo clippy --all-targets`. When dependencies change: `cargo deny check licenses bans sources`. For UI changes: `cargo run -- --screenshot shots/now.png`, then look at the PNG.
|
||||
@@ -134,6 +134,9 @@ OR Apache-2.0) is noted in the table.
|
||||
| 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). |
|
||||
| Text-field members in the ActionScript subset: `htmlText` (the tags and attributes Flash text fields accept, relative font sizes, entities), `restrict` notation (ranges, `^`, escapes), `maxChars`, `Event.CHANGE` on user edits only | `crates/doc/src/html_text.rs`, `crates/doc/src/field.rs`, `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | Adobe, *ActionScript 3.0 Reference for the Adobe Flash Platform* (`flash.text.TextField`: `htmlText`, `restrict`, `maxChars`; `flash.events.Event.CHANGE`), public documentation; WHATWG HTML (named and numeric character references) | Behaviour learned from public documentation only; own implementation (ADR 0107). |
|
||||
| Text that mixes directions: embedding levels, line breaking before reordering, reordering each line (rules L1 and L2), where a caret stands at a change of direction | `crates/text/src/lines.rs`, `crates/text/src/rich.rs`, `crates/doc/src/field.rs` | The Unicode Consortium, *Unicode Standard Annex #9: Unicode Bidirectional Algorithm*, <https://www.unicode.org/reports/tr9/>; levels and reordering by storytold/craft-libs `craft-text` (MIT OR Apache-2.0) on `unicode-bidi` (MIT OR Apache-2.0) | Open standard. Layout on shaped clusters is our own (ADR 0130); the first version was outside PR #39 by SoldierPePe. |
|
||||
| Fallback faces for letters a font lacks (cluster by cluster after shaping) | `crates/text/src/fallback.rs` | Common practice in text layout engines, described in the HarfBuzz manual ("Shaping and shape plans", clusters) and the OpenType specification (`cmap`, glyph 0 as "notdef") | Own implementation (ADR 0130); the family list and the rules for marks and invisible characters are from outside PR #40 by SoldierPePe. The family names are names only: no font is bundled. |
|
||||
| Fonts made in memory for tests (boxes for letters) | `crates/text/src/testfont.rs` | Microsoft and Adobe, *OpenType specification*: "Font file", `head`, `hhea`, `maxp`, `hmtx`, `cmap` (format 12), `loca`, `glyf`, `name`, `post` | Open specification. Written from the table descriptions; test code only, no font file is committed. |
|
||||
| Font embedding permissions (`fsType`: restricted licence, preview and print, editable, no subsetting, bitmap embedding only) | `crates/text/src/embed.rs` | Microsoft and Adobe, *OpenType specification*, `OS/2` table (`fsType`); the three-case rule proposed in storytold/craft-libs issue #82 | Open specification. Own implementation (ADR 0107). |
|
||||
| Lines of text on curves parallel to a path (offset curves measured by arc length) | `crates/text/src/lib.rs` | Standard differential geometry of parallel (offset) curves; public domain mathematics | Own implementation (ADR 0107). |
|
||||
| Lottie keyframes and eases (hold keys, cubic Bézier eases with `o`/`i` handles, split position, shape keyframes, group transform order T · R · Skew · S · T(−anchor)); subdividing a cubic at its midpoint (de Casteljau) | `crates/render/src/lottie.rs`, `crates/render/src/lottie_keys.rs`, `crates/engine/tests/lottie_player` | The public Lottie JSON format description (Lottie Animation Community); W3C CSS Easing Functions Level 1 (`cubic-bezier`); de Casteljau's algorithm (public domain mathematics) | Open specifications. Own implementation (ADR 0089). |
|
||||
|
||||
+9
-1
@@ -13,6 +13,11 @@ People who have contributed to AniCraft. The repository starts from one initial
|
||||
* Mex (MMexicann): SVG path data, `Math.round` and `Math.min`/`max` signed zeros, affine inverses, documentation.
|
||||
* NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test; Trace Bitmap and Convert to Bitmap (#489).
|
||||
* jayzed80: flipped scales in Properties, CLI subcommand help and frame numbering; copy, cut and paste keys on the stage; the frame keys after a click on the ruler (#195).
|
||||
* Mex (MMexicann): SVG path data, `Math.round` and `Math.min`/`max` signed zeros, affine inverses, documentation; preset files with a byte-order mark, oversized indices, CLI numbers, guide anchors and the Windows build scripts.
|
||||
* NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test; eight-point ovals, smooth anchors that stay smooth when a segment is bent, and non-finite numbers in transforms, paths, scripts and saved files; the length of very large vectors, a hex colour form that keeps alpha, and a test for SVG path numbers past `f32` (#142, #233, #130).
|
||||
* Mex (MMexicann): SVG path data, `Math.round` and `Math.min`/`max` signed zeros, affine inverses, documentation.
|
||||
* NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test; Trace Bitmap and Convert to Bitmap (#489).
|
||||
* jayzed80: flipped scales in Properties, CLI subcommand help and frame numbering; copy, cut and paste keys on the stage; shape-tween outlines at junctions, with dashes and width profiles, and along a motion guide (#238).
|
||||
* Efe Şahinbaş (MacallanTheRoot): the MCP render caption.
|
||||
* nocturney: localisation tests (Hebrew plurals, the product name).
|
||||
* Vincent Agerbech (va-moviestarplanet): XFL group placement.
|
||||
@@ -24,6 +29,9 @@ People who have contributed to AniCraft. The repository starts from one initial
|
||||
* Oskar Raszkiewicz (oskarraszkiewicz): the macOS menu row.
|
||||
* Wilder Ccasa (Call4han): fitting the stage by double-clicking the Hand tool (#457).
|
||||
* Dylan M. Taylor (dylanmtaylor): no caller-chosen ffmpeg over serve and MCP, bounded request lines, safer XFL folder reads.
|
||||
* Agapenor (Agapenordev): XFL folder paths with backslashes, the frame limit on loaded documents, the report behind the evaluation allowance.
|
||||
* Agapenor (Agapenordev): XFL folder paths with backslashes, the frame limit on loaded documents, the report behind the evaluation allowance and what it counts as work (#13).
|
||||
* rcoenen: Animate's shape hints (`morphHintsList`), default text line spacing and default dash gap, from files Animate saved.
|
||||
* Hagai Baram (hrb9): the Hebrew fallback face, `iw` read as Hebrew, and right-to-left language detection (#486).
|
||||
* SoldierPePe: text that mixes directions and letters from a fallback face (#39, #40).
|
||||
* Hagai Baram (hrb9): the Hebrew fallback face, `iw` read as Hebrew, and right-to-left language detection, private-use tags included (#486).
|
||||
* FredApps: a test that linked artwork survives SVG export and re-import (#500).
|
||||
@@ -23,6 +23,76 @@
|
||||
under the tools opens its colour picker (#246), and the docks keep their size while the
|
||||
pointer moves over them at every interface scale (#159, not reproduced; the issue stays
|
||||
open for a retest).
|
||||
* **Text reads right: mixed directions, and letters from a fallback face** (M5, backlog P-008,
|
||||
ADR 0130). With outside pull requests #39 and #40 by SoldierPePe, whose commits are merged
|
||||
here and rebuilt on styled text.
|
||||
* **Hebrew and Arabic with Latin words and numbers read the right way round.** Text follows
|
||||
the Unicode bidi algorithm: a number or a Latin word inside right-to-left text keeps its
|
||||
order ("2026" was drawn as "6202"), a right-to-left paragraph runs from the right, and a
|
||||
wrapped one starts with its first words. Styled runs keep their style, colour and underline
|
||||
through the reordering. It is the same in static text, text on a path and text fields, and
|
||||
so in every export.
|
||||
* **Letters your font doesn't have come from another font** instead of showing as boxes:
|
||||
Arabic in Consolas, Japanese in Arial. The rest of the block keeps your font, a letter
|
||||
takes its marks along, and the line keeps its height. `text.create` and `text.edit` say
|
||||
which font lent the letters, and how many characters no installed font has.
|
||||
* **In a text field in Test Movie, Left and Right move the caret the way they point** through
|
||||
text that mixes directions, and a selection across a change of direction is highlighted in
|
||||
its separate stretches.
|
||||
* Arabic letters join across a change of style inside a word. Letter spacing follows a
|
||||
letter with its marks instead of each glyph. A stretch of text in another script is shaped
|
||||
with that script's rules.
|
||||
* Not yet: a direction setting for a paragraph (it is the first letter's) and alignment to
|
||||
its start; the typing field beside the stage still shows right-to-left text unordered
|
||||
while the block on the stage is right; right-to-left text a script sets in the HTML page.
|
||||
* **A long Brush stroke no longer freezes the window** (M8, ADR 0129, #519, backlog P-003).
|
||||
* A stroke drawn for a long time, over itself again and again, took longer to turn into a
|
||||
shape the longer it was, and a part of it selected over the rest cost seconds on every
|
||||
frame. The outline's tracing is now bounded however long the stroke is (a fast scribble of
|
||||
60 000 samples: 1.5 s before, 0.4 s now, of which the trace is at most 0.3 s), and the
|
||||
selection's stipple is cut row by row (seconds a frame before, a few milliseconds now).
|
||||
* In the editor a long stroke's outline is traced off the window's thread: the stroke stays
|
||||
on the stage as you drew it, you can go on painting at once, and it becomes a shape, in
|
||||
one undo step, a moment later. Anything else you do waits for it first, so strokes and
|
||||
edits always happen in the order you made them.
|
||||
* `anicraft-cli bench --stroke <samples>` measures a long stroke (painting, picking, moving,
|
||||
the merge on deselect), and `bench --stroke-file <file>` a document's own artwork.
|
||||
* Not yet: the Subselection tool, the Paint Bucket and the shape tools' snapping are still
|
||||
slow on a single shape of ten thousand points and more.
|
||||
* **Free Transform on a skewed symbol** (M8, #117, backlog P-005): scaling from a corner,
|
||||
turning from outside it and skewing from an edge are now covered end to end by a test on a
|
||||
slanted instance (the fix itself came with ADR 0111). The guide says what a handle scales
|
||||
from (#193). Rotation on Windows and FreeBSD (#479) could not be reproduced on Windows 10
|
||||
and stays open.
|
||||
* **Documents too large to draw, shape-tween outlines on a guide, and small fixes from outside**
|
||||
(M8, backlog P-002, P-011 and P-012; ADR 0128).
|
||||
* **Security: no nesting of symbols hangs AniCraft.** The allowance of work one frame has
|
||||
(a million elements) now also counts the layers looked at, the size of each outline and
|
||||
how far into a long library a symbol is, so a file can multiply none of them by nesting.
|
||||
**Test Movie** has an allowance for each step: it used to look at every element of up to
|
||||
10,000 instances after every change, and give every button a whole frame's allowance at
|
||||
every move of the pointer (ideas from Agapenor's #13).
|
||||
* **A frame with artwork left out says so.** The status bar tells you once ("Some artwork
|
||||
on this frame is left out…"), Test Movie's Output panel says why a
|
||||
step stopped, and the commands that write frames (PNG, SVG, sequences, sprite sheet, GIF,
|
||||
animated PNG and WebP, video) add `"left_out": true` and a `"warning"` to their result
|
||||
instead of passing a partial picture off as the whole one. `anicraft-cli info` and the MCP
|
||||
`anicraft_render` caption say it too.
|
||||
* **Shape tweens along a motion guide keep their outlines** (jayzed80, #238). A raw shape's
|
||||
line pieces used to follow the guide one by one and cross the fill. Each piece now rides
|
||||
with the fill it edges, also when both keyframes have as many pieces; an edge two fills
|
||||
share goes with the lower fill. Outlines are no longer joined through a point where three
|
||||
or more lines meet, dashed and variable-width outlines keep their pieces, and a piece
|
||||
selected on a keyframe stays selected through the tween.
|
||||
* **Colours:** the Eyedropper's result names the colour it picked with its opacity
|
||||
(`#rrggbbaa`); `Rgba::to_hex_alpha` is the hex form that reads back as the same colour,
|
||||
and `to_hex` stays six digits for the exporters (NetterSilver, #233).
|
||||
* **Never crash:** the length of a vector with components past 1.8e19 is no longer infinite,
|
||||
so its direction is no longer lost (NetterSilver, #142; taken only out of range, so drawing
|
||||
costs the same); a private-use language tag such as `x-Arab` is not read as right-to-left
|
||||
(Hagai Baram, #486).
|
||||
* **Tests:** SVG path numbers past `f32` are refused (NetterSilver, #130); linked artwork
|
||||
survives SVG export and re-import with its link sanitised (FredApps, #500).
|
||||
* **Reliability pass on the tests** (M8). Twelve runs of the whole suite after the review's
|
||||
fixes (the picture cache race and the split command fuzz) found no further flaky test. Tests
|
||||
that wait for another thread (a save, a freed port, a GPU start) now give it a minute instead
|
||||
|
||||
Generated
+23
@@ -317,6 +317,7 @@ dependencies = [
|
||||
"anicraft-svg",
|
||||
"anicraft-text",
|
||||
"anicraft-xfl",
|
||||
"anicraft-xml",
|
||||
"craft-anicraft-format",
|
||||
"craft-csv",
|
||||
"craft-gif",
|
||||
@@ -412,6 +413,7 @@ name = "anicraft-text"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anicraft-geom",
|
||||
"craft-text",
|
||||
"fontdb",
|
||||
"harfrust",
|
||||
"skrifa",
|
||||
@@ -1404,6 +1406,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
|
||||
dependencies = [
|
||||
"unicode-bidi",
|
||||
"unicode-bidi-mirroring",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
@@ -5225,6 +5236,18 @@ version = "2.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi-mirroring"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-general-category"
|
||||
version = "1.1.0"
|
||||
|
||||
@@ -45,6 +45,9 @@ craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c5
|
||||
# bounded record parser. The same reviewed commit as craft-mime and craft-gif.
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" }
|
||||
# The Unicode bidi algorithm (UAX #9) for text that mixes directions (ADR 0130): only the `bidi`
|
||||
# module, which brings unicode-bidi and unicode-bidi-mirroring (both MIT OR Apache-2.0).
|
||||
craft-text = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["bidi"] }
|
||||
# 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"
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! `bench --stroke`: what one long, fast, pressured Brush stroke costs (issue #519). The stroke
|
||||
//! is painted, picked, moved, floated and deselected (which merges it into the drawing, ADR
|
||||
//! 0122), and each step is timed. `--stroke-file` times the same steps on the artwork of a
|
||||
//! document instead, so a reported file can be measured as it is.
|
||||
|
||||
use crate::{Args, avg_ms, open_session, round};
|
||||
use anicraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
use std::time::Instant;
|
||||
|
||||
/// Samples of the default scenario: about 50 seconds of drawing at a tablet's 120 reports a
|
||||
/// second.
|
||||
pub const DEFAULT_SAMPLES: u32 = 6000;
|
||||
/// Most samples the scenario takes (the command's own limit is `geom::brush::MAX_SAMPLES`).
|
||||
const MAX_SAMPLES: u32 = 100_000;
|
||||
|
||||
/// A fast scribble over a 1280 × 720 stage: loops that drift across it and cross themselves
|
||||
/// again and again, with the pressure swelling and fading. The same for a given `n`.
|
||||
pub fn scribble(n: u32) -> Vec<[f32; 3]> {
|
||||
let n = n.clamp(2, MAX_SAMPLES);
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
// About 16 stage units between samples: a fast hand.
|
||||
let t = i as f32 * 0.06;
|
||||
let x = 640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos();
|
||||
let y = 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin();
|
||||
[x, y, 0.55 + 0.45 * (t * 0.37).sin()]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn ms(t: Instant) -> f64 {
|
||||
round(t.elapsed().as_secs_f64() * 1000.0)
|
||||
}
|
||||
|
||||
/// Curve and line segments of every shape on the playhead's frame.
|
||||
fn segments(s: &Session) -> usize {
|
||||
s.display_list().items.iter().map(|i| i.path.cmds.len()).sum()
|
||||
}
|
||||
|
||||
pub fn bench_stroke(a: &Args) -> Result<String, String> {
|
||||
let file = a.flag("stroke-file");
|
||||
let samples = match a.flag("stroke") {
|
||||
Some("yes" | "true") | None => DEFAULT_SAMPLES,
|
||||
Some(v) => v.parse::<u32>().map_err(|_| "--stroke takes a number of samples (or yes)".to_string())?.clamp(2, MAX_SAMPLES),
|
||||
};
|
||||
let mut out = json!({"build": if cfg!(debug_assertions) { "debug (use --release for real numbers)" } else { "release" }});
|
||||
let mut s = match file {
|
||||
Some(p) => {
|
||||
out["file"] = json!(p);
|
||||
open_session(Some(p))?
|
||||
}
|
||||
None => {
|
||||
let mut s = Session::default();
|
||||
let _ = s.execute("draw.object_drawing", &json!({"on": false}));
|
||||
let t = Instant::now();
|
||||
let v = s.execute("draw.brush", &json!({"points": scribble(samples), "size": 10, "color": "#000000", "object": false})).map_err(|e| e.to_string())?;
|
||||
out["samples"] = json!(samples);
|
||||
out["draw_brush_ms"] = json!(ms(t));
|
||||
out["pieces"] = json!(v["elements"].as_array().map_or(0, Vec::len));
|
||||
out["merged"] = v["merged"].clone();
|
||||
s
|
||||
}
|
||||
};
|
||||
out["segments"] = json!(segments(&s));
|
||||
out["elements"] = json!(s.visible_elements().len());
|
||||
|
||||
let doc = s.doc.clone();
|
||||
let frame = s.frame;
|
||||
out["evaluate_ms"] = json!(round(avg_ms(5, |_| {
|
||||
let _ = anicraft_doc::evaluate(&doc, frame);
|
||||
})));
|
||||
let view = anicraft_render::View::stage(&doc, 1.0);
|
||||
let dl = anicraft_doc::evaluate(&doc, frame);
|
||||
out["render_ms"] = json!(round(avg_ms(3, |_| {
|
||||
let _ = anicraft_render::render(&dl, &view);
|
||||
})));
|
||||
out["hit_test_us"] = json!(round(
|
||||
avg_ms(200, |i| {
|
||||
let _ = s.hit_test(anicraft_geom::Vec2::new((i * 37 % 1280) as f32, (i * 53 % 720) as f32), 2.0);
|
||||
}) * 1000.0
|
||||
));
|
||||
|
||||
// The reporter's steps: select it, move it, let go of the mouse (it floats), deselect (it
|
||||
// merges into the drawing).
|
||||
let mut step = |s: &mut Session, key: &str, id: &str, p: Value| -> Result<Value, String> {
|
||||
let t = Instant::now();
|
||||
let v = s.execute(id, &p).map_err(|e| format!("{id}: {e}"))?;
|
||||
out[key] = json!(ms(t));
|
||||
Ok(v)
|
||||
};
|
||||
step(&mut s, "select_all_ms", "edit.select_all", json!({}))?;
|
||||
step(&mut s, "move_ms", "element.translate", json!({"dx": 24, "dy": 16}))?;
|
||||
step(&mut s, "float_ms", "draw.float", json!({}))?;
|
||||
step(&mut s, "deselect_merge_ms", "edit.deselect", json!({}))?;
|
||||
let t = Instant::now();
|
||||
let _ = s.undo();
|
||||
out["undo_ms"] = json!(ms(t));
|
||||
out["segments_after"] = json!(segments(&s));
|
||||
serde_json::to_string_pretty(&out).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! server (`mcp`). Every operation goes through the engine's command registry.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod bench_stroke;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod control;
|
||||
pub mod mcp;
|
||||
@@ -46,6 +47,10 @@ USAGE:
|
||||
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
|
||||
anicraft-cli bench --stroke <samples> one long Brush stroke: painting it, picking it, moving
|
||||
it and the merge when it is deselected (ADR 0129)
|
||||
anicraft-cli bench --stroke-file <file.anicraft>
|
||||
the same steps on a document's own artwork
|
||||
anicraft-cli serve [file|--sample] [--automation-read-root <folder> --automation-write-root <folder>]
|
||||
JSON-lines on stdin/stdout:
|
||||
{\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}}
|
||||
@@ -579,6 +584,9 @@ pub fn check_budgets(out: &Value) -> (Vec<Value>, Vec<String>) {
|
||||
/// `cargo run --release -p anicraft-cli -- bench`. With `--check yes`, the default scenario
|
||||
/// is compared with [`TIME_BUDGETS`] and a missed budget is an error.
|
||||
pub fn bench(a: &Args) -> Result<String, String> {
|
||||
if a.flag("stroke").is_some() || a.flag("stroke-file").is_some() {
|
||||
return bench_stroke::bench_stroke(a);
|
||||
}
|
||||
let check = a.flag("check").is_some_and(|v| v == "yes" || v == "true");
|
||||
if check {
|
||||
if cfg!(debug_assertions) {
|
||||
@@ -1021,6 +1029,33 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `bench --stroke` walks the reporter's steps of #519 (paint, pick, move, float, deselect,
|
||||
/// undo) and `--stroke-file` the same on a document: the stroke becomes one merged shape,
|
||||
/// the merge on deselect keeps it, and undo puts the drawing back as it was.
|
||||
#[test]
|
||||
fn stroke_bench_paints_moves_and_merges_a_long_stroke() {
|
||||
let out: Value = serde_json::from_str(&run(&["bench".into(), "--stroke".into(), "400".into()]).unwrap()).unwrap();
|
||||
assert_eq!(out["samples"], 400);
|
||||
assert_eq!(out["merged"], true);
|
||||
let segments = out["segments"].as_u64().unwrap();
|
||||
assert!(segments > 50, "a scribble has an outline of many curves: {segments}");
|
||||
assert_eq!(out["segments_after"].as_u64(), Some(segments), "undo takes the move and its merge back");
|
||||
for step in ["draw_brush_ms", "hit_test_us", "move_ms", "float_ms", "deselect_merge_ms", "undo_ms", "render_ms"] {
|
||||
assert!(out[step].as_f64().is_some_and(|v| v >= 0.0), "{step} was timed: {out}");
|
||||
}
|
||||
assert!(run(&["bench".into(), "--stroke".into(), "many".into()]).unwrap_err().contains("number of samples"));
|
||||
// The same steps on a saved document's artwork.
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-cli-stroke-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("stroke.anicraft");
|
||||
let mut s = Session::default();
|
||||
s.execute("draw.brush", &json!({"points": bench_stroke::scribble(200), "size": 8, "object": false})).unwrap();
|
||||
s.execute("file.save", &json!({"path": file.display().to_string()})).unwrap();
|
||||
let out: Value = serde_json::from_str(&run(&["bench".into(), "--stroke-file".into(), file.display().to_string()]).unwrap()).unwrap();
|
||||
assert!(out["samples"].is_null() && out["elements"].as_u64() == Some(1) && out["deselect_merge_ms"].is_number(), "{out}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_folder_flag() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-cli-plugins-{}", std::process::id()));
|
||||
|
||||
+11
-2
@@ -211,11 +211,20 @@ pub fn call_tool_in<H: Host + ?Sized>(h: &mut H, name: &str, args: &Value, roots
|
||||
};
|
||||
let scale = scale.min(MAX_PICTURE_EDGE / largest);
|
||||
let movie_frame = s.doc.scene_start(s.scene).saturating_add(frame);
|
||||
let png = anicraft_render::render_frame(&s.doc, movie_frame, scale).and_then(|p| p.encode_png()).map_err(|e| e.to_string())?;
|
||||
// A frame cut short by its allowance of work is said to be (ADR 0128).
|
||||
let cut = anicraft_engine::left_out::LeftOut::default();
|
||||
let dl = cut.evaluate(&s.doc, movie_frame);
|
||||
let png = anicraft_render::render(&dl, &anicraft_render::View::stage(&s.doc, scale)).and_then(|(p, _)| p.encode_png()).map_err(|e| e.to_string())?;
|
||||
let mut caption = format!("Frame {frame} of scene {} at {:.0}% ({}×{} stage).", s.scene, scale * 100.0, stage.width, stage.height);
|
||||
if cut.any() {
|
||||
caption.push_str(" Not the whole frame: ");
|
||||
caption.push_str(anicraft_engine::left_out::WARNING);
|
||||
caption.push('.');
|
||||
}
|
||||
json!({
|
||||
"content": [
|
||||
{"type": "image", "data": anicraft_doc::base64_encode(&png), "mimeType": "image/png"},
|
||||
{"type": "text", "text": format!("Frame {frame} of scene {} at {:.0}% ({}×{} stage).", s.scene, scale * 100.0, stage.width, stage.height)}
|
||||
{"type": "text", "text": caption}
|
||||
],
|
||||
"isError": false
|
||||
})
|
||||
|
||||
+260
-41
@@ -13,21 +13,74 @@ use std::sync::Arc;
|
||||
/// Symbols nested deeper than this are not drawn (guards cyclic libraries).
|
||||
pub const MAX_SYMBOL_DEPTH: usize = 32;
|
||||
|
||||
/// Most elements one evaluation (or one bounds query) visits, nested symbols and groups
|
||||
/// included. The depth cap alone leaves a symbol holding two instances of the next, 32 deep,
|
||||
/// The work one evaluation (or one bounds query) may do, nested symbols and groups included
|
||||
/// (ADR 0128). The depth cap alone leaves a symbol holding two instances of the next, 32 deep,
|
||||
/// to expand 2^32 times, which no file may make AniCraft do: past the allowance the rest is
|
||||
/// left out, so a hostile or damaged document draws in part instead of hanging or running
|
||||
/// out of memory. Real scenes stay far below it (the heaviest benchmark has 50,000 shapes).
|
||||
/// out of memory, and the result says so ([`DisplayList::left_out`]). Real scenes stay far
|
||||
/// below it (the heaviest benchmark has 50,000 shapes).
|
||||
///
|
||||
/// A unit is one element or one layer visited. A shape costs one more for every
|
||||
/// [`PATH_COMMANDS_PER_UNIT`] commands of its outline, and finding a symbol one more for every
|
||||
/// [`LIBRARY_ENTRIES_PER_UNIT`] library entries passed, so neither a huge outline nor a huge
|
||||
/// library, repeated by nesting, multiplies the work past what the allowance stands for.
|
||||
pub const MAX_EVAL_ELEMENTS: u32 = 1_000_000;
|
||||
|
||||
/// Takes one visit from `work`; `false` once the allowance is spent.
|
||||
pub(crate) fn spend(work: &Cell<u32>) -> bool {
|
||||
match work.get().checked_sub(1) {
|
||||
Some(left) => {
|
||||
work.set(left);
|
||||
true
|
||||
/// A shape's outline costs one unit of work for each this many path commands.
|
||||
pub const PATH_COMMANDS_PER_UNIT: usize = 256;
|
||||
|
||||
/// Finding a symbol costs one unit of work for each this many library entries looked at.
|
||||
pub const LIBRARY_ENTRIES_PER_UNIT: usize = 1024;
|
||||
|
||||
/// An allowance of work (see [`MAX_EVAL_ELEMENTS`]) shared by everything one query visits, that
|
||||
/// remembers whether it ran out.
|
||||
pub(crate) struct Work {
|
||||
left: Cell<u32>,
|
||||
ran_out: Cell<bool>,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
pub(crate) fn new(units: u32) -> Work {
|
||||
Work { left: Cell::new(units), ran_out: Cell::new(false) }
|
||||
}
|
||||
|
||||
/// Takes `units`; `false` once the allowance is spent (and from then on).
|
||||
pub(crate) fn spend(&self, units: u32) -> bool {
|
||||
match self.left.get().checked_sub(units) {
|
||||
Some(left) if !self.ran_out.get() => {
|
||||
self.left.set(left);
|
||||
true
|
||||
}
|
||||
_ => {
|
||||
self.left.set(0);
|
||||
self.ran_out.set(true);
|
||||
false
|
||||
}
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
|
||||
/// Something was left out because the allowance was spent.
|
||||
pub(crate) fn ran_out(&self) -> bool {
|
||||
self.ran_out.get()
|
||||
}
|
||||
|
||||
/// Takes what visiting `el` costs.
|
||||
pub(crate) fn visit(&self, el: &Element) -> bool {
|
||||
let outline = match &el.kind {
|
||||
ElementKind::Shape(s) => s.path.cmds.len() / PATH_COMMANDS_PER_UNIT,
|
||||
_ => 0,
|
||||
};
|
||||
self.spend(u32::try_from(outline).unwrap_or(u32::MAX).saturating_add(1))
|
||||
}
|
||||
|
||||
/// The library symbol `id`, paid for by how far into the library it is.
|
||||
pub(crate) fn symbol<'d>(&self, doc: &'d Document, id: SymbolId) -> Option<&'d crate::Symbol> {
|
||||
let at = doc.library.iter().position(|s| s.id == id);
|
||||
let passed = at.unwrap_or(doc.library.len()) / LIBRARY_ENTRIES_PER_UNIT;
|
||||
if passed > 0 && !self.spend(u32::try_from(passed).unwrap_or(u32::MAX)) {
|
||||
return None;
|
||||
}
|
||||
at.and_then(|i| doc.library.get(i)).map(|s| &**s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +140,10 @@ pub struct DisplayList {
|
||||
/// Links on text (ADR 0085): `(item, url)` for each item drawing characters that link
|
||||
/// somewhere, in item order. Sparse: most lists have none.
|
||||
pub links: Vec<(u32, Arc<str>)>,
|
||||
/// The frame's allowance of work ([`MAX_EVAL_ELEMENTS`]) ran out, so artwork is missing
|
||||
/// from this list: whoever shows or exports it says so instead of passing it off as the
|
||||
/// whole frame (ADR 0128).
|
||||
pub left_out: bool,
|
||||
}
|
||||
|
||||
/// A group that fades as one (see [`DisplayList::groups`]).
|
||||
@@ -160,6 +217,7 @@ impl DisplayList {
|
||||
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.left_out |= other.left_out;
|
||||
let ibase = self.items.len() as u32;
|
||||
self.links.extend(other.links.into_iter().map(|(i, u)| (i + ibase, u)));
|
||||
self.items.extend(other.items.into_iter().map(|mut i| {
|
||||
@@ -182,8 +240,9 @@ pub fn evaluate(doc: &Document, frame: u32) -> DisplayList {
|
||||
/// applied: what the stage shows while editing (and what picking and bounds use).
|
||||
pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
let work = Cell::new(MAX_EVAL_ELEMENTS);
|
||||
let work = Work::new(MAX_EVAL_ELEMENTS);
|
||||
eval_timeline(doc, doc.timeline(scene), frame, &Ctx::top(Affine::IDENTITY, &work), &mut out, None);
|
||||
out.left_out = work.ran_out();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -192,8 +251,9 @@ pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList {
|
||||
/// top-level ones, as a scene's are in [`evaluate_scene`].
|
||||
pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
let work = Cell::new(MAX_EVAL_ELEMENTS);
|
||||
let work = Work::new(MAX_EVAL_ELEMENTS);
|
||||
eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY, &work), &mut out, None);
|
||||
out.left_out = work.ran_out();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -203,8 +263,9 @@ pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayLi
|
||||
/// skin or Edit Multiple Frames composes its frames (ADR 0051).
|
||||
pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affine) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
let work = Cell::new(MAX_EVAL_ELEMENTS);
|
||||
let work = Work::new(MAX_EVAL_ELEMENTS);
|
||||
eval_timeline(doc, tl, frame, &Ctx::top(xf, &work), &mut out, None);
|
||||
out.left_out = work.ran_out();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -214,8 +275,9 @@ pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affin
|
||||
pub fn evaluate_scene_camera(doc: &Document, scene: usize, frame: u32) -> DisplayList {
|
||||
let tl = doc.timeline(scene);
|
||||
let mut out = DisplayList::default();
|
||||
let work = Cell::new(MAX_EVAL_ELEMENTS);
|
||||
let work = Work::new(MAX_EVAL_ELEMENTS);
|
||||
eval_timeline(doc, tl, frame, &Ctx::through(tl.camera_at(frame, &doc.stage), &work), &mut out, None);
|
||||
out.left_out = work.ran_out();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -224,22 +286,26 @@ pub fn evaluate_scene_camera(doc: &Document, scene: usize, frame: u32) -> Displa
|
||||
/// through the scene's camera.
|
||||
pub fn evaluate_player(doc: &Document, state: &PlayerState) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
let work = Cell::new(MAX_EVAL_ELEMENTS);
|
||||
let work = Work::new(MAX_EVAL_ELEMENTS);
|
||||
let play = Play { state, path: Vec::new() };
|
||||
let tl = doc.timeline(state.scene);
|
||||
eval_timeline(doc, tl, state.root.frame, &Ctx::through(tl.camera_at(state.root.frame, &doc.stage), &work), &mut out, Some(&play));
|
||||
out.left_out = work.ran_out();
|
||||
out
|
||||
}
|
||||
|
||||
/// A symbol's timeline at `frame`, drawn at `xf` (stage space): a button's hit area, or a movie
|
||||
/// clip's artwork, as the player sees it when `play` is given.
|
||||
pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Affine, play: Option<&Play<'_>>) -> DisplayList {
|
||||
///
|
||||
/// `work` is the caller's allowance, so a player step that looks at many instances pays for
|
||||
/// all of them from one.
|
||||
pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Affine, play: Option<&Play<'_>>, work: &Work) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
let work = Cell::new(MAX_EVAL_ELEMENTS);
|
||||
let mut cx = Ctx::top(xf, &work);
|
||||
let mut cx = Ctx::top(xf, work);
|
||||
cx.depth = 1;
|
||||
cx.stage = false;
|
||||
eval_timeline(doc, tl, frame, &cx, &mut out, play);
|
||||
out.left_out = work.ran_out();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -315,7 +381,10 @@ pub(crate) fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&
|
||||
let morph = tween.kind == TweenKind::Shape;
|
||||
let path = guide.map(|g| (g, tween.orient));
|
||||
let runs = |els: &[Arc<Element>]| els.iter().filter(|e| raw_stroke(e).is_some()).count();
|
||||
if morph && runs(&kf.elements) != runs(&next.elements) {
|
||||
// Along a motion guide the runs are joined even when both keys have as many: a guide places
|
||||
// each element by its own origin, so runs left to pair one by one would each take their own
|
||||
// way along it and leave the fill they edge.
|
||||
if morph && (runs(&kf.elements) != runs(&next.elements) || (path.is_some() && runs(&kf.elements) > 0)) {
|
||||
return Some((kf.start, Cow::Owned(morph_raw_strokes(kf, next, t, path))));
|
||||
}
|
||||
let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() };
|
||||
@@ -372,40 +441,117 @@ fn raw_stroke(e: &Element) -> Option<&Stroke> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw fill of `els` that `path` (in `xf` space) edges: the one whose edge is within two
|
||||
/// snaps of the middle of `path`, or that contains it, or the one whose origin is nearest `xf`'s.
|
||||
/// The middle, not an end: a run ends at a corner, where the runs of the fill next door end
|
||||
/// too, so an end says nothing about whose edge the run is. An edge two fills share (their
|
||||
/// outlines joined there) goes with the lower of the two, the first in the stack.
|
||||
fn fill_of(els: &[Arc<Element>], path: &Path, xf: &Affine) -> Option<usize> {
|
||||
let middle = |pl: anicraft_geom::Polyline| {
|
||||
let k = pl.points.len() / 2;
|
||||
match (pl.points.get(k.wrapping_sub(1)), pl.points.get(k)) {
|
||||
(Some(a), Some(b)) => Some(a.lerp(*b, 0.5)),
|
||||
(None, b) => b.copied(),
|
||||
(a, None) => a.copied(),
|
||||
}
|
||||
};
|
||||
if let Some(p) = path.flatten(xf, 0.25).into_iter().next().and_then(middle)
|
||||
&& let Some((k, _)) = els.iter().enumerate().find(|(_, e)| {
|
||||
matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some() && (s.path.contains(p, &e.transform, s.fill_rule) || s.path.distance_to_edge(p, &e.transform) <= 2.0 * anicraft_geom::planar::SNAP))
|
||||
})
|
||||
{
|
||||
return Some(k);
|
||||
}
|
||||
let own = xf.translation();
|
||||
els.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, e)| matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some()))
|
||||
.min_by(|(_, a), (_, b)| own.distance(a.transform.translation()).total_cmp(&own.distance(b.transform.translation())))
|
||||
.map(|(k, _)| k)
|
||||
}
|
||||
|
||||
/// Raw stroke runs joined into one outline: the indices of the runs (the first one's space is
|
||||
/// the outline's) and the joined element.
|
||||
/// the outline's), the fill they edge, and the joined element.
|
||||
struct Joined {
|
||||
members: Vec<usize>,
|
||||
fill: Option<usize>,
|
||||
el: Element,
|
||||
}
|
||||
|
||||
/// Whether an outline's runs are chained into whole outlines by [`joined_runs`]: a stroke with
|
||||
/// no dash pattern and no width profile. A dash pattern restarts, and a profile is measured, on
|
||||
/// each run, so those runs stay apart.
|
||||
fn chained(el: &Element) -> bool {
|
||||
raw_stroke(el).is_some_and(|st| st.style.dash.is_none() && st.profile.is_none())
|
||||
}
|
||||
|
||||
/// The raw stroke runs of `els` joined into one element per stroke style (and scale, rotation
|
||||
/// and skew, which the stroke's width follows, and colour effect), each in the space of its first run.
|
||||
fn joined_runs(els: &[Arc<Element>]) -> Vec<Joined> {
|
||||
/// and skew, which the stroke's width follows, and colour effect), each in the space of its first run;
|
||||
/// when `by_fill`, runs that edge different fills stay in separate outlines so each outline can
|
||||
/// follow its own fill along a motion guide.
|
||||
fn joined_runs(els: &[Arc<Element>], by_fill: bool) -> Vec<Joined> {
|
||||
let mut out: Vec<Joined> = Vec::new();
|
||||
for (i, e) in els.iter().enumerate() {
|
||||
let (Some(st), ElementKind::Shape(s)) = (raw_stroke(e), &e.kind) else { continue };
|
||||
let fill = by_fill.then(|| fill_of(els, &s.path, &e.transform)).flatten();
|
||||
let slot = out.iter_mut().find_map(|j| {
|
||||
let ElementKind::Shape(js) = &mut j.el.kind else { return None };
|
||||
let into = j.el.transform.inverse()?.mul(&e.transform);
|
||||
(j.el.transform.m[..4] == e.transform.m[..4] && js.stroke.as_ref() == Some(st) && j.el.color == e.color).then_some((&mut j.members, js, into))
|
||||
(j.fill == fill && j.el.transform.m[..4] == e.transform.m[..4] && js.stroke.as_ref() == Some(st) && j.el.color == e.color).then_some((&mut j.members, js, into))
|
||||
});
|
||||
match slot {
|
||||
Some((members, js, into)) => {
|
||||
members.push(i);
|
||||
Arc::make_mut(&mut js.path).cmds.extend(s.path.transformed(&into).cmds);
|
||||
}
|
||||
None => out.push(Joined { members: vec![i], el: (**e).clone() }),
|
||||
None => out.push(Joined { members: vec![i], fill, el: (**e).clone() }),
|
||||
}
|
||||
}
|
||||
for j in &mut out {
|
||||
if let ElementKind::Shape(s) = &mut j.el.kind {
|
||||
// A dash pattern restarts, and a width profile is measured, on each run; chained, the
|
||||
// pattern and widths would jump on the first frame after the key. Such runs stay apart.
|
||||
if chained(&j.el) && let ElementKind::Shape(s) = &mut j.el.kind {
|
||||
s.path = Arc::new(anicraft_geom::morph::chain(&s.path, anicraft_geom::planar::SNAP));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `e` with its origin moved to `origin` (in its parent's space) and its path moved back, so
|
||||
/// it looks the same.
|
||||
fn rebase(e: &mut Element, origin: anicraft_geom::Vec2) {
|
||||
let mut moved = e.transform;
|
||||
moved.m[4] = origin.x;
|
||||
moved.m[5] = origin.y;
|
||||
let (Some(inv), ElementKind::Shape(s)) = (moved.inverse(), &mut e.kind) else { return };
|
||||
let d = inv.apply(e.transform.translation());
|
||||
if !d.is_finite() {
|
||||
return;
|
||||
}
|
||||
s.path = Arc::new(s.path.transformed(&Affine::translate(d.x, d.y)));
|
||||
e.transform = moved;
|
||||
}
|
||||
|
||||
/// What stands, in an in-between frame, for a run `x` joined into the outline `el`: nothing
|
||||
/// drawn (no fill, no stroke) but the run's identity over the outline, so a run selected on a
|
||||
/// key stays selected through the tween, with the outline's bounds.
|
||||
fn joined_member(x: &Element, el: &Element) -> Element {
|
||||
let mut e = el.clone();
|
||||
e.id = x.id;
|
||||
e.name.clone_from(&x.name);
|
||||
if let ElementKind::Shape(s) = &mut e.kind {
|
||||
let pad = s.stroke.as_ref().map_or(0.0, Stroke::reach);
|
||||
let b = s.path.bounds();
|
||||
if (b.width() == 0.0 || b.height() == 0.0) && pad > 0.0 {
|
||||
let r = b.inflate(pad);
|
||||
s.path = Arc::new(Path::rect(r.min.x, r.min.y, r.width(), r.height()));
|
||||
}
|
||||
s.stroke = None;
|
||||
s.fill = None;
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
/// The partner on `b` of each joined outline of `a`: one with the same stroke and colour first, then the
|
||||
/// rest in order.
|
||||
fn pair_joined(a: &[Joined], b: &[Joined]) -> Vec<Option<usize>> {
|
||||
@@ -429,6 +575,17 @@ fn pair_joined(a: &[Joined], b: &[Joined]) -> Vec<Option<usize>> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `el` with its runs chained into whole outlines, for a morph against an outline that is
|
||||
/// chained: both ends then correspond along the whole outline, the way the fill's do. Only the
|
||||
/// in-between frames see this; the keys keep their own runs.
|
||||
fn chained_for_morph(el: &Element) -> Element {
|
||||
let mut e = el.clone();
|
||||
if let ElementKind::Shape(s) = &mut e.kind {
|
||||
s.path = Arc::new(anicraft_geom::morph::chain(&s.path, anicraft_geom::planar::SNAP));
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
/// `e` shrunk to the centre of its path: where an outline without a partner grows from or
|
||||
/// shrinks to.
|
||||
fn collapsed(e: &Element) -> Element {
|
||||
@@ -447,7 +604,21 @@ fn collapsed(e: &Element) -> Element {
|
||||
/// pairs in order, as in a plain shape tween.
|
||||
fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, guide: Option<(&PathWalk, bool)>) -> Vec<Arc<Element>> {
|
||||
let (a, b) = (&kf.elements, &next.elements);
|
||||
let (runs_a, runs_b) = (joined_runs(a), joined_runs(b));
|
||||
let (mut runs_a, mut runs_b) = (joined_runs(a, guide.is_some()), joined_runs(b, guide.is_some()));
|
||||
if guide.is_some() {
|
||||
// A guide places each element by its own origin, so an outline with an origin of its own
|
||||
// would take another path than the fill it edges. Each outline takes the origin of the
|
||||
// fill it edges, so it travels with that fill; with no fill, of the first outline.
|
||||
for (els, runs) in [(a, &mut runs_a), (b, &mut runs_b)] {
|
||||
let first = runs.first().map(|r| r.el.transform.translation());
|
||||
for r in runs.iter_mut() {
|
||||
let origin = r.fill.and_then(|k| els.get(k)).map(|e| e.transform.translation()).or(first);
|
||||
if let Some(origin) = origin {
|
||||
rebase(&mut r.el, origin);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let partner = pair_joined(&runs_a, &runs_b);
|
||||
let placed = if kf.hints.is_empty() { Vec::new() } else { crate::hints::placed_hints(kf, next) };
|
||||
// The hints placed on what `on_a` and `on_b` pick, in the spaces of `x` and `y`.
|
||||
@@ -458,6 +629,18 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress,
|
||||
};
|
||||
let mut rest_b = b.iter().enumerate().filter(|(_, e)| raw_stroke(e).is_none());
|
||||
let mut out = Vec::with_capacity(a.len());
|
||||
// Which outline of the start key draws each of its runs, worked out once: searching the
|
||||
// outlines for every run would cost n(n+1)/2 comparisons for an outline of n runs.
|
||||
let mut outline_of: Vec<Option<usize>> = vec![None; a.len()];
|
||||
for (k, r) in runs_a.iter().enumerate() {
|
||||
for &m in &r.members {
|
||||
if let Some(slot) = outline_of.get_mut(m) {
|
||||
*slot = Some(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Each joined outline of the start key, tweened; it stands in for its first run.
|
||||
let mut tweened: Vec<Option<Arc<Element>>> = vec![None; runs_a.len()];
|
||||
for (i, x) in a.iter().enumerate() {
|
||||
if raw_stroke(x).is_none() {
|
||||
let y = rest_b.next();
|
||||
@@ -466,15 +649,33 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let Some((k, ra)) = runs_a.iter().enumerate().find(|(_, r)| r.members.first() == Some(&i)) else { continue };
|
||||
let Some((k, ra)) = outline_of.get(i).copied().flatten().and_then(|k| runs_a.get(k).map(|r| (k, r))) else { continue };
|
||||
if let Some(el) = tweened.get(k).and_then(Option::as_ref) {
|
||||
// A later run of the outline keeps its identity, drawn by the first.
|
||||
out.push(Arc::new(joined_member(x, el)));
|
||||
continue;
|
||||
}
|
||||
let el = match partner.get(k).copied().flatten().and_then(|m| runs_b.get(m)) {
|
||||
Some(rb) => {
|
||||
interpolate(&ra.el, &rb.el, t, true, &hints(&|h| ra.members.contains(&h), &|h| rb.members.contains(&h), &ra.el, &rb.el), guide)
|
||||
// A solid outline against a dashed or profiled one: only one of the two is
|
||||
// chained, so a whole outline would morph against the other key's loose runs and
|
||||
// the stroke would follow a different correspondence than the fill. Both are
|
||||
// chained for the morph.
|
||||
let (x, y) = if chained(&ra.el) == chained(&rb.el) {
|
||||
(Cow::Borrowed(&ra.el), Cow::Borrowed(&rb.el))
|
||||
} else {
|
||||
(Cow::Owned(chained_for_morph(&ra.el)), Cow::Owned(chained_for_morph(&rb.el)))
|
||||
};
|
||||
interpolate(&x, &y, t, true, &hints(&|h| ra.members.contains(&h), &|h| rb.members.contains(&h), &x, &y), guide)
|
||||
}
|
||||
// No partner on the end keyframe: it shrinks away.
|
||||
None => interpolate(&ra.el, &collapsed(&ra.el), t, false, &[], guide),
|
||||
};
|
||||
out.push(Arc::new(el.unwrap_or_else(|| ra.el.clone())));
|
||||
let el = Arc::new(el.unwrap_or_else(|| ra.el.clone()));
|
||||
if let Some(slot) = tweened.get_mut(k) {
|
||||
*slot = Some(el.clone());
|
||||
}
|
||||
out.push(el);
|
||||
}
|
||||
// Outlines only on the end keyframe grow in.
|
||||
for (_, rb) in runs_b.iter().enumerate().filter(|(m, _)| !partner.contains(&Some(*m))) {
|
||||
@@ -602,9 +803,9 @@ fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(an
|
||||
/// What a timeline is evaluated inside of.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Ctx<'a> {
|
||||
/// The evaluation's allowance of element visits ([`MAX_EVAL_ELEMENTS`]), shared by everything
|
||||
/// nested in it.
|
||||
work: &'a Cell<u32>,
|
||||
/// The evaluation's allowance of work ([`MAX_EVAL_ELEMENTS`]), shared by everything nested
|
||||
/// in it.
|
||||
work: &'a Work,
|
||||
/// Local → stage transform and colour effect of the enclosing instance.
|
||||
xf: Affine,
|
||||
color: ColorTransform,
|
||||
@@ -632,12 +833,12 @@ struct Ctx<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
fn top(xf: Affine, work: &'a Cell<u32>) -> Ctx<'a> {
|
||||
fn top(xf: Affine, work: &'a Work) -> Ctx<'a> {
|
||||
Ctx { work, 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>, work: &'a Cell<u32>) -> Ctx<'a> {
|
||||
fn through(camera: Option<Camera>, work: &'a Work) -> Ctx<'a> {
|
||||
let mut cx = Ctx::top(Affine::IDENTITY, work);
|
||||
cx.stage = false;
|
||||
if let Some(c) = camera {
|
||||
@@ -777,6 +978,11 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx<'_>, out: &
|
||||
for k in 0..n {
|
||||
let index = sorted.as_ref().map_or(n - 1 - k, |o| o.get(k).copied().unwrap_or(n));
|
||||
let Some(layer) = tl.layers.get(index) else { continue };
|
||||
// A layer looked at counts as an element does, so a timeline of empty layers, repeated
|
||||
// by nesting, is bounded too.
|
||||
if !cx.work.spend(1) {
|
||||
return;
|
||||
}
|
||||
// Guide artwork is listed (marked, for editing) but never drawn; inside mask artwork
|
||||
// it plays no part at all.
|
||||
let is_guide = layer.kind == LayerKind::Guide;
|
||||
@@ -872,8 +1078,9 @@ struct LayerCtx<'a> {
|
||||
}
|
||||
|
||||
fn eval_element(doc: &Document, cx: &Ctx<'_>, lc: &LayerCtx<'_>, el: &Element, out: &mut DisplayList, play: Option<&Play<'_>>) {
|
||||
// Every element drawn counts, however deep: see MAX_EVAL_ELEMENTS.
|
||||
if !spend(cx.work) {
|
||||
// Every element drawn counts, however deep, and a shape by the size of its outline: see
|
||||
// MAX_EVAL_ELEMENTS.
|
||||
if !cx.work.visit(el) {
|
||||
return;
|
||||
}
|
||||
let LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf } = *lc;
|
||||
@@ -1002,7 +1209,7 @@ fn eval_element(doc: &Document, cx: &Ctx<'_>, lc: &LayerCtx<'_>, el: &Element, o
|
||||
}
|
||||
}
|
||||
ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => {
|
||||
let Some(sym) = doc.symbol(*symbol) else { return };
|
||||
let Some(sym) = cx.work.symbol(doc, *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.
|
||||
@@ -1079,10 +1286,22 @@ fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option<
|
||||
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) });
|
||||
// One stretch per direction the selection runs through (ADR 0130).
|
||||
let mut spans = l.spans(from, to);
|
||||
if b > l.end {
|
||||
// The line break is selected too: a little past where the line ends.
|
||||
let (x, tail) = (l.x_at(l.end), t.size * 0.25);
|
||||
match spans.last_mut() {
|
||||
Some(last) if !l.rtl && (last.1 - x).abs() < 1e-3 => last.1 = x + tail,
|
||||
_ if l.rtl => spans.push((x - tail, x)),
|
||||
_ => spans.push((x, x + tail)),
|
||||
}
|
||||
}
|
||||
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));
|
||||
for (x0, x1) in spans {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1149,7 +1368,7 @@ fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc<Path>, Affine, Op
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "eval_tests.rs"]
|
||||
mod tests;
|
||||
pub(crate) mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "pivot_tests.rs"]
|
||||
|
||||
+290
-26
@@ -739,6 +739,233 @@ fn raw_stroke_runs_with_different_colour_effects_keep_them_in_a_shape_tween() {
|
||||
assert_eq!(by(1).color, ColorEffect::None.transform(), "the first run took the later run's colour");
|
||||
}
|
||||
|
||||
/// A plain black stroke 2 wide.
|
||||
fn solid_stroke() -> crate::Stroke {
|
||||
Shape::filled(Path::new(), Paint::Solid(Rgba::BLACK)).with_stroke(Rgba::BLACK, 2.0).stroke.unwrap()
|
||||
}
|
||||
|
||||
/// A shape tween from a triangle's raw stroke runs (ids 1-3) to a square's (ids 11-14), all in
|
||||
/// `stroke`: different run counts, so the runs are joined into outlines that morph.
|
||||
fn polygon_runs_doc(stroke: &crate::Stroke) -> Document {
|
||||
let v = anicraft_geom::Vec2::new;
|
||||
let runs = |first: u64, pts: &[anicraft_geom::Vec2]| -> Vec<Arc<Element>> {
|
||||
(0..pts.len())
|
||||
.map(|k| {
|
||||
let mut p = Path::new();
|
||||
p.move_to(pts[k]).line_to(pts[(k + 1) % pts.len()]);
|
||||
let mut s = Shape::filled(p, Paint::Solid(Rgba::BLACK));
|
||||
s.fill = None;
|
||||
s.stroke = Some(stroke.clone());
|
||||
s.merge = true;
|
||||
Arc::new(Element { id: ElementId(first + k as u64), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::Shape(s) })
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut d = Document::default();
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements = runs(1, &[v(50.0, 0.0), v(100.0, 90.0), v(0.0, 90.0)]);
|
||||
k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() });
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements = runs(11, &[v(0.0, 0.0), v(100.0, 0.0), v(100.0, 100.0), v(0.0, 100.0)]);
|
||||
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
d
|
||||
}
|
||||
|
||||
/// Runs joined into one outline in a shape tween all keep their identities in between: the
|
||||
/// first draws the outline, the others stand over it undrawn, so a selection of any of them
|
||||
/// survives the tween and has bounds (a selection of a run missing from the frame is dropped).
|
||||
#[test]
|
||||
fn joined_stroke_runs_keep_their_identities_in_a_shape_tween() {
|
||||
let d = polygon_runs_doc(&solid_stroke());
|
||||
let els = crate::evaluate_layer_elements(&d.timeline(0).layers[0], 5).unwrap().1;
|
||||
let ids: Vec<u64> = els.iter().map(|e| e.id.0).collect();
|
||||
assert_eq!(ids, [1, 2, 3], "every run of the start key is there");
|
||||
let stroked: Vec<_> = els.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(s) if s.stroke.is_some())).collect();
|
||||
assert_eq!(stroked.len(), 1, "one outline is drawn, once");
|
||||
assert_eq!(stroked[0].id, ElementId(1));
|
||||
for e in els.iter() {
|
||||
assert!(!e.bounds(&d).is_empty(), "{:?} has bounds", e.id);
|
||||
}
|
||||
let list = evaluate(&d, 5);
|
||||
assert_eq!(list.items.iter().filter(|i| i.stroke.is_some() || i.fill.is_some()).count(), 1, "nothing is drawn twice");
|
||||
// Horizontal and vertical outlines have zero height or width before stroke padding: undrawn
|
||||
// members still keep non-empty bounds.
|
||||
let v = anicraft_geom::Vec2::new;
|
||||
let seg = |id: u64, a, b| {
|
||||
let mut p = Path::new();
|
||||
p.move_to(a).line_to(b);
|
||||
let mut s = Shape::filled(p, Paint::Solid(Rgba::BLACK));
|
||||
s.fill = None;
|
||||
s.stroke = Some(solid_stroke());
|
||||
s.merge = true;
|
||||
Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::Shape(s) })
|
||||
};
|
||||
for (a0, a1, a2, b0, b1, b2, b3) in [
|
||||
(v(0.0, 20.0), v(40.0, 20.0), v(80.0, 20.0), v(0.0, 20.0), v(30.0, 20.0), v(60.0, 20.0), v(90.0, 20.0)),
|
||||
(v(20.0, 0.0), v(20.0, 40.0), v(20.0, 80.0), v(20.0, 0.0), v(20.0, 30.0), v(20.0, 60.0), v(20.0, 90.0)),
|
||||
] {
|
||||
let mut d = Document::default();
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements = vec![seg(1, a0, a1), seg(2, a1, a2)];
|
||||
k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() });
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements = vec![seg(11, b0, b1), seg(12, b1, b2), seg(13, b2, b3)];
|
||||
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
let els = crate::evaluate_layer_elements(&d.timeline(0).layers[0], 5).unwrap().1;
|
||||
assert_eq!(els.len(), 2);
|
||||
for e in els.iter() {
|
||||
assert!(!e.bounds(&d).is_empty(), "axis-aligned run {:?} has bounds", e.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A dash pattern restarts on each run and a width profile is measured along each, so dashed or
|
||||
/// profiled runs are not chained into one outline: right after the key they look as they did.
|
||||
#[test]
|
||||
fn dashed_or_profiled_stroke_runs_stay_apart_in_a_shape_tween() {
|
||||
let subpaths = |d: &Document| {
|
||||
let list = evaluate(d, 1);
|
||||
list.items.iter().filter(|i| i.stroke.is_some()).map(|i| i.path.cmds.iter().filter(|c| matches!(c, anicraft_geom::PathCmd::MoveTo(_))).count()).sum::<usize>()
|
||||
};
|
||||
let solid = solid_stroke();
|
||||
assert_eq!(subpaths(&polygon_runs_doc(&solid)), 1, "solid runs join into one outline");
|
||||
let mut dashed = solid.clone();
|
||||
dashed.style.dash = crate::Dash::dashed(6.0, 3.0);
|
||||
assert!(dashed.style.dash.is_some());
|
||||
// Three runs on the start key: three pieces still, the square's fourth side growing in.
|
||||
assert!(subpaths(&polygon_runs_doc(&dashed)) >= 3, "a dashed outline keeps its runs");
|
||||
let mut tapered = solid;
|
||||
tapered.profile = crate::ProfilePreset::ALL.into_iter().find_map(crate::ProfilePreset::profile);
|
||||
assert!(tapered.profile.is_some());
|
||||
assert!(subpaths(&polygon_runs_doc(&tapered)) >= 3, "a profiled outline keeps its runs");
|
||||
}
|
||||
|
||||
/// A raw regular polygon centred on `at` as the merge stores it: its fill element (id `first`),
|
||||
/// then one stroke run per side (ids `first + 1`…), each with its own origin.
|
||||
fn polygon_at(first: u64, at: anicraft_geom::Vec2, radius: f32, sides: usize, stroke: &crate::Stroke) -> Vec<Arc<Element>> {
|
||||
use std::f32::consts::{PI, TAU};
|
||||
let pts: Vec<anicraft_geom::Vec2> = (0..sides)
|
||||
.map(|k| {
|
||||
let a = -PI / 2.0 + k as f32 * TAU / sides as f32;
|
||||
at + anicraft_geom::Vec2::new(radius * a.cos(), radius * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let mut outline = Path::new();
|
||||
if let Some(&p) = pts.first() {
|
||||
outline.move_to(p);
|
||||
}
|
||||
for &p in pts.iter().skip(1) {
|
||||
outline.line_to(p);
|
||||
}
|
||||
outline.close();
|
||||
let piece = |id: u64, path: &Path, centre: anicraft_geom::Vec2, fill: bool| {
|
||||
let mut s = Shape::filled(path.transformed(&Affine::translate(-centre.x, -centre.y)), Paint::Solid(Rgba::BLACK));
|
||||
s.fill = fill.then_some(Paint::Solid(Rgba::BLACK));
|
||||
s.stroke = (!fill).then(|| stroke.clone());
|
||||
s.merge = true;
|
||||
Arc::new(Element {
|
||||
id: ElementId(id),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(centre.x, centre.y),
|
||||
color: ColorEffect::None,
|
||||
kind: ElementKind::Shape(s),
|
||||
})
|
||||
};
|
||||
let mut out = vec![piece(first, &outline, at, true)];
|
||||
for (k, &a) in pts.iter().enumerate() {
|
||||
let b = pts[(k + 1) % sides];
|
||||
let mut side = Path::new();
|
||||
side.move_to(a).line_to(b);
|
||||
out.push(piece(first + 1 + k as u64, &side, (a + b) * 0.5, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A solid outline on one key against a dashed one on the other: the keys' outlines correspond
|
||||
/// as the fill's do, so the stroke stays on the morphed fill instead of pairing a whole outline
|
||||
/// with the other key's loose runs.
|
||||
#[test]
|
||||
fn a_solid_outline_morphs_against_a_dashed_one() {
|
||||
let v = anicraft_geom::Vec2::new;
|
||||
let solid = solid_stroke();
|
||||
let mut dashed = solid.clone();
|
||||
dashed.style.dash = crate::Dash::dashed(6.0, 3.0);
|
||||
let mut d = Document::default();
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements = polygon_at(1, v(50.0, 45.0), 50.0, 3, &solid);
|
||||
k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() });
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements = polygon_at(11, v(50.0, 50.0), 55.0, 4, &dashed);
|
||||
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
for frame in [3u32, 5, 7] {
|
||||
let list = evaluate(&d, frame);
|
||||
let fill = list.items.iter().find(|i| i.fill.is_some()).expect("the fill");
|
||||
let strokes: Vec<_> = list.items.iter().filter(|i| i.stroke.is_some()).collect();
|
||||
assert!(!strokes.is_empty(), "frame {frame}: the stroke is drawn");
|
||||
for pl in fill.path.flatten(&fill.transform, 0.25) {
|
||||
for &p in &pl.points {
|
||||
let d = strokes.iter().map(|st| st.path.distance_to_edge(p, &st.transform)).fold(f32::INFINITY, f32::min);
|
||||
assert!(d < 1.5, "frame {frame}: fill edge point {p:?} is {d} from the stroke");
|
||||
}
|
||||
}
|
||||
for st in &strokes {
|
||||
for pl in st.path.flatten(&st.transform, 0.25) {
|
||||
for &p in &pl.points {
|
||||
let d = fill.path.distance_to_edge(p, &fill.transform);
|
||||
assert!(d < 1.5, "frame {frame}: stroke point {p:?} is {d} off the fill's edge");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A guide places each element by its own origin, so each joined stroke outline takes the origin
|
||||
/// of the fill it edges: with two merged fill regions, each stroke travels with its own fill
|
||||
/// rather than following the first region's guide path.
|
||||
#[test]
|
||||
fn a_guided_shape_tween_keeps_each_stroke_with_its_own_fill() {
|
||||
let v = anicraft_geom::Vec2::new;
|
||||
let black = solid_stroke();
|
||||
let mut blue = black.clone();
|
||||
blue.color = Rgba::hex(0x0000ff);
|
||||
// Both different stroke styles and the same stroke style across the two regions: runs that
|
||||
// edge different fills stay in separate outlines and each travels its own fill's stretch.
|
||||
for second_stroke in [&blue, &black] {
|
||||
let mut d = Document::default();
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements = polygon_at(1, v(0.0, 0.0), 40.0, 3, &black);
|
||||
k0.elements.extend(polygon_at(10, v(300.0, 0.0), 40.0, 4, second_stroke));
|
||||
k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() });
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements = polygon_at(20, v(0.0, 100.0), 40.0, 5, &black);
|
||||
k1.elements.extend(polygon_at(30, v(300.0, 100.0), 40.0, 5, second_stroke));
|
||||
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
// A straight guide from the first region's start to the second's end: each element travels
|
||||
// the stretch of it between its own start and end origins.
|
||||
let pts: Vec<anicraft_geom::Vec2> = (0..=20).map(|k| v(300.0 * k as f32 / 20.0, 100.0 * k as f32 / 20.0)).collect();
|
||||
let walk = anicraft_geom::walk::PathWalk::new(&pts).expect("the guide");
|
||||
let layer = d.timeline(0).layers[0].clone();
|
||||
let of = |els: &[Arc<Element>], id: u64| els.iter().find(|e| e.id == ElementId(id)).cloned();
|
||||
for frame in [1u32, 3, 5, 7, 9] {
|
||||
let (_, els) = crate::evaluate_guided(&layer, frame, Some(&walk)).expect("an in-between frame");
|
||||
// The outline standing for a region's first run takes that region's fill's origin, so it
|
||||
// travels the same stretch of the guide as the fill it edges.
|
||||
for (run, fill) in [(2u64, 1u64), (11, 10)] {
|
||||
let (Some(r), Some(f)) = (of(&els, run), of(&els, fill)) else { panic!("frame {frame}: run {run} and fill {fill}") };
|
||||
let (a, b) = (r.transform.translation(), f.transform.translation());
|
||||
assert!(a.distance(b) < 0.01, "frame {frame}: run {run} at {a:?} left its fill at {b:?}");
|
||||
}
|
||||
// The regions travel different stretches: a stroke on the first region's path would be
|
||||
// far from the second region's fill.
|
||||
let (Some(first), Some(second)) = (of(&els, 1), of(&els, 10)) else { panic!("both fills") };
|
||||
assert!(first.transform.translation().distance(second.transform.translation()) > 100.0, "frame {frame}: the regions are apart");
|
||||
let (Some(run), Some(fill)) = (of(&els, 11), of(&els, 10)) else { panic!("the second region") };
|
||||
let off = run.bounds(&d).center().distance(fill.bounds(&d).center());
|
||||
assert!(off < 20.0, "frame {frame}: the second region's stroke is {off} from its fill");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A classic tween from scale `a` to scale `b` (with a turn and a skew at the end), eased.
|
||||
fn squash_doc(a: (f32, f32), b: (f32, f32), easing: Easing, keep_area: bool) -> Document {
|
||||
let at = |s: (f32, f32), rot: f32, skew: f32, x: f32| {
|
||||
@@ -833,32 +1060,9 @@ fn keep_area_off_is_bit_exact_with_a_tween_that_never_had_it_and_files_stay_smal
|
||||
assert!(back.scenes[0].timeline.layers[0].keyframes[0].tween.as_ref().unwrap().keep_area);
|
||||
}
|
||||
|
||||
/// A chain of symbols, each holding two instances of the next and the last one a square: 2^depth
|
||||
/// squares from `depth` symbols, with no cycle anywhere and no nesting deeper than the cap.
|
||||
fn doubling_doc(depth: u64) -> Document {
|
||||
let mut d = Document::default();
|
||||
let instance = |id: u64, symbol: u64, x: f32| Element {
|
||||
id: ElementId(id),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(x, 0.0),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None },
|
||||
};
|
||||
for level in 0..depth {
|
||||
let mut layer = Layer::new(LayerId(1000 + level), "l");
|
||||
layer.keyframes = vec![Arc::new(Keyframe::new(0, 1))];
|
||||
if level + 1 == depth {
|
||||
push(&mut layer, 0, shape_el(5000, 0.0));
|
||||
} else {
|
||||
push(&mut layer, 0, instance(2000 + level, 101 + level, 0.0));
|
||||
push(&mut layer, 0, instance(3000 + level, 101 + level, 1.0));
|
||||
}
|
||||
let timeline = Timeline { layers: vec![Arc::new(layer)] };
|
||||
d.library.push(Arc::new(Symbol { id: SymbolId(100 + level), name: format!("s{level}"), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline }));
|
||||
}
|
||||
layer0(&mut d).keyframes = vec![Arc::new(Keyframe::new(0, 1))];
|
||||
push(layer0(&mut d), 0, instance(1, 100, 0.0));
|
||||
d
|
||||
/// [`crate::sample::doubling`]: 2^(depth - 1) squares from `depth` symbols.
|
||||
pub(crate) fn doubling_doc(depth: u32) -> Document {
|
||||
crate::sample::doubling(depth)
|
||||
}
|
||||
|
||||
/// #13: the depth cap alone lets symbols that double at each level expand without end. One
|
||||
@@ -878,3 +1082,63 @@ fn symbols_that_double_at_each_level_stay_within_the_allowance() {
|
||||
assert!(!bounds.is_empty(), "what was reached still counts");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(30), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// ADR 0128: a frame that ran out of work says so, and one that did not, does not.
|
||||
#[test]
|
||||
fn a_frame_cut_short_by_the_allowance_says_artwork_is_left_out() {
|
||||
let small = evaluate(&doubling_doc(11), 0);
|
||||
assert!(!small.left_out);
|
||||
let cut = evaluate(&doubling_doc(31), 0);
|
||||
assert!(cut.left_out);
|
||||
// Whoever composes lists (onion skin, the hit overlay) keeps the mark.
|
||||
let mut both = small.clone();
|
||||
both.append(cut);
|
||||
assert!(both.left_out);
|
||||
assert!(evaluate_scene(&doubling_doc(31), 0, 0).left_out && evaluate_scene_camera(&doubling_doc(31), 0, 0).left_out);
|
||||
}
|
||||
|
||||
/// ADR 0128: what takes more work is counted as more, so nesting can multiply none of it past
|
||||
/// the allowance: layers with nothing on them, an outline of many commands, a symbol far into
|
||||
/// a long library.
|
||||
#[test]
|
||||
fn layers_long_outlines_and_long_libraries_count_as_work() {
|
||||
let plain = evaluate(&doubling_doc(31), 0).items.len();
|
||||
// 200 empty layers in every symbol: each visit of a symbol looks at all of them.
|
||||
let mut layered = doubling_doc(31);
|
||||
for sym in &mut layered.library {
|
||||
let tl = &mut Arc::make_mut(sym).timeline;
|
||||
for i in 0..200 {
|
||||
tl.layers.push(Arc::new(Layer::new(LayerId(9000 + i), "empty")));
|
||||
}
|
||||
}
|
||||
let dl = evaluate(&layered, 0);
|
||||
assert!(dl.left_out && dl.items.len() * 20 < plain, "{} of {plain}", dl.items.len());
|
||||
assert!(!layered.timeline(0).layers[0].keyframes[0].elements[0].bounds(&layered).is_empty());
|
||||
// The one shape at the bottom has an outline of several units of work.
|
||||
let mut heavy = doubling_doc(31);
|
||||
let last = heavy.library.len() - 1;
|
||||
let mut path = Path::new();
|
||||
path.move_to(Vec2::ZERO);
|
||||
for i in 0..(8 * crate::eval::PATH_COMMANDS_PER_UNIT) {
|
||||
path.line_to(Vec2::new(i as f32, (i % 7) as f32));
|
||||
}
|
||||
let shape = Arc::make_mut(&mut Arc::make_mut(&mut Arc::make_mut(&mut Arc::make_mut(&mut heavy.library[last]).timeline.layers[0]).keyframes[0]).elements[0]);
|
||||
shape.kind = ElementKind::Shape(Shape::filled(path, Paint::Solid(Rgba::BLACK)));
|
||||
let dl = evaluate(&heavy, 0);
|
||||
assert!(dl.left_out && dl.items.len() * 2 < plain, "{} of {plain}", dl.items.len());
|
||||
// The same symbols behind several thousand others: every lookup walks past them.
|
||||
let mut far = doubling_doc(31);
|
||||
let mut library: Vec<Arc<Symbol>> = (0..8 * crate::eval::LIBRARY_ENTRIES_PER_UNIT as u64).map(|i| Arc::new(Symbol { id: SymbolId(1_000_000 + i), name: String::new(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline::default() })).collect();
|
||||
library.append(&mut far.library);
|
||||
far.library = library;
|
||||
let dl = evaluate(&far, 0);
|
||||
assert!(dl.left_out && dl.items.len() * 2 < plain, "{} of {plain}", dl.items.len());
|
||||
// A library that long is no cost to a scene of ordinary size.
|
||||
let mut modest = doubling_doc(11);
|
||||
let mut library = far.library.clone();
|
||||
library.truncate(8 * crate::eval::LIBRARY_ENTRIES_PER_UNIT);
|
||||
library.append(&mut modest.library);
|
||||
modest.library = library;
|
||||
let dl = evaluate(&modest, 0);
|
||||
assert!(!dl.left_out && dl.items.len() == 1 << 10);
|
||||
}
|
||||
+90
-7
@@ -12,18 +12,80 @@ use crate::{FIELD_GUTTER, LineType, MAX_FIELD_CHARS, Rgba, TextBlock, TextField,
|
||||
use anicraft_geom::{Path, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Where one cluster (a letter with its marks, or a ligature) stands on its line (ADR 0130).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct CaretBox {
|
||||
/// The characters it covers: from `start` up to `end`.
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
/// Its left and right edges, from the text's left edge.
|
||||
pub x0: f32,
|
||||
pub x1: f32,
|
||||
/// It reads right to left.
|
||||
pub rtl: bool,
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// `(index, x)` of the boundaries clusters start at and of the line's end, ascending by
|
||||
/// index; `x` from the text's left edge (the box's, less the gutter). A boundary is at the
|
||||
/// edge its cluster is read from, so in text that mixes directions `x` does not rise with
|
||||
/// the index.
|
||||
pub stops: Vec<(u32, f32)>,
|
||||
/// The paragraph reads right to left: the line starts at its right end (ADR 0130).
|
||||
pub rtl: bool,
|
||||
/// The line's clusters as they are displayed, left to right. Empty: every character reads
|
||||
/// left to right, one after another, as `stops` has them.
|
||||
pub boxes: Vec<CaretBox>,
|
||||
}
|
||||
|
||||
impl CaretLine {
|
||||
/// Whether anything on the line reads right to left.
|
||||
pub fn mixed(&self) -> bool {
|
||||
self.rtl || self.boxes.iter().any(|b| b.rtl)
|
||||
}
|
||||
|
||||
/// The stretches of the line a selection from boundary `a` to `b` highlights, as left and
|
||||
/// right x, left to right. Text in one direction is one stretch; a selection across a change
|
||||
/// of direction is several (ADR 0130). A cluster is highlighted whole.
|
||||
pub fn spans(&self, a: u32, b: u32) -> Vec<(f32, f32)> {
|
||||
let (a, b) = (a.max(self.start), b.min(self.end));
|
||||
if a >= b {
|
||||
return Vec::new();
|
||||
}
|
||||
if self.boxes.is_empty() {
|
||||
let x0 = self.x_at(a);
|
||||
return vec![(x0, self.x_at(b).max(x0))];
|
||||
}
|
||||
let mut out: Vec<(f32, f32)> = Vec::new();
|
||||
for c in self.boxes.iter().filter(|c| c.start < b && c.end > a) {
|
||||
match out.last_mut() {
|
||||
Some(last) if (last.1 - c.x0).abs() < 1e-3 => last.1 = c.x1,
|
||||
_ => out.push((c.x0, c.x1)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The boundary the Left or Right key takes a caret at `i` to: the next place a caret can
|
||||
/// stand in that direction on this line, by where it is displayed. `None` at the line's
|
||||
/// edge. `open`: the line's end is shown on the next line (a wrapped line), so the caret
|
||||
/// doesn't stand there.
|
||||
pub fn step(&self, i: u32, right: bool, open: bool) -> Option<u32> {
|
||||
let mut places: Vec<(u32, f32)> = self.stops.iter().copied().filter(|s| (self.start..=self.end).contains(&s.0) && !(open && s.0 == self.end && s.0 > self.start)).collect();
|
||||
// Left to right; places at one x in the order the paragraph reads.
|
||||
places.sort_by(|p, q| p.1.total_cmp(&q.1).then(if self.rtl { q.0.cmp(&p.0) } else { p.0.cmp(&q.0) }));
|
||||
// Inside a cluster, the caret is at the cluster's start.
|
||||
let here = places.iter().map(|p| p.0).filter(|c| *c <= i).max()?;
|
||||
let at = places.iter().position(|p| p.0 == here)?;
|
||||
let next = if right { at.checked_add(1)? } else { at.checked_sub(1)? };
|
||||
places.get(next).map(|p| p.0)
|
||||
}
|
||||
|
||||
/// 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);
|
||||
@@ -87,6 +149,25 @@ impl FieldLook {
|
||||
Vec2::new(x, n as f32 * self.line_height)
|
||||
}
|
||||
|
||||
/// Where the Left or Right key takes a caret at boundary `i` in text that mixes directions
|
||||
/// (ADR 0130): the next place to that side as displayed, and at a line's edge the line
|
||||
/// before or after it, whichever lies that way in its paragraph's direction. `None` on a
|
||||
/// line that reads left to right throughout: the key moves one character.
|
||||
pub fn step(&self, i: u32, right: bool) -> Option<u32> {
|
||||
let n = self.line_of(i);
|
||||
let line = self.lines.get(n).filter(|l| l.mixed())?;
|
||||
let next = self.lines.get(n + 1);
|
||||
if let Some(to) = line.step(i, right, next.is_some_and(|m| m.start == line.end)) {
|
||||
return Some(to);
|
||||
}
|
||||
// The line's edge: back to the line before, or on to the line after.
|
||||
Some(if right == line.rtl {
|
||||
if n == 0 { i } else { line.start.saturating_sub(1) }
|
||||
} else {
|
||||
next.map_or(i, |m| m.start)
|
||||
})
|
||||
}
|
||||
|
||||
/// 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);
|
||||
@@ -316,12 +397,14 @@ impl Editor<'_> {
|
||||
}
|
||||
Edit::Left if !shift && a != b => moved(self.st, a, false),
|
||||
Edit::Right if !shift && a != b => moved(self.st, b, false),
|
||||
// In text that mixes directions the caret moves the way the key points, as the
|
||||
// text is displayed (ADR 0130); elsewhere one character back or on.
|
||||
Edit::Left => {
|
||||
let to = self.st.caret.saturating_sub(1);
|
||||
let to = look.and_then(|l| l.step(self.st.caret, false)).unwrap_or_else(|| self.st.caret.saturating_sub(1));
|
||||
moved(self.st, to, shift)
|
||||
}
|
||||
Edit::Right => {
|
||||
let to = self.st.caret.saturating_add(1);
|
||||
let to = look.and_then(|l| l.step(self.st.caret, true)).unwrap_or_else(|| self.st.caret.saturating_add(1));
|
||||
moved(self.st, to, shift)
|
||||
}
|
||||
Edit::Home | Edit::End | Edit::Up | Edit::Down => {
|
||||
@@ -422,14 +505,14 @@ pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option<f32>) -> Fiel
|
||||
let mut i = 0u32;
|
||||
for c in text.chars() {
|
||||
if c == '\n' {
|
||||
lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) });
|
||||
lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops), ..CaretLine::default() });
|
||||
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) });
|
||||
lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops), ..CaretLine::default() });
|
||||
(start, col) = (i, 0);
|
||||
stops.push((i, 0.0));
|
||||
}
|
||||
@@ -442,7 +525,7 @@ pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option<f32>) -> Fiel
|
||||
stops.push((i, col as f32 * cw));
|
||||
width = width.max(col as f32 * cw);
|
||||
}
|
||||
lines.push(CaretLine { start, end: i, stops });
|
||||
lines.push(CaretLine { start, end: i, stops, ..CaretLine::default() });
|
||||
let n = lines.len();
|
||||
FieldLook { outline: Arc::new(outline), pieces: Arc::from(Vec::new()), lines: lines.into(), line_height: lh, width, height: n as f32 * lh }
|
||||
}
|
||||
|
||||
@@ -199,3 +199,92 @@ fn restrict_reads_as_actionscript_writes_it() {
|
||||
assert!(allowed(&"\\".repeat(1023), '\\'));
|
||||
}
|
||||
|
||||
|
||||
// Text that mixes directions (ADR 0130). Looks are written by hand, as the layout hands them
|
||||
// over: every character 10 wide, capitals reading right to left.
|
||||
|
||||
fn cell(start: u32, x0: f32, rtl: bool) -> CaretBox {
|
||||
CaretBox { start, end: start + 1, x0, x1: x0 + 10.0, rtl }
|
||||
}
|
||||
|
||||
fn look_of(lines: Vec<CaretLine>) -> FieldLook {
|
||||
let n = lines.len() as f32;
|
||||
FieldLook { outline: Arc::new(Path::new()), pieces: Arc::from(Vec::new()), lines: lines.into(), line_height: 10.0, width: 50.0, height: n * 10.0 }
|
||||
}
|
||||
|
||||
/// "abCDE" in a left-to-right paragraph, displayed a b E D C.
|
||||
fn word_in_latin() -> FieldLook {
|
||||
let boxes = vec![cell(0, 0.0, false), cell(1, 10.0, false), cell(4, 20.0, true), cell(3, 30.0, true), cell(2, 40.0, true)];
|
||||
look_of(vec![CaretLine { start: 0, end: 5, stops: vec![(0, 0.0), (1, 10.0), (2, 50.0), (3, 40.0), (4, 30.0), (5, 20.0)], rtl: false, boxes }])
|
||||
}
|
||||
|
||||
/// "AB CD" in a right-to-left paragraph wrapped after the space: B A on the first line, D C on
|
||||
/// the second, each starting at its right end.
|
||||
fn wrapped_rtl() -> FieldLook {
|
||||
let first = CaretLine { start: 0, end: 3, stops: vec![(0, 20.0), (1, 10.0), (2, 0.0), (3, 0.0)], rtl: true, boxes: vec![cell(1, 0.0, true), cell(0, 10.0, true)] };
|
||||
let second = CaretLine { start: 3, end: 5, stops: vec![(3, 20.0), (4, 10.0), (5, 0.0)], rtl: true, boxes: vec![cell(4, 0.0, true), cell(3, 10.0, true)] };
|
||||
look_of(vec![first, second])
|
||||
}
|
||||
|
||||
/// The carets a key visits from `from`, pressed `n` times.
|
||||
fn walk(text: &str, look: &FieldLook, from: u32, key: Edit, n: usize) -> Vec<u32> {
|
||||
let field = TextField { lines: LineType::Multiline, ..TextField::new(TextKind::Input) };
|
||||
let b = block(text, field.clone());
|
||||
let mut st = FieldState { caret: from, anchor: from, ..FieldState::default() };
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
Editor { block: &b, field: &field, st: &mut st }.key(key, false, Some(look));
|
||||
st.caret
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_move_the_caret_the_way_they_point_through_a_right_to_left_word() {
|
||||
let look = word_in_latin();
|
||||
// Right from the start: past a and b, then through the word from its left (its end) to
|
||||
// its right (its start), where the line ends.
|
||||
assert_eq!(walk("abCDE", &look, 0, Edit::Right, 6), vec![1, 5, 4, 3, 2, 2]);
|
||||
assert_eq!(walk("abCDE", &look, 2, Edit::Left, 6), vec![3, 4, 5, 1, 0, 0]);
|
||||
// Each press moves the caret further the way the key points.
|
||||
let xs: Vec<f32> = [0, 1, 5, 4, 3, 2].iter().map(|i| look.caret_at(*i).x).collect();
|
||||
assert!(xs.windows(2).all(|w| w[0] < w[1]), "{xs:?}");
|
||||
// Shift keeps the anchor: the selection is still a range of characters.
|
||||
let field = TextField::new(TextKind::Input);
|
||||
let b = block("abCDE", field.clone());
|
||||
let mut st = FieldState { caret: 1, anchor: 1, ..FieldState::default() };
|
||||
Editor { block: &b, field: &field, st: &mut st }.key(Edit::Right, true, Some(&look));
|
||||
assert_eq!(st.selection(), (1, 5));
|
||||
// A line that reads left to right throughout moves by characters, as it always has.
|
||||
assert_eq!(mono_look("abc", 10.0, 10.0, None).step(1, true), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_cross_lines_in_the_paragraphs_direction() {
|
||||
let look = wrapped_rtl();
|
||||
// Left reads on in a right-to-left paragraph: to the line's left end, then the next line's
|
||||
// right end. The wrapped line's end is the next line's start, shown there.
|
||||
assert_eq!(walk("AB CD", &look, 0, Edit::Left, 6), vec![1, 2, 3, 4, 5, 5]);
|
||||
assert_eq!(walk("AB CD", &look, 5, Edit::Right, 6), vec![4, 3, 2, 1, 0, 0]);
|
||||
assert_eq!((look.caret_at(3), look.caret_at(2)), (Vec2::new(20.0, 10.0), Vec2::new(0.0, 0.0)));
|
||||
// Home is where the line starts and End where it ends, whichever side that is.
|
||||
assert_eq!(walk("AB CD", &look, 4, Edit::Home, 1), vec![3]);
|
||||
assert_eq!(look.lines[1].x_at(3), 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_across_directions_is_highlighted_in_stretches() {
|
||||
let look = word_in_latin();
|
||||
let line = &look.lines[0];
|
||||
assert_eq!(line.spans(0, 2), vec![(0.0, 20.0)]);
|
||||
assert_eq!(line.spans(2, 5), vec![(20.0, 50.0)], "the whole word");
|
||||
// b and the word's first two letters (C and D, its rightmost): two stretches.
|
||||
assert_eq!(line.spans(1, 4), vec![(10.0, 20.0), (30.0, 50.0)]);
|
||||
assert_eq!(line.spans(0, 9), vec![(0.0, 50.0)]);
|
||||
assert_eq!(line.spans(3, 3), Vec::new());
|
||||
assert_eq!(line.spans(7, 9), Vec::new());
|
||||
// Without boxes (text in one direction): from one caret place to the other.
|
||||
let plain = mono_look("abcd", 10.0, 10.0, None);
|
||||
assert_eq!(plain.lines[0].spans(1, 3), vec![(10.0, 30.0)]);
|
||||
assert!(!plain.lines[0].mixed() && line.mixed() && wrapped_rtl().lines[0].mixed());
|
||||
}
|
||||
+31
-7
@@ -97,11 +97,21 @@ impl Rgba {
|
||||
let c = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
Rgba::new(c(self.r), c(self.g), c(self.b), c(self.a))
|
||||
}
|
||||
/// Always the opaque `#rrggbb`, alpha left out: what the SVG, HTML and Lottie writers and
|
||||
/// the layer colours put where six digits are expected (they carry opacity themselves).
|
||||
/// [`Rgba::to_hex_alpha`] is the form that reads back as the same colour.
|
||||
pub fn to_hex(self) -> String {
|
||||
let s = self.sanitized();
|
||||
let b = |v: f32| (v * 255.0).round() as u8;
|
||||
format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b))
|
||||
}
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque: [`Rgba::parse_hex`] reads it back as the
|
||||
/// same colour, to the 8 bits a channel is written in.
|
||||
pub fn to_hex_alpha(self) -> String {
|
||||
let s = self.sanitized();
|
||||
let a = (s.a * 255.0).round() as u8;
|
||||
if a == u8::MAX { s.to_hex() } else { format!("{}{a:02x}", s.to_hex()) }
|
||||
}
|
||||
/// Parses `#rrggbb`, `rrggbb` or `#rrggbbaa`.
|
||||
pub fn parse_hex(s: &str) -> Option<Rgba> {
|
||||
let s = s.trim();
|
||||
@@ -1106,18 +1116,18 @@ impl Element {
|
||||
}
|
||||
/// Local-space bounds (control-point bounds for shapes, `None` for symbols).
|
||||
pub fn local_bounds(&self, doc: &Document) -> Rect {
|
||||
element_bounds(doc, self, &Affine::IDENTITY, 0, &std::cell::Cell::new(MAX_EVAL_ELEMENTS))
|
||||
element_bounds(doc, self, &Affine::IDENTITY, 0, &eval::Work::new(MAX_EVAL_ELEMENTS))
|
||||
}
|
||||
/// Bounds in the parent's space.
|
||||
pub fn bounds(&self, doc: &Document) -> Rect {
|
||||
element_bounds(doc, self, &self.transform, 0, &std::cell::Cell::new(MAX_EVAL_ELEMENTS))
|
||||
element_bounds(doc, self, &self.transform, 0, &eval::Work::new(MAX_EVAL_ELEMENTS))
|
||||
}
|
||||
}
|
||||
|
||||
/// `work` is the query's allowance of element visits ([`MAX_EVAL_ELEMENTS`]): past it the rest
|
||||
/// adds nothing, as in evaluation.
|
||||
fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize, work: &std::cell::Cell<u32>) -> Rect {
|
||||
if depth > MAX_SYMBOL_DEPTH || !eval::spend(work) {
|
||||
/// `work` is the query's allowance ([`MAX_EVAL_ELEMENTS`]): past it the rest adds nothing, as in
|
||||
/// evaluation. A shape pays for the outline measured here, and a symbol for each of its layers.
|
||||
fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize, work: &eval::Work) -> Rect {
|
||||
if depth > MAX_SYMBOL_DEPTH || !work.visit(el) {
|
||||
return Rect::EMPTY;
|
||||
}
|
||||
match &el.kind {
|
||||
@@ -1135,9 +1145,12 @@ fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize, work:
|
||||
r
|
||||
}
|
||||
ElementKind::Symbol { symbol, .. } => {
|
||||
let Some(sym) = doc.symbol(*symbol) else { return Rect::EMPTY };
|
||||
let Some(sym) = work.symbol(doc, *symbol) else { return Rect::EMPTY };
|
||||
let mut r = Rect::EMPTY;
|
||||
for layer in &sym.timeline.layers {
|
||||
if !work.spend(1) {
|
||||
return r;
|
||||
}
|
||||
if let Some(kf) = layer.keyframes.first() {
|
||||
for child in &kf.elements {
|
||||
let m = xf.mul(&child.transform);
|
||||
@@ -2521,6 +2534,17 @@ mod tests {
|
||||
assert_eq!(LoopMode::Loop.local_frame(u32::MAX, u32::MAX, 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_roundtrip_keeps_alpha() {
|
||||
let c = Rgba::parse_hex("#ff000080").unwrap();
|
||||
assert_eq!(c.to_hex_alpha(), "#ff000080");
|
||||
assert_eq!(Rgba::parse_hex(&c.to_hex_alpha()).unwrap(), c);
|
||||
// Six digits where six are expected, whatever the alpha: the exporters' contract.
|
||||
assert_eq!(c.to_hex(), "#ff0000");
|
||||
// An alpha that rounds to opaque is written as opaque, so both forms agree.
|
||||
assert_eq!(Rgba::new(1.0, 0.0, 0.0, 0.999).to_hex_alpha(), "#ff0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_roundtrip() {
|
||||
let c = Rgba::parse_hex("#ff8000").unwrap();
|
||||
|
||||
+59
-18
@@ -18,7 +18,7 @@ use crate::actions::as3::ir::{Base, Function, ListenEvent, Place, Prop, Value};
|
||||
use crate::actions::as3::run::{self, Stop, World};
|
||||
use crate::actions::as3::{Compiled, Decls, Problem};
|
||||
use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target};
|
||||
use crate::eval::{Play, evaluate_shown, evaluate_symbol, guide_walk};
|
||||
use crate::eval::{Play, Work, evaluate_shown, evaluate_symbol, guide_walk};
|
||||
use crate::field::{Changed, Edit, Editor, FieldLook, FieldState, chars, fit, scroll_to_caret};
|
||||
use crate::html_text::{self, RichStyles};
|
||||
use crate::sound::Started;
|
||||
@@ -38,6 +38,11 @@ pub const MAX_ACTIONS_PER_STEP: usize = 10_000;
|
||||
pub const MAX_ENTERS_PER_STEP: usize = 1_000;
|
||||
/// Most symbol instances the player follows.
|
||||
pub const MAX_NODES: usize = 10_000;
|
||||
/// The work one step may do looking at the movie (ADR 0128): every rebuild of the instance tree
|
||||
/// after a change and every pointer hit test in the step share it, in the units of
|
||||
/// [`crate::MAX_EVAL_ELEMENTS`]. Four full frames' worth: a movie that needs more in one step
|
||||
/// is one no machine plays in time, and a hostile one stops here instead of hanging.
|
||||
pub const MAX_WORK_PER_STEP: u32 = 4 * crate::MAX_EVAL_ELEMENTS;
|
||||
/// Most output lines one step keeps (more are counted).
|
||||
pub const MAX_OUTPUT_PER_STEP: usize = 1_000;
|
||||
/// Most pointer events one step handles.
|
||||
@@ -456,18 +461,24 @@ pub fn input(doc: &Document, state: &PlayerState, events: &[Event], host: &mut d
|
||||
/// The instance tree at `state`: the main timeline (index 0), then every symbol instance in
|
||||
/// drawing order (parents before their contents).
|
||||
pub fn tree(doc: &Document, st: &PlayerState) -> Vec<Node> {
|
||||
tree_in(doc, st, &Work::new(crate::MAX_EVAL_ELEMENTS))
|
||||
}
|
||||
|
||||
/// [`tree`], paid for from `work`: once it is spent the rest of the movie is left out.
|
||||
fn tree_in(doc: &Document, st: &PlayerState, work: &Work) -> Vec<Node> {
|
||||
let tl = doc.timeline(st.scene);
|
||||
let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, local: Affine::IDENTITY, alpha: 1.0, hittable: true, events: Vec::new(), gain: 1.0, text: None }];
|
||||
// The main timeline is seen through its camera (ADR 0027): instances are where the pointer
|
||||
// sees them.
|
||||
let camera = tl.camera_at(st.root.frame, &doc.stage);
|
||||
walk(doc, st, tl, st.root.frame, 0, 0, Affine::IDENTITY, 1, true, camera, &mut out);
|
||||
walk(doc, st, tl, st.root.frame, 0, 0, Affine::IDENTITY, 1, true, camera, work, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The button (or movie clip with event handlers) at stage point `p`, topmost first.
|
||||
pub fn hit(doc: &Document, st: &PlayerState, p: Vec2) -> Option<InstancePath> {
|
||||
hit_in(doc, st, &tree(doc, st), p)
|
||||
let work = Work::new(crate::MAX_EVAL_ELEMENTS);
|
||||
hit_in(doc, st, &tree_in(doc, st, &work), p, &work)
|
||||
}
|
||||
|
||||
/// The text field at stage point `p` the viewer can click into, topmost first (ADR 0066): what
|
||||
@@ -505,7 +516,11 @@ pub fn hit_frame(len: u32) -> u32 {
|
||||
/// shapes count however faint they are drawn). The hit test and Test Movie's hit-area overlay
|
||||
/// both use it.
|
||||
pub fn hit_area(doc: &Document, tl: &Timeline, xf: Affine) -> DisplayList {
|
||||
let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None);
|
||||
hit_area_in(doc, tl, xf, &Work::new(crate::MAX_EVAL_ELEMENTS))
|
||||
}
|
||||
|
||||
fn hit_area_in(doc: &Document, tl: &Timeline, xf: Affine, work: &Work) -> DisplayList {
|
||||
let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None, work);
|
||||
dl.items.retain(|i| !i.guide && i.masks.is_none());
|
||||
dl.links.clear();
|
||||
for i in &mut dl.items {
|
||||
@@ -543,11 +558,14 @@ pub fn tinted(dl: DisplayList, tint: Rgba, alpha: f32) -> DisplayList {
|
||||
/// Areas): where the pointer finds the buttons, drawn over the movie.
|
||||
pub fn hit_overlay(doc: &Document, st: &PlayerState, tint: Rgba, alpha: f32) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
for n in tree(doc, st).iter().filter(|n| n.kind == NodeKind::Button && n.hittable) {
|
||||
if let Some(sym) = n.symbol.and_then(|s| doc.symbol(s)) {
|
||||
out.append(tinted(hit_area(doc, &sym.timeline, n.xf), tint, alpha));
|
||||
// One allowance for the tree and every button's area, however many buttons there are.
|
||||
let work = Work::new(crate::MAX_EVAL_ELEMENTS);
|
||||
for n in tree_in(doc, st, &work).iter().filter(|n| n.kind == NodeKind::Button && n.hittable) {
|
||||
if let Some(sym) = n.symbol.and_then(|s| work.symbol(doc, s)) {
|
||||
out.append(tinted(hit_area_in(doc, &sym.timeline, n.xf, &work), tint, alpha));
|
||||
}
|
||||
}
|
||||
out.left_out = work.ran_out();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -558,7 +576,7 @@ fn plays(tl: &Timeline, index: usize) -> bool {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usize, owner: usize, xf: Affine, depth: usize, hittable: bool, camera: Option<crate::Camera>, out: &mut Vec<Node>) {
|
||||
fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usize, owner: usize, xf: Affine, depth: usize, hittable: bool, camera: Option<crate::Camera>, work: &Work, out: &mut Vec<Node>) {
|
||||
if depth > MAX_SYMBOL_DEPTH {
|
||||
return;
|
||||
}
|
||||
@@ -576,6 +594,11 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
|
||||
if !plays(tl, index) {
|
||||
continue;
|
||||
}
|
||||
// Layers and elements are paid for as the evaluator pays for them, so a timeline of
|
||||
// plain artwork, looked at once for every instance of it, is bounded too.
|
||||
if !work.spend(1) {
|
||||
return;
|
||||
}
|
||||
let gain = parent_gain * layer.sound_gain();
|
||||
let hit = hittable && layer.kind != LayerKind::Mask;
|
||||
let path_walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame));
|
||||
@@ -594,7 +617,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
|
||||
// Instances inside a group belong to the group's timeline (ADR 0073).
|
||||
let els = crate::expand_groups(&els).into_owned();
|
||||
for el in els.iter() {
|
||||
if out.len() >= MAX_NODES {
|
||||
if out.len() >= MAX_NODES || !work.spend(1) {
|
||||
return;
|
||||
}
|
||||
// Dynamic and input text fields are instances scripts can name (static text isn't).
|
||||
@@ -611,7 +634,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
|
||||
continue;
|
||||
}
|
||||
let ElementKind::Symbol { symbol, loop_mode, first_frame, events, .. } = &el.kind else { continue };
|
||||
let Some(sym) = doc.symbol(*symbol) else { continue };
|
||||
let Some(sym) = work.symbol(doc, *symbol) else { continue };
|
||||
let mut path = base.clone();
|
||||
path.push(el.id);
|
||||
let ov = st.props.get(&path);
|
||||
@@ -630,22 +653,27 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
|
||||
// Names inside a movie clip (or a button's states) are its own; a graphic's
|
||||
// contents belong to the timeline the graphic is on.
|
||||
let inner_owner = if kind == NodeKind::Graphic { owner } else { idx };
|
||||
walk(doc, st, &sym.timeline, local, idx, inner_owner, node_xf, depth + 1, hit && shown, None, out);
|
||||
walk(doc, st, &sym.timeline, local, idx, inner_owner, node_xf, depth + 1, hit && shown, None, work, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2) -> Option<InstancePath> {
|
||||
/// `work` pays for every area looked at: each interactive instance is evaluated to find the one
|
||||
/// under the pointer, and they share one allowance instead of having a whole frame's each.
|
||||
fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2, work: &Work) -> Option<InstancePath> {
|
||||
for n in nodes.iter().rev() {
|
||||
let interactive = n.kind == NodeKind::Button || (n.kind == NodeKind::MovieClip && (!n.events.is_empty() || st.listeners.contains_key(&n.path)));
|
||||
if !n.hittable || !interactive {
|
||||
continue;
|
||||
}
|
||||
let Some(sym) = n.symbol.and_then(|s| doc.symbol(s)) else { continue };
|
||||
if work.ran_out() {
|
||||
return None;
|
||||
}
|
||||
let Some(sym) = n.symbol.and_then(|s| work.symbol(doc, s)) else { continue };
|
||||
let dl = if n.kind == NodeKind::Button {
|
||||
hit_area(doc, &sym.timeline, n.xf)
|
||||
hit_area_in(doc, &sym.timeline, n.xf, work)
|
||||
} else {
|
||||
evaluate_symbol(doc, &sym.timeline, n.frame, n.xf, Some(&Play { state: st, path: n.path.clone() }))
|
||||
evaluate_symbol(doc, &sym.timeline, n.frame, n.xf, Some(&Play { state: st, path: n.path.clone() }), work)
|
||||
};
|
||||
let inside = dl.items.iter().filter(|i| !i.guide && i.masks.is_none()).any(|i| {
|
||||
let fill = i.fill.is_some() && i.path.contains(p, &i.transform, i.fill_rule);
|
||||
@@ -694,11 +722,13 @@ struct Run<'a, 'h> {
|
||||
decls: BTreeMap<TimelineRef, Arc<Decls>>,
|
||||
/// Script fuel left this step.
|
||||
fuel: u64,
|
||||
/// What is left of [`MAX_WORK_PER_STEP`].
|
||||
work: Work,
|
||||
}
|
||||
|
||||
impl<'a, 'h> Run<'a, 'h> {
|
||||
fn new(doc: &'a Document, st: PlayerState, host: &'h mut dyn ScriptHost) -> Self {
|
||||
Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new(), decls: BTreeMap::new(), fuel: MAX_FUEL_PER_STEP }
|
||||
Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new(), decls: BTreeMap::new(), fuel: MAX_FUEL_PER_STEP, work: Work::new(MAX_WORK_PER_STEP) }
|
||||
}
|
||||
|
||||
fn remember_graphics(&mut self) {
|
||||
@@ -776,6 +806,15 @@ impl<'a, 'h> Run<'a, 'h> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The step's allowance of work ran out ([`MAX_WORK_PER_STEP`]): nothing more runs this
|
||||
/// step, and the Output panel says why, once.
|
||||
fn overworked(&mut self) {
|
||||
if self.work.ran_out() && !self.halted {
|
||||
self.halted = true;
|
||||
self.out("Stopped this frame early: the movie holds more than one frame may look at, so some instances and buttons were left out (symbols nested in themselves?)");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds the instance tree after a change, starting movie clips that appeared (they
|
||||
/// enter their first frame) and forgetting those that left.
|
||||
fn refresh(&mut self) {
|
||||
@@ -788,7 +827,8 @@ impl<'a, 'h> Run<'a, 'h> {
|
||||
}
|
||||
let n = self.doc.timeline(self.st.scene).frame_count();
|
||||
self.st.root.frame = self.st.root.frame.min(n.saturating_sub(1));
|
||||
self.nodes = tree(self.doc, &self.st);
|
||||
self.nodes = tree_in(self.doc, &self.st, &self.work);
|
||||
self.overworked();
|
||||
let live: std::collections::BTreeSet<&InstancePath> = self.nodes.iter().filter(|n| n.kind == NodeKind::MovieClip).map(|n| &n.path).collect();
|
||||
self.st.clips.retain(|p, _| live.contains(p));
|
||||
for p in live {
|
||||
@@ -1590,7 +1630,8 @@ impl<'a, 'h> Run<'a, 'h> {
|
||||
if let Some(p) = p {
|
||||
self.st.mouse = p;
|
||||
}
|
||||
let now = p.and_then(|p| hit_in(self.doc, &self.st, &self.nodes, p));
|
||||
let now = p.and_then(|p| hit_in(self.doc, &self.st, &self.nodes, p, &self.work));
|
||||
self.overworked();
|
||||
if now != self.st.hover {
|
||||
let before = self.pointer_now();
|
||||
let old = std::mem::replace(&mut self.st.hover, now.clone());
|
||||
|
||||
@@ -929,3 +929,36 @@ fn max_chars_and_restrict_limit_what_the_viewer_types() {
|
||||
assert_eq!(text_of(&type_into_name(&d, &s.state, "ok").state, 6).as_deref(), Some("ok"));
|
||||
}
|
||||
|
||||
|
||||
/// ADR 0128: a step looks at the movie many times (the instance tree after every change, a hit
|
||||
/// test for every pointer event), and all of it comes out of one allowance. Movie clips that
|
||||
/// double at each level, each over a thousand plain shapes, stop the step with a line in the
|
||||
/// Output panel instead of holding the window; the next step is bounded the same way.
|
||||
#[test]
|
||||
fn a_step_over_a_movie_too_large_to_look_at_stops_and_says_so() {
|
||||
let mut d = crate::eval::tests::doubling_doc(31);
|
||||
for sym in &mut d.library {
|
||||
let sym = Arc::make_mut(sym);
|
||||
sym.kind = SymbolKind::MovieClip;
|
||||
let mut artwork = Layer::new(LayerId(7000), "artwork");
|
||||
artwork.keyframes = vec![kf(0, 1, (0..1000).map(|i| rect(50_000 + i, 0.0, 0.0, 4.0, 4.0)).collect(), vec![], "")];
|
||||
sym.timeline.layers.push(Arc::new(artwork));
|
||||
}
|
||||
let first = start(&d, &mut NoScripts);
|
||||
assert!(first.output.iter().any(|l| l.contains("left out")), "{:?}", first.output);
|
||||
let next = step(&d, &first.state, &[Event::Move(Vec2::new(1.0, 1.0)), Event::Down(Vec2::new(1.0, 1.0))], &mut NoScripts);
|
||||
assert_eq!(next.output.iter().filter(|l| l.contains("left out")).count(), 1, "said once a step: {:?}", next.output);
|
||||
// What draws the movie and its hit areas marks the same.
|
||||
assert!(evaluate_player(&d, &next.state).left_out);
|
||||
// Buttons instead: every button's hit area is a frame's worth of artwork, and the overlay
|
||||
// shows them all from one allowance.
|
||||
for sym in &mut d.library {
|
||||
Arc::make_mut(sym).kind = SymbolKind::Button;
|
||||
}
|
||||
assert!(hit_overlay(&d, &PlayerState::default(), Rgba::WHITE, 0.4).left_out);
|
||||
assert_eq!(hit(&d, &PlayerState::default(), Vec2::new(-500.0, -500.0)), None);
|
||||
// An ordinary movie is not marked.
|
||||
let small = sample::interactive();
|
||||
let s = run(&small, 3);
|
||||
assert!(!s.output.iter().any(|l| l.contains("left out")) && !evaluate_player(&small, &s.state).left_out);
|
||||
}
|
||||
@@ -242,6 +242,36 @@ pub fn interactive() -> Document {
|
||||
d
|
||||
}
|
||||
|
||||
/// A document whose symbols double at every level: `levels` symbols in a chain, each holding
|
||||
/// two instances of the next and the last one a square, so the one instance on the stage is
|
||||
/// 2^(`levels` - 1) squares, with no cycle anywhere and nothing nested deeper than
|
||||
/// [`crate::MAX_SYMBOL_DEPTH`]. Past twenty levels it is more than a frame's allowance of work
|
||||
/// ([`crate::MAX_EVAL_ELEMENTS`], ADR 0128): what tests and benchmarks use for a document too
|
||||
/// large to draw.
|
||||
pub fn doubling(levels: u32) -> Document {
|
||||
let levels = u64::from(levels.clamp(1, 31));
|
||||
let mut d = Document::default();
|
||||
let at = |id: u64, x: f32, kind: ElementKind| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 0.0), color: ColorEffect::default(), kind });
|
||||
let on_one_layer = |id: u64, elements: Vec<Arc<Element>>| {
|
||||
let mut l = Layer::new(LayerId(id), "l");
|
||||
l.keyframes = vec![Arc::new(key(0, 1, elements, None))];
|
||||
Timeline { layers: vec![Arc::new(l)] }
|
||||
};
|
||||
for level in 0..levels {
|
||||
let elements = if level + 1 == levels {
|
||||
vec![at(5000, 0.0, ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK))))]
|
||||
} else {
|
||||
vec![at(2000 + level, 0.0, instance(SymbolId(101 + level))), at(3000 + level, 1.0, instance(SymbolId(101 + level)))]
|
||||
};
|
||||
let timeline = on_one_layer(1000 + level, elements);
|
||||
d.library.push(Arc::new(Symbol { id: SymbolId(100 + level), name: format!("s{level}"), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline }));
|
||||
}
|
||||
let root = on_one_layer(1, vec![at(1, 0.0, instance(SymbolId(100)))]);
|
||||
d.timeline_mut(0).layers = root.layers;
|
||||
d.next_id = 10_000;
|
||||
d
|
||||
}
|
||||
|
||||
/// Deterministic stress document for benchmarks and scaling tests: `layers` layers with
|
||||
/// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens.
|
||||
/// Every element keeps one `Arc<Path>` across its keyframes, as a real tweened shape does.
|
||||
|
||||
@@ -30,6 +30,7 @@ regex.workspace = true
|
||||
craft-csv.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
anicraft-xml.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).
|
||||
|
||||
@@ -371,12 +371,13 @@ pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let mut shown: Vec<(u64, u64)> = Vec::new();
|
||||
let mut encoded: Vec<Encoded> = Vec::new();
|
||||
let mut prev: Option<Vec<u8>> = None;
|
||||
let cut = crate::left_out::LeftOut::default();
|
||||
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)?;
|
||||
let (pm, _) = render(&cut.evaluate(doc, f), &view)?;
|
||||
crate::publish::tick(job, 1)?;
|
||||
Ok(pm.to_rgba8())
|
||||
})
|
||||
@@ -437,7 +438,7 @@ pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
crate::vfs::write(&path, &bytes)?;
|
||||
Ok(json!({
|
||||
Ok(cut.noted(json!({
|
||||
"written": path.display().to_string(),
|
||||
"frames": n,
|
||||
"stored_frames": encoded.len(),
|
||||
@@ -446,7 +447,7 @@ pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
"height": h,
|
||||
"loop": plays,
|
||||
"ms": started.elapsed().as_millis() as u64,
|
||||
}))
|
||||
})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -421,3 +421,35 @@ fn crossing_brush_strokes_keep_what_was_drawn() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ADR 0129: an outline traced ahead (on the editor's other thread) is painted by the
|
||||
/// `draw.brush` that asks for exactly that stroke, and by no other. Either way it is gone
|
||||
/// afterwards, so it can never be painted by a later stroke.
|
||||
#[test]
|
||||
fn an_outline_traced_ahead_is_taken_by_its_own_stroke_only() {
|
||||
let stroke = json!({"points": [[100, 100], [220, 130], [300, 90]], "size": 12, "color": "#000000"});
|
||||
let other = json!({"points": [[100, 100], [220, 130], [300, 95]], "size": 12, "color": "#000000"});
|
||||
// A marker no trace would give: a square far from the stroke.
|
||||
let marker = anicraft_geom::Path::rect(600.0, 400.0, 50.0, 50.0);
|
||||
let painted_at = |staged: &Value, painted: &Value| {
|
||||
let mut s = blank(true);
|
||||
let ahead = crate::cmds_brush::stroke_request(&s, staged).unwrap().prepare();
|
||||
s.staged_stroke = Some(ahead.with_path(marker.clone()));
|
||||
run(&mut s, "draw.brush", painted.clone());
|
||||
assert!(s.staged_stroke.is_none(), "it doesn't linger");
|
||||
(top_at(&s, Vec2::new(625.0, 425.0)).is_some(), top_at(&s, Vec2::new(220.0, 130.0)).is_some())
|
||||
};
|
||||
assert_eq!(painted_at(&stroke, &stroke), (true, false), "its own stroke takes the outline as it is");
|
||||
assert_eq!(painted_at(&stroke, &other), (false, true), "another stroke traces its own");
|
||||
// Traced ahead or by the command: the same document.
|
||||
let mut plain = blank(true);
|
||||
run(&mut plain, "draw.brush", stroke.clone());
|
||||
let mut ahead = blank(true);
|
||||
ahead.staged_stroke = Some(crate::cmds_brush::stroke_request(&ahead, &stroke).unwrap().prepare());
|
||||
run(&mut ahead, "draw.brush", stroke.clone());
|
||||
assert_eq!(shapes(&plain), shapes(&ahead));
|
||||
// A stroke that fails leaves nothing staged either.
|
||||
plain.staged_stroke = Some(crate::cmds_brush::stroke_request(&plain, &stroke).unwrap().prepare());
|
||||
assert!(plain.execute("draw.brush", &json!({"points": []})).is_err());
|
||||
assert!(plain.staged_stroke.is_none());
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, MAX_WIDTH_POINTS, Paint, Rgba, Shape, Stroke, WidthPoint, WidthProfile};
|
||||
use anicraft_geom::planar;
|
||||
use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tilt, Tip, TipShape, centre_stroke, outline_shaped};
|
||||
use anicraft_geom::brush::{MAX_SAMPLES, Sample, Shaping, Tilt, Tip, TipShape, centre_stroke, outline_shaped};
|
||||
use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
@@ -237,31 +237,97 @@ fn paint_stacks(p: &Paint) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// What a Brush stroke's outline is traced from: the samples (their pressure already through
|
||||
/// the brush's curve), the tip, the shaping, and how closely the hand and the outline are
|
||||
/// followed. Tracing is the slow part of a long stroke and depends on nothing else, so the
|
||||
/// editor does it on another thread and hands the result to `draw.brush` (ADR 0129).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct StrokeRequest {
|
||||
pts: Vec<Sample>,
|
||||
tip: Tip,
|
||||
shaping: Shaping,
|
||||
smoothing: f32,
|
||||
tol: f32,
|
||||
}
|
||||
|
||||
impl StrokeRequest {
|
||||
/// The filled outline (`geom::brush::outline_shaped`). Bounded for any stroke: the grid by
|
||||
/// `MAX_CELLS`, the sampling by `MAX_STAMP_WORK`, the loops by `MAX_LOOPS`.
|
||||
pub fn trace(&self) -> Path {
|
||||
outline_shaped(&self.pts, &self.tip, &self.shaping, self.smoothing, self.tol)
|
||||
}
|
||||
|
||||
/// Traces the outline: what [`Session::staged_stroke`] takes.
|
||||
pub fn prepare(self) -> PreparedStroke {
|
||||
let path = self.trace();
|
||||
PreparedStroke { request: self, path }
|
||||
}
|
||||
|
||||
/// How many samples the stroke has.
|
||||
pub fn samples(&self) -> usize {
|
||||
self.pts.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's outline, traced ahead of the command that paints it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PreparedStroke {
|
||||
request: StrokeRequest,
|
||||
path: Path,
|
||||
}
|
||||
|
||||
impl PreparedStroke {
|
||||
/// The same request with another outline, so a test can tell a taken outline from a traced
|
||||
/// one.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_path(self, path: Path) -> PreparedStroke {
|
||||
PreparedStroke { path, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
/// The request `draw.brush` with params `p` would trace. An error is the command's own (the
|
||||
/// same params fail the same way there).
|
||||
pub fn stroke_request(s: &Session, p: &Value) -> Result<StrokeRequest> {
|
||||
stroke_inputs(s, p).map(|x| x.0)
|
||||
}
|
||||
|
||||
/// [`stroke_request`], with the brush it paints with and the opacity its pressure gives it.
|
||||
fn stroke_inputs(s: &Session, p: &Value) -> Result<(StrokeRequest, BrushPreset, f32)> {
|
||||
let pts = bounded_samples(p)?;
|
||||
let b = brush_param(s, p)?;
|
||||
let tip = b.tip();
|
||||
let size = tip.size;
|
||||
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, 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)?;
|
||||
let opacity = pressure_opacity(&b, &pts);
|
||||
// Pressure through the curve (ADR 0068) before it sizes the tip.
|
||||
let pts: Vec<Sample> = pts.iter().map(|x| Sample { pressure: b.size_pressure(x.pressure), ..*x }).collect();
|
||||
|
||||
// Smoothing and accuracy are screen distances, so a stroke looks the same at any zoom: at 50
|
||||
// the centre line may wander 3.3 screen points from the hand, at 0 a third of a point.
|
||||
// The outline is fitted within a third of a screen point, or a hundredth of the size for
|
||||
// small brushes (so a small dab is still round).
|
||||
let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(size * 0.01));
|
||||
let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(tip.size * 0.01));
|
||||
Ok((StrokeRequest { pts, tip, shaping: b.shaping(), smoothing, tol }, b, opacity))
|
||||
}
|
||||
|
||||
fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// An outline traced ahead is this stroke's or nobody's: it never waits for a later one.
|
||||
let staged = s.staged_stroke.take();
|
||||
let (request, b, opacity) = stroke_inputs(s, p)?;
|
||||
let pts = &request.pts;
|
||||
let (smoothing, tol) = (request.smoothing, request.tol);
|
||||
let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false);
|
||||
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, 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 * opacity, ..color };
|
||||
let object = object_param(s, p)?;
|
||||
if as_stroke {
|
||||
return paint_stroke(s, &pts, &b, smoothing, tol, color, object);
|
||||
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);
|
||||
let mut path = match staged {
|
||||
Some(ahead) if ahead.request == request => ahead.path,
|
||||
_ => request.trace(),
|
||||
};
|
||||
if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) {
|
||||
return Err(EngineError::Param("the stroke is too small to paint".into()));
|
||||
}
|
||||
|
||||
@@ -1073,7 +1073,7 @@ fn selection_list(s: &Session) -> anicraft_doc::DisplayList {
|
||||
i
|
||||
})
|
||||
.collect();
|
||||
anicraft_doc::DisplayList { items, clip_parents, clip_modes: full.clip_modes.clone(), groups, links: Vec::new() }
|
||||
anicraft_doc::DisplayList { items, clip_parents, clip_modes: full.clip_modes.clone(), groups, links: Vec::new(), left_out: full.left_out }
|
||||
}
|
||||
|
||||
/// Convert to Bitmap (#463): the selection, drawn by the CPU renderer on whole pixels of the
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! File, edit-history and document commands.
|
||||
|
||||
use crate::left_out::LeftOut;
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session, format};
|
||||
use anicraft_doc::{Document, MAX_STAGE_EDGE, Stage, sample};
|
||||
@@ -261,7 +262,12 @@ pub(crate) fn scale_param(p: &Value) -> Result<f32> {
|
||||
|
||||
/// Renders movie frame `frame` (scenes in order) of `doc` to PNG bytes.
|
||||
pub fn render_png(doc: &Document, frame: u32, scale: f32) -> Result<Vec<u8>> {
|
||||
let dl = anicraft_doc::evaluate(doc, frame);
|
||||
render_png_noting(doc, frame, scale, &LeftOut::default())
|
||||
}
|
||||
|
||||
/// [`render_png`], noting in `cut` a frame whose artwork was left out (ADR 0128).
|
||||
pub fn render_png_noting(doc: &Document, frame: u32, scale: f32, cut: &LeftOut) -> Result<Vec<u8>> {
|
||||
let dl = cut.evaluate(doc, frame);
|
||||
let (pm, _) = render(&dl, &View::stage(doc, scale))?;
|
||||
Ok(pm.encode_png()?)
|
||||
}
|
||||
@@ -270,9 +276,10 @@ fn export_png(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame);
|
||||
// `frame` is within the current scene; the renderer takes movie frames.
|
||||
let bytes = render_png(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), scale_param(p)?)?;
|
||||
let cut = LeftOut::default();
|
||||
let bytes = render_png_noting(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), scale_param(p)?, &cut)?;
|
||||
crate::vfs::write(&path, &bytes)?;
|
||||
Ok(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame}))
|
||||
Ok(cut.noted(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame})))
|
||||
}
|
||||
|
||||
/// Largest file Import to Stage reads.
|
||||
@@ -524,9 +531,16 @@ fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec<u8>) -> Resu
|
||||
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) }]))
|
||||
}
|
||||
|
||||
/// Movie frame `frame` as a standalone SVG document (vectors, gradients and masks kept).
|
||||
/// [`frame_svg_noting`] for a frame known to be whole: what tests compare a written file with.
|
||||
#[cfg(test)]
|
||||
pub fn frame_svg(doc: &Document, frame: u32) -> String {
|
||||
anicraft_render::svg::to_svg(&anicraft_doc::evaluate(doc, frame), &doc.stage)
|
||||
frame_svg_noting(doc, frame, &LeftOut::default())
|
||||
}
|
||||
|
||||
/// Movie frame `frame` as a standalone SVG document (vectors, gradients and masks kept),
|
||||
/// noting in `cut` a frame whose artwork was left out (ADR 0128).
|
||||
pub fn frame_svg_noting(doc: &Document, frame: u32, cut: &LeftOut) -> String {
|
||||
anicraft_render::svg::to_svg(&cut.evaluate(doc, frame), &doc.stage)
|
||||
}
|
||||
|
||||
fn export_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -535,9 +549,10 @@ fn export_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if frame >= s.frame_count() {
|
||||
return Err(EngineError::Param(format!("frame {} is past the end (the timeline has {} frames)", u64::from(frame) + 1, s.frame_count())));
|
||||
}
|
||||
let svg = frame_svg(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame));
|
||||
let cut = LeftOut::default();
|
||||
let svg = frame_svg_noting(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), &cut);
|
||||
crate::vfs::write(&path, svg.as_bytes())?;
|
||||
Ok(json!({"written": path.display().to_string(), "bytes": svg.len(), "frame": frame}))
|
||||
Ok(cut.noted(json!({"written": path.display().to_string(), "bytes": svg.len(), "frame": frame})))
|
||||
}
|
||||
|
||||
/// Export Sprite Sheet: movie frames in a grid on one PNG (transparent unless `background`),
|
||||
@@ -578,10 +593,11 @@ fn export_sprite_sheet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = &s.doc;
|
||||
// A publish counts the frames, and stops between them when cancelled (ADR 0060).
|
||||
let job = s.job.as_deref();
|
||||
let cut = LeftOut::default();
|
||||
let frames: Vec<anicraft_render::Pixmap> = (from..=to)
|
||||
.into_par_iter()
|
||||
.map(|f| {
|
||||
let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?;
|
||||
let (pm, _) = render(&cut.evaluate(doc, f), &view)?;
|
||||
crate::publish::tick(job, 1)?;
|
||||
Ok(pm)
|
||||
})
|
||||
@@ -631,7 +647,7 @@ fn export_sprite_sheet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = serde_json::to_string_pretty(&atlas).map_err(|e| EngineError::Format(e.to_string()))?;
|
||||
crate::vfs::write(&path, &png)?;
|
||||
crate::vfs::write(&json_path, text)?;
|
||||
Ok(json!({"written": path.display().to_string(), "map": json_path.display().to_string(), "frames": n, "columns": cols, "rows": rows, "width": sheet_w, "height": sheet_h}))
|
||||
Ok(cut.noted(json!({"written": path.display().to_string(), "map": json_path.display().to_string(), "frames": n, "columns": cols, "rows": rows, "width": sheet_w, "height": sheet_h})))
|
||||
}
|
||||
|
||||
/// The ffmpeg to run: `ffmpeg` param, else `ANICRAFT_FFMPEG`, else `ffmpeg` on the PATH.
|
||||
@@ -714,11 +730,12 @@ fn export_video(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = &s.doc;
|
||||
let job = s.job.as_deref();
|
||||
let mut written = 0u32;
|
||||
let cut = LeftOut::default();
|
||||
let mut failure: Option<EngineError> = None;
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
let frames: Vec<u32> = (from..=to).collect();
|
||||
'batches: for batch in frames.chunks(8) {
|
||||
let images: Vec<Vec<u8>> = match batch.par_iter().map(|&f| render(&anicraft_doc::evaluate(doc, f), &view).map(|(pm, _)| pm.to_rgba8())).collect::<std::result::Result<_, _>>() {
|
||||
let images: Vec<Vec<u8>> = match batch.par_iter().map(|&f| render(&cut.evaluate(doc, f), &view).map(|(pm, _)| pm.to_rgba8())).collect::<std::result::Result<_, _>>() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
failure = Some(e.into());
|
||||
@@ -754,7 +771,7 @@ fn export_video(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Format(format!("ffmpeg could not make the video ({status}): {}", if tail.is_empty() { "no message".to_string() } else { tail.join(" | ") })));
|
||||
}
|
||||
let bytes = crate::vfs::len(&path).unwrap_or(0);
|
||||
Ok(json!({"written": path.display().to_string(), "frames": written, "bytes": bytes, "width": w, "height": h, "fps": fps, "audio": track.is_some()}))
|
||||
Ok(cut.noted(json!({"written": path.display().to_string(), "frames": written, "bytes": bytes, "width": w, "height": h, "fps": fps, "audio": track.is_some()})))
|
||||
}
|
||||
|
||||
fn export_sequence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -775,16 +792,17 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = &s.doc;
|
||||
let job = s.job.as_deref();
|
||||
let mut files = 0usize;
|
||||
let cut = LeftOut::default();
|
||||
let frames: Vec<u32> = (from..=to).collect();
|
||||
for batch in frames.chunks(64) {
|
||||
let pngs = batch.par_iter().map(|&f| render_png(doc, f, scale)).collect::<Result<Vec<_>>>()?;
|
||||
let pngs = batch.par_iter().map(|&f| render_png_noting(doc, f, scale, &cut)).collect::<Result<Vec<_>>>()?;
|
||||
for (f, png) in batch.iter().zip(pngs) {
|
||||
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()}))
|
||||
Ok(cut.noted(json!({"frames": files, "dir": dir.display().to_string()})))
|
||||
}
|
||||
|
||||
/// Export SVG Sequence (#504): every movie frame as its own SVG file, named like the PNG
|
||||
@@ -804,9 +822,10 @@ fn export_svg_sequence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = &s.doc;
|
||||
let job = s.job.as_deref();
|
||||
let (mut files, mut bytes) = (0usize, 0u64);
|
||||
let cut = LeftOut::default();
|
||||
let frames: Vec<u32> = (from..=to).collect();
|
||||
for batch in frames.chunks(16) {
|
||||
let svgs: Vec<String> = batch.par_iter().map(|&f| frame_svg(doc, f)).collect();
|
||||
let svgs: Vec<String> = batch.par_iter().map(|&f| frame_svg_noting(doc, f, &cut)).collect();
|
||||
for (f, svg) in batch.iter().zip(svgs) {
|
||||
bytes = bytes.saturating_add(svg.len() as u64);
|
||||
crate::vfs::write(&dir.join(format!("frame_{:05}.svg", f + 1)), svg.as_bytes())?;
|
||||
@@ -814,7 +833,7 @@ fn export_svg_sequence(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
crate::publish::tick(job, batch.len() as u64)?;
|
||||
}
|
||||
Ok(json!({"frames": files, "bytes": bytes, "dir": dir.display().to_string()}))
|
||||
Ok(cut.noted(json!({"frames": files, "bytes": bytes, "dir": dir.display().to_string()})))
|
||||
}
|
||||
|
||||
/// Largest GIF we produce (frames × pixels), keeping memory and time bounded.
|
||||
@@ -921,11 +940,12 @@ fn export_gif(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = &s.doc;
|
||||
let job = s.job.as_deref();
|
||||
let delays = gif_delays(n as usize, doc.stage.fps);
|
||||
let cut = LeftOut::default();
|
||||
let frames: Vec<(craft_gif::write::PreparedFrame, u16)> = (from..to.saturating_add(1))
|
||||
.into_par_iter()
|
||||
.zip(delays.into_par_iter())
|
||||
.map(|(f, delay)| {
|
||||
let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?;
|
||||
let (pm, _) = render(&cut.evaluate(doc, f), &view)?;
|
||||
let rgba = pm.to_rgba8();
|
||||
let frame = craft_gif::write::prepare_frame(u32::from(w), u32::from(h), rgba, 10)
|
||||
.map_err(|e| EngineError::Format(e.to_string()))?;
|
||||
@@ -943,7 +963,7 @@ fn export_gif(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
crate::vfs::write(&path, &bytes)?;
|
||||
Ok(json!({"written": path.display().to_string(), "frames": n, "bytes": bytes.len(), "width": w, "height": h}))
|
||||
Ok(cut.noted(json!({"written": path.display().to_string(), "frames": n, "bytes": bytes.len(), "width": w, "height": h})))
|
||||
}
|
||||
|
||||
fn set_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -414,7 +414,7 @@ fn pick_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if other {
|
||||
st.stroke = color;
|
||||
st.use_stroke = true;
|
||||
return Ok(json!({"picked": "fill", "into": "stroke", "paint": paint_kind(&paint), "color": color.to_hex()}));
|
||||
return Ok(json!({"picked": "fill", "into": "stroke", "paint": paint_kind(&paint), "color": hex_alpha(color)}));
|
||||
}
|
||||
st.fill = color;
|
||||
st.fill_paint = (!matches!(paint, Paint::Solid(_))).then(|| paint.clone());
|
||||
@@ -423,13 +423,13 @@ fn pick_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.lock_fill = true;
|
||||
}
|
||||
st.use_fill = true;
|
||||
Ok(json!({"picked": "fill", "into": "fill", "paint": paint_kind(&paint), "color": color.to_hex()}))
|
||||
Ok(json!({"picked": "fill", "into": "fill", "paint": paint_kind(&paint), "color": hex_alpha(color)}))
|
||||
}
|
||||
Some(Picked::Line(stroke, scale)) => {
|
||||
if other {
|
||||
st.set_fill_color(stroke.color);
|
||||
st.use_fill = true;
|
||||
return Ok(json!({"picked": "line", "into": "fill", "paint": "solid", "color": stroke.color.to_hex()}));
|
||||
return Ok(json!({"picked": "line", "into": "fill", "paint": "solid", "color": hex_alpha(stroke.color)}));
|
||||
}
|
||||
st.stroke = stroke.color;
|
||||
st.stroke_width = (stroke.width * scale).clamp(0.1, 1000.0);
|
||||
@@ -447,7 +447,7 @@ fn pick_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"custom"
|
||||
}
|
||||
};
|
||||
Ok(json!({"picked": "line", "into": "stroke", "color": stroke.color.to_hex(), "width": st.stroke_width, "profile": profile, "cap": st.line.cap.key(), "join": st.line.join.key(), "style": st.line.dash_kind().key()}))
|
||||
Ok(json!({"picked": "line", "into": "stroke", "color": hex_alpha(stroke.color), "width": st.stroke_width, "profile": profile, "cap": st.line.cap.key(), "join": st.line.join.key(), "style": st.line.dash_kind().key()}))
|
||||
}
|
||||
None => Err(EngineError::State("click a fill or a line to pick its colour".into())),
|
||||
}
|
||||
@@ -598,8 +598,7 @@ impl FillSpec {
|
||||
|
||||
/// `#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) }
|
||||
c.to_hex_alpha()
|
||||
}
|
||||
|
||||
/// A fill as `paint.set_fill` reports it (in its own params' terms).
|
||||
|
||||
@@ -48,8 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// `#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) }
|
||||
c.to_hex_alpha()
|
||||
}
|
||||
|
||||
fn stops_json(stops: &[GradientStop]) -> Value {
|
||||
|
||||
@@ -302,16 +302,18 @@ fn rich_parts(d: &TextBlock) -> (Vec<anicraft_text::Run>, Vec<anicraft_text::Par
|
||||
|
||||
/// The block with its outline from laid-out pieces and its runs' fonts the families actually
|
||||
/// used; with a note when a family asked for isn't installed.
|
||||
fn finish(mut d: TextBlock, pieces: Vec<(u32, Path)>, families: &[String], paints: &[(Rgba, String)]) -> (TextBlock, Option<String>) {
|
||||
let mut note = None;
|
||||
fn finish(mut d: TextBlock, pieces: Vec<(u32, Path)>, used: Used, paints: &[(Rgba, String)]) -> (TextBlock, Option<String>) {
|
||||
let mut notes: Vec<String> = Vec::new();
|
||||
let mut runs = d.styled_runs();
|
||||
for (r, used) in runs.iter_mut().zip(families) {
|
||||
for (r, used) in runs.iter_mut().zip(used.families) {
|
||||
let asked = r.style.font.trim();
|
||||
if note.is_none() && !asked.is_empty() && !used.eq_ignore_ascii_case(asked) {
|
||||
note = Some(format!("“{asked}” isn't installed on this computer; used {used}"));
|
||||
if notes.is_empty() && !asked.is_empty() && !used.eq_ignore_ascii_case(asked) {
|
||||
notes.push(format!("“{asked}” isn't installed on this computer; used {used}"));
|
||||
}
|
||||
r.style.font.clone_from(used);
|
||||
}
|
||||
notes.extend(borrowed_note(used.fallbacks, used.missing));
|
||||
let note = (!notes.is_empty()).then(|| notes.join("; "));
|
||||
let paras = d.paragraph_styles();
|
||||
d.set_styles(runs, paras);
|
||||
let pieces = pieces.into_iter().map(|(k, p)| paints.get(k as usize).map_or((d.color, String::new(), p.clone()), |(c, u)| (*c, u.clone(), p))).collect();
|
||||
@@ -319,6 +321,36 @@ fn finish(mut d: TextBlock, pieces: Vec<(u32, Path)>, families: &[String], paint
|
||||
(d, note)
|
||||
}
|
||||
|
||||
/// What a layout drew a block with: each run's family, the families that lent letters the
|
||||
/// runs' own faces lack, and how many characters no face has (ADR 0130).
|
||||
struct Used<'a> {
|
||||
families: &'a [String],
|
||||
fallbacks: &'a [String],
|
||||
missing: usize,
|
||||
}
|
||||
|
||||
/// What to tell the user when a block's fonts don't have all of its letters: which families
|
||||
/// the others were drawn from, and how many show as boxes because no installed font has them.
|
||||
/// The block keeps the font that was chosen, so nothing else says so.
|
||||
pub(crate) fn borrowed_note(fallbacks: &[String], missing: usize) -> Option<String> {
|
||||
let mut notes = Vec::new();
|
||||
match fallbacks {
|
||||
[] => {}
|
||||
[one] => notes.push(format!("letters the font doesn't have are drawn in {one}")),
|
||||
[first, rest @ ..] => {
|
||||
let shown: Vec<&str> = rest.iter().take(3).map(String::as_str).collect();
|
||||
let more = if rest.len() > shown.len() { " and other fonts" } else { "" };
|
||||
notes.push(format!("letters the font doesn't have are drawn in {first}, {}{more}", shown.join(", ")));
|
||||
}
|
||||
}
|
||||
match missing {
|
||||
0 => {}
|
||||
1 => notes.push("1 character isn't in any installed font and shows as a box".to_string()),
|
||||
n => notes.push(format!("{n} characters aren't in any installed font and show as boxes")),
|
||||
}
|
||||
(!notes.is_empty()).then(|| notes.join("; "))
|
||||
}
|
||||
|
||||
fn layout_err(e: anicraft_text::TextError) -> EngineError {
|
||||
EngineError::State(format!("can't lay out text: {e}"))
|
||||
}
|
||||
@@ -346,7 +378,7 @@ pub(crate) fn lay_out_block(d: &TextBlock) -> Result<(TextBlock, Option<String>,
|
||||
d.box_height = set.height;
|
||||
d.on_path = Some(TextPath { path: set.path, offset, flip: on.flip });
|
||||
let shift = set.shift;
|
||||
let (b, n) = finish(d, set.pieces, &l.families, &paints);
|
||||
let (b, n) = finish(d, set.pieces, Used { families: &l.families, fallbacks: &l.fallbacks, missing: l.missing }, &paints);
|
||||
Ok((b, n, shift))
|
||||
}
|
||||
(Some(f), None) => {
|
||||
@@ -355,14 +387,16 @@ pub(crate) fn lay_out_block(d: &TextBlock) -> Result<(TextBlock, Option<String>,
|
||||
let shown = f.shown(&d.text);
|
||||
let l = field_lay(fonts, &anicraft_text::RichText { text: &shown, runs: &runs, paragraphs: ¶s, width: f.wrap_width(d.box_width) }, d.align, &f, d.box_width).map_err(layout_err)?;
|
||||
d.width = f.wrap_width(d.box_width);
|
||||
let (b, n) = finish(d, l.pieces, &l.families, &paints);
|
||||
let used = Used { families: &l.families, fallbacks: &l.fallbacks, missing: l.missing };
|
||||
let (b, n) = finish(d, l.pieces, used, &paints);
|
||||
Ok((b, n, Vec2::ZERO))
|
||||
}
|
||||
(None, None) => {
|
||||
let l = fonts.layout_rich(&anicraft_text::RichText { text: &d.text, runs: &runs, paragraphs: ¶s, width: d.width }, false).map_err(layout_err)?;
|
||||
d.box_width = l.width;
|
||||
d.box_height = l.height;
|
||||
let (b, n) = finish(d, l.pieces, &l.families, &paints);
|
||||
let used = Used { families: &l.families, fallbacks: &l.fallbacks, missing: l.missing };
|
||||
let (b, n) = finish(d, l.pieces, used, &paints);
|
||||
Ok((b, n, Vec2::ZERO))
|
||||
}
|
||||
}
|
||||
@@ -389,6 +423,10 @@ fn field_lay(fonts: &Fonts, rich: &anicraft_text::RichText, align: TextAlign, fi
|
||||
for s in &mut line.stops {
|
||||
s.1 += shift;
|
||||
}
|
||||
for b in &mut line.boxes {
|
||||
b.x0 += shift;
|
||||
b.x1 += shift;
|
||||
}
|
||||
}
|
||||
l.width += shift;
|
||||
}
|
||||
|
||||
@@ -67,8 +67,7 @@ pub(crate) fn aids_json(s: &Session) -> Value {
|
||||
}
|
||||
|
||||
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) }
|
||||
c.to_hex_alpha()
|
||||
}
|
||||
|
||||
fn guides_json(s: &Session) -> Value {
|
||||
|
||||
@@ -45,6 +45,11 @@ fn picking_a_solid_fill_sets_the_fill_colour_and_records_no_step() {
|
||||
let r = run(&mut s, "paint.pick", json!({"x": 150, "y": 150, "other": true}));
|
||||
assert_eq!(r["into"], "stroke");
|
||||
assert_eq!((s.style.stroke, s.style.fill), (Rgba::hex(0xff0000), Rgba::hex(0x00ff00)));
|
||||
// The report names the colour that was picked, its opacity included.
|
||||
rect(&mut s, 300.0, "#0000ff80");
|
||||
let r = run(&mut s, "paint.pick", json!({"x": 350, "y": 150}));
|
||||
assert_eq!(Rgba::parse_hex(r["color"].as_str().unwrap()), Some(s.style.fill));
|
||||
assert!(s.style.fill.a < 0.6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Saying when artwork was left out of a frame (ADR 0128).
|
||||
//!
|
||||
//! A frame's evaluation has an allowance of work (`anicraft_doc::MAX_EVAL_ELEMENTS`), so that no
|
||||
//! document, however its symbols nest, hangs AniCraft or runs it out of memory. A frame cut
|
||||
//! short draws in part. A command that writes such a frame still writes it, and says so in its
|
||||
//! result, so a partial picture is never passed off as the whole one.
|
||||
|
||||
use anicraft_doc::{DisplayList, Document};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
/// What a result says when artwork was left out.
|
||||
pub const WARNING: &str = "the document holds more artwork than AniCraft draws in one frame, so some of it was left out (symbols nested many times over?)";
|
||||
|
||||
/// Whether any frame one command evaluated was cut short. Shared by the threads that render a
|
||||
/// sequence's frames.
|
||||
#[derive(Default)]
|
||||
pub struct LeftOut(AtomicBool);
|
||||
|
||||
impl LeftOut {
|
||||
/// Movie frame `frame`, as `anicraft_doc::evaluate` gives it, noted when it was cut short.
|
||||
pub fn evaluate(&self, doc: &Document, frame: u32) -> DisplayList {
|
||||
let dl = anicraft_doc::evaluate(doc, frame);
|
||||
self.note(&dl);
|
||||
dl
|
||||
}
|
||||
|
||||
/// Notes `dl` when it was cut short.
|
||||
pub fn note(&self, dl: &DisplayList) {
|
||||
if dl.left_out {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn any(&self) -> bool {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// `result` as it is when every frame was whole; with `left_out: true` and a `warning`
|
||||
/// when one was not.
|
||||
pub fn noted(&self, mut result: Value) -> Value {
|
||||
if self.any()
|
||||
&& let Some(o) = result.as_object_mut()
|
||||
{
|
||||
o.insert("left_out".into(), json!(true));
|
||||
o.insert("warning".into(), json!(WARNING));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
pub mod access;
|
||||
mod anim;
|
||||
pub mod left_out;
|
||||
mod cmds_actions;
|
||||
mod cmds_bone;
|
||||
mod cmds_warp;
|
||||
@@ -465,6 +466,9 @@ pub struct Session {
|
||||
/// An import the editor prepared on another thread (ADR 0116): `file.import_video` asked
|
||||
/// for the same thing takes it instead of decoding again. Never in the document.
|
||||
pub staged_video: Option<video::Prepared>,
|
||||
/// A Brush stroke's outline the editor traced on another thread (ADR 0129): `draw.brush`
|
||||
/// asked for the same stroke takes it instead of tracing again. Never in the document.
|
||||
pub staged_stroke: Option<cmds_brush::PreparedStroke>,
|
||||
/// Files this session's publishes wrote: publishing again replaces them without asking.
|
||||
pub published: std::collections::BTreeSet<PathBuf>,
|
||||
/// The files opened and saved last, and pinned favourites (ADR 0059). They belong to the
|
||||
@@ -604,6 +608,7 @@ impl Session {
|
||||
picture_cache: RefCell::new(None),
|
||||
job: None,
|
||||
staged_video: None,
|
||||
staged_stroke: None,
|
||||
published: std::collections::BTreeSet::new(),
|
||||
recent: cmds_recent::RecentFiles::default(),
|
||||
brushes: brush_library::BrushLibrary::default(),
|
||||
@@ -1321,8 +1326,11 @@ impl Session {
|
||||
})
|
||||
.collect();
|
||||
let symbols: Vec<Value> = self.doc.library.iter().map(|s| json!({"id": s.id.0, "name": s.name, "kind": format!("{:?}", s.kind), "frames": s.timeline.frame_count()})).collect();
|
||||
// The frame shown, when its artwork is not all there (ADR 0128).
|
||||
let cut = left_out::LeftOut::default();
|
||||
cut.note(&self.display_list());
|
||||
let sounds: Vec<Value> = self.doc.sounds.iter().map(|x| json!({"id": x.id.0, "name": x.name, "format": x.format.label(), "rate": x.rate, "channels": x.channels, "seconds": x.seconds()})).collect();
|
||||
json!({
|
||||
cut.noted(json!({
|
||||
"stage": {"width": self.doc.stage.width, "height": self.doc.stage.height, "fps": self.doc.stage.fps, "background": self.doc.stage.background.to_hex()},
|
||||
"frames": self.frame_count(),
|
||||
"frame": self.frame,
|
||||
@@ -1343,7 +1351,7 @@ impl Session {
|
||||
"dirty": self.is_dirty(),
|
||||
"history": {"undo": self.history.undo_len(), "redo": self.history.redo_len(), "bytes": self.history.bytes(), "evicted": self.history.evicted},
|
||||
"state": self.state,
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -217,6 +217,35 @@ fn a_stroke_on_one_keyframe_only_shrinks_away_or_grows_in() {
|
||||
assert!(n5 > 0 && (w5 - w10 * 0.5).abs() < w10 * 0.1, "halfway: {w5} of {w10}");
|
||||
}
|
||||
|
||||
/// A filled, stroked raw shape tween that follows a curved motion guide: the joined stroke
|
||||
/// travels the guide with its fill, oriented to the path or not (#119).
|
||||
#[test]
|
||||
fn a_guided_shape_tween_carries_the_stroke_along_the_guide_with_the_fill() {
|
||||
let mut s = polygon_tween((3, json!("#ff0000"), json!("#000000")), (5, json!("#ff0000"), json!("#000000")));
|
||||
let art = s.layer;
|
||||
run(&mut s, "timeline.goto", json!({"frame": 10}));
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "element.translate", json!({"dx": 200, "dy": 0}));
|
||||
run(&mut s, "layer.add_motion_guide", json!({"layer": art.0}));
|
||||
run(&mut s, "draw.path", json!({"d": "M0 0 C0 -300 200 -300 200 0"}));
|
||||
let bounds = |items: &[&anicraft_doc::DisplayItem]| items.iter().fold(anicraft_geom::Rect::EMPTY, |r, i| r.union(&i.path.transformed(&i.transform).bounds()));
|
||||
for (frame, orient) in [3u32, 5, 7].into_iter().flat_map(|f| [(f, false), (f, true)]) {
|
||||
run(&mut s, "layer.select", json!({"layer": art.0}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 0}));
|
||||
assert_eq!(run(&mut s, "timeline.set_orient", json!({"orient": orient}))["orient"], orient);
|
||||
let list = anicraft_doc::evaluate(&s.doc, frame);
|
||||
let on = |want_fill: bool| -> Vec<&anicraft_doc::DisplayItem> {
|
||||
list.items.iter().filter(|i| i.layer == art && if want_fill { i.fill.is_some() } else { i.stroke.is_some() }).collect()
|
||||
};
|
||||
let (fill, stroke) = (bounds(&on(true)), bounds(&on(false)));
|
||||
assert!(!fill.is_empty() && !stroke.is_empty(), "frame {frame}");
|
||||
assert!(fill.center().y < -60.0, "frame {frame}: the fill rides up the arch: {fill:?}");
|
||||
for (a, b) in [(fill.min, stroke.min), (fill.max, stroke.max)] {
|
||||
assert!(a.distance(b) < 1.0, "frame {frame} (orient {orient}): the stroke left its fill: {fill:?} vs {stroke:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape hint placed on a raw outline's stroke steers the stroke's morph when the keyframes'
|
||||
/// outlines have different numbers of runs (#119).
|
||||
#[test]
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
use anicraft_doc::actions::as3::Problem;
|
||||
use anicraft_doc::actions::{Action, CompileResult, FrameScript, MAX_ACTIONS, PluginScript, check_actions};
|
||||
use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step, TimelineRef};
|
||||
use anicraft_doc::field::{CaretLine, FieldLook};
|
||||
use anicraft_doc::field::{CaretBox, CaretLine, FieldLook};
|
||||
use anicraft_doc::{Document, LayerKind, SymbolKind, TextBlock, Timeline, player};
|
||||
use anicraft_geom::Vec2;
|
||||
use anicraft_plugins::{Host, Kind, Limits, Registry};
|
||||
@@ -110,9 +110,10 @@ pub fn field_look(block: &TextBlock, shown: &str, rich: Option<&anicraft_doc::ht
|
||||
None => (crate::cmds_text::field_layout(fonts, &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?, Vec::new()),
|
||||
};
|
||||
let pieces: Vec<(anicraft_doc::Rgba, std::sync::Arc<anicraft_geom::Path>)> = if colors.len() > 1 || colors.first().is_some_and(|c| *c != block.color) { l.pieces.iter().filter_map(|(k, p)| Some((*colors.get(*k as usize)?, std::sync::Arc::new(p.clone())))).collect() } else { Vec::new() };
|
||||
let mut lines: Vec<CaretLine> = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, stops: c.stops }).collect();
|
||||
let boxes = |c: &anicraft_text::CaretLine| c.boxes.iter().map(|b| CaretBox { start: b.start, end: b.end, x0: b.x0, x1: b.x1, rtl: b.rtl }).collect();
|
||||
let mut lines: Vec<CaretLine> = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, rtl: c.rtl, boxes: boxes(&c), stops: c.stops }).collect();
|
||||
if lines.is_empty() {
|
||||
lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] });
|
||||
lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)], ..CaretLine::default() });
|
||||
}
|
||||
Some(FieldLook { outline: std::sync::Arc::new(l.outline), pieces: pieces.into(), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height })
|
||||
}
|
||||
|
||||
@@ -227,3 +227,104 @@ fn every_export_draws_each_colour_and_svg_keeps_the_link() {
|
||||
let html = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap().html;
|
||||
assert!(html.contains("\"pp\":"), "field pieces");
|
||||
}
|
||||
|
||||
/// ADR 0130: text that mixes directions through the commands, as static text, as a field and
|
||||
/// on a path, with this computer's fonts. The command says so when letters were borrowed from
|
||||
/// another font or show as boxes, and in a field the arrow keys walk the caret the way they
|
||||
/// point.
|
||||
#[test]
|
||||
fn mixed_directions_and_borrowed_letters_through_the_commands() {
|
||||
use crate::cmds_text::borrowed_note;
|
||||
assert_eq!(borrowed_note(&[], 0), None, "nothing to say about a font that has every letter");
|
||||
let both = borrowed_note(&["One".to_string(), "Two".to_string()], 3).unwrap();
|
||||
assert!(both.contains("One") && both.contains("Two") && both.contains('3'), "{both}");
|
||||
if !fonts() {
|
||||
return;
|
||||
}
|
||||
let fonts = anicraft_text::Fonts::get();
|
||||
// a b _ alef bet gimel _ 1 2 _ and a private-use character few fonts have.
|
||||
let text = "ab \u{05D0}\u{05D1}\u{05D2} 12 \u{10FFFD}";
|
||||
let mut s = Session::default();
|
||||
let out = run(&mut s, "text.create", json!({"text": text, "x": 20, "y": 20, "size": 40, "color": "#000000"}));
|
||||
let id = ElementId(out["element"].as_u64().unwrap());
|
||||
let block = text_of(&s, id);
|
||||
let style = anicraft_text::Style { family: block.font.clone(), size: 40.0, ..anicraft_text::Style::default() };
|
||||
let probe = fonts.layout_glyphs(text, &style).unwrap();
|
||||
assert_eq!(out["note"].is_string(), probe.missing > 0 || !probe.fallbacks.is_empty(), "{out}");
|
||||
assert_eq!(block.text, text, "the text is kept as it was typed");
|
||||
assert_eq!(block.outline.cmds, probe.outline.cmds, "the block's outline is the layout's");
|
||||
// A field of it: the player's caret places come with the layout's boxes.
|
||||
run(&mut s, "text.field", json!({"type": "input", "width": 600, "height": 80}));
|
||||
let field = text_of(&s, id);
|
||||
let look = crate::player::field_look(&field, &field.text, None).unwrap();
|
||||
let hebrew = fonts.layout("\u{05D0}\u{05D1}\u{05D2}", &style).unwrap().missing == 0;
|
||||
if hebrew {
|
||||
let line = &look.lines[0];
|
||||
assert!(line.mixed() && !line.rtl, "a Hebrew word in a paragraph that starts with Latin letters");
|
||||
// Right, pressed from the line's left end, visits every caret place once, each
|
||||
// further right than the last.
|
||||
let mut at = line.stops.iter().min_by(|a, b| a.1.total_cmp(&b.1)).unwrap().0;
|
||||
let mut xs = vec![look.caret_at(at).x];
|
||||
for _ in 0..line.stops.len() {
|
||||
let next = look.step(at, true).unwrap();
|
||||
if next == at {
|
||||
break;
|
||||
}
|
||||
at = next;
|
||||
xs.push(look.caret_at(at).x);
|
||||
}
|
||||
assert_eq!(xs.len(), line.stops.len(), "{xs:?}");
|
||||
assert!(xs.windows(2).all(|w| w[0] <= w[1]), "{xs:?}");
|
||||
// The Hebrew word's first letter is right of its last.
|
||||
assert!(line.x_at(3) > line.x_at(5), "{:?}", line.stops);
|
||||
}
|
||||
// On a path it lays out too, and undo brings the lines back.
|
||||
run(&mut s, "text.field", json!({"type": "static"}));
|
||||
run(&mut s, "text.edit", json!({"text": "\u{05D0}\u{05D1} ab\n12 \u{05D2}", "width": 30}));
|
||||
let wrapped = text_of(&s, id);
|
||||
assert!(wrapped.box_height > block.box_height * 1.5 && wrapped.outline.cmds.iter().all(|c| !matches!(c, anicraft_geom::PathCmd::MoveTo(p) if !p.is_finite())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_links_are_sanitized_and_round_trip_without_changing_the_drawing() {
|
||||
// Exercise the export boundary without installed fonts or text shaping.
|
||||
let mut doc = anicraft_doc::Document::default();
|
||||
doc.stage.width = 32;
|
||||
doc.stage.height = 24;
|
||||
let mut s = Session::new(doc);
|
||||
run(&mut s, "draw.rect", json!({"x": 4, "y": 4, "w": 12, "h": 8, "fill": "#336699", "stroke": null}));
|
||||
let expected = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().to_rgba8();
|
||||
assert!(expected.as_chunks::<4>().0.iter().any(|p| p == &[0x33, 0x66, 0x99, 0xff]), "the fixture draws a coloured rectangle");
|
||||
let mut dl = anicraft_doc::evaluate(&s.doc, 0);
|
||||
assert_eq!(dl.items.len(), 1);
|
||||
for (index, (url, href)) in [
|
||||
(" \thttps://example.org/?a=1&b=\"<>'\r\n\u{7f}ok ", Some("https://example.org/?a=1&b=\"<>'ok")),
|
||||
("java\tscript:alert(1)", None),
|
||||
("vb\rscript:msgbox(1)", None),
|
||||
("da\nta:text/plain,hello", None),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
dl.links = vec![(0, url.into())];
|
||||
let svg = anicraft_render::svg::to_svg(&dl, &s.doc.stage);
|
||||
let root = anicraft_xml::parse(svg.as_bytes()).unwrap();
|
||||
let anchors: Vec<_> = root.children.iter().filter(|el| el.name == "a").collect();
|
||||
assert_eq!(anchors.len(), usize::from(href.is_some()), "{url:?}: {svg}");
|
||||
assert_eq!(anchors.first().and_then(|el| el.attr("href")), href, "decoded href for {url:?}");
|
||||
if let Some(anchor) = anchors.first() {
|
||||
assert!(anchor.child("path").is_some(), "the anchor wraps the artwork");
|
||||
}
|
||||
|
||||
// Use the real file-import command rather than duplicating its document mapping.
|
||||
let path = std::env::temp_dir().join(format!("anicraft-svg-link-roundtrip-{}-{index}.svg", std::process::id()));
|
||||
std::fs::write(&path, svg.as_bytes()).unwrap();
|
||||
let back = anicraft_doc::Document { stage: s.doc.stage, ..Default::default() };
|
||||
let mut imported = Session::new(back);
|
||||
let result = imported.execute("file.import", &json!({"path": path.display().to_string(), "x": 0, "y": 0}));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
result.unwrap_or_else(|e| panic!("file.import for {url:?}: {e}"));
|
||||
let actual = anicraft_render::render_frame(&imported.doc, 0, 1.0).unwrap().to_rgba8();
|
||||
assert_eq!(actual, expected, "link handling must preserve rendered geometry for {url:?}");
|
||||
}
|
||||
}
|
||||
@@ -1941,6 +1941,68 @@ fn create_shape_tween_morphs_and_keeps_the_easing() {
|
||||
assert_eq!(s.active_layer().unwrap().keyframes[0].tween.clone().unwrap().kind, anicraft_doc::TweenKind::Classic);
|
||||
}
|
||||
|
||||
/// The flattened outlines of `items` (stage space), as line segments.
|
||||
fn outline_segments<'a>(items: impl Iterator<Item = &'a anicraft_doc::DisplayItem>) -> Vec<(Vec2, Vec2)> {
|
||||
let mut segs = Vec::new();
|
||||
for it in items {
|
||||
for pl in it.path.flatten(&it.transform, 0.05) {
|
||||
segs.extend(pl.points.windows(2).map(|w| (w[0], w[1])));
|
||||
if let (true, Some(&a), Some(&b)) = (pl.closed, pl.points.last(), pl.points.first()) {
|
||||
segs.push((a, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
/// How far `p` is from the nearest of `segs`.
|
||||
fn distance_to(segs: &[(Vec2, Vec2)], p: Vec2) -> f32 {
|
||||
segs.iter()
|
||||
.map(|&(a, b)| {
|
||||
let ab = b - a;
|
||||
let t = if ab.dot(ab) > 0.0 { ((p - a).dot(ab) / ab.dot(ab)).clamp(0.0, 1.0) } else { 0.0 };
|
||||
p.distance(a + ab * t)
|
||||
})
|
||||
.fold(f32::INFINITY, f32::min)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_tweens_carry_the_stroke_round_shapes_with_more_or_fewer_sides() {
|
||||
// Issue #119. A stroked triangle into a stroked hexagon and back (raw shapes: Merge Drawing
|
||||
// makes one stroke piece per side, 3 and 6 of them). In between, the stroke must follow the
|
||||
// whole morphing fill outline: no side left bare, no line left standing off it.
|
||||
let mut s = Session::default();
|
||||
let polygon = |s: &mut Session, sides: u32| {
|
||||
let inner = 60.0 * (std::f32::consts::PI / sides as f32).cos(); // on the edges: a polygon
|
||||
run(s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 60, "inner": inner, "points": sides, "fill": "#ff0000", "stroke": "#000000", "stroke_width": 2, "object": false}));
|
||||
};
|
||||
polygon(&mut s, 3);
|
||||
let strokes = |s: &Session| s.active_layer().unwrap().keyframes.last().unwrap().elements.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_none())).count();
|
||||
assert_eq!(strokes(&s), 3, "one stroke piece per side");
|
||||
run(&mut s, "timeline.goto", json!({"frame": 10}));
|
||||
run(&mut s, "timeline.insert_blank_keyframe", json!({}));
|
||||
polygon(&mut s, 6);
|
||||
assert_eq!(strokes(&s), 6);
|
||||
run(&mut s, "timeline.goto", json!({"frame": 20}));
|
||||
run(&mut s, "timeline.insert_blank_keyframe", json!({}));
|
||||
polygon(&mut s, 3);
|
||||
for frame in [0, 10] {
|
||||
run(&mut s, "timeline.create_shape_tween", json!({"frame": frame}));
|
||||
}
|
||||
for frame in [3, 5, 8, 13, 15, 18] {
|
||||
let list = anicraft_doc::evaluate(&s.doc, frame);
|
||||
let fill = outline_segments(list.items.iter().filter(|i| i.fill.is_some()));
|
||||
let stroke = outline_segments(list.items.iter().filter(|i| i.stroke.is_some()));
|
||||
assert!(!fill.is_empty() && !stroke.is_empty(), "frame {frame}");
|
||||
// Every point of the fill's outline has the stroke on it, and every point of the stroke
|
||||
// lies on the outline.
|
||||
let bare = fill.iter().flat_map(|&(a, b)| (0..=8).map(move |k| a.lerp(b, k as f32 / 8.0))).map(|p| distance_to(&stroke, p)).fold(0.0, f32::max);
|
||||
let stray = stroke.iter().flat_map(|&(a, b)| (0..=8).map(move |k| a.lerp(b, k as f32 / 8.0))).map(|p| distance_to(&fill, p)).fold(0.0, f32::max);
|
||||
assert!(bare < 0.5, "frame {frame}: part of the outline is {bare} from the stroke");
|
||||
assert!(stray < 0.5, "frame {frame}: a stroke is {stray} off the outline");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scenes_play_in_order_edit_separately_and_survive_save_and_undo() {
|
||||
let mut s = Session::default();
|
||||
@@ -2768,3 +2830,71 @@ fn a_motion_guide_with_sharp_corners_is_followed_to_its_end() {
|
||||
prev = p;
|
||||
}
|
||||
}
|
||||
|
||||
/// ADR 0128: a frame cut short by its allowance of work is still written, and every command
|
||||
/// that writes it says so; a whole frame's results are as they always were. (The symbols hold
|
||||
/// thousands of empty layers, so the allowance goes on looking at them and little is drawn.)
|
||||
#[test]
|
||||
fn exports_of_a_frame_too_large_to_draw_say_artwork_was_left_out() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-left-out-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut large = anicraft_doc::sample::doubling(31);
|
||||
for sym in &mut large.library {
|
||||
let tl = &mut std::sync::Arc::make_mut(sym).timeline;
|
||||
for i in 0..5_000 {
|
||||
tl.layers.push(std::sync::Arc::new(anicraft_doc::Layer::new(anicraft_doc::LayerId(9_000 + i), "empty")));
|
||||
}
|
||||
}
|
||||
for (doc, cut) in [(large, true), (anicraft_doc::sample::doubling(6), false)] {
|
||||
let mut s = Session::new(doc);
|
||||
let at = |name: &str| dir.join(format!("{cut}-{name}")).display().to_string();
|
||||
let results = [
|
||||
s.info(),
|
||||
run(&mut s, "file.export_png", json!({"path": at("f.png"), "scale": 0.1})),
|
||||
run(&mut s, "file.export_svg", json!({"path": at("f.svg")})),
|
||||
run(&mut s, "file.export_png_sequence", json!({"dir": at("png"), "scale": 0.1})),
|
||||
run(&mut s, "file.export_svg_sequence", json!({"dir": at("svg")})),
|
||||
run(&mut s, "file.export_sprite_sheet", json!({"path": at("sheet.png"), "scale": 0.1})),
|
||||
run(&mut s, "file.export_gif", json!({"path": at("f.gif"), "scale": 0.1})),
|
||||
run(&mut s, "file.export_apng", json!({"path": at("a.png"), "scale": 0.1})),
|
||||
];
|
||||
for v in &results {
|
||||
assert_eq!(v.get("left_out").and_then(Value::as_bool).unwrap_or(false), cut, "{v}");
|
||||
assert_eq!(v.get("warning").is_some(), cut, "{v}");
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// P-011: two raw fills side by side, their outlines joined along the edge they share, on a
|
||||
/// shape tween that follows a motion guide. A guide places every element by its own origin, so
|
||||
/// the stroke runs used to leave the fills and cross them. Each run rides with the fill it
|
||||
/// edges, the same number of runs on both keys or not; the shared edge goes with the lower fill.
|
||||
#[test]
|
||||
fn guided_shape_tweens_keep_each_raw_outline_on_its_fill() {
|
||||
let mut s = Session::default();
|
||||
for (x, fill) in [(100, "#e63946"), (180, "#457b9d")] {
|
||||
run(&mut s, "draw.rect", json!({"x": x, "y": 240, "w": 80, "h": 80, "fill": fill, "stroke": "#000000", "stroke_width": 4, "object": false}));
|
||||
}
|
||||
let art = s.active_layer().unwrap().id;
|
||||
run(&mut s, "timeline.goto", json!({"frame": 20}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "element.translate", json!({"dx": 440, "dy": 0}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 0}));
|
||||
run(&mut s, "timeline.create_shape_tween", json!({}));
|
||||
run(&mut s, "layer.add_motion_guide", json!({"layer": art.0}));
|
||||
for (a, b) in [((140, 280), (400, 80)), ((400, 80), (660, 280))] {
|
||||
run(&mut s, "draw.line", json!({"x0": a.0, "y0": a.1, "x1": b.0, "y1": b.1, "object": false}));
|
||||
}
|
||||
let length = |segs: &[(Vec2, Vec2)]| segs.iter().map(|(a, b)| a.distance(*b)).sum::<f32>();
|
||||
let on_art = |list: &anicraft_doc::DisplayList| (outline_segments(list.items.iter().filter(|i| i.layer == art && i.fill.is_some())), outline_segments(list.items.iter().filter(|i| i.layer == art && i.stroke.is_some())));
|
||||
let drawn = length(&on_art(&anicraft_doc::evaluate_scene(&s.doc, s.scene, 0)).1);
|
||||
assert!(drawn > 500.0, "seven sides of 80: {drawn}");
|
||||
for frame in [3, 5, 10, 15, 18] {
|
||||
let (fill, stroke) = on_art(&anicraft_doc::evaluate_scene(&s.doc, s.scene, frame));
|
||||
let stray = stroke.iter().flat_map(|&(a, b)| (0..=8).map(move |k| a.lerp(b, k as f32 / 8.0))).map(|p| distance_to(&fill, p)).fold(0.0, f32::max);
|
||||
assert!(stray < 0.5, "frame {frame}: a stroke is {stray} off the fills' outlines");
|
||||
assert!((length(&stroke) - drawn).abs() < 1.0, "frame {frame}: every run is still drawn: {} of {drawn}", length(&stroke));
|
||||
}
|
||||
}
|
||||
+106
-14
@@ -35,6 +35,11 @@ use crate::{Affine, Path, PathCmd, Vec2, fit_curve, trace};
|
||||
pub const MAX_CELLS: usize = 4_000_000;
|
||||
/// Most samples one stroke may have.
|
||||
pub const MAX_SAMPLES: usize = 100_000;
|
||||
/// Most cells the stroke's pieces may visit between them while the distance field is sampled
|
||||
/// (each piece visits the cells of its own bounds). A stroke that would visit more is sampled on
|
||||
/// a coarser grid, so the time one stroke takes is bounded however long it is and however often
|
||||
/// it crosses itself (#519): a fast scribble of 60 000 samples visited 190 million cells.
|
||||
pub const MAX_STAMP_WORK: usize = 1 << 24;
|
||||
/// The tip's size at zero pressure, as a fraction of its full size.
|
||||
pub const MIN_PRESSURE_SIZE: f32 = 0.1;
|
||||
|
||||
@@ -442,14 +447,7 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
let fine: f64 = if shaping.texture > 0.0 { f64::min(fine, 1.0 / 18.0) } else { fine };
|
||||
// In stage space the tip's narrow side is `round` radii across.
|
||||
let narrow = if turns { round } else { 1.0 };
|
||||
let mut c: f64 = (fmin / 2.5).min(fine) * narrow;
|
||||
for _ in 0..4 {
|
||||
let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0);
|
||||
if cells <= MAX_CELLS as f64 {
|
||||
break;
|
||||
}
|
||||
c *= (cells / MAX_CELLS as f64).sqrt() * 1.01;
|
||||
}
|
||||
let c = cell_size(&q, (lo, hi), (fmin / 2.5).min(fine) * narrow, narrow, dabbed);
|
||||
let origin = (lo.0 - MARGIN * c, lo.1 - MARGIN * c);
|
||||
let w = ((hi.0 - lo.0) / c + 2.0 * MARGIN).ceil() + 1.0;
|
||||
let h = ((hi.1 - lo.1) / c + 2.0 * MARGIN).ceil() + 1.0;
|
||||
@@ -481,9 +479,16 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
};
|
||||
let scale = if turn.is_some() { round } else { 1.0 };
|
||||
let (ta, tb) = (to_tip(a), to_tip(b));
|
||||
let full = top as f32;
|
||||
for y in y0 as usize..=y1 as usize {
|
||||
let py = origin.1 + (y as f64 + 0.5) * c;
|
||||
for x in x0 as usize..=x1 as usize {
|
||||
let Some(row) = field.get_mut(y * w + x0 as usize..=y * w + x1 as usize) else { continue };
|
||||
for (x, cell) in (x0 as usize..).zip(row) {
|
||||
// Deep inside paint already: nothing can raise it (a stroke that goes over
|
||||
// itself again and again costs a comparison here, not a distance).
|
||||
if *cell >= full {
|
||||
continue;
|
||||
}
|
||||
let px = origin.0 + (x as f64 + 0.5) * c;
|
||||
let tx = to_tip((px, py));
|
||||
let d = match tip.shape {
|
||||
@@ -491,9 +496,7 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
TipShape::Square => square_dist(tx, ta, ra, tb, rb),
|
||||
} * scale;
|
||||
let v = (0.5 - d / c).clamp(OUTSIDE, top) as f32;
|
||||
if let Some(cell) = field.get_mut(y * w + x)
|
||||
&& v > *cell
|
||||
{
|
||||
if v > *cell {
|
||||
*cell = v;
|
||||
}
|
||||
}
|
||||
@@ -573,6 +576,46 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
out
|
||||
}
|
||||
|
||||
/// The grid's cell size for the stroke through `q` (bounds `lo..hi`): `wanted`, or as much
|
||||
/// larger as keeps the grid within [`MAX_CELLS`] and the sampling within [`MAX_STAMP_WORK`].
|
||||
fn cell_size(q: &[(P, f64, f64)], (lo, hi): (P, P), wanted: f64, narrow: f64, dabbed: bool) -> f64 {
|
||||
let mut c = wanted;
|
||||
for _ in 0..4 {
|
||||
let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0);
|
||||
if cells <= MAX_CELLS as f64 {
|
||||
break;
|
||||
}
|
||||
c *= (cells / MAX_CELLS as f64).sqrt() * 1.01;
|
||||
}
|
||||
for _ in 0..6 {
|
||||
let work = stamp_work(&thin(q, c * 0.5), c, narrow, dabbed);
|
||||
if work <= MAX_STAMP_WORK as f64 {
|
||||
break;
|
||||
}
|
||||
c *= (work / MAX_STAMP_WORK as f64).sqrt().max(1.05);
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// About how many cells of size `c` the pieces of the stroke through `q` visit between them:
|
||||
/// each piece's own bounds, as the field is sampled (a long segment in pieces of [`PIECE`]).
|
||||
fn stamp_work(q: &[(P, f64, f64)], c: f64, narrow: f64, dabbed: bool) -> f64 {
|
||||
let cells = |len: (f64, f64), r: f64| {
|
||||
let reach = 2.0 * (r.max(c / narrow) + (MARGIN - 1.0) * c);
|
||||
((len.0 + reach) / c + 1.0) * ((len.1 + reach) / c + 1.0)
|
||||
};
|
||||
if dabbed || q.len() < 2 {
|
||||
return q.iter().map(|(_, f, _)| cells((0.0, 0.0), *f)).sum();
|
||||
}
|
||||
q.windows(2)
|
||||
.map(|pair| {
|
||||
let &[(a, ra, _), (b, rb, _)] = pair else { return 0.0 };
|
||||
let n = (dist(a, b) / PIECE.max(16.0 * c)).ceil().clamp(1.0, 1e6);
|
||||
n * cells(((a.0 - b.0).abs() / n, (a.1 - b.1).abs() / n), ra.max(rb))
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Most loops one outline keeps (a fine paper grain on a long stroke opens many holes).
|
||||
pub const MAX_LOOPS: usize = 20_000;
|
||||
/// The paper grain's size, in tip radii.
|
||||
@@ -630,7 +673,9 @@ fn v64(p: Vec2) -> P {
|
||||
(f64::from(p.x), f64::from(p.y))
|
||||
}
|
||||
fn dist(a: P, b: P) -> f64 {
|
||||
(a.0 - b.0).hypot(a.1 - b.1)
|
||||
// Not `hypot`: nothing here is near overflow, and this runs for every cell a piece visits.
|
||||
let (x, y) = (a.0 - b.0, a.1 - b.1);
|
||||
(x * x + y * y).sqrt()
|
||||
}
|
||||
fn lerp(a: P, b: P, t: f64) -> P {
|
||||
(a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)
|
||||
@@ -689,7 +734,7 @@ fn thin(q: &[(P, f64, f64)], gap: f64) -> Vec<(P, f64, f64)> {
|
||||
/// to the segment) is the minimum.
|
||||
fn round_dist(x: P, a: P, ra: f64, b: P, rb: f64) -> f64 {
|
||||
let d = (b.0 - a.0, b.1 - a.1);
|
||||
let l = d.0.hypot(d.1);
|
||||
let l = (d.0 * d.0 + d.1 * d.1).sqrt();
|
||||
let dr = rb - ra;
|
||||
let ends = || (dist(x, a) - ra).min(dist(x, b) - rb);
|
||||
if l < 1e-12 || dr.abs() >= l {
|
||||
@@ -768,6 +813,53 @@ mod tests {
|
||||
assert!(p.anchors().len() <= 16, "{} anchors", p.anchors().len());
|
||||
}
|
||||
|
||||
/// A fast scribble over a 1280 × 720 stage that crosses itself again and again, with the
|
||||
/// pressure swelling and fading: `n` samples about 16 units apart.
|
||||
fn scribble(n: usize) -> Vec<Sample> {
|
||||
(0..n)
|
||||
.map(|i| i as f32 * 0.06)
|
||||
.map(|t| Sample::new(Vec2::new(640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos(), 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin()), 0.55 + 0.45 * (t * 0.37).sin()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// #519: the cells a stroke's pieces visit are bounded, however long the stroke is. A
|
||||
/// scribble of 60 000 samples would visit several times the budget on the grid its size
|
||||
/// asks for; the grid it gets keeps it inside, and the paint is still where the hand went.
|
||||
#[test]
|
||||
fn a_long_scribble_is_sampled_within_the_work_budget() {
|
||||
let s = scribble(60_000);
|
||||
let q: Vec<(P, f64, f64)> = centre_points(&s, 3.0, 0.08, &Shaping::default()).iter().map(|p| ((f64::from(p.at.x) / 5.0, f64::from(p.at.y) / 5.0), f64::from(p.f), 0.0)).collect();
|
||||
let (lo, hi) = q.iter().fold(((f64::MAX, f64::MAX), (f64::MIN, f64::MIN)), |(lo, hi), (p, _, _)| ((lo.0.min(p.0), lo.1.min(p.1)), (hi.0.max(p.0), hi.1.max(p.1))));
|
||||
let wanted = 0.04;
|
||||
let grid_only = {
|
||||
let cells = ((hi.0 - lo.0) / wanted + 8.0) * ((hi.1 - lo.1) / wanted + 8.0);
|
||||
wanted * (cells / MAX_CELLS as f64).sqrt().max(1.0)
|
||||
};
|
||||
let unbounded = stamp_work(&thin(&q, grid_only * 0.5), grid_only, 1.0, false);
|
||||
assert!(unbounded > 2.0 * MAX_STAMP_WORK as f64, "the scenario is past the budget without the bound: {unbounded}");
|
||||
let c = cell_size(&q, (lo, hi), wanted, 1.0, false);
|
||||
let work = stamp_work(&thin(&q, c * 0.5), c, 1.0, false);
|
||||
assert!(work <= MAX_STAMP_WORK as f64 * 1.05, "{work}");
|
||||
assert!(c > grid_only && c < 0.5, "coarser, but still well under the tip's radius: {c}");
|
||||
// The outline it gives: paint under the hand at every sample, none far from all of them.
|
||||
let p = outline(&s, &Tip::round(10.0), 3.0, 0.3);
|
||||
assert!(s.iter().step_by(997).all(|x| p.contains(x.at, &Affine::IDENTITY, FillRule::EvenOdd)), "paint under the hand");
|
||||
assert!(!p.contains(Vec2::new(20.0, 20.0), &Affine::IDENTITY, FillRule::EvenOdd), "and none in the corner it never reached");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "a measurement, not a check"]
|
||||
fn long_stroke_cost() {
|
||||
for n in [1500, 6000, 20_000, 60_000, 100_000] {
|
||||
for (name, size) in [("size 10", 10.0), ("size 3", 3.0), ("size 60", 60.0)] {
|
||||
let s = scribble(n);
|
||||
let t = std::time::Instant::now();
|
||||
let p = outline(&s, &Tip::round(size), 3.0, 0.3);
|
||||
println!("{n:6} samples, {name}: {:7.1} ms, {} segments", t.elapsed().as_secs_f64() * 1000.0, p.cmds.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dab_is_the_tip() {
|
||||
let p = outline(&[Sample::new(Vec2::new(10.0, 10.0), 1.0)], &Tip::round(8.0), 1.0, 0.05);
|
||||
|
||||
+19
-1
@@ -48,8 +48,13 @@ impl Vec2 {
|
||||
pub fn cross(self, o: Vec2) -> f32 {
|
||||
self.x * o.y - self.y * o.x
|
||||
}
|
||||
/// Exact wherever the true length is a finite `f32`. The squares leave `f32` for components
|
||||
/// past about 1.8e19 (or below 1e-19), so only then is the slower `hypot` taken: in range
|
||||
/// the result is the multiply's, bit for bit, at its cost (0.85 ns against 0.83 ns; `hypot`
|
||||
/// alone is 1.9 ns, and this is on the flattening and stroking paths).
|
||||
pub fn length(self) -> f32 {
|
||||
self.dot(self).sqrt()
|
||||
let sq = self.dot(self);
|
||||
if sq.is_normal() { sq.sqrt() } else { self.x.hypot(self.y) }
|
||||
}
|
||||
pub fn normalized(self) -> Vec2 {
|
||||
let l = self.length();
|
||||
@@ -244,4 +249,17 @@ mod tests {
|
||||
assert_eq!(v.perp().dot(v), 0.0);
|
||||
assert_eq!(Vec2::ZERO.normalized(), Vec2::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_and_normalized_survive_huge_components() {
|
||||
let v = Vec2::new(3e19, 4e19);
|
||||
assert!((v.length() / 5e19 - 1.0).abs() < 1e-5, "len {}", v.length());
|
||||
let n = v.normalized();
|
||||
assert!((n.x - 0.6).abs() < 1e-5 && (n.y - 0.8).abs() < 1e-5, "{n:?}");
|
||||
// Squares too small for `f32` no longer read as no length at all.
|
||||
let tiny = Vec2::new(3e-30, 4e-30).length();
|
||||
assert!((tiny / 5e-30 - 1.0).abs() < 1e-5, "len {tiny}");
|
||||
assert_eq!(Vec2::ZERO.length(), 0.0);
|
||||
assert!(Vec2::new(f32::NAN, 1.0).length().is_nan());
|
||||
}
|
||||
}
|
||||
@@ -695,6 +695,27 @@ fn chain_find(grid: &mut HashMap<(i64, i64), Vec<usize>>, slots: &[Option<Sub>],
|
||||
best
|
||||
}
|
||||
|
||||
/// Whether exactly two run ends of `ends` lie within `tol` of `at`: a plain corner, where the
|
||||
/// line can only go on one way. Where three or more meet (a crossing, a spur), which run
|
||||
/// continues the line is a guess, so [`chain`] joins nothing there. A cell crowded beyond
|
||||
/// [`CHAIN_SCAN`] ends counts as a junction.
|
||||
fn plain_corner(ends: &HashMap<(i64, i64), Vec<Vec2>>, at: Vec2, tol: f32, cell: f32, steps: &mut usize) -> bool {
|
||||
let key = |v: Vec2| ((v.x / cell).floor() as i64, (v.y / cell).floor() as i64);
|
||||
let (kx, ky) = key(at);
|
||||
let mut n = 0;
|
||||
for dx in -1..=1_i64 {
|
||||
for dy in -1..=1_i64 {
|
||||
let Some(list) = ends.get(&(kx.saturating_add(dx), ky.saturating_add(dy))) else { continue };
|
||||
if list.len() > CHAIN_SCAN {
|
||||
return false;
|
||||
}
|
||||
*steps += list.len();
|
||||
n += list.iter().filter(|e| e.distance(at) <= tol).count();
|
||||
}
|
||||
}
|
||||
n == 2
|
||||
}
|
||||
|
||||
/// [`chain`], and the work it took: endpoint lookup steps plus segments moved.
|
||||
pub fn chain_counted(p: &Path, tol: f32) -> (Path, usize) {
|
||||
let (mut out, mut open): (Vec<Sub>, Vec<Sub>) = subpaths(p).into_iter().partition(|s| s.closed);
|
||||
@@ -704,12 +725,15 @@ pub fn chain_counted(p: &Path, tol: f32) -> (Path, usize) {
|
||||
let cell = if tol.is_finite() && tol > 0.0 { tol } else { 1.0 };
|
||||
let key = |v: Vec2| ((v.x / cell).floor() as i64, (v.y / cell).floor() as i64);
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
|
||||
let mut ends: HashMap<(i64, i64), Vec<Vec2>> = HashMap::new();
|
||||
for (i, s) in open.iter().enumerate() {
|
||||
let (a, b) = (key(s.start), key(end(s)));
|
||||
grid.entry(a).or_default().push(i);
|
||||
if b != a {
|
||||
grid.entry(b).or_default().push(i);
|
||||
}
|
||||
ends.entry(a).or_default().push(s.start);
|
||||
ends.entry(b).or_default().push(end(s));
|
||||
}
|
||||
let mut slots: Vec<Option<Sub>> = open.into_iter().map(Some).collect();
|
||||
let mut steps = 0;
|
||||
@@ -724,13 +748,21 @@ pub fn chain_counted(p: &Path, tol: f32) -> (Path, usize) {
|
||||
steps += segs.len();
|
||||
loop {
|
||||
let tail = segs.back().map_or(cur.start, |g| g[2]);
|
||||
if let Some(next) = chain_find(&mut grid, &slots, tail, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take()) {
|
||||
// Back at its start: the outline is closed, whatever else touches it there.
|
||||
if segs.len() > 1 && tail.distance(cur.start) <= tol {
|
||||
break;
|
||||
}
|
||||
if plain_corner(&ends, tail, tol, cell, &mut steps)
|
||||
&& let Some(next) = chain_find(&mut grid, &slots, tail, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take())
|
||||
{
|
||||
let next = if next.start.distance(tail) <= tol { next } else { reverse(&next) };
|
||||
steps += next.segs.len();
|
||||
segs.extend(next.segs);
|
||||
continue;
|
||||
}
|
||||
if let Some(prev) = chain_find(&mut grid, &slots, cur.start, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take()) {
|
||||
if plain_corner(&ends, cur.start, tol, cell, &mut steps)
|
||||
&& let Some(prev) = chain_find(&mut grid, &slots, cur.start, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take())
|
||||
{
|
||||
let prev = if end(&prev).distance(cur.start) <= tol { prev } else { reverse(&prev) };
|
||||
steps += prev.segs.len();
|
||||
for g in prev.segs.into_iter().rev() {
|
||||
@@ -955,6 +987,68 @@ mod tests {
|
||||
assert!(close(anchors_of(&y)[k], Vec2::new(50.0, 80.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chain_joins_pieces_that_meet_into_outlines() {
|
||||
// A triangle's sides, out of order, one drawn backwards and one a hair off its corner,
|
||||
// plus a stray line and a closed square: the sides become one closed outline.
|
||||
let (p, q, r) = (Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(5.0, 8.0));
|
||||
let sides = [Path::line(q, r), Path::line(Vec2::new(0.05, 0.0), q), Path::line(p, r)];
|
||||
let stray = Path::line(Vec2::new(50.0, 50.0), Vec2::new(60.0, 50.0));
|
||||
let square = Path::rect(100.0, 0.0, 5.0, 5.0);
|
||||
let all = Path { cmds: sides.iter().chain([&stray, &square]).flat_map(|p| p.cmds.clone()).collect() };
|
||||
let joined = chain(&all, 0.2);
|
||||
let subs = subpaths(&joined);
|
||||
assert_eq!(subs.len(), 3, "{subs:?}");
|
||||
let tri = subs.iter().find(|s| s.segs.len() == 3).unwrap();
|
||||
assert!(tri.closed);
|
||||
let corners: Vec<Vec2> = anchors(tri).collect();
|
||||
for c in [q, r] {
|
||||
assert!(corners.iter().any(|a| close(*a, c)), "{c:?} in {corners:?}");
|
||||
}
|
||||
assert!(corners.iter().any(|a| a.distance(p) < 0.1));
|
||||
assert!(subs.iter().any(|s| !s.closed && s.segs.len() == 1), "the stray line stays open");
|
||||
assert!(subs.iter().any(|s| s.closed && s.segs.len() == 4), "the square passes through");
|
||||
// The joined triangle morphs like the filled one.
|
||||
assert!(morph(&joined, &Path::ellipse(0.0, 0.0, 5.0, 5.0), 0.5).is_some());
|
||||
assert!(chain(&Path::default(), 0.2).cmds.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chain_leaves_a_junction_of_three_or_more_runs_unjoined() {
|
||||
// A square ABCD with a diagonal BD of the same style, in the order AB, BD, BC, CD, DA.
|
||||
// Three runs meet at B and at D: which one continues the line there is a guess, and a
|
||||
// wrong guess (AB → BD) folds the square's sides into an open zigzag. Nothing is joined
|
||||
// through B or D; the corners where just two runs meet (A, C) still join.
|
||||
let (a, b, c, d) = (Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0));
|
||||
let runs = [(a, b), (b, d), (b, c), (c, d), (d, a)];
|
||||
let mut p = Path::default();
|
||||
for (s, e) in runs {
|
||||
p.move_to(s).line_to(e);
|
||||
}
|
||||
let subs = subpaths(&chain(&p, 0.01));
|
||||
assert_eq!(subs.iter().map(|s| s.segs.len()).sum::<usize>(), 5, "no segment is lost");
|
||||
// DA + AB, BC + CD, and the diagonal alone.
|
||||
let mut lens: Vec<usize> = subs.iter().map(|s| s.segs.len()).collect();
|
||||
lens.sort_unstable();
|
||||
assert_eq!(lens, [1, 2, 2], "{subs:?}");
|
||||
for s in &subs {
|
||||
let pts: Vec<Vec2> = anchors(s).collect();
|
||||
// No run passes through B or D: they are only ever an end.
|
||||
for q in pts.iter().skip(1).take(pts.len().saturating_sub(2)) {
|
||||
assert!(!close(*q, b) && !close(*q, d), "joined through a junction: {pts:?}");
|
||||
}
|
||||
}
|
||||
// A triangle with a spur at A: the triangle still closes, the spur stays apart.
|
||||
let mut p = Path::default();
|
||||
for (s, e) in [(a, b), (b, c), (c, a), (a, d)] {
|
||||
p.move_to(s).line_to(e);
|
||||
}
|
||||
let subs = subpaths(&chain(&p, 0.01));
|
||||
assert_eq!(subs.len(), 2, "{subs:?}");
|
||||
assert!(subs.iter().any(|s| s.closed && s.segs.len() == 3), "the triangle closes: {subs:?}");
|
||||
assert!(subs.iter().any(|s| !s.closed && s.segs.len() == 1), "the spur stays apart: {subs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_point_snaps_to_the_outline() {
|
||||
let sq = Path::rect(0.0, 0.0, 100.0, 100.0);
|
||||
|
||||
+17
-17
@@ -212,7 +212,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let grad = || Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(120.0, 40.0), stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]));
|
||||
let mut out = Vec::new();
|
||||
// A mask: a gradient seen through a circle, an unclipped shape over it, and one under it.
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))],
|
||||
clip_parents: vec![None],
|
||||
@@ -235,10 +235,10 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
}
|
||||
let mut items = stripes;
|
||||
items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]);
|
||||
out.push(("nested masks", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0)))));
|
||||
out.push(("nested masks", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0)))));
|
||||
// Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles
|
||||
// and the render bands; a top-level shape between two groups.
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0),
|
||||
@@ -266,9 +266,9 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g));
|
||||
items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g));
|
||||
}
|
||||
out.push(("blend modes", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8)))));
|
||||
out.push(("blend modes", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8)))));
|
||||
// Masks inside groups and groups inside masks, with a blend mode, on transparent.
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0),
|
||||
@@ -284,7 +284,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
out.push(("masks and groups", dl, view(110, 90, None)));
|
||||
// Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides
|
||||
// what it clips), a group whose parent is later (top-level), a clip index past the list.
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0),
|
||||
@@ -670,7 +670,7 @@ fn binning_shapes_the_scene_into_tiles() {
|
||||
assert!(b.index.iter().all(|&v| v == 0));
|
||||
// A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In
|
||||
// the middle tile the mask has no artwork, so the clipped fill is left out there.
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0),
|
||||
@@ -699,7 +699,7 @@ fn binning_shapes_the_scene_into_tiles() {
|
||||
|
||||
#[test]
|
||||
fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() {
|
||||
let deep = |n: usize| DisplayList { links: Vec::new(),
|
||||
let deep = |n: usize| DisplayList { left_out: false, links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)],
|
||||
clip_parents: Vec::new(),
|
||||
@@ -712,7 +712,7 @@ fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() {
|
||||
let masks = |n: usize| {
|
||||
let mut items: Vec<DisplayItem> = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect();
|
||||
items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1));
|
||||
DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() }
|
||||
DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() }
|
||||
};
|
||||
assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok());
|
||||
assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips));
|
||||
@@ -883,7 +883,7 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() {
|
||||
.collect();
|
||||
let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1);
|
||||
it.color = ColorTransform::alpha(0.5);
|
||||
DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups }
|
||||
DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups }
|
||||
};
|
||||
let deep = nested(MAX_FILTER_DEPTH + 1);
|
||||
assert!(matches!(g.render(&deep, &view(12, 12, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters))));
|
||||
@@ -994,7 +994,7 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
// Inside a mask and a faded group, over a gradient.
|
||||
let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(80.0, 60.0), stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))])));
|
||||
let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0);
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] };
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] };
|
||||
out.push(("bitmap masked and multiplied", dl, view(80, 60, white)));
|
||||
// Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated.
|
||||
let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned);
|
||||
@@ -1087,7 +1087,7 @@ fn gpu_matches_the_oracle_on_every_filter() {
|
||||
for (name, f) in filters_to_test() {
|
||||
let mut items = vec![backdrop.clone()];
|
||||
items.extend(symbol_items(0));
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] };
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] };
|
||||
// At 1:1; zoomed, so sizes scale; and panned so the layer reaches past the surface.
|
||||
for v in [view(70, 60, Some(Rgba::WHITE)), View { transform: Affine::scale(1.5, 1.5), width: 105, height: 90, background: None }, View { transform: Affine::translate(-20.0, -15.0), width: 40, height: 33, background: Some(Rgba::WHITE) }] {
|
||||
let d = assert_parity(g, name, &dl, &v);
|
||||
@@ -1112,7 +1112,7 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() {
|
||||
(grp.alpha, grp.blend) = (0.7, BlendMode::Multiply);
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0));
|
||||
scenes.push(("filters in a row, faded and multiplied", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] }));
|
||||
scenes.push(("filters in a row, faded and multiplied", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] }));
|
||||
// A filtered symbol inside a filtered symbol, inside a faded one.
|
||||
let mut outer = filtered_group(vec![shadow.clone()]);
|
||||
outer.parent = Some(0);
|
||||
@@ -1120,22 +1120,22 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() {
|
||||
inner.parent = Some(1);
|
||||
let mut items = vec![bg.clone(), in_group(item(Path::rect(4.0, 40.0, 30.0, 16.0), Paint::Solid(Rgba::new(0.9, 0.6, 0.0, 1.0))), 1)];
|
||||
items.extend(symbol_items(2));
|
||||
scenes.push(("nested filtered symbols", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] }));
|
||||
scenes.push(("nested filtered symbols", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] }));
|
||||
// Masked from outside (after filtering) and inside (before).
|
||||
let mut clipped_grp = filtered_group(vec![glow.clone()]);
|
||||
clipped_grp.clip = Some(0);
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0)));
|
||||
items.push(mask(Path::ellipse(36.0, 30.0, 24.0, 20.0), 0));
|
||||
scenes.push(("masked after filtering", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] }));
|
||||
scenes.push(("masked after filtering", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] }));
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0)));
|
||||
items.push(in_group(mask(Path::rect(20.0, 10.0, 16.0, 40.0), 0), 0));
|
||||
scenes.push(("masked inside the symbol", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] }));
|
||||
scenes.push(("masked inside the symbol", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] }));
|
||||
// A bitmap inside a filtered symbol.
|
||||
let px = pixels(9, 7, 4);
|
||||
let items = vec![bg.clone(), in_group(bitmap_item(Path::ellipse(40.0, 32.0, 26.0, 20.0), &px, true, Affine::scale(4.0, 4.0)), 0)];
|
||||
scenes.push(("filtered bitmap", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] }));
|
||||
scenes.push(("filtered bitmap", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] }));
|
||||
for (name, dl) in scenes {
|
||||
for v in [view(80, 64, white), View { transform: Affine::translate(-37.0, -5.0).mul(&Affine::scale(1.3, 1.3)), width: 48, height: 48, background: white }] {
|
||||
let d = assert_parity(g, name, &dl, &v);
|
||||
|
||||
@@ -1477,7 +1477,7 @@ fn filters_and_soft_masks_compose_in_the_page_as_in_the_renderer() {
|
||||
// A mask over the symbol: its artwork drawn as it looks on its own, read as the
|
||||
// page reads it (canvas.js `maskEnd`).
|
||||
let reveal: Option<Vec<f32>> = (!inside).then(|| {
|
||||
let art = anicraft_doc::DisplayList { links: Vec::new(), items: dl.items.iter().filter(|i| i.masks.is_some()).map(|i| anicraft_doc::DisplayItem { masks: None, clip: None, group: None, ..i.clone() }).collect(), clip_parents: Vec::new(), clip_modes: Vec::new(), groups: Vec::new() };
|
||||
let art = anicraft_doc::DisplayList { left_out: false, links: Vec::new(), items: dl.items.iter().filter(|i| i.masks.is_some()).map(|i| anicraft_doc::DisplayItem { masks: None, clip: None, group: None, ..i.clone() }).collect(), clip_parents: Vec::new(), clip_modes: Vec::new(), groups: Vec::new() };
|
||||
let (mp, _) = crate::render(&art, &crate::View { background: None, ..view }).unwrap();
|
||||
mp.data.iter().map(|p| mode.reveal(*p)).collect()
|
||||
});
|
||||
|
||||
+12
-11
@@ -532,6 +532,7 @@ fn filter_setup(dl: &DisplayList, run: &FilteredRun, view: &View, surface: IRect
|
||||
clip_modes: dl.clip_modes.clone(),
|
||||
groups,
|
||||
links: Vec::new(),
|
||||
left_out: dl.left_out,
|
||||
};
|
||||
let sub_view = View { transform: Affine::translate(-b.x0 as f32, -b.y0 as f32).mul(&view.transform), width: b.width() as u32, height: b.height() as u32, background: None };
|
||||
let filters = group.filters.iter().map(|f| filters::resolve(f, scale)).collect();
|
||||
@@ -983,7 +984,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn list(items: Vec<DisplayItem>) -> DisplayList {
|
||||
DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() }
|
||||
DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() }
|
||||
}
|
||||
|
||||
/// A 40 × 40 opaque blue square masked by `art` in `mode`, on transparent.
|
||||
@@ -1078,7 +1079,7 @@ mod tests {
|
||||
let mut mask = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.2)));
|
||||
mask.masks = Some(0);
|
||||
mask.stroke = Some(anicraft_doc::Stroke::new(Rgba::BLACK, 8.0));
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() };
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() };
|
||||
let (pm, _) = render(&dl, &view(40, 40)).unwrap();
|
||||
// Pixel for pixel, the same as the circle drawn in the square's colour.
|
||||
let circle = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
@@ -1146,7 +1147,7 @@ mod tests {
|
||||
let mut blue = item(Path::rect(4.0, 0.0, 8.0, 4.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
red.group = Some(0);
|
||||
blue.group = Some(0);
|
||||
let grouped = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let grouped = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let (pm, _) = render(&grouped, &white).unwrap();
|
||||
let near = |p: Premul, q: [f32; 4]| p.iter().zip(q).all(|(a, b)| (a - b).abs() < 1e-4);
|
||||
// In the overlap only the top square shows through: half blue, half white, no red.
|
||||
@@ -1162,7 +1163,7 @@ mod tests {
|
||||
// Nested groups multiply; a group with a bad parent link is a top-level group.
|
||||
let mut inner = item(Path::rect(0.0, 0.0, 12.0, 4.0), Paint::Solid(Rgba::BLACK));
|
||||
inner.group = Some(1);
|
||||
let nested = DisplayList { links: Vec::new(),
|
||||
let nested = DisplayList { left_out: false, links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![inner],
|
||||
clip_parents: vec![],
|
||||
@@ -1177,7 +1178,7 @@ mod tests {
|
||||
// Spanning several render bands changes nothing.
|
||||
let mut tall = item(Path::rect(0.0, 0.0, 4.0, 100.0), Paint::Solid(Rgba::BLACK));
|
||||
tall.group = Some(0);
|
||||
let (t, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap();
|
||||
let (t, _) = render(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap();
|
||||
assert!((0..100).all(|y| near(t.pixel(1, y).unwrap(), [0.75, 0.75, 0.75, 1.0])));
|
||||
}
|
||||
|
||||
@@ -1207,7 +1208,7 @@ mod tests {
|
||||
inner.masks = Some(1);
|
||||
let mut lost = clipped.clone();
|
||||
lost.clip = Some(2);
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() };
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() };
|
||||
let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
let (_, rst) = render(&dl, &view(16, 16)).unwrap();
|
||||
assert_eq!((st.drawn, st.edges, st.pixels_touched), (rst.drawn, rst.edges, rst.pixels_touched));
|
||||
@@ -1220,7 +1221,7 @@ mod tests {
|
||||
let mut grouped = sq.clone();
|
||||
grouped.group = Some(1);
|
||||
let g = |parent, alpha| anicraft_doc::Group { parent, alpha, blend: BlendMode::Multiply, filters: Default::default(), clip: None };
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] };
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] };
|
||||
let (scene, _) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
assert!(scene.fills.iter().all(|f| f.group == Some(1)));
|
||||
assert_eq!((scene.groups[1].chain.clone(), scene.groups[0].alpha, scene.groups[1].alpha, scene.groups[1].blend), (vec![0, 1], 1.0, 1.0, BlendMode::Multiply));
|
||||
@@ -1262,7 +1263,7 @@ mod tests {
|
||||
let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
|
||||
clipped.clip = Some(0);
|
||||
let free = item(Path::rect(0.0, 0.0, 2.0, 2.0), Paint::Solid(Rgba::BLACK));
|
||||
let (pm, st) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap();
|
||||
let (pm, st) = render(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap();
|
||||
assert_eq!(st.drawn, 1);
|
||||
assert_eq!(pm, render(&list(vec![free]), &view(8, 8)).unwrap().0);
|
||||
}
|
||||
@@ -1277,11 +1278,11 @@ mod tests {
|
||||
inner.masks = Some(1);
|
||||
let items = vec![fill, outer, inner];
|
||||
// Clip 1 lies inside clip 0: a 32 × 32 square across two render bands survives.
|
||||
let (pm, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
let (pm, _) = render(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
assert!((alpha_sum(&pm) - 32.0 * 32.0).abs() < 1e-2, "{}", alpha_sum(&pm));
|
||||
// A parent link pointing forward (malformed) or out of range masks everything out.
|
||||
for parents in [vec![Some(1), Some(1)], vec![None, Some(9)]] {
|
||||
let (pm, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
let (pm, _) = render(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
assert_eq!(alpha_sum(&pm), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -1503,7 +1504,7 @@ mod tests {
|
||||
let bg = item(Path::rect(0.0, 0.0, 20.0, 10.0), Paint::Solid(Rgba::new(0.5, 0.5, 1.0, 1.0)));
|
||||
let mut top = item(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0)));
|
||||
top.group = Some(0);
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] };
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] };
|
||||
let (pm, _) = render(&dl, &View { background: Some(Rgba::WHITE), ..view(20, 10) }).unwrap();
|
||||
let p = pm.pixel(5, 5).unwrap();
|
||||
assert!((p[0] - 0.5).abs() < 1e-3 && p[1].abs() < 1e-3 && p[2].abs() < 1e-3, "red × lavender: {p:?}");
|
||||
|
||||
@@ -703,7 +703,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa
|
||||
items.push(DisplayItem { path: std::sync::Arc::new(outline), transform: Affine::IDENTITY, fill: Some(anicraft_doc::Paint::Solid(st.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, image: None, ..it.clone() });
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(DisplayList { links: Vec::new(), clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() })
|
||||
std::borrow::Cow::Owned(DisplayList { links: Vec::new(), clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone(), left_out: dl.left_out })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -974,7 +974,7 @@ mod tests {
|
||||
smooth: true,
|
||||
warp: None,
|
||||
};
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![item], clip_parents: Vec::new(), groups: Vec::new() };
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![item], clip_parents: Vec::new(), groups: Vec::new() };
|
||||
let view = crate::View { transform: Affine::IDENTITY, width: 400, height: 300, background: Some(anicraft_doc::Rgba::WHITE) };
|
||||
let (pm, _) = crate::render(&dl, &view).unwrap();
|
||||
pm.data.iter().map(|p| 1.0 - p[0]).collect()
|
||||
|
||||
@@ -601,7 +601,7 @@ mod tests {
|
||||
*spread = anicraft_doc::Spread::Reflect;
|
||||
}
|
||||
let items = vec![item(Path::rect(0.0, 0.0, 60.0, 60.0), Some(rad)), item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(lin))];
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(svg.contains("spreadMethod=\"repeat\"") && svg.contains("spreadMethod=\"reflect\""), "{svg}");
|
||||
assert!(svg.contains("color-interpolation=\"linearRGB\""), "{svg}");
|
||||
assert!(svg.contains("fx=\"40\" fy=\"30\""), "focal point half way along the ring's x axis: {svg}");
|
||||
@@ -630,7 +630,7 @@ mod tests {
|
||||
a.stroke = Some(Stroke::new(Rgba::BLACK, 3.0));
|
||||
a.color = ColorTransform::alpha(0.5);
|
||||
a.fill_rule = FillRule::EvenOdd;
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(svg.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"50\" viewBox=\"0 0 100 50\">"));
|
||||
assert!(svg.contains("<rect width=\"100\" height=\"50\" fill=\"#ffffff\"/>"), "background");
|
||||
assert!(svg.contains("d=\"M5 7L25 7L25 27L5 27Z\" fill=\"#ff0000\" fill-opacity=\"0.5\" fill-rule=\"evenodd\""), "{svg}");
|
||||
@@ -645,7 +645,7 @@ mod tests {
|
||||
let mut a = item(Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), None);
|
||||
a.transform = Affine::scale(2.0, 2.0);
|
||||
a.stroke = Some(st);
|
||||
to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage())
|
||||
to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage())
|
||||
};
|
||||
// The default style is written as before: round, no dashes.
|
||||
let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0));
|
||||
@@ -665,7 +665,7 @@ mod tests {
|
||||
fn variable_width_strokes_are_written_as_filled_outlines() {
|
||||
let mut a = item(Path::line(Vec2::new(0.0, 10.0), Vec2::new(80.0, 10.0)), Some(Paint::Solid(Rgba::hex(0xff0000))));
|
||||
a.stroke = Some(Stroke::new(Rgba::hex(0x0000ff), 6.0).with_profile(anicraft_doc::ProfilePreset::TaperBoth.profile()));
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(!svg.contains("stroke-width"), "no SVG stroke: {svg}");
|
||||
assert!(svg.contains("fill=\"#0000ff\""), "the outline is filled in the stroke colour");
|
||||
assert!(svg.contains("fill=\"#ff0000\""), "the shape's own fill stays");
|
||||
@@ -682,7 +682,7 @@ mod tests {
|
||||
outer.masks = Some(0);
|
||||
let mut inner = item(Path::ellipse(25.0, 25.0, 10.0, 10.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
inner.masks = Some(1);
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage());
|
||||
assert!(svg.contains("gradientTransform=\"matrix(1 0 0 1 20 0)\" x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\""), "{svg}");
|
||||
assert!(svg.contains("<stop offset=\"1\" stop-color=\"#ffffff\" stop-opacity=\"0.25\"/>"));
|
||||
assert!(svg.contains("<clipPath id=\"c1\" clipPathUnits=\"userSpaceOnUse\" clip-path=\"url(#c0)\">"), "nested clip");
|
||||
@@ -735,7 +735,7 @@ mod tests {
|
||||
let clear = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::TRANSPARENT)));
|
||||
let mut lost = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
lost.clip = Some(7);
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage());
|
||||
assert_eq!(svg.matches("<path").count(), 1, "{svg}");
|
||||
assert!(svg.contains("<clipPath id=\"c0\" clipPathUnits=\"userSpaceOnUse\"></clipPath>"), "a malformed clip clips everything");
|
||||
assert!(!svg.contains("NaN") && !svg.contains("inf"));
|
||||
@@ -769,7 +769,7 @@ mod group_tests {
|
||||
smooth: true,
|
||||
warp: None,
|
||||
};
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let svg = to_svg(&dl, &Stage { width: 4, height: 4, fps: 24.0, background: Rgba::WHITE });
|
||||
assert!(svg.contains("<g opacity=\"0.5\">") && svg.contains("<g opacity=\"0.25\">"), "{svg}");
|
||||
assert_eq!(svg.matches("<g ").count(), svg.matches("</g>").count(), "balanced");
|
||||
|
||||
@@ -141,6 +141,13 @@ mod tests {
|
||||
assert_eq!(ends(&lock).last().copied(), Some(Vec2::new(17.0, 11.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_overflowing_f32_are_errors() {
|
||||
for bad in ["M0 0 L1e39 0", "M0 0 v , 3.4028236692e38 z", "M0 0 l3e38 0 3e38 0"] {
|
||||
assert!(parse_path_data(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_input_is_an_error() {
|
||||
assert!(parse_path_data("").unwrap().is_empty());
|
||||
|
||||
@@ -14,6 +14,8 @@ fontdb.workspace = true
|
||||
# Shaping (a HarfBuzz port) and outlines/metrics: both already in the tree through egui.
|
||||
harfrust = "0.12"
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
# The Unicode bidi algorithm (UAX #9): embedding levels, line reordering (ADR 0130).
|
||||
craft-text.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Fallback faces (ADR 0130): letters a run's own face has no glyph for are drawn from another
|
||||
//! face on this computer, cluster by cluster (a letter with its marks), so the rest of the block
|
||||
//! keeps its face. The faces tried first are [`FALLBACK_FAMILIES`]; after them, any installed
|
||||
//! face that has the character.
|
||||
//!
|
||||
//! The list, the rule that a cluster moves whole and the rule that invisible format characters
|
||||
//! are never "missing" come from outside PR #40 (SoldierPePe), rebuilt here on shaped clusters.
|
||||
|
||||
use crate::Fonts;
|
||||
use skrifa::MetadataProvider as _;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Families tried, in order, for characters a run's own face doesn't have: faces with wide
|
||||
/// coverage that come with Windows, macOS and common Linux desktops, then the system faces for
|
||||
/// Chinese, Japanese, Korean, Indic and Thai text, then symbols.
|
||||
pub const FALLBACK_FAMILIES: &[&str] = &[
|
||||
"Segoe UI",
|
||||
"Arial",
|
||||
"Tahoma",
|
||||
"Geeza Pro",
|
||||
"Arial Unicode MS",
|
||||
"DejaVu Sans",
|
||||
"Noto Sans",
|
||||
"Noto Sans Arabic",
|
||||
"Noto Naskh Arabic",
|
||||
"Noto Sans Hebrew",
|
||||
"Yu Gothic",
|
||||
"Meiryo",
|
||||
"Hiragino Sans",
|
||||
"Noto Sans CJK JP",
|
||||
"Microsoft YaHei",
|
||||
"Microsoft JhengHei",
|
||||
"PingFang SC",
|
||||
"Noto Sans CJK SC",
|
||||
"Malgun Gothic",
|
||||
"Apple SD Gothic Neo",
|
||||
"Noto Sans CJK KR",
|
||||
"Nirmala UI",
|
||||
"Kohinoor Devanagari",
|
||||
"Noto Sans Devanagari",
|
||||
"Leelawadee UI",
|
||||
"Thonburi",
|
||||
"Noto Sans Thai",
|
||||
"Segoe UI Symbol",
|
||||
"Apple Symbols",
|
||||
"Noto Sans Symbols",
|
||||
"Noto Sans Symbols 2",
|
||||
"Droid Sans Fallback",
|
||||
];
|
||||
|
||||
/// Most fallback faces one block draws with; clusters past it stay in their run's face.
|
||||
pub const MAX_FALLBACK_FACES: usize = 16;
|
||||
|
||||
/// Most characters one layout searches every installed face for (after the list): each search
|
||||
/// opens up to [`crate::MAX_FALLBACK_SEARCH`] faces once, and its answer is remembered.
|
||||
pub(crate) const MAX_WIDE_SEARCHES: usize = 16;
|
||||
|
||||
/// Most answers of the wide search remembered.
|
||||
const MAX_REMEMBERED: usize = 4096;
|
||||
|
||||
/// Whether a character is drawn: not a space, a line break or another control, and not an
|
||||
/// invisible format character (joiners, direction marks and embeddings, variation selectors,
|
||||
/// the byte-order mark, the soft hyphen, tags), which fonts often don't map and which draw as
|
||||
/// nothing.
|
||||
pub fn needs_glyph(c: char) -> bool {
|
||||
let invisible = matches!(c,
|
||||
'\u{00AD}' | '\u{034F}' | '\u{061C}' | '\u{180B}'..='\u{180F}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{206F}' | '\u{FE00}'..='\u{FE0F}' | '\u{FEFF}' | '\u{E0000}'..='\u{E0FFF}');
|
||||
!c.is_control() && !c.is_whitespace() && !invisible
|
||||
}
|
||||
|
||||
/// Which of `candidates` faces draws a cluster whose own face lacks part of it. `cluster` is
|
||||
/// its drawn characters, `own` how many of them its own face has, and `has(f, c)` whether
|
||||
/// candidate `f` has `c`. The first candidate with every character wins, so a letter and its
|
||||
/// marks are shaped together; when none has them all, the one with the most, if that is more
|
||||
/// than the cluster's own face has (the earliest of equals). `None`: it stays where it is.
|
||||
pub(crate) fn pick_face(cluster: &[char], own: usize, candidates: usize, has: &mut dyn FnMut(usize, char) -> bool) -> Option<usize> {
|
||||
let mut best: Option<(usize, usize)> = None;
|
||||
for f in 0..candidates {
|
||||
let n = cluster.iter().filter(|c| has(f, **c)).count();
|
||||
if n == cluster.len() && n > 0 {
|
||||
return Some(f);
|
||||
}
|
||||
if n > own && best.is_none_or(|b| n > b.1) {
|
||||
best = Some((f, n));
|
||||
}
|
||||
}
|
||||
best.map(|b| b.0)
|
||||
}
|
||||
|
||||
/// Which characters which faces have, asked once each.
|
||||
pub(crate) struct Coverage<'f> {
|
||||
fonts: &'f Fonts,
|
||||
memo: HashMap<(fontdb::ID, char), bool>,
|
||||
}
|
||||
|
||||
impl<'f> Coverage<'f> {
|
||||
pub(crate) fn new(fonts: &'f Fonts) -> Self {
|
||||
Coverage { fonts, memo: HashMap::new() }
|
||||
}
|
||||
|
||||
pub(crate) fn has(&mut self, id: fontdb::ID, c: char) -> bool {
|
||||
let fonts = self.fonts;
|
||||
*self.memo.entry((id, c)).or_insert_with(|| fonts.covers(id, c))
|
||||
}
|
||||
}
|
||||
|
||||
impl Fonts {
|
||||
/// The faces of [`FALLBACK_FAMILIES`] on this computer in a weight and slant, in order
|
||||
/// (found once for each).
|
||||
pub(crate) fn fallback_list(&self, bold: bool, italic: bool) -> Arc<[fontdb::ID]> {
|
||||
if let Ok(known) = self.lists.lock()
|
||||
&& let Some(list) = known.get(&(bold, italic))
|
||||
{
|
||||
return list.clone();
|
||||
}
|
||||
let mut out: Vec<fontdb::ID> = Vec::new();
|
||||
for name in FALLBACK_FAMILIES {
|
||||
let q = fontdb::Query {
|
||||
families: &[fontdb::Family::Name(name)],
|
||||
weight: if bold { fontdb::Weight::BOLD } else { fontdb::Weight::NORMAL },
|
||||
stretch: fontdb::Stretch::Normal,
|
||||
style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
|
||||
};
|
||||
if let Some(id) = self.db.query(&q)
|
||||
&& !out.contains(&id)
|
||||
{
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
let out: Arc<[fontdb::ID]> = out.into();
|
||||
if let Ok(mut known) = self.lists.lock() {
|
||||
known.insert((bold, italic), out.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Any installed face with a glyph for `c`: regular faces in family order (so the answer is
|
||||
/// the same from run to run), found once and remembered. `None` when no face has it.
|
||||
pub(crate) fn any_face_with(&self, c: char) -> Option<fontdb::ID> {
|
||||
if let Ok(known) = self.wide.lock()
|
||||
&& let Some(found) = known.get(&c)
|
||||
{
|
||||
return *found;
|
||||
}
|
||||
let regular = |f: &&fontdb::FaceInfo| f.style == fontdb::Style::Normal && (300..=500).contains(&f.weight.0);
|
||||
let mut faces: Vec<(&str, fontdb::ID)> = self.db.faces().filter(regular).filter_map(|f| f.families.first().map(|(n, _)| (n.as_str(), f.id))).filter(|(n, _)| !n.starts_with('.')).collect();
|
||||
faces.sort_unstable_by(|a, b| a.0.cmp(b.0));
|
||||
let found = faces.into_iter().take(crate::MAX_FALLBACK_SEARCH).map(|(_, id)| id).find(|id| self.db.with_face_data(*id, |data, index| skrifa::FontRef::from_index(data, index).is_ok_and(|f| f.charmap().map(c).is_some() && f.outline_glyphs().format().is_some())).unwrap_or(false));
|
||||
if let Ok(mut known) = self.wide.lock()
|
||||
&& known.len() < MAX_REMEMBERED
|
||||
{
|
||||
known.insert(c, found);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Whether face `id` has a glyph for `c`: read from the font once and remembered, so text
|
||||
/// that keeps needing a fallback (every keystroke lays the block out again) doesn't open
|
||||
/// the fallback faces each time.
|
||||
pub(crate) fn covers(&self, id: fontdb::ID, c: char) -> bool {
|
||||
if let Ok(known) = self.covered.lock()
|
||||
&& let Some(has) = known.get(&(id, c))
|
||||
{
|
||||
return *has;
|
||||
}
|
||||
let has = self.db.with_face_data(id, |data, index| crate::face_has(data, index, c)).unwrap_or(false);
|
||||
if let Ok(mut known) = self.covered.lock()
|
||||
&& known.len() < MAX_REMEMBERED * 16
|
||||
{
|
||||
known.insert((id, c), has);
|
||||
}
|
||||
has
|
||||
}
|
||||
|
||||
/// A face's family name.
|
||||
pub(crate) fn family_of(&self, id: fontdb::ID) -> String {
|
||||
self.db.face(id).and_then(|f| f.families.first().map(|(n, _)| n.clone())).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Faces as the characters they have.
|
||||
fn pick(cluster: &str, own: &str, faces: &[&str]) -> Option<usize> {
|
||||
let drawn: Vec<char> = cluster.chars().filter(|c| needs_glyph(*c)).collect();
|
||||
let had = drawn.iter().filter(|c| own.contains(**c)).count();
|
||||
pick_face(&drawn, had, faces.len(), &mut |f, c| faces.get(f).is_some_and(|s| s.contains(c)))
|
||||
}
|
||||
|
||||
/// From outside PR #40: a letter and its marks go together to the first face with all of
|
||||
/// them, even when an earlier face has the letter.
|
||||
#[test]
|
||||
fn a_cluster_moves_whole_to_the_first_face_with_all_of_it() {
|
||||
assert_eq!(pick("e\u{0301}\u{0323}", "e\u{0301}", &["e\u{0323}", "e\u{0301}\u{0323}"]), Some(1));
|
||||
assert_eq!(pick("\u{05D0}", "", &["abc", "\u{05D0}\u{05D1}", "\u{05D0}"]), Some(1), "the earliest face that has it");
|
||||
// No face has all three: the one with the most, when that beats the cluster's own face.
|
||||
assert_eq!(pick("q\u{0301}\u{0323}", "q", &["q\u{0323}", "\u{0301}"]), Some(0));
|
||||
assert_eq!(pick("q\u{0301}\u{0323}", "q\u{0301}", &["q\u{0323}", "\u{0301}"]), None, "no better than its own face: it stays");
|
||||
assert_eq!(pick("\u{10FFFD}", "", &["abc", "def"]), None, "a character no face has");
|
||||
assert_eq!(pick("", "", &["abc"]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invisible_format_characters_need_no_glyph() {
|
||||
for c in ['\u{200C}', '\u{200D}', '\u{200F}', '\u{202B}', '\u{2067}', '\u{FE0F}', '\u{FEFF}', '\u{00AD}', ' ', '\n', '\t'] {
|
||||
assert!(!needs_glyph(c), "{c:?}");
|
||||
}
|
||||
for c in ['a', '\u{05D0}', '\u{0627}', '\u{0301}', '1', '-'] {
|
||||
assert!(needs_glyph(c), "{c:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
-3
@@ -8,14 +8,22 @@
|
||||
//! [`Fonts::layout_glyphs`] also hands back each glyph on its own ([`PlacedGlyph`]), for text
|
||||
//! placed glyph by glyph: along a path ([`on_path`], ADR 0070) or at SVG's per-character
|
||||
//! positions.
|
||||
//!
|
||||
//! Text that mixes directions (Hebrew or Arabic with Latin words and numbers) follows the
|
||||
//! Unicode bidi algorithm, and letters a run's face lacks come from a fallback face (ADR 0130).
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use anicraft_geom::{Path, PathCmd, Vec2};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
mod embed;
|
||||
mod fallback;
|
||||
mod lines;
|
||||
mod rich;
|
||||
#[cfg(test)]
|
||||
mod testfont;
|
||||
pub use embed::{EMBED_EM, Embedding, GlyphTable, MAX_EMBED_CHARS, TableGlyph};
|
||||
pub use fallback::{FALLBACK_FAMILIES, MAX_FALLBACK_FACES, needs_glyph};
|
||||
pub use rich::{MAX_FACES, MAX_RUNS, ParaStyle, RichText, Run, RunStyle, Shift, sanitize_para, sanitize_run};
|
||||
|
||||
/// Families tried, in order, when none is asked for or the one asked for isn't installed.
|
||||
@@ -72,7 +80,8 @@ pub struct Layout {
|
||||
pub height: f32,
|
||||
/// The family actually used (the one asked for, or the fallback).
|
||||
pub family: String,
|
||||
/// Characters the font has no glyph for (drawn as its "notdef" box).
|
||||
/// Characters no face has a glyph for, neither the run's own nor a fallback (drawn as the
|
||||
/// run's face's "notdef" box).
|
||||
pub missing: usize,
|
||||
/// Lines laid out (at least one), and the distance between their baselines (pixels): a
|
||||
/// line that continued the block would start `lines × line_height` below its top.
|
||||
@@ -92,6 +101,9 @@ pub struct Layout {
|
||||
pub pieces: Vec<(u32, Path)>,
|
||||
/// The family each run was laid out in (the one asked for, or the fallback).
|
||||
pub families: Vec<String>,
|
||||
/// The other families letters were drawn from, because their run's face lacks them, in
|
||||
/// the order they were first needed (ADR 0130).
|
||||
pub fallbacks: Vec<String>,
|
||||
}
|
||||
|
||||
/// One laid-out glyph on its own.
|
||||
@@ -352,6 +364,19 @@ fn first_subpath_closed(path: &Path) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Where one cluster (a letter with its marks, or a ligature) stands on its line (ADR 0130).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct CaretBox {
|
||||
/// The characters it covers: from `start` up to `end`.
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
/// Its left and right edges.
|
||||
pub x0: f32,
|
||||
pub x1: f32,
|
||||
/// It reads right to left: `start` is at its right edge.
|
||||
pub rtl: bool,
|
||||
}
|
||||
|
||||
/// One laid-out line's characters and caret positions. Indices count `char`s of the whole text
|
||||
/// (line breaks included); `x` is from the box's left edge, alignment applied.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -360,8 +385,15 @@ pub struct CaretLine {
|
||||
/// trailing spaces belong to it; a line break belongs to neither line).
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
/// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending.
|
||||
/// `(index, x)` of the boundaries clusters start at and of the line's end, ascending by
|
||||
/// index. A cluster's boundary is at the edge it is read from, so in text that mixes
|
||||
/// directions `x` does not rise with the index.
|
||||
pub stops: Vec<(u32, f32)>,
|
||||
/// The paragraph reads right to left: the line starts at its right end.
|
||||
pub rtl: bool,
|
||||
/// The line's clusters as they are displayed, left to right (trailing spaces left out):
|
||||
/// what a selection highlights, and the order a caret moves in.
|
||||
pub boxes: Vec<CaretBox>,
|
||||
/// The line's top and height (to the next line's top, its line spacing included) and its
|
||||
/// baseline, from the box's top (pixels).
|
||||
pub top: f32,
|
||||
@@ -434,8 +466,17 @@ impl std::error::Error for TextError {}
|
||||
pub struct Fonts {
|
||||
db: fontdb::Database,
|
||||
families: Vec<String>,
|
||||
/// Which face, if any, has each character the fallback list didn't (`Fonts::any_face_with`).
|
||||
wide: Remembered<char, Option<fontdb::ID>>,
|
||||
/// The fallback families' faces by weight and slant (`Fonts::fallback_list`), found once.
|
||||
lists: Remembered<(bool, bool), Arc<[fontdb::ID]>>,
|
||||
/// Whether a face has a character, for the letters fallback asked about (`Fonts::covers`).
|
||||
covered: Remembered<(fontdb::ID, char), bool>,
|
||||
}
|
||||
|
||||
/// Answers about the fonts that are worked out once and kept (ADR 0130).
|
||||
type Remembered<K, V> = std::sync::Mutex<std::collections::HashMap<K, V>>;
|
||||
|
||||
static FONTS: OnceLock<Fonts> = OnceLock::new();
|
||||
static EXTRA: OnceLock<Vec<Arc<[u8]>>> = OnceLock::new();
|
||||
|
||||
@@ -470,7 +511,7 @@ impl Fonts {
|
||||
let mut families: Vec<String> = db.faces().filter_map(|f| f.families.first().map(|(n, _)| n.clone())).filter(|n| !n.starts_with('.')).collect();
|
||||
families.sort_by_key(|f| f.to_lowercase());
|
||||
families.dedup();
|
||||
Fonts { db, families }
|
||||
Fonts { db, families, wide: Remembered::default(), lists: Remembered::default(), covered: Remembered::default() }
|
||||
}
|
||||
|
||||
/// A library of just these faces (tests, and documents carrying their own fonts).
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
//! Lines of text that mixes directions (ADR 0130), on shaped clusters and independent of fonts.
|
||||
//!
|
||||
//! The order is the one the Unicode bidi algorithm (UAX #9) prescribes: levels are resolved for
|
||||
//! the paragraph, text is shaped and broken into lines in reading order, and only then is each
|
||||
//! line put in the order it is displayed ([`place`]). A cluster (a letter with its marks, or a
|
||||
//! ligature) is never split, by a line break or by reordering.
|
||||
//!
|
||||
//! Breaking lines in reading order and never inside a cluster is from outside PR #39
|
||||
//! (SoldierPePe); the levels and the reordering are `craft_text::bidi`.
|
||||
|
||||
use crate::CaretBox;
|
||||
use craft_text::bidi;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
|
||||
/// One shaped cluster of a paragraph, in reading order.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Cluster {
|
||||
/// Its glyphs (a range of the paragraph's glyphs, in the order the shaper gave them).
|
||||
pub glyphs: Range<usize>,
|
||||
/// The characters it covers (of the whole text): from `start` up to `end`.
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
/// Its first character, and whether that is white space.
|
||||
pub first: char,
|
||||
pub space: bool,
|
||||
pub advance: f32,
|
||||
/// Its embedding level: odd is right to left.
|
||||
pub level: u8,
|
||||
}
|
||||
|
||||
/// A paragraph's lines as ranges of its clusters, in reading order: wrapped after the last
|
||||
/// space before the room is used up (or between the clusters of a word wider than the line),
|
||||
/// with the spaces at a line's end left out. `room(first)` is the width a line may take
|
||||
/// (`first`: the paragraph's first line); `None` keeps the paragraph on one line. There is
|
||||
/// always at least one line.
|
||||
pub(crate) fn break_lines(clusters: &[Cluster], room: &dyn Fn(bool) -> Option<f32>) -> Vec<Range<usize>> {
|
||||
let trimmed = |start: usize, mut end: usize| {
|
||||
while end > start && clusters.get(end - 1).is_some_and(|c| c.space) {
|
||||
end -= 1;
|
||||
}
|
||||
start..end
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
let (mut start, mut x, mut break_at) = (0usize, 0.0f32, None::<usize>);
|
||||
for (i, c) in clusters.iter().enumerate() {
|
||||
if let Some(w) = room(lines.is_empty())
|
||||
&& !c.space
|
||||
&& x + c.advance > w
|
||||
&& i > start
|
||||
{
|
||||
let end = break_at.unwrap_or(i);
|
||||
lines.push(trimmed(start, end));
|
||||
start = end;
|
||||
x = clusters.get(start..i).map_or(0.0, |rest| rest.iter().map(|r| r.advance).sum());
|
||||
break_at = None;
|
||||
}
|
||||
x += c.advance;
|
||||
if c.space {
|
||||
break_at = Some(i + 1);
|
||||
}
|
||||
}
|
||||
lines.push(trimmed(start, clusters.len()));
|
||||
lines
|
||||
}
|
||||
|
||||
/// One line's clusters in the order they are displayed, left to right (rules L1 and L2), with
|
||||
/// where each one stands: `(cluster, box)`, the cluster as an index into `clusters` and the
|
||||
/// box's x from the line's left end. `line` is the line's range of `clusters` and `para_level`
|
||||
/// its paragraph's embedding level.
|
||||
pub(crate) fn place(clusters: &[Cluster], line: Range<usize>, para_level: u8) -> Vec<(usize, CaretBox)> {
|
||||
let on_line = clusters.get(line.clone()).unwrap_or(&[]);
|
||||
let mixed = para_level > 0 || on_line.iter().any(|c| c.level > 0);
|
||||
let (order, levels): (Vec<usize>, Vec<u8>) = if mixed {
|
||||
let chars: Vec<char> = on_line.iter().map(|c| c.first).collect();
|
||||
let resolved: Vec<u8> = on_line.iter().map(|c| c.level).collect();
|
||||
let levels = bidi::line_levels(&chars, &resolved, para_level);
|
||||
(bidi::visual_order(&levels), levels)
|
||||
} else {
|
||||
((0..on_line.len()).collect(), vec![0; on_line.len()])
|
||||
};
|
||||
let mut x = 0.0f32;
|
||||
let mut out = Vec::with_capacity(order.len());
|
||||
for k in order {
|
||||
let Some(c) = on_line.get(k) else { continue };
|
||||
let rtl = levels.get(k).is_some_and(|l| l % 2 == 1);
|
||||
out.push((line.start + k, CaretBox { start: c.start, end: c.end, x0: x, x1: x + c.advance, rtl }));
|
||||
x += c.advance;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where the caret stands on a line (see [`crate::CaretLine::stops`]): each cluster's first
|
||||
/// character at the edge the cluster is read from (its left when it reads left to right, its
|
||||
/// right otherwise), and the boundary after the line's last cluster at that cluster's other
|
||||
/// edge. `boxes` are the line's, x from the box's left edge; `empty` is where the caret stands
|
||||
/// on a line without clusters.
|
||||
pub(crate) fn stops(boxes: &[CaretBox], empty: (u32, f32)) -> Vec<(u32, f32)> {
|
||||
let mut stops: Vec<(u32, f32)> = boxes.iter().map(|b| (b.start, if b.rtl { b.x1 } else { b.x0 })).collect();
|
||||
stops.sort_by_key(|s| s.0);
|
||||
stops.dedup_by_key(|s| s.0);
|
||||
match boxes.iter().max_by_key(|b| b.start) {
|
||||
Some(last) => stops.push((last.end.max(last.start + 1), if last.rtl { last.x0 } else { last.x1 })),
|
||||
None => stops.push(empty),
|
||||
}
|
||||
stops
|
||||
}
|
||||
|
||||
/// The script each character is shaped in: its own, or for characters every script shares
|
||||
/// (spaces, digits, punctuation, marks) the script before them (after them at the start).
|
||||
/// `None` throughout when no character has a script of its own.
|
||||
pub(crate) struct Scripts {
|
||||
known: HashMap<char, Option<harfrust::Script>>,
|
||||
}
|
||||
|
||||
impl Scripts {
|
||||
pub(crate) fn new() -> Self {
|
||||
Scripts { known: HashMap::new() }
|
||||
}
|
||||
|
||||
/// A character's own script (`None`: common to all, inherited or unknown).
|
||||
fn own(&mut self, c: char) -> Option<harfrust::Script> {
|
||||
if c.is_ascii() {
|
||||
return c.is_ascii_alphabetic().then_some(harfrust::script::LATIN);
|
||||
}
|
||||
*self.known.entry(c).or_insert_with(|| {
|
||||
// harfrust keeps its script table to itself: a buffer of one character says it.
|
||||
let mut one = harfrust::UnicodeBuffer::new();
|
||||
one.add(c, 0);
|
||||
one.guess_segment_properties();
|
||||
let s = one.script();
|
||||
(s != harfrust::script::UNKNOWN && s != harfrust::script::COMMON && s != harfrust::script::INHERITED).then_some(s)
|
||||
})
|
||||
}
|
||||
|
||||
/// The scripts of one paragraph's characters.
|
||||
pub(crate) fn of(&mut self, chars: &[char]) -> Vec<Option<harfrust::Script>> {
|
||||
let mut out: Vec<Option<harfrust::Script>> = chars.iter().map(|c| self.own(*c)).collect();
|
||||
let mut last = out.iter().flatten().next().copied();
|
||||
for s in &mut out {
|
||||
match s {
|
||||
Some(own) => last = Some(*own),
|
||||
None => *s = last,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Clusters of one character each, 10 wide: capitals are right to left (level 1, or the
|
||||
/// level given after them in `levels`), a space is a space.
|
||||
fn clusters(text: &str, levels: &[u8]) -> Vec<Cluster> {
|
||||
text.chars().enumerate().map(|(i, c)| Cluster { glyphs: i..i + 1, start: i as u32, end: i as u32 + 1, first: c, space: c == ' ', advance: 10.0, level: levels.get(i).copied().unwrap_or(0) }).collect()
|
||||
}
|
||||
|
||||
fn shown(cl: &[Cluster], line: Range<usize>, para: u8) -> String {
|
||||
place(cl, line, para).iter().map(|(k, _)| cl[*k].first).collect()
|
||||
}
|
||||
|
||||
/// From outside PR #39: lines are found in reading order, after the last space that fits
|
||||
/// or between the clusters of a word wider than the line.
|
||||
#[test]
|
||||
fn lines_break_in_reading_order() {
|
||||
let wide = |w: f32| move |_: bool| Some(w);
|
||||
assert_eq!(break_lines(&clusters("ab cd ef", &[]), &wide(50.0)), vec![0..5, 6..8]);
|
||||
assert_eq!(break_lines(&clusters("abcdefgh", &[]), &wide(30.0)), vec![0..3, 3..6, 6..8]);
|
||||
assert_eq!(break_lines(&clusters("ab cd", &[]), &|_| None), vec![0..5]);
|
||||
assert_eq!(break_lines(&[], &wide(10.0)), vec![0..0], "an empty paragraph is one empty line");
|
||||
assert_eq!(break_lines(&clusters("ab ", &[]), &wide(100.0)), vec![0..2], "spaces at the end are left out");
|
||||
// A cluster wider than the line stays whole, on a line of its own.
|
||||
let mut big = clusters("abc", &[]);
|
||||
big[1].advance = 500.0;
|
||||
assert_eq!(break_lines(&big, &wide(15.0)), vec![0..1, 1..2, 2..3]);
|
||||
// The first line's room can differ (an indent).
|
||||
let lines = break_lines(&clusters("aa bb cc dd", &[]), &|first| Some(if first { 25.0 } else { 55.0 }));
|
||||
assert_eq!(lines, vec![0..2, 3..8, 9..11]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_is_displayed_in_visual_order() {
|
||||
// Left to right throughout: as written.
|
||||
let ltr = clusters("abc def", &[]);
|
||||
assert_eq!(shown(<r, 0..7, 0), "abc def");
|
||||
// A right-to-left word inside left-to-right text is reversed in place.
|
||||
let mixed = clusters("ab CDE fg", &[0, 0, 0, 1, 1, 1, 0, 0, 0]);
|
||||
assert_eq!(shown(&mixed, 0..9, 0), "ab EDC fg");
|
||||
// A number (level 2) inside a right-to-left paragraph keeps its digits in order, and the
|
||||
// paragraph runs from the right: its first word is the rightmost.
|
||||
let rtl = clusters("ABC 123 DEF", &[1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1]);
|
||||
assert_eq!(shown(&rtl, 0..11, 1), "FED 123 CBA");
|
||||
// Each line is reordered on its own: the first line holds the first words.
|
||||
assert_eq!(shown(&rtl, 0..7, 1), "123 CBA");
|
||||
assert_eq!(shown(&rtl, 8..11, 1), "FED");
|
||||
// Boxes run left to right without gaps, each as wide as its cluster.
|
||||
let boxes: Vec<CaretBox> = place(&mixed, 0..9, 0).into_iter().map(|p| p.1).collect();
|
||||
assert!(boxes.windows(2).all(|w| w[0].x1 == w[1].x0) && boxes[0].x0 == 0.0 && boxes[8].x1 == 90.0);
|
||||
assert_eq!(boxes.iter().map(|b| b.rtl).collect::<Vec<_>>(), [false, false, false, true, true, true, false, false, false]);
|
||||
assert_eq!(boxes[3].start, 5, "the word's last letter is its leftmost");
|
||||
assert_eq!(place(<r, 3..3, 0), Vec::new());
|
||||
assert_eq!(place(<r, 5..99, 0), Vec::new(), "a range outside the paragraph places nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caret_stands_where_each_cluster_is_read_from() {
|
||||
// "ab" then "CDE" right to left: a b E D C. Before C (boundary 2) is the line's right
|
||||
// end; after E (boundary 5, the line's end) is E's left edge, where "ab" ends.
|
||||
let cl = clusters("abCDE", &[0, 0, 1, 1, 1]);
|
||||
let boxes: Vec<CaretBox> = place(&cl, 0..5, 0).into_iter().map(|p| p.1).collect();
|
||||
assert_eq!(stops(&boxes, (0, 0.0)), vec![(0, 0.0), (1, 10.0), (2, 50.0), (3, 40.0), (4, 30.0), (5, 20.0)]);
|
||||
// Left to right, the stops are the clusters' left edges and the line's end.
|
||||
let ltr: Vec<CaretBox> = place(&clusters("abc", &[]), 0..3, 0).into_iter().map(|p| p.1).collect();
|
||||
assert_eq!(stops(<r, (0, 0.0)), vec![(0, 0.0), (1, 10.0), (2, 20.0), (3, 30.0)]);
|
||||
assert_eq!(stops(&[], (7, 4.0)), vec![(7, 4.0)]);
|
||||
// A cluster of several characters has one stop, and the line's end is after all of it.
|
||||
let lig = [CaretBox { start: 0, end: 3, x0: 0.0, x1: 12.0, rtl: false }];
|
||||
assert_eq!(stops(&lig, (0, 0.0)), vec![(0, 0.0), (3, 12.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_characters_take_the_script_beside_them() {
|
||||
let mut s = Scripts::new();
|
||||
let of = |s: &mut Scripts, t: &str| s.of(&t.chars().collect::<Vec<_>>());
|
||||
assert!(of(&mut s, "12 - 3").iter().all(Option::is_none));
|
||||
let latin = Some(harfrust::script::LATIN);
|
||||
assert_eq!(of(&mut s, "(a 1)"), vec![latin; 5], "before the first letter: the script after");
|
||||
let mixed = of(&mut s, "ab \u{05D0}\u{05D1} 12");
|
||||
assert_eq!(&mixed[..3], &[latin; 3]);
|
||||
assert!(mixed[3].is_some() && mixed[3] != latin, "Hebrew letters have their own script");
|
||||
assert_eq!(&mixed[4..], &[mixed[3]; 4], "the space and digits after them are shaped with them");
|
||||
assert_eq!(of(&mut s, ""), Vec::new());
|
||||
}
|
||||
}
|
||||
+314
-131
@@ -4,14 +4,23 @@
|
||||
//! glyphs come out grouped by the run's `paint` (the caller's colour and link), so a block with
|
||||
//! several colours draws as one filled path per colour.
|
||||
//!
|
||||
//! Text that mixes directions (ADR 0130): a run is shaped in stretches of one direction and one
|
||||
//! script, lines are found in reading order and each is then put in the order it is displayed
|
||||
//! ([`crate::lines`]); a cluster its run's face has no glyph for is shaped again in a fallback
|
||||
//! face ([`crate::fallback`]).
|
||||
//!
|
||||
//! One run in one paragraph lays out exactly as [`crate::Fonts::layout`] always has: the same
|
||||
//! outline, box, lines and carets.
|
||||
|
||||
use crate::{Align, CaretLine, Fonts, Layout, MAX_CHARS, Pen, PlacedGlyph, TextError};
|
||||
use crate::fallback::{Coverage, MAX_FALLBACK_FACES, MAX_WIDE_SEARCHES, needs_glyph, pick_face};
|
||||
use crate::lines::{Cluster, Scripts, break_lines, place, stops};
|
||||
use crate::{Align, CaretBox, CaretLine, Fonts, Layout, MAX_CHARS, Pen, PlacedGlyph, TextError};
|
||||
use anicraft_geom::{Path, PathCmd, Vec2};
|
||||
use craft_text::bidi;
|
||||
use skrifa::MetadataProvider as _;
|
||||
use skrifa::raw::TableProvider as _;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Most runs laid out in one block; more are joined into the last.
|
||||
@@ -123,43 +132,188 @@ struct RunMetrics {
|
||||
}
|
||||
|
||||
/// One shaped glyph, ready to place.
|
||||
#[derive(Clone)]
|
||||
struct Shaped {
|
||||
outline: Option<Arc<Path>>,
|
||||
/// Character it starts at (of the whole text).
|
||||
/// The character its cluster starts at (of the whole text).
|
||||
index: u32,
|
||||
run: u32,
|
||||
x_offset: f32,
|
||||
y_offset: f32,
|
||||
advance: f32,
|
||||
space: bool,
|
||||
/// Its face has no glyph for it: this is the face's "notdef" box.
|
||||
notdef: bool,
|
||||
}
|
||||
|
||||
/// A stretch of one paragraph in one run: what is shaped on its own.
|
||||
/// A stretch of one paragraph in one run, one direction and one script: what is shaped on its
|
||||
/// own.
|
||||
struct Segment {
|
||||
para: usize,
|
||||
run: usize,
|
||||
/// Byte range in the text, and the character its start is.
|
||||
/// Its bytes and its characters in the text (from the first, up to the second).
|
||||
bytes: (usize, usize),
|
||||
first_char: u32,
|
||||
chars: (u32, u32),
|
||||
/// Its embedding level: odd reads right to left.
|
||||
level: u8,
|
||||
script: Option<harfrust::Script>,
|
||||
}
|
||||
|
||||
/// A laid-out line: its paragraph, whether it is the paragraph's first, its width, its glyphs
|
||||
/// with their pen x (from the line's start).
|
||||
/// in the order they are displayed with their pen x (from the line's left end), and where its
|
||||
/// clusters stand.
|
||||
struct Line {
|
||||
para: usize,
|
||||
first: bool,
|
||||
width: f32,
|
||||
glyphs: Vec<(Shaped, f32)>,
|
||||
rtl: bool,
|
||||
boxes: Vec<CaretBox>,
|
||||
}
|
||||
|
||||
/// One paragraph: its first character, its length in characters, and its byte range (without
|
||||
/// a trailing `\r`).
|
||||
/// One paragraph: its first character, its length in characters, its byte range (without a
|
||||
/// trailing `\r`) and its embedding level (odd: it reads right to left).
|
||||
struct Para {
|
||||
start: u32,
|
||||
len: u32,
|
||||
bytes: (usize, usize),
|
||||
level: u8,
|
||||
}
|
||||
|
||||
/// A face ready to shape with.
|
||||
struct Face<'a> {
|
||||
font: skrifa::FontRef<'a>,
|
||||
shaper: harfrust::Shaper<'a>,
|
||||
outlines: skrifa::outline::OutlineGlyphCollection<'a>,
|
||||
/// Outlines drawn so far, by glyph and size.
|
||||
cache: HashMap<(u32, u32), Option<Arc<Path>>>,
|
||||
}
|
||||
|
||||
/// A stretch of text to shape in one face.
|
||||
struct Job<'t> {
|
||||
text: &'t str,
|
||||
/// Its paragraph's bytes (the letters around the stretch are its context) and its own.
|
||||
para: (usize, usize),
|
||||
bytes: (usize, usize),
|
||||
first_char: u32,
|
||||
run: u32,
|
||||
rtl: bool,
|
||||
script: Option<harfrust::Script>,
|
||||
/// The size its glyphs are drawn at, and the extra space after each cluster (pixels).
|
||||
size: f32,
|
||||
letter_spacing: f32,
|
||||
}
|
||||
|
||||
/// A cluster (or several in a row) its run's face has no glyph for, to shape in a fallback
|
||||
/// face: its segment, the glyphs it replaces there, its characters and the fallback face.
|
||||
struct Hole {
|
||||
seg: usize,
|
||||
glyphs: Range<usize>,
|
||||
chars: (u32, u32),
|
||||
face: usize,
|
||||
}
|
||||
|
||||
/// Shapes a stretch of text. Glyphs come back in the order they are displayed (left to right),
|
||||
/// as the shaper gives them, each with the character its cluster starts at.
|
||||
fn shape(face: &mut Face<'_>, job: &Job<'_>) -> Vec<Shaped> {
|
||||
let Some(piece) = job.text.get(job.bytes.0..job.bytes.1) else { return Vec::new() };
|
||||
let mut to_char = vec![0u32; piece.len() + 1];
|
||||
let mut n = 0u32;
|
||||
for (b, _) in piece.char_indices() {
|
||||
if let Some(slot) = to_char.get_mut(b) {
|
||||
*slot = n;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
if let Some(last) = to_char.last_mut() {
|
||||
*last = n;
|
||||
}
|
||||
let size = skrifa::instance::Size::new(job.size);
|
||||
let upem = f32::from(skrifa::MetadataProvider::metrics(&face.font, size, skrifa::instance::LocationRef::default()).units_per_em.max(1));
|
||||
let scale = job.size / upem;
|
||||
let mut buffer = harfrust::UnicodeBuffer::new();
|
||||
buffer.push_str(piece);
|
||||
// The letters around it in its paragraph: Arabic letters join across a change of style or
|
||||
// face as they do inside one.
|
||||
if let Some(before) = job.text.get(job.para.0..job.bytes.0) {
|
||||
buffer.set_pre_context(before);
|
||||
}
|
||||
if let Some(after) = job.text.get(job.bytes.1..job.para.1) {
|
||||
buffer.set_post_context(after);
|
||||
}
|
||||
buffer.set_direction(if job.rtl { harfrust::Direction::RightToLeft } else { harfrust::Direction::LeftToRight });
|
||||
if let Some(script) = job.script {
|
||||
buffer.set_script(script);
|
||||
}
|
||||
buffer.guess_segment_properties();
|
||||
let out = face.shaper.shape(buffer, harfrust::ShapeOptions::new());
|
||||
let mut list: Vec<Shaped> = Vec::with_capacity(out.glyph_infos().len());
|
||||
for (info, pos) in out.glyph_infos().iter().zip(out.glyph_positions()) {
|
||||
let local = to_char.get(info.cluster as usize).copied().unwrap_or(n).min(n);
|
||||
let outlines = &face.outlines;
|
||||
let outline = face
|
||||
.cache
|
||||
.entry((info.glyph_id, job.size.to_bits()))
|
||||
.or_insert_with(|| {
|
||||
let g = outlines.get(skrifa::GlyphId::new(info.glyph_id))?;
|
||||
let mut p = Path::new();
|
||||
let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default());
|
||||
let mut pen = Pen { cmds: &mut p.cmds, x: 0.0, y: 0.0 };
|
||||
let _ = g.draw(settings, &mut pen);
|
||||
Some(Arc::new(p))
|
||||
})
|
||||
.clone();
|
||||
list.push(Shaped { outline, index: job.first_char + local, run: job.run, x_offset: pos.x_offset as f32 * scale, y_offset: pos.y_offset as f32 * scale, advance: pos.x_advance as f32 * scale, notdef: info.glyph_id == 0 });
|
||||
}
|
||||
// Letter spacing follows each cluster, not each glyph: a letter's marks stay on it.
|
||||
let mut i = 0;
|
||||
while let Some(index) = list.get(i).map(|g| g.index) {
|
||||
if list.get(i + 1).is_none_or(|next| next.index != index)
|
||||
&& let Some(g) = list.get_mut(i)
|
||||
{
|
||||
g.advance += job.letter_spacing;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
/// The clusters of one segment's glyphs, in reading order: each one's glyphs (a range of
|
||||
/// `glyphs`) and its characters, from its first up to the next cluster's (`end` for the last).
|
||||
fn clusters_of(glyphs: &[Shaped], end: u32) -> Vec<(Range<usize>, u32, u32)> {
|
||||
let mut out: Vec<(Range<usize>, u32, u32)> = Vec::new();
|
||||
let mut i = 0;
|
||||
while let Some(g) = glyphs.get(i) {
|
||||
let mut j = i + 1;
|
||||
while glyphs.get(j).is_some_and(|next| next.index == g.index) {
|
||||
j += 1;
|
||||
}
|
||||
out.push((i..j, g.index, end));
|
||||
i = j;
|
||||
}
|
||||
// Right-to-left glyphs come last character first.
|
||||
out.sort_by_key(|c| c.1);
|
||||
for k in 1..out.len() {
|
||||
let next = out.get(k).map(|c| c.1);
|
||||
if let (Some(c), Some(next)) = (out.get_mut(k - 1), next) {
|
||||
c.2 = next;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Fonts {
|
||||
/// Opens face `id` to shape with it.
|
||||
fn with_face<R>(&self, id: fontdb::ID, f: impl FnOnce(&mut Face<'_>) -> R) -> Option<R> {
|
||||
self.db
|
||||
.with_face_data(id, |data, index| {
|
||||
let font = skrifa::FontRef::from_index(data, index).ok()?;
|
||||
let shaper_data = harfrust::ShaperData::new(&font);
|
||||
let mut face = Face { shaper: shaper_data.shaper(&font).build(), outlines: font.outline_glyphs(), font, cache: HashMap::new() };
|
||||
Some(f(&mut face))
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Lays styled text out ([`RichText`]). `glyphs` also hands back each glyph on its own.
|
||||
pub fn layout_rich(&self, rich: &RichText, glyphs: bool) -> Result<Layout, TextError> {
|
||||
let text = rich.text;
|
||||
@@ -212,6 +366,8 @@ impl Fonts {
|
||||
families.push(faces.get(face).map_or(family, |f| f.1.clone()));
|
||||
}
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
// Embedding levels (UAX #9), when anything in the text reads right to left.
|
||||
let levels = Some(text).filter(|t| !t.is_ascii()).map(|t| bidi::Paragraph::new(t, bidi::Direction::Auto)).filter(bidi::Paragraph::needs_reordering);
|
||||
|
||||
// Paragraphs at line breaks.
|
||||
let mut paras: Vec<Para> = Vec::new();
|
||||
@@ -219,18 +375,25 @@ impl Fonts {
|
||||
for raw in text.split('\n') {
|
||||
let body = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
let len = body.chars().count() as u32;
|
||||
paras.push(Para { start: ch, len, bytes: (byte, byte + body.len()) });
|
||||
let level = levels.as_ref().map_or(0, |l| l.paragraph_level_at(byte));
|
||||
paras.push(Para { start: ch, len, bytes: (byte, byte + body.len()), level });
|
||||
byte += raw.len() + 1;
|
||||
ch += raw.chars().count() as u32 + 1;
|
||||
}
|
||||
// Byte offset of every character (and of the end).
|
||||
let mut byte_of: Vec<usize> = text.char_indices().map(|(b, _)| b).collect();
|
||||
byte_of.push(text.len());
|
||||
// Segments: each paragraph cut at run boundaries (both in order: one pass over each).
|
||||
let mut segs: Vec<(usize, Segment)> = Vec::new();
|
||||
let byte_at = |c: u32| byte_of.get(c as usize).copied().unwrap_or(text.len());
|
||||
// Segments: each paragraph cut at run boundaries (both in order: one pass over each),
|
||||
// and each of those where the direction or the script changes.
|
||||
let mut scripts = Scripts::new();
|
||||
let mut segs: Vec<Segment> = Vec::new();
|
||||
let mut ri = 0usize;
|
||||
for (pi, p) in paras.iter().enumerate() {
|
||||
let (s, e) = (p.start, p.start + p.len);
|
||||
let plain = text.get(p.bytes.0..p.bytes.1).is_none_or(str::is_ascii);
|
||||
let script_of = if plain { Vec::new() } else { scripts.of(chars.get(s as usize..e as usize).unwrap_or(&[])) };
|
||||
let kind = |c: u32| (levels.as_ref().map_or(0, |l| l.level_at(byte_at(c))), script_of.get((c - s) as usize).copied().flatten());
|
||||
while runs.get(ri).is_some_and(|r| r.1 <= s) && ri + 1 < runs.len() {
|
||||
ri += 1;
|
||||
}
|
||||
@@ -240,16 +403,22 @@ impl Fonts {
|
||||
break;
|
||||
}
|
||||
let (a, b) = (s.max(*rs), e.min(*re));
|
||||
if a < b {
|
||||
let bytes = (byte_of.get(a as usize).copied().unwrap_or(p.bytes.1), byte_of.get(b as usize).copied().unwrap_or(p.bytes.1));
|
||||
segs.push((pi, Segment { run: k, bytes, first_char: a }));
|
||||
let mut from = a;
|
||||
while from < b {
|
||||
let (level, script) = kind(from);
|
||||
let mut to = from + 1;
|
||||
while to < b && kind(to) == (level, script) {
|
||||
to += 1;
|
||||
}
|
||||
segs.push(Segment { para: pi, run: k, bytes: (byte_at(from), byte_at(to)), chars: (from, to), level, script });
|
||||
from = to;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
// The segments of each run.
|
||||
let mut segs_of_run: Vec<Vec<usize>> = vec![Vec::new(); runs.len()];
|
||||
for (si, (_, seg)) in segs.iter().enumerate() {
|
||||
for (si, seg) in segs.iter().enumerate() {
|
||||
if let Some(list) = segs_of_run.get_mut(seg.run) {
|
||||
list.push(si);
|
||||
}
|
||||
@@ -261,145 +430,161 @@ impl Fonts {
|
||||
list.push(ri);
|
||||
}
|
||||
}
|
||||
let job_for = |seg: &Segment, bytes: (usize, usize), first_char: u32, m: &RunMetrics| -> Job<'_> {
|
||||
let para = paras.get(seg.para).map_or(bytes, |p| p.bytes);
|
||||
let letter_spacing = runs.get(seg.run).map_or(0.0, |r| r.2.letter_spacing);
|
||||
Job { text, para, bytes, first_char, run: seg.run as u32, rtl: seg.level % 2 == 1, script: seg.script, size: m.glyph_size, letter_spacing }
|
||||
};
|
||||
let mut shaped: Vec<Vec<Shaped>> = (0..segs.len()).map(|_| Vec::new()).collect();
|
||||
let mut metrics: Vec<RunMetrics> = vec![RunMetrics::default(); runs.len()];
|
||||
let mut missing = 0usize;
|
||||
for (fi, (id, _)) in faces.iter().enumerate() {
|
||||
let ok = self.db.with_face_data(*id, |data, index| {
|
||||
let font = skrifa::FontRef::from_index(data, index).ok()?;
|
||||
let shaper_data = harfrust::ShaperData::new(&font);
|
||||
let shaper = shaper_data.shaper(&font).build();
|
||||
let outlines = font.outline_glyphs();
|
||||
let charmap = font.charmap();
|
||||
let os2 = font.os2().ok();
|
||||
let mut cache: HashMap<(u32, u32), Option<Arc<Path>>> = HashMap::new();
|
||||
let ok = self.with_face(*id, |face| {
|
||||
let os2 = face.font.os2().ok();
|
||||
for &ri in runs_of_face.get(fi).map_or(&[][..], Vec::as_slice) {
|
||||
let Some((rs, re, st)) = runs.get(ri) else { continue };
|
||||
let m = run_metrics(&font, os2.as_ref(), st);
|
||||
let Some((_, _, st)) = runs.get(ri) else { continue };
|
||||
let m = run_metrics(&face.font, os2.as_ref(), st);
|
||||
if let Some(slot) = metrics.get_mut(ri) {
|
||||
*slot = m;
|
||||
}
|
||||
missing += chars.get(*rs as usize..*re as usize).unwrap_or(&[]).iter().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(**c).is_none()).count();
|
||||
let size = skrifa::instance::Size::new(m.glyph_size);
|
||||
let upem = f32::from(skrifa::MetadataProvider::metrics(&font, size, skrifa::instance::LocationRef::default()).units_per_em.max(1));
|
||||
let scale = m.glyph_size / upem;
|
||||
for &si in segs_of_run.get(ri).map_or(&[][..], Vec::as_slice) {
|
||||
let Some((_, seg)) = segs.get(si) else { continue };
|
||||
let Some(piece) = text.get(seg.bytes.0..seg.bytes.1) else { continue };
|
||||
let mut to_char = vec![0u32; piece.len() + 1];
|
||||
let mut n = 0u32;
|
||||
for (b, _) in piece.char_indices() {
|
||||
if let Some(slot) = to_char.get_mut(b) {
|
||||
*slot = n;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
if let Some(last) = to_char.last_mut() {
|
||||
*last = n;
|
||||
}
|
||||
let mut buffer = harfrust::UnicodeBuffer::new();
|
||||
buffer.push_str(piece);
|
||||
buffer.guess_segment_properties();
|
||||
let out = shaper.shape(buffer, harfrust::ShapeOptions::new());
|
||||
let mut list: Vec<Shaped> = Vec::with_capacity(out.glyph_infos().len());
|
||||
for (info, pos) in out.glyph_infos().iter().zip(out.glyph_positions()) {
|
||||
let local = to_char.get(info.cluster as usize).copied().unwrap_or(n).min(n);
|
||||
let index = seg.first_char + local;
|
||||
let outline = cache
|
||||
.entry((info.glyph_id, m.glyph_size.to_bits()))
|
||||
.or_insert_with(|| {
|
||||
let g = outlines.get(skrifa::GlyphId::new(info.glyph_id))?;
|
||||
let mut p = Path::new();
|
||||
let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default());
|
||||
let mut pen = Pen { cmds: &mut p.cmds, x: 0.0, y: 0.0 };
|
||||
let _ = g.draw(settings, &mut pen);
|
||||
Some(Arc::new(p))
|
||||
})
|
||||
.clone();
|
||||
list.push(Shaped {
|
||||
outline,
|
||||
index,
|
||||
run: ri as u32,
|
||||
x_offset: pos.x_offset as f32 * scale,
|
||||
y_offset: pos.y_offset as f32 * scale,
|
||||
advance: pos.x_advance as f32 * scale + st.letter_spacing,
|
||||
space: chars.get(index as usize).is_some_and(|c| c.is_whitespace()),
|
||||
});
|
||||
}
|
||||
let Some(seg) = segs.get(si) else { continue };
|
||||
let list = shape(face, &job_for(seg, seg.bytes, seg.chars.0, &m));
|
||||
if let Some(slot) = shaped.get_mut(si) {
|
||||
*slot = list;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
});
|
||||
if ok.flatten().is_none() {
|
||||
if ok.is_none() {
|
||||
return Err(TextError::NoFonts);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback faces (ADR 0130): a cluster its run's face has no glyph for goes, whole, to
|
||||
// the first fallback face that has all of it, and is shaped again there.
|
||||
let mut missing = 0usize;
|
||||
let mut fallback_ids: Vec<fontdb::ID> = Vec::new();
|
||||
let mut holes: Vec<Hole> = Vec::new();
|
||||
if shaped.iter().flatten().any(|g| g.notdef) {
|
||||
let mut cover = Coverage::new(self);
|
||||
let mut lists: HashMap<(bool, bool), Vec<fontdb::ID>> = HashMap::new();
|
||||
let mut searches = 0usize;
|
||||
for (si, seg) in segs.iter().enumerate() {
|
||||
let Some(list) = shaped.get(si).filter(|l| l.iter().any(|g| g.notdef)) else { continue };
|
||||
let Some((_, _, st)) = runs.get(seg.run) else { continue };
|
||||
let Some(own) = face_of_run.get(seg.run).and_then(|f| faces.get(*f)).map(|f| f.0) else { continue };
|
||||
let mut open: Option<Hole> = None;
|
||||
for (g, c0, c1) in clusters_of(list, seg.chars.1) {
|
||||
let lacking = list.get(g.clone()).is_some_and(|gs| gs.iter().any(|x| x.notdef));
|
||||
let drawn: Vec<char> = if lacking { chars.get(c0 as usize..c1 as usize).unwrap_or(&[]).iter().copied().filter(|c| needs_glyph(*c)).collect() } else { Vec::new() };
|
||||
let had = drawn.iter().filter(|c| cover.has(own, **c)).count();
|
||||
let mut chosen: Option<usize> = None;
|
||||
if had < drawn.len() {
|
||||
let candidates = lists.entry((st.bold, st.italic)).or_insert_with(|| self.fallback_list(st.bold, st.italic).iter().copied().filter(|id| *id != own).collect());
|
||||
let mut pick = pick_face(&drawn, had, candidates.len(), &mut |f, c| candidates.get(f).is_some_and(|id| cover.has(*id, c)));
|
||||
let lacks = |id: Option<fontdb::ID>, cover: &mut Coverage| drawn.iter().copied().find(|c| !cover.has(id.unwrap_or(own), *c));
|
||||
// No listed face has all of it: any installed face with the letter.
|
||||
if let Some(c) = lacks(pick.and_then(|f| candidates.get(f).copied()), &mut cover)
|
||||
&& searches < MAX_WIDE_SEARCHES
|
||||
{
|
||||
searches += 1;
|
||||
if let Some(id) = self.any_face_with(c).filter(|id| *id != own && !candidates.contains(id)) {
|
||||
candidates.push(id);
|
||||
pick = pick_face(&drawn, had, candidates.len(), &mut |f, c| candidates.get(f).is_some_and(|id| cover.has(*id, c)));
|
||||
}
|
||||
}
|
||||
chosen = pick.and_then(|f| candidates.get(f).copied()).and_then(|id| match fallback_ids.iter().position(|known| *known == id) {
|
||||
Some(k) => Some(k),
|
||||
None if fallback_ids.len() < MAX_FALLBACK_FACES => {
|
||||
fallback_ids.push(id);
|
||||
Some(fallback_ids.len() - 1)
|
||||
}
|
||||
None => None,
|
||||
});
|
||||
let face = chosen.and_then(|k| fallback_ids.get(k).copied()).unwrap_or(own);
|
||||
missing += drawn.iter().filter(|c| !cover.has(face, **c)).count();
|
||||
}
|
||||
match (&mut open, chosen) {
|
||||
(Some(h), Some(f)) if h.face == f && h.chars.1 == c0 => {
|
||||
h.chars.1 = c1;
|
||||
h.glyphs = h.glyphs.start.min(g.start)..h.glyphs.end.max(g.end);
|
||||
}
|
||||
_ => {
|
||||
holes.extend(open.take());
|
||||
open = chosen.map(|face| Hole { seg: si, glyphs: g, chars: (c0, c1), face });
|
||||
}
|
||||
}
|
||||
}
|
||||
holes.extend(open);
|
||||
}
|
||||
}
|
||||
let mut patches: Vec<(usize, Range<usize>, Vec<Shaped>)> = Vec::new();
|
||||
for (k, id) in fallback_ids.iter().enumerate() {
|
||||
let done = self.with_face(*id, |face| {
|
||||
let mut out = Vec::new();
|
||||
for h in holes.iter().filter(|h| h.face == k) {
|
||||
let (Some(seg), Some(m)) = (segs.get(h.seg), segs.get(h.seg).and_then(|s| metrics.get(s.run))) else { continue };
|
||||
out.push((h.seg, h.glyphs.clone(), shape(face, &job_for(seg, (byte_at(h.chars.0), byte_at(h.chars.1)), h.chars.0, m))));
|
||||
}
|
||||
out
|
||||
});
|
||||
// A face that can't be read after all leaves its clusters as boxes.
|
||||
patches.extend(done.unwrap_or_default());
|
||||
}
|
||||
// Last glyphs first, so the ranges before them stay where they are.
|
||||
patches.sort_by_key(|p| std::cmp::Reverse((p.0, p.1.start)));
|
||||
for (si, range, list) in patches {
|
||||
if let Some(slot) = shaped.get_mut(si)
|
||||
&& range.start <= range.end
|
||||
&& range.end <= slot.len()
|
||||
{
|
||||
slot.splice(range, list);
|
||||
}
|
||||
}
|
||||
let fallbacks: Vec<String> = fallback_ids.iter().map(|id| self.family_of(*id)).collect();
|
||||
|
||||
// Paragraph styles, sanitized; missing ones take the last one's.
|
||||
let para_style = |pi: usize| -> ParaStyle { rich.paragraphs.get(pi).or(rich.paragraphs.last()).map(sanitize_para).unwrap_or_default() };
|
||||
let width = rich.width.filter(|w| w.is_finite() && *w > 0.0).map(|w| w.min(100_000.0));
|
||||
|
||||
// Lines: each paragraph's glyphs, wrapped at spaces to its room if there is a width.
|
||||
// Lines: each paragraph's clusters in reading order, wrapped at spaces to its room if
|
||||
// there is a width; then each line in the order it is displayed.
|
||||
let mut lines: Vec<Line> = Vec::new();
|
||||
let mut seg_iter = segs.into_iter().zip(shaped).peekable();
|
||||
for (pi, _) in paras.iter().enumerate() {
|
||||
let mut seg_iter = segs.iter().zip(shaped).peekable();
|
||||
for (pi, p) in paras.iter().enumerate() {
|
||||
let ps = para_style(pi);
|
||||
let mut run_glyphs: Vec<Shaped> = Vec::new();
|
||||
while let Some(((p, _), _)) = seg_iter.peek() {
|
||||
if *p != pi {
|
||||
break;
|
||||
}
|
||||
if let Some((_, g)) = seg_iter.next() {
|
||||
run_glyphs.extend(g);
|
||||
let mut para_glyphs: Vec<Shaped> = Vec::new();
|
||||
let mut clusters: Vec<Cluster> = Vec::new();
|
||||
while seg_iter.peek().is_some_and(|(seg, _)| seg.para == pi) {
|
||||
let Some((seg, list)) = seg_iter.next() else { break };
|
||||
let base = para_glyphs.len();
|
||||
for (g, start, end) in clusters_of(&list, seg.chars.1) {
|
||||
let advance = list.get(g.clone()).map_or(0.0, |gs| gs.iter().map(|x| x.advance).sum());
|
||||
let first = chars.get(start as usize).copied().unwrap_or(' ');
|
||||
clusters.push(Cluster { glyphs: base + g.start..base + g.end, start, end, first, space: first.is_whitespace(), advance, level: seg.level });
|
||||
}
|
||||
para_glyphs.extend(list);
|
||||
}
|
||||
let room = |first: bool| width.map(|w| w - ps.left_margin - ps.right_margin - if first { ps.indent } else { 0.0 });
|
||||
let mut first = true;
|
||||
let mut line: Vec<(Shaped, f32)> = Vec::new();
|
||||
let mut x = 0.0f32;
|
||||
// Where the current line could break: after its last space.
|
||||
let mut break_at: Option<usize> = None;
|
||||
for g in run_glyphs {
|
||||
if let Some(w) = room(first)
|
||||
&& !g.space
|
||||
&& x + g.advance > w
|
||||
&& !line.is_empty()
|
||||
{
|
||||
// Wrap: at the last space if there is one (dropping trailing spaces), else here.
|
||||
let rest = match break_at {
|
||||
Some(b) => line.split_off(b),
|
||||
None => Vec::new(),
|
||||
};
|
||||
while line.last().is_some_and(|(g, _)| g.space) {
|
||||
line.pop();
|
||||
for (n, range) in break_lines(&clusters, &room).into_iter().enumerate() {
|
||||
let mut line = Line { para: pi, first: n == 0, width: 0.0, glyphs: Vec::new(), rtl: p.level % 2 == 1, boxes: Vec::new() };
|
||||
for (k, at) in place(&clusters, range, p.level) {
|
||||
let mut x = at.x0;
|
||||
for g in clusters.get(k).and_then(|c| para_glyphs.get(c.glyphs.clone())).unwrap_or(&[]) {
|
||||
line.glyphs.push((g.clone(), x));
|
||||
x += g.advance;
|
||||
}
|
||||
let lw = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
lines.push(Line { para: pi, first, width: lw, glyphs: std::mem::take(&mut line) });
|
||||
first = false;
|
||||
let shift = rest.first().map_or(0.0, |(_, gx)| *gx);
|
||||
line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect();
|
||||
x = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
break_at = None;
|
||||
}
|
||||
line.push((g, x));
|
||||
x += line.last().map_or(0.0, |(g, _)| g.advance);
|
||||
if line.last().is_some_and(|(g, _)| g.space) {
|
||||
break_at = Some(line.len());
|
||||
line.width = at.x1;
|
||||
line.boxes.push(at);
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
while line.last().is_some_and(|(g, _)| g.space) {
|
||||
line.pop();
|
||||
}
|
||||
let lw = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
lines.push(Line { para: pi, first, width: lw, glyphs: line });
|
||||
}
|
||||
|
||||
// Each line's room above and below its baseline: the most any run on it needs (an
|
||||
// empty line: the run its paragraph starts in). `(ascent, descent, line height)`, the
|
||||
// height with the paragraph's line spacing.
|
||||
// height with the paragraph's line spacing. A fallback face's letters sit on the line
|
||||
// their run's face makes.
|
||||
let run_at = |c: u32| runs.partition_point(|r| r.0 <= c).saturating_sub(1);
|
||||
let line_metrics = |l: &Line| -> (f32, f32, f32) {
|
||||
let mut list: Vec<usize> = l.glyphs.iter().map(|(g, _)| g.run as usize).collect();
|
||||
@@ -536,6 +721,7 @@ impl Fonts {
|
||||
glyphs: placed,
|
||||
pieces,
|
||||
families,
|
||||
fallbacks,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -592,21 +778,18 @@ fn caret_lines(lines: &[Line], paras: &[Para], tops: &[f32], lm: &[(f32, f32, f3
|
||||
let shift = shift_of(l);
|
||||
let (pstart, plen) = paras.get(l.para).map_or((0, 0), |p| (p.start, p.len));
|
||||
let ch = |i: u32| i.clamp(pstart, pstart + plen);
|
||||
let start = if l.first { pstart } else { l.glyphs.first().map_or(pstart, |(g, _)| ch(g.index)) };
|
||||
let mut stops: Vec<(u32, f32)> = l.glyphs.iter().map(|(g, gx)| (ch(g.index), shift + gx)).collect();
|
||||
stops.sort_by_key(|s| s.0);
|
||||
stops.dedup_by_key(|s| s.0);
|
||||
let boxes: Vec<CaretBox> = l.boxes.iter().map(|b| CaretBox { start: ch(b.start), end: ch(b.end), x0: shift + b.x0, x1: shift + b.x1, rtl: b.rtl }).collect();
|
||||
let start = if l.first { pstart } else { boxes.iter().map(|b| b.start).min().unwrap_or(pstart) };
|
||||
// Where the line starts: its left end, or its right end in a right-to-left paragraph.
|
||||
let edge = shift + if l.rtl { l.width } else { 0.0 };
|
||||
let mut stops = stops(&boxes, (start, edge));
|
||||
if l.first && stops.first().is_none_or(|s| s.0 > start) {
|
||||
stops.insert(0, (start, shift));
|
||||
}
|
||||
// The boundary after the last glyph (its trailing spaces, if any, follow it).
|
||||
if let Some(&(c, _)) = stops.last() {
|
||||
stops.push((c + 1, shift + l.width));
|
||||
stops.insert(0, (start, edge));
|
||||
}
|
||||
let m = lm.get(row).copied().unwrap_or_default();
|
||||
let top = tops.get(row).copied().unwrap_or(0.0);
|
||||
let baseline = if uniform { first_ascent + top } else { top + m.0 };
|
||||
out.push(CaretLine { start, end: start, stops, top, height: m.2, baseline });
|
||||
out.push(CaretLine { start, end: start, stops, top, height: m.2, baseline, rtl: l.rtl, boxes });
|
||||
// The previous line of the same paragraph ends where this one starts.
|
||||
if !l.first && let Some(prev) = out.len().checked_sub(2).and_then(|i| out.get_mut(i)) {
|
||||
prev.end = start;
|
||||
|
||||
@@ -179,3 +179,185 @@ fn hostile_runs_are_capped_and_sanitized() {
|
||||
}
|
||||
assert_eq!(f.layout_rich(&RichText { text: &"x".repeat(MAX_CHARS + 1), runs: &[], paragraphs: &[], width: None }, false), Err(TextError::TooLong));
|
||||
}
|
||||
|
||||
// Mixed directions and fallback faces (ADR 0130), on fonts made in memory (`testfont`): every
|
||||
// letter is a box half an em wide, so at size 20 a letter is 10 pixels.
|
||||
|
||||
use crate::testfont::{self, LETTER_HEIGHT, NOTDEF_HEIGHT};
|
||||
|
||||
const LATIN: &str = "abcdefghijklmnopqrstuvwxyz0123456789 .-";
|
||||
/// Alef, bet, gimel, dalet, he.
|
||||
const HEBREW: &str = "\u{05D0}\u{05D1}\u{05D2}\u{05D3}\u{05D4} ";
|
||||
|
||||
fn both() -> Fonts {
|
||||
Fonts::from_faces([testfont::font("Test Both", &format!("{LATIN}{HEBREW}"), 500)])
|
||||
}
|
||||
|
||||
fn set(f: &Fonts, family: &str, text: &str, width: Option<f32>) -> Layout {
|
||||
let runs = [Run { chars: usize::MAX, style: RunStyle { family: family.into(), size: 20.0, ..RunStyle::default() } }];
|
||||
f.layout_rich(&RichText { text, runs: &runs, paragraphs: &[], width }, true).unwrap()
|
||||
}
|
||||
|
||||
/// The characters of the glyphs on line `row`, left to right.
|
||||
fn shown(l: &Layout, row: usize) -> Vec<u32> {
|
||||
let baseline = l.carets[row].baseline;
|
||||
let mut on: Vec<&PlacedGlyph> = l.glyphs.iter().filter(|g| g.baseline == baseline).collect();
|
||||
on.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
on.iter().map(|g| g.index).collect()
|
||||
}
|
||||
|
||||
/// How many of a layout's glyphs are "notdef" boxes.
|
||||
fn boxes(l: &Layout) -> usize {
|
||||
let notdef = 20.0 * f32::from(NOTDEF_HEIGHT) / f32::from(testfont::EM);
|
||||
let letter = 20.0 * f32::from(LETTER_HEIGHT) / f32::from(testfont::EM);
|
||||
let tall = |g: &&PlacedGlyph| g.outline.bounds().height();
|
||||
assert!(l.glyphs.iter().filter(|g| !g.outline.cmds.is_empty()).all(|g| (tall(&g) - notdef).abs() < 0.01 || (tall(&g) - letter).abs() < 0.01));
|
||||
l.glyphs.iter().filter(|g| !g.outline.cmds.is_empty() && (tall(g) - notdef).abs() < 0.01).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_right_to_left_word_in_left_to_right_text_reads_from_its_right() {
|
||||
let f = both();
|
||||
// a b _ alef bet gimel _ c d: the Hebrew word is displayed gimel, bet, alef.
|
||||
let l = set(&f, "Test Both", "ab \u{05D0}\u{05D1}\u{05D2} cd", None);
|
||||
assert_eq!(shown(&l, 0), vec![0, 1, 2, 5, 4, 3, 6, 7, 8]);
|
||||
assert_eq!((l.width, l.missing, boxes(&l)), (90.0, 0, 0));
|
||||
let c = &l.carets[0];
|
||||
assert!(!c.rtl);
|
||||
// The caret before alef is at the word's right end, after gimel at its left end.
|
||||
assert_eq!((c.x_at(3), c.x_at(4), c.x_at(5), c.x_at(6)), (60.0, 50.0, 40.0, 60.0));
|
||||
assert_eq!(c.boxes.len(), 9);
|
||||
assert!(c.boxes.windows(2).all(|w| w[0].x1 == w[1].x0), "boxes run left to right without gaps");
|
||||
// Text that reads one way is laid out as it always was.
|
||||
let plain = set(&f, "Test Both", "ab cd", None);
|
||||
assert_eq!(shown(&plain, 0), vec![0, 1, 2, 3, 4]);
|
||||
assert_eq!(plain.carets[0].stops, vec![(0, 0.0), (1, 10.0), (2, 20.0), (3, 30.0), (4, 40.0), (5, 50.0)]);
|
||||
}
|
||||
|
||||
/// From outside PR #39: a number inside right-to-left text keeps its digits in order, and a
|
||||
/// wrapped right-to-left paragraph starts with its first words.
|
||||
#[test]
|
||||
fn a_right_to_left_paragraph_runs_from_the_right_and_wraps_in_reading_order() {
|
||||
let f = both();
|
||||
// alef bet _ 1 2 _ gimel dalet, displayed: dalet gimel _ 1 2 _ bet alef.
|
||||
let l = set(&f, "Test Both", "\u{05D0}\u{05D1} 12 \u{05D2}\u{05D3}", None);
|
||||
assert_eq!(shown(&l, 0), vec![7, 6, 5, 3, 4, 2, 1, 0]);
|
||||
let c = &l.carets[0];
|
||||
assert!(c.rtl);
|
||||
assert_eq!((c.x_at(0), c.x_at(8)), (l.width, 0.0), "the paragraph starts at its right end and ends at its left");
|
||||
// Wrapped: the first line holds the first word, each line displayed right to left.
|
||||
let w = set(&f, "Test Both", "\u{05D0}\u{05D1} \u{05D2}\u{05D3}", Some(25.0));
|
||||
assert_eq!(w.lines, 2);
|
||||
assert_eq!((shown(&w, 0), shown(&w, 1)), (vec![1, 0], vec![4, 3]));
|
||||
assert_eq!((w.carets[0].start, w.carets[0].end, w.carets[1].start, w.carets[1].end), (0, 3, 3, 5));
|
||||
// Each paragraph has its own direction.
|
||||
let two = set(&f, "Test Both", "ab\n\u{05D0}\u{05D1}", None);
|
||||
assert_eq!((two.carets[0].rtl, two.carets[1].rtl), (false, true));
|
||||
assert_eq!(shown(&two, 1), vec![4, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styled_runs_keep_their_style_through_reordering() {
|
||||
let f = both();
|
||||
// The first run ends inside the Hebrew word: alef is its last letter.
|
||||
let style = |paint| RunStyle { family: "Test Both".into(), size: 20.0, underline: paint == 2, paint, ..RunStyle::default() };
|
||||
let runs = [Run { chars: 3, style: style(1) }, Run { chars: 2, style: style(2) }];
|
||||
let l = f.layout_rich(&RichText { text: "ab\u{05D0}\u{05D1}\u{05D2}", runs: &runs, paragraphs: &[], width: None }, true).unwrap();
|
||||
assert_eq!(shown(&l, 0), vec![0, 1, 4, 3, 2]);
|
||||
let paint_at = |i: u32| l.glyphs.iter().find(|g| g.index == i).unwrap().paint;
|
||||
assert_eq!([0, 1, 2, 3, 4].map(paint_at), [1, 1, 1, 2, 2]);
|
||||
// The underline is under the second run's two letters, which are displayed first.
|
||||
let piece = &l.pieces.iter().find(|p| p.0 == 2).unwrap().1;
|
||||
let b = piece.bounds();
|
||||
assert!(b.min.x >= 20.0 && b.max.x <= 40.0, "{b:?}");
|
||||
}
|
||||
|
||||
/// From outside PR #40: letters the chosen face lacks come from a fallback face, the block
|
||||
/// keeps its family, and a character no face has is counted.
|
||||
#[test]
|
||||
fn letters_the_face_lacks_come_from_a_fallback_face() {
|
||||
// A listed fallback family wins over another face that has the letters.
|
||||
let f = Fonts::from_faces([testfont::font("Test Latin", LATIN, 500), testfont::font("Noto Sans Hebrew", HEBREW, 800), testfont::font("Aaa Hebrew", HEBREW, 600)]);
|
||||
let l = set(&f, "Test Latin", "ab \u{05D0}\u{05D1}", None);
|
||||
assert_eq!((l.missing, boxes(&l)), (0, 0));
|
||||
assert_eq!((l.family.as_str(), l.families.clone(), l.fallbacks.clone()), ("Test Latin", vec!["Test Latin".to_string()], vec!["Noto Sans Hebrew".to_string()]));
|
||||
assert_eq!(l.width, 30.0 + 32.0, "the Hebrew letters are as wide as the fallback face makes them");
|
||||
assert_eq!(shown(&l, 0), vec![0, 1, 2, 4, 3]);
|
||||
// The line is the chosen face's line, whatever the fallback's metrics are.
|
||||
assert_eq!(l.line_height, set(&f, "Test Latin", "ab", None).line_height);
|
||||
// No listed family: any installed face with the letter.
|
||||
let wide = Fonts::from_faces([testfont::font("Test Latin", LATIN, 500), testfont::font("Zzz Hebrew", HEBREW, 600)]);
|
||||
let l = set(&wide, "Test Latin", "ab \u{05D0}\u{05D1}", None);
|
||||
assert_eq!((l.missing, l.fallbacks.clone(), l.width), (0, vec!["Zzz Hebrew".to_string()], 30.0 + 24.0));
|
||||
// A character no face has is counted and drawn as the chosen face's box; invisible format
|
||||
// characters are neither.
|
||||
let none = set(&f, "Test Latin", "a\u{05E9}", None);
|
||||
assert_eq!((none.missing, boxes(&none), none.fallbacks.len()), (1, 1, 0));
|
||||
let hidden = set(&f, "Test Latin", "a\u{200D}b\u{200F}", None);
|
||||
assert_eq!((hidden.missing, boxes(&hidden)), (0, 0));
|
||||
// Text the face has all of asks no other face.
|
||||
assert_eq!(set(&f, "Test Latin", "abc 123", None).fallbacks, Vec::<String>::new());
|
||||
}
|
||||
|
||||
/// From outside PR #40: a mark its letter's face lacks takes the letter along to a face with
|
||||
/// both, so the two are shaped together.
|
||||
#[test]
|
||||
fn a_letter_goes_with_its_mark_to_the_fallback_face() {
|
||||
let f = Fonts::from_faces([testfont::font("Test Latin", LATIN, 500), testfont::font("Noto Sans", "e\u{0301}", 800)]);
|
||||
let l = set(&f, "Test Latin", "e\u{0301}x", None);
|
||||
assert_eq!((l.missing, boxes(&l), l.fallbacks.clone()), (0, 0, vec!["Noto Sans".to_string()]));
|
||||
let cluster: Vec<&PlacedGlyph> = l.glyphs.iter().filter(|g| g.index == 0).collect();
|
||||
assert_eq!(cluster.len(), 2, "the letter and its mark are one cluster");
|
||||
assert!(cluster.iter().any(|g| g.advance == 16.0), "the letter is the fallback face's");
|
||||
assert_eq!(l.glyphs.iter().find(|g| g.index == 2).unwrap().advance, 10.0, "the next letter stays in its face");
|
||||
// The caret doesn't stop between a letter and its mark.
|
||||
assert_eq!(l.carets[0].stops.iter().map(|s| s.0).collect::<Vec<_>>(), vec![0, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_directions_lay_out_without_panicking() {
|
||||
let f = both();
|
||||
let nested = format!("{}ab\u{05D0}{}", "\u{2067}".repeat(300), "\u{2069}".repeat(300));
|
||||
let texts = ["\u{202E}abc\u{202C}", "\u{05D0}\n\n\u{05D1}\r\n", "a\u{2029}\u{05D0}", "\u{0301}\u{0301}", "\u{200F}", "\u{05D0} \u{05D1} ", " \u{05D0}", "1\u{05D0}2\u{05D1}3", nested.as_str(), "\u{202B}ab\u{05D0}\n\u{202C}\u{05D1}cd"];
|
||||
for text in texts {
|
||||
for width in [None, Some(1.0), Some(35.0)] {
|
||||
let l = set(&f, "Test Both", text, width);
|
||||
assert!(l.width.is_finite() && l.height.is_finite());
|
||||
assert!(l.glyphs.iter().all(|g| g.x.is_finite() && g.advance.is_finite()), "{text:?}");
|
||||
assert_eq!(l.carets.len(), l.lines);
|
||||
for c in &l.carets {
|
||||
assert!(c.start <= c.end && !c.stops.is_empty() && c.stops.iter().all(|s| s.1.is_finite() && (c.start..=c.end).contains(&s.0)), "{text:?} {c:?}");
|
||||
assert!(c.boxes.iter().all(|b| b.start < b.end && b.x0 <= b.x1), "{text:?} {c:?}");
|
||||
}
|
||||
// Every drawn character is on exactly one line.
|
||||
let mut seen: Vec<u32> = l.carets.iter().flat_map(|c| c.boxes.iter().map(|b| b.start)).collect();
|
||||
let n = seen.len();
|
||||
seen.sort_unstable();
|
||||
seen.dedup();
|
||||
assert_eq!(seen.len(), n, "{text:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With this computer's fonts: Arabic letters join, a number inside them keeps its digits in
|
||||
/// order at the line's left, and a face without Arabic letters borrows them (outside PRs #39
|
||||
/// and #40). Skipped where no installed face has Arabic letters.
|
||||
#[test]
|
||||
fn arabic_with_a_number_reads_the_right_way_round_in_any_face() {
|
||||
let Some(f) = fonts() else { return };
|
||||
let l = f.layout_glyphs("\u{0645}\u{0631}\u{062D}\u{0628}\u{0627} 2026", &Style { size: 40.0, ..Style::default() }).unwrap();
|
||||
if l.missing > 0 {
|
||||
eprintln!("no face here has Arabic letters: skipped");
|
||||
return;
|
||||
}
|
||||
let x_of = |i: u32| l.glyphs.iter().filter(|g| g.index == i).map(|g| g.x).fold(f32::INFINITY, f32::min);
|
||||
assert!(x_of(6) < x_of(7) && x_of(7) < x_of(8) && x_of(8) < x_of(9), "the digits read left to right");
|
||||
assert!(x_of(9) < x_of(4) && x_of(4) < x_of(0), "the number is left of the word, whose first letter is rightmost");
|
||||
assert!(l.carets[0].rtl);
|
||||
// Every family draws it: one without Arabic letters says which family lent them.
|
||||
for family in f.families().iter().take(40) {
|
||||
let Ok(in_family) = f.layout("\u{0628}\u{064A}\u{062A} ab", &Style { family: family.clone(), size: 40.0, ..Style::default() }) else { continue };
|
||||
assert_eq!(in_family.family, *family);
|
||||
assert_eq!(in_family.missing, 0, "{family}: the letters it lacks come from a fallback face");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Fonts made in memory for tests, so layout that depends on which letters a face has (mixed
|
||||
//! directions, fallback faces: ADR 0130) is tested the same on every computer. Our own work:
|
||||
//! the tables are written here from the OpenType specification ("Font file", `head`, `hhea`,
|
||||
//! `maxp`, `hmtx`, `cmap` format 12, `loca`, `glyf`, `name`, `post`), and every letter is a box.
|
||||
|
||||
fn be16(out: &mut Vec<u8>, v: u16) {
|
||||
out.extend(v.to_be_bytes());
|
||||
}
|
||||
|
||||
fn be32(out: &mut Vec<u8>, v: u32) {
|
||||
out.extend(v.to_be_bytes());
|
||||
}
|
||||
|
||||
/// The em square, and how tall a letter's box and the "notdef" box are (font units).
|
||||
pub(crate) const EM: u16 = 1000;
|
||||
pub(crate) const LETTER_HEIGHT: i16 = 700;
|
||||
pub(crate) const NOTDEF_HEIGHT: i16 = 300;
|
||||
|
||||
/// A TrueType font named `family` with a glyph for each character of `chars`, every one
|
||||
/// `advance` font units wide: a box [`LETTER_HEIGHT`] tall standing on the baseline (white
|
||||
/// space: nothing). Its "notdef" glyph is a box [`NOTDEF_HEIGHT`] tall. No kerning, ligatures
|
||||
/// or mark positioning.
|
||||
pub(crate) fn font(family: &str, chars: &str, advance: u16) -> Vec<u8> {
|
||||
let mut cps: Vec<char> = chars.chars().collect();
|
||||
cps.sort_unstable();
|
||||
cps.dedup();
|
||||
let n = cps.len() as u16 + 1;
|
||||
let right = advance.saturating_sub(50).max(60) as i16;
|
||||
|
||||
let (mut glyf, mut loca) = (Vec::new(), vec![0u32]);
|
||||
for g in 0..n {
|
||||
let c = g.checked_sub(1).and_then(|i| cps.get(i as usize)).copied();
|
||||
if !c.is_some_and(char::is_whitespace) {
|
||||
let top = if c.is_some() { LETTER_HEIGHT } else { NOTDEF_HEIGHT };
|
||||
for v in [1, 50, 0, right, top] {
|
||||
glyf.extend(i16::to_be_bytes(v));
|
||||
}
|
||||
be16(&mut glyf, 3); // the contour's last point
|
||||
be16(&mut glyf, 0); // no instructions
|
||||
glyf.extend([1u8; 4]); // four on-curve points, coordinates as words
|
||||
for v in [50, 0, right - 50, 0, 0, top, 0, -top] {
|
||||
glyf.extend(i16::to_be_bytes(v));
|
||||
}
|
||||
while glyf.len() % 4 != 0 {
|
||||
glyf.push(0);
|
||||
}
|
||||
}
|
||||
loca.push(glyf.len() as u32);
|
||||
}
|
||||
let loca: Vec<u8> = loca.iter().flat_map(|o| o.to_be_bytes()).collect();
|
||||
|
||||
let mut head = Vec::new();
|
||||
be32(&mut head, 0x0001_0000);
|
||||
be32(&mut head, 0x0001_0000);
|
||||
be32(&mut head, 0);
|
||||
be32(&mut head, 0x5F0F_3CF5);
|
||||
be16(&mut head, 3);
|
||||
be16(&mut head, EM);
|
||||
head.extend([0u8; 16]); // created, modified
|
||||
for v in [0, 0, right, LETTER_HEIGHT] {
|
||||
head.extend(i16::to_be_bytes(v));
|
||||
}
|
||||
be16(&mut head, 0);
|
||||
be16(&mut head, 8);
|
||||
for v in [2i16, 1, 0] {
|
||||
head.extend(v.to_be_bytes()); // direction hint, long `loca` offsets, glyph format
|
||||
}
|
||||
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
for v in [800i16, -200, 0] {
|
||||
hhea.extend(v.to_be_bytes());
|
||||
}
|
||||
be16(&mut hhea, advance);
|
||||
for v in [0i16, 0, right, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
hhea.extend(v.to_be_bytes());
|
||||
}
|
||||
be16(&mut hhea, n);
|
||||
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
for v in [n, 4, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, v);
|
||||
}
|
||||
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..n {
|
||||
be16(&mut hmtx, advance);
|
||||
be16(&mut hmtx, 50);
|
||||
}
|
||||
|
||||
let mut cmap = Vec::new();
|
||||
for v in [0u16, 1, 3, 10] {
|
||||
be16(&mut cmap, v);
|
||||
}
|
||||
be32(&mut cmap, 12);
|
||||
be16(&mut cmap, 12);
|
||||
be16(&mut cmap, 0);
|
||||
be32(&mut cmap, 16 + 12 * cps.len() as u32);
|
||||
be32(&mut cmap, 0);
|
||||
be32(&mut cmap, cps.len() as u32);
|
||||
for (i, c) in cps.iter().enumerate() {
|
||||
for v in [*c as u32, *c as u32, i as u32 + 1] {
|
||||
be32(&mut cmap, v);
|
||||
}
|
||||
}
|
||||
|
||||
let names = [(1u16, family.to_string()), (2, "Regular".to_string()), (4, family.to_string()), (6, family.replace(' ', ""))];
|
||||
let (mut name, mut strings) = (Vec::new(), Vec::new());
|
||||
be16(&mut name, 0);
|
||||
be16(&mut name, names.len() as u16);
|
||||
be16(&mut name, 6 + 12 * names.len() as u16);
|
||||
for (id, s) in &names {
|
||||
let utf16: Vec<u8> = s.encode_utf16().flat_map(u16::to_be_bytes).collect();
|
||||
for v in [3, 1, 0x0409, *id, utf16.len() as u16, strings.len() as u16] {
|
||||
be16(&mut name, v);
|
||||
}
|
||||
strings.extend(utf16);
|
||||
}
|
||||
name.extend(strings);
|
||||
|
||||
let mut post = Vec::new();
|
||||
be32(&mut post, 0x0003_0000);
|
||||
be32(&mut post, 0);
|
||||
post.extend(i16::to_be_bytes(-100));
|
||||
post.extend(i16::to_be_bytes(50));
|
||||
post.extend([0u8; 20]);
|
||||
|
||||
let tables: [(&[u8; 4], Vec<u8>); 9] = [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp), (b"name", name), (b"post", post)];
|
||||
let mut out = Vec::new();
|
||||
be32(&mut out, 0x0001_0000);
|
||||
for v in [9u16, 128, 3, 16] {
|
||||
be16(&mut out, v);
|
||||
}
|
||||
let mut offset = 12 + 16 * tables.len() as u32;
|
||||
let mut body = Vec::new();
|
||||
for (tag, data) in &tables {
|
||||
let mut padded = data.clone();
|
||||
while padded.len() % 4 != 0 {
|
||||
padded.push(0);
|
||||
}
|
||||
let sum = padded.as_chunks::<4>().0.iter().fold(0u32, |a, w| a.wrapping_add(u32::from_be_bytes(*w)));
|
||||
out.extend(*tag);
|
||||
be32(&mut out, sum);
|
||||
be32(&mut out, offset);
|
||||
be32(&mut out, data.len() as u32);
|
||||
offset += padded.len() as u32;
|
||||
body.extend(padded);
|
||||
}
|
||||
out.extend(body);
|
||||
out
|
||||
}
|
||||
@@ -34,6 +34,9 @@ so neither may depend on which fonts happen to be installed.
|
||||
embedded Inter), shapes with `harfrust` (a HarfBuzz port), reads outlines and metrics with
|
||||
`skrifa`, and breaks lines (paragraphs at line breaks; with a width, greedily at spaces).
|
||||
These crates are already in the dependency tree through egui, so no new licences.
|
||||
Text that mixes directions (Arabic or Hebrew with numbers or Latin words) follows the
|
||||
Unicode bidi algorithm, and letters the chosen face doesn't have (Arabic in Inter, say)
|
||||
come from a fallback face: [ADR 0130](0130-mixed-directions-and-fallback-faces.md).
|
||||
Bold and italic pick the matching face of the family; there is no synthetic styling.
|
||||
5. **Break Apart** turns a text element into a shape with the same outlines, as Animate's
|
||||
second Break Apart does.
|
||||
@@ -46,8 +49,8 @@ so neither may depend on which fonts happen to be installed.
|
||||
edited, and the user is told.
|
||||
* Text in Animate documents imports onto this model (ADR 0014).
|
||||
* Not yet: per-character styles in one block, vertical text, text along a path, font
|
||||
embedding for export, glyph fallback across
|
||||
fonts for missing characters (missing glyphs draw as the font's "notdef" box).
|
||||
embedding for export (a character no installed face has draws as the font's "notdef" box,
|
||||
and the command says so: ADR 0130).
|
||||
|
||||
## Note (2026-11-11): text fields
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# ADR 0128: One allowance of work for a frame and for a player step, and frames that say what they left out
|
||||
|
||||
* Status: accepted (2026-11-21)
|
||||
* Relates to: `docs/roadmap.md` (P-002), ADR 0024 (the player), ADR 0125 (the backlog), outside
|
||||
pull request #13, AGENTS.md rule 15
|
||||
|
||||
## Context
|
||||
|
||||
A symbol may hold instances of other symbols, 32 deep (`MAX_SYMBOL_DEPTH`). That cap stops a
|
||||
library that refers to itself in a cycle. It does not stop one that doubles: 32 symbols, each
|
||||
holding two instances of the next, are 2^32 shapes. The editor can't build that by accident, but
|
||||
a damaged or hostile `.anicraft` or `.fla` can hold it, and "never crash" covers such files.
|
||||
|
||||
Pull request #497 gave one evaluation, and one bounds query, an allowance of 1,000,000 element
|
||||
visits (`MAX_EVAL_ELEMENTS`). Outside pull request #13 had proposed a budget first and went
|
||||
further in what it counted. Looking at `main` after #497, four things were still open.
|
||||
|
||||
1. **Work that is not an element visit.** A timeline's layers are looked at on every visit of
|
||||
its symbol and cost nothing, so a symbol with thousands of empty layers multiplied by
|
||||
nesting. An outline of a million commands is measured once per bounds query of each instance.
|
||||
A symbol is found by walking the library, so a library of a hundred thousand symbols
|
||||
multiplied every lookup.
|
||||
2. **The player's step.** Test Movie rebuilds the instance tree after every change in a step
|
||||
(up to 10,000 actions) and evaluates every interactive instance for every pointer event (up
|
||||
to 256), each with a whole frame's allowance of its own. The tree was capped at 10,000
|
||||
instances but looked at every plain element of every one of them for nothing.
|
||||
3. **Nobody was told.** A frame cut short drew in part and looked like lost artwork. An export
|
||||
wrote the partial picture and reported success.
|
||||
4. **Outside PR #13** conflicted with all of it and needed a decision.
|
||||
|
||||
## Decision
|
||||
|
||||
### 1. One unit of work, and what costs more than one
|
||||
|
||||
The allowance stays 1,000,000 units for one evaluation or one bounds query. A unit is one
|
||||
element or one layer looked at. Two things cost more:
|
||||
|
||||
* a shape costs one more unit for every 256 commands of its outline
|
||||
(`PATH_COMMANDS_PER_UNIT`), where it is drawn and where it is measured;
|
||||
* finding a symbol costs one more unit for every 1,024 library entries passed on the way
|
||||
(`LIBRARY_ENTRIES_PER_UNIT`).
|
||||
|
||||
An ordinary document pays nothing extra: outlines are tens of commands and libraries hundreds of
|
||||
symbols, and the heaviest benchmark scene (50,000 shapes) uses a twentieth of the allowance.
|
||||
Once the allowance is spent nothing more is taken from it, so the cut is clean: what was reached
|
||||
is drawn, the rest is not.
|
||||
|
||||
#13 charged one unit for every library entry passed. That bounds the same hostile case, but an
|
||||
honest document with 2,000 symbols and 5,000 instances would spend ten times the allowance on
|
||||
lookups alone and lose artwork. Dividing by 1,024 keeps the bound (a lookup in a library of
|
||||
100,000 symbols costs about 100 units, so at most 10,000 of them happen) and leaves honest
|
||||
documents whole. A map from id to symbol would remove the cost altogether; it is a larger change
|
||||
to the document model and is not needed for the bound.
|
||||
|
||||
### 2. A player step has an allowance of its own
|
||||
|
||||
`MAX_WORK_PER_STEP` is four frames' worth (4,000,000 units). Every rebuild of the instance
|
||||
tree and every hit test in one `step`, `start` or `input` takes from it, in the same units: the
|
||||
tree pays for each layer and each element it looks at, and hit tests evaluate from the step's
|
||||
allowance instead of a fresh one each. When it is spent the step stops as it does when its
|
||||
action or fuel budget is spent, with one line in the Output panel:
|
||||
|
||||
> Stopped this frame early: the movie holds more than one frame may look at, so some instances
|
||||
> and buttons were left out (symbols nested in themselves?)
|
||||
|
||||
The queries the shell makes between steps (`tree`, `hit`, `field_at`, `hit_overlay`) each have
|
||||
one frame's allowance for everything they do; `hit_overlay` used to give every button its own.
|
||||
|
||||
Four frames, not one, because an honest step does look at the movie several times: after a
|
||||
`gotoAndPlay`, after a button changes state, for a pointer that moved. A movie that needs more
|
||||
than four full passes in one step is one no machine plays in time.
|
||||
|
||||
### 3. A list that was cut short says so, and so does whoever shows or writes it
|
||||
|
||||
`DisplayList::left_out` is set by every evaluation whose allowance ran out, and kept when lists
|
||||
are appended (onion skins, the hit-area overlay). It is a plain field of the result:
|
||||
`evaluate` stays a pure function of the document and the frame.
|
||||
|
||||
* **The stage** says once, in the status bar, as an error that stays: "Some artwork on this
|
||||
frame is left out: it holds more than AniCraft draws at once. Nothing is lost. Look for
|
||||
symbols nested many times over." It says it again only after a frame that was whole. The
|
||||
check is skipped while playing, where it would cost an evaluation every frame; the frame
|
||||
playback stops on is checked.
|
||||
* **Commands** that write frames still write them, and add `"left_out": true` and a
|
||||
`"warning"` to their result: `file.export_png`, `file.export_svg`,
|
||||
`file.export_png_sequence`, `file.export_svg_sequence`, `file.export_sprite_sheet`,
|
||||
`file.export_gif`, `file.export_apng`, `file.export_webp`, `file.export_video`. A result
|
||||
without the keys is a whole frame, so nothing that reads results today changes.
|
||||
`anicraft-cli info` reports it for the frame shown, and the MCP `render` tool says it in the
|
||||
picture's caption.
|
||||
* An export is not refused. A partial picture with a warning is more use to someone repairing a
|
||||
damaged file than no picture, and the warning is in the result an agent or a script reads.
|
||||
|
||||
### 4. What was taken from #13, and what was not
|
||||
|
||||
Taken, as ideas, into the allowance `main` already had: counting layers, symbol lookups and
|
||||
outline commands, and making exhaustion something a caller can see. Its author is credited in
|
||||
`AUTHORS.md` and the changelog.
|
||||
|
||||
Not taken: its commits (they rewrite the same functions #497 rewrote, from a base two hundred
|
||||
commits old); the per-entry lookup charge (above); a public budget type that callers pass in
|
||||
(no caller outside `anicraft-doc` needs to share one, and the player does it inside the crate);
|
||||
charging both keyframes of a tween before interpolating (the tweened elements are charged when
|
||||
they are visited, outline included, which bounds how often the work repeats); and refusing
|
||||
**Paste** at a point when the clipboard's bounds were cut short (the paste still lands, offset by
|
||||
the bounds of what was reached, which is the same partial answer every other bounds query gives).
|
||||
|
||||
## Consequences
|
||||
|
||||
* A hostile document costs a bounded amount everywhere it is looked at: about 0.1 s for a frame
|
||||
or a bounds query and under 0.3 s for a whole player step in a debug build on the development
|
||||
machine (the tests that build such documents run in 0.07 s to 0.31 s).
|
||||
* Ordinary documents are unchanged. Evaluating the 50,000-shape stress scene takes 11.7 ms a
|
||||
frame with the change and 11.9 ms without (release build, best of three; the machine's noise
|
||||
is larger than the difference).
|
||||
* `DisplayList` has one more public field. Code that builds one field by field names it.
|
||||
* Not yet: the same note from the Lottie and HTML exporters and from exporter plug-ins (they
|
||||
walk the document their own way), a notice inside the Test Movie window when the picture
|
||||
(and not the step) is cut short, and a count of how much was left out.
|
||||
@@ -0,0 +1,81 @@
|
||||
# ADR 0129: A long Brush stroke never holds the window
|
||||
|
||||
* Status: accepted (2026-11-21)
|
||||
* Relates to: ADR 0033 (the Brush), ADR 0031 (merge drawing), ADR 0122 (a moved selection
|
||||
merges when it is deselected), ADR 0116 (work prepared on another thread, then one command),
|
||||
issue #519, backlog item P-003
|
||||
|
||||
## Context
|
||||
|
||||
Issue #519: a Brush stroke drawn for 40 to 50 seconds without lifting, then moved and
|
||||
deselected, left the window "Not Responding", again and again, and the saved file did the same
|
||||
when it was opened. The reporter's file holds one raw fill of 11 370 curves in 1 107 loops.
|
||||
|
||||
Measured on that file and on generated strokes (`anicraft-cli bench --stroke <samples>` and
|
||||
`--stroke-file <file>`; a 32-thread desktop, so a laptop is several times slower):
|
||||
|
||||
| What | Before | Why |
|
||||
|---|---|---|
|
||||
| `draw.brush`, 6 000 / 20 000 / 60 000 samples of fast scribble | 306 / 807 / 1 563 ms | The distance field (ADR 0033) is sampled piece by piece, each piece over its own bounds. A stroke that goes over itself visits the same cells again and again: 190 million cell visits for 60 000 samples. The cost grew with the stroke's length without limit. |
|
||||
| A frame with part of the stroke selected over the rest (after a marquee) | 3.2 s **a frame** (debug build) | The stipple of a selected raw fill is cut by the artwork above it. Every span of the selection was compared with every span of every occluder: tens of thousands by tens of thousands. |
|
||||
| The merge when a moved stroke is deselected | 75 to 195 ms | `planar::merge`, already bounded (`MAX_SEGMENTS`, `MAX_PAIRS`). |
|
||||
| Drawing the stage with the stroke on it | 3 to 5 ms CPU, 4 to 20 ms GPU | Not a problem. |
|
||||
|
||||
So there were two unbounded costs, one in the engine (the trace) and one in the shell (the
|
||||
selection overlay, paid on every frame, which is the "loop" the reporter saw), and one bounded
|
||||
cost that is still longer than a frame.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **The trace is bounded.** `geom::brush` counts the cells a stroke's pieces would visit and,
|
||||
past `MAX_STAMP_WORK` (2²⁴), samples on a coarser grid, as it already does past `MAX_CELLS`.
|
||||
A cell that is already deep inside paint is skipped with one comparison, since nothing can
|
||||
raise it. The result for a stroke under the budget is unchanged. Past it the grid is at
|
||||
worst the size the brush's own tip asks for at full pressure (a sixth of its radius), so
|
||||
thin parts of a very long stroke are a little less fine; the outline is still traced from a
|
||||
true distance, well under a cell.
|
||||
|
||||
2. **The editor traces a long stroke on another thread.** The trace depends on nothing but the
|
||||
stroke, so it is a pure function of a `StrokeRequest`. When the pointer lifts on a stroke of
|
||||
400 samples or more, the shell starts the trace on a thread (`src/ink.rs`) and keeps drawing
|
||||
the stroke as it was drawn. When the outline is ready, the shell runs the same `draw.brush`
|
||||
as ever with the outline staged (`Session::staged_stroke`): the command takes a staged
|
||||
outline only when it is for exactly the stroke it was asked to paint, and traces otherwise.
|
||||
This is the pattern of ADR 0116 (`staged_video`). The command, its parameters, its undo step
|
||||
and what a script or an assistant sees are unchanged; headless callers trace in the command.
|
||||
|
||||
3. **Nothing comes between a stroke and its paint.** Strokes are painted in the order they
|
||||
were drawn. While strokes wait, only looking around and painting more go ahead: a frame
|
||||
whose input could edit (any key, text, a press that is not the Brush on the stage, a dropped
|
||||
file, playback, a dialog) first finishes the waiting strokes on the window's thread, as does
|
||||
any command (`App::run`, so an assistant's commands too) and leaving the document. The wait
|
||||
is bounded by decision 1. At most eight strokes wait; a ninth waits for the first.
|
||||
|
||||
4. **The merge stays on the window's thread**, bounded as before. A `Session` is not `Send`
|
||||
and cannot be cloned (plug-ins, caches, the undo history), and a merge needs the drawing it
|
||||
merges into, so moving it would mean running the command on a copy and adopting the result,
|
||||
which is a second way for an edit to enter the document. It is not worth that for 75 to
|
||||
220 ms on the largest strokes the app accepts. If it turns out to be, the copy-and-adopt
|
||||
route is the one to take, for every slow command at once, in its own ADR.
|
||||
|
||||
5. **The selection overlay looks up occluders by row.** `subtract_spans` sorts the occluders by
|
||||
their top edge and compares a span only with those in its own rows, in their original order,
|
||||
so the pieces it leaves are the ones it always left.
|
||||
|
||||
## Consequences
|
||||
|
||||
* `draw.brush` on the three generated strokes: 218 / 461 / 383 ms, of which the trace is at
|
||||
most about 300 ms whatever the stroke, and in the editor none of the trace is on the
|
||||
window's thread. What is left there is the merge.
|
||||
* The marquee case is 200 ms once (the cut) instead of seconds on every frame.
|
||||
* A stroke can be on the stage for a moment before it is in the document. Undo, save and every
|
||||
other edit see it, because they wait for it; an update is not installed while one waits.
|
||||
* The web build has one thread: it traces in the command, bounded by decision 1.
|
||||
* *Not done here:* the Subselection tool's click on a shape of 13 000 points (3 s once in a
|
||||
debug build), the Paint Bucket in a gap of such a shape (0.8 s), and the shape tools' snapping
|
||||
near it (about 100 ms a frame in a debug build). They are bounded and one-off or mild, and
|
||||
are listed under P-003 in the roadmap.
|
||||
* *Rejected:* a progress window ("processing strokes", as the reference app shows). With the
|
||||
trace bounded and off the thread there is nothing long enough to report.
|
||||
* *Rejected:* simplifying the outline to fewer curves. It changes what the artist drew, and
|
||||
the curve count was not what cost the time.
|
||||
@@ -0,0 +1,121 @@
|
||||
# ADR 0130: Text that mixes directions, and letters from a fallback face
|
||||
|
||||
* Status: accepted (2026-11-23), built
|
||||
* Relates to: ADR 0012 (text as stored outlines), ADR 0085 (styled runs and paragraphs),
|
||||
ADR 0066 (text fields), ADR 0070 and ADR 0107 (text on a path), ADR 0125 (backlog item P-008),
|
||||
outside PRs #39 and #40 (SoldierPePe)
|
||||
|
||||
## Context
|
||||
|
||||
Two things made text read wrong.
|
||||
|
||||
**Mixed directions.** Layout shaped each run of a paragraph as one stretch, in the direction of
|
||||
its first letter. A number or a Latin word inside Arabic or Hebrew came out reversed ("2026" as
|
||||
"6202"), and a wrapped right-to-left paragraph was broken from its visual left, so its last
|
||||
words came first.
|
||||
|
||||
**Missing letters.** A block was drawn with the faces its runs chose and nothing else. Arabic
|
||||
in a face without Arabic letters (Inter, the default where the app embeds it; Consolas) showed
|
||||
as boxes, and nothing said so.
|
||||
|
||||
Outside PRs #39 and #40 fixed both on the single-style layout that existed before ADR 0085.
|
||||
That layout is gone: text is now runs with their own faces, sizes and paints, in paragraphs
|
||||
with their own alignment and margins, and it is also set along paths and typed into fields
|
||||
while a movie plays. This ADR rebuilds both fixes on that layout and keeps the PRs' ideas and
|
||||
tests.
|
||||
|
||||
The constraints are the old ones: text is stored as outlines, so nothing downstream of layout
|
||||
(the renderers, every exporter, the file) knows about directions or fonts; layout must not
|
||||
panic on any text; and a document must not change because of which fonts a computer has until
|
||||
its text is edited there.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **The order of work is the bidi algorithm's** (Unicode Standard Annex #9). Embedding levels
|
||||
are resolved once for the text; text is shaped and broken into lines in reading order; each
|
||||
line is then put in the order it is displayed. Levels and reordering come from the shared
|
||||
`craft-text` crate's `bidi` module (storytold/craft-libs, on `unicode-bidi`), not from an
|
||||
app copy. A paragraph's direction is its first strong character's (rules P2 and P3).
|
||||
2. **A run is shaped in stretches of one direction and one script.** Each stretch gets its
|
||||
direction from its level and its script from its letters; characters every script shares
|
||||
(spaces, digits, punctuation, marks) take the script before them. Each stretch is shaped
|
||||
with the letters around it as context, so Arabic letters join across a change of style or
|
||||
face as they do inside one. Script itemisation uses the shaper's own script table: no new
|
||||
dependency.
|
||||
3. **Lines are made of shaped clusters.** A cluster is what the shaper says belongs together:
|
||||
a letter with its marks, or a ligature. Lines break after the last space that fits, or
|
||||
between the clusters of a word wider than the line, never inside a cluster; reordering moves
|
||||
clusters whole. Text is shaped once: a line takes its clusters as they were shaped, so a
|
||||
word broken across lines in the middle (only when it is wider than the line) keeps the
|
||||
joining forms it had.
|
||||
4. **Letters a run's face lacks come from a fallback face, cluster by cluster.** After
|
||||
shaping, a cluster with a glyph its face has no letter for is shaped again in another face:
|
||||
the first of `FALLBACK_FAMILIES` (faces with wide coverage that come with Windows, macOS and
|
||||
common Linux desktops, then the system faces for Chinese, Japanese, Korean, Indic and Thai
|
||||
text, then symbols) that has every drawn character of the cluster, in the run's weight and
|
||||
slant; when no listed face has all of it, any installed face that has the letter. A letter
|
||||
and its marks always go together. The rest of the block keeps its face, and so do the line's
|
||||
height and baseline: a fallback face's letters sit on the line the run's face makes.
|
||||
Invisible format characters (joiners, direction marks, variation selectors) are never
|
||||
missing. Limits: 16 fallback faces per block, and 16 searches of every installed face per
|
||||
layout (each remembered).
|
||||
5. **The user is told.** `text.create`, `text.edit` and the other text commands return a note
|
||||
when letters were drawn from another family (naming it) and when characters are in no
|
||||
installed font and show as boxes (how many). The block's font stays the one chosen.
|
||||
6. **Carets know where clusters stand.** A laid-out line carries its paragraph's direction and
|
||||
each cluster's box in display order. A caret's place is the edge its cluster is read from
|
||||
(the right edge of a right-to-left letter). In a field while a movie plays, Left and Right
|
||||
move the caret the way the key points through text that mixes directions, crossing to the
|
||||
line before or after at a line's edge by the paragraph's direction; a selection is still a
|
||||
range of characters and is highlighted as one stretch per direction it runs through. Lines
|
||||
that read left to right throughout behave exactly as before.
|
||||
7. **Nothing downstream changes.** Static text, text on a path and fields store the outlines
|
||||
layout made, in display order, so the CPU and GPU renderers and every exporter draw them as
|
||||
they draw any text. Text on a path takes each glyph's place on its line as it is displayed.
|
||||
No new field in the document: files are unchanged.
|
||||
8. **Tests use fonts made in memory.** `crates/text/src/testfont.rs` writes small TrueType
|
||||
fonts (boxes for letters) from the OpenType specification, so mixed directions and fallback
|
||||
are tested the same on every computer instead of being skipped where a font is missing.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Text in one direction lays out as it did, except where it mixes scripts: a stretch in
|
||||
another script is now shaped with that script's rules.
|
||||
* Letter spacing follows each cluster, not each glyph, so a letter's marks stay on it.
|
||||
* `Layout::missing` counts characters no face has; before, it counted characters the run's own
|
||||
face lacked.
|
||||
* Which fallback face is used depends on the computer. That is the same rule as for fonts
|
||||
(ADR 0012): the outline is stored, so a document only changes where it is edited.
|
||||
* One caret per boundary: at a change of direction a boundary has two places it could be
|
||||
shown, and we show it at the edge of the letter after it (the line's end at the edge of the
|
||||
letter before it). Typing a letter of the other direction there can make it appear away from
|
||||
the caret. Editors with two carets or a caret affinity avoid that; we don't have either yet.
|
||||
|
||||
## Not in this slice
|
||||
|
||||
* A direction setting for a paragraph (it is always the first strong character's), and
|
||||
alignment to the paragraph's start: a right-to-left paragraph is aligned as its paragraph
|
||||
style says, left by default, as left-to-right text is.
|
||||
* The stage editor (the field beside the block) is egui's text editor, which does not reorder;
|
||||
the block updates live and reads correctly. Typing in the block itself is P-019, which will
|
||||
use the caret boxes from point 6.
|
||||
* Script-set text in the HTML export's own player (ADR 0107) is laid out by the page's script
|
||||
from embedded glyph tables, one glyph per character and left to right; authored text there is
|
||||
outlines and reads correctly.
|
||||
* The direction SVG text asks for (`direction`, `unicode-bidi`) on import.
|
||||
* Reshaping a word broken in its middle, hyphenation and kashida justification.
|
||||
* The interface's own right-to-left layout (P-034).
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
* **Depending on `unicode-bidi` directly**, as PR #39 did. The shared crate already wraps it
|
||||
with the line rules (L1 and L2) on slices of levels, which is what a layout made of clusters
|
||||
needs, and rule 9 of the Craft standards asks apps to use shared code.
|
||||
* **Choosing a face per character before shaping**, as PR #40 did, with the Unicode class of
|
||||
each character deciding what a mark attaches to. Shaping first lets the shaper say what a
|
||||
cluster is, needs no extra character tables, costs nothing when the face has every letter,
|
||||
and treats a letter the shaper can compose from parts as present.
|
||||
* **Reshaping every line** after breaking, as PR #39 did. It shapes all text twice; shaping
|
||||
once and breaking between clusters gives the same result at every break that is at a space.
|
||||
* **A bundled font for tests.** A font file is an asset with a licence and a provenance row;
|
||||
the fonts written in `testfont.rs` are code.
|
||||
@@ -422,7 +422,8 @@ Both dialogs remember what you entered. Each command is one undo step.
|
||||
## Transforming artwork
|
||||
|
||||
With the **Free Transform** tool (**Q**), drag a handle (a corner or the middle of an edge) to
|
||||
**scale** (**Shift** keeps the proportions, **Alt** scales about the transformation point),
|
||||
**scale** (the opposite handle stays where it is; **Shift** keeps the proportions, **Alt**
|
||||
scales about the transformation point instead),
|
||||
the line between two handles to **skew** (the opposite edge stays where it is; **Alt** skews
|
||||
about the transformation point), just outside a corner to **rotate** (the pointer turns
|
||||
into a curved arrow there; **Shift** snaps to 15°), or inside the box to **move**.
|
||||
|
||||
+21
-3
@@ -82,9 +82,27 @@ font and tells you, so nothing changes behind your back.
|
||||
|
||||
### Missing characters
|
||||
|
||||
If a font doesn't have a character you type (an emoji, or a letter from another script), the
|
||||
character shows as an empty box. AniCraft doesn't borrow it from another font yet, so pick a font
|
||||
that covers your language.
|
||||
If your font doesn't have a character you type (a letter from another script, or a symbol),
|
||||
AniCraft draws that character with another font on your computer that has it, and tells you
|
||||
which one. The rest of the block stays in your font, and the lines keep their height. For the
|
||||
best look, pick a font that covers your language.
|
||||
|
||||
A character that no font on your computer has shows as an empty box, and AniCraft tells you how
|
||||
many there are.
|
||||
|
||||
### Hebrew, Arabic and other right-to-left text
|
||||
|
||||
Right-to-left text reads the right way round, also when it is mixed with Latin words and
|
||||
numbers: a paragraph that starts with a right-to-left letter runs from the right, a number
|
||||
inside it keeps its digits in order, and a wrapped paragraph starts with its first words. Arabic
|
||||
letters join as they should. This is the same for static text, text on a path and text fields,
|
||||
and in every export.
|
||||
|
||||
* A paragraph is still aligned as its alignment says. For a right-to-left paragraph, choose
|
||||
**Align Right**.
|
||||
* The box you type in over the stage shows the letters in the order you typed them; the text on
|
||||
the stage shows them as they read.
|
||||
* In a text field in Test Movie, **Left** and **Right** move the caret the way they point.
|
||||
|
||||
## Static, dynamic and input text
|
||||
|
||||
|
||||
@@ -33,6 +33,10 @@ Data tables (ADR 0118) read CSV and TSV through `craft-csv` (MIT OR Apache-2.0;
|
||||
dependency is `thiserror`), pinned to the same reviewed commit of `storytold/craft-libs` as
|
||||
`craft-mime` and `craft-gif`. No new licence.
|
||||
|
||||
Text that mixes directions (ADR 0130) resolves embedding levels through `craft-text` (MIT OR
|
||||
Apache-2.0, `storytold/craft-libs`, pinned by `rev`) with only its `bidi` feature, which brings
|
||||
`unicode-bidi` and `unicode-bidi-mirroring` (both MIT OR Apache-2.0). No new licence.
|
||||
|
||||
**Shared-library exceptions (approved by the project lead, 2026-11-17).** The move to the shared
|
||||
Craft crates brought two licences the allowlist doesn't name. Both are accepted as crate-scoped
|
||||
exceptions in `deny.toml`, and the allowlist itself is unchanged:
|
||||
|
||||
@@ -117,6 +117,15 @@ saved command's file) or `{"steps": [{"cmd", "params"}]}` runs the steps as one
|
||||
unlike `anicraft_run_script` a failing step leaves the document as it was. `macro.history` and
|
||||
`macro.save` turn the session's undo steps into a saved command.
|
||||
|
||||
## A frame with artwork left out
|
||||
|
||||
A document can hold more than AniCraft draws in one frame (symbols nested many times over, as
|
||||
in a damaged file): the frame is then drawn in part
|
||||
([ADR 0128](adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md)). The commands
|
||||
that write frames still write it, and their result has `"left_out": true` and a `"warning"`;
|
||||
`anicraft_render` says so in the picture's caption, and the document's state has the two keys
|
||||
for the frame shown. A result without them is a whole frame.
|
||||
|
||||
## Safety
|
||||
|
||||
* Everything runs through the engine's commands, so params are checked and every edit can be
|
||||
|
||||
+4
-4
@@ -99,7 +99,7 @@ not this table, says what matters most.
|
||||
|---|---|---|
|
||||
| Selection | **partial** | Raw shapes, objects, marquee, bend an edge, move a corner ([ADR 0041](adr/0041-selection-tool-on-raw-drawings.md), [ADR 0044](adr/0044-selection-across-layers.md)). Missing: a marquee that takes instances and objects it only touches ([#522](https://github.com/storytold/anicraft/issues/522)), Hide Edges ([#298](https://github.com/storytold/anicraft/issues/298)) (P-017). |
|
||||
| Subselection | **done** | [ADR 0042](adr/0042-subselection-and-merging-everywhere.md), [ADR 0045](adr/0045-raw-points-and-raw-shapes-inside-symbols.md). |
|
||||
| Free Transform | **partial** | Scale, skew, rotate, the transformation point, a box that turns with the object ([ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md)), Envelope ([ADR 0080](adr/0080-drawing-parity-leftovers.md)). Missing: Distort. Open bugs: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117)) (P-005). |
|
||||
| Free Transform | **partial** | Scale, skew, rotate, the transformation point, a box that turns with the object ([ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md)), Envelope ([ADR 0080](adr/0080-drawing-parity-leftovers.md)). Missing: Distort. Open bug: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), not reproduced on Windows 10 (P-005). |
|
||||
| Gradient Transform | **done** | Gradient and bitmap fills, Lock Fill. |
|
||||
| Lasso | **missing** | P-018 ([#515](https://github.com/storytold/anicraft/issues/515)). |
|
||||
| Polygon (lasso) | **missing** | P-018. |
|
||||
@@ -192,8 +192,8 @@ not this table, says what matters most.
|
||||
| Justified text | **missing** | Drawn left-aligned (P-033). |
|
||||
| Superscript, subscript, first-line indent, margins | **missing** | P-033. |
|
||||
| Vertical text | **missing** | P-033. |
|
||||
| Mixed directions (Hebrew or Arabic with Latin and numbers) | **partial** | Shaped per paragraph in one direction; outside PR [#39](https://github.com/storytold/anicraft/issues/39) fixes it (P-008). |
|
||||
| Letters the font lacks drawn from a fallback face | **partial** | Outside PR [#40](https://github.com/storytold/anicraft/issues/40) (P-008). |
|
||||
| Mixed directions (Hebrew or Arabic with Latin and numbers) | **partial** | Static text, text on a path and fields follow the Unicode bidi algorithm, in every export; in a field the arrow keys move the caret the way they point ([ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md); [text](guide/text.md)). Missing: a direction setting for a paragraph with alignment to its start, and right-to-left text a script sets in the HTML page (P-033). |
|
||||
| Letters the font lacks drawn from a fallback face | **done** | From a list of system faces, then any installed face; the command says which family lent them ([ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md)). |
|
||||
| Anti-alias modes and device fonts | **partial** | Text is stored as outlines, so it draws the same everywhere; there is no choice of anti-aliasing or of device fonts. |
|
||||
| Break Apart text into letters, then shapes | **done** | One step to shapes. |
|
||||
| Filters on text | **done** | [ADR 0099](adr/0099-filter-colour-and-stepped-tracks-built-in-presets-and-filters-on-text.md). |
|
||||
@@ -276,7 +276,7 @@ not this table, says what matters most.
|
||||
| Motion presets: save a tween, apply it elsewhere | **missing** | P-041. |
|
||||
| Copy and paste motion; paste properties | **missing** | P-041. |
|
||||
| 3D properties in a motion tween | **missing** | With the 3D tools (P-044). |
|
||||
| Shape tweens | **done** | Open: strokes that should follow their fills (outside PR [#238](https://github.com/storytold/anicraft/issues/238), P-011). |
|
||||
| Shape tweens | **done** | A raw shape's outline morphs with its fill, whatever the number of sides, and rides a motion guide with the fill it edges (an edge two fills share goes with the lower one). |
|
||||
| Shape hints | **done** | [ADR 0023](adr/0023-shape-hints.md). [#82](https://github.com/storytold/anicraft/issues/82) can close. Missing: hints inside a symbol edited in place. |
|
||||
| Shape tween blend (distributive, angular) | **partial** | One blend; no choice?. |
|
||||
| Keep area while tweening | **ours** | [ADR 0115](adr/0115-pen-parity-and-keep-area-tweens.md). |
|
||||
|
||||
@@ -9,6 +9,8 @@ oracle; its output must stay bit-identical).
|
||||
```sh
|
||||
cargo run --release -p anicraft-cli -- bench # 50 layers × 200 shapes × 240 frames
|
||||
cargo run --release -p anicraft-cli -- bench --layers 200 --shapes 500 --frames 600
|
||||
cargo run --release -p anicraft-cli -- bench --stroke 6000 # one long Brush stroke (ADR 0129)
|
||||
cargo run --release -p anicraft-cli -- bench --stroke-file drawing.anicraft # the same steps on a file
|
||||
```
|
||||
|
||||
`bench` builds a deterministic stress document (`doc::sample::stress`) and reports file size,
|
||||
@@ -37,6 +39,8 @@ The default `bench` scenario: 50 layers × 200 shapes × 240 frames, 200k elemen
|
||||
| UI frame while rendering | never blocked | worker thread ✅ | design (ADR 0002) |
|
||||
| Autosave: time on the editing thread | < 1 ms | 7–15 µs ✅ | `bench --check` |
|
||||
| Autosave of the 65 MB file, in the background | < 2 s | 183–184 ms ✅ | `bench --check` |
|
||||
| A long Brush stroke: tracing its outline (ADR 0129) | bounded: `MAX_STAMP_WORK` cells visited, whatever the stroke | 45 to 310 ms for 1,500 to 100,000 samples, sizes 3 to 60 (2026-11-21; 1,500 ms and growing before) | test, every PR (the budget, not the time) |
|
||||
| A long Brush stroke in the editor | the trace is never on the window's thread | worker thread ✅; the merge (75 to 220 ms at the largest) still is | test, every PR |
|
||||
| GPU stage, 1,000 shapes at 4K, stage tiles (M3 exit) | < 16.7 ms | 4.5–4.7 ms ✅ (2026-11-10, RTX 5090) | `gpu_bench --check` |
|
||||
| GPU stage, 10k shapes at 4K, stage tiles | < 16.7 ms | 10.1–10.4 ms ✅ | `gpu_bench --check` |
|
||||
| GPU stage, 50k shapes at 1080p, stage tiles | < 33.3 ms (30 fps) | 24.8–26.3 ms ✅ | `gpu_bench --check` |
|
||||
|
||||
+16
-15
@@ -45,15 +45,16 @@ the changelog.
|
||||
|---|---|---|---|---|---|
|
||||
| P-001 | AniCraft starts on every supported machine: the launch failures on Windows and Linux graphics drivers ([#164](https://github.com/storytold/anicraft/issues/164), [#158](https://github.com/storytold/anicraft/issues/158), [#207](https://github.com/storytold/anicraft/issues/207), [#268](https://github.com/storytold/anicraft/issues/268), [#421](https://github.com/storytold/anicraft/issues/421), [#342](https://github.com/storytold/anicraft/issues/342); duplicates [#488](https://github.com/storytold/anicraft/issues/488), [#448](https://github.com/storytold/anicraft/issues/448), [#412](https://github.com/storytold/anicraft/issues/412), [#313](https://github.com/storytold/anicraft/issues/313), [#286](https://github.com/storytold/anicraft/issues/286), [#285](https://github.com/storytold/anicraft/issues/285)) each end in a window or a message that says what to do | Preferences, platforms | M | reports' logs | platform |
|
||||
| P-002 | Nested symbols can't exhaust memory or hang: a work budget on evaluation and bounds (outside PR [#13](https://github.com/storytold/anicraft/issues/13)) | Symbols | S | | doc |
|
||||
| P-003 | A long Brush stroke never freezes the app ([#519](https://github.com/storytold/anicraft/issues/519)): bound the trace and fit, keep the stage responsive while it merges | Tools | M | | stage |
|
||||
| P-003 | What is left of "a long Brush stroke never freezes the app" ([#519](https://github.com/storytold/anicraft/issues/519)) after [ADR 0129](adr/0129-a-long-brush-stroke-never-holds-the-window.md) bounded the trace, took it off the window's thread and fixed the selection overlay: on one raw shape of ten thousand points and more, the Subselection tool's click (seconds, once), the Paint Bucket in a gap (about a second) and the shape tools' snapping (slow frames); and the merge of such a shape (75 to 220 ms) still runs on the window's thread | Tools | S each | | stage |
|
||||
| P-004 | Memory and frame time stay flat: 900 MB for a 24-frame move in the web build ([#314](https://github.com/storytold/anicraft/issues/314)), stutter when zoomed in ([#477](https://github.com/storytold/anicraft/issues/477)); a budget test for each | Workspace | M | | render |
|
||||
| P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117)); decide [#193](https://github.com/storytold/anicraft/issues/193) (see outside PR [#218](https://github.com/storytold/anicraft/issues/218)) and write the rule in the guide | Tools | M | | stage |
|
||||
| P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), which did not reproduce on Windows 10 (the curved pointer shows outside a corner in the real window; the headless press-and-drag tests pass) and needs the reporter's build number and steps. Done: handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117), tested end to end), and [#193](https://github.com/storytold/anicraft/issues/193) decided by [ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md) with the rule in the guide | Tools | S | the reporter's answer | stage |
|
||||
| P-006 | Animate files open right: lines missing or filled in ([#498](https://github.com/storytold/anicraft/issues/498)), a `.fla` refused on macOS ([#347](https://github.com/storytold/anicraft/issues/347)); each fixed file joins the corpus | Import | M | the reporters' files | xfl |
|
||||
| P-007 | The web build is usable: import, export and save ([#55](https://github.com/storytold/anicraft/issues/55)), preferences kept ([#56](https://github.com/storytold/anicraft/issues/56)), a web asset on each release ([#316](https://github.com/storytold/anicraft/issues/316), [#210](https://github.com/storytold/anicraft/issues/210)), a run in a real browser in CI | Preferences, platforms | M | | platform |
|
||||
| P-008 | Text reads right: mixed directions (outside PR [#39](https://github.com/storytold/anicraft/issues/39)), then letters from a fallback face (outside PR [#40](https://github.com/storytold/anicraft/issues/40)) | Text | M | [#39](https://github.com/storytold/anicraft/issues/39) before [#40](https://github.com/storytold/anicraft/issues/40) | text |
|
||||
| P-010 | Panel bugs still open: a side dock that grows under the pointer ([#159](https://github.com/storytold/anicraft/issues/159): not reproduced on `main`, which a test now pins at the reported interface scales; needs the reporters to retest a current build) and the flicker in [#255](https://github.com/storytold/anicraft/issues/255) (needs the machine; Preferences › Window graphics is the way round it). Fixed: [#513](https://github.com/storytold/anicraft/issues/513), [#246](https://github.com/storytold/anicraft/issues/246) | Workspace | S each | the reporters | shell |
|
||||
| P-011 | Shape tweens morph a raw shape's outline with its fill (outside PR [#238](https://github.com/storytold/anicraft/issues/238)) | Tweens | S | | doc |
|
||||
| P-012 | Small hardening fixes from outside: overflow in `Vec2::length` ([#142](https://github.com/storytold/anicraft/issues/142)), alpha kept by `Rgba::to_hex` ([#233](https://github.com/storytold/anicraft/issues/233)), a test for path numbers past `f32` ([#130](https://github.com/storytold/anicraft/issues/130)), private-use language tags ([#486](https://github.com/storytold/anicraft/issues/486)), a test of SVG link sanitising ([#500](https://github.com/storytold/anicraft/issues/500)) | (robustness) | S each | | several |
|
||||
| P-009 | Timeline bugs: a click on the playhead acts on every layer ([#195](https://github.com/storytold/anicraft/issues/195), outside PR [#222](https://github.com/storytold/anicraft/issues/222)), several layers selected with Ctrl and Shift ([#512](https://github.com/storytold/anicraft/issues/512)), the layer count over the header icons ([#523](https://github.com/storytold/anicraft/issues/523)), the mask edge drawn in the layer colour ([#429](https://github.com/storytold/anicraft/issues/429)) | Timeline, layers | S each | | timeline |
|
||||
| P-013 | No hairline between merged curved fills ([#182](https://github.com/storytold/anicraft/issues/182)) | Drawing model | M | | geom |
|
||||
| P-014 | Pen pressure on every desktop: Linux Wayland (outside PR [#320](https://github.com/storytold/anicraft/issues/320)), reports from tablets ([#290](https://github.com/storytold/anicraft/issues/290)) | Tools | M | a tablet to test with | platform |
|
||||
| P-015 | Verified by hand on real machines: the Mac checklist of [ADR 0062](adr/0062-test-movie-window-and-macos-document-opening.md), a hybrid-GPU laptop, passes with Narrator, VoiceOver and Orca ([ADR 0064](adr/0064-accessibility-second-pass.md)), launcher icons on Fedora ([#348](https://github.com/storytold/anicraft/issues/348)) | Accessibility, platforms | M | the machines; the person | platform |
|
||||
@@ -65,7 +66,7 @@ the changelog.
|
||||
|---|---|---|---|---|---|
|
||||
| P-017 | Selecting as in the reference app: a marquee takes instances, groups and objects it touches ([#522](https://github.com/storytold/anicraft/issues/522)); Hide Edges ([#298](https://github.com/storytold/anicraft/issues/298)); a first-use hint that a fill and its outline are separate, with double-click selecting both ([#484](https://github.com/storytold/anicraft/issues/484), [#485](https://github.com/storytold/anicraft/issues/485), [#343](https://github.com/storytold/anicraft/issues/343)); Match Size and Space in Align | Tools, drawing model | S each | | stage |
|
||||
| P-018 | Lasso, Polygon and Magic Wand tools ([#515](https://github.com/storytold/anicraft/issues/515)) | Tools | M | | stage |
|
||||
| P-019 | Text is typed in its block on the stage, in its real font and alignment ([#303](https://github.com/storytold/anicraft/issues/303)) | Text | L | P-008 | text |
|
||||
| P-019 | Text is typed in its block on the stage, in its real font and alignment ([#303](https://github.com/storytold/anicraft/issues/303)) | Text | L | | text |
|
||||
| P-020 | Modify › Shape: Smooth, Straighten, Advanced Smooth and Optimize ([#510](https://github.com/storytold/anicraft/issues/510)); Distort; oval angles and primitive shapes | Drawing model | M | | geom |
|
||||
| P-021 | Timeline and symbol commands that are missing: Reverse Frames, Distribute to Layers and to Keyframes, convert a tween to frame-by-frame, a symbol to layers and back ([#517](https://github.com/storytold/anicraft/issues/517)), New Symbol (Ctrl+F8), copy and paste layers, comment and anchor labels, a loop range | Timeline, symbols | M (splits into S) | | timeline |
|
||||
| P-022 | A sound's in and out points: trim handles in Edit Envelope, Split Audio ([#502](https://github.com/storytold/anicraft/issues/502)), read from Animate files | Sound | M | | audio |
|
||||
@@ -84,8 +85,8 @@ the changelog.
|
||||
|---|---|---|---|---|---|
|
||||
| P-031 | Scripts: arrays, objects, `switch`, string methods, event bubbling and fields, sound from scripts ([#3](https://github.com/storytold/anicraft/issues/3)); a debugger later; ActionScript 1.0 and 2.0 last ([#293](https://github.com/storytold/anicraft/issues/293)) | Interactivity | L | | player |
|
||||
| P-032 | Strokes: gradient and bitmap strokes, ragged, stipple and hatched styles, scale modes, a hairline style | Drawing model, colour | M | | render |
|
||||
| P-033 | Typography: justified text, superscript and subscript, indents and margins, vertical text, spell checking | Text | M (splits) | P-008 | text |
|
||||
| P-034 | A right-to-left interface, and Hebrew ([#45](https://github.com/storytold/anicraft/issues/45)) | Preferences | M | P-008 | shell |
|
||||
| P-033 | Typography: justified text, superscript and subscript, indents and margins, vertical text, spell checking; a direction setting for a paragraph with alignment to its start, and right-to-left text a script sets in the HTML page (left from P-008, [ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md)) | Text | M (splits) | | text |
|
||||
| P-034 | A right-to-left interface, and Hebrew ([#45](https://github.com/storytold/anicraft/issues/45)) | Preferences | M | | shell |
|
||||
| P-035 | The HTML page and Test Movie, complete: 9-slice, bent bitmaps, stream sounds after a go-to, links that click, masks in hit tests, scaling choices, a preloader; Test Movie full screen and zoom | Publishing, interactivity | M (splits) | | player |
|
||||
| P-036 | Publish formats: an animated SVG in one file (outside PR [#9](https://github.com/storytold/anicraft/issues/9)), SVG sequence and file name patterns in Publish Settings, JPEG, a texture atlas, publish settings read from Animate files, per-sound settings | Publishing | M (splits) | | engine |
|
||||
| P-037 | More formats in: AIFF, FLAC and ADPCM WAV sounds; GIF, BMP, WebP bitmaps; numbered images as frames | Import | S each | craft-libs readers | audio, doc |
|
||||
@@ -140,18 +141,18 @@ As of 2026-11-20 (27 open):
|
||||
|
||||
| PR | What | Id | State | What it still needs, or what happened |
|
||||
|---|---|---|---|---|
|
||||
| [#13](https://github.com/storytold/anicraft/issues/13) | Bound the work of evaluating nested symbols | P-002 | **planned** | Its two review findings are answered. Needs a rebase (it conflicts), its roadmap edit dropped for a changelog entry, and the principal-engineer review. First in line. |
|
||||
| [#39](https://github.com/storytold/anicraft/issues/39) | Text that mixes directions | P-008 | **planned** | Re-reviewed clean; changes were requested earlier, so it needs a fresh review at the rebased head, and the licence of any new crate checked against `standards/licences.md`. Before [#40](https://github.com/storytold/anicraft/issues/40). |
|
||||
| [#40](https://github.com/storytold/anicraft/issues/40) | Letters from a fallback face | P-008 | **planned** | Builds on [#39](https://github.com/storytold/anicraft/issues/39); rebase onto it once [#39](https://github.com/storytold/anicraft/issues/39) is in. |
|
||||
| [#13](https://github.com/storytold/anicraft/issues/13) | Bound the work of evaluating nested symbols | (done) | **superseded by** | The P-002 change ([ADR 0128](adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md)), which took its ideas into the allowance `main` already had: layers, symbol lookups and outline sizes count as work, and a frame that ran out says so. Its commits were not merged: they rewrite what [#497](https://github.com/storytold/anicraft/issues/497) rewrote, and its charge of one unit per library entry would cut honest documents with large libraries. Credited in `AUTHORS.md`. |
|
||||
| [#39](https://github.com/storytold/anicraft/issues/39) | Text that mixes directions | (P-008, done) | **superseded by** | Its commits are merged in the P-008 pull request, which rebuilds it on the styled-text layout ([ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md)): lines found in reading order and never inside a cluster, and its tests, are kept; levels and reordering come from `craft-text`. Nothing in it is left out. |
|
||||
| [#40](https://github.com/storytold/anicraft/issues/40) | Letters from a fallback face | (P-008, done) | **superseded by** | Merged and rebuilt with [#39](https://github.com/storytold/anicraft/issues/39) ([ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md)): its family list, the cluster that moves whole with its marks, invisible characters that are never missing and the note about boxes are kept; installed faces outside the list, which it left for later, are searched too. |
|
||||
| [#222](https://github.com/storytold/anicraft/issues/222) | A click on the playhead makes the frame keys act on every layer | P-009 | **merged, changed** | Merged with its commits and its test. The ruler now leaves no frames selected instead of selecting the playhead's frame on every layer, so F6, F7 and Ctrl+C keep acting on one layer and on artwork ([ADR 0131](adr/0131-layer-selection-the-ruler-and-new-masks.md)). |
|
||||
| [#532](https://github.com/storytold/anicraft/issues/532) | The Movie Explorer uses its pane's height | P-010 | **merged** | With a test that fails without it. |
|
||||
| [#535](https://github.com/storytold/anicraft/issues/535) | The layer count clear of the header buttons | P-009 | **merged, fixed** | Its checks failed on a raw size call the typography guideline test refuses; fixed on top, with a test. |
|
||||
| [#238](https://github.com/storytold/anicraft/issues/238) | Morph a shape's stroke with its fill | P-011 | **planned** | Its first fix is on `main`; the rest handles guided tweens and dashed outlines. Needs the open design question answered with pictures: which fill an outline belongs to when outlines join. |
|
||||
| [#142](https://github.com/storytold/anicraft/issues/142) | `Vec2::length` overflow | P-012 | **planned** | Needs a measured cost: `hypot` is slower than the multiply and `length` is on hot paths. If it shows, scale only inside `normalized`. |
|
||||
| [#233](https://github.com/storytold/anicraft/issues/233) | Keep alpha in `Rgba::to_hex` | P-012 | **planned** | Needs a rebase and an audit of every caller: SVG, HTML and Lottie writers expect six digits and carry alpha themselves. |
|
||||
| [#130](https://github.com/storytold/anicraft/issues/130) | Reject SVG path numbers past `f32` | P-012 | **planned** | Now a test only; ready after a rebase check. |
|
||||
| [#486](https://github.com/storytold/anicraft/issues/486) | Hebrew font, `iw`, right-to-left preparation | P-012, P-034 | **planned** | Most of it came in with [#496](https://github.com/storytold/anicraft/issues/496). What is left (private-use tags are not right-to-left) is small and ready. |
|
||||
| [#500](https://github.com/storytold/anicraft/issues/500) | A test of SVG link sanitising and re-import | P-012 | **planned** | A draft. Ready when its author marks it so. |
|
||||
| [#238](https://github.com/storytold/anicraft/issues/238) | Morph a shape's stroke with its fill | (done) | **superseded by** | Merged with its commits in the P-011 change. The design question is answered with pictures there: a stroke run belongs to the fill whose edge its middle lies on, and an edge two fills share goes with the lower one. On top of it, a guided shape tween now joins the runs even when both keys have as many. |
|
||||
| [#142](https://github.com/storytold/anicraft/issues/142) | `Vec2::length` overflow | (done) | **superseded by** | Merged with its commit in the P-012 change, then narrowed after measuring: `hypot` alone cost 1.9 ns against 0.83 ns a call, so it is taken only where the squares leave `f32` (0.85 ns, the same results in range). |
|
||||
| [#233](https://github.com/storytold/anicraft/issues/233) | Keep alpha in `Rgba::to_hex` | (done) | **superseded by** | Merged with its commit in the P-012 change, as a function of its own: `to_hex` keeps its six digits for the SVG, HTML and Lottie writers (as merged, the four callers that add their own alpha digits would have written ten), and `to_hex_alpha` is the form that reads back. The Eyedropper's result uses it. |
|
||||
| [#130](https://github.com/storytold/anicraft/issues/130) | Reject SVG path numbers past `f32` | (done) | **superseded by** | Merged with its commit in the P-012 change (the test). |
|
||||
| [#486](https://github.com/storytold/anicraft/issues/486) | Hebrew font, `iw`, right-to-left preparation | (done) | **superseded by** | The rest (private-use tags are not right-to-left) is merged with its commits in the P-012 change; the Hebrew face and `iw` came in with [#496](https://github.com/storytold/anicraft/issues/496). P-034 stays open for laying out right to left. |
|
||||
| [#500](https://github.com/storytold/anicraft/issues/500) | A test of SVG link sanitising and re-import | (done) | **superseded by** | Merged with its commits in the P-012 change, without the two lines it only reformatted. It is the one test that linked artwork survives export and re-import. |
|
||||
| [#320](https://github.com/storytold/anicraft/issues/320) | Pen pressure on Linux Wayland | P-014 | **planned** | Needs a rebase, platform code kept in `src/platform.rs` with no `unsafe`, the licences of its X11 crates checked, and a test by hand with a tablet. |
|
||||
| [#336](https://github.com/storytold/anicraft/issues/336) | Raw pressure-sensitive ink | P-028 | **planned** | After P-003, so a long stroke is bounded first. Needs a rebase and a new ADR number (0096 is taken; ask for one to be reserved). |
|
||||
| [#394](https://github.com/storytold/anicraft/issues/394) | Studio theme, canvas turn, Ctrl+Space zoom | P-029, P-046 | **planned, in parts** | Three things in one PR, 75 files. Needs to be split: the view turn and the zoom key each as their own PR (P-029), and the palette as a theme file for [ADR 0117](adr/0117-user-themes-from-a-folder.md) instead of a built-in theme (P-046). |
|
||||
@@ -253,7 +254,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va
|
||||
| Data-driven animation | **Data tables that drive animation, first slice** (ADR 0118, #416, #417, #418): numeric **tables kept in the document** as Library items, imported from **CSV, TSV or JSON** (File › Import › Import Data Table; through craft-csv; named columns, gaps, text-only columns left out and reported, a row per frame or a **key column** for a row per keyed time; 256 tables, 100 000 rows, 1 000 000 cells, files up to 32 MB; hostile input refused or cut to the limits), a **table viewer**, **Import Again** that keeps every binding; **bindings** that let a column drive a symbol instance's **X, Y, Scale X, Scale Y, Rotation, Alpha** or **the frame a graphic shows** over a span of frames, with scale, offset, linear or step interpolation and reversed key ranges, edited live in Properties › Data and evaluated purely in `evaluate` (stage, oracle, GPU stage, Test Movie and every export that draws frames agree); **Bake to Keyframes** (every frame looks as it did); `data.*` commands headless, over the CLI and MCP, and for plug-ins (all but reading a file). Not yet: bindings that follow copy, paste and duplicate; baking inside a motion tween and a Lottie export warning for live bindings; editing cells in the viewer, adding and renaming columns; text columns for captions; binding skew, tint, filter values, shapes, text and group members; expressions; audio amplitude into a table. |
|
||||
| Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. |
|
||||
| Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. |
|
||||
| Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. |
|
||||
| Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. **Documents too large to draw** ([ADR 0128](adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md)): a frame, a bounds query and a Test Movie step each have an allowance of work that no nesting of symbols gets past; a frame cut short says so in the status bar, in the results of the commands that write frames, in `info` and in the MCP picture's caption. Not yet: the same note from the Lottie and HTML exporters and exporter plug-ins, a notice inside the Test Movie window when its picture is cut short, how much was left out. |
|
||||
| Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Follow system, Dark (Graphite), Light or High contrast; ADR 0077), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). **CI on macOS and Windows** (ADR 0067): every code PR builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners besides Linux. Not yet: native macOS NSMenu, Linux arm64 and Windows ARM64 test legs on PRs, a GPU runner. Verified by hand on Windows only so far. **Robust start-up** (#207): the window opens through a list of ways (the one chosen in Preferences › Stage › Window graphics or `--renderer gl|wgpu|vulkan|dx12|metal`, then wgpu automatic, DirectX 12 on the low-power GPU on Windows, OpenGL), falling through on an error or a panic; a start that died inside a driver tries that way last for the next five starts, then 25 and 100 if it dies again (#335, ADR 0105); stage work on the window's device is submitted only inside a frame, which removes the `Surface::configure` "Failed to wait for GPU to come idle" error behind 0.2.1 closing at start-up and on resizing (#264, #309; ADR 0105); a start-up log (`Logs/anicraft.log` in the settings folder, the previous run's kept) records each way, the adapter and driver, panics and slow starts; a system message names it when nothing works. Not yet: verified on a hybrid-GPU laptop, the log from the Help menu, restarting by itself when a driver hangs at start-up. |
|
||||
| Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. **Opening documents on macOS** (ADR 0062): a double-click in Finder, a drop on the Dock icon or Open With opens the document, at launch or while running (the open-documents Apple Event through `platform.rs`, by `fmv-macos-events`, so no `unsafe` of ours), through the unsaved-changes guard; the Dock's Quit asks to save too; Windows and Linux command-line hand-over covered by a test. **Portable mode and AppImage desktop integration** (ADR 0094): an `anicraft-portable` marker (shipped in the Windows zip and the Linux tar.gz; also honoured beside `AniCraft.app` and an `.AppImage`) keeps preferences, autosave, logs, plug-ins, templates, recent files, brushes, filter presets and workspaces in `data/` beside the app, through one switch in `platform.rs`, falling back visibly when that folder can't be written; Preferences › About shows the mode and every folder; on first start from an AppImage a non-modal card offers once to add AniCraft to the applications menu (`desktop.integrate/remove/status`: desktop entry with a quoted `Exec`, MIME types and icons under `$XDG_DATA_HOME` only, idempotent, removable from About, following a moved or updated AppImage); a store-readiness job checks the Flatpak manifests, AppStream (`appstreamcli validate`), the desktop entry and any winget/MSIX manifests. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, store submissions and winget/MSIX manifests, self-update inside a portable copy, video export inside the Flatpak. |
|
||||
| Documentation | **User guide, first slice** (ADR 0069, `docs/guide/`): eighteen chapters for artists (getting started to troubleshooting, and Coming from Animate), a command reference and a shortcut reference (Windows/Linux and macOS) generated from the registry and checked for freshness by tests, every link, anchor and picture checked, eight screenshots from `scripts/guide-shots.sh`. Help › User Guide opens the book bundled in the app, offline, in the browser; the web build serves it beside the editor; `anicraft-cli guide --out <folder>` writes it. Not yet: translated guides, search, a PDF edition, context help from panels, macOS and Linux screenshots. |
|
||||
|
||||
+25
@@ -376,6 +376,9 @@ pub struct App {
|
||||
/// The tool in hand last frame (picking the Camera tool adds a camera).
|
||||
pub last_tool: Tool,
|
||||
pub status: Option<Status>,
|
||||
/// The frame shown was not all drawn when the stage last looked (ADR 0128): the status bar
|
||||
/// has said so, and says it again only after a frame that was whole.
|
||||
pub left_out_said: bool,
|
||||
pub prompt: Option<Prompt>,
|
||||
/// The Convert to Symbol dialog, and what it chose last (ADR 0053).
|
||||
pub convert: Option<crate::convert_symbol::ConvertDialog>,
|
||||
@@ -474,6 +477,9 @@ pub struct App {
|
||||
/// A filter preset being named in Properties (ADR 0091).
|
||||
pub filter_naming: crate::panels::FilterNaming,
|
||||
pub brush_samples: Vec<(anicraft_engine::geom::Vec2, Option<f32>)>,
|
||||
/// Brush strokes drawn but not yet painted: their outlines are being traced on another
|
||||
/// thread (ADR 0129). Oldest first.
|
||||
pub ink: Vec<crate::ink::Pending>,
|
||||
pub pen_pressure: Option<f32>,
|
||||
/// Whether a pointer event has carried a pen's tilt this session (ADR 0093). Until one has,
|
||||
/// the brushes' Tilt options stay hidden: they would do nothing.
|
||||
@@ -802,6 +808,7 @@ impl App {
|
||||
camera_preview: false,
|
||||
last_tool: Tool::Select,
|
||||
status: None,
|
||||
left_out_said: false,
|
||||
prompt: None,
|
||||
convert: None,
|
||||
layer_props: None,
|
||||
@@ -856,6 +863,7 @@ impl App {
|
||||
brush_lib: crate::brush_panel::BrushLibraryView::default(),
|
||||
filter_naming: Default::default(),
|
||||
brush_samples: Vec::new(),
|
||||
ink: Vec::new(),
|
||||
pen_pressure: None,
|
||||
pen_tilt_seen: false,
|
||||
eraser: crate::erasertool::EraserOptions::default(),
|
||||
@@ -1011,6 +1019,16 @@ impl App {
|
||||
self.status = Some(Status { text: text.into(), error: true, at: 0.0 });
|
||||
}
|
||||
|
||||
/// What a text command had to say about the fonts it used, in the status bar: a font that
|
||||
/// isn't installed, letters drawn from another font, characters no font has (ADR 0012,
|
||||
/// ADR 0130). The block looks right either way, so this is the only place it is said.
|
||||
pub fn text_note(&mut self, result: &Value) {
|
||||
if let Some(note) = result["note"].as_str() {
|
||||
// The engine's English, translated when a catalog has that exact message.
|
||||
self.status_ok(crate::i18n::t_dyn(note).into_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an engine command, reporting failures in the status bar.
|
||||
/// After a move, selected raw shapes float over what they landed on, and merge with it when
|
||||
/// they are deselected, as in Animate (ADR 0122, #487): until then they can be moved on.
|
||||
@@ -1031,6 +1049,9 @@ impl App {
|
||||
}
|
||||
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
|
||||
// Strokes still on their way in are painted first: commands run in the order they
|
||||
// were asked for (ADR 0129).
|
||||
crate::ink::flush(self);
|
||||
let result = self.s.execute(id, ¶ms);
|
||||
if platform::WEB && id.starts_with("file.") {
|
||||
// In a browser, what a save or an export wrote is in memory: hand it to the
|
||||
@@ -3739,6 +3760,7 @@ impl App {
|
||||
}
|
||||
"plugin.run" | "plugin.install" | "plugin.remove" | "plugin.reload" => crate::plugins_ui::status(self, id, v),
|
||||
id if id.starts_with("macro.") => crate::macros_ui::done(self, id, v),
|
||||
id if id.starts_with("text.") => self.text_note(v),
|
||||
"timeline.remove_frame" => {
|
||||
let n = v["removed"].as_u64().unwrap_or(1);
|
||||
self.status_ok(if n == 1 { tr!("Removed frame — {undo} to undo", undo = self.undo_key()).to_string() } else { trn!("Removed {n} frame — {undo} to undo", "Removed {n} frames — {undo} to undo", n, undo = self.undo_key()) });
|
||||
@@ -4801,6 +4823,9 @@ impl App {
|
||||
}
|
||||
}
|
||||
self.handle_screenshot(&ctx);
|
||||
// Brush strokes whose outlines are traced go into the document, before this frame's
|
||||
// input can edit it (ADR 0129).
|
||||
crate::ink::frame(self, &ctx);
|
||||
// An assistant's edits (ADR 0104), before anything draws: they show in this frame.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::remote::poll(self, &ctx);
|
||||
|
||||
+33
-18
@@ -323,7 +323,9 @@ pub fn sample(app: &mut App, p: Vec2, pressure: Option<f32>, xf: Xf, now: f64) {
|
||||
}
|
||||
|
||||
/// Sends the stroke (one command, one undo step). Smoothing and accuracy follow the screen.
|
||||
pub fn commit(app: &mut App, xf: Xf) {
|
||||
/// A long Brush stroke's outline is traced on another thread first, the stroke staying on the
|
||||
/// stage as drawn until it is painted (ADR 0129, `crate::ink`).
|
||||
pub fn commit(app: &mut App, ctx: &egui::Context, xf: Xf) {
|
||||
let samples = std::mem::take(&mut app.brush_samples);
|
||||
if samples.is_empty() {
|
||||
return;
|
||||
@@ -344,12 +346,19 @@ pub fn commit(app: &mut App, xf: Xf) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !crate::ink::defer(app, ctx, &samples, ¶ms, o.mode) {
|
||||
paint(app, params, o.mode);
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints a Brush stroke: `draw.brush` with `params`, and what to say when nothing was painted.
|
||||
pub fn paint(app: &mut App, params: serde_json::Value, mode: PaintMode) {
|
||||
// Paint Selection keeps the selection it paints in, for the next stroke (ADR 0080).
|
||||
let v = if o.mode == PaintMode::Selection { app.run("draw.brush", params) } else { app.draw("draw.brush", params) };
|
||||
let v = if mode == PaintMode::Selection { app.run("draw.brush", params) } else { app.draw("draw.brush", params) };
|
||||
if let Some(v) = v
|
||||
&& v["elements"].as_array().is_some_and(Vec::is_empty)
|
||||
{
|
||||
match o.mode {
|
||||
match mode {
|
||||
PaintMode::Selection => app.status_ok(tr!("Nothing painted: Paint Selection paints only inside the selected fills. Select them with the Selection tool first.")),
|
||||
PaintMode::Inside => app.status_ok(tr!("Nothing painted: Paint Inside paints only inside the fill where the stroke starts.")),
|
||||
_ => app.status_ok(tr!("Nothing to paint behind there: Paint Behind only paints empty areas.")),
|
||||
@@ -394,7 +403,7 @@ const MASK_MAX: usize = 2048;
|
||||
/// The alpha the finished stroke will have: the fill (or the stroke colour) times, when
|
||||
/// pressure drives opacity, the average mapped pressure so far. That average is what the
|
||||
/// command stores for the whole stroke (ADR 0068).
|
||||
fn intended_alpha(o: &BrushOptions, paint_a: f32, samples: &[(Vec2, Option<f32>)]) -> f32 {
|
||||
pub(crate) fn intended_alpha(o: &BrushOptions, paint_a: f32, samples: &[(Vec2, Option<f32>)]) -> f32 {
|
||||
let paint_a = if paint_a.is_finite() { paint_a.clamp(0.0, 1.0) } else { 1.0 };
|
||||
if !o.pressure_opacity || samples.is_empty() {
|
||||
return paint_a;
|
||||
@@ -430,15 +439,7 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
|
||||
let (paint, tip) = if app.tool == Tool::PaintBrush { (app.s.style.stroke, BrushOptions { shape: TipShape::Round, roundness: 100.0, ..*o }) } else { (app.s.style.fill, *o) };
|
||||
if app.drag == Drag::Brush {
|
||||
let alpha = intended_alpha(&tip, paint.a, &app.brush_samples);
|
||||
// Opaque ink stays the convex sweep the Eraser shares. A wash is one coverage image
|
||||
// at the alpha the stroke will keep, so the pen-down ink matches the ink after you
|
||||
// lift (ADR 0102).
|
||||
if (alpha * 255.0).round() >= 255.0 {
|
||||
let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint });
|
||||
draw_sweep(painter, xf, &tip, &app.brush_samples, color);
|
||||
} else {
|
||||
draw_sweep_alpha(painter, xf, &tip, &app.brush_samples, paint, alpha);
|
||||
}
|
||||
draw_ink(painter, xf, &tip, &app.brush_samples, paint, alpha, 0);
|
||||
}
|
||||
if let Some(h) = hover {
|
||||
// The tip's size and shape at the pointer, as Animate shows it.
|
||||
@@ -446,6 +447,19 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's ink as it is drawn: `paint` at `alpha`, the alpha the finished stroke will have.
|
||||
/// Opaque ink is the convex sweep the Eraser shares. A wash is one coverage image at that
|
||||
/// alpha, so the pen-down ink matches the ink after you lift (ADR 0102); `slot` names its
|
||||
/// texture (the stroke in hand is 0, strokes waiting to be painted come after, ADR 0129).
|
||||
pub(crate) fn draw_ink(painter: &egui::Painter, xf: Xf, tip: &BrushOptions, samples: &[(Vec2, Option<f32>)], paint: anicraft_engine::doc::Rgba, alpha: f32, slot: usize) {
|
||||
if (alpha * 255.0).round() >= 255.0 {
|
||||
let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint });
|
||||
draw_sweep(painter, xf, tip, samples, color);
|
||||
} else {
|
||||
draw_sweep_alpha(painter, xf, tip, samples, paint, alpha, slot);
|
||||
}
|
||||
}
|
||||
|
||||
/// The tip swept along `samples` (shared with the Eraser, ADR 0034), filled with `color`.
|
||||
pub fn draw_sweep(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option<f32>)], color: egui::Color32) {
|
||||
if samples.is_empty() {
|
||||
@@ -502,7 +516,7 @@ fn sweep_hulls(xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option<f32>)]) -> Vec
|
||||
|
||||
/// The same sweep as one coverage image, tinted at `alpha`. Overlapping pieces keep the
|
||||
/// greater coverage, so a crossing in one stroke stays one alpha.
|
||||
fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option<f32>)], paint: anicraft_engine::doc::Rgba, alpha: f32) {
|
||||
fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option<f32>)], paint: anicraft_engine::doc::Rgba, alpha: f32, slot: usize) {
|
||||
if alpha <= 0.0 {
|
||||
return;
|
||||
}
|
||||
@@ -540,14 +554,15 @@ fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples:
|
||||
pixels.push(egui::Color32::from_white_alpha(a));
|
||||
}
|
||||
let image = egui::ColorImage::new([w, h], pixels);
|
||||
let tex = sweep_texture(painter.ctx(), image);
|
||||
let tex = sweep_texture(painter.ctx(), image, slot);
|
||||
let tint = to_color32(anicraft_engine::doc::Rgba { a: alpha, ..paint });
|
||||
painter.image(tex.id(), view, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint);
|
||||
}
|
||||
|
||||
/// One reused texture for the live wash, so a stroke does not leak a texture every frame.
|
||||
fn sweep_texture(ctx: &egui::Context, image: egui::ColorImage) -> egui::TextureHandle {
|
||||
let id = egui::Id::new("anicraft.brush.sweep");
|
||||
/// One reused texture for the live wash, so a stroke does not leak a texture every frame (and
|
||||
/// one for each stroke that waits to be painted: a few at most).
|
||||
fn sweep_texture(ctx: &egui::Context, image: egui::ColorImage, slot: usize) -> egui::TextureHandle {
|
||||
let id = if slot == 0 { egui::Id::new("anicraft.brush.sweep") } else { egui::Id::new(("anicraft.brush.sweep", slot)) };
|
||||
let options = egui::TextureOptions::LINEAR;
|
||||
if let Some(mut tex) = ctx.data(|d| d.get_temp::<egui::TextureHandle>(id)) {
|
||||
tex.set(image, options);
|
||||
|
||||
+1
-2
@@ -71,8 +71,7 @@ pub fn apply_set(app: &mut App, edit: &FillEdit, selection: bool) {
|
||||
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
|
||||
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) }
|
||||
c.to_hex_alpha()
|
||||
}
|
||||
|
||||
fn stops_json(stops: &[GradientStop]) -> Value {
|
||||
|
||||
@@ -70,6 +70,9 @@ pub fn is_rtl_code(code: &str) -> bool {
|
||||
let normalized = Languages::normalize_code(code.split(['.', '@']).next().unwrap_or(code));
|
||||
let mut parts = normalized.split('-').filter(|p| !p.is_empty());
|
||||
let Some(base) = parts.next() else { return false };
|
||||
if base == "x" {
|
||||
return false;
|
||||
}
|
||||
let next = parts.find(|p| !(p.len() == 3 && p.chars().all(|c| c.is_ascii_alphabetic())));
|
||||
if let Some(script) = next.filter(|p| p.len() == 4 && p.chars().all(|c| c.is_ascii_alphabetic())) {
|
||||
return matches!(script, "arab" | "hebr" | "thaa" | "syrc" | "nkoo" | "adlm" | "mand" | "samr" | "rohg");
|
||||
|
||||
+1
-1
@@ -382,7 +382,7 @@ fn right_to_left_codes_are_recognised_by_language_and_script() {
|
||||
for rtl in ["he", "he-IL", "he-Hebr-IL", "he-x-test", "iw", "iw_IL", "iw_IL.UTF-8", "ar", "fa-IR", "ku-Arab-IQ", "zh-yue-Arab"] {
|
||||
assert!(is_rtl_code(rtl), "{rtl}");
|
||||
}
|
||||
for ltr in ["en", "ka", "ku-Latn-TR", "sd-Deva-IN", "en-x-arab", "", "-", "pseudo"] {
|
||||
for ltr in ["en", "ka", "ku-Latn-TR", "sd-Deva-IN", "en-x-arab", "x-Arab", "x-Hebr", "", "-", "pseudo"] {
|
||||
assert!(!is_rtl_code(ltr), "{ltr}");
|
||||
}
|
||||
// No right-to-left language is offered, so the interface never is.
|
||||
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
//! Brush strokes whose outline is still being traced (ADR 0129, issue #519).
|
||||
//!
|
||||
//! Tracing a long stroke's outline takes longer than a frame (a tenth of a second and more for
|
||||
//! a stroke drawn over many seconds), and it depends on nothing but the stroke. So when the
|
||||
//! pointer lifts on a long stroke, the trace runs on another thread; the stroke stays on the
|
||||
//! stage as it was drawn, and the next stroke can start at once. When the trace is done the
|
||||
//! stroke is painted by the same `draw.brush` as ever, which takes the traced outline
|
||||
//! (`Session::staged_stroke`) instead of tracing it again.
|
||||
//!
|
||||
//! Strokes are painted in the order they were drawn, and nothing else may come between a stroke
|
||||
//! and its paint: before any other edit (a key, a click anywhere but a brush on the stage, a
|
||||
//! command from an assistant, playback, another document), the waiting strokes are finished
|
||||
//! first, on this thread ([`flush`]). The wait is bounded, since a trace is
|
||||
//! (`geom::brush::MAX_STAMP_WORK`).
|
||||
|
||||
use crate::app::{App, Tool};
|
||||
use crate::brushtool::{self, BrushOptions};
|
||||
use crate::pathtools::Xf;
|
||||
use anicraft_engine::cmds_brush::{PaintMode, PreparedStroke, stroke_request};
|
||||
use anicraft_engine::doc::Rgba;
|
||||
use anicraft_engine::geom::Vec2;
|
||||
use serde_json::Value;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError, channel};
|
||||
|
||||
/// Strokes with fewer samples are traced where they are: they take less than a frame.
|
||||
pub const DEFER_SAMPLES: usize = 400;
|
||||
/// Most strokes waiting at once; one more waits for the first.
|
||||
const MAX_WAITING: usize = 8;
|
||||
|
||||
/// A stroke on its way into the document.
|
||||
pub struct Pending {
|
||||
/// The stroke as it was drawn, for the stage.
|
||||
samples: Vec<(Vec2, Option<f32>)>,
|
||||
tip: BrushOptions,
|
||||
paint: Rgba,
|
||||
alpha: f32,
|
||||
/// What `draw.brush` is run with.
|
||||
params: Value,
|
||||
mode: PaintMode,
|
||||
done: Receiver<PreparedStroke>,
|
||||
}
|
||||
|
||||
/// Takes a Brush stroke whose trace should not hold the window up: `false` when it is short
|
||||
/// enough to paint right away (nothing waiting before it), or can't be handed over (the web
|
||||
/// build has one thread; a stroke the command would refuse is left for it to refuse).
|
||||
pub fn defer(app: &mut App, ctx: &egui::Context, samples: &[(Vec2, Option<f32>)], params: &Value, mode: PaintMode) -> bool {
|
||||
if crate::platform::WEB || (app.ink.is_empty() && samples.len() < DEFER_SAMPLES) {
|
||||
return false;
|
||||
}
|
||||
let Ok(request) = stroke_request(&app.s, params) else { return false };
|
||||
if app.ink.len() >= MAX_WAITING {
|
||||
flush(app);
|
||||
}
|
||||
let (tx, done) = channel();
|
||||
let wake = ctx.clone();
|
||||
let started = std::thread::Builder::new().name("anicraft-ink".into()).spawn(move || {
|
||||
let _ = tx.send(request.prepare());
|
||||
wake.request_repaint();
|
||||
});
|
||||
if started.is_err() {
|
||||
return false;
|
||||
}
|
||||
let tip = *brushtool::options(app);
|
||||
let paint = app.s.style.fill;
|
||||
let alpha = brushtool::intended_alpha(&tip, paint.a, samples);
|
||||
app.ink.push(Pending { samples: samples.to_vec(), tip, paint, alpha, params: params.clone(), mode, done });
|
||||
true
|
||||
}
|
||||
|
||||
/// Paints the waiting strokes whose traces are done, oldest first, stopping at the first that
|
||||
/// is not.
|
||||
pub fn poll(app: &mut App) {
|
||||
if app.ink.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Out of the app while they are painted, so painting one never waits on the others.
|
||||
let mut waiting = std::mem::take(&mut app.ink).into_iter();
|
||||
let mut rest = Vec::new();
|
||||
for p in waiting.by_ref() {
|
||||
match p.done.try_recv() {
|
||||
Ok(traced) => paint(app, &p, Some(traced)),
|
||||
// The thread is gone without an outline: the command traces it.
|
||||
Err(TryRecvError::Disconnected) => paint(app, &p, None),
|
||||
Err(TryRecvError::Empty) => {
|
||||
rest.push(p);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
rest.extend(waiting);
|
||||
app.ink = rest;
|
||||
}
|
||||
|
||||
/// Paints every waiting stroke now, waiting for its trace: before anything else edits.
|
||||
pub fn flush(app: &mut App) {
|
||||
for p in std::mem::take(&mut app.ink) {
|
||||
let traced = p.done.recv().ok();
|
||||
paint(app, &p, traced);
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(app: &mut App, p: &Pending, traced: Option<PreparedStroke>) {
|
||||
app.s.staged_stroke = traced;
|
||||
brushtool::paint(app, p.params.clone(), p.mode);
|
||||
app.s.staged_stroke = None;
|
||||
}
|
||||
|
||||
/// Whether what this frame brings may go ahead of the waiting strokes: looking around and
|
||||
/// painting more. Anything that could edit (a key, text, a click that is not a brush on the
|
||||
/// stage, a dropped file) may not.
|
||||
fn only_painting(app: &App, ctx: &egui::Context) -> bool {
|
||||
if app.playing || app.modal_open() || app.palette.is_some() {
|
||||
return false;
|
||||
}
|
||||
// The presses this frame, unless something else came with them (the context is not asked
|
||||
// about its layers while its input is being read).
|
||||
let presses: Option<Vec<egui::Pos2>> = ctx.input(|i| {
|
||||
if !i.raw.dropped_files.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut presses = Vec::new();
|
||||
for e in &i.raw.events {
|
||||
match e {
|
||||
egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone | egui::Event::Touch { .. } | egui::Event::MouseWheel { .. } | egui::Event::Zoom(_) | egui::Event::WindowFocused(_) => {}
|
||||
egui::Event::PointerButton { pressed: false, .. } => {}
|
||||
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => presses.push(*pos),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(presses)
|
||||
});
|
||||
let Some(presses) = presses else { return false };
|
||||
// A press paints when the Brush is in hand and it lands on the stage itself.
|
||||
let canvas = app.stage_cache.canvas;
|
||||
presses.iter().all(|pos| app.tool == Tool::Brush && canvas.contains(*pos) && ctx.layer_id_at(*pos).is_none_or(|l| l.order == egui::Order::Background))
|
||||
}
|
||||
|
||||
/// At the start of a frame: strokes whose traces are done are painted; if this frame's input
|
||||
/// could edit, all of them are, first.
|
||||
pub fn frame(app: &mut App, ctx: &egui::Context) {
|
||||
if app.ink.is_empty() {
|
||||
return;
|
||||
}
|
||||
if only_painting(app, ctx) {
|
||||
poll(app);
|
||||
} else {
|
||||
flush(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// The waiting strokes on the stage, as they were drawn.
|
||||
pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) {
|
||||
for (slot, p) in app.ink.iter().enumerate() {
|
||||
brushtool::draw_ink(painter, xf, &p.tip, &p.samples, p.paint, p.alpha, slot + 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! A long Brush stroke keeps the window answering (issue #519, P-003).
|
||||
|
||||
use crate::app::{App, Tool};
|
||||
use anicraft_engine::geom::Vec2;
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2};
|
||||
use serde_json::json;
|
||||
use std::time::Instant;
|
||||
|
||||
/// The app on a document, a few frames in, with its clock and the worst frame so far.
|
||||
struct Rig {
|
||||
ctx: egui::Context,
|
||||
app: App,
|
||||
t: f64,
|
||||
worst: (f64, String),
|
||||
log: bool,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new(doc: anicraft_engine::doc::Document) -> Rig {
|
||||
let ctx = egui::Context::default();
|
||||
let app = App::with_context(&ctx, anicraft_engine::Session::new(doc), Some(std::path::PathBuf::from("unused.png")));
|
||||
let mut rig = Rig { ctx, app, t: 0.0, worst: (0.0, String::new()), log: false };
|
||||
for _ in 0..3 {
|
||||
rig.frame("start", Vec::new());
|
||||
}
|
||||
rig.worst = (0.0, String::new());
|
||||
rig
|
||||
}
|
||||
|
||||
fn frame(&mut self, what: &str, events: Vec<Event>) -> f64 {
|
||||
self.t += 0.05;
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(self.t), events, ..Default::default() };
|
||||
let t = Instant::now();
|
||||
let mut out = self.ctx.run_ui(input, |ui| self.app.frame(ui));
|
||||
out.textures_delta.clear();
|
||||
let ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
if self.log {
|
||||
println!("{ms:9.1} ms {what}");
|
||||
}
|
||||
if ms > self.worst.0 {
|
||||
self.worst = (ms, what.to_string());
|
||||
}
|
||||
ms
|
||||
}
|
||||
|
||||
/// Where stage point `p` is on screen.
|
||||
fn at(&self, p: Vec2) -> Pos2 {
|
||||
let app = &self.app;
|
||||
let size = vec2(app.s.doc.stage.width as f32, app.s.doc.stage.height as f32);
|
||||
let origin = app.stage_cache.canvas.center() + app.view.pan - size * app.view.zoom * 0.5;
|
||||
origin + vec2(p.x, p.y) * app.view.zoom
|
||||
}
|
||||
|
||||
fn button(pos: Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn click(&mut self, what: &str, p: Vec2) {
|
||||
let sp = self.at(p);
|
||||
self.frame(&format!("{what}: move"), vec![Event::PointerMoved(sp)]);
|
||||
self.frame(&format!("{what}: press"), vec![Rig::button(sp, true)]);
|
||||
self.frame(&format!("{what}: release"), vec![Rig::button(sp, false)]);
|
||||
self.frame(&format!("{what}: after"), Vec::new());
|
||||
}
|
||||
|
||||
fn drag(&mut self, what: &str, from: Vec2, to: Vec2) {
|
||||
let (a, b) = (self.at(from), self.at(to));
|
||||
self.frame(&format!("{what}: move"), vec![Event::PointerMoved(a)]);
|
||||
self.frame(&format!("{what}: press"), vec![Rig::button(a, true)]);
|
||||
for i in 1..=4 {
|
||||
self.frame(&format!("{what}: drag"), vec![Event::PointerMoved(a + (b - a) * (i as f32 / 4.0))]);
|
||||
}
|
||||
self.frame(&format!("{what}: release"), vec![Rig::button(b, false)]);
|
||||
for _ in 0..2 {
|
||||
self.frame(&format!("{what}: after"), Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// A stage point on the ink, and one in a gap inside the drawing's bounds.
|
||||
fn ink_and_gap(&self) -> (Vec2, Vec2) {
|
||||
let b = self.app.s.display_list().items.iter().fold(anicraft_engine::geom::Rect::EMPTY, |r, i| r.union(&i.path.bounds().transformed(&i.transform)));
|
||||
let grid = |hit: bool| {
|
||||
(0..4000)
|
||||
.map(|i| Vec2::new((i * 37 % 1280) as f32, (i * 53 % 720) as f32))
|
||||
.find(|p| b.inflate(-20.0).contains(*p) && (0..9).all(|k| self.app.s.hit_test(*p + Vec2::new((k % 3 - 1) as f32 * 2.0, (k / 3 - 1) as f32 * 2.0), 0.0).is_some() == hit))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
(grid(true), grid(false))
|
||||
}
|
||||
}
|
||||
|
||||
/// A fast scribble across the stage, as stage points with pressure: `n` samples.
|
||||
fn scribble(n: usize) -> Vec<(Vec2, Option<f32>)> {
|
||||
(0..n).map(|i| i as f32 * 0.06).map(|t| (Vec2::new(640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos(), 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin()), Some(0.55 + 0.45 * (t * 0.37).sin()))).collect()
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
/// Draws `samples` with the Brush: a press, the samples, and the release.
|
||||
fn brush(&mut self, samples: Vec<(Vec2, Option<f32>)>) {
|
||||
self.app.tool = Tool::Brush;
|
||||
let (first, last) = (samples.first().map_or(Vec2::ZERO, |s| s.0), samples.last().map_or(Vec2::ZERO, |s| s.0));
|
||||
let a = self.at(first);
|
||||
self.frame("brush: move", vec![Event::PointerMoved(a)]);
|
||||
self.frame("brush: press", vec![Rig::button(a, true)]);
|
||||
self.frame("brush: drag", vec![Event::PointerMoved(a + vec2(20.0, 12.0))]);
|
||||
self.frame("brush: drag", vec![Event::PointerMoved(a + vec2(40.0, 24.0))]);
|
||||
assert_eq!(self.app.drag, crate::app::Drag::Brush, "the press began a stroke");
|
||||
self.app.brush_samples = samples;
|
||||
let b = self.at(last);
|
||||
self.frame("brush: release", vec![Rig::button(b, false)]);
|
||||
}
|
||||
|
||||
/// Frames until no stroke waits (the trace is on another thread), or a long time has passed.
|
||||
fn until_painted(&mut self) {
|
||||
let started = Instant::now();
|
||||
while !self.app.ink.is_empty() && started.elapsed().as_secs() < 120 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
self.frame("waiting", Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
fn shapes(&self) -> usize {
|
||||
self.app.s.visible_elements().len()
|
||||
}
|
||||
}
|
||||
|
||||
fn blank() -> Rig {
|
||||
let mut rig = Rig::new(anicraft_engine::doc::Document::default());
|
||||
rig.app.s.style.object_drawing = true;
|
||||
rig
|
||||
}
|
||||
|
||||
/// ADR 0129: when the pointer lifts on a long stroke, the frame does not wait for its outline.
|
||||
/// The stroke stays on the stage as drawn, and goes into the document, as one undo step, once
|
||||
/// its outline is traced.
|
||||
#[test]
|
||||
fn a_long_stroke_is_painted_after_the_pointer_lifts_without_holding_the_frame() {
|
||||
let mut rig = blank();
|
||||
let undo_before = rig.app.s.history().undo_len();
|
||||
rig.brush(scribble(3000));
|
||||
assert_eq!(rig.app.ink.len(), 1, "the stroke waits for its outline");
|
||||
assert_eq!(rig.app.drag, crate::app::Drag::None);
|
||||
// It is still drawn: the stage paints its sweep, piece by piece.
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(rig.t + 0.01), ..Default::default() };
|
||||
let xf = crate::pathtools::Xf { origin: rig.at(Vec2::ZERO), zoom: rig.app.view.zoom };
|
||||
let mut out = rig.ctx.run_ui(input, |ui| crate::ink::draw(&rig.app, ui.painter(), xf));
|
||||
out.textures_delta.clear();
|
||||
assert!(out.shapes.len() > 100, "{} pieces", out.shapes.len());
|
||||
rig.until_painted();
|
||||
assert_eq!(rig.shapes(), 1, "painted");
|
||||
assert_eq!(rig.app.s.history().undo_len(), undo_before + 1, "one undo step");
|
||||
// A short stroke never waits.
|
||||
rig.brush(scribble(40));
|
||||
assert!(rig.app.ink.is_empty());
|
||||
assert_eq!(rig.shapes(), 2);
|
||||
}
|
||||
|
||||
/// Nothing comes between a stroke and its paint: an edit asked for while it waits finds it in
|
||||
/// the document already, strokes are painted in the order they were drawn, and a key press
|
||||
/// (undo, say) acts on the stroke, not on what was there before it.
|
||||
#[test]
|
||||
fn edits_wait_for_the_strokes_drawn_before_them() {
|
||||
let mut rig = blank();
|
||||
rig.brush(scribble(3000));
|
||||
rig.brush(scribble(60));
|
||||
assert_eq!(rig.app.ink.len(), 2, "a short stroke queues behind a waiting one");
|
||||
// A command: both strokes are in before it runs, the long one first (under the short one).
|
||||
rig.app.run("edit.select_all", json!({}));
|
||||
assert!(rig.app.ink.is_empty());
|
||||
assert_eq!(rig.app.s.selection.len(), 2);
|
||||
let widths: Vec<f32> = rig.app.s.visible_elements().iter().map(|e| rig.app.s.element_bounds(e.id).width()).collect();
|
||||
assert!(widths.first() > widths.last(), "drawn first, painted first (the long one is under the short one): {widths:?}");
|
||||
// A key: the waiting stroke is painted before the key is handled.
|
||||
let mut rig = blank();
|
||||
rig.brush(scribble(3000));
|
||||
assert_eq!(rig.app.ink.len(), 1);
|
||||
rig.frame("a key", vec![Event::Key { key: egui::Key::F13, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
assert!(rig.app.ink.is_empty());
|
||||
assert_eq!(rig.shapes(), 1);
|
||||
// Only a few strokes wait at once: one more paints the oldest first.
|
||||
let mut rig = blank();
|
||||
for _ in 0..10 {
|
||||
rig.brush(scribble(450));
|
||||
assert!(rig.app.ink.len() <= 8, "{} waiting", rig.app.ink.len());
|
||||
}
|
||||
rig.until_painted();
|
||||
assert_eq!(rig.shapes(), 10, "every stroke was painted");
|
||||
// Leaving the document: it takes its strokes with it.
|
||||
let mut rig = blank();
|
||||
rig.brush(scribble(3000));
|
||||
crate::ink::flush(&mut rig.app);
|
||||
assert_eq!(rig.shapes(), 1);
|
||||
}
|
||||
|
||||
/// The reporter's steps and every tool's gesture on the reporter's file
|
||||
/// (`ANICRAFT_STROKE_FILE`), each from a fresh window: the worst frame of each.
|
||||
#[test]
|
||||
#[ignore = "a measurement, not a check"]
|
||||
fn long_stroke_frame_cost() {
|
||||
let Ok(file) = std::env::var("ANICRAFT_STROKE_FILE") else { return };
|
||||
let doc = anicraft_engine::format::load(std::path::Path::new(&file)).expect("the file loads");
|
||||
let log = std::env::var("ANICRAFT_STROKE_LOG").is_ok();
|
||||
type Scenario = (&'static str, fn(&mut Rig, Vec2, Vec2));
|
||||
let scenarios: [Scenario; 12] = [
|
||||
("move, then click a gap", |r, ink, gap| {
|
||||
r.app.tool = Tool::Select;
|
||||
r.drag("move", ink, ink + Vec2::new(40.0, 24.0));
|
||||
r.click("deselect", gap + Vec2::new(40.0, 24.0));
|
||||
}),
|
||||
("click a gap", |r, _, gap| {
|
||||
r.app.tool = Tool::Select;
|
||||
r.click("gap", gap);
|
||||
}),
|
||||
("marquee over a part", |r, _, gap| {
|
||||
r.app.tool = Tool::Select;
|
||||
r.drag("marquee", gap, gap + Vec2::new(260.0, 180.0));
|
||||
r.click("deselect", gap);
|
||||
}),
|
||||
("double-click", |r, ink, _| {
|
||||
r.app.tool = Tool::Select;
|
||||
r.click("first", ink);
|
||||
r.click("second", ink);
|
||||
}),
|
||||
("select all, Free Transform", |r, ink, _| {
|
||||
r.app.tool = Tool::Transform;
|
||||
r.app.run("edit.select_all", json!({}));
|
||||
r.frame("selected", Vec::new());
|
||||
r.drag("move", ink, ink + Vec2::new(30.0, 10.0));
|
||||
}),
|
||||
("Subselection click", |r, ink, _| {
|
||||
r.app.tool = Tool::Subselect;
|
||||
r.click("ink", ink);
|
||||
r.frame("shown", Vec::new());
|
||||
}),
|
||||
("Paint Bucket in a gap", |r, _, gap| {
|
||||
r.app.tool = Tool::PaintBucket;
|
||||
r.click("gap", gap);
|
||||
}),
|
||||
("Paint Bucket on the ink", |r, ink, _| {
|
||||
r.app.tool = Tool::PaintBucket;
|
||||
r.click("ink", ink);
|
||||
}),
|
||||
("Eraser across", |r, ink, _| {
|
||||
r.app.tool = Tool::Eraser;
|
||||
r.drag("erase", ink + Vec2::new(-200.0, -80.0), ink + Vec2::new(200.0, 80.0));
|
||||
}),
|
||||
("Brush across", |r, ink, _| {
|
||||
r.app.tool = Tool::Brush;
|
||||
r.drag("paint", ink + Vec2::new(-200.0, 80.0), ink + Vec2::new(200.0, -80.0));
|
||||
}),
|
||||
("Pencil across", |r, ink, _| {
|
||||
r.app.tool = Tool::Pencil;
|
||||
r.drag("draw", ink + Vec2::new(-200.0, 60.0), ink + Vec2::new(200.0, -60.0));
|
||||
}),
|
||||
("Rectangle over", |r, ink, _| {
|
||||
r.app.tool = Tool::Rect;
|
||||
r.drag("draw", ink + Vec2::new(-100.0, -60.0), ink + Vec2::new(100.0, 60.0));
|
||||
r.app.tool = Tool::Select;
|
||||
r.frame("select tool", Vec::new());
|
||||
}),
|
||||
];
|
||||
for (name, run) in scenarios {
|
||||
let mut rig = Rig::new(doc.clone());
|
||||
rig.log = log;
|
||||
let (ink, gap) = rig.ink_and_gap();
|
||||
let t = Instant::now();
|
||||
run(&mut rig, ink, gap);
|
||||
println!("{:9.1} ms worst ({}), {:8.1} ms in all, {} elements <- {name}", rig.worst.0, rig.worst.1, t.elapsed().as_secs_f64() * 1000.0, rig.app.s.visible_elements().len());
|
||||
}
|
||||
}
|
||||
@@ -525,4 +525,7 @@ mod parenting_ui_tests;
|
||||
#[cfg(test)]
|
||||
mod tilt_ui_tests;
|
||||
#[cfg(test)]
|
||||
mod long_stroke_tests;
|
||||
mod ink;
|
||||
#[cfg(test)]
|
||||
mod zoom_tests;
|
||||
@@ -24,6 +24,34 @@ fn app() -> (egui::Context, App) {
|
||||
(ctx, app)
|
||||
}
|
||||
|
||||
/// ADR 0128: a frame too large to draw in full is drawn in part, and the status bar says so
|
||||
/// once, as an error that stays; going to a frame that is whole and back says it again.
|
||||
#[test]
|
||||
fn a_frame_with_artwork_left_out_says_so_in_the_status_bar() {
|
||||
let mut large = sample::doubling(31);
|
||||
// Thousands of empty layers in every symbol: the allowance goes on looking at them, so
|
||||
// the frame is cut short with little to draw.
|
||||
for sym in &mut large.library {
|
||||
let tl = &mut std::sync::Arc::make_mut(sym).timeline;
|
||||
for i in 0..5_000 {
|
||||
tl.layers.push(std::sync::Arc::new(anicraft_engine::doc::Layer::new(anicraft_engine::doc::LayerId(9_000 + i), "empty")));
|
||||
}
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
let mut big = App::with_context(&ctx, Session::new(large), Some(std::path::PathBuf::from("unused.png")));
|
||||
frame(&ctx, &mut big, vec![]);
|
||||
let said = big.status.as_ref().map(|s| (s.text.clone(), s.error));
|
||||
assert!(said.as_ref().is_some_and(|(text, error)| *error && text.contains("left out")), "{said:?}");
|
||||
// Said once: a later message is not written over while the frame stays as it is.
|
||||
big.status_ok("something else");
|
||||
frame(&ctx, &mut big, vec![]);
|
||||
assert_eq!(big.status.as_ref().map(|s| s.text.as_str()), Some("something else"));
|
||||
// An ordinary document says nothing.
|
||||
let (ctx, mut app) = app();
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
assert!(!app.status.as_ref().is_some_and(|s| s.text.contains("left out")));
|
||||
}
|
||||
|
||||
fn press(p: Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
+135
-6
@@ -230,6 +230,21 @@ fn to_v(p: Pos2) -> Vec2 {
|
||||
Vec2::new(p.x, p.y)
|
||||
}
|
||||
|
||||
/// Says in the status bar, once each time it starts, that the frame shown is not all there: its
|
||||
/// artwork took more than a frame's allowance of work, so the rest was left out (ADR 0128). A
|
||||
/// picture with parts missing and nothing said would read as lost work. Not asked while
|
||||
/// playing, where it would cost an evaluation every frame; the frame playback stops on is.
|
||||
fn note_left_out(app: &mut App) {
|
||||
if app.playing {
|
||||
return;
|
||||
}
|
||||
let cut = app.s.display_list().left_out;
|
||||
if cut && !app.left_out_said {
|
||||
app.status_err(tr!("Some artwork on this frame is left out: it holds more than AniCraft draws at once. Nothing is lost. Look for symbols nested many times over."));
|
||||
}
|
||||
app.left_out_said = cut;
|
||||
}
|
||||
|
||||
pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
// View › Rulers along the top and the left (ADR 0076); the stage view in what is left.
|
||||
let (canvas, bars) = crate::rulers::layout(app, ui.max_rect());
|
||||
@@ -237,6 +252,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
crate::camera_tool::on_tool_change(app);
|
||||
crate::shape_envelope::settle(app);
|
||||
crate::camera_tool::tick(app, ui.ctx(), now);
|
||||
note_left_out(app);
|
||||
let canvas_was = std::mem::replace(&mut app.stage_cache.canvas, canvas);
|
||||
let laid_out = std::mem::replace(&mut app.stage_cache.laid_out, true);
|
||||
// While a colour picker popup is open the stage is its eyedropper (ADR 0109): a click
|
||||
@@ -765,7 +781,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Drag::BindMarquee { start, cur } => crate::bind_tool::drag_end(app, start, cur, shift, command),
|
||||
Drag::BindPaint { .. } => crate::bind_tool::paint_end(app),
|
||||
Drag::Pencil => crate::pathtools::commit_pencil(app, xf),
|
||||
Drag::Brush => crate::brushtool::commit(app, xf),
|
||||
Drag::Brush => crate::brushtool::commit(app, ui.ctx(), xf),
|
||||
Drag::Eraser => crate::erasertool::commit(app, xf),
|
||||
// Raw shapes merge where they landed, in the drag's step (ADR 0051).
|
||||
Drag::MultiMove { .. } | Drag::MultiTransform { .. } => crate::onion::drag_end(app),
|
||||
@@ -820,7 +836,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Tool::Brush if !panning => {
|
||||
// A click paints a dab.
|
||||
crate::brushtool::start(app, to_v(sp), pressure, now);
|
||||
crate::brushtool::commit(app, xf);
|
||||
crate::brushtool::commit(app, ui.ctx(), xf);
|
||||
}
|
||||
Tool::Eraser if !panning => {
|
||||
if app.eraser.faucet {
|
||||
@@ -1383,6 +1399,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
crate::widthtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p)));
|
||||
crate::gradient_tool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning));
|
||||
crate::shape_envelope::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning));
|
||||
// Strokes on their way into the document (ADR 0129), under the one in hand.
|
||||
crate::ink::draw(app, &painter, xf);
|
||||
crate::brushtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused));
|
||||
crate::erasertool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused));
|
||||
// After this frame's edits, so a drag on the path shows where it is now.
|
||||
@@ -2621,16 +2639,33 @@ fn exclude_overlying_artwork(fills: &mut Vec<Rect>, above: &[anicraft_engine::do
|
||||
|
||||
/// Remove areas covered by `occluders` from a collection of rectangles.
|
||||
/// Each overlapping rectangle may produce up to four smaller rectangles.
|
||||
///
|
||||
/// Both lists are rows of runs, thousands of each for a long brush stroke, so a span is only
|
||||
/// compared with the occluders in its own rows: they are looked up by their top edge. Comparing
|
||||
/// every span with every occluder took seconds a frame on such a stroke (#519).
|
||||
fn subtract_spans(spans: &mut Vec<Rect>, occluders: &[Rect]) {
|
||||
let mut remaining = Vec::new();
|
||||
let mut pieces = Vec::new();
|
||||
let mut next = Vec::new();
|
||||
// The occluders by top edge (their order among equals kept), and the tallest of them: one
|
||||
// that reaches down into a span starts less than that above the span's top.
|
||||
let mut by_top: Vec<usize> = (0..occluders.len()).collect();
|
||||
let top_of = |i: usize| occluders.get(i).map_or(f32::INFINITY, |o| o.top());
|
||||
by_top.sort_by(|&a, &b| top_of(a).total_cmp(&top_of(b)));
|
||||
let tallest = occluders.iter().fold(0.0f32, |h, o| h.max(o.height()));
|
||||
let mut rows: Vec<usize> = Vec::new();
|
||||
|
||||
for span in spans.drain(..) {
|
||||
pieces.clear();
|
||||
pieces.push(span);
|
||||
let from = by_top.partition_point(|&i| top_of(i) <= span.top() - tallest);
|
||||
let to = by_top.partition_point(|&i| top_of(i) < span.bottom());
|
||||
rows.clear();
|
||||
rows.extend(by_top.get(from..to).unwrap_or(&[]));
|
||||
// In the order they were given, so the pieces come out as they always did.
|
||||
rows.sort_unstable();
|
||||
|
||||
for &occluder in occluders {
|
||||
for &occluder in rows.iter().filter_map(|&i| occluders.get(i)) {
|
||||
// Skip occluders that cannot touch the original span.
|
||||
let overlap = span.intersect(occluder);
|
||||
if overlap.width() <= 0.0 || overlap.height() <= 0.0 {
|
||||
@@ -2774,6 +2809,34 @@ mod pattern_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// #519: occluders are looked up by row instead of each being tried against every span.
|
||||
/// What is left is the same as trying them all: every point of a span is kept exactly when
|
||||
/// no occluder covers it, whatever the occluders' heights and order.
|
||||
#[test]
|
||||
fn spans_lose_exactly_what_the_occluders_in_their_rows_cover() {
|
||||
// A fixed scatter: rows of runs, and occluders one row to many rows tall, unsorted.
|
||||
let n = |i: u32, k: u32, m: u32| (i.wrapping_mul(2_654_435_761).wrapping_add(k.wrapping_mul(40_503)) >> 7) % m;
|
||||
let spans: Vec<Rect> = (0..300).map(|i| Rect::from_min_size(pos2(n(i, 1, 180) as f32, (n(i, 2, 50) * 4) as f32), vec2(4.0 + n(i, 3, 40) as f32, 4.0))).collect();
|
||||
let occluders: Vec<Rect> = (0..400).map(|i| Rect::from_min_size(pos2(n(i, 4, 190) as f32 + 0.5, n(i, 5, 200) as f32 + 0.25), vec2(1.0 + n(i, 6, 25) as f32, if i % 7 == 0 { 30.0 } else { 1.0 }))).collect();
|
||||
let mut left = spans.clone();
|
||||
subtract_spans(&mut left, &occluders);
|
||||
let inside = |rects: &[Rect], p: Pos2| rects.iter().any(|r| r.contains(p));
|
||||
let mut kept = 0;
|
||||
for y in 0..420 {
|
||||
for x in 0..460 {
|
||||
let p = pos2(x as f32 * 0.5 + 0.13, y as f32 * 0.5 + 0.11);
|
||||
let want = inside(&spans, p) && !inside(&occluders, p);
|
||||
assert_eq!(inside(&left, p), want, "at {p:?}");
|
||||
kept += usize::from(want);
|
||||
}
|
||||
}
|
||||
assert!(kept > 1000, "the scatter leaves something to compare: {kept}");
|
||||
// Nothing to take away leaves the spans as they were.
|
||||
let mut same = spans.clone();
|
||||
subtract_spans(&mut same, &[]);
|
||||
assert_eq!(same, spans);
|
||||
}
|
||||
|
||||
/// A thin opaque foreground shape must hide the selection
|
||||
/// backing of artwork behind it, even between stipple rows.
|
||||
#[test]
|
||||
@@ -4622,15 +4685,17 @@ pub fn commit_text(app: &mut App) {
|
||||
let mut p = te.edit_params();
|
||||
p["x"] = json!(te.at.x);
|
||||
p["y"] = json!(te.at.y);
|
||||
app.run("text.create", p);
|
||||
if let Some(made) = app.run("text.create", p) {
|
||||
app.text_note(&made);
|
||||
}
|
||||
}
|
||||
Some(_) if te.text == te.original => {}
|
||||
Some(id) => {
|
||||
app.run("element.select", json!({"ids": [id.0]}));
|
||||
if te.text.trim().is_empty() {
|
||||
app.run("edit.delete", json!({}));
|
||||
} else {
|
||||
app.run("text.edit", te.edit_params());
|
||||
} else if let Some(edited) = app.run("text.edit", te.edit_params()) {
|
||||
app.text_note(&edited);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5351,6 +5416,70 @@ mod pointer_tests {
|
||||
assert_eq!((icon, arrowheads), (CursorIcon::Move, 0), "inside the box: move");
|
||||
}
|
||||
|
||||
/// #117: a symbol instance that is skewed still answers Free Transform on the stage. Its
|
||||
/// box is the slanted one its artwork has, the handles are on that box's corners, and a
|
||||
/// drag from a corner scales it, one from just outside a corner turns it, and one on an
|
||||
/// edge skews it further: each changes the instance, and each is one undo step.
|
||||
#[test]
|
||||
fn free_transform_handles_work_on_a_skewed_symbol() {
|
||||
let (mut app, ctx, at) = scene();
|
||||
app.run("edit.select_all", json!({}));
|
||||
app.run("edit.delete", json!({}));
|
||||
app.run("draw.rect", json!({"x": 300, "y": 200, "w": 200, "h": 100, "fill": "#3366ff", "stroke": null, "object": true}));
|
||||
app.run("modify.convert_to_symbol", json!({"name": "Slanted"}));
|
||||
// Slant it: the top slides right of the bottom.
|
||||
app.run("modify.transform", json!({"a": 1, "b": 0, "c": -0.6, "d": 1, "e": 150, "f": 0}));
|
||||
app.tool = Tool::Transform;
|
||||
let mut t = 2.0;
|
||||
let mut frame = |app: &mut App, events: Vec<Event>| {
|
||||
t += 0.05;
|
||||
run_frame(&ctx, app, t, events);
|
||||
};
|
||||
frame(&mut app, Vec::new());
|
||||
let instance = |app: &App| app.s.selected_elements().first().map(|(_, e)| e.transform).expect("the instance is selected");
|
||||
let box_of = |app: &App| crate::xform::frame(app).expect("a selection has a box");
|
||||
let slanted = box_of(&app);
|
||||
let [tl, tr, br, bl] = slanted.corners();
|
||||
assert!((tl.x - bl.x).abs() > 30.0 && (tl.y - tr.y).abs() < 1.0, "the box slants with the instance: {tl:?} {tr:?} {br:?} {bl:?}");
|
||||
let mut drag = |app: &mut App, from: Vec2, to: Vec2| {
|
||||
let (a, b) = (at(from.x, from.y), at(to.x, to.y));
|
||||
frame(app, vec![Event::PointerMoved(a)]);
|
||||
frame(app, vec![button(a, true)]);
|
||||
for i in 1..=5 {
|
||||
frame(app, vec![Event::PointerMoved(a + (b - a) * (i as f32 / 5.0))]);
|
||||
}
|
||||
frame(app, vec![button(b, false)]);
|
||||
frame(app, Vec::new());
|
||||
};
|
||||
let steps = |app: &App| app.s.history().undo_len();
|
||||
// The bottom right corner, pulled away from the box: larger, and still as slanted.
|
||||
let (before, undo) = (instance(&app).decompose(), steps(&app));
|
||||
let out = (br - tl).normalized() * 60.0;
|
||||
drag(&mut app, br, br + out);
|
||||
let after = instance(&app).decompose();
|
||||
assert!(after.sx > before.sx * 1.1 && after.sy > before.sy * 1.1, "scaled from the corner handle: {before:?} to {after:?}");
|
||||
assert_eq!(steps(&app), undo + 1, "one undo step");
|
||||
let now = box_of(&app);
|
||||
assert!(now.corners()[0].distance(tl) < 1.0, "the opposite corner stays where it was");
|
||||
// Just outside the top right corner: a turn.
|
||||
let (before, undo) = (instance(&app).decompose(), steps(&app));
|
||||
let [_, tr, _, _] = now.corners();
|
||||
let outside = tr + (tr - now.handle(0, 0)).normalized() * (14.0 / app.view.zoom);
|
||||
drag(&mut app, outside, outside + Vec2::new(40.0, 120.0));
|
||||
let after = instance(&app).decompose();
|
||||
assert!((after.rotation - before.rotation).abs().to_degrees() > 5.0, "turned from outside the corner: {before:?} to {after:?}");
|
||||
assert_eq!(steps(&app), undo + 1);
|
||||
// The top edge between its handles, slid along itself: more slant, the bottom edge kept.
|
||||
let now = box_of(&app);
|
||||
let (undo, bottom) = (steps(&app), now.handle(0, 1));
|
||||
let on_edge = now.handle(-1, -1).lerp(now.handle(0, -1), 0.5);
|
||||
let along = (now.handle(1, -1) - now.handle(-1, -1)).normalized() * 50.0;
|
||||
drag(&mut app, on_edge, on_edge + along);
|
||||
let skewed = box_of(&app);
|
||||
assert!(skewed.handle(0, -1).distance(now.handle(0, -1)) > 20.0 && skewed.handle(0, 1).distance(bottom) < 1.0, "the top edge slid, the bottom stayed");
|
||||
assert_eq!(steps(&app), undo + 1);
|
||||
}
|
||||
|
||||
/// A double-click: press, release, `gap` seconds, press, release (each its own frame).
|
||||
fn double_click(gap: f64) -> App {
|
||||
let (mut app, ctx, at) = scene();
|
||||
|
||||
@@ -272,6 +272,8 @@ fn busy(app: &App) -> Option<&'static str> {
|
||||
/// Finishes what is in progress on the shown document, before it is put aside or closed: text
|
||||
/// being typed and a pen path are kept, playback stops, an open drag ends its undo step.
|
||||
fn settle(app: &mut App) {
|
||||
// Brush strokes on their way into this document (ADR 0129).
|
||||
crate::ink::flush(app);
|
||||
if app.playing {
|
||||
app.toggle_play();
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ pub(crate) fn safe_to_install(app: &crate::app::App) -> bool {
|
||||
&& app.pen.is_none()
|
||||
&& app.pencil.is_empty()
|
||||
&& app.brush_samples.is_empty()
|
||||
&& app.ink.is_empty()
|
||||
&& app.raw_touched.is_empty()
|
||||
&& app.drag == crate::app::Drag::None
|
||||
&& app.motion_drag.is_none()
|
||||
|
||||
Reference in new issue
Block a user