mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-28 17:19:31 +01:00
Merge fix/text-bidi (main) into fix/text-fallback
# Conflicts: # docs/roadmap.md
This commit is contained in:
commit
39c5de8047
106 files changed
+11716
-1055
No files matched your search
+5
-3
@@ -78,7 +78,9 @@ OR Apache-2.0) is noted in the table.
|
||||
| Technique | Where | Reference | Notes |
|
||||
|---|---|---|---|
|
||||
| Signed-area coverage accumulation rasterizer | `crates/render/src/raster.rs` | Raph Levien, *font-rs* (2016), <https://github.com/raphlinus/font-rs>, Apache-2.0; also stb_truetype v2 (public domain) | Our implementation follows the published accumulate-and-prefix-sum approach. Credited here; Apache-2.0 includes a patent licence. |
|
||||
| Tile binning with per-row backdrops; per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (<https://github.com/linebender/vello>, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019). |
|
||||
| Tile binning with integer backdrops and left-edge steps ("y-edges"); per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (<https://github.com/linebender/vello>, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019, ADR 0048). |
|
||||
| Tile binning on the GPU: count, prefix sum, scatter, per-tile lists | `crates/gpu/src/gpu_binning.rs`, `crates/gpu/src/bin.wgsl`, `crates/gpu/src/scan.wgsl` | The binning stages described for *Vello* (above) and Patrick Walton's *Pathfinder* (<https://github.com/servo/pathfinder>, Apache-2.0 OR MIT) design posts; the work-efficient scan of G. E. Blelloch, *Prefix Sums and Their Applications* (CMU-CS-90-190, 1990) | Our own arrangement (one invocation per row of a fill's tiles, no atomics) written from the public descriptions; no code or shaders copied (ADR 0048). |
|
||||
| Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). |
|
||||
| Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), <https://cldr.unicode.org>, Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. |
|
||||
| Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). |
|
||||
| Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | |
|
||||
@@ -94,7 +96,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| SVG path data syntax (file format v2) | `crates/geom/src/path.rs` | W3C SVG 1.1 / 2 | W3C Royalty-Free Patent Policy. |
|
||||
| Marching-squares contour tracing (Paint Bucket regions, Brush outlines) | `crates/geom/src/trace.rs` | Lorensen & Cline (1987); public algorithm | Ported from PhotoCraft's mask tracer (same project family and licence) and reviewed. |
|
||||
| Chamfer distance transform (3-4) and flood fill | `crates/engine/src/cmds_paint.rs` | G. Borgefors, *Distance transformations in digital images* (1986); public algorithms | Gap closing, and growing fills under their outlines. |
|
||||
| ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs` | PKWARE APPNOTE.TXT (published ZIP specification); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries; no ZIP64 or encryption. |
|
||||
| ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs`, `crates/xfl/tests/support/fla.rs` | PKWARE APPNOTE.TXT 6.3 (published ZIP specification), the Info-ZIP Unicode path extra field (0x7075, Info-ZIP `proginfo/extrafld.txt`); CRC-32 by slicing by 8 (M. Kounavis and F. Berry, "A Systematic Approach to Building High Performance Software-based CRC Generators", IEEE ISCC 2005); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries, ZIP64, data descriptors, CP437 and UTF-8 names; no encryption (ADR 0054). |
|
||||
| JPEG decoding (imported images) | `crates/engine/src/cmds_file.rs` | `zune-jpeg` (MIT OR Apache-2.0 OR Zlib), already in the dependency tree | Decoded to RGBA, kept as PNG. |
|
||||
| XFL document structure and shape edges | `crates/xfl/src/` | The publicly documented XFL package structure (`DOMDocument.xml`, `LIBRARY/*.xml`, edge strings) | Clean room: no Animate or third-party converter code (ADR 0009). |
|
||||
| Full SVG path data and elliptical-arc to Bézier conversion | `crates/geom/src/svg.rs` | W3C SVG 1.1 §8.3 and Appendix F.6 (implementation notes) | W3C Royalty-Free Patent Policy. |
|
||||
@@ -103,7 +105,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| Exact clipping of filled paths by a convex polygon | `crates/geom/src/clip.rs` | I. E. Sutherland and G. W. Hodgman, "Reentrant Polygon Clipping", CACM 17(1), 1974, extended to Bézier segments (de Casteljau subdivision, roots bracketed by critical points) | Published algorithm; no code taken. |
|
||||
| Shape morphing (cubic normalization, subdivision to equal segment counts, winding and start-point alignment) | `crates/geom/src/morph.rs` | Standard curve-blending techniques from the public computer-graphics literature (de Casteljau subdivision, exact degree elevation) | |
|
||||
| Affine QR decomposition for tweening | `crates/geom/src/affine.rs` | Standard linear algebra | |
|
||||
| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. |
|
||||
| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`; deleting a raw drawing's point joins its edges, `raw::join`, ADR 0045) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs`, `crates/geom/src/raw.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. |
|
||||
| Monotone cubic interpolation of stroke widths (width profiles) | `crates/doc/src/width.rs` | F. N. Fritsch and R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 17(2), 1980 | Published algorithm (harmonic-mean tangents). |
|
||||
| Stroke caps, joins, miter limit and dash patterns (`butt`/`square` caps, miter length and limit, dash arrays restarting per subpath, zero-length round-capped dashes as dots) | `crates/doc/src/stroke_style.rs`, `crates/render/src/stroke.rs`, SVG/HTML/Lottie export, `crates/svg` | W3C SVG 1.1 §11.4 and SVG 2 / CSS Fill and Stroke Module Level 3 (stroke properties); WHATWG HTML canvas line styles; the public Lottie JSON schema (`lc`, `lj`, `ml`, `d`); public descriptions of XFL `SolidStroke`/`DashedStroke`/`DottedStroke` attributes | W3C Royalty-Free Patent Policy; open specifications. |
|
||||
| Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. |
|
||||
|
||||
+109
@@ -2,6 +2,115 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Library and Properties polish** (ADR 0053, M2).
|
||||
* **Drag Library items onto the stage**: symbols and bitmaps land at the pointer on the
|
||||
active layer at the playhead, a sound goes onto that layer's keyframe; drag several at once.
|
||||
One undo step, and it works inside a symbol open for editing. The stage shows where they
|
||||
land and on which layer.
|
||||
* **Place on Stage** (the Library's button, right-click, or **Enter** in the list) puts the
|
||||
selected items at the centre of the view.
|
||||
* **Swap Bitmap** in Properties › Bitmap: a placed bitmap keeps its position and transform
|
||||
and takes the new bitmap's size; a shape painted with a bitmap fill keeps its outline.
|
||||
* **Convert to Symbol** (F8) asks for a name, a type and a **Library folder**, and offers the
|
||||
folder and type you used last.
|
||||
* **"mixed" on every Properties row** when several elements differ: Symbol, Type, Filters,
|
||||
Blending, Looping, First frame, Bitmap and Width now join Scale, Rotation, Alpha, Fill,
|
||||
Stroke and Style. A change sets them all; Type sets the type of every selected instance's
|
||||
symbol.
|
||||
* Headless: `library.place {items: [..], x, y}` (and `{sound}`), `element.swap_bitmap`,
|
||||
`kind` and `folder` on `modify.convert_to_symbol`; `symbol.set_kind` without `symbol` sets
|
||||
every selected instance's symbol.
|
||||
* **`.fla` files open reliably, and hostile ones safely** (ADR 0054, M4).
|
||||
* The `.fla` reader takes the layouts zip tools write: folder entries, Windows `\`
|
||||
separators, CP437 and UTF-8 names (and Info-ZIP Unicode names), data descriptors and
|
||||
ZIP64. Each entry's size and checksum are checked.
|
||||
* Damaged or hostile archives fail with a sentence that names the problem: entries sharing
|
||||
bytes, sizes or checksums that lie, compression bombs (a 1024 : 1 ratio cap, 256 MB per
|
||||
entry, 1 GiB in all), paths with `..`, absolute or drive paths, duplicate names, more than
|
||||
32 nested folders, a central directory cut short. Nothing is ever extracted to disk.
|
||||
* A renamed `.fla` opens (it is recognised by its contents), and a `.fla` saved by Flash CS4
|
||||
or earlier says to open it in Animate and save it again.
|
||||
* Every corpus package, packed nine ways, imports identically to its folder and renders the
|
||||
same golden frames; a fuzz throws 9,664 hostile archives at the reader. A 54.6 MB `.fla`
|
||||
imports in 311–328 ms (checksums by slicing by 8: reading every entry 53 ms, was 130 ms).
|
||||
|
||||
* **Edit Multiple Frames, complete; onion skin inside symbols** (ADR 0051, M1).
|
||||
* With Edit Multiple Frames on, **Cut, Copy, Paste, Paste in Place and Clear** act on the
|
||||
artwork selected on every keyframe between the markers. Paste in Place puts artwork copied
|
||||
from several keyframes back keyframe by keyframe, and artwork copied on one frame onto every
|
||||
keyframe; Paste puts it on the current frame.
|
||||
* **Free Transform** shows one box around the selection on every keyframe and scales, rotates
|
||||
and moves it all about one pivot, one undo step per drag. **Align** (To Stage too),
|
||||
**Rotate 90°** and **Flip** work across keyframes, and so do the arrow keys.
|
||||
* Merge-drawing shapes moved, transformed or pasted there **merge again** on their own
|
||||
keyframe, so drawings stay connected.
|
||||
* **Onion skin and Edit Multiple Frames work inside a symbol** edited in place, on the
|
||||
symbol's own timeline.
|
||||
* Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`,
|
||||
`frames.paste`, `frames.merge`.
|
||||
|
||||
* **Library management** (ADR 0050, M2).
|
||||
* **Folders**: New Folder (the folder icon under the list, or right-click), nested as deep as
|
||||
you like (32 levels). Drag items and folders onto a folder to move them in, onto an item to
|
||||
join its folder, or below the list for the top level; right-click › Move to does the same.
|
||||
Deleting a folder that holds items asks first, and its items go with it.
|
||||
* **Rename in place** with F2 or a double-click on the name; Enter keeps it, Esc cancels.
|
||||
Names are unique within a folder (case aside), as in Animate. Convert to Symbol picks the next
|
||||
free “Symbol n”.
|
||||
* **Duplicate Symbol** (right-click): “Ball copy” in the same folder, ready to rename.
|
||||
* **Swap Symbol** in Properties › Symbol: pick another symbol for the selected instances.
|
||||
Position, colour effect, blending, filters, looping and instance name stay.
|
||||
* A **use count** for every item, **Select Unused Items** and **Delete Unused Items…** (in
|
||||
More). Unused means nothing in any scene reaches it, so one pass clears a whole unused
|
||||
branch; symbols with a linkage class count as used. Deleting an item the movie uses asks,
|
||||
and its instances go with it.
|
||||
* **Sort** by name, type, use count or date added, ascending or descending, and **search**
|
||||
by name; folders that hold a match open.
|
||||
* A **preview** of the current item (a symbol's first frame, the bitmap, or a sound's
|
||||
waveform with a play button) and its **properties**: a symbol's type and linkage class, a
|
||||
bitmap's **Allow Smoothing**. Smoothing off keeps hard pixel edges on the stage, in
|
||||
renders, in SVG and in the HTML page.
|
||||
* Animate files keep their library folders and Allow Smoothing.
|
||||
* Headless: `library.items`, `library.new_folder`, `library.rename`, `library.move`,
|
||||
`library.duplicate`, `library.delete`, `library.unused`, `library.delete_unused`,
|
||||
`library.set_smoothing`, `element.swap_symbol`.
|
||||
* **The GPU stage sorts heavy frames into tiles on the graphics card, and outlines are cheap**
|
||||
(ADR 0048, M3).
|
||||
* Frames with many shapes are binned on the GPU (count, prefix sum, scatter and tile-list
|
||||
compute passes) instead of on the CPU: the CPU only lays out the shapes' points, and every
|
||||
buffer is sized up front, so nothing is read back. On Vulkan, a 10,000-shape 4K frame
|
||||
drawn as one texture takes about 5 ms instead of 22, a 50,000-shape one about 23 ms
|
||||
instead of 122, and the 50,000-shape 4K stage about 37 ms instead of 75. Frames with few
|
||||
shapes, shapes inside masks or faded symbols, and Direct3D 12 (where the passes cost more
|
||||
per stage tile) are still binned on the CPU, which stays the reference
|
||||
(`ANICRAFT_GPU_BINNING=cpu|gpu|auto` to compare).
|
||||
* **Outline mode** (an outlined layer, and onion skin's Outlines) draws true one-pixel
|
||||
hairlines, one edge per segment where the old half-pixel strokes had four and a disc at
|
||||
every bend, in the CPU renderer and on the GPU alike. On a 2,000-shape scene with ±5 onion
|
||||
frames, outlines are now as fast as tinted onion frames: 10 ms on the GPU stage at 1080p
|
||||
(was 73) and 17 ms on the CPU stage (was 34–39). Lines look the same, with smoother joins.
|
||||
* Parity with the CPU renderer is unchanged (at most 1/255 on every test scene), and a test
|
||||
checks that the GPU's tile lists are the CPU's, entry by entry and pixel by pixel.
|
||||
* **Raw points, snapping while drawing, and symbols edited in place** (ADR 0045, issue #42, M1).
|
||||
* **Add a point** on a merged drawing's line or fill edge with the Pen's Alt-click or a
|
||||
Subselection double-click: every shape on that edge gets it, and the curve keeps its shape.
|
||||
* **Delete points** with Delete (or the right-click menu): the shapes that share each point are
|
||||
joined across it, so a fill and its outline stay together; deleting a line's last points
|
||||
removes it. A point where three or more lines meet is kept, and the status bar says so.
|
||||
* **Make Smooth / Make Corner** on raw points. Dragging a handle of a smooth point keeps the
|
||||
other handle in line (on drawing objects too); **Alt** moves it alone.
|
||||
* The **Line, Rectangle, Oval, PolyStar and Pen** tools snap their points to points, lines and
|
||||
fill edges within 10 screen pixels, with a ring where they will snap. **Snap to Objects** is
|
||||
now Ctrl+Shift+/, as in Animate.
|
||||
* **Double-click a symbol instance** (or press Ctrl+E, or double-click the symbol in the
|
||||
Library) to edit it in place: the rest of the stage dims, the timeline shows the symbol's
|
||||
layers, and merge drawing, the Selection and Subselection tools and every other tool work
|
||||
inside it as on the stage. The edit bar shows `Scene 1 › Symbol`; click the scene, press
|
||||
Ctrl+E or double-click empty stage to go back. Undo returns to the symbol where a change was
|
||||
made. Rotated instances open upright.
|
||||
* Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth`
|
||||
on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`; `doc.info` lists
|
||||
the open symbols.
|
||||
* **Motion path points pinned to frames** (ADR 0049, M2). As in Animate, a motion tween's
|
||||
position keyframes are now points on its path: move the object at a frame and the path gets a
|
||||
point there that the object passes exactly on that frame, whatever else you do to the path.
|
||||
|
||||
Generated
+1
@@ -283,6 +283,7 @@ dependencies = [
|
||||
"anicraft-text",
|
||||
"anicraft-xfl",
|
||||
"gif",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png 0.17.16",
|
||||
"rayon",
|
||||
"serde",
|
||||
|
||||
@@ -43,13 +43,25 @@ pub struct Bitmap {
|
||||
/// The image as PNG.
|
||||
#[serde(with = "base64_bytes")]
|
||||
pub png: Arc<Vec<u8>>,
|
||||
/// Allow Smoothing (ADR 0050): scaled or turned, the image is filtered between its pixels;
|
||||
/// off, each pixel stays a hard-edged square (pixel art). On unless a file says otherwise.
|
||||
#[serde(default = "yes", skip_serializing_if = "is_yes")]
|
||||
pub smoothing: bool,
|
||||
#[serde(skip)]
|
||||
decoded: Arc<OnceLock<Option<Arc<Pixels>>>>,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn is_yes(b: &bool) -> bool {
|
||||
*b
|
||||
}
|
||||
|
||||
impl PartialEq for Bitmap {
|
||||
fn eq(&self, o: &Bitmap) -> bool {
|
||||
self.id == o.id && self.name == o.name && self.width == o.width && self.height == o.height && (Arc::ptr_eq(&self.png, &o.png) || self.png == o.png)
|
||||
self.id == o.id && self.name == o.name && self.width == o.width && self.height == o.height && self.smoothing == o.smoothing && (Arc::ptr_eq(&self.png, &o.png) || self.png == o.png)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +72,7 @@ impl Bitmap {
|
||||
let (width, height) = (px.width, px.height);
|
||||
let decoded = OnceLock::new();
|
||||
let _ = decoded.set(Some(Arc::new(px)));
|
||||
Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), decoded: Arc::new(decoded) })
|
||||
Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), smoothing: true, decoded: Arc::new(decoded) })
|
||||
}
|
||||
|
||||
/// A bitmap from PNG or JPEG data (told apart by their signatures; JPEGs become PNG).
|
||||
|
||||
@@ -37,6 +37,9 @@ pub struct DisplayItem {
|
||||
pub group: Option<u32>,
|
||||
/// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied).
|
||||
pub image: Option<Arc<crate::Pixels>>,
|
||||
/// Whether `image` is filtered between its pixels (the bitmap's Allow Smoothing, ADR 0050);
|
||||
/// off, each pixel is a hard-edged square.
|
||||
pub smooth: bool,
|
||||
}
|
||||
|
||||
/// Back-to-front list of shapes.
|
||||
@@ -127,6 +130,25 @@ pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList {
|
||||
out
|
||||
}
|
||||
|
||||
/// A symbol's timeline at its own `frame`, in the symbol's space, as the stage edits it while the
|
||||
/// symbol is open for editing (ADR 0045): what picking and bounds use then. Its layers are the
|
||||
/// top-level ones, as a scene's are in [`evaluate_scene`].
|
||||
pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY), &mut out, None);
|
||||
out
|
||||
}
|
||||
|
||||
/// [`evaluate_timeline`] placed by `xf` (symbol space to stage space): what an instance of the
|
||||
/// timeline at `xf` shows, but with the timeline's own layers as the top-level ones, so each item
|
||||
/// still says which of them it is on. The stage draws a symbol open in place this way when onion
|
||||
/// skin or Edit Multiple Frames composes its frames (ADR 0051).
|
||||
pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affine) -> DisplayList {
|
||||
let mut out = DisplayList::default();
|
||||
eval_timeline(doc, tl, frame, &Ctx::top(xf), &mut out, None);
|
||||
out
|
||||
}
|
||||
|
||||
/// Scene `scene` at its own `frame` as the movie shows it: through the scene's camera, each
|
||||
/// layer shifted by its depth, the camera's tint over everything (ADR 0027). Without a camera
|
||||
/// this is [`evaluate_scene`].
|
||||
@@ -431,6 +453,10 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
|
||||
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels),
|
||||
_ => None,
|
||||
},
|
||||
smooth: match &s.fill {
|
||||
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing),
|
||||
_ => true,
|
||||
},
|
||||
}),
|
||||
ElementKind::Text(t) => out.items.push(DisplayItem {
|
||||
path: t.outline.clone(),
|
||||
@@ -447,6 +473,7 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
|
||||
guide,
|
||||
group: cx.group,
|
||||
image: None,
|
||||
smooth: true,
|
||||
}),
|
||||
ElementKind::Camera => {}
|
||||
ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => {
|
||||
|
||||
+16
-4
@@ -14,6 +14,7 @@ mod filter;
|
||||
mod easing;
|
||||
mod eval;
|
||||
mod hints;
|
||||
pub mod library;
|
||||
pub mod motion;
|
||||
pub mod path_table;
|
||||
pub mod width;
|
||||
@@ -26,13 +27,14 @@ pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST
|
||||
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png};
|
||||
pub use easing::Easing;
|
||||
pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre};
|
||||
pub use library::{FolderId, LibraryEntry, LibraryFolder, LibraryItem, LibraryTree, NameError};
|
||||
pub use motion::{MotionTween, OnPath, Pin, PinError, Property, PropertyKey, Props, Track, motion_path};
|
||||
pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync};
|
||||
pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile};
|
||||
pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle};
|
||||
pub use camera::Camera;
|
||||
pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose};
|
||||
pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, guide_walk, instance_start};
|
||||
pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start};
|
||||
pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript};
|
||||
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
|
||||
@@ -1095,6 +1097,9 @@ pub struct Document {
|
||||
/// Sounds in the library, placed on keyframes through [`FrameSound`].
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub sounds: Vec<Arc<Sound>>,
|
||||
/// The Library's folders and which folder each item is in (ADR 0050).
|
||||
#[serde(default, skip_serializing_if = "library_tree_is_empty")]
|
||||
pub library_tree: Arc<LibraryTree>,
|
||||
/// The class scripts run the main timeline as (Animate's "document class"), kept as text
|
||||
/// (ADR 0013 tier 1); empty when there is none.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
@@ -1119,6 +1124,8 @@ struct DocumentFile {
|
||||
#[serde(default)]
|
||||
sounds: Vec<Arc<Sound>>,
|
||||
#[serde(default)]
|
||||
library_tree: Arc<LibraryTree>,
|
||||
#[serde(default)]
|
||||
document_class: String,
|
||||
#[serde(default = "first_id")]
|
||||
next_id: u64,
|
||||
@@ -1130,7 +1137,7 @@ impl From<DocumentFile> for Document {
|
||||
if let Some(tl) = f.timeline {
|
||||
scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl }));
|
||||
}
|
||||
Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, document_class: f.document_class, next_id: f.next_id }
|
||||
Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, next_id: f.next_id }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1138,18 +1145,22 @@ fn first_id() -> u64 {
|
||||
1
|
||||
}
|
||||
|
||||
fn library_tree_is_empty(t: &Arc<LibraryTree>) -> bool {
|
||||
t.is_empty()
|
||||
}
|
||||
|
||||
/// What `timeline(i)` returns for a scene that does not exist (never for a sanitized document).
|
||||
static NO_TIMELINE: Timeline = Timeline { layers: Vec::new() };
|
||||
|
||||
impl PartialEq for Document {
|
||||
fn eq(&self, o: &Document) -> bool {
|
||||
self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds)
|
||||
self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Document {
|
||||
fn default() -> Self {
|
||||
let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), next_id: 1 };
|
||||
let id = LayerId(d.alloc_id());
|
||||
d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1")));
|
||||
d
|
||||
@@ -1280,6 +1291,7 @@ impl Document {
|
||||
for s in &self.sounds {
|
||||
max_id = max_id.max(s.id.0);
|
||||
}
|
||||
self.sanitize_library_tree(&mut max_id);
|
||||
self.next_id = self.next_id.max(max_id.saturating_add(1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
//! How the Library is organised (ADR 0050): folders, the folder each item is in, names unique
|
||||
//! within a folder, how often each item is used, and which items nothing reaches.
|
||||
//!
|
||||
//! The organisation is kept apart from the items themselves ([`Document::library_tree`]): moving
|
||||
//! or renaming a folder touches one small table, never a symbol's timeline, and documents from
|
||||
//! before folders open with every item at the top level.
|
||||
|
||||
use crate::{BitmapId, Document, ElementId, ElementKind, LayerId, Paint, SoundId, Symbol, SymbolId, Timeline};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Unique id of a Library folder (from the document's id counter).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct FolderId(pub u64);
|
||||
|
||||
/// A symbol, bitmap or sound in the Library.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum LibraryItem {
|
||||
Symbol(SymbolId),
|
||||
Bitmap(BitmapId),
|
||||
Sound(SoundId),
|
||||
}
|
||||
|
||||
impl LibraryItem {
|
||||
/// The id inside, whatever the kind (ids are unique across kinds within a document).
|
||||
pub fn raw(self) -> u64 {
|
||||
match self {
|
||||
LibraryItem::Symbol(i) => i.0,
|
||||
LibraryItem::Bitmap(i) => i.0,
|
||||
LibraryItem::Sound(i) => i.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of the Library: an item or a folder.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum LibraryEntry {
|
||||
Item(LibraryItem),
|
||||
Folder(FolderId),
|
||||
}
|
||||
|
||||
/// A Library folder. Folders nest; `parent` is `None` at the top level.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct LibraryFolder {
|
||||
pub id: FolderId,
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<FolderId>,
|
||||
}
|
||||
|
||||
/// The Library's folders and where each item is.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct LibraryTree {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub folders: Vec<LibraryFolder>,
|
||||
/// The folder each item is in. An item not listed is at the top level.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty", with = "placed_list")]
|
||||
pub placed: BTreeMap<LibraryItem, FolderId>,
|
||||
}
|
||||
|
||||
impl LibraryTree {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.folders.is_empty() && self.placed.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// `placed` as a list of `{"symbol": 3, "folder": 7}` (JSON object keys must be strings).
|
||||
mod placed_list {
|
||||
use super::{FolderId, LibraryItem};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Placed {
|
||||
#[serde(flatten)]
|
||||
item: LibraryItem,
|
||||
folder: FolderId,
|
||||
}
|
||||
|
||||
pub fn serialize<S: Serializer>(m: &BTreeMap<LibraryItem, FolderId>, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.collect_seq(m.iter().map(|(item, folder)| Placed { item: *item, folder: *folder }))
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<BTreeMap<LibraryItem, FolderId>, D::Error> {
|
||||
let v: Vec<Placed> = Vec::deserialize(d)?;
|
||||
Ok(v.into_iter().map(|p| (p.item, p.folder)).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Most folders in a Library.
|
||||
pub const MAX_FOLDERS: usize = 10_000;
|
||||
/// Deepest folder nesting (a top-level folder is at depth 1).
|
||||
pub const MAX_FOLDER_DEPTH: usize = 32;
|
||||
/// Longest Library name (characters).
|
||||
pub const MAX_NAME_CHARS: usize = 256;
|
||||
|
||||
/// Why a name can't be used for a Library item or folder.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum NameError {
|
||||
Empty,
|
||||
TooLong,
|
||||
/// `/` separates folders in a path (`Characters/Ball`).
|
||||
Slash,
|
||||
/// The folder already holds an item or folder of that name (case aside).
|
||||
Taken(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NameError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
NameError::Empty => write!(f, "a Library name can't be empty"),
|
||||
NameError::TooLong => write!(f, "a Library name is at most {MAX_NAME_CHARS} characters"),
|
||||
NameError::Slash => write!(f, "a Library name can't contain “/” (it separates folders)"),
|
||||
NameError::Taken(n) => write!(f, "this folder already has an item named “{n}”"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Library names compare without case, as in Animate.
|
||||
fn same_name(a: &str, b: &str) -> bool {
|
||||
a == b || a.to_lowercase() == b.to_lowercase()
|
||||
}
|
||||
|
||||
/// A name trimmed and checked for the Library's rules (not for clashes).
|
||||
pub fn clean_name(name: &str) -> Result<String, NameError> {
|
||||
let n = name.trim();
|
||||
if n.is_empty() {
|
||||
return Err(NameError::Empty);
|
||||
}
|
||||
if n.chars().count() > MAX_NAME_CHARS {
|
||||
return Err(NameError::TooLong);
|
||||
}
|
||||
if n.contains('/') {
|
||||
return Err(NameError::Slash);
|
||||
}
|
||||
Ok(n.to_string())
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Every item in the Library: symbols, then bitmaps, then sounds.
|
||||
pub fn library_items(&self) -> impl Iterator<Item = LibraryItem> + '_ {
|
||||
self.library
|
||||
.iter()
|
||||
.map(|s| LibraryItem::Symbol(s.id))
|
||||
.chain(self.bitmaps.iter().map(|b| LibraryItem::Bitmap(b.id)))
|
||||
.chain(self.sounds.iter().map(|s| LibraryItem::Sound(s.id)))
|
||||
}
|
||||
|
||||
pub fn has_item(&self, item: LibraryItem) -> bool {
|
||||
self.item_name(item).is_some()
|
||||
}
|
||||
|
||||
pub fn item_name(&self, item: LibraryItem) -> Option<&str> {
|
||||
match item {
|
||||
LibraryItem::Symbol(id) => self.symbol(id).map(|s| s.name.as_str()),
|
||||
LibraryItem::Bitmap(id) => self.bitmap(id).map(|b| b.name.as_str()),
|
||||
LibraryItem::Sound(id) => self.sound(id).map(|s| s.name.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn folder(&self, id: FolderId) -> Option<&LibraryFolder> {
|
||||
self.library_tree.folders.iter().find(|f| f.id == id)
|
||||
}
|
||||
|
||||
pub fn has_entry(&self, e: LibraryEntry) -> bool {
|
||||
match e {
|
||||
LibraryEntry::Item(i) => self.has_item(i),
|
||||
LibraryEntry::Folder(f) => self.folder(f).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn entry_name(&self, e: LibraryEntry) -> Option<&str> {
|
||||
match e {
|
||||
LibraryEntry::Item(i) => self.item_name(i),
|
||||
LibraryEntry::Folder(f) => self.folder(f).map(|f| f.name.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder `e` is in (`None`: the top level).
|
||||
pub fn parent_of(&self, e: LibraryEntry) -> Option<FolderId> {
|
||||
match e {
|
||||
LibraryEntry::Item(i) => self.library_tree.placed.get(&i).copied(),
|
||||
LibraryEntry::Folder(f) => self.folder(f).and_then(|f| f.parent),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folders from the top level down to `id` (inclusive). Bounded, so a damaged tree can't
|
||||
/// loop.
|
||||
pub fn folder_chain(&self, id: FolderId) -> Vec<FolderId> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = Some(id);
|
||||
while let Some(f) = at.and_then(|i| self.folder(i)) {
|
||||
if out.len() >= MAX_FOLDER_DEPTH || out.contains(&f.id) {
|
||||
break;
|
||||
}
|
||||
out.push(f.id);
|
||||
at = f.parent;
|
||||
}
|
||||
out.reverse();
|
||||
out
|
||||
}
|
||||
|
||||
/// `e`'s place as a path, `Characters/Hero/Ball` (`/` joins folder names).
|
||||
pub fn entry_path(&self, e: LibraryEntry) -> String {
|
||||
let mut parts: Vec<&str> = self.parent_of(e).map(|p| self.folder_chain(p)).unwrap_or_default().into_iter().filter_map(|f| self.folder(f).map(|x| x.name.as_str())).collect();
|
||||
parts.push(self.entry_name(e).unwrap_or(""));
|
||||
parts.join("/")
|
||||
}
|
||||
|
||||
/// Whether `inner` is `outer` or inside it, at any depth.
|
||||
pub fn folder_within(&self, inner: FolderId, outer: FolderId) -> bool {
|
||||
self.folder_chain(inner).contains(&outer)
|
||||
}
|
||||
|
||||
/// The folders and items directly in `parent` (`None`: the top level), folders first.
|
||||
pub fn library_children(&self, parent: Option<FolderId>) -> Vec<LibraryEntry> {
|
||||
let folders = self.library_tree.folders.iter().filter(|f| f.parent == parent).map(|f| LibraryEntry::Folder(f.id));
|
||||
let items = self.library_items().filter(|i| self.library_tree.placed.get(i).copied() == parent).map(LibraryEntry::Item);
|
||||
folders.chain(items).collect()
|
||||
}
|
||||
|
||||
/// Everything inside folder `id` at any depth (not the folder itself): folders, then items.
|
||||
pub fn folder_contents(&self, id: FolderId) -> Vec<LibraryEntry> {
|
||||
let inside: Vec<FolderId> = self.library_tree.folders.iter().filter(|f| f.id != id && self.folder_within(f.id, id)).map(|f| f.id).collect();
|
||||
let mut all = inside.clone();
|
||||
all.push(id);
|
||||
let items = self.library_items().filter(|i| self.library_tree.placed.get(i).is_some_and(|f| all.contains(f)));
|
||||
inside.into_iter().map(LibraryEntry::Folder).chain(items.map(LibraryEntry::Item)).collect()
|
||||
}
|
||||
|
||||
/// How deep folder `id` is (1 at the top level).
|
||||
pub fn folder_depth(&self, id: FolderId) -> usize {
|
||||
self.folder_chain(id).len()
|
||||
}
|
||||
|
||||
/// How many folder levels `id` holds, itself included (1 for a folder without subfolders).
|
||||
pub fn folder_height(&self, id: FolderId) -> usize {
|
||||
let base = self.folder_depth(id);
|
||||
self.library_tree.folders.iter().filter(|f| self.folder_within(f.id, id)).map(|f| self.folder_depth(f.id) + 1 - base).max().unwrap_or(1)
|
||||
}
|
||||
|
||||
/// Whether folder `parent` already holds something named `name` (case aside), other than
|
||||
/// `except`.
|
||||
pub fn name_taken(&self, parent: Option<FolderId>, name: &str, except: Option<LibraryEntry>) -> bool {
|
||||
self.library_children(parent).into_iter().filter(|e| Some(*e) != except).any(|e| self.entry_name(e).is_some_and(|n| same_name(n, name)))
|
||||
}
|
||||
|
||||
/// `name` checked for the Library's rules and for a clash in `parent`.
|
||||
pub fn check_name(&self, parent: Option<FolderId>, name: &str, except: Option<LibraryEntry>) -> Result<String, NameError> {
|
||||
let n = clean_name(name)?;
|
||||
if self.name_taken(parent, &n, except) {
|
||||
return Err(NameError::Taken(n));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// `wanted`, or `wanted 2`, `wanted 3`, … whichever `parent` doesn't hold yet.
|
||||
pub fn unique_name(&self, parent: Option<FolderId>, wanted: &str) -> String {
|
||||
let base: String = wanted.trim().replace('/', "-").chars().take(MAX_NAME_CHARS - 8).collect();
|
||||
let base = if base.is_empty() { "Item".to_string() } else { base };
|
||||
if !self.name_taken(parent, &base, None) {
|
||||
return base;
|
||||
}
|
||||
let siblings = self.library_children(parent).len() + 2;
|
||||
(2..=siblings).map(|n| format!("{base} {n}")).find(|c| !self.name_taken(parent, c, None)).unwrap_or(base)
|
||||
}
|
||||
|
||||
/// `stem 1`, `stem 2`, … the first that `parent` doesn't hold, counting from `start`.
|
||||
pub fn numbered_name(&self, parent: Option<FolderId>, stem: &str, start: usize) -> String {
|
||||
let end = start + self.library_children(parent).len() + 1;
|
||||
(start.max(1)..=end).map(|n| format!("{stem} {n}")).find(|c| !self.name_taken(parent, c, None)).unwrap_or_else(|| format!("{stem} {end}"))
|
||||
}
|
||||
|
||||
/// Moves `e` into folder `to` (`None`: the top level). No checks: see `library.move`.
|
||||
pub fn place_entry(&mut self, e: LibraryEntry, to: Option<FolderId>) {
|
||||
let tree = Arc::make_mut(&mut self.library_tree);
|
||||
match e {
|
||||
LibraryEntry::Item(i) => match to {
|
||||
Some(f) => {
|
||||
tree.placed.insert(i, f);
|
||||
}
|
||||
None => {
|
||||
tree.placed.remove(&i);
|
||||
}
|
||||
},
|
||||
LibraryEntry::Folder(id) => {
|
||||
if let Some(f) = tree.folders.iter_mut().find(|f| f.id == id) {
|
||||
f.parent = to;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder at `path` (`Characters/Hero`), made where missing. `None` for an empty path,
|
||||
/// or when the Library can't hold more folders or nesting.
|
||||
pub fn ensure_folder_path(&mut self, path: &str) -> Option<FolderId> {
|
||||
let mut parent: Option<FolderId> = None;
|
||||
for (depth, part) in path.split('/').map(str::trim).filter(|p| !p.is_empty()).enumerate() {
|
||||
if depth >= MAX_FOLDER_DEPTH {
|
||||
break;
|
||||
}
|
||||
let part: String = part.chars().take(MAX_NAME_CHARS).collect();
|
||||
let found = self.library_tree.folders.iter().find(|f| f.parent == parent && same_name(&f.name, &part)).map(|f| f.id);
|
||||
parent = Some(match found {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
if self.library_tree.folders.len() >= MAX_FOLDERS {
|
||||
return parent;
|
||||
}
|
||||
let id = FolderId(self.alloc_id());
|
||||
Arc::make_mut(&mut self.library_tree).folders.push(LibraryFolder { id, name: part, parent });
|
||||
id
|
||||
}
|
||||
});
|
||||
}
|
||||
parent
|
||||
}
|
||||
|
||||
/// How many times each item is used: symbol instances, shapes filled with a bitmap and
|
||||
/// keyframes playing a sound, counted once per keyframe on every timeline (scenes and
|
||||
/// symbols). Items used nowhere are left out.
|
||||
pub fn library_uses(&self) -> HashMap<LibraryItem, usize> {
|
||||
let mut uses: HashMap<LibraryItem, usize> = HashMap::new();
|
||||
for tl in self.timelines() {
|
||||
visit_refs(tl, |item| *uses.entry(item).or_default() += 1);
|
||||
}
|
||||
uses
|
||||
}
|
||||
|
||||
/// The items nothing in the movie reaches: not placed in any scene, nor inside a symbol
|
||||
/// that is (at any depth). Symbols with a linkage class count as reached, since scripts
|
||||
/// can make them by name. In Library order.
|
||||
pub fn unused_items(&self) -> Vec<LibraryItem> {
|
||||
let mut reached: HashSet<LibraryItem> = HashSet::new();
|
||||
let mut stack: Vec<SymbolId> = self.library.iter().filter(|s| s.linkage.is_some()).map(|s| s.id).collect();
|
||||
for s in &stack {
|
||||
reached.insert(LibraryItem::Symbol(*s));
|
||||
}
|
||||
let reach = |item: LibraryItem, reached: &mut HashSet<LibraryItem>, stack: &mut Vec<SymbolId>| {
|
||||
if reached.insert(item)
|
||||
&& let LibraryItem::Symbol(id) = item
|
||||
{
|
||||
stack.push(id);
|
||||
}
|
||||
};
|
||||
for scene in &self.scenes {
|
||||
visit_refs(&scene.timeline, |item| reach(item, &mut reached, &mut stack));
|
||||
}
|
||||
// Each symbol is walked at most once (it enters the stack when first reached).
|
||||
while let Some(id) = stack.pop() {
|
||||
if let Some(sym) = self.symbol(id) {
|
||||
visit_refs(&sym.timeline, |item| reach(item, &mut reached, &mut stack));
|
||||
}
|
||||
}
|
||||
self.library_items().filter(|i| !reached.contains(i)).collect()
|
||||
}
|
||||
|
||||
/// Whether symbol `outer` is `inner` or holds an instance of it at any depth (so placing
|
||||
/// `inner` inside `outer` would make a symbol contain itself).
|
||||
pub fn symbol_contains(&self, outer: SymbolId, inner: SymbolId) -> bool {
|
||||
let mut seen: HashSet<SymbolId> = HashSet::new();
|
||||
let mut stack = vec![outer];
|
||||
while let Some(id) = stack.pop() {
|
||||
if id == inner {
|
||||
return true;
|
||||
}
|
||||
if !seen.insert(id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(sym) = self.symbol(id) {
|
||||
visit_refs(&sym.timeline, |item| {
|
||||
if let LibraryItem::Symbol(s) = item {
|
||||
stack.push(s);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A copy of symbol `id` named `name`, with fresh layer and element ids, in the same
|
||||
/// folder, right after it in the Library. Its linkage class stays with the original (a
|
||||
/// class names one symbol). The new symbol's id, or `None` if there is no such symbol.
|
||||
pub fn duplicate_symbol(&mut self, id: SymbolId, name: String) -> Option<SymbolId> {
|
||||
let at = self.library.iter().position(|s| s.id == id)?;
|
||||
let src = self.library.get(at)?.clone();
|
||||
let new_id = SymbolId(self.alloc_id());
|
||||
let timeline = fresh_ids(&src.timeline, &mut || self.alloc_id());
|
||||
let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, timeline };
|
||||
self.library.insert(at + 1, Arc::new(copy));
|
||||
if let Some(f) = self.library_tree.placed.get(&LibraryItem::Symbol(id)).copied() {
|
||||
Arc::make_mut(&mut self.library_tree).placed.insert(LibraryItem::Symbol(new_id), f);
|
||||
}
|
||||
Some(new_id)
|
||||
}
|
||||
|
||||
/// Repairs a loaded Library tree: folders with unique ids and usable names, parents that
|
||||
/// exist, no cycles, nesting within [`MAX_FOLDER_DEPTH`], and only placements of items and
|
||||
/// folders that exist. Touches the tree only if something needs it.
|
||||
pub(crate) fn sanitize_library_tree(&mut self, max_id: &mut u64) {
|
||||
let ok = |d: &Document| {
|
||||
let t = &d.library_tree;
|
||||
let mut ids = HashSet::new();
|
||||
t.folders.len() <= MAX_FOLDERS
|
||||
&& t.folders.iter().all(|f| ids.insert(f.id) && clean_name(&f.name).as_deref() == Ok(f.name.as_str()) && f.parent.is_none_or(|p| p != f.id && d.folder(p).is_some()))
|
||||
&& t.folders.iter().all(|f| d.folder_chain(f.id).first().is_some_and(|top| d.folder(*top).is_some_and(|x| x.parent.is_none())))
|
||||
&& t.placed.iter().all(|(i, f)| d.has_item(*i) && d.folder(*f).is_some())
|
||||
};
|
||||
for f in &self.library_tree.folders {
|
||||
*max_id = (*max_id).max(f.id.0);
|
||||
}
|
||||
if ok(self) {
|
||||
return;
|
||||
}
|
||||
let mut tree = (*self.library_tree).clone();
|
||||
let mut seen = HashSet::new();
|
||||
tree.folders.retain(|f| seen.insert(f.id));
|
||||
tree.folders.truncate(MAX_FOLDERS);
|
||||
for (i, f) in tree.folders.iter_mut().enumerate() {
|
||||
let name: String = f.name.trim().replace('/', "-").chars().take(MAX_NAME_CHARS).collect();
|
||||
f.name = if name.is_empty() { format!("Folder {}", i + 1) } else { name };
|
||||
}
|
||||
let ids: HashSet<FolderId> = tree.folders.iter().map(|f| f.id).collect();
|
||||
for f in &mut tree.folders {
|
||||
if f.parent.is_some_and(|p| p == f.id || !ids.contains(&p)) {
|
||||
f.parent = None;
|
||||
}
|
||||
}
|
||||
// Cycles and over-deep chains: the first folder found on one goes to the top level.
|
||||
for i in 0..tree.folders.len() {
|
||||
let Some(start) = tree.folders.get(i).map(|f| f.id) else { continue };
|
||||
let mut at = tree.folders.get(i).and_then(|f| f.parent);
|
||||
let mut steps = 1;
|
||||
let mut bad = false;
|
||||
while let Some(p) = at {
|
||||
steps += 1;
|
||||
if p == start || steps > MAX_FOLDER_DEPTH {
|
||||
bad = true;
|
||||
break;
|
||||
}
|
||||
at = tree.folders.iter().find(|f| f.id == p).and_then(|f| f.parent);
|
||||
}
|
||||
if bad && let Some(f) = tree.folders.get_mut(i) {
|
||||
f.parent = None;
|
||||
}
|
||||
}
|
||||
let items: HashSet<LibraryItem> = self.library_items().collect();
|
||||
tree.placed.retain(|i, f| items.contains(i) && ids.contains(f));
|
||||
self.library_tree = Arc::new(tree);
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `f` once per Library reference on each keyframe of `tl`: symbol instances, bitmap
|
||||
/// fills and the keyframe's sound.
|
||||
pub fn visit_refs(tl: &Timeline, mut f: impl FnMut(LibraryItem)) {
|
||||
for l in &tl.layers {
|
||||
for k in &l.keyframes {
|
||||
for e in &k.elements {
|
||||
match &e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => f(LibraryItem::Symbol(*symbol)),
|
||||
ElementKind::Shape(s) => {
|
||||
if let Some(Paint::Bitmap { bitmap, .. }) = &s.fill {
|
||||
f(LibraryItem::Bitmap(*bitmap));
|
||||
}
|
||||
}
|
||||
ElementKind::Text(_) | ElementKind::Camera => {}
|
||||
}
|
||||
}
|
||||
if let Some(s) = &k.sound {
|
||||
f(LibraryItem::Sound(s.sound));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `tl` with new layer and element ids from `alloc`, every reference to them (layer parents,
|
||||
/// motion tween targets, bone ends) following. An element keeps one id across keyframes, as
|
||||
/// tweens need.
|
||||
pub fn fresh_ids(tl: &Timeline, alloc: &mut dyn FnMut() -> u64) -> Timeline {
|
||||
let mut layers: HashMap<LayerId, LayerId> = HashMap::new();
|
||||
let mut elements: HashMap<ElementId, ElementId> = HashMap::new();
|
||||
for l in &tl.layers {
|
||||
layers.entry(l.id).or_insert_with(|| LayerId(alloc()));
|
||||
for k in &l.keyframes {
|
||||
for e in &k.elements {
|
||||
elements.entry(e.id).or_insert_with(|| ElementId(alloc()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let el = |id: ElementId| elements.get(&id).copied().unwrap_or(id);
|
||||
let out = tl
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let mut l = (**l).clone();
|
||||
l.id = layers.get(&l.id).copied().unwrap_or(l.id);
|
||||
l.parent = l.parent.map(|p| layers.get(&p).copied().unwrap_or(p));
|
||||
if let Some(a) = &mut l.armature {
|
||||
for b in &mut Arc::make_mut(a).bones {
|
||||
b.parent = el(b.parent);
|
||||
b.child = el(b.child);
|
||||
}
|
||||
}
|
||||
for k in &mut l.keyframes {
|
||||
let k = Arc::make_mut(k);
|
||||
for e in &mut k.elements {
|
||||
Arc::make_mut(e).id = el(e.id);
|
||||
}
|
||||
if let Some(m) = &mut k.motion {
|
||||
m.target = el(m.target);
|
||||
}
|
||||
}
|
||||
Arc::new(l)
|
||||
})
|
||||
.collect();
|
||||
Timeline { layers: out }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "library_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,195 @@
|
||||
use super::*;
|
||||
use crate::{Element, Layer, Linkage, Symbol, SymbolKind, sample};
|
||||
|
||||
fn instance(d: &mut Document, symbol: SymbolId) -> Arc<Element> {
|
||||
Arc::new(Element {
|
||||
id: ElementId(d.alloc_id()),
|
||||
name: String::new(),
|
||||
transform: Default::default(),
|
||||
color: Default::default(),
|
||||
kind: ElementKind::Symbol { symbol, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() },
|
||||
})
|
||||
}
|
||||
|
||||
/// A symbol named `name` holding instances of `inside`.
|
||||
fn add_symbol(d: &mut Document, name: &str, inside: &[SymbolId]) -> SymbolId {
|
||||
let id = SymbolId(d.alloc_id());
|
||||
let mut layer = Layer::new(LayerId(d.alloc_id()), "Layer 1");
|
||||
let els: Vec<_> = inside.iter().map(|s| instance(d, *s)).collect();
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.elements = els;
|
||||
}
|
||||
d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(layer)] } }));
|
||||
id
|
||||
}
|
||||
|
||||
fn sym(d: &Document, name: &str) -> SymbolId {
|
||||
d.library.iter().find(|s| s.name == name).map(|s| s.id).unwrap_or(SymbolId(0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_round_trip_and_older_files_open_without_them() {
|
||||
let mut d = sample::demo();
|
||||
let plain = serde_json::to_string(&d).unwrap();
|
||||
assert!(!plain.contains("library_tree"), "a Library without folders writes nothing new");
|
||||
let back: Document = serde_json::from_str(&plain).unwrap();
|
||||
assert!(back.library_tree.is_empty());
|
||||
|
||||
let chars = d.ensure_folder_path("Characters/Hero").unwrap();
|
||||
let ball = sym(&d, "Ball");
|
||||
d.place_entry(LibraryEntry::Item(LibraryItem::Symbol(ball)), Some(chars));
|
||||
let json = serde_json::to_string(&d).unwrap();
|
||||
assert!(json.contains(&format!("{{\"symbol\":{},\"folder\":{}}}", ball.0, chars.0)), "{json}");
|
||||
let mut back: Document = serde_json::from_str(&json).unwrap();
|
||||
back.sanitize();
|
||||
assert_eq!(back.library_tree, d.library_tree);
|
||||
assert_eq!(back.entry_path(LibraryEntry::Item(LibraryItem::Symbol(ball))), "Characters/Hero/Ball");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_paths_are_made_once_and_matched_without_case() {
|
||||
let mut d = Document::default();
|
||||
let a = d.ensure_folder_path("Characters/Hero").unwrap();
|
||||
let b = d.ensure_folder_path(" characters / HERO ").unwrap();
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(d.library_tree.folders.len(), 2);
|
||||
assert_eq!(d.folder_depth(a), 2);
|
||||
assert_eq!(d.ensure_folder_path(""), None);
|
||||
assert_eq!(d.ensure_folder_path("//"), None);
|
||||
let top = d.folder_chain(a)[0];
|
||||
assert_eq!(d.folder_height(top), 2);
|
||||
assert!(d.folder_within(a, top) && !d.folder_within(top, a));
|
||||
// Nesting stops at the limit instead of growing without end.
|
||||
let deep = vec!["x"; MAX_FOLDER_DEPTH + 10].join("/");
|
||||
let f = d.ensure_folder_path(&deep).unwrap();
|
||||
assert_eq!(d.folder_depth(f), MAX_FOLDER_DEPTH);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_unique_per_folder_without_case() {
|
||||
let mut d = sample::demo();
|
||||
let f = d.ensure_folder_path("Props").unwrap();
|
||||
let ball = LibraryEntry::Item(LibraryItem::Symbol(sym(&d, "Ball")));
|
||||
assert_eq!(d.check_name(None, "ball", None), Err(NameError::Taken("ball".into())));
|
||||
assert_eq!(d.check_name(None, " Ball ", Some(ball)).as_deref(), Ok("Ball"), "an item may keep its own name");
|
||||
assert_eq!(d.check_name(Some(f), "Ball", None).as_deref(), Ok("Ball"), "another folder may hold the same name");
|
||||
assert_eq!(d.check_name(None, "a/b", None), Err(NameError::Slash));
|
||||
assert_eq!(d.check_name(None, " ", None), Err(NameError::Empty));
|
||||
assert_eq!(d.check_name(None, &"x".repeat(MAX_NAME_CHARS + 1), None), Err(NameError::TooLong));
|
||||
assert_eq!(d.check_name(None, "props", None), Err(NameError::Taken("props".into())), "folders and items share a folder's names");
|
||||
assert_eq!(d.unique_name(None, "Ball"), "Ball 2");
|
||||
assert_eq!(d.unique_name(None, "Ball copy"), "Ball copy");
|
||||
assert_eq!(d.numbered_name(None, "Symbol", 1), "Symbol 1");
|
||||
add_symbol(&mut d, "Symbol 1", &[]);
|
||||
assert_eq!(d.numbered_name(None, "Symbol", 1), "Symbol 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_trees_are_repaired_on_load() {
|
||||
let mut d = sample::demo();
|
||||
let ball = LibraryItem::Symbol(sym(&d, "Ball"));
|
||||
let t = Arc::make_mut(&mut d.library_tree);
|
||||
let f = |id: u64, name: &str, parent: Option<u64>| LibraryFolder { id: FolderId(id), name: name.into(), parent: parent.map(FolderId) };
|
||||
t.folders = vec![f(900, "A", Some(901)), f(901, "B", Some(900)), f(902, " ", Some(902)), f(903, "C/D", Some(999)), f(900, "Dup", None)];
|
||||
t.placed.insert(ball, FolderId(901));
|
||||
t.placed.insert(LibraryItem::Sound(SoundId(12345)), FolderId(900));
|
||||
t.placed.insert(LibraryItem::Symbol(SymbolId(77777)), FolderId(900));
|
||||
d.sanitize();
|
||||
let t = &d.library_tree;
|
||||
assert_eq!(t.folders.len(), 4, "the duplicate id is dropped");
|
||||
assert!(t.folders.iter().all(|f| d.folder_chain(f.id).len() <= 2), "the cycle is broken");
|
||||
assert!(t.folders.iter().all(|f| f.parent != Some(f.id) && f.parent.is_none_or(|p| d.folder(p).is_some())));
|
||||
assert!(t.folders.iter().all(|f| clean_name(&f.name).is_ok()), "{:?}", t.folders);
|
||||
assert_eq!(t.placed.len(), 1, "only items that exist stay placed");
|
||||
assert!(d.next_id > 903, "folder ids stay unique");
|
||||
// A sane tree is left alone (same Arc).
|
||||
let before = d.library_tree.clone();
|
||||
d.sanitize();
|
||||
assert!(Arc::ptr_eq(&before, &d.library_tree));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_count_every_keyframe_and_unused_follows_reachability() {
|
||||
let mut d = sample::demo();
|
||||
let (ball, star) = (sym(&d, "Ball"), sym(&d, "Star"));
|
||||
let uses = d.library_uses();
|
||||
assert!(uses.get(&LibraryItem::Symbol(ball)).copied().unwrap_or(0) > 0);
|
||||
assert!(uses.get(&LibraryItem::Symbol(star)).copied().unwrap_or(0) > 0);
|
||||
assert!(d.unused_items().is_empty(), "the sample uses everything");
|
||||
|
||||
// Inner is used only inside Outer, which nothing places: both are unused, though Inner
|
||||
// has a use.
|
||||
let inner = add_symbol(&mut d, "Inner", &[]);
|
||||
let outer = add_symbol(&mut d, "Outer", &[inner, inner]);
|
||||
assert_eq!(d.library_uses().get(&LibraryItem::Symbol(inner)), Some(&2));
|
||||
assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(inner), LibraryItem::Symbol(outer)]);
|
||||
// A linkage class makes a symbol reachable (scripts make it by name), and what it holds.
|
||||
if let Some(s) = d.library.iter_mut().find(|s| s.id == outer) {
|
||||
Arc::make_mut(s).linkage = Some(Linkage { class: "Outer".into(), base: String::new() });
|
||||
}
|
||||
assert!(d.unused_items().is_empty());
|
||||
// Cycles terminate.
|
||||
let a = add_symbol(&mut d, "A", &[]);
|
||||
let b = add_symbol(&mut d, "B", &[a]);
|
||||
if let Some(s) = d.library.iter_mut().find(|s| s.id == a) {
|
||||
let layer = Arc::make_mut(&mut Arc::make_mut(s).timeline.layers[0]);
|
||||
let e = Arc::new(Element { id: ElementId(5_000_000), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: b, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } });
|
||||
layer.keyframe_mut(0).unwrap().elements.push(e);
|
||||
}
|
||||
assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(a), LibraryItem::Symbol(b)]);
|
||||
assert!(d.symbol_contains(a, b) && d.symbol_contains(b, a) && d.symbol_contains(a, a));
|
||||
assert!(!d.symbol_contains(inner, outer) && d.symbol_contains(outer, inner));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_duplicate_has_fresh_ids_and_keeps_its_folder() {
|
||||
let mut d = sample::demo();
|
||||
let star = sym(&d, "Star");
|
||||
let f = d.ensure_folder_path("FX").unwrap();
|
||||
d.place_entry(LibraryEntry::Item(LibraryItem::Symbol(star)), Some(f));
|
||||
if let Some(s) = d.library.iter_mut().find(|s| s.id == star) {
|
||||
Arc::make_mut(s).linkage = Some(Linkage { class: "Star".into(), base: String::new() });
|
||||
}
|
||||
let copy = d.duplicate_symbol(star, "Star copy".into()).unwrap();
|
||||
let (a, b) = (d.symbol(star).unwrap(), d.symbol(copy).unwrap());
|
||||
assert_eq!(b.name, "Star copy");
|
||||
assert_eq!(b.kind, a.kind);
|
||||
assert!(b.linkage.is_none(), "a class names one symbol");
|
||||
assert_eq!(d.parent_of(LibraryEntry::Item(LibraryItem::Symbol(copy))), Some(f));
|
||||
let ids = |s: &Symbol| -> HashSet<u64> { s.timeline.layers.iter().flat_map(|l| std::iter::once(l.id.0).chain(l.keyframes.iter().flat_map(|k| k.elements.iter().map(|e| e.id.0)))).collect() };
|
||||
assert!(ids(a).is_disjoint(&ids(b)));
|
||||
assert_eq!(ids(a).len(), ids(b).len());
|
||||
// Same artwork: only ids differ, and an element keeps one id across its keyframes.
|
||||
for (la, lb) in a.timeline.layers.iter().zip(&b.timeline.layers) {
|
||||
assert_eq!(la.keyframes.len(), lb.keyframes.len());
|
||||
for (ka, kb) in la.keyframes.iter().zip(&lb.keyframes) {
|
||||
for (ea, eb) in ka.elements.iter().zip(&kb.elements) {
|
||||
assert_eq!((&ea.kind, ea.transform), (&eb.kind, eb.transform));
|
||||
}
|
||||
}
|
||||
let first: Vec<u64> = lb.keyframes.iter().filter_map(|k| k.elements.first().map(|e| e.id.0)).collect();
|
||||
if first.len() > 1 && la.keyframes.iter().filter_map(|k| k.elements.first().map(|e| e.id.0)).collect::<HashSet<_>>().len() == 1 {
|
||||
assert!(first.windows(2).all(|w| w[0] == w[1]));
|
||||
}
|
||||
}
|
||||
let order: Vec<SymbolId> = d.library.iter().map(|s| s.id).collect();
|
||||
let at = order.iter().position(|s| *s == star).unwrap();
|
||||
assert_eq!(order[at + 1], copy, "the copy sits right after its original");
|
||||
assert_eq!(d.duplicate_symbol(SymbolId(424242), "x".into()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_contents_reach_every_depth() {
|
||||
let mut d = sample::demo();
|
||||
let a = d.ensure_folder_path("A").unwrap();
|
||||
let ab = d.ensure_folder_path("A/B").unwrap();
|
||||
let c = d.ensure_folder_path("C").unwrap();
|
||||
let ball = LibraryItem::Symbol(sym(&d, "Ball"));
|
||||
d.place_entry(LibraryEntry::Item(ball), Some(ab));
|
||||
let inside = d.folder_contents(a);
|
||||
assert_eq!(inside, vec![LibraryEntry::Folder(ab), LibraryEntry::Item(ball)]);
|
||||
assert!(d.folder_contents(c).is_empty());
|
||||
assert_eq!(d.library_children(Some(ab)), vec![LibraryEntry::Item(ball)]);
|
||||
assert!(d.library_children(None).starts_with(&[LibraryEntry::Folder(a), LibraryEntry::Folder(c)]));
|
||||
assert!(!d.library_children(None).contains(&LibraryEntry::Item(ball)));
|
||||
}
|
||||
@@ -41,7 +41,7 @@ fn key(start: u32, duration: u32, elements: Vec<Arc<Element>>, tween: Option<Eas
|
||||
|
||||
/// Builds the demo document: a bouncing ball, a spinning star, a pulsing sun over hills.
|
||||
pub fn demo() -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 };
|
||||
let (w, h) = (1280.0, 720.0);
|
||||
|
||||
// --- library -------------------------------------------------------------------------
|
||||
@@ -147,7 +147,7 @@ pub fn demo() -> Document {
|
||||
/// whose last frame traces a line and goes back to the menu.
|
||||
pub fn interactive() -> Document {
|
||||
use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, Target};
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 };
|
||||
const LEN: u32 = 36;
|
||||
let solid = |c: u32| Paint::Solid(Rgba::hex(c));
|
||||
|
||||
@@ -211,7 +211,7 @@ pub fn interactive() -> Document {
|
||||
/// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens.
|
||||
/// Every element keeps one `Arc<Path>` across its keyframes, as a real tweened shape does.
|
||||
pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 };
|
||||
let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000));
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let mut rnd = move || {
|
||||
|
||||
@@ -25,6 +25,8 @@ gif.workspace = true
|
||||
[dev-dependencies]
|
||||
# Decodes exported sheets in tests (already in the tree through the renderer).
|
||||
png.workspace = true
|
||||
# Packs the XFL corpus into .fla archives in tests (ADR 0054; already in the tree through xfl).
|
||||
miniz_oxide = "0.8"
|
||||
# Plug-in test fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception).
|
||||
wat = "1.228"
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ pub(crate) enum Scope {
|
||||
/// A timeline commands address: a scene's (the one being edited) or a library symbol's.
|
||||
fn timeline_mut(s: &mut Session, symbol: Option<SymbolId>, scope: Scope) -> Result<&mut Timeline> {
|
||||
match symbol {
|
||||
None => Ok(s.doc.timeline_mut(s.scene)),
|
||||
None => Ok(crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)),
|
||||
Some(id) => {
|
||||
let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?;
|
||||
if scope == Scope::Runs && sym.kind != SymbolKind::MovieClip {
|
||||
|
||||
@@ -46,7 +46,7 @@ struct Found {
|
||||
|
||||
/// Instance `id` on the scene at the playhead (as it shows: tweened, posed).
|
||||
fn find_instance(s: &Session, id: ElementId) -> Option<Found> {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
tl.layers.iter().enumerate().find_map(|(index, l)| {
|
||||
let (_, els) = evaluate_layer_elements(l, s.frame)?;
|
||||
let el = els.iter().find(|e| e.id == id)?.clone();
|
||||
@@ -56,8 +56,8 @@ fn find_instance(s: &Session, id: ElementId) -> Option<Found> {
|
||||
|
||||
/// The armature layer holding bone `id`, and its armature.
|
||||
fn find_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc<Armature>)> {
|
||||
s.doc
|
||||
.timeline(s.scene)
|
||||
s
|
||||
.timeline()
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.kind == LayerKind::Armature)
|
||||
@@ -85,7 +85,7 @@ fn opt_point(p: &Value, key: &str) -> Result<Option<Vec2>> {
|
||||
}
|
||||
|
||||
fn unlocked(s: &Session, id: LayerId) -> Result<()> {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let l = tl.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
if l.locked || tl.locked_by_folder(id) {
|
||||
return Err(EngineError::State(format!("layer '{}' is locked", l.name)));
|
||||
@@ -105,7 +105,7 @@ fn take_off(s: &mut Session, layer: LayerId, id: ElementId) -> Result<()> {
|
||||
|
||||
/// A layer name `base_N` no layer of the scene has yet.
|
||||
fn fresh_name(s: &Session, base: &str) -> String {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
(1..).map(|n| format!("{base}{n}")).find(|n| tl.layers.iter().all(|l| &l.name != n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
unlocked(s, x.layer)?;
|
||||
}
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let arm_of = |x: &Found| (x.kind == LayerKind::Armature).then(|| tl.layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default());
|
||||
let (fa, ta) = (arm_of(&f), arm_of(&t));
|
||||
match (&fa, &ta) {
|
||||
@@ -186,10 +186,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => {
|
||||
// The first bone: both instances move to a new armature layer above them, whose one
|
||||
// pose spans from their keyframe to the end of the timeline.
|
||||
let (start, end) = s.doc.timeline(s.scene).layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end()));
|
||||
let (start, end) = s.timeline().layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end()));
|
||||
let end = end.max(s.frame_count());
|
||||
take_off(s, f.layer, from)?;
|
||||
if s.doc.timeline(s.scene).layers.len() >= 1000 {
|
||||
if s.timeline().layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let lid = LayerId(s.doc.alloc_id());
|
||||
@@ -203,7 +203,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
k.tween = Some(Tween::default());
|
||||
layer.keyframes = vec![Arc::new(k)];
|
||||
let index = f.index.min(t.index);
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
layer.parent = tl.container_at(index, LayerKind::Armature);
|
||||
tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer));
|
||||
tl.repair_masks();
|
||||
@@ -230,7 +230,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
left.bones.retain(|b| !gone.contains(&b.id));
|
||||
let dissolve = left.is_empty();
|
||||
let freed: Vec<ElementId> = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() };
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let (start, end) = (layer.keyframes.first().map_or(0, |k| k.start), layer.end_frame());
|
||||
@@ -244,7 +244,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut k = Keyframe::new(start, end.saturating_sub(start).max(1));
|
||||
k.elements = shown;
|
||||
freed_layer.keyframes = vec![Arc::new(k)];
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
if dissolve {
|
||||
tl.layers.retain(|l| l.id != lid);
|
||||
tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer));
|
||||
@@ -328,7 +328,7 @@ fn edit_pose<T>(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Ar
|
||||
if frame > MAX_FRAME {
|
||||
return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}")));
|
||||
}
|
||||
let arm = s.doc.timeline(s.scene).layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?;
|
||||
let arm = s.timeline().layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?;
|
||||
// Past the end a pose carries on from the last one (not a blank keyframe).
|
||||
{
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
@@ -411,7 +411,7 @@ fn solve(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
|
||||
let only = opt_u64(p, "layer")?.map(LayerId);
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let deg = |v: f32| v.to_degrees();
|
||||
let pt = |v: Vec2| json!([v.x, v.y]);
|
||||
let list: Vec<Value> = tl
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// The scene's camera layer id.
|
||||
pub(crate) fn camera_layer(s: &Session) -> Option<LayerId> {
|
||||
s.doc.timeline(s.scene).camera_layer().map(|l| l.id)
|
||||
s.timeline().camera_layer().map(|l| l.id)
|
||||
}
|
||||
|
||||
fn no_camera() -> EngineError {
|
||||
@@ -42,12 +42,16 @@ fn no_camera() -> EngineError {
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// A scene has the camera, not a symbol (ADR 0027, 0045).
|
||||
if !s.editing.is_empty() {
|
||||
return Err(EngineError::State("the camera belongs to a scene: close the symbol you are editing first (Edit › Edit Document)".into()));
|
||||
}
|
||||
if let Some(id) = camera_layer(s) {
|
||||
s.layer = id;
|
||||
s.selection.clear();
|
||||
return Ok(json!({"layer": id.0, "added": false}));
|
||||
}
|
||||
if s.doc.timeline(s.scene).layers.len() >= 1000 {
|
||||
if s.timeline().layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let id = LayerId(s.doc.alloc_id());
|
||||
@@ -61,7 +65,7 @@ fn add(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut k = Keyframe::new(0, frames);
|
||||
k.elements.push(Arc::new(Camera::rest(&s.doc.stage).to_element(el)));
|
||||
layer.keyframes = vec![Arc::new(k)];
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
tl.layers.insert(0, Arc::new(layer));
|
||||
tl.repair_masks();
|
||||
s.layer = id;
|
||||
@@ -71,11 +75,11 @@ fn add(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn remove(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let id = camera_layer(s).ok_or_else(no_camera)?;
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
tl.layers.retain(|l| l.id != id);
|
||||
tl.repair_masks();
|
||||
if s.layer == id {
|
||||
s.layer = s.doc.timeline(s.scene).layers.first().map_or(LayerId(0), |l| l.id);
|
||||
s.layer = s.timeline().layers.first().map_or(LayerId(0), |l| l.id);
|
||||
s.selection.clear();
|
||||
}
|
||||
Ok(json!({"removed": id.0}))
|
||||
@@ -187,9 +191,9 @@ fn camera_json(c: &Camera, stage: &anicraft_doc::Stage) -> Value {
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
|
||||
let Some(id) = camera_layer(s) else { return Ok(json!({"camera": false})) };
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let on = tl.camera_layer().is_some_and(|l| l.visible);
|
||||
let mut v = s.doc.timeline(s.scene).camera_state_at(frame, &s.doc.stage).map_or_else(|| json!({}), |c| camera_json(&c, &s.doc.stage));
|
||||
let mut v = s.timeline().camera_state_at(frame, &s.doc.stage).map_or_else(|| json!({}), |c| camera_json(&c, &s.doc.stage));
|
||||
v["camera"] = json!(true);
|
||||
v["layer"] = json!(id.0);
|
||||
v["on"] = json!(on);
|
||||
|
||||
+125
-49
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Selection, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline};
|
||||
use anicraft_geom::{Affine, Decomposed, Path, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
@@ -15,7 +15,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, cap?, join?, style?, dash?, object?}", true, draw_star),
|
||||
c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (the line style, as stroke.set_style; default: the tool's), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line),
|
||||
c("draw.object_drawing", "Object Drawing", "", Some("J"), "{on?: bool} (default: toggle)", false, object_drawing),
|
||||
c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", None, "{on?: bool} (default: toggle) dragged points and selections snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point and raw.move_handle do nothing while it is off)", false, snap_to_objects),
|
||||
c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", Some("Ctrl+Shift+/"), "{on?: bool} (default: toggle) dragged points and selections, and the points the Line, Rectangle, Oval, PolyStar and Pen tools draw, snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point, raw.move_handle and draw.snap do nothing while it is off)", false, snap_to_objects),
|
||||
c("edit.select_all", "Select All", "Edit", Some("Ctrl+A"), "{}", false, select_all),
|
||||
c("edit.deselect", "Deselect All", "Edit", Some("Ctrl+Shift+A"), "{}", false, |s, _| {
|
||||
s.selection.clear();
|
||||
@@ -33,15 +33,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))),
|
||||
c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))),
|
||||
c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))),
|
||||
c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the selected instance's)}", true, set_symbol_kind),
|
||||
c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the symbols of every selected instance)}", true, set_symbol_kind),
|
||||
c("element.rename", "Instance Name", "", None, "{name}", true, |s, p| s.each_layer(true, |s| rename(s, p))),
|
||||
c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, true))),
|
||||
c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, true))),
|
||||
c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, false))),
|
||||
c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, false))),
|
||||
c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol),
|
||||
c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name? (default: the next free “Symbol n”; a name the folder holds gets a number), kind?: graphic|movie_clip|button (default: graphic), folder?: Library folder id (default: the top level)} → {symbol, instance, name, layer, folder} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol),
|
||||
c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))),
|
||||
c("library.place", "Place Instance", "", None, "{symbol | bitmap, x?, y?}", true, place),
|
||||
c("library.place", "Place on Stage", "", None, "{symbol | bitmap | sound: id, x?, y?} or {items: [{symbol | bitmap | sound: id}, ..], x?, y?} → {element, elements, sound?}: symbols and bitmaps centred on x, y (default: the stage centre; inside an open symbol, in its space) in the active layer's keyframe at the playhead, selected; a sound goes onto that keyframe, its span grown to fit (one sound per keyframe). One undo step", true, place),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ fn object_drawing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Everything on every visible, unlocked layer at the playhead, as Animate's Select All.
|
||||
fn select_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let layers: Vec<LayerId> = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect();
|
||||
let layers: Vec<LayerId> = s.timeline().layers.iter().map(|l| l.id).collect();
|
||||
let mut sel = Selection::default();
|
||||
for l in layers.into_iter().filter(|l| s.gathers(*l)) {
|
||||
sel.extend_on(l, s.elements_on(l).iter().map(|e| e.id));
|
||||
@@ -203,9 +203,9 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Where each element is at the playhead: on `layer`, else the active layer first, then the
|
||||
// others top to bottom.
|
||||
let order: Vec<LayerId> = match opt_u64(p, "layer")?.map(LayerId) {
|
||||
Some(l) if s.doc.timeline(s.scene).layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))),
|
||||
Some(l) if s.timeline().layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))),
|
||||
Some(l) => vec![l],
|
||||
None => std::iter::once(s.layer).chain(s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(),
|
||||
None => std::iter::once(s.layer).chain(s.timeline().layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(),
|
||||
};
|
||||
let mut at: std::collections::HashMap<ElementId, LayerId> = std::collections::HashMap::new();
|
||||
for l in order {
|
||||
@@ -219,7 +219,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::State(format!("element {} is not on the active layer, or any layer, at this frame", id.0)));
|
||||
};
|
||||
if !s.selectable(l) {
|
||||
let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
return Err(EngineError::State(format!("element {} is on layer '{name}', which is locked or hidden", id.0)));
|
||||
}
|
||||
picked.push((l, id));
|
||||
@@ -526,30 +526,33 @@ fn set_loop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// A symbol's kind, for every instance of it: a graphic keeps step with the timeline it is
|
||||
/// placed on, a movie clip plays its own timeline on a loop, a button shows its Up frame.
|
||||
fn set_symbol_kind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = match str_req(p, "kind")? {
|
||||
"graphic" => SymbolKind::Graphic,
|
||||
"movie_clip" | "movie clip" => SymbolKind::MovieClip,
|
||||
"button" => SymbolKind::Button,
|
||||
other => return Err(EngineError::Param(format!("unknown symbol kind '{other}' (graphic, movie_clip or button)"))),
|
||||
};
|
||||
let id = match opt_u64(p, "symbol")? {
|
||||
Some(id) => SymbolId(id),
|
||||
let kind = crate::cmds_library::kind_of(str_req(p, "kind")?)?;
|
||||
let ids: Vec<SymbolId> = match opt_u64(p, "symbol")? {
|
||||
Some(id) => vec![SymbolId(id)],
|
||||
None => {
|
||||
// The symbol of the selected instance.
|
||||
let (layer, sel) = s.selection.first().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?;
|
||||
s.elements_on(layer)
|
||||
.iter()
|
||||
.find(|e| e.id == sel)
|
||||
.and_then(|e| match e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => Some(symbol),
|
||||
ElementKind::Shape(_) | ElementKind::Text(_) | ElementKind::Camera => None,
|
||||
})
|
||||
.ok_or_else(|| EngineError::State("the selection is not a symbol instance".into()))?
|
||||
// The symbols of the selected instances, on every layer (ADR 0053: a "mixed" Type
|
||||
// row sets them all), in selection order.
|
||||
let mut ids = Vec::new();
|
||||
for (layer, sel) in s.selection.iter() {
|
||||
if let Some(ElementKind::Symbol { symbol, .. }) = s.elements_on(layer).iter().find(|e| e.id == sel).map(|e| &e.kind)
|
||||
&& !ids.contains(symbol)
|
||||
{
|
||||
ids.push(*symbol);
|
||||
}
|
||||
}
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::State(if s.selection.is_empty() { "select a symbol instance, or pass 'symbol'".into() } else { "the selection is not a symbol instance".into() }));
|
||||
}
|
||||
ids
|
||||
}
|
||||
};
|
||||
let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?;
|
||||
std::sync::Arc::make_mut(sym).kind = kind;
|
||||
Ok(json!({"symbol": id.0, "kind": format!("{kind:?}")}))
|
||||
for id in &ids {
|
||||
let sym = s.doc.library.iter_mut().find(|x| x.id == *id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?;
|
||||
if sym.kind != kind {
|
||||
std::sync::Arc::make_mut(sym).kind = kind;
|
||||
}
|
||||
}
|
||||
Ok(json!({"symbol": ids.first().map(|i| i.0), "symbols": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "kind": format!("{kind:?}")}))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -648,8 +651,14 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(&top) = layers.first() else {
|
||||
return Err(EngineError::State("select something to convert".into()));
|
||||
};
|
||||
let n = s.doc.library.len() + 1;
|
||||
let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}"));
|
||||
// Into the folder asked for (ADR 0053), else the top level; the name is free there: the
|
||||
// next free “Symbol n”, or the name asked for with a number when the folder has it already.
|
||||
let folder = crate::cmds_library::opt_folder(s, p, "folder")?;
|
||||
let kind = opt_str(p, "kind")?.map(crate::cmds_library::kind_of).transpose()?.unwrap_or(SymbolKind::Graphic);
|
||||
let name: String = match opt_str(p, "name")? {
|
||||
Some(n) => s.doc.unique_name(folder, n),
|
||||
None => s.doc.numbered_name(folder, "Symbol", s.doc.library.len() + 1),
|
||||
};
|
||||
let bounds = s.selection_bounds();
|
||||
let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() };
|
||||
let sym_id = SymbolId(s.doc.alloc_id());
|
||||
@@ -668,7 +677,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut inner: Vec<Arc<Layer>> = Vec::with_capacity(layers.len());
|
||||
for l in layers {
|
||||
let sel = s.selection.on(l);
|
||||
let source = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
let source = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
let picked = s.with_layer(l, |s| -> Result<Vec<Arc<Element>>> {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len());
|
||||
@@ -694,10 +703,13 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
inner.push(Arc::new(layer));
|
||||
}
|
||||
s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: inner } }));
|
||||
s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind, linkage: None, timeline: Timeline { layers: inner } }));
|
||||
if folder.is_some() {
|
||||
s.doc.place_entry(LibraryEntry::Item(LibraryItem::Symbol(sym_id)), folder);
|
||||
}
|
||||
s.layer = top;
|
||||
s.select_only([inst_id]);
|
||||
Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0}))
|
||||
Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0, "folder": folder.map(|f| f.0)}))
|
||||
}
|
||||
|
||||
fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
@@ -752,18 +764,86 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"created": fresh_ids.len()}))
|
||||
}
|
||||
|
||||
/// Places a Library item centred on `x`/`y` (default: the stage centre): an instance of
|
||||
/// `symbol`, or a rectangle of `bitmap`'s size showing it, in the current keyframe, selected.
|
||||
/// Most items one `library.place` takes.
|
||||
const MAX_PLACE: usize = 1_000;
|
||||
|
||||
/// Places Library items at `x`/`y` (default: the stage centre), as a drop from the Library
|
||||
/// does (ADR 0053): an instance of each symbol, a rectangle of each bitmap's size showing it,
|
||||
/// in the active layer's keyframe at the playhead, all selected; a sound goes onto that
|
||||
/// keyframe. One command, so one undo step however many items.
|
||||
fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(bitmap) = opt_u64(p, "bitmap")? {
|
||||
return place_bitmap(s, p, anicraft_doc::BitmapId(bitmap));
|
||||
let items: Vec<LibraryItem> = match p.get("items") {
|
||||
Some(list) => {
|
||||
let list = list.as_array().ok_or_else(|| EngineError::Param("param 'items' must be a list of {\"symbol\" | \"bitmap\" | \"sound\": id}".into()))?;
|
||||
if list.len() > MAX_PLACE {
|
||||
return Err(EngineError::Param(format!("at most {MAX_PLACE} items at once")));
|
||||
}
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for v in list {
|
||||
match crate::cmds_library::entry_of(v)? {
|
||||
LibraryEntry::Item(i) => out.push(i),
|
||||
LibraryEntry::Folder(_) => return Err(EngineError::Param("a folder can't be placed; name the items in it".into())),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
None => match (opt_u64(p, "symbol")?, opt_u64(p, "bitmap")?, opt_u64(p, "sound")?) {
|
||||
(Some(i), None, None) => vec![LibraryItem::Symbol(SymbolId(i))],
|
||||
(None, Some(i), None) => vec![LibraryItem::Bitmap(anicraft_doc::BitmapId(i))],
|
||||
(None, None, Some(i)) => vec![LibraryItem::Sound(anicraft_doc::SoundId(i))],
|
||||
_ => return Err(EngineError::Param("name one item ('symbol', 'bitmap' or 'sound'), or a list in 'items'".into())),
|
||||
},
|
||||
};
|
||||
if items.is_empty() {
|
||||
return Err(EngineError::Param("nothing to place".into()));
|
||||
}
|
||||
let sym = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' or 'bitmap' is required".into()))?);
|
||||
if s.doc.symbol(sym).is_none() {
|
||||
return Err(EngineError::State(format!("no symbol with id {}", sym.0)));
|
||||
let mut sound = None;
|
||||
for &i in &items {
|
||||
if !s.doc.has_item(i) {
|
||||
return Err(EngineError::State(match i {
|
||||
LibraryItem::Symbol(id) => format!("no symbol with id {}", id.0),
|
||||
LibraryItem::Bitmap(id) => format!("no bitmap with id {}", id.0),
|
||||
LibraryItem::Sound(id) => format!("no sound with id {} in the library", id.0),
|
||||
}));
|
||||
}
|
||||
match i {
|
||||
LibraryItem::Symbol(id) if crate::editing::would_nest(s, id) => return Err(EngineError::State("a symbol can't be placed inside itself".into())),
|
||||
LibraryItem::Sound(id) => {
|
||||
if sound.is_some_and(|x| x != id) {
|
||||
return Err(EngineError::State("a keyframe holds one sound; place sounds one at a time, on different keyframes or layers".into()));
|
||||
}
|
||||
sound = Some(id);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0);
|
||||
let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0);
|
||||
if !(x.is_finite() && y.is_finite()) || x.abs() > 1.0e6 || y.abs() > 1.0e6 {
|
||||
return Err(EngineError::Param("'x' and 'y' must be within a million pixels of the origin".into()));
|
||||
}
|
||||
let mut placed = Vec::new();
|
||||
for &i in &items {
|
||||
match i {
|
||||
LibraryItem::Symbol(id) => placed.push(place_symbol(s, id, x, y)?),
|
||||
LibraryItem::Bitmap(id) => placed.push(place_bitmap(s, id, x, y)?),
|
||||
LibraryItem::Sound(_) => {}
|
||||
}
|
||||
}
|
||||
let mut out = json!({"element": placed.first().map(|e| e.0), "elements": placed.iter().map(|e| e.0).collect::<Vec<_>>()});
|
||||
if let Some(id) = sound {
|
||||
if s.active_layer().is_some_and(|l| l.locked) || s.timeline().locked_by_folder(s.layer) {
|
||||
return Err(EngineError::State("the active layer is locked; unlock it to put a sound on it".into()));
|
||||
}
|
||||
out["sound"] = crate::cmds_sound::place(s, &json!({"sound": id.0, "extend": true}))?;
|
||||
}
|
||||
if !placed.is_empty() {
|
||||
s.select_only(placed.iter().copied());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn place_symbol(s: &mut Session, sym: SymbolId, x: f32, y: f32) -> Result<ElementId> {
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
@@ -773,17 +853,14 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
kind: ElementKind::Symbol { symbol: sym, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() },
|
||||
};
|
||||
s.editable_keyframe()?.elements.push(Arc::new(el));
|
||||
s.select_only([id]);
|
||||
Ok(json!({"element": id.0}))
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> Result<Value> {
|
||||
fn place_bitmap(s: &mut Session, bitmap: anicraft_doc::BitmapId, x: f32, y: f32) -> Result<ElementId> {
|
||||
let (name, w, h) = match s.doc.bitmap(bitmap) {
|
||||
Some(b) => (b.name.clone(), b.width as f32, b.height as f32),
|
||||
None => return Err(EngineError::State(format!("no bitmap with id {}", bitmap.0))),
|
||||
};
|
||||
let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0);
|
||||
let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0);
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
@@ -799,6 +876,5 @@ fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> R
|
||||
}),
|
||||
};
|
||||
s.editable_keyframe()?.elements.push(Arc::new(el));
|
||||
s.select_only([id]);
|
||||
Ok(json!({"element": id.0}))
|
||||
Ok(id)
|
||||
}
|
||||
@@ -267,7 +267,7 @@ fn faucet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// The layers `draw.erase_all` clears: visible, unlocked layers that hold artwork (not folders,
|
||||
/// not the camera), with the number of elements at the playhead on each.
|
||||
pub(crate) fn erasable_layers(s: &Session) -> Vec<(anicraft_doc::LayerId, usize)> {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
tl.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !tl.locked_by_folder(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera))
|
||||
@@ -283,7 +283,7 @@ fn erase_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let (scene, frame) = (s.scene, s.frame);
|
||||
let mut erased = 0;
|
||||
for (id, _) in &layers {
|
||||
let Some(layer) = s.doc.timeline_mut(scene).layer_mut(*id) else { continue };
|
||||
let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).layer_mut(*id) else { continue };
|
||||
let Some(i) = layer.keyframe_index_at(frame) else { continue };
|
||||
let Some(kf) = layer.keyframe_mut(i) else { continue };
|
||||
erased += kf.elements.len();
|
||||
|
||||
@@ -298,7 +298,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Clips and masks (ADR 0021): a folder named after the file holding, top first, each
|
||||
// run of artwork, with a mask layer over the runs that are masked.
|
||||
let made = layers.len() + masks + 1;
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
if tl.layers.len() + made > 1000 {
|
||||
return Err(EngineError::State(format!("importing {} would make {made} layers; a timeline holds at most 1000", path.display())));
|
||||
}
|
||||
@@ -343,7 +343,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
cl.keyframes = keys(els);
|
||||
stack.push(cl);
|
||||
}
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
for (k, l) in stack.into_iter().enumerate() {
|
||||
tl.layers.insert((at + k).min(tl.layers.len()), Arc::new(l));
|
||||
}
|
||||
|
||||
@@ -83,11 +83,11 @@ fn copy_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let count = count_param(p)?;
|
||||
let mut ids = target_layers(s, p)?;
|
||||
// Top to bottom, whatever order the params gave.
|
||||
let order: Vec<LayerId> = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect();
|
||||
let order: Vec<LayerId> = s.timeline().layers.iter().map(|l| l.id).collect();
|
||||
ids.sort_by_key(|id| order.iter().position(|o| o == id));
|
||||
let mut layers = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
let l = s.doc.timeline(s.scene).layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
let l = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
layers.push(FrameSlice { name: l.name.clone(), keys: slice(l, frame, count)? });
|
||||
}
|
||||
let clip = FrameClipboard { layers, count, symbols: Vec::new(), sounds: Vec::new() };
|
||||
@@ -123,7 +123,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if frame.saturating_add(clip.count) > MAX_FRAME || s.frame_count().saturating_add(clip.count) > MAX_FRAME {
|
||||
return Err(EngineError::State("the timeline would grow past its maximum length".into()));
|
||||
}
|
||||
let mut row = s.doc.timeline(s.scene).layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?;
|
||||
let mut row = s.timeline().layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?;
|
||||
import_symbols(s, &clip.symbols);
|
||||
for x in &clip.sounds {
|
||||
if s.doc.sound(x.id).is_none() {
|
||||
@@ -135,8 +135,8 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut pasted = Vec::new();
|
||||
for sl in &clip.layers {
|
||||
// Missing layers below are created, named after the copied ones.
|
||||
if s.doc.timeline(s.scene).layers.get(row).is_none() {
|
||||
if s.doc.timeline(s.scene).layers.len() >= 1000 {
|
||||
if s.timeline().layers.get(row).is_none() {
|
||||
if s.timeline().layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let id = LayerId(s.doc.alloc_id());
|
||||
@@ -145,7 +145,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The pasted keys are its frames (no stray blank frame at 1).
|
||||
l.keyframes.clear();
|
||||
}
|
||||
s.doc.timeline_mut(s.scene).layers.push(Arc::new(l));
|
||||
crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).layers.push(Arc::new(l));
|
||||
}
|
||||
let mut keys = Vec::with_capacity(sl.keys.len());
|
||||
for k in &sl.keys {
|
||||
@@ -161,7 +161,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
keys.push(Arc::new(k));
|
||||
}
|
||||
let Some(layer) = s.doc.timeline_mut(s.scene).layers.get_mut(row).map(Arc::make_mut) else { continue };
|
||||
let Some(layer) = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).layers.get_mut(row).map(Arc::make_mut) else { continue };
|
||||
crate::cmds_camera::keys_fit(layer.kind, keys.iter().map(|k| &**k))?;
|
||||
if layer.keyframe_index_at(frame).is_some() {
|
||||
insert_keyframe_at(layer, frame, true)?;
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fn find(s: &Session, p: &Value) -> Result<(LayerId, usize, HintSide)> {
|
||||
let (lid, frame) = target(s, p)?;
|
||||
let lid = lid.unwrap_or(s.layer);
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let layer = tl.layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?;
|
||||
let (i, side) = layer.hint_tween_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is not in a shape tween; select the span and use Insert › Create Shape Tween", frame + 1)))?;
|
||||
Ok((lid, i, side))
|
||||
@@ -36,7 +36,7 @@ fn find(s: &Session, p: &Value) -> Result<(LayerId, usize, HintSide)> {
|
||||
/// The same, for an edit: refuses locked layers.
|
||||
fn find_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Layer, usize, HintSide)> {
|
||||
let (lid, i, side) = find(s, p)?;
|
||||
if s.doc.timeline(s.scene).locked_by_folder(lid) {
|
||||
if s.timeline().locked_by_folder(lid) {
|
||||
return Err(EngineError::State("the layer is in a locked folder".into()));
|
||||
}
|
||||
let layer = s.layer_mut(Some(lid))?;
|
||||
@@ -125,7 +125,7 @@ fn clear_hints(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn list_hints(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (lid, i, side) = find(s, p)?;
|
||||
let layer = s.doc.timeline(s.scene).layer(lid).ok_or_else(|| EngineError::State("no such layer".into()))?;
|
||||
let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State("no such layer".into()))?;
|
||||
let (Some(a), Some(b)) = (layer.hint_keyframe(i, HintSide::Start), layer.hint_keyframe(i, HintSide::End)) else { return Err(EngineError::State("the keyframe went away".into())) };
|
||||
let hints: Vec<Value> = a
|
||||
.hints
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
//! Library management (ADR 0050): folders, renaming, moving, duplicating and deleting items,
|
||||
//! use counts and unused items, bitmap smoothing, and Swap Symbol.
|
||||
//!
|
||||
//! An item or folder is named in params as `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}`
|
||||
//! or `{"folder": id}`. Sorting and filtering the list are views (the shell's); `library.items`
|
||||
//! gives a script everything it needs to do the same.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::library::{MAX_FOLDER_DEPTH, MAX_FOLDERS};
|
||||
use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryFolder, LibraryItem, Paint, SoundId, SymbolId, SymbolKind, Timeline};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("library.items", "List Library", "", None, "{} every folder (id, name, parent, path) and item (symbol | bitmap | sound id, kind, name, folder, path, uses, unused) in Library order; `uses` counts instances, bitmap fills and keyframe sounds once per keyframe", false, items as crate::RunFn),
|
||||
c("library.new_folder", "New Folder", "", None, "{name? (default: the next free “Folder n”), parent?: folder id} → {folder, name}; names are unique within a folder (case aside) and can't hold “/”", true, new_folder),
|
||||
c("library.rename", "Rename", "", None, "{symbol | bitmap | sound | folder: id, name} renames a Library item or folder; the name must be free in its folder (case aside) and can't hold “/”", true, rename),
|
||||
c("library.move", "Move to Folder", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..], to: folder id | null (the top level)} moves items and folders (with what they hold) into a folder; a folder can't go inside itself, and a name the folder already has stops the move", true, move_to),
|
||||
c("library.duplicate", "Duplicate Symbol", "", None, "{symbol, name? (default: “<name> copy”)} → {symbol, name}: a copy in the same folder, with its own layers and elements and no linkage class", true, duplicate),
|
||||
c("library.delete", "Delete", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..]} deletes items and folders with everything in them; instances of deleted symbols, shapes filled with deleted bitmaps and keyframes' deleted sounds go too (asks first when anything deleted is in use or a folder isn't empty)", true, delete),
|
||||
c("library.unused", "Select Unused Items", "", None, "{} → {items: [..]} the items nothing in the movie reaches: not in a scene, nor inside a symbol that is; symbols with a linkage class count as used", false, unused),
|
||||
c("library.delete_unused", "Delete Unused Items", "", None, "{} deletes every item `library.unused` lists (asks first)", true, delete_unused),
|
||||
c("library.set_smoothing", "Allow Smoothing", "", None, "{bitmap, on?: bool (default: toggle)} whether the bitmap is filtered when scaled or turned (off: hard-edged pixels)", true, set_smoothing),
|
||||
c("element.swap_bitmap", "Swap Bitmap", "", None, "{bitmap} the selected bitmaps and bitmap-filled shapes show another bitmap: a placed bitmap keeps its transform and top-left corner and takes the new bitmap's size; a bitmap fill keeps its shape and fill transform", true, |s, p| s.each_layer(false, |s| swap_bitmap(s, p))),
|
||||
c("element.swap_symbol", "Swap Symbol", "", None, "{symbol} the selected instances show another symbol, keeping their transform, colour effect, blending, filters, looping, actions and instance name", true, |s, p| s.each_layer(false, |s| swap_symbol(s, p))),
|
||||
]
|
||||
}
|
||||
|
||||
/// Most entries one command takes.
|
||||
const MAX_ENTRIES: usize = 100_000;
|
||||
|
||||
/// The entry a JSON object names: `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}` or
|
||||
/// `{"folder": id}`.
|
||||
pub(crate) fn entry_of(v: &Value) -> Result<LibraryEntry> {
|
||||
let id = |k: &str| v.get(k).and_then(Value::as_u64);
|
||||
match (id("symbol"), id("bitmap"), id("sound"), id("folder")) {
|
||||
(Some(i), None, None, None) => Ok(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(i)))),
|
||||
(None, Some(i), None, None) => Ok(LibraryEntry::Item(LibraryItem::Bitmap(BitmapId(i)))),
|
||||
(None, None, Some(i), None) => Ok(LibraryEntry::Item(LibraryItem::Sound(SoundId(i)))),
|
||||
(None, None, None, Some(i)) => Ok(LibraryEntry::Folder(FolderId(i))),
|
||||
_ => Err(EngineError::Param("name one Library entry: {\"symbol\" | \"bitmap\" | \"sound\" | \"folder\": id}".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `entry` as params name it.
|
||||
pub fn entry_json(e: LibraryEntry) -> Value {
|
||||
match e {
|
||||
LibraryEntry::Item(LibraryItem::Symbol(i)) => json!({"symbol": i.0}),
|
||||
LibraryEntry::Item(LibraryItem::Bitmap(i)) => json!({"bitmap": i.0}),
|
||||
LibraryEntry::Item(LibraryItem::Sound(i)) => json!({"sound": i.0}),
|
||||
LibraryEntry::Folder(f) => json!({"folder": f.0}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries in list `key`, each checked to exist (no repeats).
|
||||
pub(crate) fn entries_of(s: &Session, p: &Value, key: &str) -> Result<Vec<LibraryEntry>> {
|
||||
let list = p.get(key).and_then(Value::as_array).ok_or_else(|| EngineError::Param(format!("param '{key}' must be a list of Library entries")))?;
|
||||
if list.len() > MAX_ENTRIES {
|
||||
return Err(EngineError::Param(format!("at most {MAX_ENTRIES} entries")));
|
||||
}
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
let mut seen = HashSet::new();
|
||||
for v in list {
|
||||
let e = entry_of(v)?;
|
||||
if !s.doc.has_entry(e) {
|
||||
return Err(EngineError::State(format!("the Library has no {}", describe(e))));
|
||||
}
|
||||
if seen.insert(e) {
|
||||
out.push(e);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn describe(e: LibraryEntry) -> String {
|
||||
match e {
|
||||
LibraryEntry::Item(LibraryItem::Symbol(i)) => format!("symbol {}", i.0),
|
||||
LibraryEntry::Item(LibraryItem::Bitmap(i)) => format!("bitmap {}", i.0),
|
||||
LibraryEntry::Item(LibraryItem::Sound(i)) => format!("sound {}", i.0),
|
||||
LibraryEntry::Folder(f) => format!("folder {}", f.0),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn opt_folder(s: &Session, p: &Value, key: &str) -> Result<Option<FolderId>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => {
|
||||
let id = v.as_u64().map(FolderId).ok_or_else(|| EngineError::Param(format!("param '{key}' must be a folder id or null")))?;
|
||||
if s.doc.folder(id).is_none() {
|
||||
return Err(EngineError::State(format!("the Library has no folder {}", id.0)));
|
||||
}
|
||||
Ok(Some(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbol type `key` names (`graphic`, `movie_clip` or `button`).
|
||||
pub(crate) fn kind_of(key: &str) -> Result<SymbolKind> {
|
||||
match key {
|
||||
"graphic" => Ok(SymbolKind::Graphic),
|
||||
"movie_clip" | "movie clip" => Ok(SymbolKind::MovieClip),
|
||||
"button" => Ok(SymbolKind::Button),
|
||||
_ => Err(EngineError::Param(format!("unknown symbol type '{key}' (graphic, movie_clip or button)"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn kind_key(k: SymbolKind) -> &'static str {
|
||||
match k {
|
||||
SymbolKind::Graphic => "graphic",
|
||||
SymbolKind::MovieClip => "movie_clip",
|
||||
SymbolKind::Button => "button",
|
||||
}
|
||||
}
|
||||
|
||||
fn items(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let d = &s.doc;
|
||||
let uses = d.library_uses();
|
||||
let unused: HashSet<LibraryItem> = d.unused_items().into_iter().collect();
|
||||
let folders: Vec<Value> = d
|
||||
.library_tree
|
||||
.folders
|
||||
.iter()
|
||||
.map(|f| json!({"folder": f.id.0, "name": f.name, "parent": f.parent.map(|p| p.0), "path": d.entry_path(LibraryEntry::Folder(f.id))}))
|
||||
.collect();
|
||||
let items: Vec<Value> = d
|
||||
.library_items()
|
||||
.map(|i| {
|
||||
let e = LibraryEntry::Item(i);
|
||||
let mut v = entry_json(e);
|
||||
v["name"] = json!(d.item_name(i));
|
||||
v["folder"] = json!(d.parent_of(e).map(|f| f.0));
|
||||
v["path"] = json!(d.entry_path(e));
|
||||
v["uses"] = json!(uses.get(&i).copied().unwrap_or(0));
|
||||
v["unused"] = json!(unused.contains(&i));
|
||||
match i {
|
||||
LibraryItem::Symbol(id) => {
|
||||
if let Some(sym) = d.symbol(id) {
|
||||
v["kind"] = json!(kind_key(sym.kind));
|
||||
v["frames"] = json!(sym.timeline.frame_count());
|
||||
v["linkage"] = json!(sym.linkage.as_ref().map(|l| &l.class));
|
||||
}
|
||||
}
|
||||
LibraryItem::Bitmap(id) => {
|
||||
if let Some(b) = d.bitmap(id) {
|
||||
v["kind"] = json!("bitmap");
|
||||
v["width"] = json!(b.width);
|
||||
v["height"] = json!(b.height);
|
||||
v["smoothing"] = json!(b.smoothing);
|
||||
}
|
||||
}
|
||||
LibraryItem::Sound(id) => {
|
||||
if let Some(x) = d.sound(id) {
|
||||
v["kind"] = json!("sound");
|
||||
v["seconds"] = json!(x.seconds());
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"folders": folders, "items": items, "unused": unused.len()}))
|
||||
}
|
||||
|
||||
fn new_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let parent = opt_folder(s, p, "parent")?;
|
||||
if s.doc.library_tree.folders.len() >= MAX_FOLDERS {
|
||||
return Err(EngineError::State(format!("the Library holds at most {MAX_FOLDERS} folders")));
|
||||
}
|
||||
if parent.is_some_and(|f| s.doc.folder_depth(f) >= MAX_FOLDER_DEPTH) {
|
||||
return Err(EngineError::State(format!("folders nest at most {MAX_FOLDER_DEPTH} deep")));
|
||||
}
|
||||
let name = match opt_str(p, "name")? {
|
||||
Some(n) => s.doc.check_name(parent, n, None).map_err(|e| EngineError::Param(e.to_string()))?,
|
||||
None => s.doc.numbered_name(parent, "Folder", 1),
|
||||
};
|
||||
let id = FolderId(s.doc.alloc_id());
|
||||
Arc::make_mut(&mut s.doc.library_tree).folders.push(LibraryFolder { id, name: name.clone(), parent });
|
||||
Ok(json!({"folder": id.0, "name": name}))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let e = entry_of(p)?;
|
||||
if !s.doc.has_entry(e) {
|
||||
return Err(EngineError::State(format!("the Library has no {}", describe(e))));
|
||||
}
|
||||
let name = s.doc.check_name(s.doc.parent_of(e), str_req(p, "name")?, Some(e)).map_err(|err| EngineError::Param(err.to_string()))?;
|
||||
let d = &mut s.doc;
|
||||
match e {
|
||||
LibraryEntry::Item(LibraryItem::Symbol(id)) => {
|
||||
if let Some(x) = d.library.iter_mut().find(|x| x.id == id) {
|
||||
Arc::make_mut(x).name = name.clone();
|
||||
}
|
||||
}
|
||||
LibraryEntry::Item(LibraryItem::Bitmap(id)) => {
|
||||
if let Some(x) = d.bitmaps.iter_mut().find(|x| x.id == id) {
|
||||
Arc::make_mut(x).name = name.clone();
|
||||
}
|
||||
}
|
||||
LibraryEntry::Item(LibraryItem::Sound(id)) => {
|
||||
if let Some(x) = d.sounds.iter_mut().find(|x| x.id == id) {
|
||||
Arc::make_mut(x).name = name.clone();
|
||||
}
|
||||
}
|
||||
LibraryEntry::Folder(id) => {
|
||||
if let Some(f) = Arc::make_mut(&mut d.library_tree).folders.iter_mut().find(|f| f.id == id) {
|
||||
f.name = name.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut v = entry_json(e);
|
||||
v["name"] = json!(name);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn move_to(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let list = entries_of(s, p, "items")?;
|
||||
if p.get("to").is_none() {
|
||||
return Err(EngineError::Param("param 'to' is required: a folder id, or null for the top level".into()));
|
||||
}
|
||||
let to = opt_folder(s, p, "to")?;
|
||||
let mut moved = 0;
|
||||
for e in list {
|
||||
if s.doc.parent_of(e) == to {
|
||||
continue;
|
||||
}
|
||||
if let LibraryEntry::Folder(f) = e {
|
||||
if to.is_some_and(|t| s.doc.folder_within(t, f)) {
|
||||
return Err(EngineError::State(format!("“{}” can't go inside itself", s.doc.entry_name(e).unwrap_or(""))));
|
||||
}
|
||||
if to.map_or(0, |t| s.doc.folder_depth(t)) + s.doc.folder_height(f) > MAX_FOLDER_DEPTH {
|
||||
return Err(EngineError::State(format!("folders nest at most {MAX_FOLDER_DEPTH} deep")));
|
||||
}
|
||||
}
|
||||
let name = s.doc.entry_name(e).unwrap_or("").to_string();
|
||||
if s.doc.name_taken(to, &name, Some(e)) {
|
||||
let place = to.and_then(|t| s.doc.folder(t)).map_or_else(|| "The top level of the Library".to_string(), |f| format!("“{}”", f.name));
|
||||
return Err(EngineError::State(format!("{place} already has an item named “{name}”; rename one of them first")));
|
||||
}
|
||||
s.doc.place_entry(e, to);
|
||||
moved += 1;
|
||||
}
|
||||
Ok(json!({"moved": moved, "to": to.map(|f| f.0)}))
|
||||
}
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?);
|
||||
let Some(src) = s.doc.symbol(id) else {
|
||||
return Err(EngineError::State(format!("no symbol with id {}", id.0)));
|
||||
};
|
||||
let parent = s.doc.parent_of(LibraryEntry::Item(LibraryItem::Symbol(id)));
|
||||
let name = match opt_str(p, "name")? {
|
||||
Some(n) => s.doc.check_name(parent, n, None).map_err(|e| EngineError::Param(e.to_string()))?,
|
||||
None => s.doc.unique_name(parent, &format!("{} copy", src.name)),
|
||||
};
|
||||
let copy = s.doc.duplicate_symbol(id, name.clone()).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?;
|
||||
Ok(json!({"symbol": copy.0, "name": name}))
|
||||
}
|
||||
|
||||
/// What deleting `entries` takes: the items (folders expanded into what they hold) and the
|
||||
/// folders.
|
||||
pub(crate) fn deletion(s: &Session, entries: &[LibraryEntry]) -> (Vec<LibraryItem>, Vec<FolderId>) {
|
||||
let mut items: Vec<LibraryItem> = Vec::new();
|
||||
let mut folders: Vec<FolderId> = Vec::new();
|
||||
let add = |e: LibraryEntry, items: &mut Vec<LibraryItem>, folders: &mut Vec<FolderId>| match e {
|
||||
LibraryEntry::Item(i) if !items.contains(&i) => items.push(i),
|
||||
LibraryEntry::Folder(f) if !folders.contains(&f) => folders.push(f),
|
||||
_ => {}
|
||||
};
|
||||
for &e in entries {
|
||||
add(e, &mut items, &mut folders);
|
||||
if let LibraryEntry::Folder(f) = e {
|
||||
for inner in s.doc.folder_contents(f) {
|
||||
add(inner, &mut items, &mut folders);
|
||||
}
|
||||
}
|
||||
}
|
||||
(items, folders)
|
||||
}
|
||||
|
||||
/// Takes every reference to `gone` off `tl` (instances, bitmap-filled shapes, keyframe sounds),
|
||||
/// un-sharing only the layers and keyframes that had one. How many references went.
|
||||
fn strip(tl: &mut Timeline, gone: &HashSet<LibraryItem>) -> usize {
|
||||
let refers = |e: &anicraft_doc::Element| match &e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => gone.contains(&LibraryItem::Symbol(*symbol)),
|
||||
ElementKind::Shape(sh) => matches!(&sh.fill, Some(Paint::Bitmap { bitmap, .. }) if gone.contains(&LibraryItem::Bitmap(*bitmap))),
|
||||
ElementKind::Text(_) | ElementKind::Camera => false,
|
||||
};
|
||||
let sounds = |k: &anicraft_doc::Keyframe| k.sound.as_ref().is_some_and(|f| gone.contains(&LibraryItem::Sound(f.sound)));
|
||||
let hit = |k: &anicraft_doc::Keyframe| sounds(k) || k.elements.iter().any(|e| refers(e));
|
||||
let mut n = 0;
|
||||
for l in tl.layers.iter_mut().filter(|l| l.keyframes.iter().any(|k| hit(k))) {
|
||||
for k in Arc::make_mut(l).keyframes.iter_mut().filter(|k| hit(k)) {
|
||||
let k = Arc::make_mut(k);
|
||||
if sounds(k) {
|
||||
k.sound = None;
|
||||
n += 1;
|
||||
}
|
||||
let before = k.elements.len();
|
||||
k.elements.retain(|e| !refers(e));
|
||||
n += before - k.elements.len();
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Deletes `items` and `folders` from the Library and every use of the items from the movie.
|
||||
fn remove(s: &mut Session, items: &[LibraryItem], folders: &[FolderId]) -> Value {
|
||||
let gone: HashSet<LibraryItem> = items.iter().copied().collect();
|
||||
let mut uses = 0;
|
||||
if !gone.is_empty() {
|
||||
for scene in &mut s.doc.scenes {
|
||||
if strip_needed(&scene.timeline, &gone) {
|
||||
uses += strip(&mut Arc::make_mut(scene).timeline, &gone);
|
||||
}
|
||||
}
|
||||
s.doc.library.retain(|x| !gone.contains(&LibraryItem::Symbol(x.id)));
|
||||
s.doc.bitmaps.retain(|x| !gone.contains(&LibraryItem::Bitmap(x.id)));
|
||||
s.doc.sounds.retain(|x| !gone.contains(&LibraryItem::Sound(x.id)));
|
||||
for sym in &mut s.doc.library {
|
||||
if strip_needed(&sym.timeline, &gone) {
|
||||
uses += strip(&mut Arc::make_mut(sym).timeline, &gone);
|
||||
}
|
||||
}
|
||||
// The fill swatch may hold a deleted bitmap (picked with the Eyedropper).
|
||||
if let Some(Paint::Bitmap { bitmap, .. }) = &s.style.fill_paint
|
||||
&& gone.contains(&LibraryItem::Bitmap(*bitmap))
|
||||
{
|
||||
s.style.fill_paint = None;
|
||||
}
|
||||
}
|
||||
let dead: HashSet<FolderId> = folders.iter().copied().collect();
|
||||
if !dead.is_empty() || s.doc.library_tree.placed.keys().any(|i| gone.contains(i)) {
|
||||
let t = Arc::make_mut(&mut s.doc.library_tree);
|
||||
t.placed.retain(|i, f| !gone.contains(i) && !dead.contains(f));
|
||||
t.folders.retain(|f| !dead.contains(&f.id));
|
||||
// A folder whose parent went (it was named on its own) goes to the top level.
|
||||
let ids: HashSet<FolderId> = t.folders.iter().map(|f| f.id).collect();
|
||||
for f in &mut t.folders {
|
||||
if f.parent.is_some_and(|p| !ids.contains(&p)) {
|
||||
f.parent = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
json!({"deleted": items.len(), "folders": folders.len(), "uses": uses})
|
||||
}
|
||||
|
||||
fn strip_needed(tl: &Timeline, gone: &HashSet<LibraryItem>) -> bool {
|
||||
let mut any = false;
|
||||
anicraft_doc::library::visit_refs(tl, |i| any |= gone.contains(&i));
|
||||
any
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let list = entries_of(s, p, "items")?;
|
||||
if list.is_empty() {
|
||||
return Err(EngineError::State("nothing to delete".into()));
|
||||
}
|
||||
let (items, folders) = deletion(s, &list);
|
||||
Ok(remove(s, &items, &folders))
|
||||
}
|
||||
|
||||
fn unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let list: Vec<Value> = s.doc.unused_items().into_iter().map(|i| entry_json(LibraryEntry::Item(i))).collect();
|
||||
Ok(json!({"items": list}))
|
||||
}
|
||||
|
||||
fn delete_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let items = s.doc.unused_items();
|
||||
Ok(remove(s, &items, &[]))
|
||||
}
|
||||
|
||||
fn set_smoothing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?);
|
||||
let on = opt_bool(p, "on")?;
|
||||
let b = s.doc.bitmaps.iter_mut().find(|b| b.id == id).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", id.0)))?;
|
||||
let on = on.unwrap_or(!b.smoothing);
|
||||
if b.smoothing != on {
|
||||
Arc::make_mut(b).smoothing = on;
|
||||
}
|
||||
Ok(json!({"bitmap": id.0, "smoothing": on}))
|
||||
}
|
||||
|
||||
fn swap_symbol(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let to = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?);
|
||||
if s.doc.symbol(to).is_none() {
|
||||
return Err(EngineError::State(format!("no symbol with id {}", to.0)));
|
||||
}
|
||||
// Inside a symbol open for editing (ADR 0045), never swap in that symbol or one that holds it.
|
||||
if crate::editing::would_nest(s, to) {
|
||||
return Err(EngineError::State("a symbol can't be placed inside itself".into()));
|
||||
}
|
||||
let mut swapped = 0;
|
||||
for e in s.selected_elements_mut()? {
|
||||
if let ElementKind::Symbol { symbol, .. } = &mut e.kind {
|
||||
*symbol = to;
|
||||
swapped += 1;
|
||||
}
|
||||
}
|
||||
if swapped == 0 {
|
||||
return Err(EngineError::State("select a symbol instance to swap".into()));
|
||||
}
|
||||
Ok(json!({"swapped": swapped, "symbol": to.0}))
|
||||
}
|
||||
|
||||
/// Swap Bitmap (ADR 0053), as Animate's Properties offer on a bitmap. A bitmap placed from the
|
||||
/// Library is a rectangle of the bitmap's size filled with it: it keeps its transform (so its
|
||||
/// top-left corner stays put) and becomes the new bitmap's size, and its name follows when it was
|
||||
/// the old bitmap's. Any other shape filled with a bitmap keeps its outline and fill transform.
|
||||
fn swap_bitmap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let to = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?);
|
||||
let Some(new) = s.doc.bitmap(to).map(|b| (b.name.clone(), b.width as f32, b.height as f32)) else {
|
||||
return Err(EngineError::State(format!("no bitmap with id {}", to.0)));
|
||||
};
|
||||
let sizes: std::collections::HashMap<BitmapId, (String, f32, f32)> = s.doc.bitmaps.iter().map(|b| (b.id, (b.name.clone(), b.width as f32, b.height as f32))).collect();
|
||||
let mut swapped = 0;
|
||||
for e in s.selected_elements_mut()? {
|
||||
let ElementKind::Shape(sh) = &mut e.kind else { continue };
|
||||
let Some(Paint::Bitmap { bitmap, repeat, matrix }) = &mut sh.fill else { continue };
|
||||
let old = *bitmap;
|
||||
*bitmap = to;
|
||||
swapped += 1;
|
||||
if old == to {
|
||||
continue;
|
||||
}
|
||||
if let Some((name, w, h)) = sizes.get(&old)
|
||||
&& !*repeat
|
||||
&& *matrix == anicraft_geom::Affine::IDENTITY
|
||||
&& *sh.path == anicraft_geom::Path::rect(0.0, 0.0, *w, *h)
|
||||
{
|
||||
sh.path = Arc::new(anicraft_geom::Path::rect(0.0, 0.0, new.1, new.2));
|
||||
if e.name == *name {
|
||||
e.name.clone_from(&new.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if swapped == 0 {
|
||||
return Err(EngineError::State("select a bitmap, or a shape filled with one, to swap".into()));
|
||||
}
|
||||
Ok(json!({"swapped": swapped, "bitmap": to.0}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "library_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "place_tests.rs"]
|
||||
mod place_tests;
|
||||
@@ -50,6 +50,9 @@ pub struct ClipLayer {
|
||||
pub layer: LayerId,
|
||||
pub name: String,
|
||||
pub elements: Vec<Element>,
|
||||
/// The keyframe (its first frame) it was copied from with Edit Multiple Frames (ADR 0051),
|
||||
/// where Paste in Place on Multiple Frames puts it back; `None` for a copy on one frame.
|
||||
pub frame: Option<u32>,
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
@@ -101,9 +104,9 @@ fn copy(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut copied = Vec::with_capacity(layers.len());
|
||||
for l in layers {
|
||||
let elements: Vec<Element> = s.elements_on(l).iter().filter(|e| s.selection.contains(l, e.id)).map(|e| (**e).clone()).collect();
|
||||
let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default();
|
||||
if !elements.is_empty() {
|
||||
copied.push(ClipLayer { layer: l, name, elements });
|
||||
copied.push(ClipLayer { layer: l, name, elements, frame: None });
|
||||
}
|
||||
}
|
||||
let all: Vec<Element> = copied.iter().flat_map(|c| c.elements.iter().cloned()).collect();
|
||||
@@ -141,32 +144,46 @@ fn clip_element_bounds(s: &Session, e: &Element) -> Rect {
|
||||
/// layers below it, in order, with missing layers created at the bottom named after the copied
|
||||
/// ones, as Paste Frames does.
|
||||
fn paste_targets(s: &mut Session) -> Result<Vec<LayerId>> {
|
||||
let n = s.clipboard.layers.len();
|
||||
// Each layer the artwork came from once (a copy with Edit Multiple Frames has one entry per
|
||||
// keyframe, ADR 0051), in order.
|
||||
let mut src: Vec<(LayerId, String)> = Vec::new();
|
||||
for c in &s.clipboard.layers {
|
||||
if !src.iter().any(|(l, _)| *l == c.layer) {
|
||||
src.push((c.layer, c.name.clone()));
|
||||
}
|
||||
}
|
||||
let dst = layer_targets(s, &src)?;
|
||||
Ok(s.clipboard.layers.iter().map(|c| src.iter().position(|(l, _)| *l == c.layer).and_then(|i| dst.get(i)).copied().unwrap_or(s.layer)).collect())
|
||||
}
|
||||
|
||||
/// [`paste_targets`] for each source layer (its id and name).
|
||||
fn layer_targets(s: &mut Session, src: &[(LayerId, String)]) -> Result<Vec<LayerId>> {
|
||||
let n = src.len();
|
||||
if n <= 1 {
|
||||
return Ok(vec![s.layer]);
|
||||
}
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let drawable = |s: &Session, l: &Layer| s.selectable(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature);
|
||||
let home: Vec<LayerId> = s.clipboard.layers.iter().filter_map(|c| tl.layer(c.layer).filter(|l| l.name == c.name && drawable(s, l)).map(|l| l.id)).collect();
|
||||
let home: Vec<LayerId> = src.iter().filter_map(|(id, name)| tl.layer(*id).filter(|l| l.name == *name && drawable(s, l)).map(|l| l.id)).collect();
|
||||
if home.len() == n {
|
||||
return Ok(home);
|
||||
}
|
||||
let at = s.active_layer_index().unwrap_or(0);
|
||||
let mut out = vec![s.layer];
|
||||
out.extend(tl.layers.iter().skip(at + 1).filter(|l| drawable(s, l)).map(|l| l.id).take(n - 1));
|
||||
let names: Vec<String> = s.clipboard.layers.iter().skip(out.len()).map(|c| c.name.clone()).collect();
|
||||
let names: Vec<String> = src.iter().skip(out.len()).map(|(_, name)| name.clone()).collect();
|
||||
for name in names {
|
||||
if s.doc.timeline(s.scene).layers.len() >= 1000 {
|
||||
if s.timeline().layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
let id = LayerId(s.doc.alloc_id());
|
||||
let count = s.doc.timeline(s.scene).layers.len();
|
||||
let count = s.timeline().layers.len();
|
||||
let mut layer = Layer::new(id, name);
|
||||
if let Some(k) = layer.keyframe_mut(0) {
|
||||
k.duration = s.frame_count().max(1);
|
||||
}
|
||||
layer.color = crate::cmds_timeline::layer_color(count + 1);
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
tl.layers.push(Arc::new(layer));
|
||||
tl.repair_masks();
|
||||
out.push(id);
|
||||
@@ -174,10 +191,19 @@ fn paste_targets(s: &mut Session) -> Result<Vec<LayerId>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether pasting the clipboard would put a symbol inside itself: inside an open symbol, an
|
||||
/// instance of it (or of one using it).
|
||||
pub(crate) fn clipboard_nests(s: &Session) -> bool {
|
||||
s.clipboard.layers.iter().flat_map(|c| &c.elements).any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { symbol, .. } if crate::editing::would_nest(s, symbol)))
|
||||
}
|
||||
|
||||
fn paste_with(s: &mut Session, offset: Vec2) -> Result<Value> {
|
||||
if s.clipboard.is_empty() {
|
||||
return Err(EngineError::State("the clipboard is empty".into()));
|
||||
}
|
||||
if clipboard_nests(s) {
|
||||
return Err(EngineError::State("a symbol can't be pasted inside itself".into()));
|
||||
}
|
||||
import_symbols(s, &s.clipboard.symbols.clone());
|
||||
let targets = paste_targets(s)?;
|
||||
let copied = s.clipboard.layers.clone();
|
||||
@@ -191,21 +217,27 @@ fn paste_with(s: &mut Session, offset: Vec2) -> Result<Value> {
|
||||
sel.extend_on(layer, fresh);
|
||||
}
|
||||
s.selection = sel;
|
||||
if let Some(&first) = targets.first()
|
||||
&& targets.len() > 1
|
||||
let mut layers: Vec<LayerId> = Vec::new();
|
||||
for l in &targets {
|
||||
if !layers.contains(l) {
|
||||
layers.push(*l);
|
||||
}
|
||||
}
|
||||
if let Some(&first) = layers.first()
|
||||
&& layers.len() > 1
|
||||
{
|
||||
s.layer = first;
|
||||
}
|
||||
let mut v = json!({"pasted": all, "merged": merged});
|
||||
if targets.len() > 1 {
|
||||
v["layers"] = json!(targets.iter().map(|l| l.0).collect::<Vec<_>>());
|
||||
if layers.len() > 1 {
|
||||
v["layers"] = json!(layers.iter().map(|l| l.0).collect::<Vec<_>>());
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Pastes `elements` moved by `offset` into the active layer's keyframe at the playhead; their
|
||||
/// new ids, and whether raw shapes merged.
|
||||
fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec<ElementId>, bool)> {
|
||||
pub(crate) fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec<ElementId>, bool)> {
|
||||
let mut fresh = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
let mut raw = Vec::new();
|
||||
|
||||
@@ -75,7 +75,7 @@ pub(crate) fn begin_edit(layer: LayerId, kf: &mut Keyframe, frame: u32) -> Optio
|
||||
/// the base back. On the span's first frame a property without keys changes the base itself.
|
||||
pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) {
|
||||
let scene = s.scene;
|
||||
let Some(layer) = s.doc.timeline_mut(scene).layer_mut(e.layer) else { return };
|
||||
let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).layer_mut(e.layer) else { return };
|
||||
let Some(kf) = layer.keyframe_starting_at(e.start).and_then(|i| layer.keyframe_mut(i)) else { return };
|
||||
let Some(idx) = kf.elements.iter().position(|x| x.id == e.target) else { return };
|
||||
let Some(after) = kf.elements.get(idx).map(|x| (**x).clone()) else { return };
|
||||
@@ -550,7 +550,7 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (lid, frame) = target(s, p)?;
|
||||
let lid = lid.unwrap_or(s.layer);
|
||||
let (start, ids) = {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let layer = tl.layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?;
|
||||
if layer.kind == LayerKind::Folder {
|
||||
return Err(EngineError::State("a folder holds layers, not frames; pick a layer inside it".into()));
|
||||
@@ -704,7 +704,7 @@ fn set_ease(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (lid, frame) = target(s, p)?;
|
||||
let lid = lid.unwrap_or(s.layer);
|
||||
let layer = s.doc.timeline(s.scene).layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?;
|
||||
let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?;
|
||||
let kf = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?;
|
||||
let m = kf.motion.as_ref().ok_or_else(|| EngineError::State(format!("frame {} is not in a motion tween", frame + 1)))?;
|
||||
let base = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e));
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param, style};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, Shape};
|
||||
use anicraft_geom::edit::{ANCHOR, polyline_path, simplify};
|
||||
use anicraft_geom::edit::{ANCHOR, C1, C2, polyline_path, simplify};
|
||||
use anicraft_geom::{Affine, Path, PathCmd, Vec2, fit_curve};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeSet;
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
true,
|
||||
draw_freehand,
|
||||
),
|
||||
c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy}", true, move_points),
|
||||
c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy, smooth?: bool} (a handle moved alone at a smooth anchor turns the other one with it, keeping its length, unless smooth is false: Alt breaks the pair)", true, move_points),
|
||||
c("path.add_point", "Add Anchor Point", "", None, "{id, x, y, slop?}", true, add_point),
|
||||
c("path.delete_points", "Delete Anchor Points", "", None, "{id, cmds: [..]}", true, delete_points),
|
||||
c("path.convert_point", "Convert Anchor Point", "", None, "{id, cmd, smooth: bool}", true, convert_point),
|
||||
@@ -149,6 +149,7 @@ fn move_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let slot = pair.get(1).and_then(Value::as_u64).filter(|s| *s <= 2).ok_or_else(bad)?;
|
||||
wanted.push((usize::try_from(cmd).unwrap_or(usize::MAX), slot as u8));
|
||||
}
|
||||
let smooth = opt_bool(p, "smooth")?.unwrap_or(true);
|
||||
let (sh, m) = shape_mut(s, p)?;
|
||||
let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?;
|
||||
let local = inv.apply_vector(d);
|
||||
@@ -168,15 +169,42 @@ fn move_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set.insert((cmd, slot));
|
||||
}
|
||||
}
|
||||
// The other handle of a smooth anchor whose handle moves alone (ADR 0045), as it was.
|
||||
let partners: Vec<(usize, u8, Vec2, Vec2)> = if smooth { set.iter().filter_map(|&(cmd, slot)| partner(path, &set, cmd, slot)).collect() } else { Vec::new() };
|
||||
for &(cmd, slot) in &set {
|
||||
if let Some(q) = path.point(cmd, slot) {
|
||||
path.set_point(cmd, slot, q + local);
|
||||
}
|
||||
}
|
||||
for (cmd, slot, anchor, handle) in partners {
|
||||
if let Some(k) = path.point(cmd, slot) {
|
||||
path.set_point(cmd, slot, anicraft_geom::raw::turned_opposite(anchor, handle + local, k));
|
||||
}
|
||||
}
|
||||
check_path(path)?;
|
||||
Ok(json!({"moved": set.len()}))
|
||||
}
|
||||
|
||||
/// For handle `(cmd, slot)` moving alone: the other handle of its anchor when the anchor is smooth
|
||||
/// and that handle stays (`(cmd, slot)`), with the anchor and this handle where they are now.
|
||||
fn partner(path: &Path, moving: &BTreeSet<(usize, u8)>, cmd: usize, slot: u8) -> Option<(usize, u8, Vec2, Vec2)> {
|
||||
// Slot 2 is the in-handle of anchor `cmd`; slot 1 the out-handle of the anchor before.
|
||||
let anchor = match slot {
|
||||
C2 => path.canonical_anchor(cmd),
|
||||
C1 => path.canonical_anchor(cmd.checked_sub(1)?),
|
||||
_ => return None,
|
||||
};
|
||||
let (i, o) = path.anchor_segments(anchor);
|
||||
let other = if slot == C2 { (o?, C1) } else { (i?, C2) };
|
||||
if moving.contains(&other) || path.anchor_group(anchor).iter().any(|g| g.1 == ANCHOR && moving.contains(g)) {
|
||||
return None;
|
||||
}
|
||||
let (a, h, k) = (path.point(anchor, ANCHOR)?, path.point(cmd, slot)?, path.point(other.0, other.1)?);
|
||||
// A quadratic's control is both its ends' handle: turning it would bend the other end.
|
||||
let cubic = |c: usize| matches!(path.cmds.get(c), Some(PathCmd::CubicTo(..)));
|
||||
(cubic(other.0) && anicraft_geom::raw::smooth_at(a, h, k)).then_some((other.0, other.1, a, h))
|
||||
}
|
||||
|
||||
fn add_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 1000.0);
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> {
|
||||
const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw", "frames"];
|
||||
match id {
|
||||
"edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"),
|
||||
"edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" => {
|
||||
"edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" | "frames.cut" | "frames.copy" | "frames.paste" => {
|
||||
Err("plug-ins don't use your clipboard")
|
||||
}
|
||||
_ => match id.split('.').next().unwrap_or("") {
|
||||
@@ -75,8 +75,7 @@ impl Host for SessionHost<'_> {
|
||||
fn document_view(s: &Session) -> Value {
|
||||
let st = &s.doc.stage;
|
||||
let layers: Vec<Value> = s
|
||||
.doc
|
||||
.timeline(s.scene)
|
||||
.timeline()
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "parent": l.parent.map(|p| p.0)}))
|
||||
|
||||
@@ -158,7 +158,7 @@ fn hit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Makes the layer of what is at `at` (within `slop`) the active one, as a click does.
|
||||
fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) {
|
||||
pub(crate) fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) {
|
||||
if let Some((layer, _)) = s.hit_test(at, slop)
|
||||
&& layer != s.layer
|
||||
{
|
||||
@@ -263,6 +263,38 @@ pub(crate) fn edit_edge(s: &mut Session, id: ElementId, cmd: usize, old: &Cubic,
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Changes every copy of the edge `old` (stage space) into `new` (same ends): in every raw shape on
|
||||
/// the editable keyframe, or only in `only` (a drawing object edits itself alone). Returns the
|
||||
/// shapes that changed.
|
||||
pub(crate) fn follow_edge(s: &mut Session, only: Option<ElementId>, old: &Cubic, new: &Cubic) -> Result<Vec<ElementId>> {
|
||||
let area = new.iter().chain(old).fold(Rect::EMPTY, |mut r, q| {
|
||||
r.include(*q);
|
||||
r
|
||||
});
|
||||
let kf = s.editable_keyframe()?;
|
||||
let mut changed = Vec::new();
|
||||
for e in kf.elements.iter_mut() {
|
||||
let take = match only {
|
||||
Some(id) => e.id == id,
|
||||
None => mergeable(e).is_some_and(|x| !reach(x, &e.transform).intersect(&area).is_empty()),
|
||||
};
|
||||
if !take {
|
||||
continue;
|
||||
}
|
||||
let (Some(inv), ElementKind::Shape(x)) = (e.transform.inverse(), &e.kind) else { continue };
|
||||
let mut edited = (*x.path).clone();
|
||||
if rawgeom::follow(&mut edited, &rawgeom::transform(old, &inv), &rawgeom::transform(new, &inv), SNAP / e.transform.mean_scale().max(1e-6)) == 0 {
|
||||
continue;
|
||||
}
|
||||
check_extent(&edited)?;
|
||||
if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind {
|
||||
x.path = Arc::new(edited);
|
||||
}
|
||||
changed.push(e.id);
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
// ----- moving shared points ---------------------------------------------------------------------
|
||||
|
||||
fn points_param(p: &Value) -> Result<Option<Vec<(ElementId, usize)>>> {
|
||||
@@ -497,6 +529,31 @@ fn snap_point(els: &[Arc<Element>], to: Vec2, radius: f32, moving: &[(ElementId,
|
||||
snap_to(&t, to, radius).map(|(q, k, _)| (q, k))
|
||||
}
|
||||
|
||||
/// Where a point drawn at `p` snaps (the Line, Rectangle, Oval, PolyStar and Pen tools, ADR
|
||||
/// 0045): the nearest anchor within `radius`, else the nearest point on a line or fill edge, of
|
||||
/// what the stage shows near it.
|
||||
pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32) -> Option<(Vec2, SnapTo)> {
|
||||
if !(radius > 0.0 && p.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let dl = s.display_list();
|
||||
let mut t = Targets::default();
|
||||
for item in dl.items.iter() {
|
||||
if t.points.len() + t.segs.len() > MAX_TARGETS {
|
||||
break;
|
||||
}
|
||||
let pad = item.stroke.as_ref().map_or(0.0, |st| st.reach() * item.transform.mean_scale());
|
||||
if !item.path.bounds().transformed(&item.transform).inflate(pad + radius).contains(p) {
|
||||
continue;
|
||||
}
|
||||
let mut path = (*item.path).clone();
|
||||
path.close_explicitly();
|
||||
t.points.extend(path.editable_anchors().into_iter().map(|(_, q)| item.transform.apply(q)));
|
||||
t.segs.extend((0..path.cmds.len().min(MAX_TARGETS)).filter_map(|k| rawgeom::segment_cubic(&path, k)).map(|c| rawgeom::transform(&c, &item.transform)));
|
||||
}
|
||||
snap_to(&t, p, radius).map(|(q, k, _)| (q, k))
|
||||
}
|
||||
|
||||
/// After the selection moved: the extra move that snaps one of its anchors (the nearest to
|
||||
/// `from` when given, else whichever comes closest) onto an anchor or line of the shapes that
|
||||
/// did not move, within `radius`.
|
||||
@@ -555,7 +612,7 @@ fn select_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// What each layer has under the marquee, from one display list: wholly inside, or (raw
|
||||
// shapes) partly.
|
||||
let mut found: Vec<(LayerId, Vec<ElementId>, Vec<ElementId>)> = Vec::new();
|
||||
let layers: Vec<LayerId> = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect();
|
||||
let layers: Vec<LayerId> = s.timeline().layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect();
|
||||
for l in layers {
|
||||
let (mut picked, mut partial) = (Vec::new(), Vec::new());
|
||||
for e in s.elements_on(l) {
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Adding and deleting the anchors of raw drawings, making them smooth or corners, and where a
|
||||
//! point being drawn snaps (ADR 0045; issue #42 §1 and §3).
|
||||
//!
|
||||
//! A layer's merged drawing stores a shared point once in each shape that has it (ADR 0031), so
|
||||
//! these work on positions, as the Subselection tool shows them (`raw.points`), and change every
|
||||
//! copy alike: an added point is added to every shape with that edge; a deleted one is joined
|
||||
//! across in every shape that has it, so the drawing stays connected.
|
||||
|
||||
use crate::cmds_raw::{activate_layer_at, check_extent, follow_edge, positions_param, remerge_in_place, snap_drawn};
|
||||
use crate::merge::{mergeable, reach};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ElementId, ElementKind, Keyframe};
|
||||
use anicraft_geom::planar::SNAP;
|
||||
use anicraft_geom::raw::{self as rawgeom, Seg, Sub};
|
||||
use anicraft_geom::{Path, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c(
|
||||
"raw.add_point",
|
||||
"Add Anchor Point",
|
||||
"",
|
||||
None,
|
||||
"{x, y, slop?} adds an anchor on the raw line or fill edge at (x, y): every raw shape with that edge gets it, and the curve keeps its shape; returns where it is",
|
||||
true,
|
||||
add_point as crate::RunFn,
|
||||
),
|
||||
c(
|
||||
"raw.delete_points",
|
||||
"Delete Anchor Points",
|
||||
"",
|
||||
None,
|
||||
"{points: [[x, y], ..]} deletes the raw anchors at those positions (as raw.points lists them): every shape that has one is joined across it, so the drawing stays connected; a free end shortens its line; a shape left with nothing is removed; a point where three or more edges meet is kept",
|
||||
true,
|
||||
delete_points,
|
||||
),
|
||||
c(
|
||||
"raw.convert_points",
|
||||
"Convert Anchor Points",
|
||||
"",
|
||||
None,
|
||||
"{points: [[x, y], ..], smooth: bool} makes the raw anchors at those positions smooth (their handles in one line) or corners (handles drawn in), in every shape that has them",
|
||||
true,
|
||||
convert_points,
|
||||
),
|
||||
c(
|
||||
"draw.snap",
|
||||
"Snap Point",
|
||||
"",
|
||||
None,
|
||||
"{x, y, snap} where a point drawn at (x, y) snaps while Snap to Objects is on: the nearest anchor within `snap` stage units, else the nearest point on a line or fill edge; returns {x, y, snapped: {x, y, to} | null}",
|
||||
false,
|
||||
snap_cmd,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Ends of segments this near a position are at it (the copies of a shared point lie within
|
||||
/// `SNAP` of each other, ADR 0042).
|
||||
const ENDS: f32 = 1.5 * SNAP;
|
||||
|
||||
/// The raw shapes on `kf` near `at`: index, whether filled, and stage-space subpaths.
|
||||
fn near(kf: &Keyframe, at: Vec2) -> Vec<(usize, bool, Vec<Sub>)> {
|
||||
kf.elements
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, e)| {
|
||||
let sh = mergeable(e)?;
|
||||
reach(sh, &e.transform).contains(at).then(|| (i, sh.fill.is_some(), rawgeom::subpaths(&sh.path.transformed(&e.transform))))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The distinct edges leaving `at` among `shapes`.
|
||||
fn edges(shapes: &[(usize, bool, Vec<Sub>)], at: Vec2) -> Vec<Seg> {
|
||||
rawgeom::distinct_edges(shapes.iter().flat_map(|(_, _, subs)| rawgeom::edges_at(subs, at, ENDS)), ENDS)
|
||||
}
|
||||
|
||||
fn points(p: &Value) -> Result<Vec<Vec2>> {
|
||||
let pts = positions_param(p, "points")?;
|
||||
if pts.is_empty() {
|
||||
return Err(EngineError::Param("param 'points' is required: the positions of the anchors, as raw.points lists them".into()));
|
||||
}
|
||||
Ok(pts)
|
||||
}
|
||||
|
||||
// ----- adding ------------------------------------------------------------------------------------
|
||||
|
||||
fn add_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 100.0);
|
||||
activate_layer_at(s, at, slop);
|
||||
// The nearest raw line or fill edge.
|
||||
let mut best: Option<(f32, Vec2)> = None;
|
||||
for e in s.visible_elements() {
|
||||
let Some(sh) = mergeable(&e) else { continue };
|
||||
if !reach(sh, &e.transform).inflate(slop).contains(at) {
|
||||
continue;
|
||||
}
|
||||
let mut path = (*sh.path).clone();
|
||||
path.close_explicitly();
|
||||
let half = sh.stroke.as_ref().map_or(0.0, |st| st.width * 0.5 * e.transform.mean_scale());
|
||||
if let Some((cmd, t, d)) = path.nearest_segment(at, &e.transform)
|
||||
&& d <= slop + half
|
||||
&& best.is_none_or(|b| d < b.0)
|
||||
&& let Some(q) = path.segment_point(cmd, t)
|
||||
{
|
||||
best = Some((d, e.transform.apply(q)));
|
||||
}
|
||||
}
|
||||
let (_, q) = best.ok_or_else(|| EngineError::State("no line or fill edge of a merged drawing there".into()))?;
|
||||
let kf = s.editable_keyframe()?;
|
||||
if near(kf, q).iter().any(|(_, _, subs)| subs.iter().flat_map(|sb| &sb.segs).any(|g| g.c[0].distance(q) <= 2.0 * SNAP || g.c[3].distance(q) <= 2.0 * SNAP)) {
|
||||
return Err(EngineError::State("there is a point there already".into()));
|
||||
}
|
||||
let mut changed = Vec::new();
|
||||
for e in kf.elements.iter_mut() {
|
||||
let Some(sh) = mergeable(e) else { continue };
|
||||
if !reach(sh, &e.transform).contains(q) {
|
||||
continue;
|
||||
}
|
||||
let Some(inv) = e.transform.inverse() else { continue };
|
||||
let mut path = (*sh.path).clone();
|
||||
path.close_explicitly();
|
||||
let len = path.cmds.len();
|
||||
// Splits the segment through the point (de Casteljau: the curve is unchanged).
|
||||
rawgeom::anchors_at(&mut path, inv.apply(q), SNAP / e.transform.mean_scale().max(1e-6));
|
||||
if path.cmds.len() == len {
|
||||
continue;
|
||||
}
|
||||
if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind {
|
||||
x.path = Arc::new(path);
|
||||
}
|
||||
changed.push(e.id);
|
||||
}
|
||||
if changed.is_empty() {
|
||||
return Err(EngineError::State("cannot add a point there".into()));
|
||||
}
|
||||
// Nothing moved, so nothing merges: the point stays until a merge finds it on a straight
|
||||
// line that it no longer bends (issue #42 §1).
|
||||
Ok(json!({"x": q.x, "y": q.y, "changed": changed.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
// ----- deleting ----------------------------------------------------------------------------------
|
||||
|
||||
fn delete_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = points(p)?;
|
||||
let (mut deleted, mut kept) = (0usize, 0usize);
|
||||
let mut changed: Vec<ElementId> = Vec::new();
|
||||
let mut removed: Vec<ElementId> = Vec::new();
|
||||
for at in pts {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let shapes = near(kf, at);
|
||||
let edges = edges(&shapes, at);
|
||||
let joined = match edges.as_slice() {
|
||||
[] => continue,
|
||||
[_] => None,
|
||||
[a, b] => Some(rawgeom::join(a, b).ok_or_else(|| EngineError::Param("cannot join the lines across that point".into()))?),
|
||||
_ => {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut gone: Vec<ElementId> = Vec::new();
|
||||
let mut any = false;
|
||||
for (i, filled, mut subs) in shapes {
|
||||
if !rawgeom::delete_anchor(&mut subs, at, &edges, joined.as_ref(), ENDS) {
|
||||
continue;
|
||||
}
|
||||
rawgeom::tidy(&mut subs, filled);
|
||||
let Some(e) = kf.elements.get_mut(i) else { continue };
|
||||
any = true;
|
||||
if subs.is_empty() {
|
||||
gone.push(e.id);
|
||||
continue;
|
||||
}
|
||||
let Some(inv) = e.transform.inverse() else { continue };
|
||||
let path: Path = rawgeom::from_subpaths(&subs).transformed(&inv);
|
||||
check_extent(&path)?;
|
||||
if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind {
|
||||
x.path = Arc::new(path);
|
||||
}
|
||||
if !changed.contains(&e.id) {
|
||||
changed.push(e.id);
|
||||
}
|
||||
}
|
||||
kf.elements.retain(|e| !gone.contains(&e.id));
|
||||
changed.retain(|id| !gone.contains(id));
|
||||
removed.extend(gone);
|
||||
deleted += usize::from(any);
|
||||
}
|
||||
if deleted == 0 {
|
||||
return Err(EngineError::State(if kept > 0 { "a point where three or more lines meet can't be deleted; delete a line there instead".into() } else { "no point of a merged drawing there".into() }));
|
||||
}
|
||||
let here = s.layer;
|
||||
s.selection.retain(|l, id| l != here || !removed.contains(&id));
|
||||
// Joined runs and fills merge again with what they touch, as after any edit.
|
||||
remerge_in_place(s, &changed)?;
|
||||
Ok(json!({"deleted": deleted, "kept": kept, "removed": removed.iter().map(|e| e.0).collect::<Vec<_>>(), "selected": s.selection.id_list()}))
|
||||
}
|
||||
|
||||
// ----- smooth and corner -------------------------------------------------------------------------
|
||||
|
||||
fn convert_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = points(p)?;
|
||||
let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required".into()))?;
|
||||
let mut changed: Vec<ElementId> = Vec::new();
|
||||
let mut converted = 0usize;
|
||||
for at in pts {
|
||||
let kf = s.editable_keyframe()?;
|
||||
let edges = edges(&near(kf, at), at);
|
||||
let edits: Vec<(Seg, Seg)> = if smooth {
|
||||
match edges.as_slice() {
|
||||
[a, b] => rawgeom::smooth_pair(a, b).map(|(na, nb)| vec![(*a, na), (*b, nb)]).unwrap_or_default(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
} else {
|
||||
edges.iter().filter_map(|e| rawgeom::corner(e).map(|n| (*e, n))).collect()
|
||||
};
|
||||
converted += usize::from(!edits.is_empty());
|
||||
for (old, new) in edits {
|
||||
for id in follow_edge(s, None, &old.c, &new.c)? {
|
||||
if !changed.contains(&id) {
|
||||
changed.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
remerge_in_place(s, &changed)?;
|
||||
Ok(json!({"converted": converted, "changed": changed.len()}))
|
||||
}
|
||||
|
||||
// ----- snapping while drawing --------------------------------------------------------------------
|
||||
|
||||
fn snap_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0));
|
||||
Ok(match snap_drawn(s, at, radius) {
|
||||
Some((q, kind)) => json!({"x": q.x, "y": q.y, "snapped": {"x": q.x, "y": q.y, "to": kind.key()}}),
|
||||
None => json!({"x": at.x, "y": at.y, "snapped": null}),
|
||||
})
|
||||
}
|
||||
@@ -10,8 +10,8 @@
|
||||
//! Which anchors are selected is view state, kept by the editor (as for drawing objects): the
|
||||
//! commands here report anchors and handles by stage position, and take positions back.
|
||||
|
||||
use crate::cmds_raw::{check_extent, edit_edge, remerge_in_place};
|
||||
use crate::merge::mergeable;
|
||||
use crate::cmds_raw::{check_extent, edit_edge, follow_edge, remerge_in_place};
|
||||
use crate::merge::{mergeable, reach};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind};
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Handle",
|
||||
"",
|
||||
None,
|
||||
"{id, cmd, slot: 1|2, dx, dy, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false)",
|
||||
"{id, cmd, slot: 1|2, dx, dy, smooth?: bool, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false); at a smooth anchor the other handle turns to stay opposite, keeping its length (unless smooth is false: Alt breaks the pair)",
|
||||
true,
|
||||
move_handle,
|
||||
),
|
||||
@@ -378,7 +378,7 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer);
|
||||
let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.timeline().locked_by_folder(s.layer);
|
||||
let empty = json!({"selected": s.selection.id_list(), "anchors": []});
|
||||
if !usable || !(r.width() > 0.0 || r.height() > 0.0) {
|
||||
return Ok(empty);
|
||||
@@ -400,6 +400,32 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ----- handles -----------------------------------------------------------------------------------
|
||||
|
||||
/// The other curve at the anchor of handle `slot` of `old` (stage space) when the anchor is smooth
|
||||
/// there: the one edge leaving it whose handle lies opposite this one ([`rawgeom::smooth_at`]), in
|
||||
/// any raw shape on the layer (or in `el` alone, a drawing object). Oriented from the anchor.
|
||||
fn opposite_handle(els: &[Arc<Element>], el: &Element, raw: bool, old: &Cubic, slot: usize) -> Option<rawgeom::Seg> {
|
||||
let (a, h) = if slot == 1 { (old[0], old[1]) } else { (old[3], old[2]) };
|
||||
let dragged = rawgeom::Seg { c: if slot == 1 { *old } else { [old[3], old[2], old[1], old[0]] }, line: false };
|
||||
let tol = 1.5 * SNAP;
|
||||
let mut subs = Vec::new();
|
||||
let from = |e: &Element| match &e.kind {
|
||||
ElementKind::Shape(sh) => rawgeom::subpaths(&sh.path.transformed(&e.transform)),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if raw {
|
||||
for e in els.iter().filter(|e| mergeable(e).is_some_and(|sh| reach(sh, &e.transform).contains(a))) {
|
||||
subs.extend(from(e));
|
||||
}
|
||||
} else {
|
||||
subs = from(el);
|
||||
}
|
||||
let edges = rawgeom::distinct_edges(rawgeom::edges_at(&subs, a, tol), tol);
|
||||
let mut found = edges.into_iter().filter(|f| !rawgeom::same_edge(f, &dragged, tol) && !f.line && rawgeom::smooth_at(a, h, f.c[1]));
|
||||
let f = found.next()?;
|
||||
// Two candidates: a junction, not a smooth pair.
|
||||
found.next().is_none().then_some(f)
|
||||
}
|
||||
|
||||
fn move_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?);
|
||||
let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?;
|
||||
@@ -426,7 +452,18 @@ fn move_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
bounds.move_to(new[0]).cubic_to(new[1], new[2], new[3]);
|
||||
check_extent(&bounds)?;
|
||||
let raw = mergeable(el).is_some();
|
||||
let changed = edit_edge(s, id, cmd, &old, &new, raw)?;
|
||||
// A smooth anchor's other handle turns with this one (ADR 0045).
|
||||
let partner = if opt_bool(p, "smooth")?.unwrap_or(true) { opposite_handle(&els, el, raw, &old, slot).map(|f| (f, new[slot])) } else { None };
|
||||
let mut changed = edit_edge(s, id, cmd, &old, &new, raw)?;
|
||||
if let Some((f, h)) = partner {
|
||||
let a = f.c[0];
|
||||
let turned = rawgeom::Seg { c: [a, rawgeom::turned_opposite(a, h, f.c[1]), f.c[2], f.c[3]], line: false };
|
||||
for e in follow_edge(s, (!raw).then_some(id), &f.c, &turned.c)? {
|
||||
if !changed.contains(&e) {
|
||||
changed.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if raw && merge_after {
|
||||
remerge_in_place(s, &changed)?;
|
||||
}
|
||||
|
||||
@@ -32,9 +32,11 @@ pub(crate) fn target_scene(s: &Session, p: &Value) -> Result<usize> {
|
||||
|
||||
/// Opens scene `i` at its first frame, on its top layer.
|
||||
fn open_scene(s: &mut Session, i: usize) {
|
||||
// A scene is edited from its own timeline: open symbols close first (ADR 0045).
|
||||
s.exit_all();
|
||||
s.scene = i.min(s.doc.scenes.len().saturating_sub(1));
|
||||
s.frame = 0;
|
||||
s.layer = s.doc.timeline(s.scene).layers.first().map_or(LayerId(0), |l| l.id);
|
||||
s.layer = s.timeline().layers.first().map_or(LayerId(0), |l| l.id);
|
||||
s.selection.clear();
|
||||
}
|
||||
|
||||
|
||||
@@ -200,7 +200,7 @@ fn sound_param(s: &Session, p: &Value) -> Result<SoundId> {
|
||||
/// Place Sound: the sound goes on the keyframe covering the frame (a blank keyframe is made
|
||||
/// on an empty frame), Animate-style. With `extend`, the layer's last span grows to the sound's
|
||||
/// length so its waveform shows in full.
|
||||
fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = sound_param(s, p)?;
|
||||
let fps = s.doc.stage.fps;
|
||||
let want = s.doc.sound(id).map_or(1, |x| x.movie_frames(fps));
|
||||
@@ -239,7 +239,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// shaped over, which Custom starts from.
|
||||
let (lid, frame) = target(s, p)?;
|
||||
let fps = s.doc.stage.fps;
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let place = tl.layer(lid.unwrap_or(s.layer)).and_then(|l| l.keyframe_at(frame)).map(|k| (k.duration, s.doc.frame_count().saturating_sub(s.doc.scene_start(s.scene).saturating_add(k.start))));
|
||||
let sounds = s.doc.sounds.clone();
|
||||
let heard = move |fs: &FrameSound| match (sounds.iter().find(|x| x.id == fs.sound), place) {
|
||||
|
||||
@@ -54,11 +54,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// mask back into a normal layer (its masked layers become normal too).
|
||||
fn toggle_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
let is_mask = s.doc.timeline(s.scene).layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask;
|
||||
let is_mask = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask;
|
||||
let ty = if is_mask { "normal" } else { "mask" };
|
||||
set_type(s, id, ty)?;
|
||||
if !is_mask {
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
// The normal layer directly below, in the same folder, becomes masked.
|
||||
let mask_parent = tl.layer(id).and_then(|m| m.parent);
|
||||
if let Some(i) = tl.layers.iter().position(|l| l.id == id)
|
||||
@@ -76,7 +76,7 @@ fn toggle_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Draw a line on the guide; the layer's classic tweens travel along it.
|
||||
fn add_motion_guide(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
let Some(l) = tl.layers.get(i) else { return Err(EngineError::State("no such layer".into())) };
|
||||
if l.kind != LayerKind::Normal {
|
||||
@@ -100,7 +100,7 @@ fn add_motion_guide(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(k) = guide.keyframe_mut(0) {
|
||||
k.duration = s.frame_count().max(1);
|
||||
}
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
tl.layers.insert(i, Arc::new(guide));
|
||||
if let Some(l) = tl.layers.get_mut(i + 1) {
|
||||
Arc::make_mut(l).parent = Some(gid);
|
||||
@@ -127,7 +127,7 @@ fn set_layer_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> {
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder) {
|
||||
return Err(EngineError::State("a folder holds layers; it can't become another kind of layer".into()));
|
||||
@@ -162,8 +162,8 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
fn layer_type_json(s: &Session, id: LayerId) -> Value {
|
||||
let Some(l) = s.doc.timeline(s.scene).layer(id) else { return json!({}) };
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let Some(l) = s.timeline().layer(id) else { return json!({}) };
|
||||
let tl = s.timeline();
|
||||
let parent_kind = l.parent.and_then(|p| tl.layer(p)).map(|x| x.kind);
|
||||
let masked_by = l.parent.filter(|_| parent_kind == Some(LayerKind::Mask));
|
||||
let guided_by = l.parent.filter(|_| parent_kind == Some(LayerKind::Guide));
|
||||
@@ -200,7 +200,7 @@ pub(crate) fn target_layers(s: &Session, p: &Value) -> Result<Vec<LayerId>> {
|
||||
let mut out: Vec<LayerId> = Vec::with_capacity(ids.len());
|
||||
let mut folders = 0;
|
||||
for id in ids {
|
||||
let Some(l) = s.doc.timeline(s.scene).layer(id) else { return Err(EngineError::State(format!("no layer with id {}", id.0))) };
|
||||
let Some(l) = s.timeline().layer(id) else { return Err(EngineError::State(format!("no layer with id {}", id.0))) };
|
||||
// Folders have no frames: a range across a folder row acts on the layers only.
|
||||
if l.kind == LayerKind::Folder {
|
||||
folders += 1;
|
||||
@@ -463,7 +463,7 @@ fn move_keyframes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// keep their content. Lifting everything before placing anything makes overlapping row
|
||||
/// ranges (dragging two rows down by one) come out right.
|
||||
fn move_across_layers(s: &mut Session, p: &Value, from: u32, to: u32, by: i64, layer_by: i64) -> Result<Value> {
|
||||
let order: Vec<LayerId> = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect();
|
||||
let order: Vec<LayerId> = s.timeline().layers.iter().map(|l| l.id).collect();
|
||||
let mut rows: Vec<usize> = target_layers(s, p)?.iter().filter_map(|id| order.iter().position(|o| o == id)).collect();
|
||||
rows.sort_unstable();
|
||||
let mut plan = Vec::with_capacity(rows.len());
|
||||
@@ -661,7 +661,7 @@ pub(crate) fn layer_color(n: usize) -> anicraft_doc::Rgba {
|
||||
}
|
||||
|
||||
fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result<Value> {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
if tl.layers.len() >= 1000 {
|
||||
return Err(EngineError::State("too many layers (limit 1000)".into()));
|
||||
}
|
||||
@@ -688,7 +688,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result<Value> {
|
||||
k.duration = s.frame_count().max(1);
|
||||
}
|
||||
layer.color = layer_color(n);
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
tl.layers.insert(at, Arc::new(layer));
|
||||
tl.repair_masks();
|
||||
s.layer = id;
|
||||
@@ -700,7 +700,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result<Value> {
|
||||
/// stays where it is, in the mask's folder.
|
||||
fn delete_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
let is_folder = tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder);
|
||||
let range = if is_folder { tl.group_range(i) } else { i..i + 1 };
|
||||
@@ -709,7 +709,7 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::State("a document needs at least one layer to draw on".into()));
|
||||
}
|
||||
let up = tl.layers.get(i).and_then(|l| l.parent);
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
if !is_folder {
|
||||
for l in tl.layers.iter_mut().filter(|l| l.parent == Some(id)) {
|
||||
Arc::make_mut(l).parent = up;
|
||||
@@ -718,8 +718,8 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let removed: Vec<LayerId> = tl.layers.drain(range.clone()).map(|l| l.id).collect();
|
||||
tl.repair_masks();
|
||||
if removed.contains(&s.layer) {
|
||||
let j = range.start.min(s.doc.timeline(s.scene).layers.len().saturating_sub(1));
|
||||
s.layer = s.doc.timeline(s.scene).layers.get(j).map_or(LayerId(0), |l| l.id);
|
||||
let j = range.start.min(s.timeline().layers.len().saturating_sub(1));
|
||||
s.layer = s.timeline().layers.get(j).map_or(LayerId(0), |l| l.id);
|
||||
s.selection.clear();
|
||||
}
|
||||
Ok(json!({"deleted": id.0, "layers": removed.len()}))
|
||||
@@ -747,11 +747,11 @@ fn select_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = if let Some(id) = opt_u64(p, "layer")? {
|
||||
LayerId(id)
|
||||
} else if let Some(i) = opt_u64(p, "index")? {
|
||||
usize::try_from(i).ok().and_then(|i| s.doc.timeline(s.scene).layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))?
|
||||
usize::try_from(i).ok().and_then(|i| s.timeline().layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))?
|
||||
} else {
|
||||
return Err(EngineError::Param("pass {\"layer\": id} or {\"index\": n}".into()));
|
||||
};
|
||||
if s.doc.timeline(s.scene).layer(id).is_none() {
|
||||
if s.timeline().layer(id).is_none() {
|
||||
return Err(EngineError::State(format!("no layer with id {}", id.0)));
|
||||
}
|
||||
// A click on a layer's name in Animate: the layer becomes active with all of its artwork at
|
||||
@@ -774,7 +774,7 @@ fn select_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// where it landed: moving it in under a folder or mask puts it inside, moving it out frees it.
|
||||
fn move_layer(s: &mut Session, p: &Value, d: i64) -> Result<Value> {
|
||||
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
|
||||
let tl = s.doc.timeline_mut(s.scene);
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing);
|
||||
let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?;
|
||||
let n = tl.layers.len();
|
||||
if tl.layers.get(i).is_some_and(|l| matches!(l.kind, LayerKind::Mask | LayerKind::Folder)) {
|
||||
|
||||
@@ -40,7 +40,7 @@ fn plural(n: usize, word: &str) -> String {
|
||||
|
||||
fn target_layer<'a>(s: &'a Session, p: &Value) -> Option<&'a Layer> {
|
||||
let id = p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId);
|
||||
s.doc.timeline(s.scene).layer(id)
|
||||
s.timeline().layer(id)
|
||||
}
|
||||
|
||||
fn target_frame(s: &Session, p: &Value) -> u32 {
|
||||
@@ -59,7 +59,7 @@ fn lost_keys(s: &Session, p: &Value, hit: impl Fn(&Keyframe) -> bool) -> Vec<(St
|
||||
None => vec![p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId)],
|
||||
};
|
||||
ids.iter()
|
||||
.filter_map(|id| s.doc.timeline(s.scene).layer(*id))
|
||||
.filter_map(|id| s.timeline().layer(*id))
|
||||
.flat_map(|l| l.keyframes.iter().filter(|k| !k.elements.is_empty() && hit(k)).map(|k| (l.name.clone(), k.elements.len())))
|
||||
.collect()
|
||||
}
|
||||
@@ -144,6 +144,53 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"library.delete" => {
|
||||
// Routine when nothing deleted is in use and no folder holds anything (undo is there);
|
||||
// asks when instances go with it or a folder takes its contents (ADR 0050).
|
||||
let list = crate::cmds_library::entries_of(s, p, "items").ok()?;
|
||||
let (items, folders) = crate::cmds_library::deletion(s, &list);
|
||||
let uses = s.doc.library_uses();
|
||||
let used: Vec<&anicraft_doc::LibraryItem> = items.iter().filter(|i| uses.get(i).is_some_and(|n| *n > 0)).collect();
|
||||
let n_uses: usize = used.iter().filter_map(|i| uses.get(*i)).sum();
|
||||
let inside = items.len() + folders.len() - list.len();
|
||||
if used.is_empty() && inside == 0 {
|
||||
return None;
|
||||
}
|
||||
let what = match list.as_slice() {
|
||||
[one] => format!("“{}”", s.doc.entry_name(*one).unwrap_or("")),
|
||||
_ => plural(list.len(), "item"),
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
if inside > 0 {
|
||||
parts.push(format!("{what} {} {}, deleted with {}.", if list.len() == 1 { "holds" } else { "hold" }, plural(inside, "item"), if list.len() == 1 { "it" } else { "them" }));
|
||||
}
|
||||
if !used.is_empty() {
|
||||
parts.push(format!("{} used {} in the movie; {} go too.", if used.len() == 1 { "One of them is".to_string() } else { format!("{} of them are", used.len()) }, plural(n_uses, "time"), if n_uses == 1 { "that use" } else { "those uses" }));
|
||||
}
|
||||
parts.push("You can undo this.".into());
|
||||
Some(Confirmation {
|
||||
title: if inside > 0 && list.len() == 1 { "Delete folder?".into() } else { "Delete from Library?".into() },
|
||||
message: parts.join(" "),
|
||||
action: "Delete".into(),
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"library.delete_unused" => {
|
||||
let unused = s.doc.unused_items();
|
||||
let names: Vec<String> = unused.iter().take(5).filter_map(|i| s.doc.item_name(*i)).map(|n| format!("“{n}”")).collect();
|
||||
let more = unused.len().saturating_sub(names.len());
|
||||
(!unused.is_empty()).then(|| Confirmation {
|
||||
title: "Delete unused items?".into(),
|
||||
message: format!(
|
||||
"Nothing in the movie uses {}: {}{}. They leave the Library. You can undo this.",
|
||||
if unused.len() == 1 { "this item".to_string() } else { format!("these {} items", unused.len()) },
|
||||
names.join(", "),
|
||||
if more > 0 { format!(" and {more} more") } else { String::new() }
|
||||
),
|
||||
action: "Delete Unused".into(),
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"draw.erase_all" => {
|
||||
// Double-clicking the Eraser: everything on the stage at this frame (ADR 0034).
|
||||
let layers = crate::cmds_erase::erasable_layers(s);
|
||||
@@ -155,11 +202,11 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"camera.remove" => camera_removal(s, s.doc.timeline(s.scene).camera_layer()?),
|
||||
"camera.remove" => camera_removal(s, s.timeline().camera_layer()?),
|
||||
"bone.remove" => {
|
||||
// The bone's moves in every pose go with it (ADR 0043); one pose loses nothing.
|
||||
let id = anicraft_doc::BoneId(p.get("bone").and_then(Value::as_u64)?);
|
||||
let l = s.doc.timeline(s.scene).layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?;
|
||||
let l = s.timeline().layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?;
|
||||
let arm = l.armature.as_deref()?;
|
||||
let n = crate::cmds_bone::poses(l);
|
||||
let below = arm.subtree(id).len().saturating_sub(1);
|
||||
@@ -184,7 +231,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
}
|
||||
if l.kind == anicraft_doc::LayerKind::Folder {
|
||||
// A folder goes with everything in it.
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
let tl = s.timeline();
|
||||
let i = tl.layers.iter().position(|x| x.id == l.id)?;
|
||||
let inner = tl.layers.get(tl.group_range(i))?;
|
||||
let n = inner.len().saturating_sub(1);
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Editing a symbol's timeline in place (ADR 0045), as Animate's double-click on an instance does.
|
||||
//!
|
||||
//! The session keeps a stack of open symbols. While one is open, every command works on its
|
||||
//! timeline instead of the scene's ([`Session::timeline`]): its layers are the active layers, the
|
||||
//! playhead is its playhead, and positions are in its own space. So drawing, merge drawing (ADR
|
||||
//! 0031), the Selection tool (ADR 0041) and Subselection (ADR 0042) behave inside a symbol exactly
|
||||
//! as on the stage: they are the same commands on another timeline. Which symbol is open is view
|
||||
//! state, but undo snapshots keep it, so an undo goes back to where its change was made.
|
||||
//!
|
||||
//! The stage draws [`Session::stage_picture`]: the open symbol where its instance stands, over the
|
||||
//! timelines it sits in, dimmed.
|
||||
|
||||
use crate::history::StateId;
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Selection, Session};
|
||||
use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LoopMode, Symbol, SymbolId, SymbolKind, Timeline};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c(
|
||||
"symbol.edit",
|
||||
"Edit Symbols",
|
||||
"Edit",
|
||||
Some("Ctrl+E"),
|
||||
"{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)",
|
||||
false,
|
||||
edit as crate::RunFn,
|
||||
),
|
||||
c("symbol.exit", "Edit Document", "Edit", None, "{all?: bool} closes the open symbol (default: one level; all: back to the scene), selecting the instance it was opened from", false, exit),
|
||||
]
|
||||
}
|
||||
|
||||
/// Most symbols open inside each other at once.
|
||||
const MAX_LEVELS: usize = 32;
|
||||
/// How much the artwork around an open symbol shows (Animate dims it).
|
||||
const DIM: f32 = 0.35;
|
||||
|
||||
/// A symbol open for editing, and what to go back to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct EditLevel {
|
||||
pub symbol: SymbolId,
|
||||
/// The instance it was opened from, on the timeline below (none: from the Library).
|
||||
pub instance: Option<(LayerId, ElementId)>,
|
||||
/// Stage space from the symbol's space: where the instance stands (through every level).
|
||||
pub transform: Affine,
|
||||
/// The timeline below as it was: its active layer, playhead and selection.
|
||||
pub layer: LayerId,
|
||||
pub frame: u32,
|
||||
pub selection: Selection,
|
||||
}
|
||||
|
||||
/// The timeline being edited: the open symbol's, else the scene's.
|
||||
pub(crate) fn edited<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> &'a Timeline {
|
||||
match editing.last().and_then(|l| doc.symbol(l.symbol)) {
|
||||
Some(sym) => &sym.timeline,
|
||||
None => doc.timeline(scene),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`edited`] ([`Session::timeline`]), copy-on-write. Takes the fields, so a caller can keep using the session's others.
|
||||
pub(crate) fn edited_mut<'a>(doc: &'a mut Document, scene: usize, editing: &[EditLevel]) -> &'a mut Timeline {
|
||||
let open = editing.last().and_then(|l| doc.library.iter().position(|s| s.id == l.symbol));
|
||||
// (Borrowed only on the branch that returns it.)
|
||||
match open {
|
||||
Some(i) if i < doc.library.len() => &mut Arc::make_mut(&mut doc.library[i]).timeline,
|
||||
_ => doc.timeline_mut(scene),
|
||||
}
|
||||
}
|
||||
|
||||
/// How the stage shows the open symbol: its space on the stage is `translate(origin) ·
|
||||
/// scale(scale)`. `in_place` when that is exactly where its instance stands, so the artwork
|
||||
/// around it shows too.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct EditView {
|
||||
pub origin: Vec2,
|
||||
pub scale: f32,
|
||||
pub in_place: bool,
|
||||
}
|
||||
|
||||
/// What the stage draws: a document, the movie frame of it to render, and a state id for caching
|
||||
/// the picture (equal ids, equal pictures).
|
||||
#[derive(Clone)]
|
||||
pub struct StagePicture {
|
||||
pub doc: Document,
|
||||
pub frame: u32,
|
||||
pub state: StateId,
|
||||
/// The open symbol in front, when one is open: onion skin and Edit Multiple Frames compose
|
||||
/// its own frames (ADR 0051).
|
||||
pub front: Option<Arc<Front>>,
|
||||
}
|
||||
|
||||
/// The open symbol in a [`StagePicture`]: the picture's top layer `layer` shows `timeline` at its
|
||||
/// `frame`, placed by `at`. With onion skin on, that layer is drawn instead as the timeline's
|
||||
/// frames composed by [`crate::onion::compose_timeline`], placed the same way.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Front {
|
||||
pub layer: LayerId,
|
||||
pub timeline: Timeline,
|
||||
pub frame: u32,
|
||||
pub at: Affine,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The timeline being edited: the open symbol's (ADR 0045), else the scene's.
|
||||
pub fn timeline(&self) -> &Timeline {
|
||||
edited(&self.doc, self.scene, &self.editing)
|
||||
}
|
||||
|
||||
/// The symbol open for editing, if any.
|
||||
pub fn editing_symbol(&self) -> Option<SymbolId> {
|
||||
self.editing.last().map(|l| l.symbol)
|
||||
}
|
||||
|
||||
/// Closes levels whose symbol is gone (an undo, a Library deletion), from the first such.
|
||||
pub(crate) fn fix_editing(&mut self) {
|
||||
if let Some(i) = self.editing.iter().position(|l| self.doc.symbol(l.symbol).is_none()) {
|
||||
while self.editing.len() > i {
|
||||
self.exit_level();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn enter_level(&mut self, symbol: SymbolId, instance: Option<(LayerId, ElementId)>, transform: Affine, frame: u32) {
|
||||
self.editing.push(EditLevel { symbol, instance, transform, layer: self.layer, frame: self.frame, selection: std::mem::take(&mut self.selection) });
|
||||
// The top layer inside, at the frame the instance shows.
|
||||
self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id);
|
||||
self.frame = frame.min(self.timeline().frame_count().saturating_sub(1));
|
||||
self.revision += 1;
|
||||
self.dl_cache.replace(None);
|
||||
}
|
||||
|
||||
/// Closes the open symbol; the instance it was opened from is selected again. False when
|
||||
/// none is open.
|
||||
pub(crate) fn exit_level(&mut self) -> bool {
|
||||
let Some(l) = self.editing.pop() else { return false };
|
||||
self.layer = l.layer;
|
||||
self.frame = l.frame;
|
||||
self.selection = match l.instance {
|
||||
Some((layer, id)) => Selection::only(layer, [id]),
|
||||
None => l.selection,
|
||||
};
|
||||
self.revision += 1;
|
||||
self.dl_cache.replace(None);
|
||||
true
|
||||
}
|
||||
|
||||
/// Closes every open symbol (scene changes, opening a document).
|
||||
pub(crate) fn exit_all(&mut self) {
|
||||
while self.exit_level() {}
|
||||
}
|
||||
|
||||
/// How the stage shows the open symbol, `None` on the stage itself. In place when its
|
||||
/// instance is only moved and scaled evenly (the editor's view can follow that exactly);
|
||||
/// otherwise upright and at full size, with its registration point where the instance's is.
|
||||
pub fn edit_view(&self) -> Option<EditView> {
|
||||
let l = self.editing.last()?;
|
||||
let [a, b, c, d, e, f] = l.transform.m;
|
||||
let origin = Vec2::new(e, f);
|
||||
let even = b.abs() < 1e-5 && c.abs() < 1e-5 && a > 1e-4 && (a - d).abs() <= 1e-4 * a.max(1.0);
|
||||
let in_place = even && self.editing.iter().all(|l| l.instance.is_some());
|
||||
Some(if in_place { EditView { origin, scale: a, in_place } } else { EditView { origin, scale: 1.0, in_place: false } })
|
||||
}
|
||||
|
||||
/// What the stage draws (ADR 0045): the document at the playhead; while a symbol is open, its
|
||||
/// timeline at its playhead where its instance stands, over the timelines it sits in dimmed.
|
||||
pub fn stage_picture(&self) -> Arc<StagePicture> {
|
||||
let Some(view) = self.edit_view() else {
|
||||
return Arc::new(StagePicture { doc: self.doc.clone(), frame: self.doc.scene_start(self.scene).saturating_add(self.frame), state: self.state, front: None });
|
||||
};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
(self.state, self.scene, self.frame).hash(&mut h);
|
||||
for l in &self.editing {
|
||||
(l.symbol, l.instance, l.frame, l.transform.m.map(f32::to_bits)).hash(&mut h);
|
||||
}
|
||||
let key = h.finish();
|
||||
if let Some((k, pic)) = &*self.picture_cache.borrow()
|
||||
&& *k == key
|
||||
{
|
||||
return pic.clone();
|
||||
}
|
||||
let mut doc = self.doc.clone();
|
||||
let mut tl = Timeline::default();
|
||||
// The open symbol, in front.
|
||||
let at = Affine::translate(view.origin.x, view.origin.y).mul(&Affine::scale(view.scale, view.scale));
|
||||
let open = self.timeline().clone();
|
||||
let layer = placed(&mut doc, open.clone(), at, self.frame, 1.0);
|
||||
let front = Arc::new(Front { layer: layer.id, timeline: open, frame: self.frame, at });
|
||||
tl.layers.push(layer);
|
||||
// Around it, dimmed: each timeline below, without the instance opened from it.
|
||||
if view.in_place {
|
||||
for (i, l) in self.editing.iter().enumerate().rev() {
|
||||
let parent = i.checked_sub(1).and_then(|j| self.editing.get(j));
|
||||
let below = match parent {
|
||||
None => self.doc.timeline(self.scene).clone(),
|
||||
Some(p) => self.doc.symbol(p.symbol).map(|s| s.timeline.clone()).unwrap_or_default(),
|
||||
};
|
||||
let xf = parent.map_or(Affine::IDENTITY, |p| p.transform);
|
||||
tl.layers.push(placed(&mut doc, without(below, l.instance), xf, l.frame, DIM));
|
||||
}
|
||||
}
|
||||
*doc.timeline_mut(self.scene) = tl;
|
||||
// Apart from document states (counted up from 1), and the same for the same picture.
|
||||
let pic = Arc::new(StagePicture { frame: doc.scene_start(self.scene), doc, state: key | 1 << 63, front: Some(front) });
|
||||
self.picture_cache.replace(Some((key, pic.clone())));
|
||||
pic
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer holding `timeline` as a graphic symbol's instance at `transform`, showing its `frame`
|
||||
/// at opacity `alpha` (a symbol added to `doc`, which is only drawn).
|
||||
fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, alpha: f32) -> Arc<Layer> {
|
||||
let symbol = SymbolId(doc.alloc_id());
|
||||
doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, timeline }));
|
||||
let mut k = Keyframe::new(0, 1);
|
||||
k.elements.push(Arc::new(Element {
|
||||
id: ElementId(doc.alloc_id()),
|
||||
name: String::new(),
|
||||
transform,
|
||||
color: ColorEffect { alpha, ..ColorEffect::default() },
|
||||
kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() },
|
||||
}));
|
||||
let mut layer = Layer::new(LayerId(doc.alloc_id()), "");
|
||||
layer.keyframes.push(Arc::new(k));
|
||||
Arc::new(layer)
|
||||
}
|
||||
|
||||
/// Whether an instance of `sym` placed in the open symbol would put a symbol inside itself: `sym`
|
||||
/// is open, or uses an open one, however deep.
|
||||
pub(crate) fn would_nest(s: &Session, sym: SymbolId) -> bool {
|
||||
if s.editing.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut seen: Vec<SymbolId> = Vec::new();
|
||||
let mut todo = vec![sym];
|
||||
while let Some(id) = todo.pop() {
|
||||
if s.editing.iter().any(|l| l.symbol == id) {
|
||||
return true;
|
||||
}
|
||||
if seen.contains(&id) || seen.len() > 100_000 {
|
||||
continue;
|
||||
}
|
||||
seen.push(id);
|
||||
let Some(sym) = s.doc.symbol(id) else { continue };
|
||||
for k in sym.timeline.layers.iter().flat_map(|l| l.keyframes.iter()) {
|
||||
todo.extend(k.elements.iter().filter_map(|e| match e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => Some(symbol),
|
||||
_ => None,
|
||||
}));
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `tl` without the instance `which` (on every keyframe of its layer).
|
||||
fn without(mut tl: Timeline, which: Option<(LayerId, ElementId)>) -> Timeline {
|
||||
let Some((layer, id)) = which else { return tl };
|
||||
if let Some(l) = tl.layer_mut(layer) {
|
||||
for k in &mut l.keyframes {
|
||||
if k.elements.iter().any(|e| e.id == id) {
|
||||
Arc::make_mut(k).elements.retain(|e| e.id != id);
|
||||
}
|
||||
}
|
||||
}
|
||||
tl
|
||||
}
|
||||
|
||||
/// The instance `id` on a layer at the playhead of the timeline being edited, and its layer.
|
||||
fn instance(s: &Session, id: ElementId) -> Option<(LayerId, Arc<Element>)> {
|
||||
s.timeline().layers.iter().map(|l| l.id).find_map(|l| s.elements_on(l).into_iter().find(|e| e.id == id).map(|e| (l, e)))
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.editing.len() >= MAX_LEVELS {
|
||||
return Err(EngineError::State(format!("at most {MAX_LEVELS} symbols can be open inside each other")));
|
||||
}
|
||||
// From the Library: alone, its registration point at the stage's centre.
|
||||
if let Some(sym) = opt_u64(p, "symbol")? {
|
||||
let symbol = SymbolId(sym);
|
||||
if s.doc.symbol(symbol).is_none() {
|
||||
return Err(EngineError::State(format!("no symbol {sym} in the Library")));
|
||||
}
|
||||
if s.editing.iter().any(|l| l.symbol == symbol) {
|
||||
return Err(EngineError::State("that symbol is open already".into()));
|
||||
}
|
||||
let c = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5);
|
||||
s.enter_level(symbol, None, Affine::translate(c.x, c.y), 0);
|
||||
return Ok(editing_json(s));
|
||||
}
|
||||
let id = match opt_u64(p, "id")? {
|
||||
Some(i) => ElementId(i),
|
||||
None => {
|
||||
let picked: Vec<ElementId> = s.selection.on(s.layer).into_iter().filter(|id| instance(s, *id).is_some_and(|(_, e)| matches!(e.kind, ElementKind::Symbol { .. }))).collect();
|
||||
match picked.as_slice() {
|
||||
[one] => *one,
|
||||
// Nothing to open: Ctrl+E goes back to the document, as in Animate.
|
||||
[] if !s.editing.is_empty() => {
|
||||
s.exit_all();
|
||||
return Ok(editing_json(s));
|
||||
}
|
||||
[] => return Err(EngineError::State("select a symbol instance to edit it (or double-click it)".into())),
|
||||
_ => return Err(EngineError::State("select one symbol instance to edit".into())),
|
||||
}
|
||||
}
|
||||
};
|
||||
let (layer, el) = instance(s, id).ok_or_else(|| EngineError::State(format!("element {} is not on a layer here at this frame", id.0)))?;
|
||||
if !s.selectable(layer) {
|
||||
return Err(EngineError::State("that instance's layer is locked or hidden".into()));
|
||||
}
|
||||
let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = el.kind else { return Err(EngineError::State("that is not a symbol instance".into())) };
|
||||
let sym = s.doc.symbol(symbol).ok_or_else(|| EngineError::State("that instance's symbol is missing from the Library".into()))?;
|
||||
if s.editing.iter().any(|l| l.symbol == symbol) {
|
||||
return Err(EngineError::State("that symbol is open already".into()));
|
||||
}
|
||||
// A graphic opens at the frame the instance shows; movie clips and buttons at their first.
|
||||
let len = sym.timeline.frame_count();
|
||||
let start = s.timeline().layer(layer).and_then(|l| l.keyframe_at(s.frame)).map_or(s.frame, |k| k.start);
|
||||
let frame = if sym.kind == SymbolKind::Graphic { loop_mode.local_frame(s.frame.saturating_sub(start), first_frame, len) } else { 0 };
|
||||
let below = s.editing.last().map_or(Affine::IDENTITY, |l| l.transform);
|
||||
s.enter_level(symbol, Some((layer, id)), below.mul(&el.transform), frame);
|
||||
Ok(editing_json(s))
|
||||
}
|
||||
|
||||
fn exit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.editing.is_empty() {
|
||||
return Err(EngineError::State("no symbol is open for editing".into()));
|
||||
}
|
||||
if opt_bool(p, "all")?.unwrap_or(false) {
|
||||
s.exit_all();
|
||||
} else {
|
||||
s.exit_level();
|
||||
}
|
||||
Ok(editing_json(s))
|
||||
}
|
||||
|
||||
/// The open symbols, outermost first.
|
||||
pub(crate) fn editing_json(s: &Session) -> Value {
|
||||
let list: Vec<Value> = s.editing.iter().map(|l| json!({"symbol": l.symbol.0, "name": s.doc.symbol(l.symbol).map(|x| x.name.clone()), "instance": l.instance.map(|(_, e)| e.0)})).collect();
|
||||
json!({"editing": list, "layer": s.layer.0, "frame": s.frame, "selected": s.selection.id_list()})
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Editing a symbol's timeline in place, with raw drawings inside it (ADR 0045).
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, SymbolId};
|
||||
use anicraft_geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn raw(s: &Session) -> Vec<Arc<Element>> {
|
||||
s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect()
|
||||
}
|
||||
|
||||
fn has(points: &[Vec2], p: (f32, f32)) -> bool {
|
||||
points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 0.3)
|
||||
}
|
||||
|
||||
/// A raw outlined rectangle (100 × 80) turned into a symbol, its instance moved to stand at
|
||||
/// (250, 140): the symbol's space runs from (−50, −40) to (50, 40).
|
||||
fn boxed() -> (Session, ElementId, SymbolId) {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.object_drawing", json!({"on": false}));
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"}));
|
||||
let (inst, sym) = (ElementId(v["instance"].as_u64().unwrap_or(0)), SymbolId(v["symbol"].as_u64().unwrap_or(0)));
|
||||
run(&mut s, "element.translate", json!({"dx": 200, "dy": 100}));
|
||||
(s, inst, sym)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_shapes_inside_a_symbol_merge_and_take_the_selection_and_subselection_tools() {
|
||||
let (mut s, inst, sym) = boxed();
|
||||
let steps = s.history_len();
|
||||
let v = run(&mut s, "symbol.edit", json!({}));
|
||||
assert_eq!(v["editing"][0]["symbol"], json!(sym.0), "{v}");
|
||||
assert_eq!(s.history_len(), steps, "opening is not an edit");
|
||||
let view = s.edit_view().unwrap_or_else(|| panic!("open"));
|
||||
assert!(view.in_place && view.origin.distance(Vec2::new(250.0, 140.0)) < 1e-3 && (view.scale - 1.0).abs() < 1e-6, "{view:?}");
|
||||
// Inside: the symbol's own layer, its raw drawing of five shapes, in its space.
|
||||
assert_eq!(s.timeline().layers.len(), 1);
|
||||
assert_eq!(raw(&s).len(), 5);
|
||||
assert!(s.hit_test(Vec2::new(0.0, 0.0), 1.0).is_some(), "picking is in the symbol's space");
|
||||
// Subselection: everything connected shows its four corners.
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 0, "y": -40}));
|
||||
assert_eq!(v["anchors"].as_array().map(Vec::len), Some(4), "{v}");
|
||||
// The Selection tool: a corner moves with every shape on it.
|
||||
run(&mut s, "raw.move_point", json!({"x": 50, "y": -40, "to_x": 60, "to_y": -50}));
|
||||
assert!(has(&s.raw_points(&raw(&s).iter().map(|e| e.id).collect::<Vec<_>>()).anchors, (60.0, -50.0)));
|
||||
// Merge drawing: a line right across cuts the fill in two.
|
||||
run(&mut s, "draw.line", json!({"x0": -70, "y0": 0, "x1": 70, "y1": 0, "stroke": "#000000"}));
|
||||
let fills = raw(&s).into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count();
|
||||
assert_eq!(fills, 2);
|
||||
// Points: added and deleted inside, shared as on the stage.
|
||||
run(&mut s, "raw.add_point", json!({"x": -50, "y": 20}));
|
||||
run(&mut s, "raw.delete_points", json!({"points": [[-50, 20]]}));
|
||||
// Back on the stage: the instance is selected and shows the edits where it stands.
|
||||
run(&mut s, "symbol.exit", json!({}));
|
||||
assert!(s.editing.is_empty());
|
||||
assert_eq!(s.selection.ids().collect::<Vec<_>>(), vec![inst]);
|
||||
let b = s.element_bounds(inst);
|
||||
assert!(b.max.x > 309.0 && b.min.y < 91.0, "the moved corner at (310, 90): {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_goes_back_into_the_symbol_where_the_change_was_made() {
|
||||
let (mut s, _, sym) = boxed();
|
||||
run(&mut s, "symbol.edit", json!({}));
|
||||
run(&mut s, "raw.delete_points", json!({"points": [[-50, -40]]}));
|
||||
assert_eq!(raw(&s).iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(), 1);
|
||||
run(&mut s, "symbol.exit", json!({}));
|
||||
assert!(s.undo().is_ok());
|
||||
assert_eq!(s.editing_symbol(), Some(sym), "undo opens the symbol again");
|
||||
assert_eq!(s.raw_points(&raw(&s).iter().map(|e| e.id).collect::<Vec<_>>()).anchors.len(), 4, "with the corner back");
|
||||
// Undoing the conversion takes the symbol away: editing closes.
|
||||
while s.undo().is_ok() {}
|
||||
assert!(s.editing.is_empty() && s.doc.library.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_from_the_library_and_guards() {
|
||||
let (mut s, inst, sym) = boxed();
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
assert!(s.execute("symbol.edit", &json!({})).is_err(), "nothing selected to open");
|
||||
assert!(s.execute("symbol.exit", &json!({})).is_err(), "nothing open");
|
||||
run(&mut s, "symbol.edit", json!({"symbol": sym.0}));
|
||||
let view = s.edit_view().unwrap_or_else(|| panic!("open"));
|
||||
let centre = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5);
|
||||
assert!(!view.in_place && view.origin == centre, "alone, at the stage's centre: {view:?}");
|
||||
assert!(s.execute("library.place", &json!({"symbol": sym.0})).is_err(), "not inside itself");
|
||||
assert!(s.execute("symbol.edit", &json!({"symbol": sym.0})).is_err(), "open already");
|
||||
// Ctrl+E with nothing to open goes back to the document.
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
run(&mut s, "symbol.edit", json!({}));
|
||||
assert!(s.editing.is_empty());
|
||||
// A rotated instance opens upright where it stands, the artwork around it hidden.
|
||||
run(&mut s, "element.select", json!({"ids": [inst.0]}));
|
||||
run(&mut s, "modify.transform", json!({"a": 0.0, "b": 1.0, "c": -1.0, "d": 0.0, "e": 0.0, "f": 0.0}));
|
||||
run(&mut s, "symbol.edit", json!({"id": inst.0}));
|
||||
let view = s.edit_view().unwrap_or_else(|| panic!("open"));
|
||||
assert!(!view.in_place && (view.scale - 1.0).abs() < 1e-6, "{view:?}");
|
||||
// A scene change closes it.
|
||||
run(&mut s, "scene.new", json!({}));
|
||||
assert!(s.editing.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stage_shows_the_open_symbol_in_place_over_the_dimmed_stage() {
|
||||
let (mut s, _, _) = boxed();
|
||||
// Something else on the stage, beside the instance.
|
||||
run(&mut s, "draw.rect", json!({"x": 400, "y": 300, "w": 50, "h": 50, "fill": "#0000ff", "stroke": null, "object": true}));
|
||||
run(&mut s, "element.pick", json!({"x": 250, "y": 140}));
|
||||
run(&mut s, "symbol.edit", json!({}));
|
||||
let pic = s.stage_picture();
|
||||
assert_eq!(pic.state, s.stage_picture().state, "the same picture twice");
|
||||
let px = anicraft_render::render_frame(&pic.doc, pic.frame, 1.0).unwrap_or_else(|e| panic!("{e}"));
|
||||
let at = |x: u32, y: u32| px.pixel(x, y).unwrap_or_else(|| panic!("in the picture"));
|
||||
// The symbol's fill in full red where its instance stands...
|
||||
let red = at(250, 140);
|
||||
assert!(red[0] > 0.95 && red[1] < 0.05 && red[2] < 0.05, "{red:?}");
|
||||
// ...and the stage around it dimmed (blue at about a third over white).
|
||||
let blue = at(425, 325);
|
||||
assert!(blue[2] > 0.95 && blue[0] > 0.5 && blue[0] < 0.8, "{blue:?}");
|
||||
// The document itself is untouched by the picture.
|
||||
assert_eq!(s.doc.library.len(), 1);
|
||||
// Back on the stage, the picture is the document.
|
||||
run(&mut s, "symbol.exit", json!({}));
|
||||
assert_eq!(s.stage_picture().state, s.state);
|
||||
}
|
||||
@@ -28,6 +28,8 @@ pub struct Snapshot {
|
||||
pub doc: Document,
|
||||
pub state: StateId,
|
||||
pub scene: usize,
|
||||
/// The symbols open for editing (ADR 0045).
|
||||
pub editing: Vec<crate::editing::EditLevel>,
|
||||
pub frame: u32,
|
||||
pub layer: LayerId,
|
||||
pub selection: crate::Selection,
|
||||
@@ -243,6 +245,6 @@ pub fn unique_bytes(old: &Document, new: &Document) -> usize {
|
||||
|
||||
/// Estimated total bytes of a document (as if nothing were shared). Used for reporting.
|
||||
pub fn document_bytes(doc: &Document) -> usize {
|
||||
let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: doc.next_id };
|
||||
let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: doc.next_id };
|
||||
unique_bytes(doc, &empty)
|
||||
}
|
||||
+48
-16
@@ -16,10 +16,12 @@ mod cmds_frames;
|
||||
mod cmds_modify;
|
||||
mod cmds_motion;
|
||||
mod cmds_hints;
|
||||
pub mod cmds_library;
|
||||
mod cmds_paint;
|
||||
mod cmds_path;
|
||||
pub mod cmds_raw;
|
||||
pub mod cmds_rawsub;
|
||||
mod cmds_rawpoints;
|
||||
mod cmds_recovery;
|
||||
mod cmds_script;
|
||||
pub mod cmds_plugin;
|
||||
@@ -30,9 +32,11 @@ mod cmds_timeline;
|
||||
mod cmds_width;
|
||||
mod cmds_stroke;
|
||||
pub mod confirm;
|
||||
pub mod editing;
|
||||
pub mod format;
|
||||
pub mod history;
|
||||
mod merge;
|
||||
pub mod multi;
|
||||
pub mod onion;
|
||||
pub mod recovery;
|
||||
pub mod render_service;
|
||||
@@ -113,12 +117,16 @@ pub fn commands() -> Vec<CommandSpec> {
|
||||
v.extend(cmds_scene::specs());
|
||||
v.extend(cmds_frames::specs());
|
||||
v.extend(onion::specs());
|
||||
v.extend(multi::specs());
|
||||
v.extend(cmds_draw::specs());
|
||||
v.extend(cmds_library::specs());
|
||||
v.extend(merge::specs());
|
||||
v.extend(cmds_modify::specs());
|
||||
v.extend(cmds_path::specs());
|
||||
v.extend(cmds_raw::specs());
|
||||
v.extend(cmds_rawsub::specs());
|
||||
v.extend(cmds_rawpoints::specs());
|
||||
v.extend(editing::specs());
|
||||
v.extend(cmds_brush::specs());
|
||||
v.extend(cmds_erase::specs());
|
||||
v.extend(cmds_paint::specs());
|
||||
@@ -138,6 +146,9 @@ pub const SHORTCUT_ALIASES: &[(&str, &str)] = &[
|
||||
("Backspace", "edit.delete"),
|
||||
("Shift+,", "timeline.first_frame"),
|
||||
("Shift+.", "timeline.last_frame"),
|
||||
// Snap to Objects is Animate's Ctrl+Shift+/ (ADR 0045). Where / and ? share a key (US, UK),
|
||||
// the key arrives as ?, so that spelling is bound too.
|
||||
("Ctrl+Shift+?", "draw.snap_to_objects"),
|
||||
];
|
||||
|
||||
pub fn find_command(id: &str) -> Option<CommandSpec> {
|
||||
@@ -233,14 +244,17 @@ impl ToolStyle {
|
||||
}
|
||||
|
||||
/// An open document plus everything the editor tracks about it.
|
||||
/// A display list and the `(state, scene, frame)` it was evaluated for.
|
||||
type CachedList = (StateId, usize, u32, Arc<DisplayList>);
|
||||
/// A display list and the `(state, scene, frame, open symbol)` it was evaluated for.
|
||||
type CachedList = (StateId, usize, u32, Option<anicraft_doc::SymbolId>, Arc<DisplayList>);
|
||||
|
||||
pub struct Session {
|
||||
/// The document: a persistent tree, so cloning it (undo, render thread) is cheap.
|
||||
pub doc: Document,
|
||||
/// The scene being edited (index into `doc.scenes`).
|
||||
pub scene: usize,
|
||||
/// Symbols open for editing, outermost first (ADR 0045). While one is open, commands work on
|
||||
/// its timeline: `frame`, `layer` and `selection` are its.
|
||||
pub editing: Vec<editing::EditLevel>,
|
||||
/// Playhead within the scene (0-based).
|
||||
pub frame: u32,
|
||||
/// Active layer.
|
||||
@@ -280,6 +294,8 @@ pub struct Session {
|
||||
pub(crate) pending_cut: Option<(CutOrigin, Vec<ElementId>)>,
|
||||
/// The open gesture began on a provisional cut: the document with the cut.
|
||||
gesture_cut: Option<Document>,
|
||||
/// The last picture of an open symbol in place, by its key (ADR 0045).
|
||||
picture_cache: RefCell<Option<(u64, Arc<editing::StagePicture>)>>,
|
||||
}
|
||||
|
||||
/// Each piece of a marquee's cut, with the shape it was cut from.
|
||||
@@ -323,6 +339,7 @@ impl Session {
|
||||
Session {
|
||||
doc,
|
||||
scene: 0,
|
||||
editing: Vec::new(),
|
||||
frame: 0,
|
||||
layer,
|
||||
selection: Selection::default(),
|
||||
@@ -343,6 +360,7 @@ impl Session {
|
||||
provisional: None,
|
||||
pending_cut: None,
|
||||
gesture_cut: None,
|
||||
picture_cache: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,20 +635,22 @@ impl Session {
|
||||
if g.doc == self.doc && g.selection == self.selection {
|
||||
return;
|
||||
}
|
||||
let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 };
|
||||
let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 };
|
||||
self.restore(back);
|
||||
self.revision += 1;
|
||||
self.fix_selection();
|
||||
}
|
||||
|
||||
fn snapshot(&self, label: &str) -> Snapshot {
|
||||
Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 }
|
||||
Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 }
|
||||
}
|
||||
|
||||
fn restore(&mut self, s: Snapshot) {
|
||||
self.doc = s.doc;
|
||||
self.state = s.state;
|
||||
self.scene = s.scene;
|
||||
// Where the change was made: an undo inside a symbol opens it again (ADR 0045).
|
||||
self.editing = s.editing;
|
||||
self.frame = s.frame;
|
||||
self.layer = s.layer;
|
||||
self.selection = s.selection;
|
||||
@@ -691,28 +711,34 @@ impl Session {
|
||||
// ----- queries ---------------------------------------------------------------------------
|
||||
|
||||
pub fn frame_count(&self) -> u32 {
|
||||
self.doc.timeline(self.scene).frame_count()
|
||||
self.timeline().frame_count()
|
||||
}
|
||||
|
||||
pub fn active_layer(&self) -> Option<&Layer> {
|
||||
self.doc.timeline(self.scene).layer(self.layer)
|
||||
self.timeline().layer(self.layer)
|
||||
}
|
||||
|
||||
pub fn active_layer_index(&self) -> Option<usize> {
|
||||
self.doc.timeline(self.scene).layers.iter().position(|l| l.id == self.layer)
|
||||
self.timeline().layers.iter().position(|l| l.id == self.layer)
|
||||
}
|
||||
|
||||
/// The current scene evaluated at the playhead, cached per `(state, scene, frame)`.
|
||||
pub fn display_list(&self) -> Arc<DisplayList> {
|
||||
if let Some((s, sc, f, dl)) = &*self.dl_cache.borrow()
|
||||
let open = self.editing_symbol();
|
||||
if let Some((s, sc, f, o, dl)) = &*self.dl_cache.borrow()
|
||||
&& *s == self.state
|
||||
&& *sc == self.scene
|
||||
&& *f == self.frame
|
||||
&& *o == open
|
||||
{
|
||||
return dl.clone();
|
||||
}
|
||||
let dl = Arc::new(evaluate_scene(&self.doc, self.scene, self.frame));
|
||||
self.dl_cache.replace(Some((self.state, self.scene, self.frame, dl.clone())));
|
||||
// An open symbol is edited in its own space (ADR 0045).
|
||||
let dl = Arc::new(match open.and_then(|id| self.doc.symbol(id)) {
|
||||
Some(sym) => anicraft_doc::evaluate_timeline(&self.doc, &sym.timeline, self.frame),
|
||||
None => evaluate_scene(&self.doc, self.scene, self.frame),
|
||||
});
|
||||
self.dl_cache.replace(Some((self.state, self.scene, self.frame, open, dl.clone())));
|
||||
dl
|
||||
}
|
||||
|
||||
@@ -725,7 +751,8 @@ impl Session {
|
||||
/// Topmost element under `p` (stage space) on a visible, unlocked layer. A bounding-box
|
||||
/// test rejects almost every item before any curve is flattened.
|
||||
pub fn hit_test(&self, p: Vec2, slop: f32) -> Option<(LayerId, ElementId)> {
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
// The timeline being edited: a symbol open in place picks in its own layers (ADR 0045).
|
||||
let tl = self.timeline();
|
||||
let dl = self.display_list();
|
||||
let i = pick_index(&dl, p, slop, |_, it| tl.layer(it.layer).is_some_and(|layer| !layer.locked && !tl.locked_by_folder(layer.id)))?;
|
||||
dl.items.get(i).map(|it| (it.layer, it.element))
|
||||
@@ -750,7 +777,7 @@ impl Session {
|
||||
|
||||
pub(crate) fn layer_mut(&mut self, id: Option<LayerId>) -> Result<&mut Layer> {
|
||||
let id = id.unwrap_or(self.layer);
|
||||
self.doc.timeline_mut(self.scene).layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))
|
||||
crate::editing::edited_mut(&mut self.doc, self.scene, &self.editing).layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))
|
||||
}
|
||||
|
||||
/// The keyframe on the active layer that edits at the playhead should change. Creates a
|
||||
@@ -764,7 +791,7 @@ impl Session {
|
||||
/// refused there.
|
||||
pub(crate) fn editable_keyframe_in(&mut self, what: KeyEdit) -> Result<&mut Keyframe> {
|
||||
let frame = self.frame;
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
let tl = self.timeline();
|
||||
if let Some(l) = tl.layer(self.layer) {
|
||||
if l.kind == LayerKind::Folder {
|
||||
return Err(EngineError::State(format!("'{}' is a folder; pick a layer inside it to draw on", l.name)));
|
||||
@@ -781,7 +808,7 @@ impl Session {
|
||||
}
|
||||
// Through the fields, not `layer_mut`, so `motion_edit` can be set below.
|
||||
let (scene, active) = (self.scene, self.layer);
|
||||
let layer = self.doc.timeline_mut(scene).layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?;
|
||||
let layer = crate::editing::edited_mut(&mut self.doc, scene, &self.editing).layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?;
|
||||
if layer.locked {
|
||||
return Err(EngineError::State(format!("layer '{}' is locked", layer.name)));
|
||||
}
|
||||
@@ -821,8 +848,7 @@ impl Session {
|
||||
/// JSON summary used by `doc.info` and the CLI.
|
||||
pub fn info(&self) -> Value {
|
||||
let layers: Vec<Value> = self
|
||||
.doc
|
||||
.timeline(self.scene)
|
||||
.timeline()
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
@@ -844,6 +870,8 @@ impl Session {
|
||||
"layer": self.layer.0,
|
||||
"selection": self.selection.id_list(),
|
||||
"selection_layers": self.selected_layers().iter().map(|l| l.0).collect::<Vec<_>>(),
|
||||
// The symbols open for editing, outermost first (ADR 0045); `layers` are the open one's.
|
||||
"editing": editing::editing_json(self)["editing"],
|
||||
"layers": layers,
|
||||
"library": symbols,
|
||||
"sounds": sounds,
|
||||
@@ -917,6 +945,10 @@ mod raw_tests;
|
||||
#[cfg(test)]
|
||||
mod rawsub_tests;
|
||||
#[cfg(test)]
|
||||
mod rawpoints_tests;
|
||||
#[cfg(test)]
|
||||
mod editing_tests;
|
||||
#[cfg(test)]
|
||||
mod brush_tests;
|
||||
#[cfg(test)]
|
||||
mod web_tests;
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
//! Library management end to end (ADR 0050): folders, names, moves, duplicates, Swap Symbol,
|
||||
//! deletion with its confirmations, unused items, smoothing, the file format and undo.
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryItem, SymbolId, sample};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, id: &str, p: Value) -> String {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => panic!("{id} {p} should fail, gave {v}"),
|
||||
Err(e) => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sym(s: &Session, name: &str) -> u64 {
|
||||
s.doc.library.iter().find(|x| x.name == name).map(|x| x.id.0).unwrap_or_else(|| panic!("no symbol {name}"))
|
||||
}
|
||||
|
||||
fn folder(v: &Value) -> u64 {
|
||||
v["folder"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn path(s: &Session, symbol: u64) -> String {
|
||||
s.doc.entry_path(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(symbol))))
|
||||
}
|
||||
|
||||
/// Instances of `symbol` on every timeline.
|
||||
fn instances(s: &Session, symbol: u64) -> usize {
|
||||
s.doc.timelines().flat_map(|t| &t.layers).flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).filter(|e| matches!(e.kind, ElementKind::Symbol { symbol: x, .. } if x.0 == symbol)).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_are_made_named_and_nested() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let a = run(&mut s, "library.new_folder", json!({}));
|
||||
assert_eq!(a["name"], "Folder 1");
|
||||
let b = run(&mut s, "library.new_folder", json!({}));
|
||||
assert_eq!(b["name"], "Folder 2");
|
||||
let inner = run(&mut s, "library.new_folder", json!({"name": "Hero", "parent": folder(&a)}));
|
||||
assert_eq!(s.doc.entry_path(LibraryEntry::Folder(FolderId(folder(&inner)))), "Folder 1/Hero");
|
||||
// Names: unique per folder without case, no slashes, not empty.
|
||||
assert!(err(&mut s, "library.new_folder", json!({"name": "folder 1"})).contains("already has"));
|
||||
assert!(err(&mut s, "library.new_folder", json!({"name": "a/b"})).contains("/"));
|
||||
assert!(err(&mut s, "library.new_folder", json!({"name": " "})).contains("empty"));
|
||||
assert!(err(&mut s, "library.new_folder", json!({"parent": 999_999})).contains("no folder"));
|
||||
run(&mut s, "library.new_folder", json!({"name": "Hero"}));
|
||||
// Renaming.
|
||||
run(&mut s, "library.rename", json!({"folder": folder(&a), "name": "Characters"}));
|
||||
assert_eq!(s.doc.folder(FolderId(folder(&a))).unwrap().name, "Characters");
|
||||
let ball = sym(&s, "Ball");
|
||||
assert!(err(&mut s, "library.rename", json!({"symbol": ball, "name": "star"})).contains("already has"));
|
||||
run(&mut s, "library.rename", json!({"symbol": ball, "name": "BALL"}));
|
||||
run(&mut s, "library.rename", json!({"symbol": ball, "name": "Ball"}));
|
||||
assert!(err(&mut s, "library.rename", json!({"symbol": ball, "folder": 1, "name": "x"})).contains("one Library entry"));
|
||||
// One undo step each.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(s.doc.symbol(SymbolId(ball)).unwrap().name, "BALL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_move_in_and_out_of_folders() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star"));
|
||||
let chars = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"})));
|
||||
let hero = folder(&run(&mut s, "library.new_folder", json!({"name": "Hero", "parent": chars})));
|
||||
let v = run(&mut s, "library.move", json!({"items": [{"symbol": ball}, {"symbol": star}], "to": hero}));
|
||||
assert_eq!(v["moved"], 2);
|
||||
assert_eq!(path(&s, ball), "Characters/Hero/Ball");
|
||||
// Out again, one step for the whole move.
|
||||
run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": null}));
|
||||
assert_eq!(path(&s, ball), "Ball");
|
||||
s.undo().unwrap();
|
||||
assert_eq!(path(&s, ball), "Characters/Hero/Ball");
|
||||
// A folder moves with what it holds, but never into itself.
|
||||
let props = folder(&run(&mut s, "library.new_folder", json!({"name": "Props"})));
|
||||
run(&mut s, "library.move", json!({"items": [{"folder": hero}], "to": props}));
|
||||
assert_eq!(path(&s, star), "Props/Hero/Star");
|
||||
assert!(err(&mut s, "library.move", json!({"items": [{"folder": props}], "to": hero})).contains("inside itself"));
|
||||
assert!(err(&mut s, "library.move", json!({"items": [{"folder": props}], "to": props})).contains("inside itself"));
|
||||
// A name clash stops the move and leaves everything where it was.
|
||||
run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": null}));
|
||||
let star2 = run(&mut s, "library.duplicate", json!({"symbol": star, "name": "Ball"}));
|
||||
let before = s.doc.library_tree.clone();
|
||||
let e = err(&mut s, "library.move", json!({"items": [{"symbol": star}, {"symbol": star2["symbol"]}], "to": null}));
|
||||
assert!(e.contains("already has an item named “Ball”"), "{e}");
|
||||
assert_eq!(s.doc.library_tree, before);
|
||||
assert!(err(&mut s, "library.move", json!({"items": [{"symbol": ball}]})).contains("'to'"));
|
||||
assert!(err(&mut s, "library.move", json!({"items": [{"symbol": 424_242}], "to": null})).contains("no symbol"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_survive_save_and_open() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let ball = sym(&s, "Ball");
|
||||
let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"})));
|
||||
run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f}));
|
||||
let text = crate::format::to_json(&s.doc).unwrap();
|
||||
let back = Session::new(crate::format::from_json(&text).unwrap());
|
||||
assert_eq!(path(&back, ball), "Characters/Ball");
|
||||
assert_eq!(back.doc.library_tree, s.doc.library_tree);
|
||||
assert!(back.doc.next_id > f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicates_are_named_after_their_original() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let ball = sym(&s, "Ball");
|
||||
let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Props"})));
|
||||
run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f}));
|
||||
let a = run(&mut s, "library.duplicate", json!({"symbol": ball}));
|
||||
assert_eq!(a["name"], "Ball copy");
|
||||
let b = run(&mut s, "library.duplicate", json!({"symbol": ball}));
|
||||
assert_eq!(b["name"], "Ball copy 2");
|
||||
assert_eq!(path(&s, a["symbol"].as_u64().unwrap()), "Props/Ball copy");
|
||||
assert!(err(&mut s, "library.duplicate", json!({"symbol": ball, "name": "ball COPY"})).contains("already has"));
|
||||
assert!(err(&mut s, "library.duplicate", json!({"symbol": 424_242})).contains("no symbol"));
|
||||
assert_eq!(instances(&s, a["symbol"].as_u64().unwrap()), 0, "a copy isn't placed");
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc.symbol(SymbolId(b["symbol"].as_u64().unwrap())).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_symbol_keeps_everything_but_the_symbol() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star"));
|
||||
let el = run(&mut s, "library.place", json!({"symbol": ball, "x": 100, "y": 50}))["element"].as_u64().unwrap();
|
||||
run(&mut s, "symbol.set_kind", json!({"symbol": ball, "kind": "movie_clip"}));
|
||||
run(&mut s, "element.set_transform", json!({"sx": 2, "rotation": 30}));
|
||||
run(&mut s, "element.set_alpha", json!({"alpha": 0.5}));
|
||||
run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]}));
|
||||
run(&mut s, "element.rename", json!({"name": "hero"}));
|
||||
let find = |s: &Session| s.elements_on(s.layer).iter().find(|e| e.id.0 == el).map(|e| (**e).clone()).unwrap();
|
||||
let before = find(&s);
|
||||
let v = run(&mut s, "element.swap_symbol", json!({"symbol": star}));
|
||||
assert_eq!(v["swapped"], 1);
|
||||
let after = find(&s);
|
||||
assert_eq!((after.transform, after.color, &after.name), (before.transform, before.color, &before.name));
|
||||
match (&before.kind, &after.kind) {
|
||||
(ElementKind::Symbol { symbol: a, loop_mode: la, filters: fa, blend: ba, .. }, ElementKind::Symbol { symbol: b, loop_mode: lb, filters: fb, blend: bb, .. }) => {
|
||||
assert_eq!((a.0, b.0), (ball, star));
|
||||
assert_eq!((la, fa, ba), (lb, fb, bb));
|
||||
}
|
||||
_ => panic!("still an instance"),
|
||||
}
|
||||
assert_eq!(s.selection.on(s.layer).first().map(|e| e.0), Some(el), "it stays selected");
|
||||
assert!(err(&mut s, "element.swap_symbol", json!({"symbol": 424_242})).contains("no symbol"));
|
||||
assert!(err(&mut s, "element.swap_symbol", json!({})).contains("'symbol'"));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
assert!(s.execute("element.swap_symbol", &json!({"symbol": ball})).is_err(), "nothing selected");
|
||||
s.undo().unwrap();
|
||||
assert!(matches!(find(&s).kind, ElementKind::Symbol { symbol, .. } if symbol.0 == ball));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_asks_when_it_takes_uses_or_folder_contents() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star"));
|
||||
assert!(instances(&s, star) > 0, "the sample places Star (inside Ball too)");
|
||||
// An unused item goes without asking.
|
||||
let copy = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap();
|
||||
let p = json!({"items": [{"symbol": copy}]});
|
||||
assert!(s.confirmation("library.delete", &p).is_none());
|
||||
run(&mut s, "library.delete", p);
|
||||
assert!(s.doc.symbol(SymbolId(copy)).is_none());
|
||||
// A used one asks (undoable tier), and its instances go everywhere, inside symbols too.
|
||||
let p = json!({"items": [{"symbol": star}]});
|
||||
let c = s.confirmation("library.delete", &p).expect("asks");
|
||||
assert!(!c.irreversible && c.message.contains("used") && c.message.contains("undo"), "{c:?}");
|
||||
run(&mut s, "library.delete", p);
|
||||
assert_eq!(instances(&s, star), 0);
|
||||
assert!(s.doc.symbol(SymbolId(ball)).is_some());
|
||||
s.undo().unwrap();
|
||||
assert!(instances(&s, star) > 0);
|
||||
// A folder that holds items asks, and takes them with it.
|
||||
let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Old"})));
|
||||
let inner = folder(&run(&mut s, "library.new_folder", json!({"name": "Older", "parent": f})));
|
||||
let spare = run(&mut s, "library.duplicate", json!({"symbol": ball}))["symbol"].as_u64().unwrap();
|
||||
run(&mut s, "library.move", json!({"items": [{"symbol": spare}], "to": inner}));
|
||||
let p = json!({"items": [{"folder": f}]});
|
||||
let c = s.confirmation("library.delete", &p).expect("asks");
|
||||
assert!(c.title.contains("folder") && c.message.contains("holds 2 items"), "{c:?}");
|
||||
let v = run(&mut s, "library.delete", p);
|
||||
assert_eq!((v["deleted"].as_u64(), v["folders"].as_u64()), (Some(1), Some(2)));
|
||||
assert!(s.doc.library_tree.is_empty() && s.doc.symbol(SymbolId(spare)).is_none());
|
||||
// An empty folder goes without asking.
|
||||
let empty = folder(&run(&mut s, "library.new_folder", json!({})));
|
||||
assert!(s.confirmation("library.delete", &json!({"items": [{"folder": empty}]})).is_none());
|
||||
assert!(err(&mut s, "library.delete", json!({"items": []})).contains("nothing"));
|
||||
assert!(err(&mut s, "library.delete", json!({"items": [{"folder": 1}]})).contains("no folder"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_bitmap_or_a_sound_takes_its_uses() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let id = BitmapId(s.doc.alloc_id());
|
||||
let mut px = Vec::new();
|
||||
for _ in 0..4 {
|
||||
px.extend_from_slice(&[255, 0, 0, 255]);
|
||||
}
|
||||
let bytes = anicraft_render::encode_png(2, 2, &px).unwrap();
|
||||
s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(id, "red.png", bytes).unwrap()));
|
||||
let el = run(&mut s, "library.place", json!({"bitmap": id.0}))["element"].as_u64().unwrap();
|
||||
let item = LibraryItem::Bitmap(id);
|
||||
assert_eq!(s.doc.library_uses().get(&item), Some(&1));
|
||||
// Smoothing toggles, is one undo step, and is kept by the file.
|
||||
assert_eq!(run(&mut s, "library.set_smoothing", json!({"bitmap": id.0}))["smoothing"], false);
|
||||
let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap();
|
||||
assert!(!back.bitmap(id).unwrap().smoothing);
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc.bitmap(id).unwrap().smoothing);
|
||||
assert!(!crate::format::to_json(&s.doc).unwrap().contains("smoothing"), "the default is written as nothing");
|
||||
run(&mut s, "library.delete", json!({"items": [{"bitmap": id.0}]}));
|
||||
assert!(s.doc.bitmap(id).is_none());
|
||||
assert!(s.elements_on(s.layer).iter().all(|e| e.id.0 != el), "the placed bitmap goes with it");
|
||||
assert!(err(&mut s, "library.set_smoothing", json!({"bitmap": id.0})).contains("no bitmap"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unused_items_are_listed_and_deleted_after_asking() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let star = sym(&s, "Star");
|
||||
assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([]));
|
||||
assert!(s.confirmation("library.delete_unused", &json!({})).is_none());
|
||||
let a = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap();
|
||||
let b = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap();
|
||||
// In Library order: each copy sits right after its original, so the later one comes first.
|
||||
assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([{"symbol": b}, {"symbol": a}]));
|
||||
let c = s.confirmation("library.delete_unused", &json!({})).expect("asks");
|
||||
assert!(c.message.contains("these 2 items") && c.message.contains("Star copy"), "{c:?}");
|
||||
let v = run(&mut s, "library.delete_unused", json!({}));
|
||||
assert_eq!(v["deleted"], 2);
|
||||
assert!(s.doc.symbol(SymbolId(a)).is_none() && s.doc.symbol(SymbolId(star)).is_some());
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc.symbol(SymbolId(a)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_listing_has_paths_kinds_and_uses() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let ball = sym(&s, "Ball");
|
||||
let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"})));
|
||||
run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f}));
|
||||
let v = run(&mut s, "library.items", json!({}));
|
||||
assert_eq!(v["folders"], json!([{"folder": f, "name": "Characters", "parent": null, "path": "Characters"}]));
|
||||
let b = v["items"].as_array().unwrap().iter().find(|i| i["symbol"] == ball).unwrap();
|
||||
assert_eq!((b["path"].as_str(), b["folder"].as_u64(), b["kind"].as_str(), b["unused"].as_bool()), (Some("Characters/Ball"), Some(f), Some("graphic"), Some(false)));
|
||||
assert!(b["uses"].as_u64().unwrap() > 0);
|
||||
assert_eq!(v["unused"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_symbol_picks_a_free_name() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
let first = run(&mut s, "modify.convert_to_symbol", json!({}));
|
||||
assert_eq!(first["name"], "Symbol 1");
|
||||
run(&mut s, "library.rename", json!({"symbol": first["symbol"], "name": "Symbol 2"}));
|
||||
run(&mut s, "draw.rect", json!({"x": 20, "y": 0, "w": 10, "h": 10}));
|
||||
let second = run(&mut s, "modify.convert_to_symbol", json!({}));
|
||||
assert_eq!(second["name"], "Symbol 3", "“Symbol 2” is taken");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_an_open_symbol_swap_never_nests_and_deleting_it_closes_it() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
let outer = run(&mut s, "modify.convert_to_symbol", json!({"name": "Outer"}))["symbol"].as_u64().unwrap();
|
||||
run(&mut s, "draw.rect", json!({"x": 40, "y": 0, "w": 10, "h": 10}));
|
||||
let other = run(&mut s, "modify.convert_to_symbol", json!({"name": "Other"}))["symbol"].as_u64().unwrap();
|
||||
run(&mut s, "symbol.edit", json!({"symbol": outer}));
|
||||
assert_eq!(s.editing.len(), 1);
|
||||
run(&mut s, "library.place", json!({"symbol": other}));
|
||||
assert!(err(&mut s, "element.swap_symbol", json!({"symbol": outer})).contains("inside itself"));
|
||||
// Deleting the open symbol takes the editor back to the scene.
|
||||
run(&mut s, "library.delete", json!({"items": [{"symbol": outer}], "confirm": true}));
|
||||
assert!(s.editing.is_empty() && s.doc.symbol(SymbolId(outer)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_counts_stay_quick_on_a_large_document() {
|
||||
// 100 layers × 100 shapes keyed every 12 frames over 240 frames (200,000 element keys),
|
||||
// plus 1,000 symbols in 50 folders, each placed once. Measured, loosely bounded (CI varies);
|
||||
// the shell works these out once per document change, not per frame.
|
||||
let mut s = Session::new(anicraft_doc::sample::stress(100, 100, 240));
|
||||
// A new layer, so the symbol holds only the new rectangle (drawing selects it).
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5}));
|
||||
let sym = run(&mut s, "modify.convert_to_symbol", json!({}))["symbol"].as_u64().unwrap();
|
||||
for i in 0..50 {
|
||||
run(&mut s, "library.new_folder", json!({"name": format!("F{i}")}));
|
||||
}
|
||||
let folders: Vec<u64> = s.doc.library_tree.folders.iter().map(|f| f.id.0).collect();
|
||||
for i in 0..999 {
|
||||
let c = run(&mut s, "library.duplicate", json!({"symbol": sym, "name": format!("S{i}")}))["symbol"].as_u64().unwrap();
|
||||
run(&mut s, "library.move", json!({"items": [{"symbol": c}], "to": folders[i % folders.len()]}));
|
||||
}
|
||||
let t = std::time::Instant::now();
|
||||
let uses = s.doc.library_uses();
|
||||
let counted = t.elapsed();
|
||||
let t = std::time::Instant::now();
|
||||
let unused = s.doc.unused_items();
|
||||
let reach = t.elapsed();
|
||||
let t = std::time::Instant::now();
|
||||
let listed = run(&mut s, "library.items", json!({}));
|
||||
let listing = t.elapsed();
|
||||
println!("library of {} items, {} folders: use counts {counted:?}, unused {reach:?} ({} unused), library.items {listing:?}", s.doc.library.len(), folders.len(), unused.len());
|
||||
assert_eq!(listed["items"].as_array().map(Vec::len), Some(1000));
|
||||
assert_eq!(unused.len(), 999);
|
||||
assert!(uses.values().sum::<usize>() >= 1);
|
||||
assert!(counted.as_millis() < 500 && reach.as_millis() < 500, "counted {counted:?}, unused {reach:?}");
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
//! Edit Multiple Frames, complete (ADR 0051; ADR 0047 began it with moves).
|
||||
//!
|
||||
//! With Edit Multiple Frames on, the artwork on every keyframe within the onion markers is edited
|
||||
//! as if it were on one frame. These commands are that editing, on a list of [`FrameItem`]s (an
|
||||
//! element on one keyframe), or on everything the markers show when no list is given:
|
||||
//!
|
||||
//! * `frames.edit_multiple` moves, `frames.transform` scales, rotates and skews about one shared
|
||||
//! pivot, `frames.align` aligns: each item on its own keyframe, as one undo step;
|
||||
//! * `frames.delete`, `frames.copy`, `frames.cut`; `frames.paste` pastes in place onto every
|
||||
//! keyframe within the markers (artwork copied from several keyframes goes back keyframe by
|
||||
//! keyframe);
|
||||
//! * raw (merge-drawing) shapes that moved or landed go back into the drawing on their own
|
||||
//! keyframe, cut and joined with what they touch, as `draw.drop` does on one frame
|
||||
//! (`merge: false` holds that back while a drag is under way; `frames.merge` does it when the
|
||||
//! drag ends).
|
||||
//!
|
||||
//! Every command answers with `items`: what the selection is afterwards (merged pieces have new
|
||||
//! ids), so a front end keeps the multi-frame selection without asking again.
|
||||
//!
|
||||
//! The timeline is the one being edited, so all of this works inside a symbol open in place
|
||||
//! (ADR 0045) on the symbol's own keyframes.
|
||||
|
||||
use crate::cmds_modify::{ClipLayer, Clipboard, collect_symbols, import_symbols};
|
||||
use crate::onion::{FrameItem, multi_editable};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, LayerId, Timeline};
|
||||
use anicraft_geom::{Affine, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..], merge?: bool} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; raw shapes merge again where they land unless merge is false; one undo step; answers the items after the move", true, move_cmd as crate::RunFn),
|
||||
c("frames.transform", "Transform on Multiple Frames", "", None, "{first, last, items?, merge?, a, b, c, d, e, f} (an affine in stage space) | {rotate? (degrees), scale_x?, scale_y?, skew_x?, skew_y? (degrees), pivot?: [x, y] (default: the centre of every item's bounds together)} transforms the items on each keyframe about one shared pivot, as Free Transform does with Edit Multiple Frames on; one undo step", true, transform_cmd),
|
||||
c("frames.align", "Align on Multiple Frames", "", None, "{first, last, edge: left|hcenter|right|top|vcenter|bottom, items?, to_stage? (default: one item aligns to the stage), merge?} lines the items up with the edge of their bounds together (or the stage's), each on its own keyframe", true, align_cmd),
|
||||
c("frames.delete", "Clear on Multiple Frames", "", None, "{first, last, items?} deletes the items (default: everything shown) from their keyframes", true, delete_cmd),
|
||||
c("frames.copy", "Copy on Multiple Frames", "", None, "{first, last, items?} copies the items (default: everything shown), remembering each one's keyframe: Paste on Multiple Frames puts them back keyframe by keyframe, Paste puts them all on the current frame", false, copy_cmd),
|
||||
c("frames.cut", "Cut on Multiple Frames", "", None, "{first, last, items?} frames.copy, then frames.delete", true, cut_cmd),
|
||||
c("frames.paste", "Paste in Place on Multiple Frames", "", None, "{first, last, layer?} pastes in place onto the keyframes within the markers: artwork copied from several keyframes onto the keyframe covering the frame each came from (on the layers it came from when it came from several, else on `layer` or the active layer); artwork copied on one frame onto every keyframe of the layer; raw shapes merge where they land", true, paste_cmd),
|
||||
c("frames.merge", "Merge on Multiple Frames", "", None, "{first, last, items} the raw shapes among the items merge again with what they touch on their keyframes (the end of a drag made with merge: false); answers the items after the merge", true, merge_cmd),
|
||||
]
|
||||
}
|
||||
|
||||
// ----- params and the chosen items -----------------------------------------------------------
|
||||
|
||||
/// Most items a command takes.
|
||||
const MAX_ITEMS: usize = 100_000;
|
||||
|
||||
/// The `first` and `last` params, in order.
|
||||
pub(crate) fn range_param(p: &Value) -> Result<(u32, u32)> {
|
||||
let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)")));
|
||||
let (a, b) = (req("first")?, req("last")?);
|
||||
if a.max(b) > crate::MAX_FRAME {
|
||||
return Err(EngineError::Param(format!("frames go up to {}", crate::MAX_FRAME)));
|
||||
}
|
||||
Ok((a.min(b), a.max(b)))
|
||||
}
|
||||
|
||||
fn items_param(p: &Value) -> Result<Option<Vec<FrameItem>>> {
|
||||
let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into());
|
||||
let list = v.as_array().ok_or_else(bad)?;
|
||||
if list.len() > MAX_ITEMS {
|
||||
return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items")));
|
||||
}
|
||||
list.iter()
|
||||
.map(|t| {
|
||||
let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?;
|
||||
let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad);
|
||||
let frame = u32::try_from(n(1)?).map_err(|_| bad())?;
|
||||
Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) })
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// The items a command acts on, with their stage bounds: the `items` given (each must be shown
|
||||
/// in `first..=last`), or everything shown.
|
||||
fn chosen(s: &Session, p: &Value, first: u32, last: u32) -> Result<Vec<(FrameItem, Rect)>> {
|
||||
let shown = s.multi_frame_items(first, last);
|
||||
let Some(list) = items_param(p)? else { return Ok(shown) };
|
||||
let index: std::collections::HashMap<FrameItem, Rect> = shown.into_iter().collect();
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
let mut seen = HashSet::new();
|
||||
for it in list {
|
||||
let Some(&b) = index.get(&it) else {
|
||||
return Err(EngineError::State(format!(
|
||||
"element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)",
|
||||
it.element.0, it.layer.0, it.frame
|
||||
)));
|
||||
};
|
||||
if seen.insert(it) {
|
||||
out.push((it, b));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The items keyframe by keyframe: (layer, keyframe start) → ids, in the order first seen.
|
||||
fn by_keyframe(items: &[FrameItem]) -> BTreeMap<(LayerId, u32), Vec<ElementId>> {
|
||||
let mut out: BTreeMap<(LayerId, u32), Vec<ElementId>> = BTreeMap::new();
|
||||
for it in items {
|
||||
let ids = out.entry((it.layer, it.frame)).or_default();
|
||||
if !ids.contains(&it.element) {
|
||||
ids.push(it.element);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn items_json(items: &[FrameItem]) -> Value {
|
||||
json!(items.iter().map(FrameItem::to_json).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn merge_param(p: &Value) -> Result<bool> {
|
||||
Ok(opt_bool(p, "merge")?.unwrap_or(true))
|
||||
}
|
||||
|
||||
/// Runs `f` with the playhead on frame `start` of `layer` (a keyframe's first frame), so the
|
||||
/// editing helpers that work at the playhead work on that keyframe; both come back after.
|
||||
fn at_keyframe<T>(s: &mut Session, layer: LayerId, start: u32, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
|
||||
let frame = s.frame;
|
||||
s.frame = start;
|
||||
let r = s.with_layer(layer, f);
|
||||
s.frame = frame;
|
||||
r
|
||||
}
|
||||
|
||||
// ----- moves and transforms ------------------------------------------------------------------
|
||||
|
||||
/// Whether `m` only moves (no scale, rotation or skew).
|
||||
fn translation_only(m: &Affine) -> bool {
|
||||
let [a, b, c, d, _, _] = m.m;
|
||||
(a - 1.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// Applies each item's own stage-space affine to it on its keyframe (`t' = m · t`). A motion
|
||||
/// tween's object carries its path and X/Y keys along; it can only move (refused otherwise).
|
||||
/// Nothing changes when anything is refused (the session rolls back a failed command).
|
||||
fn apply_each(s: &mut Session, moves: &[(FrameItem, Affine)]) -> Result<usize> {
|
||||
let mut by: BTreeMap<(LayerId, u32), Vec<(ElementId, Affine)>> = BTreeMap::new();
|
||||
for (it, m) in moves {
|
||||
if !m.is_finite() || m.determinant().abs() < 1e-8 {
|
||||
return Err(EngineError::Param("the transform is degenerate (it would collapse the artwork)".into()));
|
||||
}
|
||||
by.entry((it.layer, it.frame)).or_default().push((it.element, *m));
|
||||
}
|
||||
let mut n = 0usize;
|
||||
for ((layer, start), list) in &by {
|
||||
let l = s.layer_mut(Some(*layer))?;
|
||||
let Some(ki) = l.keyframe_starting_at(*start) else { continue };
|
||||
let Some(kf) = l.keyframe_mut(ki) else { continue };
|
||||
if let Some(mt) = kf.motion.as_mut()
|
||||
&& let Some((_, m)) = list.iter().find(|(id, _)| *id == mt.target)
|
||||
{
|
||||
if !translation_only(m) {
|
||||
return Err(EngineError::State("a motion tween's object can only be moved on several frames at once; scale, rotate or skew it on its own keyframe".into()));
|
||||
}
|
||||
let d = m.translation();
|
||||
if d != Vec2::ZERO && !mt.translate(d) {
|
||||
return Err(EngineError::State("the motion path would move out of range".into()));
|
||||
}
|
||||
}
|
||||
for e in kf.elements_mut_where(|id| list.iter().any(|(x, _)| *x == id)) {
|
||||
let Some((_, m)) = list.iter().find(|(x, _)| *x == e.id) else { continue };
|
||||
let t = m.mul(&e.transform);
|
||||
let d = t.decompose();
|
||||
if !t.is_finite() || d.sx.abs() > 10_000.0 || d.sy.abs() > 10_000.0 || d.sx.abs() < 1e-4 || d.sy.abs() < 1e-4 {
|
||||
return Err(EngineError::Param("the transform would make an element too large or too small".into()));
|
||||
}
|
||||
e.transform = t;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// The raw shapes among `items` go back into the drawing on their keyframes, on top of what they
|
||||
/// touch, cutting and joining it (`draw.drop` on each keyframe). The items afterwards: objects as
|
||||
/// they were, each raw shape's pieces with their new ids.
|
||||
fn remerge(s: &mut Session, items: &[FrameItem]) -> Result<Vec<FrameItem>> {
|
||||
// Each keyframe's raw shapes merged: (layer, start) → the pieces (ids gone, ids new).
|
||||
let mut merged: BTreeMap<(LayerId, u32), (Vec<ElementId>, Vec<ElementId>)> = BTreeMap::new();
|
||||
for ((layer, start), ids) in by_keyframe(items) {
|
||||
let l = s.layer_mut(Some(layer))?;
|
||||
let Some(ki) = l.keyframe_starting_at(start) else { continue };
|
||||
let Some(kf) = l.keyframe_mut(ki) else { continue };
|
||||
let mut moving: Vec<Element> = Vec::new();
|
||||
kf.elements.retain(|e| {
|
||||
let take = ids.contains(&e.id) && crate::merge::mergeable(e).is_some();
|
||||
if take {
|
||||
moving.push((**e).clone());
|
||||
}
|
||||
!take
|
||||
});
|
||||
if moving.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let gone: Vec<ElementId> = moving.iter().map(|e| e.id).collect();
|
||||
let fresh = at_keyframe(s, layer, start, |s| crate::merge::merge_in(s, moving))?;
|
||||
merged.insert((layer, start), (gone, fresh));
|
||||
}
|
||||
// In the order given: objects as they were, each keyframe's pieces where its first raw
|
||||
// shape was.
|
||||
let mut out: Vec<FrameItem> = Vec::with_capacity(items.len());
|
||||
for it in items {
|
||||
match merged.get_mut(&(it.layer, it.frame)) {
|
||||
Some((gone, fresh)) if gone.contains(&it.element) => out.extend(std::mem::take(fresh).into_iter().map(|element| FrameItem { element, ..*it })),
|
||||
_ => out.push(*it),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `remerge` when `merge`, else the items as they are.
|
||||
fn finish(s: &mut Session, items: Vec<FrameItem>, merge: bool) -> Result<Vec<FrameItem>> {
|
||||
if merge { remerge(s, &items) } else { Ok(items) }
|
||||
}
|
||||
|
||||
fn move_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT {
|
||||
return Err(EngineError::Param("the move is too large".into()));
|
||||
}
|
||||
let merge = merge_param(p)?;
|
||||
let items: Vec<FrameItem> = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect();
|
||||
let keyframes = by_keyframe(&items).len();
|
||||
let mv = Affine::translate(d.x, d.y);
|
||||
let moved = if d == Vec2::ZERO { 0 } else { apply_each(s, &items.iter().map(|it| (*it, mv)).collect::<Vec<_>>())? };
|
||||
let items = if moved > 0 { finish(s, items, merge)? } else { items };
|
||||
Ok(json!({"moved": moved, "keyframes": keyframes, "dx": d.x, "dy": d.y, "items": items_json(&items)}))
|
||||
}
|
||||
|
||||
/// The transform a `frames.transform` call asks for, given the items' bounds together.
|
||||
fn transform_param(p: &Value, bounds: Rect) -> Result<Affine> {
|
||||
let keys = ["a", "b", "c", "d", "e", "f"];
|
||||
if keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
let mut m = [0.0f32; 6];
|
||||
for (slot, k) in m.iter_mut().zip(keys) {
|
||||
*slot = f32_req(p, k)?;
|
||||
}
|
||||
return Ok(Affine { m });
|
||||
}
|
||||
let deg = |k: &str| -> Result<f32> {
|
||||
let v = opt_f32(p, k)?.unwrap_or(0.0);
|
||||
if v.abs() > 36_000.0 {
|
||||
return Err(EngineError::Param(format!("param '{k}' is out of range")));
|
||||
}
|
||||
Ok(v.to_radians())
|
||||
};
|
||||
let factor = |k: &str| -> Result<f32> {
|
||||
let v = opt_f32(p, k)?.unwrap_or(1.0);
|
||||
if !(1e-3..=1e3).contains(&v.abs()) {
|
||||
return Err(EngineError::Param(format!("param '{k}' must be a scale between 0.001 and 1000 (negative flips)")));
|
||||
}
|
||||
Ok(v)
|
||||
};
|
||||
let (sx, sy, r, kx, ky) = (factor("scale_x")?, factor("scale_y")?, deg("rotate")?, deg("skew_x")?, deg("skew_y")?);
|
||||
let pivot = match p.get("pivot").filter(|v| !v.is_null()) {
|
||||
Some(v) => {
|
||||
let bad = || EngineError::Param("param 'pivot' must be [x, y]".into());
|
||||
let a = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?;
|
||||
let n = |i: usize| a.get(i).and_then(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite() && x.abs() <= crate::cmds_draw::MAX_EXTENT).ok_or_else(bad);
|
||||
Vec2::new(n(0)?, n(1)?)
|
||||
}
|
||||
None => bounds.center(),
|
||||
};
|
||||
// Scale, then skew, then rotate, about the pivot.
|
||||
let skew = Affine { m: [1.0, ky.tan(), kx.tan(), 1.0, 0.0, 0.0] };
|
||||
let m = Affine::rotate(r).mul(&skew).mul(&Affine::scale(sx, sy));
|
||||
Ok(Affine::translate(pivot.x, pivot.y).mul(&m).mul(&Affine::translate(-pivot.x, -pivot.y)))
|
||||
}
|
||||
|
||||
fn transform_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let merge = merge_param(p)?;
|
||||
let chosen = chosen(s, p, first, last)?;
|
||||
if chosen.is_empty() {
|
||||
return Err(EngineError::State("nothing to transform on the frames between the markers".into()));
|
||||
}
|
||||
let bounds = chosen.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b));
|
||||
let m = transform_param(p, bounds)?;
|
||||
let items: Vec<FrameItem> = chosen.into_iter().map(|(it, _)| it).collect();
|
||||
let n = apply_each(s, &items.iter().map(|it| (*it, m)).collect::<Vec<_>>())?;
|
||||
let items = finish(s, items, merge)?;
|
||||
Ok(json!({"transformed": n, "keyframes": by_keyframe(&items).len(), "matrix": m.m, "items": items_json(&items)}))
|
||||
}
|
||||
|
||||
fn align_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let edge = str_req(p, "edge")?;
|
||||
let merge = merge_param(p)?;
|
||||
let chosen: Vec<(FrameItem, Rect)> = chosen(s, p, first, last)?.into_iter().filter(|(_, b)| !b.is_empty()).collect();
|
||||
if chosen.is_empty() {
|
||||
return Err(EngineError::State("nothing to align on the frames between the markers".into()));
|
||||
}
|
||||
let to_stage = opt_bool(p, "to_stage")?.unwrap_or(chosen.len() == 1);
|
||||
let target = if to_stage { Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32) } else { chosen.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b)) };
|
||||
let d = |b: &Rect| -> Result<Vec2> {
|
||||
Ok(match edge {
|
||||
"left" => Vec2::new(target.min.x - b.min.x, 0.0),
|
||||
"hcenter" => Vec2::new(target.center().x - b.center().x, 0.0),
|
||||
"right" => Vec2::new(target.max.x - b.max.x, 0.0),
|
||||
"top" => Vec2::new(0.0, target.min.y - b.min.y),
|
||||
"vcenter" => Vec2::new(0.0, target.center().y - b.center().y),
|
||||
"bottom" => Vec2::new(0.0, target.max.y - b.max.y),
|
||||
_ => return Err(EngineError::Param(format!("unknown edge '{edge}' (left, hcenter, right, top, vcenter or bottom)"))),
|
||||
})
|
||||
};
|
||||
let mut moves = Vec::with_capacity(chosen.len());
|
||||
for (it, b) in &chosen {
|
||||
let v = d(b)?;
|
||||
if v != Vec2::ZERO {
|
||||
moves.push((*it, Affine::translate(v.x, v.y)));
|
||||
}
|
||||
}
|
||||
let n = apply_each(s, &moves)?;
|
||||
let moved: Vec<FrameItem> = moves.iter().map(|(it, _)| *it).collect();
|
||||
let mut items: Vec<FrameItem> = chosen.iter().map(|(it, _)| *it).filter(|it| !moved.contains(it)).collect();
|
||||
items.extend(finish(s, moved, merge)?);
|
||||
Ok(json!({"moved": n, "to_stage": to_stage, "items": items_json(&items)}))
|
||||
}
|
||||
|
||||
fn merge_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
if items_param(p)?.is_none() {
|
||||
return Err(EngineError::Param("param 'items' is required (the items a drag moved)".into()));
|
||||
}
|
||||
let items: Vec<FrameItem> = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect();
|
||||
let items = remerge(s, &items)?;
|
||||
Ok(json!({"items": items_json(&items)}))
|
||||
}
|
||||
|
||||
// ----- delete, copy, cut, paste --------------------------------------------------------------
|
||||
|
||||
fn delete_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let items: Vec<FrameItem> = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect();
|
||||
if items.is_empty() {
|
||||
return Err(EngineError::State("nothing to delete on the frames between the markers".into()));
|
||||
}
|
||||
let groups = by_keyframe(&items);
|
||||
let mut deleted = 0usize;
|
||||
for ((layer, start), ids) in &groups {
|
||||
let l = s.layer_mut(Some(*layer))?;
|
||||
let Some(ki) = l.keyframe_starting_at(*start) else { continue };
|
||||
let Some(kf) = l.keyframe_mut(ki) else { continue };
|
||||
let before = kf.elements.len();
|
||||
kf.elements.retain(|e| !ids.contains(&e.id));
|
||||
deleted += before - kf.elements.len();
|
||||
}
|
||||
s.selection.clear();
|
||||
Ok(json!({"deleted": deleted, "keyframes": groups.len(), "items": []}))
|
||||
}
|
||||
|
||||
/// The layers' order in `tl`, top first, for sorting.
|
||||
fn rank(tl: &Timeline, l: LayerId) -> usize {
|
||||
tl.layers.iter().position(|x| x.id == l).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
fn copy_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let items: Vec<FrameItem> = chosen(s, p, first, last)?.into_iter().map(|(it, _)| it).collect();
|
||||
if items.is_empty() {
|
||||
return Err(EngineError::State("nothing to copy on the frames between the markers".into()));
|
||||
}
|
||||
let tl = s.timeline();
|
||||
let mut groups: Vec<((LayerId, u32), Vec<ElementId>)> = by_keyframe(&items).into_iter().collect();
|
||||
// Top layer first, then frame order (a clipboard lists layers top to bottom).
|
||||
groups.sort_by_key(|((l, f), _)| (rank(tl, *l), *f));
|
||||
let mut layers = Vec::with_capacity(groups.len());
|
||||
for ((layer, start), ids) in groups {
|
||||
let Some(l) = tl.layer(layer) else { continue };
|
||||
let Some(k) = l.keyframe_starting_at(start).and_then(|i| l.keyframes.get(i)) else { continue };
|
||||
// In their stacking order on the keyframe.
|
||||
let elements: Vec<Element> = k.elements.iter().filter(|e| ids.contains(&e.id)).map(|e| (**e).clone()).collect();
|
||||
if !elements.is_empty() {
|
||||
layers.push(ClipLayer { layer, name: l.name.clone(), elements, frame: Some(start) });
|
||||
}
|
||||
}
|
||||
let all: Vec<Element> = layers.iter().flat_map(|c| c.elements.iter().cloned()).collect();
|
||||
let symbols = collect_symbols(s, &all);
|
||||
let (n, keyframes) = (all.len(), layers.len());
|
||||
s.clipboard = Clipboard { layers, symbols };
|
||||
Ok(json!({"copied": n, "keyframes": keyframes}))
|
||||
}
|
||||
|
||||
fn cut_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let v = copy_cmd(s, p)?;
|
||||
delete_cmd(s, p)?;
|
||||
Ok(json!({"cut": v["copied"], "keyframes": v["keyframes"], "items": []}))
|
||||
}
|
||||
|
||||
/// The first frames of `layer`'s keyframes that Edit Multiple Frames shows in `first..=last`
|
||||
/// (the playhead's too); none when it doesn't edit that layer.
|
||||
fn shown_keyframes(tl: &Timeline, layer: LayerId, first: u32, last: u32) -> Vec<u32> {
|
||||
let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return Vec::new() };
|
||||
if !multi_editable(tl, i) {
|
||||
return Vec::new();
|
||||
}
|
||||
tl.layers.get(i).map(|l| l.keyframes.iter().filter(|k| k.start <= last && k.end() > first).map(|k| k.start).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn paste_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
if s.clipboard.is_empty() {
|
||||
return Err(EngineError::State("the clipboard is empty".into()));
|
||||
}
|
||||
if crate::cmds_modify::clipboard_nests(s) {
|
||||
return Err(EngineError::State("a symbol can't be pasted inside itself".into()));
|
||||
}
|
||||
let active = match opt_u64(p, "layer")? {
|
||||
Some(id) => LayerId(id),
|
||||
None => s.layer,
|
||||
};
|
||||
let clip = s.clipboard.clone();
|
||||
// Artwork from several layers goes back on those layers when they are all here and edited
|
||||
// with Edit Multiple Frames; else everything goes on the one layer, as a paste does.
|
||||
let mut from: Vec<LayerId> = Vec::new();
|
||||
for c in &clip.layers {
|
||||
if !from.contains(&c.layer) {
|
||||
from.push(c.layer);
|
||||
}
|
||||
}
|
||||
let tl = s.timeline();
|
||||
let home = from.len() > 1 && from.iter().all(|l| !shown_keyframes(tl, *l, first, last).is_empty());
|
||||
let mut plan: Vec<(LayerId, u32, &ClipLayer)> = Vec::new();
|
||||
let mut skipped = 0usize;
|
||||
for c in &clip.layers {
|
||||
let target = if home { c.layer } else { active };
|
||||
let keys = shown_keyframes(tl, target, first, last);
|
||||
match c.frame {
|
||||
// Back onto the keyframe covering the frame it came from, if the markers show it.
|
||||
Some(f) => match tl.layer(target).and_then(|l| l.keyframe_at(f)).map(|k| k.start).filter(|k| keys.contains(k)) {
|
||||
Some(k) => plan.push((target, k, c)),
|
||||
None => skipped += 1,
|
||||
},
|
||||
// Copied on one frame: onto every keyframe shown.
|
||||
None => plan.extend(keys.iter().map(|&k| (target, k, c))),
|
||||
}
|
||||
}
|
||||
if plan.is_empty() {
|
||||
let why = if tl.layer(active).is_some_and(|_| shown_keyframes(tl, active, first, last).is_empty()) { "the layer has no keyframe Edit Multiple Frames can paste onto between the markers (it must be visible, unlocked and hold artwork)" } else { "none of the copied keyframes is between the markers" };
|
||||
return Err(EngineError::State(why.into()));
|
||||
}
|
||||
import_symbols(s, &clip.symbols);
|
||||
let mut items = Vec::new();
|
||||
let mut keyframes: HashSet<(LayerId, u32)> = HashSet::new();
|
||||
for (layer, start, c) in plan {
|
||||
let (fresh, _) = at_keyframe(s, layer, start, |s| crate::cmds_modify::paste_layer(s, &c.elements, Vec2::ZERO))?;
|
||||
keyframes.insert((layer, start));
|
||||
items.extend(fresh.into_iter().map(|element| FrameItem { layer, frame: start, element }));
|
||||
}
|
||||
s.selection.clear();
|
||||
Ok(json!({"pasted": items.len(), "keyframes": keyframes.len(), "skipped": skipped, "items": items_json(&items)}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "multi_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,349 @@
|
||||
//! Edit Multiple Frames, complete (ADR 0051): transforms about one shared pivot, align, delete,
|
||||
//! copy, cut and paste per keyframe, raw shapes merged again on their keyframes, and all of it
|
||||
//! (with onion skin) inside a symbol open in place.
|
||||
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use crate::onion::OnionSkin;
|
||||
use anicraft_doc::{ElementKind, Keyframe, LayerId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// One layer, a 20 × 20 drawing object walking right: keyframes on frames 0, 4 and 8 with it at
|
||||
/// x = 10, 50 and 90 (y = 10). The playhead is on frame 4.
|
||||
fn walk() -> (Session, LayerId, ElementId) {
|
||||
let mut s = Session::default();
|
||||
let layer = s.layer;
|
||||
let id = ElementId(run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap());
|
||||
for f in [4, 8] {
|
||||
run(&mut s, "timeline.goto", json!({"frame": f}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
run(&mut s, "element.select", json!({"ids": [id.0]}));
|
||||
run(&mut s, "element.translate", json!({"dx": 40, "dy": 0}));
|
||||
}
|
||||
run(&mut s, "timeline.goto", json!({"frame": 4}));
|
||||
(s, layer, id)
|
||||
}
|
||||
|
||||
fn key(s: &Session, layer: LayerId, start: u32) -> Keyframe {
|
||||
let l = s.timeline().layer(layer).unwrap();
|
||||
(**l.keyframes.iter().find(|k| k.start == start).unwrap()).clone()
|
||||
}
|
||||
|
||||
/// The bounds of every element on the keyframe of `layer` starting at `start`.
|
||||
fn bounds_on(s: &Session, layer: LayerId, start: u32) -> Vec<Rect> {
|
||||
key(s, layer, start).elements.iter().map(|e| e.bounds(&s.doc)).collect()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: [f32; 4]) -> bool {
|
||||
[a.min.x, a.min.y, a.max.x, a.max.y].iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transform_about_the_shared_pivot_lands_each_keyframes_artwork_exactly() {
|
||||
let (mut s, a, _) = walk();
|
||||
let steps = s.history_len();
|
||||
// Together the three copies span x 10..110, y 10..30: the pivot is (60, 20).
|
||||
let v = run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "scale_x": 2, "scale_y": 0.5}));
|
||||
assert_eq!((v["transformed"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3)));
|
||||
// x' = 60 + 2 (x − 60), y' = 20 + 0.5 (y − 20).
|
||||
for (f, x) in [(0, 10.0), (4, 50.0), (8, 90.0)] {
|
||||
let b = bounds_on(&s, a, f)[0];
|
||||
assert!(near(b, [60.0 + 2.0 * (x - 60.0), 15.0, 60.0 + 2.0 * (x + 20.0 - 60.0), 25.0]), "keyframe {f}: {b:?}");
|
||||
}
|
||||
assert_eq!(s.history_len(), steps + 1, "one undo step");
|
||||
s.undo().unwrap();
|
||||
// A quarter turn (clockwise on the y-down stage): (x, y) → (60 − (y − 20), 20 + (x − 60)).
|
||||
run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "rotate": 90}));
|
||||
for (f, x) in [(0, 10.0), (4, 50.0), (8, 90.0)] {
|
||||
let b = bounds_on(&s, a, f)[0];
|
||||
let (cx, cy) = (x + 10.0, 20.0);
|
||||
let (nx, ny) = (60.0 - (cy - 20.0), 20.0 + (cx - 60.0));
|
||||
assert!(near(b, [nx - 10.0, ny - 10.0, nx + 10.0, ny + 10.0]), "keyframe {f}: {b:?}");
|
||||
}
|
||||
// Its own pivot, and a matrix, as Free Transform sends.
|
||||
s.undo().unwrap();
|
||||
let on8 = key(&s, a, 8).elements[0].id.0;
|
||||
run(&mut s, "frames.transform", json!({"first": 0, "last": 8, "scale_x": 2, "pivot": [10, 10], "items": [[a.0, 8, on8]]}));
|
||||
assert!(near(bounds_on(&s, a, 8)[0], [170.0, 10.0, 210.0, 30.0]));
|
||||
assert!(near(bounds_on(&s, a, 0)[0], [10.0, 10.0, 30.0, 30.0]), "only the item given");
|
||||
run(&mut s, "frames.transform", json!({"first": 0, "last": 4, "a": 1, "b": 0, "c": 0, "d": 1, "e": 5, "f": -5}));
|
||||
assert!(near(bounds_on(&s, a, 0)[0], [15.0, 5.0, 35.0, 25.0]));
|
||||
// Degenerate or wild transforms are refused, with nothing changed.
|
||||
let before = s.doc.clone();
|
||||
assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "a": 0, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0})).is_err());
|
||||
assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "scale_x": 0})).is_err());
|
||||
assert!(s.execute("frames.transform", &json!({"first": 0, "last": 8, "pivot": [1]})).is_err());
|
||||
assert!(s.doc == before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_lines_every_keyframes_artwork_up() {
|
||||
let (mut s, a, _) = walk();
|
||||
run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 0, "dy": 0}));
|
||||
let v = run(&mut s, "frames.align", json!({"first": 0, "last": 8, "edge": "left"}));
|
||||
assert_eq!(v["moved"], json!(2), "the one already at the left edge stays");
|
||||
for f in [0, 4, 8] {
|
||||
assert!(near(bounds_on(&s, a, f)[0], [10.0, 10.0, 30.0, 30.0]), "keyframe {f}");
|
||||
}
|
||||
s.undo().unwrap();
|
||||
run(&mut s, "frames.align", json!({"first": 0, "last": 8, "edge": "bottom", "to_stage": true}));
|
||||
let h = s.doc.stage.height as f32;
|
||||
assert!([0, 4, 8].iter().all(|&f| (bounds_on(&s, a, f)[0].max.y - h).abs() < 1e-3));
|
||||
assert!(s.execute("frames.align", &json!({"first": 0, "last": 8, "edge": "middle"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_copy_cut_and_paste_count_per_keyframe() {
|
||||
let (mut s, a, id) = walk();
|
||||
// A second element on keyframes 0 and 8 only.
|
||||
run(&mut s, "timeline.goto", json!({"frame": 0}));
|
||||
run(&mut s, "draw.rect", json!({"x": 10, "y": 100, "w": 10, "h": 10, "object": true}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 8}));
|
||||
run(&mut s, "draw.rect", json!({"x": 90, "y": 100, "w": 10, "h": 10, "object": true}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 4}));
|
||||
let count = |s: &Session| [0, 4, 8].map(|f| key(s, a, f).elements.len());
|
||||
assert_eq!(count(&s), [2, 1, 2]);
|
||||
|
||||
// Copy the walker on 0 and 8 (with its keyframes), cut everything else.
|
||||
let walker = |f| json!([a.0, f, id.0]);
|
||||
let v = run(&mut s, "frames.copy", json!({"first": 0, "last": 8, "items": [walker(0), walker(8)]}));
|
||||
assert_eq!((v["copied"].as_u64(), v["keyframes"].as_u64()), (Some(2), Some(2)));
|
||||
assert_eq!(s.clipboard.layers.iter().map(|c| c.frame).collect::<Vec<_>>(), vec![Some(0), Some(8)]);
|
||||
let steps = s.history_len();
|
||||
let v = run(&mut s, "frames.delete", json!({"first": 0, "last": 8, "items": [walker(0), walker(4), walker(8)]}));
|
||||
assert_eq!((v["deleted"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3)));
|
||||
assert_eq!(count(&s), [1, 0, 1]);
|
||||
assert_eq!(s.history_len(), steps + 1, "one undo step");
|
||||
|
||||
// Paste in place: back keyframe by keyframe, where each came from.
|
||||
let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 8}));
|
||||
assert_eq!((v["pasted"].as_u64(), v["keyframes"].as_u64(), v["skipped"].as_u64()), (Some(2), Some(2), Some(0)));
|
||||
assert_eq!(count(&s), [2, 0, 2]);
|
||||
assert!(near(bounds_on(&s, a, 8)[1], [90.0, 10.0, 110.0, 30.0]), "in place");
|
||||
assert_eq!(v["items"].as_array().map(Vec::len), Some(2), "what was pasted is what is selected");
|
||||
// Markers that leave out frame 8: only the copy from 0 goes back.
|
||||
let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 3}));
|
||||
assert_eq!((v["pasted"].as_u64(), v["skipped"].as_u64()), (Some(1), Some(1)));
|
||||
assert_eq!(count(&s), [3, 0, 2]);
|
||||
|
||||
// Copied on one frame: onto every keyframe shown.
|
||||
run(&mut s, "timeline.goto", json!({"frame": 0}));
|
||||
let small = key(&s, a, 0).elements[0].id;
|
||||
run(&mut s, "element.select", json!({"ids": [small.0]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let v = run(&mut s, "frames.paste", json!({"first": 0, "last": 8}));
|
||||
assert_eq!((v["pasted"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3)));
|
||||
assert_eq!(count(&s), [4, 1, 3]);
|
||||
|
||||
// Cut: copies, then deletes, as one step.
|
||||
let steps = s.history_len();
|
||||
let v = run(&mut s, "frames.cut", json!({"first": 0, "last": 8}));
|
||||
assert_eq!(v["cut"], json!(8));
|
||||
assert_eq!(count(&s), [0, 0, 0]);
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
// A plain Paste puts a multi-frame copy on the current frame, on the active layer.
|
||||
run(&mut s, "timeline.goto", json!({"frame": 4}));
|
||||
run(&mut s, "edit.paste_in_place", json!({}));
|
||||
assert_eq!(count(&s), [0, 8, 0]);
|
||||
|
||||
// Nothing to act on, or nowhere to paste: refused.
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": a.0}));
|
||||
assert!(s.execute("frames.paste", &json!({"first": 0, "last": 8})).is_err(), "a locked layer");
|
||||
}
|
||||
|
||||
/// Raw (merge-drawing) rectangles, the same colour, on keyframes 0 and 5: one at x 0..40 and one
|
||||
/// at x 100..140 (y 0..40). Their ids on each keyframe.
|
||||
fn raw_pair() -> (Session, LayerId) {
|
||||
let mut s = Session::default();
|
||||
s.style.object_drawing = false;
|
||||
let layer = s.layer;
|
||||
for x in [0, 100] {
|
||||
run(&mut s, "draw.rect", json!({"x": x, "y": 0, "w": 40, "h": 40, "fill": "#3366ff", "stroke": null}));
|
||||
}
|
||||
run(&mut s, "timeline.goto", json!({"frame": 5}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 0}));
|
||||
(s, layer)
|
||||
}
|
||||
|
||||
fn raw_fills(s: &Session, layer: LayerId, start: u32) -> Vec<Rect> {
|
||||
key(s, layer, start).elements.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_some())).map(|e| e.bounds(&s.doc)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_shapes_merge_again_on_each_keyframe_after_a_move_or_transform() {
|
||||
let (mut s, a) = raw_pair();
|
||||
assert_eq!(raw_fills(&s, a, 0).len(), 2);
|
||||
let right = |s: &Session, f: u32| key(s, a, f).elements.iter().find(|e| e.bounds(&s.doc).min.x > 50.0).map(|e| json!([a.0, f, e.id.0])).unwrap();
|
||||
let items = json!([right(&s, 0), right(&s, 5)]);
|
||||
// Moved left by 80 it overlaps the other (x 20..60): one fill region on each keyframe.
|
||||
let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 5, "dx": -80, "dy": 0, "items": items}));
|
||||
for f in [0, 5] {
|
||||
let fills = raw_fills(&s, a, f);
|
||||
assert_eq!(fills.len(), 1, "keyframe {f}: joined into one fill: {fills:?}");
|
||||
assert!(near(fills[0], [0.0, 0.0, 60.0, 40.0]), "keyframe {f}: {:?}", fills[0]);
|
||||
}
|
||||
// The selection is the merged pieces, with their new ids.
|
||||
let after: Vec<Value> = v["items"].as_array().unwrap().clone();
|
||||
assert_eq!(after.len(), 2);
|
||||
for it in &after {
|
||||
let f = it[1].as_u64().unwrap() as u32;
|
||||
assert!(key(&s, a, f).elements.iter().any(|e| json!(e.id.0) == it[2]), "{it} is on its keyframe");
|
||||
}
|
||||
s.undo().unwrap();
|
||||
assert_eq!(raw_fills(&s, a, 5).len(), 2, "one undo takes the move and the merge back");
|
||||
|
||||
// A drag holds the merge back (merge: false) and merges when it ends (frames.merge).
|
||||
let items = json!([right(&s, 0), right(&s, 5)]);
|
||||
s.begin_gesture("Move");
|
||||
for _ in 0..4 {
|
||||
run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 5, "dx": -20, "dy": 0, "items": items, "merge": false}));
|
||||
}
|
||||
assert_eq!(raw_fills(&s, a, 0).len(), 2, "not merged mid-drag");
|
||||
let v = run(&mut s, "frames.merge", json!({"first": 0, "last": 5, "items": items}));
|
||||
s.end_gesture();
|
||||
assert_eq!([0, 5].map(|f| raw_fills(&s, a, f).len()), [1, 1]);
|
||||
assert_eq!(v["items"].as_array().map(Vec::len), Some(2));
|
||||
assert!(s.execute("frames.merge", &json!({"first": 0, "last": 5})).is_err(), "items are required");
|
||||
|
||||
// A transform merges too: the right square scaled 3× about its right edge reaches over.
|
||||
s.undo().unwrap();
|
||||
let items = json!([right(&s, 0), right(&s, 5)]);
|
||||
run(&mut s, "frames.transform", json!({"first": 0, "last": 5, "items": items, "scale_x": 3, "pivot": [140, 0]}));
|
||||
for f in [0, 5] {
|
||||
let fills = raw_fills(&s, a, f);
|
||||
assert_eq!(fills.len(), 1, "keyframe {f}: {fills:?}");
|
||||
assert!(near(fills[0], [0.0, 0.0, 140.0, 40.0]), "keyframe {f}: {:?}", fills[0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_motion_tweens_object_moves_but_does_not_scale_on_several_frames() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "object": true}));
|
||||
run(&mut s, "timeline.insert_frame", json!({"count": 9}));
|
||||
run(&mut s, "timeline.create_motion_tween", json!({}));
|
||||
let before = s.doc.clone();
|
||||
let e = s.execute("frames.transform", &json!({"first": 0, "last": 9, "rotate": 30}));
|
||||
assert!(e.is_err_and(|e| e.to_string().contains("motion tween")));
|
||||
assert!(s.doc == before);
|
||||
run(&mut s, "frames.transform", json!({"first": 0, "last": 9, "a": 1, "b": 0, "c": 0, "d": 1, "e": 10, "f": 0}));
|
||||
}
|
||||
|
||||
/// A symbol open in place (ADR 0045) whose own timeline has keyframes on 0 and 4, the playhead on 4.
|
||||
fn in_symbol() -> (Session, LayerId, ElementId) {
|
||||
let mut s = Session::default();
|
||||
let id = ElementId(run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap());
|
||||
run(&mut s, "modify.convert_to_symbol", json!({"name": "Walker"}));
|
||||
run(&mut s, "element.translate", json!({"dx": 100, "dy": 50}));
|
||||
run(&mut s, "symbol.edit", json!({}));
|
||||
let inner = s.layer;
|
||||
run(&mut s, "timeline.goto", json!({"frame": 4}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
run(&mut s, "element.select", json!({"ids": [id.0]}));
|
||||
run(&mut s, "element.translate", json!({"dx": 40, "dy": 0}));
|
||||
assert_eq!(s.editing.len(), 1);
|
||||
(s, inner, id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_a_symbol_the_commands_edit_its_own_keyframes() {
|
||||
let (mut s, inner, id) = in_symbol();
|
||||
let shown = s.multi_frame_items(0, 4);
|
||||
assert_eq!(shown.iter().map(|(it, _)| it.frame).collect::<Vec<_>>(), vec![0, 4], "the symbol's keyframes");
|
||||
run(&mut s, "frames.transform", json!({"first": 0, "last": 4, "scale_x": 2, "scale_y": 2}));
|
||||
// In the symbol's space (its registration point at the square's centre) the two copies
|
||||
// span x −10..50, y −10..10 together: the pivot is (20, 0).
|
||||
assert!(near(bounds_on(&s, inner, 0)[0], [-40.0, -20.0, 0.0, 20.0]));
|
||||
assert!(near(bounds_on(&s, inner, 4)[0], [40.0, -20.0, 80.0, 20.0]));
|
||||
run(&mut s, "frames.copy", json!({"first": 0, "last": 4, "items": [[inner.0, 0, id.0]]}));
|
||||
run(&mut s, "frames.paste", json!({"first": 0, "last": 4}));
|
||||
assert_eq!(key(&s, inner, 0).elements.len(), 2);
|
||||
run(&mut s, "frames.delete", json!({"first": 0, "last": 4}));
|
||||
assert!([0, 4].iter().all(|&f| key(&s, inner, f).elements.is_empty()));
|
||||
// The scene's own timeline never changed shape: one layer, one instance.
|
||||
assert_eq!(s.doc.timeline(s.scene).layers.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() {
|
||||
let (s, _, _) = in_symbol();
|
||||
let pic = s.stage_picture();
|
||||
let front = pic.front.clone().expect("the open symbol is in front");
|
||||
assert_eq!(front.frame, 4);
|
||||
let plain = crate::render_service::display_list_with_onion(&pic.doc, pic.frame, None);
|
||||
let ghosts = OnionSkin { markers: crate::onion::Markers::Relative { before: 4, after: 0 }, keyframes_only: true, ..OnionSkin::default() };
|
||||
let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &ghosts);
|
||||
assert_eq!(dl.items.len(), plain.items.len() + 1, "frame 0 of the symbol under its frame 4");
|
||||
// The symbol's origin stands at x 110: its frame 0 (x −10..10) shows at x 100..120, tinted
|
||||
// and faded; its frame 4 (x 30..50) at 140..160 at full strength, on top.
|
||||
let left = |i: &anicraft_doc::DisplayItem| i.path.bounds().transformed(&i.transform).min.x;
|
||||
let n = dl.items.len();
|
||||
let (ghost, now) = (&dl.items[n - 2], &dl.items[n - 1]);
|
||||
assert_eq!((left(ghost), left(now)), (100.0, 140.0));
|
||||
assert!(ghost.color.alpha < 1.0 && ghost.color.tint_amount > 0.0 && now.color.alpha == 1.0);
|
||||
// The job does the same, keyed apart from the plain picture.
|
||||
let view = anicraft_render::View { transform: Affine::IDENTITY, width: 64, height: 64, background: None };
|
||||
let plain_job = crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, Some(&ghosts));
|
||||
let job = plain_job.clone().inside(pic.front.clone());
|
||||
assert_ne!(job.key, plain_job.key);
|
||||
assert_eq!(job.display_list().items.len(), dl.items.len());
|
||||
// Edit Multiple Frames shows both keyframes at full strength.
|
||||
let multi = OnionSkin { edit_multiple: true, markers: crate::onion::Markers::Relative { before: 4, after: 0 }, ..OnionSkin::default() };
|
||||
let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi);
|
||||
assert!(dl.items.iter().rev().take(2).all(|i| i.color.alpha == 1.0 && i.color.tint_amount == 0.0));
|
||||
// With nothing to add, the job draws the picture as it is.
|
||||
let off = make_off(&pic);
|
||||
assert_eq!(off.display_list().items.len(), plain.items.len());
|
||||
}
|
||||
|
||||
fn make_off(pic: &crate::editing::StagePicture) -> crate::render_service::FrameJob {
|
||||
let view = anicraft_render::View { transform: Affine::IDENTITY, width: 64, height: 64, background: None };
|
||||
crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, None).inside(pic.front.clone())
|
||||
}
|
||||
|
||||
|
||||
/// Measured numbers for ADR 0051: `cargo test -p anicraft-engine --lib multi_timings -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn multi_timings() {
|
||||
use std::time::Instant;
|
||||
// 24 keyframes, each with 12 × 12 raw squares and 50 objects.
|
||||
let mut s = Session::default();
|
||||
s.style.object_drawing = false;
|
||||
for i in 0..144 {
|
||||
let (x, y) = ((i % 12) as f32 * 50.0, (i / 12) as f32 * 50.0);
|
||||
run(&mut s, "draw.rect", json!({"x": x, "y": y, "w": 30, "h": 30, "fill": "#3366ff", "stroke": null}));
|
||||
}
|
||||
for i in 0..50 {
|
||||
run(&mut s, "draw.rect", json!({"x": 700 + i, "y": i * 10, "w": 20, "h": 20, "object": true}));
|
||||
}
|
||||
for f in 1..24 {
|
||||
run(&mut s, "timeline.goto", json!({"frame": f * 2}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
}
|
||||
let last = 47;
|
||||
let t = |label: &str, f: &mut dyn FnMut(&mut Session)| {
|
||||
let mut s2 = Session::new(s.doc.clone());
|
||||
let t0 = Instant::now();
|
||||
f(&mut s2);
|
||||
eprintln!("{label}: {:.2} ms", t0.elapsed().as_secs_f64() * 1000.0);
|
||||
};
|
||||
let objects = |s: &Session| -> Vec<Value> { s.multi_frame_items(0, last).into_iter().filter(|(it, _)| key(s, it.layer, it.frame).elements.iter().any(|e| e.id == it.element && !matches!(&e.kind, ElementKind::Shape(sh) if sh.merge))).map(|(it, _)| it.to_json()).collect() };
|
||||
let raws = |s: &Session| -> Vec<Value> { s.multi_frame_items(0, last).into_iter().filter(|(it, _)| key(s, it.layer, it.frame).elements.iter().any(|e| e.id == it.element && matches!(&e.kind, ElementKind::Shape(sh) if sh.merge))).map(|(it, _)| it.to_json()).take(24 * 12).collect() };
|
||||
let (objects, raws) = (objects(&s), raws(&s));
|
||||
eprintln!("items shown: {}, objects: {}, raw: {}", s.multi_frame_items(0, last).len(), objects.len(), raws.len());
|
||||
t("list what is shown (24 keyframes)", &mut |s| drop(s.multi_frame_items(0, last)));
|
||||
t("move 1,200 objects, a drag step", &mut |s| drop(run(s, "frames.edit_multiple", json!({"first": 0, "last": last, "dx": 1, "dy": 0, "items": objects, "merge": false}))));
|
||||
t("rotate 1,200 objects", &mut |s| drop(run(s, "frames.transform", json!({"first": 0, "last": last, "rotate": 15, "items": objects}))));
|
||||
t("move and merge 288 raw squares (24 keyframes)", &mut |s| drop(run(s, "frames.edit_multiple", json!({"first": 0, "last": last, "dx": 25, "dy": 0, "items": raws}))));
|
||||
t("copy 1,200 objects, paste in place", &mut |s| {
|
||||
run(s, "frames.copy", json!({"first": 0, "last": last, "items": objects}));
|
||||
run(s, "frames.paste", json!({"first": 0, "last": last}));
|
||||
});
|
||||
t("delete everything shown", &mut |s| drop(run(s, "frames.delete", json!({"first": 0, "last": last}))));
|
||||
}
|
||||
+17
-89
@@ -18,10 +18,9 @@
|
||||
//! Behaviour learned from Adobe's public help pages on onion skinning and from watching the
|
||||
//! program; nothing was copied.
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session};
|
||||
use crate::{CommandSpec, MAX_FRAME, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline};
|
||||
use anicraft_geom::{Affine, Rect, Vec2};
|
||||
use anicraft_geom::{Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
@@ -341,9 +340,14 @@ fn interleave(tl: &Timeline, parts: Vec<DisplayList>) -> (DisplayList, Vec<usize
|
||||
/// or Edit Multiple Frames' keyframes, each under the playhead's artwork on its own layer.
|
||||
/// `eval` evaluates one frame of the scene (with or without its camera).
|
||||
pub fn compose(doc: &Document, scene: usize, local: u32, skin: Option<&OnionSkin>, eval: impl Fn(usize, u32) -> DisplayList + Sync) -> DisplayList {
|
||||
let now = eval(scene, local);
|
||||
compose_timeline(doc.timeline(scene), local, skin, |f| eval(scene, f))
|
||||
}
|
||||
|
||||
/// [`compose`] for any timeline: `tl` at its frame `local`, `eval` evaluating one of its frames
|
||||
/// (a scene's, or a symbol's open in place, ADR 0051). Pure: the same inputs give the same list.
|
||||
pub fn compose_timeline(tl: &Timeline, local: u32, skin: Option<&OnionSkin>, eval: impl Fn(u32) -> DisplayList + Sync) -> DisplayList {
|
||||
let now = eval(local);
|
||||
let Some(skin) = skin.filter(|s| s.shows()) else { return now };
|
||||
let tl = doc.timeline(scene);
|
||||
let (first, last) = skin.range(local, tl.frame_count());
|
||||
let extras = if skin.edit_multiple { multi_frames(tl, local, first, last) } else { onion_frames(tl, local, skin) };
|
||||
if extras.is_empty() {
|
||||
@@ -351,7 +355,7 @@ pub fn compose(doc: &Document, scene: usize, local: u32, skin: Option<&OnionSkin
|
||||
}
|
||||
// The frames are independent: evaluated in parallel, kept in order.
|
||||
use rayon::prelude::*;
|
||||
let mut parts: Vec<DisplayList> = extras.par_iter().map(|e| eval(scene, e.frame)).collect();
|
||||
let mut parts: Vec<DisplayList> = extras.par_iter().map(|e| eval(e.frame)).collect();
|
||||
for (part, e) in parts.iter_mut().zip(&extras) {
|
||||
keep_layers(part, &e.layers);
|
||||
if let Some(past) = e.past {
|
||||
@@ -391,11 +395,15 @@ impl Session {
|
||||
/// (each keyframe as it looks on its first frame, the playhead's as it looks there), with
|
||||
/// the keyframe start of each item's layer (`None`: a layer it doesn't edit).
|
||||
fn multi_list(&self, first: u32, last: u32) -> (DisplayList, Vec<Option<u32>>) {
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
// The timeline being edited: a symbol open in place has its own frames (ADR 0045).
|
||||
let tl = self.timeline();
|
||||
let mut parts = Vec::new();
|
||||
let mut starts: Vec<Vec<(LayerId, u32)>> = Vec::new();
|
||||
for e in multi_frames(tl, self.frame, first, last) {
|
||||
let mut dl = anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame);
|
||||
let mut dl = match self.editing_symbol().and_then(|id| self.doc.symbol(id)) {
|
||||
Some(sym) => anicraft_doc::evaluate_timeline(&self.doc, &sym.timeline, e.frame),
|
||||
None => anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame),
|
||||
};
|
||||
keep_layers(&mut dl, &e.layers);
|
||||
parts.push(dl);
|
||||
starts.push(e.layers.iter().map(|l| (*l, e.frame)).collect());
|
||||
@@ -450,95 +458,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("frames.artwork", "Artwork on Multiple Frames", "", None, "{first, last} lists every element Edit Multiple Frames shows in frames first..=last (0-based): [layer, frame (its keyframe's first frame), id] with stage bounds; the playhead's elements as they look there", false, artwork as crate::RunFn),
|
||||
c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..]} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; one undo step", true, edit_multiple),
|
||||
]
|
||||
}
|
||||
|
||||
/// The `first` and `last` params, in order.
|
||||
fn range_param(p: &Value) -> Result<(u32, u32)> {
|
||||
let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)")));
|
||||
let (a, b) = (req("first")?, req("last")?);
|
||||
if a.max(b) > MAX_FRAME {
|
||||
return Err(EngineError::Param(format!("frames go up to {MAX_FRAME}")));
|
||||
}
|
||||
Ok((a.min(b), a.max(b)))
|
||||
}
|
||||
|
||||
fn artwork(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let (first, last) = crate::multi::range_param(p)?;
|
||||
let items: Vec<Value> = s.multi_frame_items(first, last).into_iter().map(|(it, b)| json!({"layer": it.layer.0, "frame": it.frame, "id": it.element.0, "bounds": [b.min.x, b.min.y, b.max.x, b.max.y]})).collect();
|
||||
Ok(json!({"first": first, "last": last, "items": items}))
|
||||
}
|
||||
|
||||
/// Most items `frames.edit_multiple` takes.
|
||||
const MAX_ITEMS: usize = 100_000;
|
||||
|
||||
fn items_param(p: &Value) -> Result<Option<Vec<FrameItem>>> {
|
||||
let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into());
|
||||
let list = v.as_array().ok_or_else(bad)?;
|
||||
if list.len() > MAX_ITEMS {
|
||||
return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items")));
|
||||
}
|
||||
list.iter()
|
||||
.map(|t| {
|
||||
let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?;
|
||||
let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad);
|
||||
let frame = u32::try_from(n(1)?).map_err(|_| bad())?;
|
||||
Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) })
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
fn edit_multiple(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (first, last) = range_param(p)?;
|
||||
let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT {
|
||||
return Err(EngineError::Param("the move is too large".into()));
|
||||
}
|
||||
let shown: Vec<FrameItem> = s.multi_frame_items(first, last).into_iter().map(|(it, _)| it).collect();
|
||||
let items = match items_param(p)? {
|
||||
Some(list) => {
|
||||
let have: HashSet<FrameItem> = shown.iter().copied().collect();
|
||||
if let Some(bad) = list.iter().find(|it| !have.contains(it)) {
|
||||
return Err(EngineError::State(format!(
|
||||
"element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)",
|
||||
bad.element.0, bad.layer.0, bad.frame
|
||||
)));
|
||||
}
|
||||
list
|
||||
}
|
||||
None => shown,
|
||||
};
|
||||
// One pass per keyframe: (layer, keyframe start) → its ids.
|
||||
let mut by_key: BTreeMap<(LayerId, u32), HashSet<ElementId>> = BTreeMap::new();
|
||||
for it in &items {
|
||||
by_key.entry((it.layer, it.frame)).or_default().insert(it.element);
|
||||
}
|
||||
let mv = Affine::translate(d.x, d.y);
|
||||
let mut moved = 0usize;
|
||||
for ((layer, start), ids) in &by_key {
|
||||
let l = s.layer_mut(Some(*layer))?;
|
||||
let Some(ki) = l.keyframe_starting_at(*start) else { continue };
|
||||
let Some(kf) = l.keyframe_mut(ki) else { continue };
|
||||
// A motion tween's object carries its path and X/Y keys along (refused, with nothing
|
||||
// changed, if they would leave the stage's range).
|
||||
if let Some(m) = kf.motion.as_mut()
|
||||
&& ids.contains(&m.target)
|
||||
&& d != Vec2::ZERO
|
||||
&& !m.translate(d)
|
||||
{
|
||||
return Err(EngineError::State("the motion path would move out of range".into()));
|
||||
}
|
||||
for e in kf.elements_mut_where(|id| ids.contains(&id)) {
|
||||
e.transform = mv.mul(&e.transform);
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
Ok(json!({"moved": moved, "keyframes": by_key.len(), "dx": d.x, "dy": d.y}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "onion_tests.rs"]
|
||||
mod tests;
|
||||
@@ -4,6 +4,7 @@
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use anicraft_doc::{DisplayItem, ElementId, LayerId, Rgba, evaluate_scene, sample};
|
||||
use anicraft_geom::Affine;
|
||||
use anicraft_render::{View, render};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Placing Library items (a drop on the stage, Place on Stage), Swap Bitmap and Convert to Symbol
|
||||
//! into a folder (ADR 0053).
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{BitmapId, Element, ElementKind, FolderId, LibraryEntry, LibraryItem, Paint, SymbolId, SymbolKind, sample};
|
||||
use anicraft_geom::{Affine, Path, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, id: &str, p: Value) -> String {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => panic!("{id} {p} should fail, gave {v}"),
|
||||
Err(e) => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sym(s: &Session, name: &str) -> u64 {
|
||||
s.doc.library.iter().find(|x| x.name == name).map(|x| x.id.0).unwrap_or_else(|| panic!("no symbol {name}"))
|
||||
}
|
||||
|
||||
/// A `w`×`h` bitmap of one colour, added to the Library.
|
||||
fn add_bitmap(s: &mut Session, name: &str, w: u32, h: u32) -> BitmapId {
|
||||
let id = BitmapId(s.doc.alloc_id());
|
||||
let bytes = anicraft_render::encode_png(w, h, &[255, 0, 0, 255].repeat((w * h) as usize)).unwrap();
|
||||
s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(id, name, bytes).unwrap()));
|
||||
id
|
||||
}
|
||||
|
||||
fn add_sound(s: &mut Session, name: &str) -> u64 {
|
||||
let id = anicraft_doc::SoundId(s.doc.alloc_id());
|
||||
let wav = crate::cmds_sound::test_wav(8000, &[0.25; 8000]);
|
||||
s.doc.sounds.push(Arc::new(anicraft_doc::Sound::from_data(id, name, wav).unwrap()));
|
||||
id.0
|
||||
}
|
||||
|
||||
/// Element `id` on the timeline being edited.
|
||||
fn element(s: &Session, id: u64) -> Element {
|
||||
s.timeline().layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find(|e| e.id.0 == id).map(|e| (**e).clone()).unwrap_or_else(|| panic!("no element {id}"))
|
||||
}
|
||||
|
||||
fn shape(e: &Element) -> &anicraft_doc::Shape {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(sh) => sh,
|
||||
k => panic!("not a shape: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_places_symbols_bitmaps_and_a_sound_in_one_undo_step() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star"));
|
||||
let bitmap = add_bitmap(&mut s, "red.png", 4, 2);
|
||||
let sound = add_sound(&mut s, "beep.wav");
|
||||
run(&mut s, "timeline.goto", json!({"frame": 3}));
|
||||
let layer = s.layer;
|
||||
let before = s.doc.clone();
|
||||
let steps = s.history.undo_len();
|
||||
let v = run(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"symbol": star}, {"bitmap": bitmap.0}, {"sound": sound}], "x": 200, "y": 120}));
|
||||
assert_eq!(s.history.undo_len(), steps + 1, "one undo step");
|
||||
let ids: Vec<u64> = v["elements"].as_array().unwrap().iter().map(|x| x.as_u64().unwrap()).collect();
|
||||
assert_eq!(ids.len(), 3);
|
||||
assert_eq!(v["element"], ids[0]);
|
||||
assert_eq!(s.selection.ids().map(|e| e.0).collect::<Vec<_>>(), ids, "what was placed is selected");
|
||||
// Symbols stand with their registration point on the drop point; a bitmap is centred on it.
|
||||
for &id in &ids[..2] {
|
||||
assert_eq!(element(&s, id).transform.apply(Vec2::ZERO), Vec2::new(200.0, 120.0));
|
||||
}
|
||||
assert_eq!(element(&s, ids[2]).transform.apply(Vec2::new(2.0, 1.0)), Vec2::new(200.0, 120.0));
|
||||
// All on the active layer's keyframe at the playhead, the sound too.
|
||||
assert_eq!(s.layer, layer);
|
||||
let k = s.active_layer().unwrap().keyframe_at(3).unwrap();
|
||||
assert!(ids.iter().all(|id| k.elements.iter().any(|e| e.id.0 == *id)));
|
||||
assert_eq!(k.sound.as_ref().map(|f| f.sound.0), Some(sound));
|
||||
assert_eq!(v["sound"]["sound"], sound);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(s.doc, before, "one undo takes the whole drop back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_one_item_keeps_the_old_params_and_takes_a_sound_alone() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let sound = add_sound(&mut s, "beep.wav");
|
||||
let selected: Vec<_> = s.selection.ids().collect();
|
||||
let v = run(&mut s, "library.place", json!({"sound": sound}));
|
||||
assert_eq!(v["elements"], json!([]));
|
||||
assert!(v["element"].is_null());
|
||||
assert_eq!(s.selection.ids().collect::<Vec<_>>(), selected, "a sound alone leaves the selection");
|
||||
let k = s.active_layer().unwrap().keyframe_at(s.frame).unwrap();
|
||||
assert_eq!(k.sound.as_ref().map(|f| f.sound.0), Some(sound));
|
||||
// Without a position: the stage centre.
|
||||
let ball = sym(&s, "Ball");
|
||||
let el = run(&mut s, "library.place", json!({"symbol": ball}))["element"].as_u64().unwrap();
|
||||
let c = Vec2::new(s.doc.stage.width as f32 / 2.0, s.doc.stage.height as f32 / 2.0);
|
||||
assert_eq!(element(&s, el).transform.apply(Vec2::ZERO), c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_refuses_what_it_cannot_do_and_changes_nothing() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let ball = sym(&s, "Ball");
|
||||
let (a, b) = (add_sound(&mut s, "a.wav"), add_sound(&mut s, "b.wav"));
|
||||
let f = run(&mut s, "library.new_folder", json!({}))["folder"].as_u64().unwrap();
|
||||
let before = s.doc.clone();
|
||||
assert!(err(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"folder": f}]})).contains("folder"));
|
||||
assert!(err(&mut s, "library.place", json!({"items": [{"sound": a}, {"sound": b}]})).contains("one sound"));
|
||||
assert!(err(&mut s, "library.place", json!({"items": [{"symbol": ball}, {"symbol": 999_999}]})).contains("no symbol"));
|
||||
assert!(err(&mut s, "library.place", json!({"items": []})).contains("nothing"));
|
||||
assert!(err(&mut s, "library.place", json!({"items": "x"})).contains("list"));
|
||||
assert!(err(&mut s, "library.place", json!({"items": (0..1001).map(|_| json!({"symbol": ball})).collect::<Vec<_>>()})).contains("at most"));
|
||||
assert!(err(&mut s, "library.place", json!({"symbol": ball, "bitmap": 1})).contains("one item"));
|
||||
err(&mut s, "library.place", json!({"symbol": ball, "x": 1e300}));
|
||||
assert!(err(&mut s, "library.place", json!({"symbol": ball, "x": 2e6})).contains("million"));
|
||||
assert!(err(&mut s, "library.place", json!({"sound": 999_999})).contains("no sound"));
|
||||
assert_eq!(s.doc, before);
|
||||
// A locked layer takes neither artwork nor a sound.
|
||||
let layer = s.layer.0;
|
||||
run(&mut s, "layer.toggle_lock", json!({"layer": layer}));
|
||||
let locked = s.doc.clone();
|
||||
assert!(err(&mut s, "library.place", json!({"symbol": ball})).contains("locked"));
|
||||
assert!(err(&mut s, "library.place", json!({"sound": a})).contains("locked"));
|
||||
assert_eq!(s.doc, locked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_inside_a_symbol_open_for_editing_uses_its_space() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star"));
|
||||
run(&mut s, "symbol.edit", json!({"symbol": ball}));
|
||||
let el = run(&mut s, "library.place", json!({"symbol": star, "x": 5, "y": -7}))["element"].as_u64().unwrap();
|
||||
let inside = s.doc.symbol(SymbolId(ball)).unwrap().timeline.layers.iter().flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).find(|e| e.id.0 == el).cloned().expect("in the open symbol");
|
||||
assert_eq!(inside.transform.apply(Vec2::ZERO), Vec2::new(5.0, -7.0));
|
||||
assert!(err(&mut s, "library.place", json!({"items": [{"symbol": star}, {"symbol": ball}]})).contains("inside itself"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_bitmap_resizes_a_placed_bitmap_and_keeps_a_filled_shape() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let small = add_bitmap(&mut s, "small.png", 2, 2);
|
||||
let big = add_bitmap(&mut s, "big.png", 6, 4);
|
||||
let placed = run(&mut s, "library.place", json!({"bitmap": small.0, "x": 100, "y": 100}))["element"].as_u64().unwrap();
|
||||
let corner = element(&s, placed).transform.apply(Vec2::ZERO);
|
||||
// A drawn rectangle filled with the small bitmap, tiled, on a second layer.
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
let drawn = run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 30, "h": 30, "object": true}))["element"].as_u64().unwrap();
|
||||
let tiled = Paint::Bitmap { bitmap: small, repeat: true, matrix: Affine::scale(2.0, 2.0) };
|
||||
for e in s.editable_keyframe().unwrap().elements_mut_where(|id| id.0 == drawn) {
|
||||
if let ElementKind::Shape(sh) = &mut e.kind {
|
||||
sh.fill = Some(tiled.clone());
|
||||
}
|
||||
}
|
||||
let drawn_path = shape(&element(&s, drawn)).path.clone();
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
let steps = s.history.undo_len();
|
||||
let v = run(&mut s, "element.swap_bitmap", json!({"bitmap": big.0}));
|
||||
assert_eq!(v["swapped"], 2, "on both layers");
|
||||
assert_eq!(s.history.undo_len(), steps + 1);
|
||||
let p = element(&s, placed);
|
||||
assert_eq!(p.name, "big.png", "the name follows the bitmap");
|
||||
assert_eq!(p.transform.apply(Vec2::ZERO), corner, "the top-left corner stays");
|
||||
assert_eq!(*shape(&p).path, Path::rect(0.0, 0.0, 6.0, 4.0), "the new bitmap's size");
|
||||
assert_eq!(shape(&p).fill, Some(Paint::Bitmap { bitmap: big, repeat: false, matrix: Affine::IDENTITY }));
|
||||
let d = element(&s, drawn);
|
||||
assert_eq!(shape(&d).path, drawn_path, "a filled shape keeps its outline");
|
||||
assert_eq!(shape(&d).fill, Some(Paint::Bitmap { bitmap: big, repeat: true, matrix: Affine::scale(2.0, 2.0) }), "and its fill transform");
|
||||
// The old bitmap is now unused; one undo brings it back.
|
||||
assert!(s.doc.unused_items().contains(&LibraryItem::Bitmap(small)));
|
||||
s.undo().unwrap();
|
||||
assert!(!s.doc.unused_items().contains(&LibraryItem::Bitmap(small)));
|
||||
// Refusals.
|
||||
assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": 999_999})).contains("no bitmap"));
|
||||
assert!(err(&mut s, "element.swap_bitmap", json!({})).contains("'bitmap'"));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})).contains("nothing is selected"));
|
||||
let other = run(&mut s, "draw.rect", json!({"x": 300, "y": 300, "w": 5, "h": 5, "object": true}))["element"].as_u64().unwrap();
|
||||
run(&mut s, "element.select", json!({"ids": [other]}));
|
||||
assert!(err(&mut s, "element.swap_bitmap", json!({"bitmap": big.0})).contains("filled with one"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_symbol_goes_into_the_folder_asked_for_with_a_free_name() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let props = run(&mut s, "library.new_folder", json!({"name": "Props"}))["folder"].as_u64().unwrap();
|
||||
let entry = |v: &Value| LibraryEntry::Item(LibraryItem::Symbol(SymbolId(v["symbol"].as_u64().unwrap())));
|
||||
run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "object": true}));
|
||||
let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Ball", "kind": "movie_clip", "folder": props}));
|
||||
assert_eq!(v["folder"], props);
|
||||
assert_eq!(v["name"], "Ball", "Props has no Ball yet (the top level's doesn't count)");
|
||||
assert_eq!(s.doc.parent_of(entry(&v)), Some(FolderId(props)));
|
||||
assert_eq!(s.doc.entry_path(entry(&v)), "Props/Ball");
|
||||
assert_eq!(s.doc.symbol(SymbolId(v["symbol"].as_u64().unwrap())).unwrap().kind, SymbolKind::MovieClip);
|
||||
// The same name again in that folder gets a number; no name gives the next free “Symbol n”.
|
||||
run(&mut s, "draw.rect", json!({"x": 50, "y": 10, "w": 20, "h": 20, "object": true}));
|
||||
assert_eq!(run(&mut s, "modify.convert_to_symbol", json!({"name": "ball", "folder": props}))["name"], "ball 2");
|
||||
run(&mut s, "draw.rect", json!({"x": 90, "y": 10, "w": 20, "h": 20, "object": true}));
|
||||
let v = run(&mut s, "modify.convert_to_symbol", json!({"folder": props}));
|
||||
assert!(v["name"].as_str().unwrap().starts_with("Symbol "));
|
||||
assert_eq!(s.doc.symbol(SymbolId(v["symbol"].as_u64().unwrap())).unwrap().kind, SymbolKind::Graphic, "graphic by default");
|
||||
// Without a folder: the top level, as before.
|
||||
run(&mut s, "draw.rect", json!({"x": 130, "y": 10, "w": 20, "h": 20, "object": true}));
|
||||
let v = run(&mut s, "modify.convert_to_symbol", json!({}));
|
||||
assert!(v["folder"].is_null());
|
||||
assert_eq!(s.doc.parent_of(entry(&v)), None);
|
||||
// Refusals change nothing.
|
||||
run(&mut s, "draw.rect", json!({"x": 170, "y": 10, "w": 20, "h": 20, "object": true}));
|
||||
let before = s.doc.clone();
|
||||
assert!(err(&mut s, "modify.convert_to_symbol", json!({"folder": 999_999})).contains("no folder"));
|
||||
assert!(err(&mut s, "modify.convert_to_symbol", json!({"kind": "sprite"})).contains("symbol type"));
|
||||
assert_eq!(s.doc, before);
|
||||
// The file keeps where it went.
|
||||
let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap();
|
||||
assert_eq!(back.library_tree, s.doc.library_tree);
|
||||
}
|
||||
@@ -175,6 +175,9 @@ fn every_command_namespace_has_a_plugin_policy() {
|
||||
}
|
||||
assert!(plugin_may_call("draw.rect").is_ok());
|
||||
assert!(plugin_may_call("future.thing").is_err());
|
||||
// Edit Multiple Frames (ADR 0051): document edits yes, the clipboard no.
|
||||
assert!(["frames.transform", "frames.delete", "frames.align", "frames.merge", "frames.edit_multiple"].iter().all(|c| plugin_may_call(c).is_ok()));
|
||||
assert!(["frames.copy", "frames.cut", "frames.paste"].iter().all(|c| plugin_may_call(c).is_err()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! Adding and deleting raw anchors, smooth handle pairs, Make Smooth / Corner and snapping while
|
||||
//! drawing (ADR 0045), through the commands.
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{Element, ElementKind};
|
||||
use anicraft_geom::raw::{self as rawgeom};
|
||||
use anicraft_geom::walk::cubic_point;
|
||||
use anicraft_geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn raw_session() -> Session {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.object_drawing", json!({"on": false}));
|
||||
s
|
||||
}
|
||||
|
||||
fn raw(s: &Session) -> Vec<Arc<Element>> {
|
||||
s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect()
|
||||
}
|
||||
|
||||
fn is_fill(e: &Element) -> bool {
|
||||
matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())
|
||||
}
|
||||
|
||||
fn all_ids(s: &Session) -> Vec<anicraft_doc::ElementId> {
|
||||
raw(s).iter().map(|e| e.id).collect()
|
||||
}
|
||||
|
||||
fn anchors(s: &Session) -> Vec<Vec2> {
|
||||
s.raw_points(&all_ids(s)).anchors
|
||||
}
|
||||
|
||||
fn has(points: &[Vec2], p: (f32, f32)) -> bool {
|
||||
points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 0.3)
|
||||
}
|
||||
|
||||
fn area(e: &Element) -> f32 {
|
||||
let ElementKind::Shape(sh) = &e.kind else { return 0.0 };
|
||||
sh.path.flatten(&e.transform, 0.01).iter().map(|pl| pl.points.iter().zip(pl.points.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b)).sum::<f32>() * 0.5).sum::<f32>().abs()
|
||||
}
|
||||
|
||||
/// Every shape's anchors in stage space.
|
||||
fn shape_anchors(e: &Element) -> Vec<Vec2> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.path.editable_anchors().into_iter().map(|(_, q)| e.transform.apply(q)).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Largest distance from points of the curve `c` (stage space) to the shape's outline.
|
||||
fn off_outline(e: &Element, c: &rawgeom::Cubic) -> f32 {
|
||||
let ElementKind::Shape(sh) = &e.kind else { return f32::INFINITY };
|
||||
(0..=20).map(|i| sh.path.distance_to_edge(cubic_point(c, i as f32 / 20.0), &e.transform)).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
/// A raw arc (a fill under it and its outline): `M0 100 C0 0 200 0 200 100 Z`.
|
||||
fn arc(s: &mut Session) -> rawgeom::Cubic {
|
||||
run(s, "draw.path", json!({"d": "M0 100 C0 0 200 0 200 100 Z", "fill": "#ff0000", "stroke": "#000000"}));
|
||||
run(s, "edit.deselect", json!({}));
|
||||
[Vec2::new(0.0, 100.0), Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), Vec2::new(200.0, 100.0)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_added_point_is_shared_by_every_shape_on_the_edge_and_the_curve_keeps_its_shape() {
|
||||
let mut s = raw_session();
|
||||
let c = arc(&mut s);
|
||||
let before = anchors(&s).len();
|
||||
// How far the outlines are from the drawn curve (flattening): adding may not change it.
|
||||
let was: Vec<(anicraft_doc::ElementId, f32)> = raw(&s).iter().map(|e| (e.id, off_outline(e, &c))).collect();
|
||||
let top = cubic_point(&c, 0.5);
|
||||
let v = run(&mut s, "raw.add_point", json!({"x": top.x, "y": top.y + 1.0, "slop": 4}));
|
||||
let at = Vec2::new(v["x"].as_f64().unwrap_or(0.0) as f32, v["y"].as_f64().unwrap_or(0.0) as f32);
|
||||
assert!(at.distance(top) < 0.05, "on the curve: {at:?} vs {top:?}");
|
||||
assert_eq!(v["changed"].as_array().map(Vec::len), Some(2), "the fill and its outline: {v}");
|
||||
assert_eq!(anchors(&s).len(), before + 1, "listed once");
|
||||
let changed: Vec<u64> = v["changed"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect();
|
||||
for e in raw(&s).into_iter().filter(|e| changed.contains(&e.id.0)) {
|
||||
assert!(has(&shape_anchors(&e), (at.x, at.y)), "{} lacks the point", e.id.0);
|
||||
// Analytic: the old curve still lies on every shape's outline, as closely as before.
|
||||
let w = was.iter().find(|x| x.0 == e.id).map_or(0.0, |x| x.1);
|
||||
assert!(off_outline(&e, &c) <= w + 1e-3 && w < 0.25, "the curve moved: {} (was {w})", off_outline(&e, &c));
|
||||
}
|
||||
// One undo step; a second point at the same place is refused.
|
||||
assert!(s.can_undo());
|
||||
assert!(s.execute("raw.add_point", &json!({"x": at.x, "y": at.y})).is_err());
|
||||
assert!(s.execute("raw.add_point", &json!({"x": 900, "y": 900})).is_err(), "nothing there");
|
||||
// Deleting it gives the curve back, in both shapes.
|
||||
run(&mut s, "raw.delete_points", json!({"points": [[at.x, at.y]]}));
|
||||
assert_eq!(anchors(&s).len(), before);
|
||||
let on_curve: Vec<Arc<Element>> = raw(&s).into_iter().filter(|e| off_outline(e, &c) < 0.3).collect();
|
||||
assert_eq!(on_curve.len(), 2, "the fill and the arc's line still follow the curve");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_corner_rejoins_the_fill_and_its_outline() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let steps = s.history_len();
|
||||
let v = run(&mut s, "raw.delete_points", json!({"points": [[0, 0]]}));
|
||||
assert_eq!(v["deleted"], json!(1), "{v}");
|
||||
assert_eq!(s.history_len(), steps + 1, "one undo step");
|
||||
// A triangle of half the area, outlined all round.
|
||||
let fill: Vec<Arc<Element>> = raw(&s).into_iter().filter(|e| is_fill(e)).collect();
|
||||
assert_eq!(fill.len(), 1);
|
||||
assert!((area(&fill[0]) - 4000.0).abs() < 1.0, "{}", area(&fill[0]));
|
||||
let pts = anchors(&s);
|
||||
assert_eq!(pts.len(), 3, "{pts:?}");
|
||||
assert!(!has(&pts, (0.0, 0.0)));
|
||||
// Connectivity: every shape's anchors are shared with another shape.
|
||||
let all = raw(&s);
|
||||
for e in &all {
|
||||
for p in shape_anchors(e) {
|
||||
let n = all.iter().filter(|o| o.id != e.id && has(&shape_anchors(o), (p.x, p.y))).count();
|
||||
assert!(n >= 1, "{p:?} of {} is on no other shape", e.id.0);
|
||||
}
|
||||
}
|
||||
// The diagonal is stroked: some outline runs from (0, 80) to (100, 0).
|
||||
let diag = rawgeom::Seg::line(Vec2::new(0.0, 80.0), Vec2::new(100.0, 0.0)).c;
|
||||
assert!(all.iter().filter(|e| !is_fill(e)).any(|e| off_outline(e, &diag) < 0.05), "no line on the new edge");
|
||||
s.undo().unwrap_or_default();
|
||||
assert_eq!(anchors(&s).len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_last_points_of_a_line_removes_it_and_junctions_stay() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0, "stroke": "#000000"}));
|
||||
let v = run(&mut s, "raw.delete_points", json!({"points": [[100, 0]]}));
|
||||
assert_eq!(v["removed"].as_array().map(Vec::len), Some(1), "a one-segment line goes: {v}");
|
||||
assert!(raw(&s).is_empty());
|
||||
assert!(s.selection.is_empty(), "nothing selected that is gone");
|
||||
// A T: the point where the stem stands on the bar joins three edges.
|
||||
run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0, "stroke": "#000000"}));
|
||||
run(&mut s, "draw.line", json!({"x0": 50, "y0": 0, "x1": 50, "y1": 60, "stroke": "#000000"}));
|
||||
let n = raw(&s).len();
|
||||
let e = s.execute("raw.delete_points", &json!({"points": [[50, 0]]}));
|
||||
assert!(e.is_err_and(|e| e.to_string().contains("three or more")));
|
||||
assert_eq!(raw(&s).len(), n);
|
||||
// The stem's free end shortens nothing else.
|
||||
run(&mut s, "raw.delete_points", json!({"points": [[50, 60]]}));
|
||||
assert!(!has(&anchors(&s), (50.0, 60.0)));
|
||||
assert!(has(&anchors(&s), (0.0, 0.0)) && has(&anchors(&s), (100.0, 0.0)));
|
||||
assert!(s.execute("raw.delete_points", &json!({"points": []})).is_err());
|
||||
assert!(s.execute("raw.delete_points", &json!({"points": [[500, 500]]})).is_err());
|
||||
}
|
||||
|
||||
/// A raw S-curve stroke through (100, 0) with a smooth anchor there.
|
||||
fn s_curve(s: &mut Session) {
|
||||
run(s, "draw.path", json!({"d": "M0 0 C0 -50 60 -50 100 0 C140 50 200 50 200 0", "stroke": "#000000", "fill": null}));
|
||||
run(s, "edit.deselect", json!({}));
|
||||
}
|
||||
|
||||
/// The handles at `a` listed by `raw.points`.
|
||||
fn handles_at(s: &Session, a: Vec2) -> Vec<crate::cmds_rawsub::Handle> {
|
||||
s.raw_points(&all_ids(s)).handles.into_iter().filter(|h| h.anchor.distance(a) < 0.3).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_a_smooth_anchors_handle_keeps_the_other_opposite_and_alt_breaks_it() {
|
||||
let mut s = raw_session();
|
||||
s_curve(&mut s);
|
||||
let a = Vec2::new(100.0, 0.0);
|
||||
let hs = handles_at(&s, a);
|
||||
assert_eq!(hs.len(), 2, "{hs:?}");
|
||||
let (h, k) = (hs[0], hs[1]);
|
||||
let len_k = k.at.distance(a);
|
||||
run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 0, "dy": 30}));
|
||||
let hs = handles_at(&s, a);
|
||||
assert_eq!(hs.len(), 2);
|
||||
let (moved, other) = if hs[0].at.distance(h.at + Vec2::new(0.0, 30.0)) < 0.5 { (hs[0], hs[1]) } else { (hs[1], hs[0]) };
|
||||
assert!(moved.at.distance(h.at + Vec2::new(0.0, 30.0)) < 0.5, "{hs:?}");
|
||||
// Colinear: on one line through the anchor, opposite, the other's length kept.
|
||||
assert!(rawgeom::smooth_at(a, moved.at, other.at), "{moved:?} {other:?}");
|
||||
assert!((moved.at - a).normalized().cross((other.at - a).normalized()).abs() < 1e-3);
|
||||
assert!((other.at.distance(a) - len_k).abs() < 0.3);
|
||||
// Alt (smooth: false) moves the handle alone: a corner.
|
||||
let before = other.at;
|
||||
run(&mut s, "raw.move_handle", json!({"id": moved.id.0, "cmd": moved.cmd, "slot": moved.slot, "dx": 30, "dy": 0, "smooth": false}));
|
||||
let hs = handles_at(&s, a);
|
||||
assert!(hs.iter().any(|x| x.at.distance(before) < 0.3), "the other stays: {hs:?}");
|
||||
assert!(!rawgeom::smooth_at(a, hs[0].at, hs[1].at));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_corner_and_make_smooth_on_raw_anchors() {
|
||||
let mut s = raw_session();
|
||||
s_curve(&mut s);
|
||||
let a = Vec2::new(100.0, 0.0);
|
||||
let v = run(&mut s, "raw.convert_points", json!({"points": [[a.x, a.y]], "smooth": false}));
|
||||
assert_eq!(v["converted"], json!(1), "{v}");
|
||||
assert!(handles_at(&s, a).is_empty(), "the handles are drawn in");
|
||||
let v = run(&mut s, "raw.convert_points", json!({"points": [[a.x, a.y]], "smooth": true}));
|
||||
assert_eq!(v["converted"], json!(1), "{v}");
|
||||
let hs = handles_at(&s, a);
|
||||
assert_eq!(hs.len(), 2, "{hs:?}");
|
||||
assert!(rawgeom::smooth_at(a, hs[0].at, hs[1].at));
|
||||
// Smooth on a fill's corner: the fill and both sides it has there follow.
|
||||
run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
let v = run(&mut s, "raw.convert_points", json!({"points": [[300, 0]], "smooth": true}));
|
||||
assert_eq!(v["converted"], json!(1));
|
||||
let fill = raw(&s).into_iter().find(|e| is_fill(e)).unwrap_or_else(|| panic!("a fill"));
|
||||
assert!(area(&fill) > 8000.0, "the corner rounds out: {}", area(&fill));
|
||||
for e in raw(&s).iter().filter(|e| !is_fill(e) && e.transform.apply(Vec2::ZERO).x > 250.0) {
|
||||
let ElementKind::Shape(sh) = &e.kind else { continue };
|
||||
let ElementKind::Shape(fs) = &fill.kind else { continue };
|
||||
for pl in sh.path.flatten(&e.transform, 0.05) {
|
||||
for p in pl.points {
|
||||
assert!(fs.path.distance_to_edge(p, &fill.transform) < 0.3, "{p:?} off the fill's edge");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_snaps_to_anchors_then_lines_while_snap_to_objects_is_on() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
let v = run(&mut s, "draw.snap", json!({"x": 104, "y": 3, "snap": 10}));
|
||||
assert_eq!(v["snapped"]["to"], json!("point"), "{v}");
|
||||
assert_eq!((v["x"].as_f64(), v["y"].as_f64()), (Some(100.0), Some(0.0)));
|
||||
let v = run(&mut s, "draw.snap", json!({"x": 50, "y": 84, "snap": 10}));
|
||||
assert_eq!(v["snapped"]["to"], json!("line"), "{v}");
|
||||
assert!((v["y"].as_f64().unwrap_or(0.0) - 80.0).abs() < 1e-3 && (v["x"].as_f64().unwrap_or(0.0) - 50.0).abs() < 1e-3);
|
||||
let v = run(&mut s, "draw.snap", json!({"x": 300, "y": 300, "snap": 10}));
|
||||
assert!(v["snapped"].is_null());
|
||||
// Off, nothing snaps.
|
||||
run(&mut s, "draw.snap_to_objects", json!({"on": false}));
|
||||
let v = run(&mut s, "draw.snap", json!({"x": 104, "y": 3, "snap": 10}));
|
||||
assert!(v["snapped"].is_null() && v["x"] == json!(104.0));
|
||||
// A line drawn from a snapped point shares the rectangle's corner.
|
||||
run(&mut s, "draw.snap_to_objects", json!({"on": true}));
|
||||
let a = run(&mut s, "draw.snap", json!({"x": 98, "y": 78, "snap": 10}));
|
||||
run(&mut s, "draw.line", json!({"x0": a["x"], "y0": a["y"], "x1": 200, "y1": 200, "stroke": "#000000"}));
|
||||
assert!(has(&anchors(&s), (100.0, 80.0)) && anchors(&s).len() == 5, "{:?}", anchors(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_paths_smooth_anchor_keeps_its_handles_opposite() {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
let v = run(&mut s, "draw.path", json!({"d": "M0 0 C0 -50 60 -50 100 0 C140 50 200 50 200 0", "stroke": "#000000", "fill": null}));
|
||||
let id = v["element"].as_u64().unwrap_or(0);
|
||||
let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path"));
|
||||
let ElementKind::Shape(sh) = &el.kind else { panic!() };
|
||||
let p = sh.path.clone();
|
||||
// The in-handle of anchor 1 (C2 of command 1) moves; command 2's C1 turns with it.
|
||||
run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 2]], "dx": 0, "dy": 25}));
|
||||
let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path"));
|
||||
let ElementKind::Shape(sh) = &el.kind else { panic!() };
|
||||
let (a, h, k) = (sh.path.point(1, 0), sh.path.point(1, 2), sh.path.point(2, 1));
|
||||
let (Some(a), Some(h), Some(k)) = (a, h, k) else { panic!("points") };
|
||||
assert!(rawgeom::smooth_at(a, h, k), "{a:?} {h:?} {k:?}");
|
||||
assert!((k.distance(a) - p.point(2, 1).map_or(0.0, |q| q.distance(a))).abs() < 1e-3, "length kept");
|
||||
run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 2]], "dx": 30, "dy": 0, "smooth": false}));
|
||||
let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path"));
|
||||
let ElementKind::Shape(sh) = &el.kind else { panic!() };
|
||||
assert_eq!(sh.path.point(2, 1), Some(k), "Alt moves the handle alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_points_timings() {
|
||||
// ADR 0042's drawing: 12 × 12 outlined, rounded squares and a line across every row.
|
||||
let mut s = raw_session();
|
||||
for i in 0..12 {
|
||||
for j in 0..12 {
|
||||
run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000", "radius": 6}));
|
||||
}
|
||||
run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"}));
|
||||
}
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let n = s.visible_elements().len();
|
||||
let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1e3;
|
||||
let t = std::time::Instant::now();
|
||||
let v = run(&mut s, "raw.add_point", json!({"x": 320, "y": 300}));
|
||||
let add = ms(t);
|
||||
let at = [v["x"].as_f64().unwrap_or(0.0), v["y"].as_f64().unwrap_or(0.0)];
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "raw.delete_points", json!({"points": [at]}));
|
||||
let delete = ms(t);
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "raw.convert_points", json!({"points": [[306, 300]], "smooth": true}));
|
||||
let smooth = ms(t);
|
||||
let h = handles_at(&s, Vec2::new(306.0, 300.0)).first().copied().unwrap_or_else(|| panic!("handles after Make Smooth"));
|
||||
s.begin_gesture("Move Handle");
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 1, "dy": 1, "merge": false}));
|
||||
let pair = ms(t);
|
||||
s.end_gesture();
|
||||
let t = std::time::Instant::now();
|
||||
for k in 0..100 {
|
||||
let _ = s.execute("draw.snap", &json!({"x": 3 + k * 6, "y": 303, "snap": 10}));
|
||||
}
|
||||
let snap = ms(t) / 100.0;
|
||||
// Inside a symbol: the whole drawing converted, opened in place, and its stage picture.
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "modify.convert_to_symbol", json!({"name": "Grid"}));
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "symbol.edit", json!({}));
|
||||
let open = ms(t);
|
||||
let t = std::time::Instant::now();
|
||||
let pic = s.stage_picture();
|
||||
let picture = ms(t);
|
||||
let a = anchors(&s).first().copied().unwrap_or_else(|| panic!("anchors inside"));
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "raw.move_point", json!({"x": a.x, "y": a.y, "to_x": a.x - 5.0, "to_y": a.y}));
|
||||
let inside = ms(t);
|
||||
eprintln!("{n} raw shapes; add point {add:.2} ms, delete point {delete:.2} ms, make smooth {smooth:.2} ms, smooth handle frame {pair:.2} ms, draw snap {snap:.3} ms; inside a symbol: open {open:.2} ms, stage picture {picture:.2} ms (frame {}), point move {inside:.2} ms", pic.frame);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_edits_keep_a_dashed_lines_style() {
|
||||
let mut s = raw_session();
|
||||
// A dashed, butt-capped, mitred zigzag (ADR 0046).
|
||||
run(&mut s, "draw.path", json!({"d": "M0 0 L50 40 L100 0 L150 40", "stroke": "#000000", "fill": null, "stroke_width": 2, "cap": "none", "join": "miter", "dash": [6, 3]}));
|
||||
let styled = |s: &Session| {
|
||||
raw(s).iter().all(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.stroke.as_ref().is_some_and(|st| st.style.dash == anicraft_doc::Dash::dashed(6.0, 3.0) && st.style.cap == anicraft_doc::Cap::Butt && st.style.join == anicraft_doc::Join::Miter),
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
run(&mut s, "raw.add_point", json!({"x": 25, "y": 20}));
|
||||
run(&mut s, "raw.delete_points", json!({"points": [[50, 40]]}));
|
||||
run(&mut s, "raw.convert_points", json!({"points": [[100, 0]], "smooth": true}));
|
||||
assert!(!raw(&s).is_empty() && styled(&s), "every piece keeps the line's style");
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
//! keep its pictures on the GPU ([`Raster::Native`], ADR 0029): the cache then holds them, under
|
||||
//! a budget of their own, and only the shell knows what they are.
|
||||
|
||||
use crate::editing::Front;
|
||||
use crate::history::StateId;
|
||||
use crate::onion::OnionSkin;
|
||||
use anicraft_doc::{DisplayList, Document, evaluate_scene, evaluate_scene_camera};
|
||||
@@ -41,6 +42,9 @@ pub struct FrameJob {
|
||||
/// Seen through the scene's camera (View › Preview Through Camera, ADR 0027): what the
|
||||
/// movie shows, rather than the stage as edited.
|
||||
pub camera: bool,
|
||||
/// A symbol open in place, in front of the picture (ADR 0045): onion skin composes its own
|
||||
/// frames (ADR 0051). Set with [`FrameJob::inside`].
|
||||
pub front: Option<Arc<Front>>,
|
||||
}
|
||||
|
||||
impl FrameJob {
|
||||
@@ -58,6 +62,47 @@ impl FrameJob {
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The same job for a stage picture whose top layer is the open symbol `front` (from
|
||||
/// [`crate::editing::StagePicture::front`]): onion skin and Edit Multiple Frames then compose
|
||||
/// the symbol's frames, not the picture's one frame. Keyed apart from the plain job.
|
||||
pub fn inside(mut self, front: Option<Arc<Front>>) -> FrameJob {
|
||||
if let Some(f) = front {
|
||||
if self.onion.is_some() {
|
||||
let mix = |k: u64| {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
(k, "front", f.layer.0).hash(&mut h);
|
||||
h.finish()
|
||||
};
|
||||
self.key = mix(self.key);
|
||||
self.scene = mix(self.scene);
|
||||
}
|
||||
self.front = Some(f);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// What the job draws: its frame with what its onion settings add (ADR 0047), on the open
|
||||
/// symbol's own timeline when there is one (ADR 0051).
|
||||
pub fn display_list(&self) -> DisplayList {
|
||||
let onion = self.onion.as_ref().filter(|o| o.shows());
|
||||
match (&self.front, onion) {
|
||||
(Some(front), Some(skin)) => display_list_inside(&self.doc, self.frame, front, skin),
|
||||
_ => display_list_for(&self.doc, self.frame, self.onion.as_ref(), self.camera),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stage picture's frame with the open symbol in front composed by `skin`: the timelines around
|
||||
/// it as they are, then the symbol's frames, each layer's onion frames under its artwork.
|
||||
pub fn display_list_inside(doc: &Document, frame: u32, front: &Front, skin: &OnionSkin) -> DisplayList {
|
||||
let (scene, local) = doc.locate(frame);
|
||||
let mut around = doc.timeline(scene).clone();
|
||||
around.layers.retain(|l| l.id != front.layer);
|
||||
let mut dl = anicraft_doc::evaluate_timeline(doc, &around, local);
|
||||
let tl = &front.timeline;
|
||||
dl.append(crate::onion::compose_timeline(tl, front.frame, Some(skin), |f| anicraft_doc::evaluate_timeline_at(doc, tl, f, front.at)));
|
||||
dl
|
||||
}
|
||||
|
||||
/// A finished image: premultiplied RGBA8, ready for a texture upload, or (`native`) an image
|
||||
@@ -128,7 +173,7 @@ pub fn frame_key(state: StateId, frame: u32, view: &View, onion: Option<&OnionSk
|
||||
/// A job whose `scene` is derived from the same inputs as its key.
|
||||
pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob {
|
||||
let onion = onion.filter(|o| o.shows()).copied();
|
||||
FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false }
|
||||
FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false, front: None }
|
||||
}
|
||||
|
||||
/// A job for rasterizer `raster` (from [`RenderService::raster_id`]; 0 is the CPU oracle, and
|
||||
@@ -192,7 +237,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>)
|
||||
|
||||
/// Renders a job synchronously, evaluating its scene.
|
||||
pub fn render_job(job: &FrameJob) -> FrameImage {
|
||||
render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion.as_ref(), job.camera))
|
||||
render_job_with(job, &job.display_list())
|
||||
}
|
||||
|
||||
/// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel.
|
||||
@@ -204,7 +249,7 @@ pub fn render_batch(jobs: &[FrameJob]) -> Vec<FrameImage> {
|
||||
fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec<FrameImage> {
|
||||
let mut scenes: HashMap<u64, Arc<DisplayList>> = HashMap::new();
|
||||
for j in jobs {
|
||||
scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera)));
|
||||
scenes.entry(j.scene).or_insert_with(|| Arc::new(j.display_list()));
|
||||
}
|
||||
jobs.par_iter()
|
||||
.map(|j| {
|
||||
@@ -212,7 +257,7 @@ fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec<FrameImage> {
|
||||
let raster = slot.raster.as_ref().filter(|_| j.raster != 0 && j.raster == slot.id);
|
||||
match scenes.get(&j.scene) {
|
||||
Some(dl) => render_job_by(j, dl, raster),
|
||||
None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera), raster),
|
||||
None => render_job_by(j, &j.display_list(), raster),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -184,13 +184,13 @@ fn merge_results(results: Vec<(LayerId, Value)>) -> Value {
|
||||
impl Session {
|
||||
/// The elements on `layer` at the playhead (tweens applied).
|
||||
pub fn elements_on(&self, layer: LayerId) -> Vec<Arc<Element>> {
|
||||
self.doc.timeline(self.scene).layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default()
|
||||
self.timeline().layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether artwork on `layer` can be selected: it is in this scene, shown and unlocked
|
||||
/// (folders included), and not a folder.
|
||||
pub fn selectable(&self, layer: LayerId) -> bool {
|
||||
let tl = self.doc.timeline(self.scene);
|
||||
let tl = self.timeline();
|
||||
let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return false };
|
||||
tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder) && !tl.locked_by_folder(layer) && !tl.hidden_by_folder(i)
|
||||
}
|
||||
@@ -199,14 +199,14 @@ impl Session {
|
||||
/// artwork on it. The camera layer holds only the camera, and an armature layer's
|
||||
/// instances are posed by their bones, so they are gathered only while active.
|
||||
pub fn gathers(&self, layer: LayerId) -> bool {
|
||||
let kind = self.doc.timeline(self.scene).layer(layer).map(|l| l.kind);
|
||||
let kind = self.timeline().layer(layer).map(|l| l.kind);
|
||||
self.selectable(layer) && (layer == self.layer || !matches!(kind, Some(LayerKind::Camera | LayerKind::Armature)))
|
||||
}
|
||||
|
||||
/// The layers with selected items, top to bottom.
|
||||
pub fn selected_layers(&self) -> Vec<LayerId> {
|
||||
let mine = self.selection.layers();
|
||||
self.doc.timeline(self.scene).layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect()
|
||||
self.timeline().layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect()
|
||||
}
|
||||
|
||||
/// Every selected element as it looks at the playhead, with its layer: layers top to
|
||||
@@ -249,8 +249,10 @@ impl Session {
|
||||
/// locked (a locked or hidden layer is never selected), and keeps the active layer valid.
|
||||
pub fn fix_selection(&mut self) {
|
||||
self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1));
|
||||
if self.doc.timeline(self.scene).layer(self.layer).is_none() {
|
||||
self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id);
|
||||
// A symbol that is gone closes (ADR 0045).
|
||||
self.fix_editing();
|
||||
if self.timeline().layer(self.layer).is_none() {
|
||||
self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id);
|
||||
}
|
||||
if self.selection.is_empty() {
|
||||
return;
|
||||
@@ -321,7 +323,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.doc.timeline(self.scene).layer(active).is_some() {
|
||||
if self.timeline().layer(active).is_some() {
|
||||
self.layer = active;
|
||||
}
|
||||
self.selection = after;
|
||||
@@ -341,7 +343,7 @@ impl Session {
|
||||
crate::cmds_motion::finish_edit(self, edit);
|
||||
}
|
||||
self.dl_cache.replace(None);
|
||||
if self.doc.timeline(self.scene).layer(active).is_some() {
|
||||
if self.timeline().layer(active).is_some() {
|
||||
self.layer = active;
|
||||
}
|
||||
r
|
||||
|
||||
@@ -513,7 +513,7 @@ fn save_load_round_trip() {
|
||||
/// Adversarial params for every command: must return Ok or Err, never panic.
|
||||
#[test]
|
||||
fn panic_hunt_every_command() {
|
||||
let hostile: Vec<Value> = vec![
|
||||
let mut hostile: Vec<Value> = vec![
|
||||
Value::Null,
|
||||
json!({}),
|
||||
json!([]),
|
||||
@@ -623,6 +623,15 @@ fn panic_hunt_every_command() {
|
||||
json!({"first": u64::MAX, "last": 0, "dx": 5, "dy": 5, "items": []}),
|
||||
json!({"first": 40, "last": 0, "dx": 3, "dy": -2}),
|
||||
json!({"first": 0, "last": 100_001, "dx": f64::NAN, "dy": 0, "items": [[1, 2]]}),
|
||||
// Edit Multiple Frames, complete (ADR 0051): transforms at the limits, pivots and edges
|
||||
// that aren't, pastes onto ranges with nothing in them, merges of what isn't raw.
|
||||
json!({"first": 0, "last": 99_999, "a": 0, "b": 0, "c": 0, "d": 0, "e": 1e30, "f": 0, "merge": "x"}),
|
||||
json!({"first": 0, "last": 50, "a": 1e9, "b": 1, "c": 1, "d": 1e-9, "e": 0, "f": f64::NAN}),
|
||||
json!({"first": 0, "last": 50, "rotate": 1e9, "scale_x": 1e-9, "scale_y": -1e9, "skew_x": 90, "skew_y": -90, "pivot": [1e30, 0]}),
|
||||
json!({"first": 0, "last": 50, "rotate": 45, "skew_x": 89.999, "pivot": [5], "edge": "nope", "to_stage": "x"}),
|
||||
json!({"first": 0, "last": 50, "scale_x": -1, "pivot": [0, 0], "edge": "vcenter", "to_stage": true, "merge": false}),
|
||||
json!({"first": 3, "last": 1, "edge": "right", "layer": u64::MAX, "items": [[0, 0, 0]]}),
|
||||
json!({"first": 0, "last": 99_999, "layer": 0, "items": (0..200).map(|i| json!([i, i, i])).collect::<Vec<_>>()}),
|
||||
];
|
||||
// File commands are exercised separately (they touch the disk).
|
||||
let skip = |id: &str| id.starts_with("file.");
|
||||
@@ -677,7 +686,63 @@ fn panic_hunt_every_command() {
|
||||
layered.execute(id, &p).unwrap();
|
||||
}
|
||||
assert_eq!(layered.selected_layers().len(), 2, "the fuzz starts with a selection on two layers");
|
||||
for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered] {
|
||||
// Raw drawings inside a symbol open for editing in place (ADR 0045), with a point added.
|
||||
let mut in_symbol = Session::default();
|
||||
in_symbol.style.object_drawing = false;
|
||||
for (id, p) in [
|
||||
("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})),
|
||||
("modify.convert_to_symbol", json!({"name": "Inner"})),
|
||||
("element.translate", json!({"dx": 30, "dy": 15})),
|
||||
("symbol.edit", json!({})),
|
||||
("draw.rect", json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"})),
|
||||
("raw.add_point", json!({"x": 45, "y": 90})),
|
||||
] {
|
||||
in_symbol.execute(id, &p).unwrap();
|
||||
}
|
||||
assert_eq!(in_symbol.editing.len(), 1, "the fuzz starts inside a symbol");
|
||||
// Raw drawings on several keyframes, artwork copied from two of them (ADR 0051).
|
||||
let mut keyed = Session::default();
|
||||
keyed.style.object_drawing = false;
|
||||
for (id, p) in [
|
||||
("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})),
|
||||
("draw.rect", json!({"x": 100, "y": 0, "w": 60, "h": 60, "fill": "#ff0000"})),
|
||||
("timeline.goto", json!({"frame": 4})),
|
||||
("timeline.insert_keyframe", json!({})),
|
||||
("timeline.goto", json!({"frame": 8})),
|
||||
("timeline.insert_keyframe", json!({})),
|
||||
("frames.copy", json!({"first": 0, "last": 8})),
|
||||
("timeline.goto", json!({"frame": 4})),
|
||||
] {
|
||||
keyed.execute(id, &p).unwrap();
|
||||
}
|
||||
// Library folders, nested, with items in them (ADR 0050); the fuzz moves, renames and
|
||||
// deletes them, folders into themselves, names that clash or hold a slash.
|
||||
let mut library = Session::new(sample::demo());
|
||||
let outer = library.execute("library.new_folder", &json!({"name": "Characters"})).unwrap()["folder"].as_u64().unwrap();
|
||||
let inner = library.execute("library.new_folder", &json!({"name": "Hero", "parent": outer})).unwrap()["folder"].as_u64().unwrap();
|
||||
let ball = library.doc.library.first().map(|x| x.id.0).unwrap();
|
||||
library.execute("library.move", &json!({"items": [{"symbol": ball}], "to": inner})).unwrap();
|
||||
library.execute("library.duplicate", &json!({"symbol": ball})).unwrap();
|
||||
// ...and a bitmap placed on the stage, for Swap Bitmap (ADR 0053).
|
||||
let bm = anicraft_doc::BitmapId(library.doc.alloc_id());
|
||||
let png = anicraft_render::encode_png(3, 2, &[0, 0, 255, 255].repeat(6)).unwrap();
|
||||
library.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(bm, "b.png", png).unwrap()));
|
||||
library.execute("library.place", &json!({"bitmap": bm.0})).unwrap();
|
||||
hostile.push(json!({"bitmap": bm.0, "items": [{"bitmap": bm.0}, {"symbol": ball}], "x": 3, "y": 4}));
|
||||
hostile.extend([
|
||||
json!({"items": [{"folder": outer}], "to": inner, "folder": outer, "name": "Hero", "parent": inner, "confirm": true}),
|
||||
json!({"items": [{"folder": inner}, {"symbol": ball}, {"folder": inner}], "to": null, "folder": inner, "name": "a/b", "symbol": ball}),
|
||||
json!({"items": [{"symbol": ball, "folder": outer}, "x", {"sound": u64::MAX}], "to": u64::MAX, "parent": "x", "name": " "}),
|
||||
json!({"items": (0..200).map(|i| json!({"folder": i})).collect::<Vec<_>>(), "to": outer, "symbol": ball, "name": "x".repeat(300), "on": "x", "bitmap": 1}),
|
||||
json!({"items": [{"symbol": ball}], "to": outer, "symbol": ball, "name": "Ball copy", "confirm": true}),
|
||||
// Drops from the Library and Swap Bitmap (ADR 0053): mixed lists, two sounds, far points.
|
||||
json!({"items": [{"symbol": ball}, {"sound": SOUND}, {"bitmap": u64::MAX}], "x": 1e300, "y": -1e300}),
|
||||
json!({"items": [{"sound": SOUND}, {"sound": SOUND}, {"symbol": ball}], "x": 999_999, "y": -999_999, "bitmap": 0}),
|
||||
json!({"items": [{"symbol": ball}, {"symbol": ball}, {"folder": inner}, null], "x": "a"}),
|
||||
json!({"items": (0..1500).map(|_| json!({"symbol": ball})).collect::<Vec<_>>(), "x": 0, "y": 0}),
|
||||
json!({"sound": SOUND, "symbol": ball, "x": 10, "y": 10}),
|
||||
]);
|
||||
for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, keyed, library] {
|
||||
let mut s = start;
|
||||
for spec in commands().iter().filter(|c| !skip(c.id)) {
|
||||
for p in &hostile {
|
||||
@@ -689,14 +754,20 @@ fn panic_hunt_every_command() {
|
||||
let _ = s.execute(spec.id, p);
|
||||
}
|
||||
}
|
||||
// The document must still evaluate and render.
|
||||
// The document must still evaluate and render, and so must what the stage shows.
|
||||
for f in [0, 1, 5, 47, 1000] {
|
||||
let _ = anicraft_render::render_frame(&s.doc, f, 0.1);
|
||||
}
|
||||
let pic = s.stage_picture();
|
||||
let _ = anicraft_render::render_frame(&pic.doc, pic.frame, 0.1);
|
||||
// ...and its sounds lay out and mix.
|
||||
let voices = anicraft_doc::sound::voices(&s.doc, 8000);
|
||||
let mut out = vec![0.0; 2 * 4096];
|
||||
anicraft_doc::audio::mix(&voices, 8000, Default::default(), 0, &mut out);
|
||||
// ...and its Library tree stays whole: nothing a load would have to repair.
|
||||
let mut loaded = s.doc.clone();
|
||||
loaded.sanitize();
|
||||
assert_eq!(loaded.library_tree, s.doc.library_tree);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,15 @@
|
||||
//! package's `golden/` folder. Probes then check, by hand-worked colours, what the golden
|
||||
//! should show. `UPDATE_GOLDENS=1` rewrites the goldens (see `golden/mod.rs`).
|
||||
//!
|
||||
//! Each package also opens as a `.fla` archive, packed in every layout zip writers use, with
|
||||
//! `file.open`, as the same document and the same golden frames (ADR 0054).
|
||||
//!
|
||||
//! The report and structure of each package, and its hostile variants, are checked in the xfl
|
||||
//! crate (`crates/xfl/tests/corpus.rs`).
|
||||
|
||||
mod golden;
|
||||
#[path = "../../xfl/tests/support/fla.rs"]
|
||||
mod pack;
|
||||
|
||||
use anicraft_engine::Session;
|
||||
use anicraft_engine::doc::Document;
|
||||
@@ -204,3 +209,46 @@ fn raw_shapes_open_raw_merged_and_unchanged_to_the_eye() {
|
||||
assert!(raw_total > 0 && merged_total > 0, "the corpus has raw shapes, merged: {raw_total} shapes, {merged_total} keyframes");
|
||||
assert!(failures.is_empty(), "merged raw shapes look different:\n{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
/// Each package as a `.fla` file, in every zip layout (ADR 0054), opens with `file.open` as
|
||||
/// the same document as its folder and renders the same golden frames.
|
||||
#[test]
|
||||
fn every_package_opens_from_a_fla_with_the_same_golden_frames() {
|
||||
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-fla");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut failures = Vec::new();
|
||||
let mut checked = 0;
|
||||
for (case, frames) in FRAMES {
|
||||
let folder = corpus().join(case);
|
||||
let mut s = Session::default();
|
||||
let want = s.execute("file.open", &json!({"path": folder.display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}"));
|
||||
// Animate's own pointer file inside the folder opens it too.
|
||||
let mut x = Session::default();
|
||||
x.execute("file.open", &json!({"path": folder.join(format!("{case}.xfl")).display().to_string()})).unwrap_or_else(|e| panic!("{case}.xfl: {e}"));
|
||||
assert!(x.doc == s.doc, "{case}: the .xfl opens differently from its folder");
|
||||
let files = pack::package(&folder);
|
||||
for (n, v) in pack::VARIANTS.iter().enumerate() {
|
||||
let path = dir.join(format!("{case}-{n}.fla"));
|
||||
std::fs::write(&path, pack::pack(&files, v)).unwrap();
|
||||
let mut t = Session::default();
|
||||
let got = t.execute("file.open", &json!({"path": path.display().to_string()})).unwrap_or_else(|e| panic!("{case}, {}: {e}", v.name));
|
||||
assert_eq!(got["report"], want["report"], "{case}, {}", v.name);
|
||||
assert!(t.doc == s.doc, "{case}, {}: the .fla opens differently from the folder", v.name);
|
||||
}
|
||||
// The goldens (imported without fonts, as they were made), rendered from the .fla in
|
||||
// its most unusual layout.
|
||||
let fla = pack::pack(&files, &pack::VARIANTS[pack::VARIANTS.len() - 1]);
|
||||
let (doc, _) = anicraft_xfl::import_fla_with_fonts(&fla, &Fonts::from_faces(Vec::new())).unwrap_or_else(|e| panic!("{case}: {e}"));
|
||||
for &f in *frames {
|
||||
let (w, h, rgba) = render(&doc, f);
|
||||
let golden = corpus().join(case).join("golden").join(format!("frame-{f:03}.png"));
|
||||
if let Err(e) = golden::compare(&golden, &format!("{case}-fla-frame-{f:03}"), w, h, &rgba, golden::DEFAULT) {
|
||||
failures.push(e);
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{} of {checked} .fla frames differ from their goldens:
|
||||
{}", failures.len(), failures.join("
|
||||
"));
|
||||
}
|
||||
@@ -383,7 +383,7 @@ fn leaving(cands: [Vec2; 3]) -> Option<Vec2> {
|
||||
}
|
||||
|
||||
/// One cubic in place of `a` then `b` (see [`Path::merge_at`]). `None` for non-finite input.
|
||||
fn merge_cubics(a: [Vec2; 4], b: [Vec2; 4]) -> Option<[Vec2; 4]> {
|
||||
pub(crate) fn merge_cubics(a: [Vec2; 4], b: [Vec2; 4]) -> Option<[Vec2; 4]> {
|
||||
use crate::walk::cubic_point;
|
||||
const N: usize = 24;
|
||||
let (p0, p3) = (a[0], b[3]);
|
||||
|
||||
@@ -180,6 +180,298 @@ pub fn anchors_at(path: &mut Path, p: Vec2, tol: f32) -> Vec<usize> {
|
||||
}
|
||||
}
|
||||
|
||||
// ----- points shared by several shapes (ADR 0045) ------------------------------------------------
|
||||
|
||||
/// One segment of a subpath: a cubic, and whether it is a straight line (kept a line when the path
|
||||
/// is written back).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Seg {
|
||||
pub c: Cubic,
|
||||
pub line: bool,
|
||||
}
|
||||
|
||||
impl Seg {
|
||||
pub fn line(a: Vec2, b: Vec2) -> Seg {
|
||||
Seg { c: [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b], line: true }
|
||||
}
|
||||
/// The same segment run the other way.
|
||||
pub fn reversed(&self) -> Seg {
|
||||
Seg { c: [self.c[3], self.c[2], self.c[1], self.c[0]], line: self.line }
|
||||
}
|
||||
}
|
||||
|
||||
/// A subpath as its segments, each starting where the one before ends. A closed one ends where
|
||||
/// it starts.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Sub {
|
||||
pub segs: Vec<Seg>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
/// `path` as subpaths (a `Close` that draws an edge back to the start gets that edge as a line;
|
||||
/// a lone move is dropped).
|
||||
pub fn subpaths(path: &Path) -> Vec<Sub> {
|
||||
let mut p = path.clone();
|
||||
p.close_explicitly();
|
||||
let mut out: Vec<Sub> = Vec::new();
|
||||
let mut cur: Option<Sub> = None;
|
||||
for k in 0..p.cmds.len().min(MAX_CMDS) {
|
||||
match p.cmds.get(k) {
|
||||
Some(PathCmd::MoveTo(_)) => {
|
||||
out.extend(cur.take().filter(|s| !s.segs.is_empty()));
|
||||
cur = Some(Sub { segs: Vec::new(), closed: false });
|
||||
}
|
||||
Some(PathCmd::Close) => {
|
||||
if let Some(mut s) = cur.take().filter(|s| !s.segs.is_empty()) {
|
||||
s.closed = true;
|
||||
out.push(s);
|
||||
}
|
||||
}
|
||||
Some(cmd) => {
|
||||
if let Some(c) = segment_cubic(&p, k) {
|
||||
let seg = Seg { c, line: matches!(cmd, PathCmd::LineTo(_)) };
|
||||
cur.get_or_insert_with(|| Sub { segs: Vec::new(), closed: false }).segs.push(seg);
|
||||
}
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
out.extend(cur.filter(|s| !s.segs.is_empty()));
|
||||
out
|
||||
}
|
||||
|
||||
/// The path of `subs` (lines as lines, everything else as cubics).
|
||||
pub fn from_subpaths(subs: &[Sub]) -> Path {
|
||||
let mut p = Path::new();
|
||||
for s in subs {
|
||||
let Some(first) = s.segs.first() else { continue };
|
||||
p.move_to(first.c[0]);
|
||||
for g in &s.segs {
|
||||
if g.line {
|
||||
p.line_to(g.c[3]);
|
||||
} else {
|
||||
p.cubic_to(g.c[1], g.c[2], g.c[3]);
|
||||
}
|
||||
}
|
||||
if s.closed {
|
||||
p.close();
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// The segments of `subs` that start or end at `at` (within `tol`), each as the edge leaving
|
||||
/// `at` (reversed when it ends there).
|
||||
pub fn edges_at(subs: &[Sub], at: Vec2, tol: f32) -> Vec<Seg> {
|
||||
let mut out = Vec::new();
|
||||
for s in subs {
|
||||
for g in &s.segs {
|
||||
if g.c[0].distance(at) <= tol {
|
||||
out.push(*g);
|
||||
}
|
||||
if g.c[3].distance(at) <= tol {
|
||||
out.push(g.reversed());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether two edges leaving one anchor are the same edge: their far ends and points along them
|
||||
/// within `tol`.
|
||||
pub fn same_edge(a: &Seg, b: &Seg, tol: f32) -> bool {
|
||||
a.c[3].distance(b.c[3]) <= tol && [0.25f32, 0.5, 0.75].iter().all(|&t| cubic_point(&a.c, t).distance(cubic_point(&b.c, t)) <= tol * 2.0)
|
||||
}
|
||||
|
||||
/// The edges among `edges` that are distinct ([`same_edge`]), in order.
|
||||
pub fn distinct_edges(edges: impl IntoIterator<Item = Seg>, tol: f32) -> Vec<Seg> {
|
||||
let mut out: Vec<Seg> = Vec::new();
|
||||
for e in edges {
|
||||
if !out.iter().any(|x| same_edge(x, &e, tol)) {
|
||||
out.push(e);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The one edge in place of the edges `a` and `b` that leave an anchor: from `a`'s far end to
|
||||
/// `b`'s. Two lines make a line; anything else the cubic that fits both best, keeping the
|
||||
/// directions they leave their far ends in ([`Path::merge_at`]'s fit).
|
||||
pub fn join(a: &Seg, b: &Seg) -> Option<Seg> {
|
||||
if a.line && b.line {
|
||||
return Some(Seg::line(a.c[3], b.c[3]));
|
||||
}
|
||||
let c = crate::edit::merge_cubics(a.reversed().c, b.c)?;
|
||||
Some(Seg { c, line: false })
|
||||
}
|
||||
|
||||
/// The edges `a` and `b` that leave one anchor, made smooth there: their handles at the anchor on
|
||||
/// one line, along the direction from `a`'s far end to `b`'s, each a third of its edge's chord
|
||||
/// long ([`Path::make_smooth`]). `None` when the far ends coincide.
|
||||
pub fn smooth_pair(a: &Seg, b: &Seg) -> Option<(Seg, Seg)> {
|
||||
let at = a.c[0];
|
||||
let dir = (b.c[3] - a.c[3]).normalized();
|
||||
if dir == Vec2::ZERO {
|
||||
return None;
|
||||
}
|
||||
let ha = at - dir * (at.distance(a.c[3]) / 3.0);
|
||||
let hb = at + dir * (at.distance(b.c[3]) / 3.0);
|
||||
let (na, nb) = (Seg { c: [at, ha, a.c[2], a.c[3]], line: false }, Seg { c: [at, hb, b.c[2], b.c[3]], line: false });
|
||||
(na.c.iter().chain(&nb.c).all(|p| p.is_finite())).then_some((na, nb))
|
||||
}
|
||||
|
||||
/// `e` (leaving an anchor) with its handle at the anchor drawn in onto it: a corner there. `None`
|
||||
/// when it has none to draw in (a line, or a handle already on the anchor).
|
||||
pub fn corner(e: &Seg) -> Option<Seg> {
|
||||
(!e.line && e.c[1].distance(e.c[0]) > 1e-4).then_some(Seg { c: [e.c[0], e.c[0], e.c[2], e.c[3]], line: false })
|
||||
}
|
||||
|
||||
/// Handles at one anchor lying on one line, on opposite sides, within this angle's sine (3°): a
|
||||
/// smooth anchor.
|
||||
const SMOOTH_SIN: f32 = 0.052;
|
||||
|
||||
/// Whether the handles `h` and `k` of the anchor `a` make it smooth: both off the anchor, on one
|
||||
/// line through it, on opposite sides.
|
||||
pub fn smooth_at(a: Vec2, h: Vec2, k: Vec2) -> bool {
|
||||
let (u, v) = (h - a, k - a);
|
||||
let (lu, lv) = (u.length(), v.length());
|
||||
lu > 1e-4 && lv > 1e-4 && u.dot(v) < 0.0 && (u.cross(v) / (lu * lv)).abs() <= SMOOTH_SIN
|
||||
}
|
||||
|
||||
/// `k` turned about the anchor `a` so it lies opposite `h`, keeping its length (the other handle
|
||||
/// of a smooth anchor while `h` is dragged). `k` itself when `h` is on the anchor.
|
||||
pub fn turned_opposite(a: Vec2, h: Vec2, k: Vec2) -> Vec2 {
|
||||
let dir = (h - a).normalized();
|
||||
if dir == Vec2::ZERO {
|
||||
return k;
|
||||
}
|
||||
a - dir * a.distance(k)
|
||||
}
|
||||
|
||||
/// Deletes the anchor at `at` (within `tol`) from `subs`, where the drawing has the distinct
|
||||
/// edges `edges` leaving it.
|
||||
///
|
||||
/// * Two edges: every copy of either becomes `joined` (the edge from the first's far end to the
|
||||
/// second's, see [`join`]). A run through the anchor takes it once in place of both; a line
|
||||
/// ending there now runs along the whole new edge, so the drawing stays connected.
|
||||
/// * One edge (the free end of lines): the segment there goes.
|
||||
///
|
||||
/// Returns whether anything changed. Subpaths may be left empty or flat: see [`tidy`].
|
||||
pub fn delete_anchor(subs: &mut [Sub], at: Vec2, edges: &[Seg], joined: Option<&Seg>, tol: f32) -> bool {
|
||||
let which = |e: &Seg| edges.iter().position(|x| same_edge(x, e, tol));
|
||||
let toward = |from: usize| -> Option<Seg> {
|
||||
// The new edge leaving the far end of edge `from` (towards the other edge's far end).
|
||||
let j = joined?;
|
||||
Some(if from == 0 { *j } else { j.reversed() })
|
||||
};
|
||||
let mut changed = false;
|
||||
for s in subs.iter_mut() {
|
||||
// Each pass takes one vertex at `at`; bounded by the segments there are.
|
||||
for _ in 0..=s.segs.len() {
|
||||
let Some(step) = vertex_at(s, at, tol) else { break };
|
||||
let done = match step {
|
||||
Vertex::Through(v) => {
|
||||
// in: segs[v - 1] arrives, out: segs[v] leaves (v ≥ 1 after rotation).
|
||||
let (Some(inn), Some(out)) = (s.segs.get(v - 1).copied(), s.segs.get(v).copied()) else { break };
|
||||
match (which(&inn.reversed()), which(&out), edges.len()) {
|
||||
(Some(a), Some(b), 2) if a != b => match toward(a) {
|
||||
Some(n) => {
|
||||
s.segs.splice(v - 1..=v, [n]);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
Vertex::Start => match (s.segs.first().and_then(which), edges.len()) {
|
||||
// The new first segment ends where the old one did.
|
||||
(Some(a), 2) => match (toward(1 - a), s.segs.first_mut()) {
|
||||
(Some(n), Some(first)) => {
|
||||
*first = n;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
(Some(_), 1) => {
|
||||
s.segs.remove(0);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
Vertex::End => {
|
||||
match (s.segs.last().and_then(|g| which(&g.reversed())), edges.len()) {
|
||||
(Some(a), 2) => match (toward(a), s.segs.last_mut()) {
|
||||
(Some(n), Some(last)) => {
|
||||
*last = n;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
(Some(_), 1) => {
|
||||
s.segs.pop();
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
};
|
||||
if !done {
|
||||
break;
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Where a subpath has a vertex at a point.
|
||||
enum Vertex {
|
||||
/// Between segments `v - 1` and `v` (a closed subpath is turned so `v ≥ 1`).
|
||||
Through(usize),
|
||||
/// An open subpath's start or end.
|
||||
Start,
|
||||
End,
|
||||
}
|
||||
|
||||
fn vertex_at(s: &mut Sub, at: Vec2, tol: f32) -> Option<Vertex> {
|
||||
let n = s.segs.len();
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
if s.closed {
|
||||
let v = s.segs.iter().position(|g| g.c[0].distance(at) <= tol)?;
|
||||
// Turn the loop so the vertex is not at the seam.
|
||||
let turn = if v == 0 { n - 1 } else { 0 };
|
||||
s.segs.rotate_left(turn);
|
||||
return Some(Vertex::Through(if v == 0 { 1 } else { v }));
|
||||
}
|
||||
if s.segs.first().is_some_and(|g| g.c[0].distance(at) <= tol) {
|
||||
return Some(Vertex::Start);
|
||||
}
|
||||
if s.segs.last().is_some_and(|g| g.c[3].distance(at) <= tol) {
|
||||
return Some(Vertex::End);
|
||||
}
|
||||
(1..n).find(|&v| s.segs.get(v).is_some_and(|g| g.c[0].distance(at) <= tol)).map(Vertex::Through)
|
||||
}
|
||||
|
||||
/// Drops the subpaths an edit left with nothing to show: no segments, no length, or (when
|
||||
/// `filled`) a closed outline with no area.
|
||||
pub fn tidy(subs: &mut Vec<Sub>, filled: bool) {
|
||||
subs.retain(|s| {
|
||||
let pts: Vec<Vec2> = s.segs.iter().flat_map(|g| (0..8).map(move |i| cubic_point(&g.c, i as f32 / 8.0))).chain(s.segs.last().map(|g| g.c[3])).collect();
|
||||
let length: f32 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.distance(*b))).sum();
|
||||
if s.segs.is_empty() || length <= 1e-3 {
|
||||
return false;
|
||||
}
|
||||
if filled && s.closed {
|
||||
let area: f32 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.cross(*b))).sum::<f32>() * 0.5;
|
||||
return area.abs() > 1e-3;
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -235,6 +527,110 @@ mod tests {
|
||||
assert!(anchors_at(&mut p, Vec2::new(40.0, 5.0), 0.2).is_empty());
|
||||
}
|
||||
|
||||
fn v(x: f32, y: f32) -> Vec2 {
|
||||
Vec2::new(x, y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subpaths_round_trip() {
|
||||
let mut p = Path::rect(0.0, 0.0, 10.0, 10.0);
|
||||
p.move_to(v(20.0, 0.0)).cubic_to(v(20.0, 5.0), v(25.0, 10.0), v(30.0, 10.0));
|
||||
let subs = subpaths(&p);
|
||||
assert_eq!(subs.len(), 2);
|
||||
assert!(subs[0].closed && subs[0].segs.len() == 4 && subs[0].segs.iter().all(|g| g.line), "the closing edge is written out: {:?}", subs[0]);
|
||||
assert!(!subs[1].closed && !subs[1].segs[0].line);
|
||||
let back = subpaths(&from_subpaths(&subs));
|
||||
assert_eq!(back, subs);
|
||||
}
|
||||
|
||||
/// A raw rectangle as merge drawing stores it: the fill and four sides, each its own path.
|
||||
fn outlined_rect() -> Vec<Vec<Sub>> {
|
||||
let (a, b, c, d) = (v(0.0, 0.0), v(100.0, 0.0), v(100.0, 80.0), v(0.0, 80.0));
|
||||
// The fill starts at the corner deleted below, to cover the seam.
|
||||
let fill = vec![Sub { segs: vec![Seg::line(a, b), Seg::line(b, c), Seg::line(c, d), Seg::line(d, a)], closed: true }];
|
||||
let side = |p, q| vec![Sub { segs: vec![Seg::line(p, q)], closed: false }];
|
||||
vec![fill, side(a, b), side(b, c), side(c, d), side(d, a)]
|
||||
}
|
||||
|
||||
fn delete(shapes: &mut [Vec<Sub>], at: Vec2) -> usize {
|
||||
let edges = distinct_edges(shapes.iter().flat_map(|s| edges_at(s, at, 0.2)), 0.2);
|
||||
let joined = if edges.len() == 2 { join(&edges[0], &edges[1]) } else { None };
|
||||
shapes.iter_mut().map(|s| delete_anchor(s, at, &edges, joined.as_ref(), 0.2)).filter(|c| *c).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_corner_keeps_the_drawing_connected() {
|
||||
let mut shapes = outlined_rect();
|
||||
let edges = distinct_edges(shapes.iter().flat_map(|s| edges_at(s, v(0.0, 0.0), 0.2)), 0.2);
|
||||
assert_eq!(edges.len(), 2, "two edges meet at a corner, each in the fill and a side");
|
||||
assert_eq!(delete(&mut shapes, v(0.0, 0.0)), 3, "the fill and both sides there");
|
||||
// The fill is a triangle now, cut along the diagonal from (0, 80) to (100, 0).
|
||||
let fill = &shapes[0][0];
|
||||
assert!(fill.closed && fill.segs.len() == 3 && fill.segs.iter().all(|g| g.line), "{fill:?}");
|
||||
assert!(fill.segs.iter().all(|g| g.c[0].distance(v(0.0, 0.0)) > 1.0));
|
||||
// Both sides that ended there now run along the diagonal: every anchor is shared.
|
||||
let diag = Seg::line(v(0.0, 80.0), v(100.0, 0.0));
|
||||
for s in [&shapes[1], &shapes[4]] {
|
||||
let g = s[0].segs[0];
|
||||
assert!(same_edge(&g, &diag, 0.01) || same_edge(&g.reversed(), &diag, 0.01), "{g:?}");
|
||||
}
|
||||
let anchors: Vec<Vec2> = shapes.iter().flatten().flat_map(|s| s.segs.iter().flat_map(|g| [g.c[0], g.c[3]])).collect();
|
||||
for p in &anchors {
|
||||
assert!(anchors.iter().filter(|q| q.distance(*p) < 1e-3).count() >= 2, "{p:?} is on one shape only");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_point_that_splitting_added_gives_the_curve_back() {
|
||||
let arc = Seg { c: [v(0.0, 0.0), v(0.0, -60.0), v(100.0, -60.0), v(100.0, 0.0)], line: false };
|
||||
let (a, b) = (sub(&arc.c, 0.0, 0.35), sub(&arc.c, 0.35, 1.0));
|
||||
let at = a[3];
|
||||
// A fill under the arc and the arc's own stroke, both with the point.
|
||||
let fill = vec![Sub { segs: vec![Seg { c: a, line: false }, Seg { c: b, line: false }, Seg::line(v(100.0, 0.0), v(0.0, 0.0))], closed: true }];
|
||||
let stroke = vec![Sub { segs: vec![Seg { c: b, line: false }.reversed(), Seg { c: a, line: false }.reversed()], closed: false }];
|
||||
let mut shapes = vec![fill, stroke];
|
||||
assert_eq!(delete(&mut shapes, at), 2);
|
||||
let (f, s) = (shapes[0][0].segs[0], shapes[1][0].segs[0]);
|
||||
assert_eq!((shapes[0][0].segs.len(), shapes[1][0].segs.len()), (2, 1));
|
||||
for t in [0.1f32, 0.3, 0.5, 0.7, 0.9] {
|
||||
assert!(nearest(&f.c, cubic_point(&arc.c, t)).1 < 0.05, "fill off the old curve at {t}");
|
||||
}
|
||||
assert!(same_edge(&f, &s.reversed(), 1e-3), "the fill and the stroke keep one edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_free_end_shortens_the_line_and_its_last_point_removes_it() {
|
||||
let mut shapes = vec![vec![Sub { segs: vec![Seg::line(v(0.0, 0.0), v(50.0, 0.0)), Seg::line(v(50.0, 0.0), v(50.0, 50.0))], closed: false }]];
|
||||
assert_eq!(delete(&mut shapes, v(50.0, 50.0)), 1);
|
||||
assert_eq!(shapes[0][0].segs.len(), 1);
|
||||
assert_eq!(delete(&mut shapes, v(50.0, 0.0)), 1);
|
||||
tidy(&mut shapes[0], false);
|
||||
assert!(shapes[0].is_empty());
|
||||
// A triangle's fill losing a corner has no area left.
|
||||
let tri = |a, b, c| vec![Sub { segs: vec![Seg::line(a, b), Seg::line(b, c), Seg::line(c, a)], closed: true }];
|
||||
let mut t = vec![tri(v(0.0, 0.0), v(10.0, 0.0), v(5.0, 9.0))];
|
||||
assert_eq!(delete(&mut t, v(5.0, 9.0)), 1);
|
||||
tidy(&mut t[0], true);
|
||||
assert!(t[0].is_empty(), "{:?}", t[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_and_corner_handles() {
|
||||
let (a, b) = (Seg::line(v(0.0, 0.0), v(-30.0, 10.0)), Seg::line(v(0.0, 0.0), v(40.0, 10.0)));
|
||||
let Some((sa, sb)) = smooth_pair(&a, &b) else { panic!("no pair") };
|
||||
assert!(smooth_at(v(0.0, 0.0), sa.c[1], sb.c[1]), "{sa:?} {sb:?}");
|
||||
assert!((sa.c[1].distance(v(0.0, 0.0)) - a.c[3].length() / 3.0).abs() < 1e-3);
|
||||
assert_eq!((sa.c[3], sb.c[3]), (a.c[3], b.c[3]), "far ends stay");
|
||||
let Some(c) = corner(&sa) else { panic!("a curve has a handle") };
|
||||
assert_eq!(c.c[1], c.c[0]);
|
||||
assert!(corner(&a).is_none() && corner(&c).is_none(), "nothing to draw in");
|
||||
// Dragging one handle of a smooth anchor turns the other with it, keeping its length.
|
||||
let k = turned_opposite(v(0.0, 0.0), v(0.0, 10.0), v(20.0, 0.0));
|
||||
assert!(k.distance(v(0.0, -20.0)) < 1e-4, "{k:?}");
|
||||
assert!(!smooth_at(v(0.0, 0.0), v(10.0, 0.0), v(0.0, 10.0)), "a corner");
|
||||
assert!(!smooth_at(v(0.0, 0.0), v(10.0, 0.0), v(20.0, 0.1)), "same side");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_finds_the_closest_point_on_a_curve() {
|
||||
let c = [Vec2::new(0.0, 0.0), Vec2::new(0.0, 50.0), Vec2::new(100.0, 50.0), Vec2::new(100.0, 0.0)];
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
//! GPU stage timings and parity against the CPU oracle (ADR 0019, ADR 0029, ADR 0032; numbers
|
||||
//! GPU stage timings and parity against the CPU oracle (ADR 0019, 0029, 0032, 0048; numbers
|
||||
//! in docs/performance.md).
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run --release -p anicraft-gpu --example gpu_bench
|
||||
//! cargo run --release -p anicraft-gpu --example gpu_bench -- --layers 50 --shapes 200
|
||||
//! cargo run --release -p anicraft-gpu --example gpu_bench -- --only onion
|
||||
//! cargo run --release -p anicraft-gpu --example gpu_bench -- --check # fails past a budget
|
||||
//! ```
|
||||
//! Prints the adapter, then for each scene and size: CPU ms; the first slice's read-back path
|
||||
//! (prepare + bin + upload, compute, copy back); the direct path the window uses (into a
|
||||
//! texture, no readback): what the calling thread spends, and until the GPU has finished; the
|
||||
//! stage's way (512 px tiles drawn in parallel, as the render service does, until finished);
|
||||
//! the work the fine pass did; and how far the GPU's picture is from the oracle's.
|
||||
//! Prints the adapter, then for each scene and size: CPU ms; then, with the tiles binned on
|
||||
//! the CPU and then on the GPU (ADR 0048), the direct path the window uses (into a texture, no
|
||||
//! readback): what the calling thread spends, and until the GPU has finished; the stage's way
|
||||
//! (512 px tiles drawn in parallel, as the render service does, until finished); and how far
|
||||
//! the GPU-binned picture is from the oracle's.
|
||||
|
||||
use anicraft_doc::{Bitmap, BitmapId, ColorEffect, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample};
|
||||
use anicraft_doc::{Bitmap, BitmapId, ColorEffect, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample};
|
||||
use anicraft_geom::{FillRule, Path};
|
||||
use anicraft_gpu::{GpuRenderer, Output, compare_premul8};
|
||||
use anicraft_gpu::{Binning, GpuRenderer, compare_premul8};
|
||||
use anicraft_geom::Affine;
|
||||
use anicraft_render::{View, render};
|
||||
use rayon::prelude::*;
|
||||
@@ -139,7 +141,72 @@ fn filtered() -> Document {
|
||||
doc
|
||||
}
|
||||
|
||||
/// Onion skin as the stage composes it (ADR 0047), for the bench: no onion skin, ±5 frames
|
||||
/// tinted and fading, or ±5 frames as outlines.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Onion {
|
||||
Off,
|
||||
Tinted,
|
||||
Outlines,
|
||||
}
|
||||
|
||||
/// Frame `frame` with ±5 onion frames, as `anicraft_engine::onion::compose` draws them with
|
||||
/// the default colours, tint and fade: each frame's items under the playhead's on their own
|
||||
/// layer (nearest on top), at its alpha and tint, or as hairline outlines in its colour. (The
|
||||
/// engine sits beside this crate, so the bench builds the same list itself.)
|
||||
fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList {
|
||||
let now = evaluate(doc, frame);
|
||||
if mode == Onion::Off {
|
||||
return now;
|
||||
}
|
||||
let frames = doc.frame_count().max(1);
|
||||
let (past, future) = (Rgba::hex(0x4f8dff), Rgba::hex(0x4cd07d));
|
||||
let rank: std::collections::HashMap<LayerId, usize> = doc.timeline(0).layers.iter().enumerate().map(|(i, l)| (l.id, i)).collect();
|
||||
let mut dl = DisplayList::default();
|
||||
let mut part_of: Vec<usize> = Vec::new();
|
||||
for d in (1..=5u32).rev() {
|
||||
for (is_past, f) in [(true, frame.checked_sub(d)), (false, Some(frame + d).filter(|f| *f < frames))] {
|
||||
let Some(f) = f else { continue };
|
||||
// Fading from 0.5 next to the playhead to 0.12 at the marker; tinted at 0.8.
|
||||
let alpha = 0.5 + (0.12 - 0.5) * (d - 1) as f32 / 4.0;
|
||||
let color = if is_past { past } else { future };
|
||||
let mut part = evaluate(doc, f);
|
||||
for item in &mut part.items {
|
||||
item.color = item.color.concat(&ColorEffect { alpha, tint: color, tint_amount: 0.8 });
|
||||
if mode == Onion::Outlines && item.masks.is_none() {
|
||||
item.outline = Some(color.with_alpha(alpha));
|
||||
}
|
||||
}
|
||||
part_of.extend(std::iter::repeat_n(part_of.last().map_or(0, |p| p + 1), part.items.len()));
|
||||
dl.append(part);
|
||||
}
|
||||
}
|
||||
let k = part_of.last().map_or(0, |p| p + 1);
|
||||
part_of.extend(std::iter::repeat_n(k, now.items.len()));
|
||||
dl.append(now);
|
||||
// Layer by layer, bottom first; within a layer, the parts in order (a stable sort).
|
||||
let mut order: Vec<usize> = (0..dl.items.len()).collect();
|
||||
order.sort_by_key(|&i| (std::cmp::Reverse(dl.items.get(i).and_then(|it| rank.get(&it.layer)).copied().unwrap_or(0)), part_of.get(i).copied().unwrap_or(0)));
|
||||
let mut items: Vec<Option<anicraft_doc::DisplayItem>> = std::mem::take(&mut dl.items).into_iter().map(Some).collect();
|
||||
dl.items = order.into_iter().filter_map(|i| items.get_mut(i).and_then(Option::take)).collect();
|
||||
dl
|
||||
}
|
||||
|
||||
/// Timing budgets for the stage on the GPU (docs/performance.md › Budgets), checked with
|
||||
/// `--check` on a known machine: `(scene, width, what, limit in ms)`, `what` being the Auto
|
||||
/// column's `direct` or `tiled` (the stage's way).
|
||||
const BUDGETS: &[(&str, u32, &str, f64)] = &[
|
||||
("1,000 shapes", 3840, "tiled", 16.7),
|
||||
("stress 50×200", 3840, "tiled", 16.7),
|
||||
("50,000 shapes", 1920, "tiled", 33.3),
|
||||
("50,000 shapes", 3840, "direct", 33.3),
|
||||
];
|
||||
/// Outline mode against tinted onion skin (ADR 0048: no slower), at 1080p in stage tiles.
|
||||
const OUTLINE_RATIO: f64 = 1.25;
|
||||
|
||||
fn main() {
|
||||
let check = std::env::args().any(|a| a == "--check");
|
||||
let mut measured: Vec<(String, u32, &str, f64)> = Vec::new();
|
||||
let gpu = match GpuRenderer::new() {
|
||||
Ok(g) => g,
|
||||
Err(e) => {
|
||||
@@ -150,95 +217,117 @@ fn main() {
|
||||
println!("adapter: {}", gpu.adapter);
|
||||
let (layers, shapes) = (arg("--layers", 50), arg("--shapes", 200));
|
||||
let runs = arg("--runs", 12);
|
||||
let scenes: Vec<(String, Document)> = vec![
|
||||
(format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)),
|
||||
("1,000 shapes".into(), sample::stress(5, 200, 240)),
|
||||
(format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))),
|
||||
("sample".into(), sample::demo()),
|
||||
("composited sample".into(), composited()),
|
||||
("filtered sample".into(), filtered()),
|
||||
("200 bitmaps".into(), bitmaps()),
|
||||
let only: Option<String> = std::env::args().skip_while(|a| a != "--only").nth(1);
|
||||
let onion_doc = sample::stress(20, 100, 48);
|
||||
let plain = |name: String, doc: Document| (name, doc, Onion::Off);
|
||||
let scenes: Vec<(String, Document, Onion)> = vec![
|
||||
plain(format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)),
|
||||
plain("1,000 shapes".into(), sample::stress(5, 200, 240)),
|
||||
plain("50,000 shapes".into(), sample::stress(250, 200, 240)),
|
||||
plain(format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))),
|
||||
plain("sample".into(), sample::demo()),
|
||||
plain("composited sample".into(), composited()),
|
||||
plain("filtered sample".into(), filtered()),
|
||||
plain("200 bitmaps".into(), bitmaps()),
|
||||
("onion off 20×100".into(), onion_doc.clone(), Onion::Off),
|
||||
("onion ±5 tinted".into(), onion_doc.clone(), Onion::Tinted),
|
||||
("onion ±5 outlines".into(), onion_doc, Onion::Outlines),
|
||||
];
|
||||
println!("Per scene and size: the CPU oracle, then the GPU stage with the tiles binned on the CPU, then as Binning::Auto bins them (on the GPU with --forced):");
|
||||
println!("direct = the calling thread's time with render_texture (prepare + bin + upload/submit), waited = until the GPU has finished,");
|
||||
println!("tiled = 512 px stage tiles in parallel until finished. Parity: the GPU-binned picture against the oracle (mean / max / px).");
|
||||
println!(
|
||||
"{:<20} {:>10} {:>8} {:>9} {:>9} {:>9} {:>7} {:>22} {:>8} {:>8} parity (mean / max / differing px)",
|
||||
"scene", "size", "CPU ms", "readback", "direct", "direct+", "tiled", "prepare + bin + submit", "entries", "pieces"
|
||||
"{:<20} {:>10} {:>7} | {:>7} {:>7} {:>7} {:>19} | {:>7} {:>7} {:>7} {:>19} | parity",
|
||||
"scene", "size", "CPU", "direct", "waited", "tiled", "prep + bin + gpu", "direct", "waited", "tiled", "prep + bin + gpu"
|
||||
);
|
||||
for (name, doc) in &scenes {
|
||||
for (name, doc, onion) in scenes.iter().filter(|(n, ..)| only.as_ref().is_none_or(|o| n.contains(o.as_str()))) {
|
||||
for scale in [1.0f32, 2.0] {
|
||||
let v = View::stage(doc, scale * 1920.0 / doc.stage.width as f32);
|
||||
let frames = doc.frame_count().max(1);
|
||||
let dl0 = evaluate(doc, 0);
|
||||
// Warm-up (pipeline caches, allocations).
|
||||
let _ = gpu.render(&dl0, &v, Output::Premul8);
|
||||
let _ = gpu.render_texture(&dl0, &v);
|
||||
let _ = gpu.wait_idle();
|
||||
let _ = render(&dl0, &v);
|
||||
let evaluate = |doc: &Document, f: u32| onion_list(doc, f, *onion);
|
||||
let dl0 = evaluate(doc, if *onion == Onion::Off { 0 } else { 30 });
|
||||
let lists: Vec<_> = (0..runs).map(|i| evaluate(doc, (i * 20) % frames)).collect();
|
||||
let per = |t: Instant| t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
|
||||
let _ = render(&dl0, &v);
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _ = render(dl, &v);
|
||||
}
|
||||
let cpu_ms = per(t);
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _ = gpu.render(dl, &v, Output::Premul8);
|
||||
}
|
||||
let readback_ms = per(t);
|
||||
// Direct: what the calling thread spends (the stage's cost per tile), then each frame
|
||||
// waited for to the end (the latency until the window can show it).
|
||||
let mut sum = [0.0f32; 3];
|
||||
let mut work = (0, 0);
|
||||
let t = Instant::now();
|
||||
let mut keep = Vec::with_capacity(lists.len());
|
||||
for dl in &lists {
|
||||
if let Ok(f) = gpu.render_texture(dl, &v) {
|
||||
sum[0] += f.timings.prepare;
|
||||
sum[1] += f.timings.bin;
|
||||
sum[2] += f.timings.gpu;
|
||||
work = (f.entries, f.pieces);
|
||||
keep.push(f);
|
||||
}
|
||||
}
|
||||
let direct_ms = per(t);
|
||||
let _ = gpu.wait_idle();
|
||||
drop(keep);
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _ = gpu.render_texture(dl, &v);
|
||||
let _ = gpu.wait_idle();
|
||||
}
|
||||
let done_ms = per(t);
|
||||
// The stage: 512 px tiles of the same frame, in parallel, then waited for.
|
||||
// The stage's tiles: 512 px of the same frame, drawn in parallel.
|
||||
let tiles: Vec<View> = (0..v.height.div_ceil(512))
|
||||
.flat_map(|ty| (0..v.width.div_ceil(512)).map(move |tx| (tx, ty)))
|
||||
.map(|(tx, ty)| View { transform: Affine::translate(-((tx * 512) as f32), -((ty * 512) as f32)).mul(&v.transform), width: 512.min(v.width - tx * 512), height: 512.min(v.height - ty * 512), background: v.background })
|
||||
.collect();
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture(dl, tv).ok()).collect();
|
||||
let mut cols = Vec::new();
|
||||
let mut binned_on_gpu = false;
|
||||
let second = if std::env::args().any(|a| a == "--forced") { Binning::Gpu } else { Binning::Auto };
|
||||
for binning in [Binning::Cpu, second] {
|
||||
// Warm-up (pipeline caches, allocations).
|
||||
let _ = gpu.render_texture_with(&dl0, &v, binning);
|
||||
let _ = gpu.wait_idle();
|
||||
let mut sum = [0.0f32; 3];
|
||||
let t = Instant::now();
|
||||
let mut keep = Vec::with_capacity(lists.len());
|
||||
for dl in &lists {
|
||||
if let Ok(f) = gpu.render_texture_with(dl, &v, binning) {
|
||||
sum[0] += f.timings.prepare;
|
||||
sum[1] += f.timings.bin;
|
||||
sum[2] += f.timings.gpu;
|
||||
binned_on_gpu |= f.gpu_binned;
|
||||
keep.push(f);
|
||||
}
|
||||
}
|
||||
let direct = per(t);
|
||||
let _ = gpu.wait_idle();
|
||||
drop(keep);
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _ = gpu.render_texture_with(dl, &v, binning);
|
||||
let _ = gpu.wait_idle();
|
||||
}
|
||||
let waited = per(t);
|
||||
let t = Instant::now();
|
||||
for dl in &lists {
|
||||
let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture_with(dl, tv, binning).ok()).collect();
|
||||
let _ = gpu.wait_idle();
|
||||
}
|
||||
let tiled = per(t);
|
||||
let n = runs as f32;
|
||||
if binning == Binning::Auto {
|
||||
measured.push((name.clone(), v.width, "direct", direct));
|
||||
measured.push((name.clone(), v.width, "tiled", tiled));
|
||||
}
|
||||
cols.push(format!("{direct:>7.2} {waited:>7.2} {tiled:>7.2} {:>19}", format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n)));
|
||||
}
|
||||
let tiled_ms = per(t);
|
||||
let n = runs as f32;
|
||||
let parity = match (gpu.render_texture(&dl0, &v).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) {
|
||||
let parity = match (gpu.render_texture_with(&dl0, &v, Binning::Gpu).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) {
|
||||
(Ok(g), Ok((c, _))) => compare_premul8(&g, &c.to_premul_rgba8()).map_or("size mismatch".into(), |d| format!("{:.4} / {} / {}", d.mean, d.max, d.differing)),
|
||||
(Err(e), _) => format!("GPU: {e}"),
|
||||
(_, Err(e)) => format!("CPU: {e}"),
|
||||
};
|
||||
println!(
|
||||
"{:<20} {:>10} {:>8.2} {:>9.2} {:>9.2} {:>9.2} {:>7.2} {:>22} {:>8} {:>8} {parity}",
|
||||
name,
|
||||
format!("{}×{}", v.width, v.height),
|
||||
cpu_ms,
|
||||
readback_ms,
|
||||
direct_ms,
|
||||
done_ms,
|
||||
tiled_ms,
|
||||
format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n),
|
||||
work.0,
|
||||
work.1
|
||||
);
|
||||
let note = if binned_on_gpu { "" } else { " (binned on the CPU: masks, groups or few edges)" };
|
||||
println!("{:<20} {:>10} {:>7.2} | {} | {} | {parity}{note}", name, format!("{}×{}", v.width, v.height), cpu_ms, cols[0], cols[1]);
|
||||
}
|
||||
}
|
||||
if !check {
|
||||
return;
|
||||
}
|
||||
let get = |scene: &str, w: u32, what: &str| measured.iter().find(|m| m.0 == scene && m.1 == w && m.2 == what).map(|m| m.3);
|
||||
let mut missed = 0;
|
||||
println!();
|
||||
println!("budgets (the means above; run on a quiet machine)");
|
||||
for &(scene, w, what, limit) in BUDGETS {
|
||||
let got = get(scene, w, what);
|
||||
let ok = got.is_some_and(|g| g <= limit);
|
||||
missed += usize::from(!ok);
|
||||
println!(" {} {scene} at {w} px, {what}: {} (budget {limit} ms)", if ok { "ok " } else { "MISS" }, got.map_or("not measured".into(), |g| format!("{g:.2} ms")));
|
||||
}
|
||||
let ratio = get("onion ±5 outlines", 1920, "tiled").zip(get("onion ±5 tinted", 1920, "tiled")).map(|(o, t)| o / t);
|
||||
let ok = ratio.is_some_and(|r| r <= OUTLINE_RATIO);
|
||||
missed += usize::from(!ok);
|
||||
println!(" {} onion outlines / tinted at 1920 px, tiled: {} (budget {OUTLINE_RATIO})", if ok { "ok " } else { "MISS" }, ratio.map_or("not measured".into(), |r| format!("{r:.2}")));
|
||||
if missed > 0 {
|
||||
println!("{missed} budget(s) missed");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
// AniCraft GPU stage: tile binning on the GPU (ADR 0048).
|
||||
//
|
||||
// The same tile lists as the CPU binning (binning.rs, the reference), from the prepared fills'
|
||||
// flattened polygons, in four kinds of dispatch:
|
||||
//
|
||||
// 1. `count`, one invocation per row of tiles of each fill (an "op-row"): its edges split at
|
||||
// tile rows and columns (binning.rs › split_edge, split_row), plus the steps where the
|
||||
// outline passes from one column to another (› Track, steps), or a hairline's segments by
|
||||
// reach (› hairline_tiles), counted per tile of the fill (an "op-tile"); and the backdrops: the
|
||||
// directions of the pieces starting on the row's top edge, summed along the row. Each
|
||||
// op-row is one invocation's alone, so nothing needs atomics and integers add up the same
|
||||
// in any order: the counts and backdrops are exact.
|
||||
// 2. `scan_blocks` and `scan_add`: an exclusive prefix sum of the counts (the public
|
||||
// work-efficient scan: per workgroup, then the workgroups' totals, then added back), which
|
||||
// places every op-tile's pieces.
|
||||
// 3. `scatter`: the same walk again, writing each piece where its op-tile's pieces go, in the
|
||||
// walk's order (the same every frame).
|
||||
// 4. `tiles`, one invocation per tile: its fills in drawing order (the fills overlapping its
|
||||
// row, from the CPU, which only needs their bounds), keeping those with pieces or a
|
||||
// backdrop there, as the entries the fine pass reads.
|
||||
//
|
||||
// The binding layout fits the smallest devices (four storage buffers per stage): one buffer of
|
||||
// inputs, one of working values (counts, backdrops, offsets, cursors, scan totals), the pieces
|
||||
// (`geo`) and the fine pass's index.
|
||||
|
||||
struct Params {
|
||||
// tiles across, tiles down, op-rows, tiles
|
||||
size: vec4<u32>,
|
||||
// op-tiles, piece capacity, where the entries start in `index`, 0
|
||||
more: vec4<u32>,
|
||||
// where the ops, polygons, points and op-row owners start in `input`
|
||||
at: vec4<u32>,
|
||||
// where the rows' fills and the rows' starts are in `input`
|
||||
at2: vec4<u32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> params: Params;
|
||||
@group(0) @binding(1) var<storage, read> input: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> work: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> geo: array<vec4<f32>>;
|
||||
@group(0) @binding(4) var<storage, read_write> index: array<u32>;
|
||||
|
||||
const T: f32 = 16.0;
|
||||
// gpu_binning.rs › HAIRLINE_BIT: the op is a hairline.
|
||||
const HAIRLINE_BIT: u32 = 0x80000000u;
|
||||
// How far around a hairline segment its tiles are taken (binning.rs › HAIRLINE_MARGIN).
|
||||
const M: f32 = 1.25;
|
||||
|
||||
// What to do with a piece.
|
||||
const COUNT: u32 = 0u;
|
||||
const WRITE: u32 = 1u;
|
||||
|
||||
struct Op {
|
||||
first_poly: u32,
|
||||
polys: u32,
|
||||
tx0: u32,
|
||||
ty0: u32,
|
||||
ncols: u32,
|
||||
nrows: u32,
|
||||
tile_base: u32,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
fn op_at(i: u32) -> Op {
|
||||
let b = params.at.x + i * 8u;
|
||||
return Op(input[b], input[b + 1u], input[b + 2u], input[b + 3u], input[b + 4u], input[b + 5u], input[b + 6u], input[b + 7u]);
|
||||
}
|
||||
|
||||
fn point(i: u32) -> vec2<f32> {
|
||||
let b = params.at.z + i * 2u;
|
||||
return vec2<f32>(bitcast<f32>(input[b]), bitcast<f32>(input[b + 1u]));
|
||||
}
|
||||
|
||||
// Finite (not NaN or infinite), from the bits: comparisons with NaN may be optimized away.
|
||||
fn finite(v: f32) -> bool {
|
||||
return (bitcast<u32>(v) & 0x7f800000u) != 0x7f800000u;
|
||||
}
|
||||
|
||||
fn finite2(p: vec2<f32>) -> bool {
|
||||
return finite(p.x) && finite(p.y);
|
||||
}
|
||||
|
||||
// The working values: counts, backdrops, offsets and cursors, `params.more.x` each.
|
||||
fn counts_at(t: u32) -> u32 {
|
||||
return t;
|
||||
}
|
||||
fn backdrop_at(t: u32) -> u32 {
|
||||
return params.more.x + t;
|
||||
}
|
||||
fn offset_at(t: u32) -> u32 {
|
||||
return 2u * params.more.x + t;
|
||||
}
|
||||
fn cursor_at(t: u32) -> u32 {
|
||||
return 3u * params.more.x + t;
|
||||
}
|
||||
|
||||
// The walk of one op-row: what it is and where its pieces go.
|
||||
struct Walk {
|
||||
mode: u32,
|
||||
// the op-tile of the row's first column
|
||||
tile0: u32,
|
||||
ncols: i32,
|
||||
hairline: bool,
|
||||
row_y0: f32,
|
||||
// the row's top-left in pixels
|
||||
ox: f32,
|
||||
}
|
||||
|
||||
// The fill's range (binning.rs › Range).
|
||||
struct Rng {
|
||||
xlo: f32,
|
||||
xhi: f32,
|
||||
ylo: f32,
|
||||
yhi: f32,
|
||||
ncols: i32,
|
||||
nrows: i32,
|
||||
}
|
||||
|
||||
// binning.rs › top_crossing.
|
||||
fn top_crossing(s: vec4<f32>, row_y0: f32) -> i32 {
|
||||
if s.y == s.w || min(s.y, s.w) != row_y0 {
|
||||
return 0;
|
||||
}
|
||||
return select(-1, 1, s.w > s.y);
|
||||
}
|
||||
|
||||
// One piece in column `col` of the walk's row (−1: left of the fill's tiles).
|
||||
fn emit(w: Walk, col: i32, s: vec4<f32>) {
|
||||
if w.mode == COUNT {
|
||||
if col >= 0 && col < w.ncols {
|
||||
let t = counts_at(w.tile0 + u32(col));
|
||||
work[t] = work[t] + 1u;
|
||||
}
|
||||
if !w.hairline {
|
||||
let c = top_crossing(s, w.row_y0);
|
||||
if c != 0 && col + 1 < w.ncols {
|
||||
let t = backdrop_at(w.tile0 + u32(col + 1));
|
||||
work[t] = bitcast<u32>(bitcast<i32>(work[t]) + c);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if col < 0 || col >= w.ncols {
|
||||
return;
|
||||
}
|
||||
let tile = w.tile0 + u32(col);
|
||||
let k = work[cursor_at(tile)];
|
||||
work[cursor_at(tile)] = k + 1u;
|
||||
let at = work[offset_at(tile)] + k;
|
||||
if at < params.more.y {
|
||||
let ox = w.ox + f32(u32(col) * 16u);
|
||||
geo[at] = vec4<f32>(s.x - ox, s.y - w.row_y0, s.z - ox, s.w - w.row_y0);
|
||||
}
|
||||
}
|
||||
|
||||
// The polygon's last piece so far in this invocation's row, and its first (binning.rs › Track).
|
||||
var<private> tr_last: bool;
|
||||
var<private> tr_last_col: i32;
|
||||
var<private> tr_last_y: f32;
|
||||
var<private> tr_first: bool;
|
||||
var<private> tr_first_col: i32;
|
||||
|
||||
// binning.rs › steps: where the outline passes from column `a` (its piece ending at height
|
||||
// `y`) to column `b`, a vertical piece on each tile boundary between them, from there to the
|
||||
// row's bottom.
|
||||
fn steps(w: Walk, r: Rng, a: i32, y: f32, b: i32) {
|
||||
if a == b {
|
||||
return;
|
||||
}
|
||||
let top = w.row_y0;
|
||||
let bottom = top + T;
|
||||
if !(y > top && y < bottom) {
|
||||
return;
|
||||
}
|
||||
let right = a < b;
|
||||
let lo = min(a, b);
|
||||
let hi = max(a, b);
|
||||
for (var k = max(lo + 1, 0); k <= min(hi, r.ncols - 1); k++) {
|
||||
let x = r.xlo + f32(k) * T;
|
||||
if right {
|
||||
emit(w, k, vec4<f32>(x, bottom, x, y));
|
||||
} else {
|
||||
emit(w, k, vec4<f32>(x, y, x, bottom));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A piece of the polygon in this row, in the direction of travel (column −1: left of the
|
||||
// fill's tiles; `ncols`: right of them, drawing nothing): kept, and seen by the steps.
|
||||
fn piece(w: Walk, r: Rng, col: i32, s: vec4<f32>) {
|
||||
if col < r.ncols {
|
||||
emit(w, col, s);
|
||||
}
|
||||
if tr_last {
|
||||
steps(w, r, tr_last_col, tr_last_y, col);
|
||||
} else {
|
||||
tr_first = true;
|
||||
tr_first_col = col;
|
||||
}
|
||||
tr_last = true;
|
||||
tr_last_col = col;
|
||||
tr_last_y = s.w;
|
||||
}
|
||||
|
||||
fn push(w: Walk, r: Rng, col: i32, u: vec2<f32>, v: vec2<f32>, down: bool) {
|
||||
if (down && v.y <= u.y) || (!down && v.y >= u.y) {
|
||||
return;
|
||||
}
|
||||
piece(w, r, col, vec4<f32>(u, v));
|
||||
}
|
||||
|
||||
// binning.rs › split_row: a piece inside one tile row, from `s` to `e` (the edge's direction),
|
||||
// split at the fill's left and right edges and at tile columns.
|
||||
fn split_row(w: Walk, s: vec2<f32>, e: vec2<f32>, r: Rng) {
|
||||
let down = e.y > s.y;
|
||||
let dx = e.x - s.x;
|
||||
let lo = min(s.x, e.x);
|
||||
let hi = max(s.x, e.x);
|
||||
if hi <= r.xlo && lo < r.xlo {
|
||||
push(w, r, -1, s, e, down);
|
||||
return;
|
||||
}
|
||||
if lo >= r.xhi {
|
||||
push(w, r, r.ncols, s, e, down);
|
||||
return;
|
||||
}
|
||||
let cl = i32(floor((lo - r.xlo) / T));
|
||||
if dx == 0.0 || (lo >= r.xlo && hi < r.xhi && cl == i32(floor((hi - r.xlo) / T))) {
|
||||
push(w, r, clamp(cl, 0, r.ncols - 1), s, e, down);
|
||||
return;
|
||||
}
|
||||
let kmin = max(i32(floor((lo - r.xlo) / T)) + 1, 0);
|
||||
let kmax = min(i32(ceil((hi - r.xlo) / T)) - 1, r.ncols);
|
||||
let count = max(kmax - kmin + 1, 0);
|
||||
var prev = s;
|
||||
for (var j = 0; j <= count; j++) {
|
||||
var next = e;
|
||||
if j != count {
|
||||
let k = select(kmax - j, kmin + j, dx > 0.0);
|
||||
let x = r.xlo + f32(k) * T;
|
||||
if !(x > lo && x < hi) {
|
||||
continue;
|
||||
}
|
||||
let t = clamp((x - s.x) / dx, 0.0, 1.0);
|
||||
next = vec2<f32>(x, s.y + (e.y - s.y) * t);
|
||||
}
|
||||
let mid = 0.5 * (prev.x + next.x);
|
||||
if mid < r.xlo {
|
||||
push(w, r, -1, prev, next, down);
|
||||
} else if mid < r.xhi {
|
||||
push(w, r, clamp(i32(floor((mid - r.xlo) / T)), 0, r.ncols - 1), prev, next, down);
|
||||
} else {
|
||||
push(w, r, r.ncols, prev, next, down);
|
||||
}
|
||||
prev = next;
|
||||
}
|
||||
}
|
||||
|
||||
// binning.rs › split_edge, for tile row `row` only.
|
||||
fn split_edge(w: Walk, a: vec2<f32>, b: vec2<f32>, r: Rng, row: u32) {
|
||||
if !(finite2(a) && finite2(b)) || a.y == b.y {
|
||||
return;
|
||||
}
|
||||
let down = a.y < b.y;
|
||||
let p = select(b, a, down);
|
||||
let q = select(a, b, down);
|
||||
let y0 = max(p.y, r.ylo);
|
||||
let y1 = min(q.y, r.yhi);
|
||||
if y1 <= y0 {
|
||||
return;
|
||||
}
|
||||
let first = u32(max(floor((y0 - r.ylo) / T), 0.0));
|
||||
let last = u32(max(ceil((y1 - r.ylo) / T), 0.0));
|
||||
if row < first || row >= last {
|
||||
return;
|
||||
}
|
||||
let dxdy = (q.x - p.x) / (q.y - p.y);
|
||||
let ry0 = r.ylo + f32(row * 16u);
|
||||
let ys = max(y0, ry0);
|
||||
let ye = min(y1, ry0 + T);
|
||||
if ye <= ys {
|
||||
return;
|
||||
}
|
||||
let top = vec2<f32>(p.x + (ys - p.y) * dxdy, ys);
|
||||
let bottom = vec2<f32>(p.x + (ye - p.y) * dxdy, ye);
|
||||
if down {
|
||||
split_row(w, top, bottom, r);
|
||||
} else {
|
||||
split_row(w, bottom, top, r);
|
||||
}
|
||||
}
|
||||
|
||||
// binning.rs › hairline_tiles, for tile row `row` only: the segment, whole, into every column
|
||||
// within reach.
|
||||
fn hairline(w: Walk, a: vec2<f32>, b: vec2<f32>, r: Rng, row: u32) {
|
||||
if !(finite2(a) && finite2(b)) {
|
||||
return;
|
||||
}
|
||||
let r0 = max(floor((min(a.y, b.y) - M - r.ylo) / T), 0.0);
|
||||
let r1 = min(floor((max(a.y, b.y) + M - r.ylo) / T), f32(r.nrows - 1));
|
||||
let rf = f32(row);
|
||||
if !(r1 >= r0) || rf < r0 || rf > r1 {
|
||||
return;
|
||||
}
|
||||
let top = r.ylo + rf * T;
|
||||
let dx = b.x - a.x;
|
||||
let dy = b.y - a.y;
|
||||
var xa = min(a.x, b.x);
|
||||
var xb = max(a.x, b.x);
|
||||
if dy != 0.0 {
|
||||
let t0 = clamp((top - M - a.y) / dy, 0.0, 1.0);
|
||||
let t1 = clamp((top + T + M - a.y) / dy, 0.0, 1.0);
|
||||
let u = a.x + dx * t0;
|
||||
let v = a.x + dx * t1;
|
||||
xa = min(u, v);
|
||||
xb = max(u, v);
|
||||
}
|
||||
let c0 = max(floor((xa - M - r.xlo) / T), 0.0);
|
||||
let c1 = min(floor((xb + M - r.xlo) / T), f32(r.ncols - 1));
|
||||
if !(c1 >= c0) {
|
||||
return;
|
||||
}
|
||||
for (var col = i32(c0); col <= i32(c1); col++) {
|
||||
emit(w, col, vec4<f32>(a, b));
|
||||
}
|
||||
}
|
||||
|
||||
// The invocation's index in a dispatch of 64-wide workgroups spread over x and y.
|
||||
fn linear(wg: vec3<u32>, n: vec3<u32>, lid: vec3<u32>, width: u32) -> u32 {
|
||||
return (wg.y * n.x + wg.x) * width + lid.x;
|
||||
}
|
||||
|
||||
fn walk(mode: u32, t: u32) {
|
||||
if t >= params.size.z {
|
||||
return;
|
||||
}
|
||||
let opi = input[params.at.w + t];
|
||||
let o = op_at(opi);
|
||||
// This op-row's row within the fill: how far `t` is past the fill's first op-row, which
|
||||
// `row_of` holds in the op's own slot of rows (op-rows are in op order).
|
||||
let row = t - input[params.at.w + params.size.z + opi];
|
||||
let ylo = f32(o.ty0 * 16u);
|
||||
let r = Rng(f32(o.tx0 * 16u), f32((o.tx0 + o.ncols) * 16u), ylo, f32((o.ty0 + o.nrows) * 16u), i32(o.ncols), i32(o.nrows));
|
||||
let hair = (o.flags & HAIRLINE_BIT) != 0u;
|
||||
let w = Walk(mode, o.tile_base + row * o.ncols, i32(o.ncols), hair, f32((o.ty0 + row) * 16u), r.xlo);
|
||||
for (var pi = 0u; pi < o.polys; pi++) {
|
||||
let pb = params.at.y + (o.first_poly + pi) * 2u;
|
||||
let start = input[pb];
|
||||
let n = input[pb + 1u];
|
||||
if hair {
|
||||
if n == 1u {
|
||||
let p = point(start);
|
||||
hairline(w, p, p, r, row);
|
||||
}
|
||||
for (var i = 0u; i + 1u < n; i++) {
|
||||
hairline(w, point(start + i), point(start + i + 1u), r, row);
|
||||
}
|
||||
} else if n >= 2u {
|
||||
tr_last = false;
|
||||
tr_first = false;
|
||||
for (var i = 0u; i < n; i++) {
|
||||
let a = point(start + i);
|
||||
let b = point(start + select(i + 1u, 0u, i + 1u == n));
|
||||
split_edge(w, a, b, r, row);
|
||||
}
|
||||
if tr_last && tr_first {
|
||||
steps(w, r, tr_last_col, tr_last_y, tr_first_col);
|
||||
}
|
||||
}
|
||||
}
|
||||
if mode == COUNT && !hair {
|
||||
// The backdrop deltas, summed along the row.
|
||||
var acc = 0;
|
||||
for (var c = 0u; c < o.ncols; c++) {
|
||||
let at = backdrop_at(w.tile0 + c);
|
||||
acc += bitcast<i32>(work[at]);
|
||||
work[at] = bitcast<u32>(acc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn count(@builtin(workgroup_id) wg: vec3<u32>, @builtin(num_workgroups) n: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
|
||||
walk(COUNT, linear(wg, n, lid, 64u));
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn scatter(@builtin(workgroup_id) wg: vec3<u32>, @builtin(num_workgroups) n: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
|
||||
walk(WRITE, linear(wg, n, lid, 64u));
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn tiles(@builtin(workgroup_id) wg: vec3<u32>, @builtin(num_workgroups) n: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
|
||||
let t = linear(wg, n, lid, 64u);
|
||||
if t >= params.size.w {
|
||||
return;
|
||||
}
|
||||
let tx = t % params.size.x;
|
||||
let ty = t / params.size.x;
|
||||
let start = index[2u * t];
|
||||
let rs = params.at2.x + input[params.at2.y + ty];
|
||||
let re = params.at2.x + input[params.at2.y + ty + 1u];
|
||||
var k = 0u;
|
||||
for (var i = rs; i < re; i++) {
|
||||
let opi = input[i];
|
||||
let o = op_at(opi);
|
||||
if tx < o.tx0 || tx >= o.tx0 + o.ncols {
|
||||
continue;
|
||||
}
|
||||
let ot = o.tile_base + (ty - o.ty0) * o.ncols + (tx - o.tx0);
|
||||
var c = work[counts_at(ot)];
|
||||
let bd = work[backdrop_at(ot)];
|
||||
if c == 0u && bd == 0u {
|
||||
continue;
|
||||
}
|
||||
let off = min(work[offset_at(ot)], params.more.y);
|
||||
c = min(c, params.more.y - off);
|
||||
let e = params.more.z + (start + k) * 4u;
|
||||
index[e] = opi;
|
||||
index[e + 1u] = off;
|
||||
index[e + 2u] = c;
|
||||
index[e + 3u] = bd;
|
||||
k++;
|
||||
}
|
||||
index[2u * t + 1u] = k;
|
||||
}
|
||||
+410
-195
@@ -1,13 +1,26 @@
|
||||
//! Tile binning: the CPU half of the GPU stage (ADR 0019, ADR 0029).
|
||||
//!
|
||||
//! The surface is cut into 16 × 16 pixel tiles. Every fill's edges are split at tile rows and
|
||||
//! columns; each piece lands in the one tile it crosses. What a piece contributes to the tiles
|
||||
//! to its right is a plain winding change per pixel row (it lies wholly to their left), so it
|
||||
//! is summed into a **backdrop** of 16 values, one per pixel row, carried across the tile row
|
||||
//! as in the public sparse-strips and Vello designs. A tile of a fill then needs only its own
|
||||
//! pieces and its backdrop: the fine shader computes each pixel's exact area coverage from
|
||||
//! those, the same integral the CPU oracle's accumulation buffer computes (ADR 0002). Tiles
|
||||
//! with neither (outside the fill) get no entry; interior tiles get a backdrop and no pieces.
|
||||
//! columns; each piece lands in the one tile it crosses. Everything left of a tile reaches it
|
||||
//! as the fill's winding number along the tile's left edge (ADR 0048), which is
|
||||
//!
|
||||
//! * its **backdrop**, the winding number just below the tile's top-left corner: an integer,
|
||||
//! the sum of the directions of the pieces further left that start on the tile row's top
|
||||
//! edge (they are the edges crossing it), plus
|
||||
//! * a step wherever the outline crosses the tile's left edge, kept as one more piece: a
|
||||
//! vertical line on that edge from the crossing down to the tile's bottom, upwards where the
|
||||
//! outline crosses rightwards (the winding there drops by one), downwards where it crosses
|
||||
//! leftwards.
|
||||
//!
|
||||
//! These are the backdrops and "y-edges" of Vello's tiles (its public design notes). A tile of
|
||||
//! a fill then needs only its own pieces and its backdrop: the fine shader computes each
|
||||
//! pixel's exact area coverage from those, the same integral the CPU oracle's accumulation
|
||||
//! buffer computes (ADR 0002). Tiles with neither (outside the fill) get no entry; interior
|
||||
//! tiles get a backdrop and no pieces. Backdrops are integers, so they add up the same in any
|
||||
//! order, and the GPU computes the same lists ([`crate::gpu_binning`]).
|
||||
//!
|
||||
//! A **hairline** (outline mode, ADR 0048) is binned by distance instead: each segment, whole,
|
||||
//! into every tile with a pixel centre within its reach; the shader takes the nearest.
|
||||
//!
|
||||
//! Each tile then lists its entries in drawing order, so the shader composites every pixel in
|
||||
//! one pass, front to back in the display list's order. Masks and groups (ADR 0029) are more
|
||||
@@ -34,8 +47,14 @@ type Vec4 = [f32; 4];
|
||||
/// Tile side in pixels (the shader's workgroup is one tile, one invocation per pixel).
|
||||
pub const TILE: u32 = 16;
|
||||
const T: f32 = TILE as f32;
|
||||
/// "No backdrop" in an entry; "no clip" or "no group" in the tables.
|
||||
/// "No clip" or "no group" in the tables.
|
||||
pub const NONE: u32 = u32::MAX;
|
||||
/// Fill rule code of a hairline in an op header (`0` non-zero, `1` even-odd).
|
||||
pub const HAIRLINE: u32 = 2;
|
||||
/// How far around a hairline segment its tiles are taken (`bin.wgsl` › `M`): a pixel centre
|
||||
/// within its reach is within `REACH` of a point of it, so the tile holding that centre holds a
|
||||
/// point within `REACH` of the segment's box; a quarter pixel more absorbs rounding.
|
||||
pub(crate) const HAIRLINE_MARGIN: f32 = anicraft_render::hairline::REACH + 0.25;
|
||||
/// `vec4`s of paint data per fill.
|
||||
pub const PAINT_VEC4S: usize = 4;
|
||||
/// Gradient table entries (the oracle's LUT size).
|
||||
@@ -97,11 +116,11 @@ pub fn blend_code(m: BlendMode) -> u32 {
|
||||
/// A scene ready for the fine shader.
|
||||
///
|
||||
/// * `index` (u32): `[start, count]` per tile into the entry list; then each entry as
|
||||
/// `[op, first piece, pieces, backdrop]` (the backdrop's first `vec4` in `geo`, or [`NONE`]),
|
||||
/// or a control entry ([`CTRL`] set); then each op's header `[kind, fill rule, ramp start in
|
||||
/// paints, flags]`.
|
||||
/// `[op, first piece, pieces, backdrop]` (the backdrop an `i32`), or a control entry ([`CTRL`]
|
||||
/// set); then, at `ops_at`, each op's header `[kind, fill rule (or HAIRLINE), ramp start in
|
||||
/// paints, flags]` ([`Binned::op_heads`]).
|
||||
/// * `geo` (`vec4<f32>`): pieces `(x0, y0, x1, y1)` relative to their tile's top-left, in the
|
||||
/// edge's direction; then backdrops, four `vec4`s (16 rows) each.
|
||||
/// edge's direction (left-edge steps included); a hairline's are its segments, whole.
|
||||
/// * `paints` (`vec4<f32>`): per op its colour, then the inverse paint transform and gradient,
|
||||
/// bitmap or layer parameters; then the gradient tables (256 premultiplied colours each);
|
||||
/// then (filled in on the GPU, [`Binned::layer_at`]) the filtered layers' pixels.
|
||||
@@ -113,6 +132,8 @@ pub struct Binned {
|
||||
pub index: Vec<u32>,
|
||||
pub entries_at: u32,
|
||||
pub ops_at: u32,
|
||||
/// The op headers, which go at `ops_at` in the index.
|
||||
pub op_heads: Vec<u32>,
|
||||
pub geo: Vec<[f32; 4]>,
|
||||
pub paints: Vec<[f32; 4]>,
|
||||
/// The paint buffer's whole length in `vec4`s: `paints`, then room for the layers.
|
||||
@@ -128,16 +149,18 @@ pub struct Binned {
|
||||
/// Pieces plus entries the fine pass walks, summed over tiles (each for 256 pixels): what
|
||||
/// bounds how long the dispatch runs.
|
||||
pub work: u64,
|
||||
/// Binned on the GPU: `index` holds only the tile headers (`[start, 0]`, room for every
|
||||
/// tile the fills' bounds cover), `geo` is empty, and the GPU computes the entries and
|
||||
/// pieces from this plan (`entries` and `pieces` are then upper bounds).
|
||||
pub gpu: Option<crate::gpu_binning::Plan>,
|
||||
}
|
||||
|
||||
/// A chunk of fills' share of the scene (binned in parallel; chunking keeps allocations few).
|
||||
#[derive(Default)]
|
||||
struct Local {
|
||||
/// `[op, tile, first piece, pieces, backdrop or NONE]`, piece and backdrop indices local.
|
||||
/// `[op, tile, first piece, pieces, backdrop]`, piece indices local.
|
||||
entries: Vec<[u32; 5]>,
|
||||
pieces: Vec<[f32; 4]>,
|
||||
/// Backdrops, four `vec4`s (16 pixel rows) each.
|
||||
backdrops: Vec<[f32; 4]>,
|
||||
}
|
||||
|
||||
/// An edge piece inside one tile row, in absolute pixels; `col` is the tile column relative to
|
||||
@@ -177,6 +200,12 @@ struct RowOut {
|
||||
/// shader holds ([`MAX_GROUP_DEPTH`], [`MAX_CLIP_DEPTH`]) or it has more bitmaps than
|
||||
/// [`MAX_IMAGES`]; the caller draws it on the CPU.
|
||||
pub fn bin(scene: &Scene, width: u32, height: u32) -> Result<Binned, NeedsFull> {
|
||||
bin_with(scene, width, height, None)
|
||||
}
|
||||
|
||||
/// [`bin`], or with `gpu`, a plan for binning on the GPU instead ([`Binned::gpu`]) when the
|
||||
/// scene can take it and fits `gpu`'s limits ([`crate::gpu_binning`]).
|
||||
pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_binning::Limits>) -> Result<Binned, NeedsFull> {
|
||||
if scene.groups.iter().any(|g| g.chain.len() > MAX_GROUP_DEPTH) {
|
||||
return Err(NeedsFull::Groups);
|
||||
}
|
||||
@@ -206,91 +235,16 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result<Binned, NeedsFull>
|
||||
|
||||
let tiles_x = width.div_ceil(TILE);
|
||||
let tiles_y = height.div_ceil(TILE);
|
||||
let (tx, ty) = (tiles_x as usize, tiles_y as usize);
|
||||
// Phase 1, parallel over chunks of ops: pieces, backdrops and entries; each chunk's
|
||||
// entries then sorted (stably, so drawing order holds) by tile row, with row offsets.
|
||||
let locals: Vec<(Local, Vec<u32>)> = ops
|
||||
.par_chunks(CHUNK)
|
||||
.enumerate()
|
||||
.map(|(c, chunk)| {
|
||||
let mut out = Local::default();
|
||||
let mut scratch = Vec::new();
|
||||
for (i, f) in chunk.iter().enumerate() {
|
||||
bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch);
|
||||
}
|
||||
out.entries.sort_by_key(|e| e[1] / tiles_x.max(1));
|
||||
let mut rows = vec![0u32; ty + 1];
|
||||
for e in &out.entries {
|
||||
if let Some(r) = rows.get_mut((e[1] / tiles_x.max(1)) as usize + 1) {
|
||||
*r += 1;
|
||||
}
|
||||
}
|
||||
for r in 1..rows.len() {
|
||||
rows[r] += rows[r - 1];
|
||||
}
|
||||
(out, rows)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Where each chunk's pieces and backdrops go in `geo`.
|
||||
let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum();
|
||||
let mut piece_at = Vec::with_capacity(locals.len());
|
||||
let mut bd_at = Vec::with_capacity(locals.len());
|
||||
let (mut p, mut b) = (0usize, pieces);
|
||||
for (l, _) in &locals {
|
||||
piece_at.push(p as u32);
|
||||
bd_at.push(b as u32);
|
||||
p += l.pieces.len();
|
||||
b += l.backdrops.len();
|
||||
}
|
||||
|
||||
// Phase 2, parallel over tile rows: each tile's stream of entries.
|
||||
let rows: Vec<RowOut> = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &bd_at, &tables)).collect();
|
||||
let mut row_at = vec![0usize; ty + 1];
|
||||
for (r, out) in rows.iter().enumerate() {
|
||||
row_at[r + 1] = row_at[r] + out.stream.len();
|
||||
}
|
||||
let total = row_at[ty];
|
||||
let work = rows.iter().map(|r| r.work).sum();
|
||||
let entries_at = 2 * tx * ty;
|
||||
let ops_at = entries_at + 4 * total;
|
||||
let mut index = vec![0u32; ops_at + 4 * ops.len()];
|
||||
// Phase 3, parallel over tile rows: headers and streams copied into place.
|
||||
{
|
||||
let (headers, rest) = index.split_at_mut(entries_at);
|
||||
let (mut entries, _) = rest.split_at_mut(4 * total);
|
||||
let mut row_entries: Vec<&mut [u32]> = Vec::with_capacity(ty);
|
||||
for r in 0..ty {
|
||||
let (mine, after) = std::mem::take(&mut entries).split_at_mut(4 * (row_at[r + 1] - row_at[r]));
|
||||
row_entries.push(mine);
|
||||
entries = after;
|
||||
// On the GPU when asked and the scene can take it (no fill in a mask or a group, for now):
|
||||
// then the fills alone are the ops (no mask artwork draws).
|
||||
let plan = gpu.filter(|_| scene.fills.iter().all(|f| f.clip.is_none() && f.group.is_none())).and_then(|lim| crate::gpu_binning::plan(&scene.fills, tiles_x, tiles_y, lim));
|
||||
let lists = match &plan {
|
||||
Some(p) => {
|
||||
ops.truncate(nf);
|
||||
Lists::on_gpu(p, tiles_x, tiles_y)
|
||||
}
|
||||
headers.par_chunks_mut(2 * tx.max(1)).zip(row_entries).zip(&rows).enumerate().for_each(|(r, ((head, out), row))| {
|
||||
for (h, &[s, n]) in head.as_chunks_mut::<2>().0.iter_mut().zip(&row.heads) {
|
||||
*h = [row_at[r] as u32 + s, n];
|
||||
}
|
||||
for (d, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(&row.stream) {
|
||||
*d = *s;
|
||||
}
|
||||
});
|
||||
}
|
||||
// Pieces, then backdrops, copied in parallel into their places.
|
||||
let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; b];
|
||||
{
|
||||
let (mut piece_dst, mut bd_dst) = geo.split_at_mut(pieces);
|
||||
let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(2 * locals.len());
|
||||
for (l, _) in &locals {
|
||||
let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len());
|
||||
jobs.push((a, &l.pieces));
|
||||
piece_dst = rest;
|
||||
let (a, rest) = std::mem::take(&mut bd_dst).split_at_mut(l.backdrops.len());
|
||||
jobs.push((a, &l.backdrops));
|
||||
bd_dst = rest;
|
||||
}
|
||||
jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s));
|
||||
}
|
||||
// Tens of thousands of small buffers: free them on the pool, off the frame's path.
|
||||
anicraft_render::drop_in_background((locals, rows));
|
||||
None => cpu_lists(&ops, &tables, tiles_x, tiles_y),
|
||||
};
|
||||
|
||||
// Paints: a fixed record per op, then the gradient tables, then the layers' pixels.
|
||||
let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len());
|
||||
@@ -313,9 +267,11 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result<Binned, NeedsFull>
|
||||
return Err(NeedsFull::Filters);
|
||||
}
|
||||
let paints_len = cursor;
|
||||
let mut op_heads: Vec<u32> = Vec::with_capacity(4 * ops.len());
|
||||
let u = f32::from_bits;
|
||||
for (op, f) in ops.iter().enumerate() {
|
||||
let rule = match f.rule {
|
||||
_ if f.hairline => HAIRLINE,
|
||||
FillRule::NonZero => 0,
|
||||
FillRule::EvenOdd => 1,
|
||||
};
|
||||
@@ -336,8 +292,8 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result<Binned, NeedsFull>
|
||||
let m = inv.m;
|
||||
(RADIAL, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]])
|
||||
}
|
||||
// The oracle's bilinear sample of a bitmap (crates/render/src/paint.rs › sample).
|
||||
(Shader::Bitmap { inv, pixels, repeat, fx }, _) => {
|
||||
// The oracle's sample of a bitmap (crates/render/src/paint.rs › sample).
|
||||
(Shader::Bitmap { inv, pixels, repeat, fx, smooth }, _) => {
|
||||
if pixels.width == 0 || pixels.height == 0 {
|
||||
(SOLID, [[0.0; 4]; 4])
|
||||
} else {
|
||||
@@ -351,7 +307,8 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result<Binned, NeedsFull>
|
||||
};
|
||||
let m = inv.m;
|
||||
let (k, alpha, tint, keep) = colour_effect(fx);
|
||||
(BITMAP, [[u(slot as u32), u(u32::from(*repeat)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], k, alpha], [tint[0], tint[1], tint[2], u(keep)]])
|
||||
// Bit 0: repeat; bit 1: the nearest pixel instead of bilinear (no smoothing).
|
||||
(BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], k, alpha], [tint[0], tint[1], tint[2], u(keep)]])
|
||||
}
|
||||
}
|
||||
// `prepare_scene` never hands these over; draw nothing rather than guess.
|
||||
@@ -365,10 +322,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result<Binned, NeedsFull>
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let at = ops_at + 4 * op;
|
||||
if let Some(slot) = index.get_mut(at..at + 4) {
|
||||
slot.copy_from_slice(&[kind, rule, ramp, flags]);
|
||||
}
|
||||
op_heads.extend_from_slice(&[kind, rule, ramp, flags]);
|
||||
}
|
||||
paints.extend_from_slice(&ramps);
|
||||
if paints.len() != PAINT_VEC4S * ops.len() + table_len {
|
||||
@@ -376,7 +330,115 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result<Binned, NeedsFull>
|
||||
return Err(NeedsFull::Filters);
|
||||
}
|
||||
|
||||
Ok(Binned { tiles_x, tiles_y, index, entries_at: entries_at as u32, ops_at: ops_at as u32, geo, paints, paints_len, layer_at, images, entries: total, pieces, work })
|
||||
let Lists { index, geo, entries_at, ops_at, entries, pieces, work } = lists;
|
||||
Ok(Binned { tiles_x, tiles_y, index, entries_at, ops_at, op_heads, geo, paints, paints_len, layer_at, images, entries, pieces, work, gpu: plan })
|
||||
}
|
||||
|
||||
/// The tile lists (or, binned on the GPU, room for them).
|
||||
struct Lists {
|
||||
index: Vec<u32>,
|
||||
geo: Vec<[f32; 4]>,
|
||||
entries_at: u32,
|
||||
ops_at: u32,
|
||||
entries: usize,
|
||||
pieces: usize,
|
||||
work: u64,
|
||||
}
|
||||
|
||||
impl Lists {
|
||||
/// Headers `[start, 0]` with room for every tile its fills' bounds cover; the GPU fills in
|
||||
/// the entries and the counts. Entries and pieces are upper bounds.
|
||||
fn on_gpu(p: &crate::gpu_binning::Plan, tiles_x: u32, tiles_y: u32) -> Lists {
|
||||
let entries_at = 2 * tiles_x * tiles_y;
|
||||
let ops_at = entries_at + 4 * p.op_tiles;
|
||||
let work = u64::from(p.op_tiles) + u64::from(p.piece_cap);
|
||||
Lists { index: p.headers.clone(), geo: Vec::new(), entries_at, ops_at, entries: p.op_tiles as usize, pieces: p.piece_cap as usize, work }
|
||||
}
|
||||
}
|
||||
|
||||
/// The tile lists, binned on the CPU (in parallel per chunk of fills, then per tile row).
|
||||
fn cpu_lists(ops: &[&Fill], tables: &Tables, tiles_x: u32, tiles_y: u32) -> Lists {
|
||||
let (tx, ty) = (tiles_x as usize, tiles_y as usize);
|
||||
// Phase 1, parallel over chunks of ops: pieces, backdrops and entries; each chunk's
|
||||
// entries then sorted (stably, so drawing order holds) by tile row, with row offsets.
|
||||
let locals: Vec<(Local, Vec<u32>)> = ops
|
||||
.par_chunks(CHUNK)
|
||||
.enumerate()
|
||||
.map(|(c, chunk)| {
|
||||
let mut out = Local::default();
|
||||
let mut scratch = (Vec::new(), Track::default());
|
||||
for (i, f) in chunk.iter().enumerate() {
|
||||
bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch);
|
||||
}
|
||||
out.entries.sort_by_key(|e| e[1] / tiles_x.max(1));
|
||||
let mut rows = vec![0u32; ty + 1];
|
||||
for e in &out.entries {
|
||||
if let Some(r) = rows.get_mut((e[1] / tiles_x.max(1)) as usize + 1) {
|
||||
*r += 1;
|
||||
}
|
||||
}
|
||||
for r in 1..rows.len() {
|
||||
rows[r] += rows[r - 1];
|
||||
}
|
||||
(out, rows)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Where each chunk's pieces go in `geo`.
|
||||
let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum();
|
||||
let mut piece_at = Vec::with_capacity(locals.len());
|
||||
let mut p = 0usize;
|
||||
for (l, _) in &locals {
|
||||
piece_at.push(p as u32);
|
||||
p += l.pieces.len();
|
||||
}
|
||||
|
||||
// Phase 2, parallel over tile rows: each tile's stream of entries.
|
||||
let rows: Vec<RowOut> = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, tables)).collect();
|
||||
let mut row_at = vec![0usize; ty + 1];
|
||||
for (r, out) in rows.iter().enumerate() {
|
||||
row_at[r + 1] = row_at[r] + out.stream.len();
|
||||
}
|
||||
let total = row_at[ty];
|
||||
let work = rows.iter().map(|r| r.work).sum();
|
||||
let entries_at = 2 * tx * ty;
|
||||
let ops_at = entries_at + 4 * total;
|
||||
let mut index = vec![0u32; ops_at];
|
||||
// Phase 3, parallel over tile rows: headers and streams copied into place.
|
||||
{
|
||||
let (headers, rest) = index.split_at_mut(entries_at);
|
||||
let (mut entries, _) = rest.split_at_mut(4 * total);
|
||||
let mut row_entries: Vec<&mut [u32]> = Vec::with_capacity(ty);
|
||||
for r in 0..ty {
|
||||
let (mine, after) = std::mem::take(&mut entries).split_at_mut(4 * (row_at[r + 1] - row_at[r]));
|
||||
row_entries.push(mine);
|
||||
entries = after;
|
||||
}
|
||||
headers.par_chunks_mut(2 * tx.max(1)).zip(row_entries).zip(&rows).enumerate().for_each(|(r, ((head, out), row))| {
|
||||
for (h, &[s, n]) in head.as_chunks_mut::<2>().0.iter_mut().zip(&row.heads) {
|
||||
*h = [row_at[r] as u32 + s, n];
|
||||
}
|
||||
for (d, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(&row.stream) {
|
||||
*d = *s;
|
||||
}
|
||||
});
|
||||
}
|
||||
// Pieces copied in parallel into their places.
|
||||
let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces];
|
||||
{
|
||||
let mut piece_dst = &mut geo[..];
|
||||
let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(locals.len());
|
||||
for (l, _) in &locals {
|
||||
let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len());
|
||||
jobs.push((a, &l.pieces));
|
||||
piece_dst = rest;
|
||||
}
|
||||
jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s));
|
||||
}
|
||||
// Tens of thousands of small buffers: free them on the pool, off the frame's path.
|
||||
anicraft_render::drop_in_background((locals, rows));
|
||||
|
||||
Lists { index, geo, entries_at: entries_at as u32, ops_at: ops_at as u32, entries: total, pieces, work }
|
||||
}
|
||||
|
||||
/// A colour effect as the shader applies it to each bitmap tap, the same arithmetic as
|
||||
@@ -403,7 +465,7 @@ fn colour_effect(fx: &anicraft_doc::ColorEffect) -> (f32, f32, [f32; 3], u32) {
|
||||
|
||||
/// Tile row `r`'s streams: per tile, its fills in drawing order with the clip and group
|
||||
/// entries they need.
|
||||
fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec<u32>)], piece_at: &[u32], bd_at: &[u32], t: &Tables) -> RowOut {
|
||||
fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec<u32>)], piece_at: &[u32], t: &Tables) -> RowOut {
|
||||
let first_tile = (r * tx) as u32;
|
||||
let slices = || {
|
||||
locals.iter().enumerate().map(move |(c, (l, rows))| {
|
||||
@@ -430,13 +492,12 @@ fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec<u32>)], piece_at: &[u3
|
||||
let mut ae = vec![[0u32; 4]; nart];
|
||||
let mut cursor: Vec<[u32; 2]> = count[..tx].to_vec();
|
||||
for (c, es) in slices() {
|
||||
let (p0, b0) = (piece_at.get(c).copied().unwrap_or(0), bd_at.get(c).copied().unwrap_or(0));
|
||||
let p0 = piece_at.get(c).copied().unwrap_or(0);
|
||||
for &[op, tile, s0, n, bd] in es {
|
||||
let Some(cur) = cursor.get_mut(tile.wrapping_sub(first_tile) as usize) else { continue };
|
||||
let art = usize::from(op >= t.fills);
|
||||
let at = cur[art] as usize;
|
||||
cur[art] += 1;
|
||||
let bd = if bd == NONE { NONE } else { b0 + bd };
|
||||
let slot = if art == 1 { ae.get_mut(at) } else { fe.get_mut(at) };
|
||||
if let Some(slot) = slot {
|
||||
*slot = [op, p0 + s0, n, bd];
|
||||
@@ -514,30 +575,33 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec<
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits one fill's edges into tile pieces and walks each tile row for backdrops.
|
||||
fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, pieces: &mut Vec<Piece>) {
|
||||
let b = f.bounds;
|
||||
if b.is_empty() {
|
||||
return;
|
||||
}
|
||||
let tx0 = b.x0.max(0) as u32 / TILE;
|
||||
let tx1 = (b.x1.max(0) as u32).div_ceil(TILE).min(tiles_x);
|
||||
let ty0 = b.y0.max(0) as u32 / TILE;
|
||||
let ty1 = (b.y1.max(0) as u32).div_ceil(TILE).min(tiles_y);
|
||||
if tx1 <= tx0 || ty1 <= ty0 {
|
||||
return;
|
||||
}
|
||||
let ncols = (tx1 - tx0) as i32;
|
||||
let range = Range { ylo: (ty0 * TILE) as f32, yhi: (ty1 * TILE) as f32, xlo: (tx0 * TILE) as f32, xhi: (tx1 * TILE) as f32, ncols };
|
||||
/// Splits one fill's edges into tile pieces (with the steps where its outline crosses a tile's
|
||||
/// left edge) and walks each tile row for the backdrops.
|
||||
fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, (pieces, track): &mut (Vec<Piece>, Track)) {
|
||||
let Some(range) = Range::of(f, tiles_x, tiles_y) else { return };
|
||||
pieces.clear();
|
||||
for poly in &f.polys {
|
||||
let n = poly.len();
|
||||
if n < 2 {
|
||||
continue;
|
||||
if f.hairline {
|
||||
for poly in &f.polys {
|
||||
for_segments(poly, |a, b| hairline_tiles(a, b, &range, HAIRLINE_MARGIN, |row, col| pieces.push(Piece { row, col, seg: [a.x, a.y, b.x, b.y] })));
|
||||
}
|
||||
for i in 0..n {
|
||||
let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue };
|
||||
split_edge(a, c, &range, pieces);
|
||||
} else {
|
||||
for poly in &f.polys {
|
||||
let n = poly.len();
|
||||
if n < 2 {
|
||||
continue;
|
||||
}
|
||||
track.start(range.nrows as usize);
|
||||
let mut keep = |p: Piece| pieces.push(p);
|
||||
for i in 0..n {
|
||||
let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue };
|
||||
split_edge(a, c, &range, |row, col, seg| {
|
||||
if col < range.ncols {
|
||||
keep(Piece { row, col, seg });
|
||||
}
|
||||
track.see(row, Seen { col, end_y: seg[3] }, &range, &mut keep);
|
||||
});
|
||||
}
|
||||
track.finish(&range, &mut keep);
|
||||
}
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
@@ -549,53 +613,37 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec
|
||||
let mut i = 0usize;
|
||||
while let Some(first) = pieces.get(i) {
|
||||
let row = first.row;
|
||||
let row_y0 = ((ty0 + row) * TILE) as f32;
|
||||
let mut wind = [0.0f32; 16];
|
||||
// Parts left of the fill's tiles only shift the winding.
|
||||
let row_y0 = range.row_y0(row);
|
||||
// Pieces left of the fill's tiles only count where they start on the row's top edge.
|
||||
let mut backdrop = 0i32;
|
||||
while let Some(p) = pieces.get(i).filter(|p| p.row == row && p.col < 0) {
|
||||
add_rows(&mut wind, &p.seg, row_y0);
|
||||
backdrop += top_crossing(&p.seg, row_y0);
|
||||
i += 1;
|
||||
}
|
||||
let mut last_bd: Option<(u32, [f32; 16])> = None;
|
||||
for col in 0..ncols {
|
||||
for col in 0..range.ncols {
|
||||
let start = i;
|
||||
while pieces.get(i).is_some_and(|p| p.row == row && p.col == col) {
|
||||
i += 1;
|
||||
}
|
||||
let here = pieces.get(start..i).unwrap_or(&[]);
|
||||
let empty_wind = wind.iter().all(|w| w.abs() < 1e-6);
|
||||
if empty_wind {
|
||||
wind = [0.0; 16];
|
||||
}
|
||||
if here.is_empty() && empty_wind {
|
||||
if here.is_empty() && backdrop == 0 {
|
||||
// Nothing here; and nothing further right either once the row's pieces are used.
|
||||
if !pieces.get(i).is_some_and(|p| p.row == row) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let tile_x = tx0 + col as u32;
|
||||
let tile = (ty0 + row) * tiles_x + tile_x;
|
||||
let bd = if empty_wind {
|
||||
NONE
|
||||
} else {
|
||||
match last_bd {
|
||||
Some((k, w)) if w == wind => k,
|
||||
_ => {
|
||||
let k = out.backdrops.len() as u32;
|
||||
out.backdrops.extend_from_slice(wind.as_chunks::<4>().0);
|
||||
last_bd = Some((k, wind));
|
||||
k
|
||||
}
|
||||
}
|
||||
};
|
||||
let tile_x = range.tx0 + col as u32;
|
||||
let tile = (range.ty0 + row) * tiles_x + tile_x;
|
||||
let (ox, oy) = ((tile_x * TILE) as f32, row_y0);
|
||||
let s0 = out.pieces.len() as u32;
|
||||
for p in here {
|
||||
out.pieces.push([p.seg[0] - ox, p.seg[1] - oy, p.seg[2] - ox, p.seg[3] - oy]);
|
||||
add_rows(&mut wind, &p.seg, row_y0);
|
||||
}
|
||||
out.entries.push([op, tile, s0, here.len() as u32, bd]);
|
||||
out.entries.push([op, tile, s0, here.len() as u32, backdrop as u32]);
|
||||
if !f.hairline {
|
||||
backdrop += here.iter().map(|p| top_crossing(&p.seg, row_y0)).sum::<i32>();
|
||||
}
|
||||
}
|
||||
// Skip whatever is left of this row (pieces right of the range never get here).
|
||||
while pieces.get(i).is_some_and(|p| p.row == row) {
|
||||
@@ -604,38 +652,75 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill's tile range, in pixels and tiles.
|
||||
struct Range {
|
||||
ylo: f32,
|
||||
yhi: f32,
|
||||
xlo: f32,
|
||||
xhi: f32,
|
||||
ncols: i32,
|
||||
}
|
||||
|
||||
/// Adds the winding a piece gives everything to its right, per pixel row of its tile row.
|
||||
fn add_rows(wind: &mut [f32; 16], seg: &[f32; 4], row_y0: f32) {
|
||||
let (ya, yb, dir) = if seg[1] < seg[3] { (seg[1], seg[3], 1.0) } else { (seg[3], seg[1], -1.0) };
|
||||
let r0 = ((ya - row_y0).floor().max(0.0)) as usize;
|
||||
let r1 = ((yb - row_y0).ceil().min(T)) as usize;
|
||||
for r in r0..r1 {
|
||||
let lo = row_y0 + r as f32;
|
||||
let d = yb.min(lo + 1.0) - ya.max(lo);
|
||||
if d > 0.0
|
||||
&& let Some(w) = wind.get_mut(r)
|
||||
{
|
||||
*w += dir * d;
|
||||
/// The edges of a closed polygon (fills) or the segments of an open polyline (hairlines; a
|
||||
/// single point is a dot).
|
||||
fn for_segments(poly: &[Vec2], mut f: impl FnMut(Vec2, Vec2)) {
|
||||
match poly {
|
||||
[] => {}
|
||||
[p] => f(*p, *p),
|
||||
_ => {
|
||||
for w in poly.windows(2) {
|
||||
f(w[0], w[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits edge `a → b` at tile rows and columns inside the fill's range.
|
||||
fn split_edge(a: Vec2, b: Vec2, r: &Range, out: &mut Vec<Piece>) {
|
||||
/// The direction (`1` down, `−1` up) of a piece that starts on its tile row's top edge at
|
||||
/// `row_y0`, which means its edge crosses that edge; `0` for any other piece.
|
||||
pub(crate) fn top_crossing(seg: &[f32; 4], row_y0: f32) -> i32 {
|
||||
if seg[1] == seg[3] || seg[1].min(seg[3]) != row_y0 {
|
||||
return 0;
|
||||
}
|
||||
if seg[3] > seg[1] { 1 } else { -1 }
|
||||
}
|
||||
|
||||
/// A fill's tile range, in pixels and tiles.
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Range {
|
||||
pub(crate) tx0: u32,
|
||||
pub(crate) ty0: u32,
|
||||
pub(crate) ylo: f32,
|
||||
pub(crate) yhi: f32,
|
||||
pub(crate) xlo: f32,
|
||||
pub(crate) xhi: f32,
|
||||
pub(crate) ncols: i32,
|
||||
pub(crate) nrows: i32,
|
||||
}
|
||||
|
||||
impl Range {
|
||||
/// The tiles `f`'s bounds cover, within the surface's; `None` when there are none.
|
||||
pub(crate) fn of(f: &Fill, tiles_x: u32, tiles_y: u32) -> Option<Range> {
|
||||
let b = f.bounds;
|
||||
if b.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let tx0 = b.x0.max(0) as u32 / TILE;
|
||||
let tx1 = (b.x1.max(0) as u32).div_ceil(TILE).min(tiles_x);
|
||||
let ty0 = b.y0.max(0) as u32 / TILE;
|
||||
let ty1 = (b.y1.max(0) as u32).div_ceil(TILE).min(tiles_y);
|
||||
if tx1 <= tx0 || ty1 <= ty0 {
|
||||
return None;
|
||||
}
|
||||
let (ncols, nrows) = ((tx1 - tx0) as i32, (ty1 - ty0) as i32);
|
||||
Some(Range { tx0, ty0, ylo: (ty0 * TILE) as f32, yhi: (ty1 * TILE) as f32, xlo: (tx0 * TILE) as f32, xhi: (tx1 * TILE) as f32, ncols, nrows })
|
||||
}
|
||||
|
||||
fn row_y0(&self, row: u32) -> f32 {
|
||||
((self.ty0 + row) * TILE) as f32
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits edge `a → b` at tile rows and columns inside the fill's range, row by row, each row's
|
||||
/// pieces in the edge's direction of travel. Parts right of the fill's tiles come as column
|
||||
/// `ncols` (they draw nothing, but the steps on the tiles' left edges need to see them).
|
||||
fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32, [f32; 4])) {
|
||||
if !(a.is_finite() && b.is_finite()) || a.y == b.y {
|
||||
return;
|
||||
}
|
||||
// Work top to bottom; restore the direction when storing.
|
||||
let (p, q, down) = if a.y < b.y { (a, b, true) } else { (b, a, false) };
|
||||
let down = a.y < b.y;
|
||||
let (p, q) = if down { (a, b) } else { (b, a) };
|
||||
let y0 = p.y.max(r.ylo);
|
||||
let y1 = q.y.min(r.yhi);
|
||||
if y1 <= y0 {
|
||||
@@ -652,21 +737,26 @@ fn split_edge(a: Vec2, b: Vec2, r: &Range, out: &mut Vec<Piece>) {
|
||||
if ye <= ys {
|
||||
continue;
|
||||
}
|
||||
let (xs, xe) = (x_at(ys), x_at(ye));
|
||||
split_row(row, Vec2::new(xs, ys), Vec2::new(xe, ye), down, r, out);
|
||||
let (top, bottom) = (Vec2::new(x_at(ys), ys), Vec2::new(x_at(ye), ye));
|
||||
if down {
|
||||
split_row(row, top, bottom, r, &mut out);
|
||||
} else {
|
||||
split_row(row, bottom, top, r, &mut out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits a piece inside one tile row at the fill's left and right edges and at tile columns.
|
||||
fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec<Piece>) {
|
||||
/// Splits a piece inside one tile row, from `s` to `e` (the edge's direction), at the fill's
|
||||
/// left and right edges and at tile columns: column −1 left of the fill's tiles, `ncols` right.
|
||||
fn split_row(row: u32, s: Vec2, e: Vec2, r: &Range, out: &mut impl FnMut(u32, i32, [f32; 4])) {
|
||||
let down = e.y > s.y;
|
||||
let mut push = |col: i32, u: Vec2, v: Vec2| {
|
||||
if v.y <= u.y {
|
||||
if (down && v.y <= u.y) || (!down && v.y >= u.y) {
|
||||
return;
|
||||
}
|
||||
let seg = if down { [u.x, u.y, v.x, v.y] } else { [v.x, v.y, u.x, u.y] };
|
||||
out.push(Piece { row, col, seg });
|
||||
out(row, col, [u.x, u.y, v.x, v.y]);
|
||||
};
|
||||
// Points where the piece crosses a column boundary (or the range's edges), top to bottom.
|
||||
// Points where the piece crosses a column boundary (or the range's edges), in order.
|
||||
let dx = e.x - s.x;
|
||||
let at_x = |x: f32| -> Vec2 {
|
||||
let t = ((x - s.x) / dx).clamp(0.0, 1.0);
|
||||
@@ -674,12 +764,15 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec<Pi
|
||||
};
|
||||
let col_of = |x: f32| ((x - r.xlo) / T).floor() as i32;
|
||||
let (lo, hi) = (s.x.min(e.x), s.x.max(e.x));
|
||||
if hi <= r.xlo {
|
||||
// Left of the fill's tiles (a vertical piece on their left edge is in the first column:
|
||||
// the backdrop and the left-edge steps count only what lies strictly left of a tile).
|
||||
if hi <= r.xlo && lo < r.xlo {
|
||||
push(-1, s, e);
|
||||
return;
|
||||
}
|
||||
if lo >= r.xhi {
|
||||
return; // wholly right of the fill's tiles: it covers none of their pixels
|
||||
push(r.ncols, s, e);
|
||||
return;
|
||||
}
|
||||
// Most pieces (flattened curves are short) lie inside one tile column.
|
||||
let cl = col_of(lo);
|
||||
@@ -709,11 +802,133 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec<Pi
|
||||
push(-1, prev, next);
|
||||
} else if mid < r.xhi {
|
||||
push(col_of(mid).clamp(0, r.ncols - 1), prev, next);
|
||||
} else {
|
||||
push(r.ncols, prev, next);
|
||||
}
|
||||
prev = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece as the left-edge steps see it: its column and the height where it ends.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Seen {
|
||||
col: i32,
|
||||
end_y: f32,
|
||||
}
|
||||
|
||||
/// Per tile row of a fill, the last piece of the polygon walked so far there and its first:
|
||||
/// consecutive pieces of a row in different columns are where the outline crosses tiles' left
|
||||
/// edges.
|
||||
#[derive(Default)]
|
||||
struct Track {
|
||||
last: Vec<Option<Seen>>,
|
||||
first: Vec<Option<Seen>>,
|
||||
touched: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
/// Ready for a polygon of a fill with `nrows` tile rows.
|
||||
fn start(&mut self, nrows: usize) {
|
||||
for &r in &self.touched {
|
||||
if let Some(l) = self.last.get_mut(r as usize) {
|
||||
*l = None;
|
||||
}
|
||||
if let Some(f) = self.first.get_mut(r as usize) {
|
||||
*f = None;
|
||||
}
|
||||
}
|
||||
self.touched.clear();
|
||||
if self.last.len() < nrows {
|
||||
self.last.resize(nrows, None);
|
||||
self.first.resize(nrows, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// The next piece of the polygon in tile row `row`; the steps between it and the row's
|
||||
/// previous piece go to `out`.
|
||||
fn see(&mut self, row: u32, s: Seen, r: &Range, out: &mut impl FnMut(Piece)) {
|
||||
let (Some(last), Some(first)) = (self.last.get_mut(row as usize), self.first.get_mut(row as usize)) else { return };
|
||||
match *last {
|
||||
Some(p) => steps(p, s, row, r, out),
|
||||
None => {
|
||||
*first = Some(s);
|
||||
self.touched.push(row);
|
||||
}
|
||||
}
|
||||
*last = Some(s);
|
||||
}
|
||||
|
||||
/// The polygon is closed: each row's last piece is followed by its first.
|
||||
fn finish(&mut self, r: &Range, out: &mut impl FnMut(Piece)) {
|
||||
for &row in &self.touched {
|
||||
if let (Some(Some(l)), Some(Some(f))) = (self.last.get(row as usize), self.first.get(row as usize)) {
|
||||
steps(*l, *f, row, r, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps in the winding along the tiles' left edges between consecutive pieces `a` and `b`
|
||||
/// of one tile row (ADR 0048): where the outline passes from column `a.col` to `b.col`, at the
|
||||
/// height where `a` ends, each tile boundary between them gets a vertical piece on its left
|
||||
/// edge from there to the row's bottom: upwards when the outline runs right (the winding left
|
||||
/// of the tile drops by one), downwards when it runs left. On the row's top edge the backdrop
|
||||
/// has the step already, on its bottom edge it changes nothing.
|
||||
fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) {
|
||||
if a.col == b.col {
|
||||
return;
|
||||
}
|
||||
let top = r.ylo + (row * TILE) as f32;
|
||||
let (y, bottom) = (a.end_y, top + T);
|
||||
if !(y > top && y < bottom) {
|
||||
return;
|
||||
}
|
||||
let right = a.col < b.col;
|
||||
let (lo, hi) = if right { (a.col, b.col) } else { (b.col, a.col) };
|
||||
for k in (lo + 1).max(0)..=hi.min(r.ncols - 1) {
|
||||
let x = r.xlo + k as f32 * T;
|
||||
let seg = if right { [x, bottom, x, y] } else { [x, y, x, bottom] };
|
||||
out(Piece { row, col: k, seg });
|
||||
}
|
||||
}
|
||||
|
||||
/// Every tile of the range within `margin` of segment `a → b` (rows and columns padded by it),
|
||||
/// as `(row, col)` relative to the range. With [`HAIRLINE_MARGIN`], every tile with a pixel
|
||||
/// centre within a hairline's reach (`bin.wgsl` › `hairline` uses the same).
|
||||
pub(crate) fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, margin: f32, mut out: impl FnMut(u32, i32)) {
|
||||
if !(a.is_finite() && b.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let m = margin;
|
||||
let (ymin, ymax) = (a.y.min(b.y), a.y.max(b.y));
|
||||
let r0 = (((ymin - m - r.ylo) / T).floor()).max(0.0);
|
||||
let r1 = (((ymax + m - r.ylo) / T).floor()).min((r.nrows - 1) as f32);
|
||||
if r1 < r0 {
|
||||
return;
|
||||
}
|
||||
let (dx, dy) = (b.x - a.x, b.y - a.y);
|
||||
for row in r0 as i32..=r1 as i32 {
|
||||
let top = r.ylo + row as f32 * T;
|
||||
// The segment's part within the row's band, then the columns within reach of it.
|
||||
let (xa, xb) = if dy == 0.0 {
|
||||
(a.x.min(b.x), a.x.max(b.x))
|
||||
} else {
|
||||
let t0 = ((top - m - a.y) / dy).clamp(0.0, 1.0);
|
||||
let t1 = ((top + T + m - a.y) / dy).clamp(0.0, 1.0);
|
||||
let (u, v) = (a.x + dx * t0, a.x + dx * t1);
|
||||
(u.min(v), u.max(v))
|
||||
};
|
||||
let c0 = (((xa - m - r.xlo) / T).floor()).max(0.0);
|
||||
let c1 = (((xb + m - r.xlo) / T).floor()).min((r.ncols - 1) as f32);
|
||||
if c1 < c0 {
|
||||
continue;
|
||||
}
|
||||
for col in c0 as i32..=c1 as i32 {
|
||||
out(row as u32, col);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Coverage of pixel `(px, py)` (tile-relative) from one piece: the same integral the oracle's
|
||||
/// accumulation buffer computes. Used by tests to check the binning on the CPU.
|
||||
#[cfg(test)]
|
||||
|
||||
+56
-16
@@ -1,11 +1,13 @@
|
||||
// AniCraft GPU stage: fine rasterization (ADR 0019, ADR 0029).
|
||||
//
|
||||
// One workgroup per 16 × 16 tile, one invocation per pixel. Each pixel walks its tile's entries
|
||||
// in drawing order. An entry's coverage is its backdrop (winding from edges left of the tile,
|
||||
// per pixel row) plus the exact area each of the tile's edge pieces covers in the pixel: the
|
||||
// same integral as the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the
|
||||
// fill rule, the paint (solid, or the oracle's own 256-entry gradient table) and src-over on
|
||||
// premultiplied colour, all in f32, as the oracle does.
|
||||
// in drawing order. An entry's coverage is its backdrop (the winding number just below the
|
||||
// tile's top-left corner, an integer; ADR 0048) plus the exact area each of the tile's edge
|
||||
// pieces covers in the pixel, the steps on the tile's left edge included: the same integral as
|
||||
// the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the fill rule, the
|
||||
// paint (solid, or the oracle's own 256-entry gradient table) and src-over on premultiplied
|
||||
// colour, all in f32, as the oracle does. A hairline (ADR 0048) is 1 − the distance from the
|
||||
// pixel centre to its nearest segment (crates/render/src/hairline.rs).
|
||||
//
|
||||
// Masks and groups (ADR 0029) are control entries in the same list, mirroring the oracle's band
|
||||
// compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage, levels
|
||||
@@ -66,6 +68,7 @@ const LEVEL_END: u32 = 0x80000005u;
|
||||
const CLIPPED: u32 = 1u;
|
||||
const ART: u32 = 2u;
|
||||
const MAX_GROUP_DEPTH: u32 = 8u;
|
||||
const HAIRLINE: u32 = 2u;
|
||||
|
||||
// Mean of clamp(u, 0, 1) for u running linearly from u0 to u1.
|
||||
fn avg_clamp(u0: f32, u1: f32) -> f32 {
|
||||
@@ -102,6 +105,22 @@ fn piece_cover(s: vec4<f32>, px: f32, py: f32) -> f32 {
|
||||
return dir * (yb - ya) * avg_clamp(px + 1.0 - xa, px + 1.0 - xb);
|
||||
}
|
||||
|
||||
// Distance from `p` to the segment `s` (x0, y0, x1, y1): hairline.rs › seg_dist, step by step.
|
||||
fn seg_dist(p: vec2<f32>, s: vec4<f32>) -> f32 {
|
||||
let dx = s.z - s.x;
|
||||
let dy = s.w - s.y;
|
||||
let qx = p.x - s.x;
|
||||
let qy = p.y - s.y;
|
||||
let l = dx * dx + dy * dy;
|
||||
var t = 0.0;
|
||||
if l > 0.0 {
|
||||
t = clamp((qx * dx + qy * dy) / l, 0.0, 1.0);
|
||||
}
|
||||
let ex = qx - dx * t;
|
||||
let ey = qy - dy * t;
|
||||
return sqrt(ex * ex + ey * ey);
|
||||
}
|
||||
|
||||
fn fold(w: f32, rule: u32) -> f32 {
|
||||
if rule == 0u {
|
||||
return min(abs(w), 1.0);
|
||||
@@ -160,14 +179,17 @@ fn rem_euclid(u: f32, n: f32) -> f32 {
|
||||
return select(r, r + n, r < 0.0);
|
||||
}
|
||||
|
||||
// The oracle's bilinear sample of a bitmap at pixel centre `p` (paint.rs › sample).
|
||||
// The oracle's sample of a bitmap at pixel centre `p` (paint.rs › sample): bilinear, or the
|
||||
// pixel `p` falls in when the bitmap doesn't allow smoothing (flag bit 1).
|
||||
fn bitmap(base: u32, p: vec2<f32>) -> vec4<f32> {
|
||||
let h0 = paints[base];
|
||||
let m = paints[base + 1u];
|
||||
let n = paints[base + 2u];
|
||||
let tint = paints[base + 3u];
|
||||
let slot = bitcast<u32>(h0.x);
|
||||
let repeat = bitcast<u32>(h0.y) != 0u;
|
||||
let flags = bitcast<u32>(h0.y);
|
||||
let repeat = (flags & 1u) != 0u;
|
||||
let nearest = (flags & 2u) != 0u;
|
||||
let size = vec2<i32>(i32(bitcast<u32>(h0.z)), i32(bitcast<u32>(h0.w)));
|
||||
let w = f32(size.x);
|
||||
let h = f32(size.y);
|
||||
@@ -182,6 +204,9 @@ fn bitmap(base: u32, p: vec2<f32>) -> vec4<f32> {
|
||||
} else if u < 0.0 || v < 0.0 || u >= w || v >= h {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
if nearest {
|
||||
return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, n, tint);
|
||||
}
|
||||
let fx_ = u - 0.5;
|
||||
let fy_ = v - 0.5;
|
||||
let x0 = floor(fx_);
|
||||
@@ -357,16 +382,31 @@ fn pixel(wg: vec3<u32>, lid: vec3<u32>) -> vec4<f32> {
|
||||
}
|
||||
let first = index[e + 1u];
|
||||
let pieces = index[e + 2u];
|
||||
let bd = index[e + 3u];
|
||||
var w = 0.0;
|
||||
if bd != NONE {
|
||||
w = geo[bd + (lid.y >> 2u)][lid.y & 3u];
|
||||
}
|
||||
for (var k = 0u; k < pieces; k++) {
|
||||
w += piece_cover(geo[first + k], px, py);
|
||||
}
|
||||
let h = params.at.y + op * 4u;
|
||||
var cov = fold(w, index[h + 1u]);
|
||||
let rule = index[h + 1u];
|
||||
var cov = 0.0;
|
||||
if rule == HAIRLINE {
|
||||
var d = 2.0;
|
||||
let pc = vec2<f32>(px + 0.5, py + 0.5);
|
||||
for (var k = 0u; k < pieces; k++) {
|
||||
let sg = geo[first + k];
|
||||
// Out of reach of the segment's box: at least 1 away, so it can't be nearest
|
||||
// within reach (the coverage comes out the same, without the division).
|
||||
let lo = min(sg.xy, sg.zw) - vec2<f32>(1.0);
|
||||
let hi = max(sg.xy, sg.zw) + vec2<f32>(1.0);
|
||||
if any(pc < lo) || any(pc > hi) {
|
||||
continue;
|
||||
}
|
||||
d = min(d, seg_dist(pc, sg));
|
||||
}
|
||||
cov = clamp(1.0 - d, 0.0, 1.0);
|
||||
} else {
|
||||
var w = f32(bitcast<i32>(index[e + 3u]));
|
||||
for (var k = 0u; k < pieces; k++) {
|
||||
w += piece_cover(geo[first + k], px, py);
|
||||
}
|
||||
cov = fold(w, rule);
|
||||
}
|
||||
let flags = index[h + 3u];
|
||||
if (flags & ART) != 0u {
|
||||
let k = clamp(cov, 0.0, 1.0);
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
//! Tile binning on the GPU (ADR 0048): the host half.
|
||||
//!
|
||||
//! [`crate::binning`] is the reference: it splits every fill's edges into tile pieces on the
|
||||
//! CPU. Here the CPU only lays out what the GPU needs, in time proportional to the fills and
|
||||
//! their points, and `bin.wgsl` does the splitting, the backdrops and the tile lists:
|
||||
//!
|
||||
//! * the fills' points and polygons, one flat buffer, with each fill's tile range;
|
||||
//! * one GPU invocation per row of tiles of each fill (an *op-row*), and room for each tile
|
||||
//! of each fill's bounds (an *op-tile*): its piece count, backdrop, place and cursor;
|
||||
//! * per tile row, the fills overlapping it in drawing order, and per tile where its entries
|
||||
//! go: room for every fill whose bounds cover it (the GPU keeps those with pieces or a
|
||||
//! backdrop there, in order);
|
||||
//! * an upper bound of the pieces, from each edge's rows and columns, so every buffer is sized
|
||||
//! before the GPU runs and nothing is read back.
|
||||
//!
|
||||
//! The passes count, scan (prefix sum), scatter and list; their output is the same tile lists
|
||||
//! as the CPU's, bit for bit in everything but rounding (a test compares them per pixel).
|
||||
|
||||
use crate::binning::{HAIRLINE_MARGIN, Range, TILE, hairline_tiles};
|
||||
use anicraft_render::Fill;
|
||||
use rayon::prelude::*;
|
||||
|
||||
/// An op that is a hairline (`bin.wgsl` › `HAIRLINE_BIT`).
|
||||
const HAIRLINE_BIT: u32 = 1 << 31;
|
||||
/// `u32`s per op in the input (`bin.wgsl` › `Op`).
|
||||
const OP_WORDS: usize = 8;
|
||||
/// Values one scan workgroup handles (`scan.wgsl`).
|
||||
const SCAN_BLOCK: u32 = 1024;
|
||||
|
||||
/// When and how far the GPU bins.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
/// The largest buffer the device binds (bytes).
|
||||
pub binding: u64,
|
||||
/// Fewer edges than this bin on the CPU, where it takes less than setting up the passes.
|
||||
pub min_edges: u64,
|
||||
}
|
||||
|
||||
/// Most edge visits the GPU's per-row passes may make (each row of a fill walks all its
|
||||
/// edges): far above real scenes (the 50k-shape 4K stress frame makes about 6 M), it keeps a
|
||||
/// fill with very many edges over very many rows on the CPU, which splits each edge once.
|
||||
pub const MAX_VISITS: u64 = 1 << 26;
|
||||
|
||||
/// What the GPU needs to bin a scene, laid out by the CPU.
|
||||
pub struct Plan {
|
||||
/// The ops, polygons, points, op-row owners (and each op's first op-row), the rows' fills
|
||||
/// and the rows' starts, at [`Plan::at`].
|
||||
pub(crate) input: Vec<u32>,
|
||||
pub(crate) at: [u32; 6],
|
||||
pub(crate) op_rows: u32,
|
||||
/// Tiles of the fills' bounds: the entries' room and the working values' length.
|
||||
pub op_tiles: u32,
|
||||
/// Room for pieces: an upper bound.
|
||||
pub piece_cap: u32,
|
||||
/// `[start, 0]` per tile.
|
||||
pub(crate) headers: Vec<u32>,
|
||||
/// Edges, and edge visits by the per-row passes.
|
||||
pub edges: u64,
|
||||
pub visits: u64,
|
||||
}
|
||||
|
||||
/// What one fill needs: its range and how much room.
|
||||
struct Info {
|
||||
range: Option<Range>,
|
||||
polys: u32,
|
||||
points: u32,
|
||||
edges: u64,
|
||||
pieces: u64,
|
||||
}
|
||||
|
||||
fn info(f: &Fill, tiles_x: u32, tiles_y: u32) -> Info {
|
||||
let Some(r) = Range::of(f, tiles_x, tiles_y) else { return Info { range: None, polys: 0, points: 0, edges: 0, pieces: 0 } };
|
||||
let mut pieces = 0u64;
|
||||
let mut edges = 0u64;
|
||||
for poly in &f.polys {
|
||||
if f.hairline {
|
||||
let mut seg = |a, b| {
|
||||
pieces += hairline_pieces(a, b, &r);
|
||||
edges += 1;
|
||||
};
|
||||
match poly.as_slice() {
|
||||
[] => {}
|
||||
[p] => seg(*p, *p),
|
||||
_ => poly.windows(2).for_each(|w| seg(w[0], w[1])),
|
||||
}
|
||||
} else {
|
||||
let n = poly.len();
|
||||
if n < 2 {
|
||||
continue;
|
||||
}
|
||||
for i in 0..n {
|
||||
if let (Some(&a), Some(&b)) = (poly.get(i), poly.get((i + 1) % n)) {
|
||||
pieces += edge_pieces(a, b, &r);
|
||||
}
|
||||
}
|
||||
edges += n as u64;
|
||||
}
|
||||
}
|
||||
let points = f.polys.iter().map(Vec::len).sum::<usize>() as u32;
|
||||
Info { range: Some(r), polys: f.polys.len() as u32, points, edges, pieces }
|
||||
}
|
||||
|
||||
/// At most how many tiles a hairline segment reaches (`binning.rs` › `hairline_tiles`), with a
|
||||
/// pixel more reach than the binning's, whatever the GPU's rounding: the tiles of its padded
|
||||
/// box (most segments are short), or row by row for a long one, where the box would be loose.
|
||||
fn hairline_pieces(a: anicraft_geom::Vec2, b: anicraft_geom::Vec2, r: &Range) -> u64 {
|
||||
if !(a.is_finite() && b.is_finite()) {
|
||||
return 0;
|
||||
}
|
||||
let (t, m) = (TILE as f32, HAIRLINE_MARGIN + 1.0);
|
||||
let span = |lo: f32, hi: f32, base: f32, n: i32| (((hi + m - base) / t).floor().min((n - 1) as f32) - ((lo - m - base) / t).floor().max(0.0) + 1.0).max(0.0);
|
||||
let rows = span(a.y.min(b.y), a.y.max(b.y), r.ylo, r.nrows);
|
||||
let cols = span(a.x.min(b.x), a.x.max(b.x), r.xlo, r.ncols);
|
||||
if rows * cols <= 16.0 {
|
||||
return (rows * cols) as u64;
|
||||
}
|
||||
let mut n = 0u64;
|
||||
hairline_tiles(a, b, r, m, |_, _| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
/// At most how many pieces edge `a → b` gives (`binning.rs` › `split_edge` and `steps`): one
|
||||
/// per tile row it spans, one more per column boundary it crosses, a left-edge step per column
|
||||
/// boundary it passes, and one for where it meets the next edge; with slack for rounding.
|
||||
fn edge_pieces(a: anicraft_geom::Vec2, b: anicraft_geom::Vec2, r: &Range) -> u64 {
|
||||
if !(a.is_finite() && b.is_finite()) {
|
||||
return 0;
|
||||
}
|
||||
let t = TILE as f32;
|
||||
let (y0, y1) = (a.y.min(b.y).max(r.ylo), a.y.max(b.y).min(r.yhi));
|
||||
if y1 < y0 {
|
||||
return 0;
|
||||
}
|
||||
let rows = ((y1 - r.ylo) / t).floor() - ((y0 - r.ylo) / t).floor() + 1.0;
|
||||
let (x0, x1) = (a.x.min(b.x).max(r.xlo), a.x.max(b.x).min(r.xhi));
|
||||
let cols = if x1 >= x0 { ((x1 - r.xlo) / t).floor() - ((x0 - r.xlo) / t).floor() + 1.0 } else { 1.0 };
|
||||
(rows.clamp(0.0, r.nrows as f32 + 1.0) + 2.0 * cols.clamp(0.0, r.ncols as f32 + 1.0)) as u64 + 3
|
||||
}
|
||||
|
||||
/// The plan for binning `fills` (the scene's, in drawing order) on a `tiles_x × tiles_y`
|
||||
/// surface; `None` when the CPU should: too few edges to be worth it, too many visits, or a
|
||||
/// buffer larger than the device binds.
|
||||
pub fn plan(fills: &[Fill], tiles_x: u32, tiles_y: u32, lim: &Limits) -> Option<Plan> {
|
||||
let infos: Vec<Info> = fills.par_iter().map(|f| info(f, tiles_x, tiles_y)).collect();
|
||||
let n = fills.len();
|
||||
let (mut polys, mut points, mut op_tiles, mut op_rows, mut pieces, mut edges, mut visits) = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64);
|
||||
for i in &infos {
|
||||
polys += u64::from(i.polys);
|
||||
points += u64::from(i.points);
|
||||
pieces += i.pieces;
|
||||
edges += i.edges;
|
||||
if let Some(r) = &i.range {
|
||||
op_tiles += (r.ncols as u64) * (r.nrows as u64);
|
||||
op_rows += r.nrows as u64;
|
||||
visits += (r.nrows as u64) * i.edges;
|
||||
}
|
||||
}
|
||||
let tiles = u64::from(tiles_x) * u64::from(tiles_y);
|
||||
let words = OP_WORDS as u64 * n as u64 + 2 * polys + 2 * points + op_rows + n as u64 + op_rows + u64::from(tiles_y) + 1;
|
||||
let work_words = 4 * op_tiles + 2 * op_tiles.div_ceil(u64::from(SCAN_BLOCK)) + 64;
|
||||
let fits = |bytes: u64| bytes <= lim.binding;
|
||||
if edges < lim.min_edges || visits > MAX_VISITS || pieces >= u64::from(u32::MAX) || op_tiles >= u64::from(u32::MAX) / 4 {
|
||||
return None;
|
||||
}
|
||||
if !(fits(4 * words) && fits(4 * work_words) && fits(16 * pieces) && fits(4 * (2 * tiles + 4 * op_tiles + 4 * n as u64))) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Where everything goes.
|
||||
let at_ops = 0usize;
|
||||
let at_polys = at_ops + OP_WORDS * n;
|
||||
let at_points = at_polys + 2 * polys as usize;
|
||||
let at_row_of = at_points + 2 * points as usize;
|
||||
let at_row_ops = at_row_of + op_rows as usize + n;
|
||||
let at_row_start = at_row_ops + op_rows as usize;
|
||||
let mut input = vec![0u32; at_row_start + tiles_y as usize + 1];
|
||||
|
||||
// Per op: its first polygon, point, op-tile and op-row.
|
||||
let mut firsts = Vec::with_capacity(n);
|
||||
let (mut p0, mut q0, mut t0, mut r0) = (0u32, 0u32, 0u32, 0u32);
|
||||
for i in &infos {
|
||||
firsts.push((p0, q0, t0, r0));
|
||||
p0 += i.polys;
|
||||
q0 += i.points;
|
||||
if let Some(r) = &i.range {
|
||||
t0 += (r.ncols * r.nrows) as u32;
|
||||
r0 += r.nrows as u32;
|
||||
}
|
||||
}
|
||||
{
|
||||
let (head, rest) = input.split_at_mut(at_polys);
|
||||
let (poly_words, rest) = rest.split_at_mut(at_points - at_polys);
|
||||
let (point_words, rest) = rest.split_at_mut(at_row_of - at_points);
|
||||
let (row_of, rest) = rest.split_at_mut(op_rows as usize);
|
||||
let (row_base, rest) = rest.split_at_mut(n);
|
||||
let (row_ops, row_start) = rest.split_at_mut(op_rows as usize);
|
||||
// Each op's slices of the polygon and point tables, then filled in parallel.
|
||||
let mut jobs: Vec<Job> = Vec::with_capacity(n);
|
||||
let (mut pw, mut qw) = (poly_words, point_words);
|
||||
for ((h, f), (i, first)) in head.chunks_mut(OP_WORDS).zip(fills).zip(infos.iter().zip(&firsts)) {
|
||||
let (a, b) = std::mem::take(&mut pw).split_at_mut(2 * i.polys as usize);
|
||||
let (c, d) = std::mem::take(&mut qw).split_at_mut(2 * i.points as usize);
|
||||
pw = b;
|
||||
qw = d;
|
||||
jobs.push((h, a, c, f, i, *first));
|
||||
}
|
||||
jobs.into_par_iter().for_each(|(h, pw, qw, f, i, (p0, q0, t0, _))| {
|
||||
let (tx0, ty0, ncols, nrows) = i.range.map_or((0, 0, 0, 0), |r| (r.tx0, r.ty0, r.ncols as u32, r.nrows as u32));
|
||||
let flags = if f.hairline { HAIRLINE_BIT } else { 0 };
|
||||
h.copy_from_slice(&[p0, i.polys, tx0, ty0, ncols, nrows, t0, flags]);
|
||||
let mut q = q0;
|
||||
for (slot, poly) in pw.as_chunks_mut::<2>().0.iter_mut().zip(&f.polys) {
|
||||
slot.copy_from_slice(&[q, poly.len() as u32]);
|
||||
q += poly.len() as u32;
|
||||
}
|
||||
for (slot, p) in qw.as_chunks_mut::<2>().0.iter_mut().zip(f.polys.iter().flatten()) {
|
||||
slot.copy_from_slice(&[p.x.to_bits(), p.y.to_bits()]);
|
||||
}
|
||||
});
|
||||
// Op-rows in op order: who owns each, and each op's first.
|
||||
let mut k = 0usize;
|
||||
for (op, (i, first)) in infos.iter().zip(&firsts).enumerate() {
|
||||
if let Some(b) = row_base.get_mut(op) {
|
||||
*b = first.3;
|
||||
}
|
||||
for _ in 0..i.range.map_or(0, |r| r.nrows) {
|
||||
if let Some(o) = row_of.get_mut(k) {
|
||||
*o = op as u32;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
// Each tile row's fills, in drawing order (a counting sort by row).
|
||||
for i in &infos {
|
||||
if let Some(r) = &i.range {
|
||||
for row in r.ty0..r.ty0 + r.nrows as u32 {
|
||||
if let Some(c) = row_start.get_mut(row as usize + 1) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for j in 1..row_start.len() {
|
||||
row_start[j] += row_start[j - 1];
|
||||
}
|
||||
let mut cursor: Vec<u32> = row_start.to_vec();
|
||||
for (op, i) in infos.iter().enumerate() {
|
||||
if let Some(r) = &i.range {
|
||||
for row in r.ty0..r.ty0 + r.nrows as u32 {
|
||||
if let Some(c) = cursor.get_mut(row as usize)
|
||||
&& let Some(slot) = row_ops.get_mut(*c as usize)
|
||||
{
|
||||
*slot = op as u32;
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Where each tile's entries go: room for every fill whose bounds cover it (a 2D running
|
||||
// sum over the bounds' corners).
|
||||
let (w, h) = (tiles_x as usize + 1, tiles_y as usize + 1);
|
||||
let mut cover = vec![0i64; w * h];
|
||||
for r in infos.iter().filter_map(|i| i.range) {
|
||||
let (x0, y0, x1, y1) = (r.tx0 as usize, r.ty0 as usize, r.tx0 as usize + r.ncols as usize, r.ty0 as usize + r.nrows as usize);
|
||||
for (x, y, d) in [(x0, y0, 1), (x1, y0, -1), (x0, y1, -1), (x1, y1, 1)] {
|
||||
if let Some(c) = cover.get_mut(y * w + x) {
|
||||
*c += d;
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let left = if x > 0 { cover[y * w + x - 1] } else { 0 };
|
||||
let up = if y > 0 { cover[(y - 1) * w + x] } else { 0 };
|
||||
let diag = if x > 0 && y > 0 { cover[(y - 1) * w + x - 1] } else { 0 };
|
||||
cover[y * w + x] += left + up - diag;
|
||||
}
|
||||
}
|
||||
let mut headers = vec![0u32; 2 * tiles as usize];
|
||||
let mut start = 0u64;
|
||||
for ty in 0..tiles_y as usize {
|
||||
for tx in 0..tiles_x as usize {
|
||||
if let Some(hd) = headers.get_mut(2 * (ty * tiles_x as usize + tx)) {
|
||||
*hd = start as u32;
|
||||
}
|
||||
start += cover.get(ty * w + tx).copied().unwrap_or(0).max(0) as u64;
|
||||
}
|
||||
}
|
||||
if start != op_tiles {
|
||||
return None; // the room per tile must add up to the op-tiles (it always does)
|
||||
}
|
||||
let at = [at_ops, at_polys, at_points, at_row_of, at_row_ops, at_row_start].map(|a| a as u32);
|
||||
Some(Plan { input, at, op_rows: op_rows as u32, op_tiles: op_tiles as u32, piece_cap: pieces as u32, headers, edges, visits })
|
||||
}
|
||||
|
||||
/// One op's share of the input to fill in: its record, polygon and point words, the fill, its
|
||||
/// sizes, and its first polygon, point, op-tile and op-row.
|
||||
type Job<'a> = (&'a mut [u32], &'a mut [u32], &'a mut [u32], &'a Fill, &'a Info, (u32, u32, u32, u32));
|
||||
|
||||
/// The binning pipelines (`bin.wgsl`, `scan.wgsl`).
|
||||
pub(crate) struct Pipelines {
|
||||
count: wgpu::ComputePipeline,
|
||||
scatter: wgpu::ComputePipeline,
|
||||
tiles: wgpu::ComputePipeline,
|
||||
layout: wgpu::BindGroupLayout,
|
||||
scan_blocks: wgpu::ComputePipeline,
|
||||
scan_add: wgpu::ComputePipeline,
|
||||
scan_layout: wgpu::BindGroupLayout,
|
||||
}
|
||||
|
||||
impl Pipelines {
|
||||
pub(crate) fn new(device: &wgpu::Device) -> Pipelines {
|
||||
let entry = |binding: u32, ty: wgpu::BufferBindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, count: None };
|
||||
let rw = wgpu::BufferBindingType::Storage { read_only: false };
|
||||
let bin_entries = [entry(0, wgpu::BufferBindingType::Uniform), entry(1, wgpu::BufferBindingType::Storage { read_only: true }), entry(2, rw), entry(3, rw), entry(4, rw)];
|
||||
let ([count, scatter, tiles], layout) = pipelines(device, "anicraft-bin", include_str!("bin.wgsl"), &bin_entries, ["count", "scatter", "tiles"]);
|
||||
let ([scan_blocks, scan_add], scan_layout) = pipelines(device, "anicraft-scan", include_str!("scan.wgsl"), &[entry(0, wgpu::BufferBindingType::Uniform), entry(1, rw)], ["scan_blocks", "scan_add"]);
|
||||
Pipelines { count, scatter, tiles, layout, scan_blocks, scan_add, scan_layout }
|
||||
}
|
||||
}
|
||||
|
||||
/// One shader's entry points as pipelines sharing one bind group layout.
|
||||
fn pipelines<const N: usize>(device: &wgpu::Device, label: &str, src: &str, entries: &[wgpu::BindGroupLayoutEntry], points: [&str; N]) -> ([wgpu::ComputePipeline; N], wgpu::BindGroupLayout) {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(src.into()) });
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries });
|
||||
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: &[Some(&layout)], immediate_size: 0 });
|
||||
let pipes = points.map(|p| device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(p), layout: Some(&pl), module: &module, entry_point: Some(p), compilation_options: Default::default(), cache: None }));
|
||||
(pipes, layout)
|
||||
}
|
||||
|
||||
/// Workgroups for `n` invocations of `width`, spread over x and y (at most 65,535 each way).
|
||||
fn groups(n: u32, width: u32) -> (u32, u32) {
|
||||
let g = n.div_ceil(width).max(1);
|
||||
let x = g.min(65_535);
|
||||
(x, g.div_ceil(x))
|
||||
}
|
||||
|
||||
/// The fine pass's index and pieces, binned on the GPU into `enc` from `plan`: the index with
|
||||
/// the tile headers at 0 and `op_heads` at `ops_at`. Only those are uploaded (through `queue`,
|
||||
/// ahead of `enc`'s submission): the entries' room starts zeroed on the GPU.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn record(device: &wgpu::Device, queue: &wgpu::Queue, pipes: &Pipelines, enc: &mut wgpu::CommandEncoder, plan: &Plan, tiles_x: u32, tiles_y: u32, entries_at: u32, ops_at: u32, op_heads: &[u32]) -> Result<(wgpu::Buffer, wgpu::Buffer), String> {
|
||||
use wgpu::util::DeviceExt;
|
||||
let index_len = (ops_at as usize + op_heads.len()).max(4);
|
||||
let index = device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * index_len as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
if !plan.headers.is_empty() && plan.headers.len() <= index_len {
|
||||
queue.write_buffer(&index, 0, bytemuck::cast_slice(&plan.headers));
|
||||
}
|
||||
if !op_heads.is_empty() && ops_at as usize + op_heads.len() <= index_len {
|
||||
queue.write_buffer(&index, 4 * u64::from(ops_at), bytemuck::cast_slice(op_heads));
|
||||
}
|
||||
let geo = device.create_buffer(&wgpu::BufferDescriptor { label: Some("geo"), size: 16 * u64::from(plan.piece_cap.max(1)), usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
|
||||
if plan.op_rows == 0 {
|
||||
return Ok((index, geo));
|
||||
}
|
||||
let n = plan.op_tiles;
|
||||
// Counts, backdrops, offsets, cursors, then the scan's totals level by level. New buffers
|
||||
// start zeroed.
|
||||
let mut levels: Vec<[u32; 4]> = Vec::new();
|
||||
let (mut src, mut dst, mut len, mut sums) = (0u32, 2 * n, n, 4 * n);
|
||||
loop {
|
||||
let blocks = len.div_ceil(SCAN_BLOCK);
|
||||
levels.push([src, dst, sums, len]);
|
||||
if blocks <= 1 {
|
||||
break;
|
||||
}
|
||||
(src, dst, len) = (sums, sums, blocks);
|
||||
sums += blocks;
|
||||
}
|
||||
let work_len = (sums + 2) as u64;
|
||||
let work = device.create_buffer(&wgpu::BufferDescriptor { label: Some("bin-work"), size: 4 * work_len, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });
|
||||
let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("bin-input"), contents: bytemuck::cast_slice(&plan.input), usage: wgpu::BufferUsages::STORAGE });
|
||||
let tiles = tiles_x * tiles_y;
|
||||
let a = plan.at;
|
||||
let params: [u32; 16] = [tiles_x, tiles_y, plan.op_rows, tiles, n, plan.piece_cap, entries_at, 0, a[0], a[1], a[2], a[3], a[4], a[5], 0, 0];
|
||||
let ubuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("bin-params"), contents: bytemuck::cast_slice(¶ms), usage: wgpu::BufferUsages::UNIFORM });
|
||||
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("anicraft-bin"),
|
||||
layout: &pipes.layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: work.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 3, resource: geo.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 4, resource: index.as_entire_binding() },
|
||||
],
|
||||
});
|
||||
let scans: Vec<(wgpu::BindGroup, u32)> = levels
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let u = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("scan-params"), contents: bytemuck::cast_slice(l), usage: wgpu::BufferUsages::UNIFORM });
|
||||
let b = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("anicraft-scan"),
|
||||
layout: &pipes.scan_layout,
|
||||
entries: &[wgpu::BindGroupEntry { binding: 0, resource: u.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: work.as_entire_binding() }],
|
||||
});
|
||||
(b, l[3].div_ceil(SCAN_BLOCK))
|
||||
})
|
||||
.collect();
|
||||
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("anicraft-bin"), timestamp_writes: None });
|
||||
let rows = groups(plan.op_rows, 64);
|
||||
pass.set_pipeline(&pipes.count);
|
||||
pass.set_bind_group(0, &bind, &[]);
|
||||
pass.dispatch_workgroups(rows.0, rows.1, 1);
|
||||
// The scan, level by level up, then each level's totals added back down.
|
||||
pass.set_pipeline(&pipes.scan_blocks);
|
||||
for (b, blocks) in &scans {
|
||||
let g = groups(*blocks, 1);
|
||||
pass.set_bind_group(0, b, &[]);
|
||||
pass.dispatch_workgroups(g.0, g.1, 1);
|
||||
}
|
||||
pass.set_pipeline(&pipes.scan_add);
|
||||
for (b, blocks) in scans.iter().rev().skip(1) {
|
||||
let g = groups(*blocks, 1);
|
||||
pass.set_bind_group(0, b, &[]);
|
||||
pass.dispatch_workgroups(g.0, g.1, 1);
|
||||
}
|
||||
pass.set_pipeline(&pipes.scatter);
|
||||
pass.set_bind_group(0, &bind, &[]);
|
||||
pass.dispatch_workgroups(rows.0, rows.1, 1);
|
||||
let t = groups(tiles, 64);
|
||||
pass.set_pipeline(&pipes.tiles);
|
||||
pass.dispatch_workgroups(t.0, t.1, 1);
|
||||
drop(pass);
|
||||
Ok((index, geo))
|
||||
}
|
||||
+199
-33
@@ -2,10 +2,11 @@
|
||||
//!
|
||||
//! Draws the same scene as the CPU oracle (`anicraft-render`) with wgpu compute: the oracle
|
||||
//! prepares it ([`anicraft_render::prepare_scene`]: flattening, strokes, paints and their
|
||||
//! gradient tables, clips and groups), [`binning`] sorts the edges into 16 × 16 tiles on the
|
||||
//! CPU, and one compute pass computes every pixel's exact area coverage and composites the
|
||||
//! fills in order, inside their masks and groups (alpha and blend modes) as the oracle's band
|
||||
//! compositor does. Bitmap fills are sampled from textures uploaded once per image
|
||||
//! gradient tables, clips and groups), the edges are sorted into 16 × 16 tiles, on the GPU
|
||||
//! ([`gpu_binning`], ADR 0048) or on the CPU ([`binning`], the reference, and the way for fills
|
||||
//! in masks and groups), and one compute pass computes every pixel's exact area coverage
|
||||
//! (or a hairline's distance) and composites the fills in order, inside their masks and groups
|
||||
//! (alpha and blend modes) as the oracle's band compositor does. Bitmap fills are sampled from textures uploaded once per image
|
||||
//! ([`images`]); a filtered symbol is drawn into a layer of its own, filtered by compute passes
|
||||
//! that run the oracle's filter steps ([`layers`]), and composited like any fill (ADR 0032).
|
||||
//! The output is the oracle's within float rounding (the parity tests check mean and maximum
|
||||
@@ -22,6 +23,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod binning;
|
||||
pub mod gpu_binning;
|
||||
pub mod images;
|
||||
mod layers;
|
||||
|
||||
@@ -29,6 +31,7 @@ use anicraft_doc::DisplayList;
|
||||
use anicraft_render::{MAX_PIXELS, NeedsFull, Pixmap, RenderStats, View, paint::premultiply, prepare_scene};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use rayon::prelude::*;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use web_time::Instant;
|
||||
use wgpu::util::DeviceExt;
|
||||
@@ -68,11 +71,58 @@ pub struct GpuFrame {
|
||||
pub pixmap: Option<Pixmap>,
|
||||
pub stats: RenderStats,
|
||||
pub timings: Timings,
|
||||
/// Tile entries and edge pieces the fine pass walked.
|
||||
/// Tile entries and edge pieces the fine pass walked (when binned on the GPU, the room
|
||||
/// made for them: upper bounds).
|
||||
pub entries: usize,
|
||||
pub pieces: usize,
|
||||
/// Whether the GPU binned the frame's tiles ([`Binning`]).
|
||||
pub gpu_binned: bool,
|
||||
}
|
||||
|
||||
/// Where a frame's edges are sorted into tiles (ADR 0048).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Binning {
|
||||
/// On the GPU when the scene can take it (no fill inside a mask or a group, for now), has
|
||||
/// enough edges to be worth the passes ([`AUTO_MIN_EDGES`]) and the device runs Vulkan
|
||||
/// (where it was measured to win); otherwise on the CPU.
|
||||
Auto,
|
||||
/// Always on the CPU (the reference).
|
||||
Cpu,
|
||||
/// On the GPU whenever the scene can take it, however small (tests and benchmarks).
|
||||
Gpu,
|
||||
}
|
||||
|
||||
impl Binning {
|
||||
fn code(self) -> u8 {
|
||||
match self {
|
||||
Binning::Auto => 0,
|
||||
Binning::Cpu => 1,
|
||||
Binning::Gpu => 2,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_code(c: u8) -> Binning {
|
||||
match c {
|
||||
1 => Binning::Cpu,
|
||||
2 => Binning::Gpu,
|
||||
_ => Binning::Auto,
|
||||
}
|
||||
}
|
||||
|
||||
/// `ANICRAFT_GPU_BINNING=cpu|gpu|auto` (for comparing them in the app); auto otherwise.
|
||||
fn from_env() -> Binning {
|
||||
match std::env::var("ANICRAFT_GPU_BINNING").map(|v| v.trim().to_ascii_lowercase()).as_deref() {
|
||||
Ok("cpu") => Binning::Cpu,
|
||||
Ok("gpu") => Binning::Gpu,
|
||||
_ => Binning::Auto,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fewer edges than this are binned on the CPU in [`Binning::Auto`]: below it the CPU bins a
|
||||
/// frame in less time than the GPU's passes take to set up (measured, docs/performance.md).
|
||||
pub const AUTO_MIN_EDGES: u64 = 32_768;
|
||||
|
||||
/// A frame rendered into a texture on the renderer's device: premultiplied RGBA8
|
||||
/// (`Rgba8Unorm`, the bytes [`Pixmap::to_premul_rgba8`] gives), sampleable, ready for the window
|
||||
/// to show (egui's `register_native_texture`). The work is submitted, not waited for: anything
|
||||
@@ -86,6 +136,7 @@ pub struct GpuTexture {
|
||||
pub timings: Timings,
|
||||
pub entries: usize,
|
||||
pub pieces: usize,
|
||||
pub gpu_binned: bool,
|
||||
}
|
||||
|
||||
/// Where a frame's time went (milliseconds, on the calling thread).
|
||||
@@ -93,7 +144,8 @@ pub struct GpuTexture {
|
||||
pub struct Timings {
|
||||
/// Cull, flatten, stroke and paint set-up (shared with the oracle, parallel).
|
||||
pub prepare: f32,
|
||||
/// Tile binning (parallel per fill and per tile row) and buffer packing.
|
||||
/// Tile binning on the CPU (parallel per fill and per tile row), or laying out the GPU's
|
||||
/// binning (per fill), and buffer packing.
|
||||
pub bin: f32,
|
||||
/// Upload and submit; for read-back frames also the wait for the GPU and the copy back.
|
||||
pub gpu: f32,
|
||||
@@ -131,6 +183,16 @@ pub struct GpuRenderer {
|
||||
texture_pipeline: wgpu::ComputePipeline,
|
||||
texture_layout: wgpu::BindGroupLayout,
|
||||
filters: layers::FilterPipelines,
|
||||
bins: gpu_binning::Pipelines,
|
||||
/// [`Binning`], as its code.
|
||||
binning: AtomicU8,
|
||||
/// Why the GPU doesn't bin on this device (its self-test came back wrong); then every
|
||||
/// frame bins on the CPU, and the rest of the GPU stage still runs.
|
||||
no_gpu_binning: Mutex<Option<String>>,
|
||||
/// Whether [`Binning::Auto`] bins on the GPU on this backend: on Vulkan, where it was
|
||||
/// measured to win in the stage's tiles. On Direct3D 12 the passes cost more per stage tile
|
||||
/// than the CPU's binning (ADR 0048), and other backends aren't measured yet.
|
||||
auto_bins: bool,
|
||||
/// Bound where a texture slot or a buffer is unused.
|
||||
blank: wgpu::TextureView,
|
||||
/// Placeholders for a filter pass's coverage (written) and ramp (read): one buffer can't be
|
||||
@@ -247,7 +309,7 @@ impl GpuRenderer {
|
||||
}
|
||||
let limits = device.limits();
|
||||
check(adapter, &limits, &name)?;
|
||||
Self::build(device, queue, limits, name, true, Arc::new(Mutex::new(None)))
|
||||
Self::build(device, queue, limits, name, info.backend, true, Arc::new(Mutex::new(None)))
|
||||
}))
|
||||
.unwrap_or_else(|_| Err(GpuError::Unavailable("the GPU driver failed while starting".into())))
|
||||
}
|
||||
@@ -285,10 +347,10 @@ impl GpuRenderer {
|
||||
g.get_or_insert_with(|| format!("device lost: {msg}"));
|
||||
});
|
||||
}
|
||||
Self::build(device, queue, want, name, false, broken)
|
||||
Self::build(device, queue, want, name, info.backend, false, broken)
|
||||
}
|
||||
|
||||
fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, shared: bool, broken: Arc<Mutex<Option<String>>>) -> Result<GpuRenderer, GpuError> {
|
||||
fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, backend: wgpu::Backend, shared: bool, broken: Arc<Mutex<Option<String>>>) -> Result<GpuRenderer, GpuError> {
|
||||
let scopes = Scopes::push(&device);
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("anicraft-fine"), source: wgpu::ShaderSource::Wgsl(include_str!("fine.wgsl").into()) });
|
||||
let entry = |binding: u32, ty: wgpu::BindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None };
|
||||
@@ -316,6 +378,7 @@ impl GpuRenderer {
|
||||
let storage_texture = wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: wgpu::TextureFormat::Rgba8Unorm, view_dimension: wgpu::TextureViewDimension::D2 };
|
||||
let (texture_pipeline, texture_layout) = make("anicraft-fine-texture", entry(5, storage_texture), "main_texture");
|
||||
let filters = layers::FilterPipelines::new(&device);
|
||||
let bins = gpu_binning::Pipelines::new(&device);
|
||||
let blank = device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("anicraft-blank"),
|
||||
@@ -341,6 +404,10 @@ impl GpuRenderer {
|
||||
texture_pipeline,
|
||||
texture_layout,
|
||||
filters,
|
||||
bins,
|
||||
binning: AtomicU8::new(Binning::from_env().code()),
|
||||
no_gpu_binning: Mutex::new(None),
|
||||
auto_bins: backend == wgpu::Backend::Vulkan,
|
||||
blank,
|
||||
blank_coverage,
|
||||
blank_ramp,
|
||||
@@ -376,6 +443,7 @@ impl GpuRenderer {
|
||||
guide: false,
|
||||
group: None,
|
||||
image: None,
|
||||
smooth: true,
|
||||
};
|
||||
let solid = |x: f32, c: Rgba| item(Path::rect(x, 2.0, 8.0, 16.0), Paint::Solid(c));
|
||||
let mut bitmap = item(Path::rect(2.0, 18.0, 20.0, 2.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::scale(3.0, 1.0) });
|
||||
@@ -400,9 +468,38 @@ impl GpuRenderer {
|
||||
let off = d.map_or("a wrong size".to_string(), |d| format!("{} of {} pixels off, by up to {}/255{at}", d.differing, d.pixels, d.max));
|
||||
Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong {how} ({off})", self.adapter)))
|
||||
};
|
||||
check("read back", &self.render(&dl, &view, Output::Premul8)?.premul8)?;
|
||||
let t = self.render_texture(&dl, &view)?;
|
||||
check("through a texture", &self.read_texture(&t)?)
|
||||
check("read back", &self.render_with(&dl, &view, Output::Premul8, Binning::Cpu)?.premul8)?;
|
||||
let t = self.render_texture_with(&dl, &view, Binning::Cpu)?;
|
||||
check("through a texture", &self.read_texture(&t)?)?;
|
||||
// Binned on the GPU (the plain fills; the bitmap and the symbol bin on the CPU): if that
|
||||
// comes back wrong, only the binning stays on the CPU here.
|
||||
let plain = DisplayList { items: dl.items.iter().take(3).cloned().collect(), ..Default::default() };
|
||||
let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?;
|
||||
let why = match self.render_with(&plain, &view, Output::Premul8, Binning::Gpu) {
|
||||
Ok(got) => match compare_premul8(&got.premul8, &want.to_premul_rgba8()) {
|
||||
Some(d) if got.gpu_binned && d.max <= 2 && d.mean <= 0.1 => None,
|
||||
Some(d) if got.gpu_binned => Some(format!("{} of {} pixels off, by up to {}/255", d.differing, d.pixels, d.max)),
|
||||
_ => Some("it wasn't binned on the GPU".to_string()),
|
||||
},
|
||||
Err(GpuError::Device(e)) => return Err(GpuError::Unavailable(format!("{}: the GPU binning failed: {e}", self.adapter))),
|
||||
Err(e) => Some(e.to_string()),
|
||||
};
|
||||
*self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner) = why.map(|w| format!("{}: the self-test came back wrong binned on the GPU ({w}); binning on the CPU", self.adapter));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Why the GPU doesn't bin on this device, if it doesn't (for Preferences and reports).
|
||||
pub fn gpu_binning_off(&self) -> Option<String> {
|
||||
self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner).clone()
|
||||
}
|
||||
|
||||
/// Where frames' edges are sorted into tiles from now on.
|
||||
pub fn set_binning(&self, b: Binning) {
|
||||
self.binning.store(b.code(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn binning(&self) -> Binning {
|
||||
Binning::from_code(self.binning.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// Whether the device has failed (lost, or an error in or outside a render); then use the
|
||||
@@ -423,19 +520,29 @@ impl GpuRenderer {
|
||||
/// Renders a display list and reads it back. [`GpuError::NeedsFull`] means "draw this one
|
||||
/// on the CPU".
|
||||
pub fn render(&self, dl: &DisplayList, view: &View, output: Output) -> Result<GpuFrame, GpuError> {
|
||||
self.render_with(dl, view, output, self.binning())
|
||||
}
|
||||
|
||||
/// [`GpuRenderer::render`], binned as `binning` says (tests and benchmarks).
|
||||
pub fn render_with(&self, dl: &DisplayList, view: &View, output: Output, binning: Binning) -> Result<GpuFrame, GpuError> {
|
||||
self.guard(|| {
|
||||
let (job, stats, mut timings, cost) = self.prepare(dl, view)?;
|
||||
let (job, stats, mut timings, cost) = self.prepare(dl, view, binning)?;
|
||||
let t = Instant::now();
|
||||
let (premul8, pixmap) = self.run_readback(&job, view, output)?;
|
||||
timings.gpu = ms(t);
|
||||
Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: cost.entries, pieces: cost.pieces })
|
||||
Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() })
|
||||
})
|
||||
}
|
||||
|
||||
/// Renders a display list into a new texture on this renderer's device (no readback).
|
||||
pub fn render_texture(&self, dl: &DisplayList, view: &View) -> Result<GpuTexture, GpuError> {
|
||||
self.render_texture_with(dl, view, self.binning())
|
||||
}
|
||||
|
||||
/// [`GpuRenderer::render_texture`], binned as `binning` says (tests and benchmarks).
|
||||
pub fn render_texture_with(&self, dl: &DisplayList, view: &View, binning: Binning) -> Result<GpuTexture, GpuError> {
|
||||
self.guard(|| {
|
||||
let (job, stats, mut timings, cost) = self.prepare(dl, view)?;
|
||||
let (job, stats, mut timings, cost) = self.prepare(dl, view, binning)?;
|
||||
let t = Instant::now();
|
||||
let (w, h) = (view.width, view.height);
|
||||
let max = self.limits.max_texture_dimension_2d;
|
||||
@@ -464,7 +571,7 @@ impl GpuRenderer {
|
||||
self.queue.submit([enc.finish()]);
|
||||
self.pop(scopes)?;
|
||||
timings.gpu = ms(t);
|
||||
Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces })
|
||||
Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -511,14 +618,14 @@ impl GpuRenderer {
|
||||
|
||||
/// The oracle's preparation and the binning, for the scene and each filtered layer it shows
|
||||
/// (in parallel); checked against the limits and the device's.
|
||||
fn prepare(&self, dl: &DisplayList, view: &View) -> Result<(Job, RenderStats, Timings, Cost), GpuError> {
|
||||
fn prepare(&self, dl: &DisplayList, view: &View, binning: Binning) -> Result<(Job, RenderStats, Timings, Cost), GpuError> {
|
||||
let (w, h) = (view.width, view.height);
|
||||
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
|
||||
return Err(GpuError::TooLarge(format!("image {w}×{h} is outside the GPU stage's range")));
|
||||
}
|
||||
let t0 = Instant::now();
|
||||
let mut bin_ms = 0.0;
|
||||
let (job, stats) = self.plan(dl, view, 0, &mut bin_ms)?;
|
||||
let (job, stats) = self.plan(dl, view, 0, binning, &mut bin_ms)?;
|
||||
let total = ms(t0);
|
||||
let mut cost = Cost::default();
|
||||
job.cost(&mut cost);
|
||||
@@ -533,10 +640,18 @@ impl GpuRenderer {
|
||||
}
|
||||
|
||||
/// One scene: prepared and binned, then its shown layers planned the same way.
|
||||
fn plan(&self, dl: &DisplayList, view: &View, depth: usize, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> {
|
||||
fn plan(&self, dl: &DisplayList, view: &View, depth: usize, binning: Binning, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> {
|
||||
let (mut scene, stats) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?;
|
||||
let t = Instant::now();
|
||||
let binned = binning::bin(&scene, view.width, view.height).map_err(GpuError::NeedsFull)?;
|
||||
let off = self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner).is_some();
|
||||
let lim = match binning {
|
||||
_ if off => None,
|
||||
Binning::Cpu => None,
|
||||
Binning::Auto if !self.auto_bins => None,
|
||||
Binning::Auto => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: AUTO_MIN_EDGES }),
|
||||
Binning::Gpu => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }),
|
||||
};
|
||||
let binned = binning::bin_with(&scene, view.width, view.height, lim.as_ref()).map_err(GpuError::NeedsFull)?;
|
||||
*bin_ms += ms(t);
|
||||
let shown: Vec<(u32, anicraft_render::FilterLayer)> = std::mem::take(&mut scene.layers).into_iter().zip(&binned.layer_at).filter_map(|(l, at)| Some(((*at)?, l))).collect();
|
||||
// Free the prepared polygons on the pool, off this frame's path (as the oracle does).
|
||||
@@ -553,7 +668,7 @@ impl GpuRenderer {
|
||||
let shown = shown.into_iter();
|
||||
let planned: Vec<Result<LayerJob, GpuError>> = shown
|
||||
.map(|(at, l)| {
|
||||
let (job, _) = self.plan(&l.list, &l.view, depth + 1, &mut 0.0)?;
|
||||
let (job, _) = self.plan(&l.list, &l.view, depth + 1, binning, &mut 0.0)?;
|
||||
Ok(LayerJob { at, job: Box::new(job), view: l.view, ops: l.filters })
|
||||
})
|
||||
.collect();
|
||||
@@ -561,11 +676,17 @@ impl GpuRenderer {
|
||||
Ok((Job { binned, layers }, stats))
|
||||
}
|
||||
|
||||
/// The largest buffer the device binds.
|
||||
fn binding_cap(&self) -> u64 {
|
||||
self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size)
|
||||
}
|
||||
|
||||
/// Every buffer a job binds fits what the device binds.
|
||||
fn check_sizes(&self, job: &Job) -> Result<(), GpuError> {
|
||||
let cap = self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size);
|
||||
let cap = self.binding_cap();
|
||||
let b = &job.binned;
|
||||
let sizes = [("tile lists", b.index.len() as u64 * 4), ("edges", b.geo.len() as u64 * 16), ("paints and layers", b.paints_len as u64 * 16)];
|
||||
let pieces = b.gpu.as_ref().map_or(b.geo.len() as u64, |p| u64::from(p.piece_cap));
|
||||
let sizes = [("tile lists", (u64::from(b.ops_at) + b.op_heads.len() as u64) * 4), ("edges", pieces * 16), ("paints and layers", b.paints_len as u64 * 16)];
|
||||
for (what, n) in sizes {
|
||||
if n > cap {
|
||||
return Err(GpuError::TooLarge(format!("{what} need {} MB, more than this GPU binds ({} MB)", n >> 20, cap >> 20)));
|
||||
@@ -613,13 +734,34 @@ impl GpuRenderer {
|
||||
enc.copy_buffer_to_buffer(&img, 0, &pbuf, u64::from(l.at) * 16, 16 * n);
|
||||
}
|
||||
let views = self.images.lock().unwrap_or_else(PoisonError::into_inner).views(&self.device, &self.queue, self.limits.max_texture_dimension_2d, &b.images)?;
|
||||
self.fine_pass(enc, b, &pbuf, &views, view, output, target);
|
||||
let (ibuf, gbuf) = match &b.gpu {
|
||||
Some(plan) => gpu_binning::record(&self.device, &self.queue, &self.bins, enc, plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?,
|
||||
None => self.upload_lists(b)?,
|
||||
};
|
||||
self.fine_pass(enc, b, &ibuf, &gbuf, &pbuf, &views, view, output, target);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The CPU's tile lists and op headers, and its pieces, as buffers.
|
||||
fn upload_lists(&self, b: &binning::Binned) -> Result<(wgpu::Buffer, wgpu::Buffer), GpuError> {
|
||||
let len = (b.ops_at as usize + b.op_heads.len()).max(4);
|
||||
let ibuf = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * len as u64, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: true });
|
||||
{
|
||||
let mut m = ibuf.slice(..).get_mapped_range_mut().map_err(|e| GpuError::Device(e.to_string()))?;
|
||||
write_words(&mut m, 0, &b.index);
|
||||
write_words(&mut m, b.ops_at as usize, &b.op_heads);
|
||||
}
|
||||
ibuf.unmap();
|
||||
// Bindings can't be empty: pad to one vec4.
|
||||
let pad = [[0f32; 4]];
|
||||
let geo: &[[f32; 4]] = if b.geo.is_empty() { &pad } else { &b.geo };
|
||||
let gbuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("geo"), contents: bytemuck::cast_slice(geo), usage: wgpu::BufferUsages::STORAGE });
|
||||
Ok((ibuf, gbuf))
|
||||
}
|
||||
|
||||
/// Uploads the binned scene and records the fine pass into `target`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn fine_pass(&self, enc: &mut wgpu::CommandEncoder, b: &binning::Binned, pbuf: &wgpu::Buffer, images: &[wgpu::TextureView], view: &View, output: Output, target: Target) {
|
||||
fn fine_pass(&self, enc: &mut wgpu::CommandEncoder, b: &binning::Binned, ibuf: &wgpu::Buffer, gbuf: &wgpu::Buffer, pbuf: &wgpu::Buffer, images: &[wgpu::TextureView], view: &View, output: Output, target: Target) {
|
||||
let bg = view.background.map_or([0.0; 4], premultiply);
|
||||
let mut uniform = [0u32; 12];
|
||||
uniform[..4].copy_from_slice(&[view.width, view.height, b.tiles_x, u32::from(output == Output::Float)]);
|
||||
@@ -627,15 +769,7 @@ impl GpuRenderer {
|
||||
for (u, f) in uniform[8..].iter_mut().zip(bg) {
|
||||
*u = f.to_bits();
|
||||
}
|
||||
let storage = |label: &str, bytes: &[u8]| {
|
||||
// Bindings can't be empty: pad to one vec4.
|
||||
let pad = [0u8; 16];
|
||||
let contents = if bytes.is_empty() { &pad[..] } else { bytes };
|
||||
self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage: wgpu::BufferUsages::STORAGE })
|
||||
};
|
||||
let ubuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("params"), contents: bytemuck::cast_slice(&uniform), usage: wgpu::BufferUsages::UNIFORM });
|
||||
let ibuf = storage("index", bytemuck::cast_slice(&b.index));
|
||||
let gbuf = storage("geo", bytemuck::cast_slice(&b.geo));
|
||||
let mut entries = vec![
|
||||
wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: ibuf.as_entire_binding() },
|
||||
@@ -695,6 +829,30 @@ impl GpuRenderer {
|
||||
})
|
||||
}
|
||||
|
||||
/// The tile lists the GPU bins for `dl` (forced, however small), read back as a
|
||||
/// [`binning::Binned`] like the CPU's: `None` when the scene isn't one the GPU bins.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn gpu_lists(&self, dl: &DisplayList, view: &View) -> Result<Option<binning::Binned>, GpuError> {
|
||||
let (scene, _) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?;
|
||||
let lim = gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 };
|
||||
let mut b = binning::bin_with(&scene, view.width, view.height, Some(&lim)).map_err(GpuError::NeedsFull)?;
|
||||
let Some(plan) = b.gpu.take() else { return Ok(None) };
|
||||
let scopes = Scopes::push(&self.device);
|
||||
let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-bin-test") });
|
||||
let (ibuf, gbuf) = gpu_binning::record(&self.device, &self.queue, &self.bins, &mut enc, &plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?;
|
||||
let (isize, gsize) = (ibuf.size(), gbuf.size());
|
||||
let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: isize + gsize, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
enc.copy_buffer_to_buffer(&ibuf, 0, &read, 0, isize);
|
||||
enc.copy_buffer_to_buffer(&gbuf, 0, &read, isize, gsize);
|
||||
self.queue.submit([enc.finish()]);
|
||||
let bytes = self.map(&read, scopes)?;
|
||||
let words: Vec<u32> = bytes.as_chunks::<4>().0.iter().map(|w| u32::from_le_bytes(*w)).collect();
|
||||
let n = isize as usize / 4;
|
||||
b.index = words.get(..b.ops_at as usize).unwrap_or(&[]).to_vec();
|
||||
b.geo = words.get(n..).unwrap_or(&[]).as_chunks::<4>().0.iter().map(|v| v.map(f32::from_bits)).collect();
|
||||
Ok(Some(b))
|
||||
}
|
||||
|
||||
/// Waits for `read`'s copy, pops the error scopes and returns its bytes.
|
||||
fn map(&self, read: &wgpu::Buffer, scopes: Scopes) -> Result<Vec<u8>, GpuError> {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
@@ -766,6 +924,14 @@ pub(crate) fn describe(e: &wgpu::Error) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `words` at word `at` of a mapped buffer, if they fit.
|
||||
pub(crate) fn write_words(m: &mut wgpu::BufferViewMut, at: usize, words: &[u32]) {
|
||||
let (a, b) = (4 * at, 4 * (at + words.len()));
|
||||
if !words.is_empty() && b <= m.len() {
|
||||
m.slice(a..b).copy_from_slice(bytemuck::cast_slice(words));
|
||||
}
|
||||
}
|
||||
|
||||
fn ms(t: Instant) -> f32 {
|
||||
t.elapsed().as_secs_f32() * 1000.0
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// AniCraft GPU stage: the prefix sum for the GPU binning (ADR 0048, bin.wgsl).
|
||||
//
|
||||
// An exclusive scan of `n` values in `values` (the binning's working buffer): each workgroup
|
||||
// scans 1024 of them (four per invocation, then the invocations' totals in workgroup memory)
|
||||
// and leaves its total; the totals are scanned the same way, level by level, and added back.
|
||||
// The public work-efficient scan (Blelloch's "Prefix sums and their applications", 1990), in
|
||||
// its simplest form.
|
||||
|
||||
// `src`, `dst` and the workgroups' totals (`sums`) in `work`, and how many values.
|
||||
struct ScanParams {
|
||||
src: u32,
|
||||
dst: u32,
|
||||
sums: u32,
|
||||
n: u32,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> sp: ScanParams;
|
||||
@group(0) @binding(1) var<storage, read_write> values: array<u32>;
|
||||
|
||||
var<workgroup> sh: array<u32, 256>;
|
||||
|
||||
fn load(i: u32) -> u32 {
|
||||
if i < sp.n {
|
||||
return values[sp.src + i];
|
||||
}
|
||||
return 0u;
|
||||
}
|
||||
|
||||
fn store(i: u32, v: u32) {
|
||||
if i < sp.n {
|
||||
values[sp.dst + i] = v;
|
||||
}
|
||||
}
|
||||
|
||||
// Each workgroup scans 1024 values (four per invocation), exclusive, and leaves its total.
|
||||
@compute @workgroup_size(256)
|
||||
fn scan_blocks(@builtin(workgroup_id) wg: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
|
||||
let block = wg.y * nw.x + wg.x;
|
||||
let base = block * 1024u + lid.x * 4u;
|
||||
// Four values by name, not a loop over an array: FXC (Direct3D's compiler) must unroll
|
||||
// loops that index local arrays.
|
||||
let v0 = load(base);
|
||||
let v1 = load(base + 1u);
|
||||
let v2 = load(base + 2u);
|
||||
let v3 = load(base + 3u);
|
||||
let total = v0 + v1 + v2 + v3;
|
||||
sh[lid.x] = total;
|
||||
workgroupBarrier();
|
||||
for (var off = 1u; off < 256u; off <<= 1u) {
|
||||
var t = 0u;
|
||||
if lid.x >= off {
|
||||
t = sh[lid.x - off];
|
||||
}
|
||||
workgroupBarrier();
|
||||
sh[lid.x] += t;
|
||||
workgroupBarrier();
|
||||
}
|
||||
let acc = sh[lid.x] - total;
|
||||
store(base, acc);
|
||||
store(base + 1u, acc + v0);
|
||||
store(base + 2u, acc + v0 + v1);
|
||||
store(base + 3u, acc + v0 + v1 + v2);
|
||||
// (A dispatch spread over x and y may have a few workgroups past the end.)
|
||||
if lid.x == 255u && block * 1024u < sp.n {
|
||||
values[sp.sums + block] = sh[255];
|
||||
}
|
||||
}
|
||||
|
||||
// Adds each workgroup's scanned total to its values.
|
||||
@compute @workgroup_size(256)
|
||||
fn scan_add(@builtin(workgroup_id) wg: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
|
||||
let block = wg.y * nw.x + wg.x;
|
||||
if block * 1024u >= sp.n {
|
||||
return;
|
||||
}
|
||||
let add = values[sp.sums + block];
|
||||
for (var i = 0u; i < 4u; i++) {
|
||||
let at = block * 1024u + lid.x * 4u + i;
|
||||
if at < sp.n {
|
||||
values[sp.dst + at] += add;
|
||||
}
|
||||
}
|
||||
}
|
||||
+176
-10
@@ -31,6 +31,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem {
|
||||
guide: false,
|
||||
group: None,
|
||||
image: None,
|
||||
smooth: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,10 +127,40 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red));
|
||||
huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 };
|
||||
out.push(("off-surface", list(vec![huge]), view(100, 80, Some(Rgba::WHITE))));
|
||||
out.push(("outlines", outlined(), view(150, 110, Some(Rgba::WHITE))));
|
||||
out.extend(composited_scenes());
|
||||
out
|
||||
}
|
||||
|
||||
/// Outline mode (ADR 0048): hairlines along closed and open paths, crossing tiles in every
|
||||
/// direction, overlapping, faded, past the surface, over a fill, and a point.
|
||||
fn outlined() -> DisplayList {
|
||||
let outline = |path: Path, c: Rgba, t: Affine| {
|
||||
let mut i = item(path, Paint::Solid(Rgba::BLACK));
|
||||
i.outline = Some(c);
|
||||
i.transform = t;
|
||||
i
|
||||
};
|
||||
let blue = Rgba::hex(0x4f8dff).with_alpha(0.5);
|
||||
let green = Rgba::hex(0x4cd07d).with_alpha(0.8);
|
||||
let mut wave = Path::default();
|
||||
wave.move_to(Vec2::new(-20.0, 90.0));
|
||||
for k in 0..12 {
|
||||
wave.line_to(Vec2::new(k as f32 * 15.3, 90.0 + if k % 2 == 0 { 9.7 } else { -7.1 }));
|
||||
}
|
||||
list(vec![
|
||||
item(Path::rect(20.0, 20.0, 50.0, 40.0), Paint::Solid(Rgba::new(0.9, 0.8, 0.2, 1.0))),
|
||||
outline(Path::ellipse(50.0, 45.0, 37.3, 29.1), blue, Affine::IDENTITY),
|
||||
outline(Path::star(95.0, 50.0, 40.0, 16.0, 5), green, Affine::rotate(0.05)),
|
||||
outline(Path::star(95.0, 50.0, 40.0, 16.0, 5), green, Affine::translate(0.25, 0.5)),
|
||||
outline(Path::rect(16.0, 32.0, 112.0, 0.0), Rgba::BLACK, Affine::IDENTITY),
|
||||
outline(Path::rect(8.5, 4.25, 133.0, 100.0), Rgba::new(0.8, 0.1, 0.1, 1.0), Affine::IDENTITY),
|
||||
outline(wave, Rgba::new(0.2, 0.2, 0.2, 0.9), Affine::IDENTITY),
|
||||
outline(Path::ellipse(140.0, 100.0, 60.0, 50.0), blue, Affine::IDENTITY),
|
||||
outline(Path::line(Vec2::new(60.5, 70.5), Vec2::new(60.5, 70.5)), Rgba::BLACK, Affine::IDENTITY),
|
||||
])
|
||||
}
|
||||
|
||||
/// Masks and groups (ADR 0029): each stresses one part of the oracle's band compositor.
|
||||
fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let red = Rgba::new(0.9, 0.1, 0.1, 1.0);
|
||||
@@ -264,14 +295,9 @@ fn emulate(b: &Binned, v: &View) -> Vec<Premul> {
|
||||
}
|
||||
k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"),
|
||||
}
|
||||
let mut wnd = if bd == binning::NONE { 0.0 } else { b.geo[bd as usize + ly / 4][ly % 4] };
|
||||
for k in 0..n {
|
||||
let s = b.geo[first + k];
|
||||
wnd += piece_cover(s, lx as f32, ly as f32);
|
||||
}
|
||||
let hd = b.ops_at as usize + op * 4;
|
||||
let mut cov = if b.index[hd + 1] == 0 { wnd.abs().min(1.0) } else { let t = wnd.abs() % 2.0; if t > 1.0 { 2.0 - t } else { t } };
|
||||
let flags = b.index[hd + 3];
|
||||
let hd = op * 4;
|
||||
let mut cov = entry_cover(&b.geo[first..first + n], bd, b.op_heads[hd + 1], lx, ly);
|
||||
let flags = b.op_heads[hd + 3];
|
||||
if flags & bn::ART != 0 {
|
||||
let k = cov.clamp(0.0, 1.0);
|
||||
level = level + k - level * k;
|
||||
@@ -283,7 +309,7 @@ fn emulate(b: &Binned, v: &View) -> Vec<Premul> {
|
||||
if cov <= 1e-4 {
|
||||
continue;
|
||||
}
|
||||
let s = match b.index[hd] {
|
||||
let s = match b.op_heads[hd] {
|
||||
0 => solid_of(b, op),
|
||||
kind => {
|
||||
let base = op * PAINT_VEC4S;
|
||||
@@ -293,7 +319,7 @@ fn emulate(b: &Binned, v: &View) -> Vec<Premul> {
|
||||
let d = q - Vec2::new(nn[2], nn[3]);
|
||||
let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { d.length() * g[2] };
|
||||
let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255;
|
||||
b.paints[b.index[hd + 2] as usize + i]
|
||||
b.paints[b.op_heads[hd + 2] as usize + i]
|
||||
}
|
||||
};
|
||||
let sa = s[3] * cov;
|
||||
@@ -308,6 +334,26 @@ fn emulate(b: &Binned, v: &View) -> Vec<Premul> {
|
||||
out
|
||||
}
|
||||
|
||||
/// An entry's coverage of pixel `(lx, ly)` of its tile, as `fine.wgsl` computes it: the
|
||||
/// backdrop and its pieces under fill rule `rule`, or a hairline's distance.
|
||||
fn entry_cover(pieces: &[[f32; 4]], backdrop: u32, rule: u32, lx: usize, ly: usize) -> f32 {
|
||||
if rule == bn::HAIRLINE {
|
||||
let p = Vec2::new(lx as f32 + 0.5, ly as f32 + 0.5);
|
||||
let d = pieces.iter().fold(2.0f32, |d, s| d.min(anicraft_render::hairline::seg_dist(p, Vec2::new(s[0], s[1]), Vec2::new(s[2], s[3]))));
|
||||
return (1.0 - d).clamp(0.0, 1.0);
|
||||
}
|
||||
let mut wnd = backdrop as i32 as f32;
|
||||
for s in pieces {
|
||||
wnd += piece_cover(*s, lx as f32, ly as f32);
|
||||
}
|
||||
if rule == 0 {
|
||||
wnd.abs().min(1.0)
|
||||
} else {
|
||||
let t = wnd.abs() % 2.0;
|
||||
if t > 1.0 { 2.0 - t } else { t }
|
||||
}
|
||||
}
|
||||
|
||||
/// `fine.wgsl` › `close_group` and `blend`, on the CPU (the oracle's formulas, written again
|
||||
/// from the shader's numbering).
|
||||
fn close_group(s: Premul, below: Premul, alpha: f32, m: u32) -> Premul {
|
||||
@@ -443,6 +489,22 @@ fn binned_coverage_matches_the_oracle_on_the_cpu() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Thousands of overlapping shapes at awkward scales: edges meet tile corners and boundaries
|
||||
/// within float rounding, where the backdrops and the left-edge steps must agree (ADR 0048).
|
||||
#[test]
|
||||
fn binned_coverage_matches_the_oracle_on_stress_frames() {
|
||||
let doc = sample::stress(20, 100, 48);
|
||||
for (f, s, at) in [(0u32, 1.0f32, (0.0, 0.0)), (30, 0.5, (0.0, 0.0)), (7, 2.3, (-900.0, -700.0)), (41, 0.73, (-11.5, -3.25))] {
|
||||
let dl = anicraft_doc::evaluate(&doc, f);
|
||||
let v = View { transform: Affine::translate(at.0, at.1).mul(&Affine::scale(s, s)), width: 1920, height: 1080, background: Some(Rgba::WHITE) };
|
||||
let (scene, _) = prepare_scene(&dl, &v).unwrap();
|
||||
let b = binning::bin(&scene, v.width, v.height).unwrap();
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
let (mean, max) = f32_diff(&emulate(&b, &v), &oracle.data);
|
||||
assert!(mean < 1e-4 && max < 4e-3, "frame {f} at {s}: mean {mean:e}, max {max:e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_composited_sample_really_has_masks_and_groups() {
|
||||
let comp = composited_sample();
|
||||
@@ -549,6 +611,7 @@ fn degenerate_geometry_bins_without_trouble() {
|
||||
clip,
|
||||
group,
|
||||
layer: None,
|
||||
hairline: false,
|
||||
};
|
||||
// A fill naming a layer that isn't there draws nothing.
|
||||
let mut lost = fill(None, None);
|
||||
@@ -734,6 +797,12 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0);
|
||||
let dl = DisplayList { items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] };
|
||||
out.push(("bitmap masked and multiplied", dl, view(80, 60, white)));
|
||||
// Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated.
|
||||
let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned);
|
||||
hard.smooth = false;
|
||||
let mut hard_tiled = bitmap_item(Path::ellipse(50.0, 40.0, 45.0, 35.0), &c, true, Affine::scale(4.0, 3.0));
|
||||
hard_tiled.smooth = false;
|
||||
out.push(("bitmaps without smoothing", list(vec![hard_tiled, hard]), view(100, 80, white)));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -914,3 +983,100 @@ fn gpu_matches_the_oracle_on_the_filtered_sample() {
|
||||
assert_parity(g, "filtered sample tile", &dl, &tile);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ----- binning on the GPU (ADR 0048) ----------------------------------------------------------
|
||||
|
||||
/// Scenes the GPU bins (no fill in a mask or a group): the analytic ones, the sample, stress
|
||||
/// frames at awkward scales and offsets, and onion-skin style outlines over them.
|
||||
fn gpu_binned_scenes() -> Vec<(String, DisplayList, View)> {
|
||||
let plain = |dl: &DisplayList| dl.items.iter().all(|i| i.clip.is_none() && i.group.is_none());
|
||||
let mut out: Vec<(String, DisplayList, View)> = scenes().into_iter().filter(|(_, dl, _)| plain(dl)).map(|(n, dl, v)| (n.to_string(), dl, v)).collect();
|
||||
let demo = sample::demo();
|
||||
out.push(("sample".into(), anicraft_doc::evaluate(&demo, 13), View::stage(&demo, 0.37)));
|
||||
let doc = sample::stress(20, 100, 48);
|
||||
for (f, s, at) in [(0u32, 1.0f32, (0.0, 0.0)), (30, 0.5, (0.0, 0.0)), (7, 2.3, (-900.0, -700.0)), (41, 0.73, (-11.5, -3.25))] {
|
||||
let dl = anicraft_doc::evaluate(&doc, f);
|
||||
let v = View { transform: Affine::translate(at.0, at.1).mul(&Affine::scale(s, s)), width: 1920, height: 1080, background: Some(Rgba::WHITE) };
|
||||
out.push((format!("stress frame {f} at {s}"), dl, v));
|
||||
}
|
||||
// Onion skin's outlines: the frames before and after as hairlines, under the playhead's.
|
||||
let mut dl = DisplayList::default();
|
||||
for f in [25u32, 27, 33, 35] {
|
||||
let mut part = anicraft_doc::evaluate(&doc, f);
|
||||
for i in &mut part.items {
|
||||
i.outline = Some(Rgba::hex(if f < 30 { 0x4f8dff } else { 0x4cd07d }).with_alpha(0.4));
|
||||
}
|
||||
dl.append(part);
|
||||
}
|
||||
dl.append(anicraft_doc::evaluate(&doc, 30));
|
||||
out.push(("stress with outlined frames".into(), dl, View::stage(&doc, 0.8)));
|
||||
out
|
||||
}
|
||||
|
||||
/// What an entry covers in each of its tile's 256 pixels.
|
||||
fn entry_pixels(b: &Binned, e: usize) -> [f32; 256] {
|
||||
let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]);
|
||||
let rule = b.op_heads[4 * op + 1];
|
||||
let pieces = b.geo.get(first..first + n).unwrap_or(&[]);
|
||||
std::array::from_fn(|i| entry_cover(pieces, bd, rule, i % 16, i / 16))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_binning_produces_the_cpus_tile_lists() {
|
||||
let Some(g) = gpu() else { return };
|
||||
for (name, dl, v) in gpu_binned_scenes() {
|
||||
let Some(gb) = g.gpu_lists(&dl, &v).unwrap() else { panic!("{name}: the GPU should bin this") };
|
||||
let (scene, _) = prepare_scene(&dl, &v).unwrap();
|
||||
let cb = binning::bin(&scene, v.width, v.height).unwrap();
|
||||
assert_eq!((gb.tiles_x, gb.tiles_y, &gb.op_heads), (cb.tiles_x, cb.tiles_y, &cb.op_heads), "{name}");
|
||||
let (mut entries, mut pieces) = (0usize, 0usize);
|
||||
for t in 0..(cb.tiles_x * cb.tiles_y) as usize {
|
||||
let list = |b: &Binned| -> Vec<(u32, [f32; 256])> {
|
||||
let (s, n) = (b.index[2 * t] as usize, b.index[2 * t + 1] as usize);
|
||||
(s..s + n).map(|i| b.entries_at as usize + 4 * i).map(|e| (b.index[e], entry_pixels(b, e))).collect()
|
||||
};
|
||||
let (a, c) = (list(&gb), list(&cb));
|
||||
let ops = |l: &[(u32, [f32; 256])]| l.iter().map(|x| x.0).collect::<Vec<_>>();
|
||||
assert_eq!(ops(&a), ops(&c), "{name}: tile {t}'s fills");
|
||||
for ((op, pa), (_, pc)) in a.iter().zip(&c) {
|
||||
let worst = pa.iter().zip(pc).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
|
||||
assert!(worst < 1e-3, "{name}: tile {t}, op {op}: coverage off by {worst}");
|
||||
}
|
||||
entries += a.len();
|
||||
let (s, n) = (gb.index[2 * t] as usize, gb.index[2 * t + 1] as usize);
|
||||
pieces += (s..s + n).map(|i| gb.index[gb.entries_at as usize + 4 * i + 2] as usize).sum::<usize>();
|
||||
}
|
||||
assert_eq!(entries, cb.entries, "{name}");
|
||||
assert!(pieces <= gb.pieces && entries <= gb.entries, "{name}: within the room made for them");
|
||||
// And the fine pass's arithmetic over the GPU's lists draws the oracle's picture.
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
let eg = emulate(&gb, &v);
|
||||
let (mean, max) = f32_diff(&eg, &oracle.data);
|
||||
assert!(mean < 1e-4 && max < 4e-3, "{name}: mean {mean:e}, max {max:e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_binned_frames_match_the_oracle() {
|
||||
let Some(g) = gpu() else { return };
|
||||
// Where the GPU stage runs (lavapipe in CI included), its binning must too.
|
||||
assert_eq!(g.gpu_binning_off(), None);
|
||||
for (name, dl, v) in gpu_binned_scenes() {
|
||||
let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap();
|
||||
assert!(f.gpu_binned, "{name}");
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
let d = compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap();
|
||||
assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "{name}: {d:?}");
|
||||
let t = g.render_texture_with(&dl, &v, Binning::Gpu).unwrap();
|
||||
assert!(t.gpu_binned && g.read_texture(&t).unwrap() == f.premul8, "{name}: the texture holds the read-back bytes");
|
||||
}
|
||||
// Masks and groups stay on the CPU's binning, and still draw right.
|
||||
for (name, dl, v) in composited_scenes() {
|
||||
let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap();
|
||||
let uses = |dl: &DisplayList| dl.items.iter().any(|i| i.clip.is_some() || i.group.is_some());
|
||||
assert_eq!(f.gpu_binned, !uses(&dl), "{name}: binned on the GPU {}", f.gpu_binned);
|
||||
let (oracle, _) = render(&dl, &v).unwrap();
|
||||
assert!(compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap().max <= 2, "{name}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! Hairlines (ADR 0048): the one-pixel lines of outline mode (an outlined layer, onion skin's
|
||||
//! outlines), drawn straight from the flattened path instead of as stroke polygons.
|
||||
//!
|
||||
//! A pixel's coverage is `1 − d`, clamped to `0..=1`, where `d` is the distance from the
|
||||
//! pixel's centre to the nearest point of the line. Across a horizontal or vertical line that
|
||||
//! is exactly the area a one-pixel-wide line covers in each pixel (a line through a pixel
|
||||
//! centre covers it fully; one on a pixel boundary covers the two pixels beside it half each);
|
||||
//! in other directions it is the line seen through a one-pixel tent filter. Overlaps and joins
|
||||
//! never darken (the nearest point counts, not a sum), ends and corners are round, and each
|
||||
//! segment is one edge to bin and test, where a stroked hairline was four plus a disc at every
|
||||
//! bend. The GPU stage computes the same distance (`fine.wgsl` › `seg_dist`).
|
||||
|
||||
use crate::raster::IRect;
|
||||
use anicraft_geom::Vec2;
|
||||
|
||||
/// How far a hairline reaches from its line, in pixels: beyond this its coverage is 0.
|
||||
pub const REACH: f32 = 1.0;
|
||||
|
||||
/// Distance from `p` to the segment `a → b` (a point when they coincide). The GPU computes it
|
||||
/// with the same steps (`fine.wgsl` › `seg_dist`).
|
||||
#[inline]
|
||||
pub fn seg_dist(p: Vec2, a: Vec2, b: Vec2) -> f32 {
|
||||
let (dx, dy) = (b.x - a.x, b.y - a.y);
|
||||
let (qx, qy) = (p.x - a.x, p.y - a.y);
|
||||
let l = dx * dx + dy * dy;
|
||||
let t = if l > 0.0 { ((qx * dx + qy * dy) / l).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let (ex, ey) = (qx - dx * t, qy - dy * t);
|
||||
(ex * ex + ey * ey).sqrt()
|
||||
}
|
||||
|
||||
/// A hairline's coverage at distance `d` from it.
|
||||
#[inline]
|
||||
pub fn coverage(d: f32) -> f32 {
|
||||
(REACH - d).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Pixel bounds of hairlines along `polys`, within `surface`.
|
||||
pub fn bounds(polys: &[Vec<Vec2>], surface: IRect) -> Option<IRect> {
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
|
||||
for p in polys.iter().flatten().filter(|p| p.is_finite()) {
|
||||
x0 = x0.min(p.x);
|
||||
y0 = y0.min(p.y);
|
||||
x1 = x1.max(p.x);
|
||||
y1 = y1.max(p.y);
|
||||
}
|
||||
if !(x1 >= x0 && y1 >= y0) {
|
||||
return None;
|
||||
}
|
||||
let b = IRect {
|
||||
x0: (x0 - REACH).floor().max(surface.x0 as f32) as i32,
|
||||
y0: (y0 - REACH).floor().max(surface.y0 as f32) as i32,
|
||||
x1: (x1 + REACH).ceil().min(surface.x1 as f32) as i32,
|
||||
y1: (y1 + REACH).ceil().min(surface.y1 as f32) as i32,
|
||||
};
|
||||
(!b.is_empty()).then_some(b)
|
||||
}
|
||||
|
||||
/// Adds segment `a → b` to `acc` (coverage over `b`, row by row, `bounds.width()` per row),
|
||||
/// keeping the larger coverage in every pixel it reaches.
|
||||
pub fn add_segment(acc: &mut [f32], bounds: IRect, a: Vec2, b: Vec2) {
|
||||
if !(a.is_finite() && b.is_finite()) || bounds.is_empty() {
|
||||
return;
|
||||
}
|
||||
let w = bounds.width();
|
||||
// Pixel rows whose centres lie within reach of the segment.
|
||||
let ylo = ((a.y.min(b.y) - REACH - 0.5).floor()).max(bounds.y0 as f32);
|
||||
let yhi = ((a.y.max(b.y) + REACH + 0.5).ceil()).min(bounds.y1 as f32);
|
||||
if yhi <= ylo {
|
||||
return;
|
||||
}
|
||||
let (dx, dy) = (b.x - a.x, b.y - a.y);
|
||||
for py in ylo as i32..yhi as i32 {
|
||||
let yc = py as f32 + 0.5;
|
||||
// The part of the segment within reach of this row's centres, then the pixels within
|
||||
// reach of that part.
|
||||
let (xa, xb) = if dy.abs() < 1e-12 {
|
||||
(a.x.min(b.x), a.x.max(b.x))
|
||||
} else {
|
||||
let t0 = ((yc - REACH - a.y) / dy).clamp(0.0, 1.0);
|
||||
let t1 = ((yc + REACH - a.y) / dy).clamp(0.0, 1.0);
|
||||
let (u, v) = (a.x + dx * t0, a.x + dx * t1);
|
||||
(u.min(v), u.max(v))
|
||||
};
|
||||
let x0 = (xa - REACH - 0.5).floor().max(bounds.x0 as f32);
|
||||
let x1 = (xb + REACH + 0.5).ceil().min(bounds.x1 as f32);
|
||||
if x1 <= x0 {
|
||||
continue;
|
||||
}
|
||||
let row = (py - bounds.y0) as usize * w;
|
||||
for px in x0 as i32..x1 as i32 {
|
||||
let c = coverage(seg_dist(Vec2::new(px as f32 + 0.5, yc), a, b));
|
||||
if let Some(v) = acc.get_mut(row + (px - bounds.x0) as usize)
|
||||
&& c > *v
|
||||
{
|
||||
*v = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an open polyline (a closed one repeats its first point at the end).
|
||||
pub fn add_polyline(acc: &mut [f32], bounds: IRect, pts: &[Vec2]) {
|
||||
match pts {
|
||||
[] => {}
|
||||
[p] => add_segment(acc, bounds, *p, *p),
|
||||
_ => {
|
||||
for w in pts.windows(2) {
|
||||
add_segment(acc, bounds, w[0], w[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn draw(pts: &[Vec2], w: i32, h: i32) -> Vec<f32> {
|
||||
let b = IRect { x0: 0, y0: 0, x1: w, y1: h };
|
||||
let mut acc = vec![0.0; (w * h) as usize];
|
||||
add_polyline(&mut acc, b, pts);
|
||||
acc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axis_aligned_lines_cover_exactly_one_pixel_of_area_per_row_or_column() {
|
||||
// Through pixel centres: the row is covered fully, nothing else.
|
||||
let a = draw(&[Vec2::new(-5.0, 4.5), Vec2::new(30.0, 4.5)], 20, 10);
|
||||
for (i, v) in a.iter().enumerate() {
|
||||
let want = if i / 20 == 4 { 1.0 } else { 0.0 };
|
||||
assert!((v - want).abs() < 1e-6, "pixel {i}: {v}");
|
||||
}
|
||||
// On a pixel boundary: the two rows beside it, half each. A quarter off: 3/4 and 1/4.
|
||||
for (y, rows) in [(4.0f32, [(3usize, 0.5f32), (4, 0.5)]), (4.25, [(3, 0.25), (4, 0.75)])] {
|
||||
let a = draw(&[Vec2::new(7.5, -5.0), Vec2::new(7.5, 30.0)], 10, 20);
|
||||
assert!(a.chunks(10).all(|r| (r[7] - 1.0).abs() < 1e-6 && r[6] == 0.0), "vertical through centres");
|
||||
let a = draw(&[Vec2::new(-5.0, y), Vec2::new(30.0, y)], 20, 10);
|
||||
for (r, want) in rows {
|
||||
assert!(a[r * 20..r * 20 + 20].iter().all(|v| (v - want).abs() < 1e-6), "y {y}, row {r}");
|
||||
}
|
||||
assert!((a.iter().sum::<f32>() - 20.0).abs() < 1e-4, "one pixel of area per column");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_and_overlaps_never_darken_and_ends_are_round() {
|
||||
// A corner and the same segment twice: still at most 1 anywhere, 1 on the line.
|
||||
let a = draw(&[Vec2::new(2.5, 2.5), Vec2::new(12.5, 2.5), Vec2::new(12.5, 12.5), Vec2::new(2.5, 2.5)], 16, 16);
|
||||
assert!(a.iter().all(|v| (0.0..=1.0).contains(v)));
|
||||
assert_eq!(a[2 * 16 + 12], 1.0);
|
||||
assert_eq!(a[8 * 16 + 12], 1.0);
|
||||
// Round end: the pixel centre half a pixel past the end, diagonally, is √0.5 away.
|
||||
let a = draw(&[Vec2::new(4.0, 4.0), Vec2::new(10.0, 4.0)], 16, 10);
|
||||
assert!((a[4 * 16 + 10] - (1.0 - 0.5f32.sqrt())).abs() < 1e-6, "{}", a[4 * 16 + 10]);
|
||||
assert_eq!(a[4 * 16 + 11], 0.0, "beyond reach past the end");
|
||||
// A single point is a dot.
|
||||
let a = draw(&[Vec2::new(3.5, 3.5)], 8, 8);
|
||||
assert_eq!(a[3 * 8 + 3], 1.0);
|
||||
assert_eq!(a.iter().filter(|v| **v > 0.0).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn far_and_broken_points_stay_bounded() {
|
||||
let a = draw(&[Vec2::new(-1e9, -1e9), Vec2::new(1e9, 1e9), Vec2::new(f32::NAN, 0.0), Vec2::new(3.0, f32::INFINITY)], 32, 32);
|
||||
assert!(a.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)));
|
||||
assert!(a.iter().any(|v| *v > 0.9), "the long diagonal shows");
|
||||
assert!(bounds(&[vec![Vec2::new(f32::NAN, 1.0)]], IRect { x0: 0, y0: 0, x1: 8, y1: 8 }).is_none());
|
||||
}
|
||||
}
|
||||
@@ -354,6 +354,9 @@ impl<'a> Bake<'a> {
|
||||
self.images.push(format!("data:image/png;base64,{}", base64_encode(&b.png)));
|
||||
}
|
||||
let mut o = json!({"b": i, "rep": repeat});
|
||||
if !b.smoothing {
|
||||
o["px"] = json!(true);
|
||||
}
|
||||
if let Some(m) = matrix(m) {
|
||||
o["m"] = m;
|
||||
}
|
||||
|
||||
@@ -153,7 +153,11 @@
|
||||
g.globalAlpha = bitmap ? Math.min(Math.max(it.c[0], 0), 1) : 1;
|
||||
set(g, it.m);
|
||||
g.fillStyle = style;
|
||||
// A bitmap without Allow Smoothing keeps hard pixel edges (ADR 0050).
|
||||
const hard = bitmap && movie.paints[it.f].px === true;
|
||||
if (hard) g.imageSmoothingEnabled = false;
|
||||
g.fill(path, it.eo ? "evenodd" : "nonzero");
|
||||
if (hard) g.imageSmoothingEnabled = true;
|
||||
g.globalAlpha = 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,6 +548,15 @@ fn bitmaps_and_sounds_are_embedded_once() {
|
||||
assert_eq!(js.eval("P.start().sounds"), json!([[0, "event", 1, false, 1, 1, null]]));
|
||||
let silent = movie(&doc, &HtmlOptions { sound: false, ..Default::default() });
|
||||
assert_eq!((silent.stats.sounds, silent.json["timelines"][0].get("snd")), (0, None));
|
||||
// A bitmap without Allow Smoothing says so; the page draws it with hard pixel edges, and
|
||||
// an SVG frame marks its image pixelated (ADR 0050).
|
||||
if let Some(b) = doc.bitmaps.first_mut() {
|
||||
Arc::make_mut(b).smoothing = false;
|
||||
}
|
||||
let hard = movie(&doc, &HtmlOptions::default());
|
||||
assert_eq!(hard.json["paints"][0], json!({"b": 0, "rep": true, "m": [2, 0, 0, 2, 0, 0], "px": true}));
|
||||
let svg = crate::svg::to_svg(&anicraft_doc::evaluate(&doc, 0), &doc.stage);
|
||||
assert!(svg.contains("image-rendering=\"pixelated\""), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+45
-11
@@ -8,6 +8,7 @@ pub mod paint;
|
||||
pub mod raster;
|
||||
pub mod stroke;
|
||||
pub mod filters;
|
||||
pub mod hairline;
|
||||
pub mod html;
|
||||
pub mod lottie;
|
||||
pub mod svg;
|
||||
@@ -218,9 +219,16 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re
|
||||
open.push(OpenGroup { id: g, buf: vec![[0.0; 4]; rows.len()], dirty: NO_PIXELS });
|
||||
}
|
||||
let mask = op.clip.map(|c| band_clips.get(&clips, c, band, w, &mut cov, &mut row));
|
||||
cov.reset(b);
|
||||
for poly in &op.polys {
|
||||
cov.add_polygon(poly);
|
||||
if op.hairline {
|
||||
cov.reset_direct(b);
|
||||
for poly in &op.polys {
|
||||
cov.add_hairline(poly);
|
||||
}
|
||||
} else {
|
||||
cov.reset(b);
|
||||
for poly in &op.polys {
|
||||
cov.add_polygon(poly);
|
||||
}
|
||||
}
|
||||
match open.last_mut() {
|
||||
Some(top) => {
|
||||
@@ -294,6 +302,9 @@ pub struct Fill {
|
||||
/// [`render`] draws it: the layer's pixel at `(x, y)` is at `(x - x0, y - y0)` of its
|
||||
/// `bounds`, transparent outside.
|
||||
pub layer: Option<u32>,
|
||||
/// A hairline (outline mode, ADR 0048): `polys` are open polylines (a closed one repeats
|
||||
/// its first point), drawn by [`hairline`]'s distance coverage; `rule` doesn't apply.
|
||||
pub hairline: bool,
|
||||
}
|
||||
|
||||
/// A filtered group (a symbol instance with filters) as [`render`] draws it: its items on
|
||||
@@ -383,7 +394,7 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat
|
||||
op.bounds = op.bounds.intersect(&clips.bounds(c));
|
||||
!op.bounds.is_empty()
|
||||
});
|
||||
let fill = |op: Prepared| Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds, clip: op.clip, group: op.group, layer: op.layer };
|
||||
let fill = |op: Prepared| Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds, clip: op.clip, group: op.group, layer: op.layer, hairline: op.hairline };
|
||||
let mut fills = Vec::with_capacity(ops.len());
|
||||
for op in ops {
|
||||
stats.edges += op.polys.iter().map(Vec::len).sum::<usize>();
|
||||
@@ -465,6 +476,7 @@ impl FilterSetup {
|
||||
masks: None,
|
||||
group: Some(self.group),
|
||||
layer: None,
|
||||
hairline: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -656,6 +668,8 @@ struct Prepared {
|
||||
group: Option<u32>,
|
||||
/// A filtered layer's pixels instead of `shader` ([`Fill::layer`]; only in [`prepare_scene`]).
|
||||
layer: Option<u32>,
|
||||
/// A hairline ([`Fill::hairline`]).
|
||||
hairline: bool,
|
||||
}
|
||||
|
||||
/// The clips of a display list: their mask artwork and where each can be non-zero.
|
||||
@@ -779,12 +793,36 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
|
||||
return out;
|
||||
}
|
||||
let (clip, masks, group) = (item.clip, item.masks, item.group);
|
||||
// (Mask artwork is never outlined: it draws nothing of its own.)
|
||||
if let Some(color) = item.outline.filter(|_| !is_mask) {
|
||||
// Outline mode: a hairline in the layer colour, no fill (ADR 0048).
|
||||
let shader = Shader::Solid(premultiply(color));
|
||||
if shader.is_solid().is_some_and(|c| c[3] <= 0.0) {
|
||||
return out;
|
||||
}
|
||||
let polys: Vec<Vec<Vec2>> = lines
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let mut pts = l.points;
|
||||
if l.closed
|
||||
&& let Some(&first) = pts.first()
|
||||
{
|
||||
pts.push(first);
|
||||
}
|
||||
pts
|
||||
})
|
||||
.collect();
|
||||
if let Some(b) = hairline::bounds(&polys, surface) {
|
||||
out.push(Prepared { polys, rule: FillRule::NonZero, shader, bounds: b, clip, masks, group, layer: None, hairline: true });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
let mut push = |polys: Vec<Vec<Vec2>>, rule, shader: Shader| {
|
||||
if shader.is_solid().is_some_and(|c| c[3] <= 0.0) {
|
||||
return;
|
||||
}
|
||||
if let Some(b) = pixel_bounds(&polys, surface) {
|
||||
out.push(Prepared { polys, rule, shader, bounds: b, clip, masks, group, layer: None });
|
||||
out.push(Prepared { polys, rule, shader, bounds: b, clip, masks, group, layer: None, hairline: false });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -792,11 +830,6 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
|
||||
push(lines.iter().map(|l| l.points.clone()).collect(), item.fill_rule, Shader::Solid([1.0; 4]));
|
||||
return out;
|
||||
}
|
||||
if let Some(color) = item.outline {
|
||||
// Outline mode: hairline in the layer colour, no fill.
|
||||
push(stroke::stroke_polygons(&lines, 0.5), FillRule::NonZero, Shader::Solid(premultiply(color)));
|
||||
return out;
|
||||
}
|
||||
// The stroke is outlined from the flattened lines first, so the fill can then take them
|
||||
// without a copy; it is still drawn after the fill.
|
||||
let stroke = item.stroke.as_ref().and_then(|st| {
|
||||
@@ -808,7 +841,7 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
|
||||
});
|
||||
if let Some(fill) = &item.fill {
|
||||
let polys: Vec<Vec<Vec2>> = lines.into_iter().map(|l| l.points).collect();
|
||||
push(polys, item.fill_rule, Shader::new(fill, &m, &item.color, item.image.as_ref()));
|
||||
push(polys, item.fill_rule, Shader::new(fill, &m, &item.color, item.image.as_ref()).smoothed(item.smooth));
|
||||
}
|
||||
if let Some((polys, shader)) = stroke {
|
||||
push(polys, FillRule::NonZero, shader);
|
||||
@@ -893,6 +926,7 @@ mod tests {
|
||||
guide: false,
|
||||
group: None,
|
||||
image: None,
|
||||
smooth: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,8 +18,9 @@ pub enum Shader {
|
||||
Solid(Premul),
|
||||
Linear { inv: Affine, start: Vec2, dir: Vec2, lut: Box<[Premul; LUT]> },
|
||||
Radial { inv: Affine, center: Vec2, inv_radius: f32, lut: Box<[Premul; LUT]> },
|
||||
/// Bilinear samples of a bitmap: `inv` maps pixels back to the bitmap's own pixel grid.
|
||||
Bitmap { inv: Affine, pixels: Arc<Pixels>, repeat: bool, fx: ColorEffect },
|
||||
/// Samples of a bitmap: `inv` maps pixels back to the bitmap's own pixel grid. Bilinear
|
||||
/// when `smooth` (Allow Smoothing, ADR 0050), else the nearest pixel.
|
||||
Bitmap { inv: Affine, pixels: Arc<Pixels>, repeat: bool, fx: ColorEffect, smooth: bool },
|
||||
/// Premultiplied pixels already in surface space (a filtered group): `w` wide, its top-left
|
||||
/// at `(x0, y0)`; transparent outside.
|
||||
Image { data: Arc<Vec<Premul>>, x0: i32, y0: i32, w: usize },
|
||||
@@ -75,7 +76,7 @@ impl Shader {
|
||||
}
|
||||
(Paint::Bitmap { repeat, matrix, .. }, Some(inv)) => match (image, matrix.inverse()) {
|
||||
// Pixel → shape space → image pixels.
|
||||
(Some(px), Some(to_image)) => Shader::Bitmap { inv: to_image.mul(&inv), pixels: px.clone(), repeat: *repeat, fx: *fx },
|
||||
(Some(px), Some(to_image)) => Shader::Bitmap { inv: to_image.mul(&inv), pixels: px.clone(), repeat: *repeat, fx: *fx, smooth: true },
|
||||
// A collapsed image matrix shows nothing.
|
||||
(Some(_), None) => Shader::Solid([0.0; 4]),
|
||||
(None, _) => Shader::Solid(premultiply(fx.apply(paint.primary_color()))),
|
||||
@@ -84,6 +85,14 @@ impl Shader {
|
||||
}
|
||||
}
|
||||
|
||||
/// This shader with a bitmap's Allow Smoothing (other shaders are unchanged).
|
||||
pub fn smoothed(mut self, on: bool) -> Shader {
|
||||
if let Shader::Bitmap { smooth, .. } = &mut self {
|
||||
*smooth = on;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_solid(&self) -> Option<Premul> {
|
||||
match self {
|
||||
@@ -104,7 +113,7 @@ impl Shader {
|
||||
Shader::Solid(c) => *c,
|
||||
Shader::Linear { inv, start, dir, lut } => lookup(lut, (inv.apply(p) - *start).dot(*dir)),
|
||||
Shader::Radial { inv, center, inv_radius, lut } => lookup(lut, (inv.apply(p) - *center).length() * inv_radius),
|
||||
Shader::Bitmap { inv, pixels, repeat, fx } => sample(pixels, inv.apply(p), *repeat, fx),
|
||||
Shader::Bitmap { inv, pixels, repeat, fx, smooth } => sample(pixels, inv.apply(p), *repeat, *smooth, fx),
|
||||
Shader::Image { data, x0, y0, w } => {
|
||||
let (dx, dy) = (x - x0, y - y0);
|
||||
if dx < 0 || dy < 0 || dx as usize >= *w {
|
||||
@@ -116,9 +125,10 @@ impl Shader {
|
||||
}
|
||||
}
|
||||
|
||||
/// A bilinear sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), with the
|
||||
/// colour effect applied and premultiplied. Outside a non-repeating bitmap: transparent.
|
||||
fn sample(px: &Pixels, q: Vec2, repeat: bool, fx: &ColorEffect) -> Premul {
|
||||
/// A sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), bilinear when
|
||||
/// `smooth`, else the pixel `q` is in, with the colour effect applied and premultiplied.
|
||||
/// Outside a non-repeating bitmap: transparent.
|
||||
fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorEffect) -> Premul {
|
||||
let (w, h) = (px.width as f32, px.height as f32);
|
||||
if !(q.x.is_finite() && q.y.is_finite()) || w < 1.0 || h < 1.0 {
|
||||
return [0.0; 4];
|
||||
@@ -130,6 +140,10 @@ fn sample(px: &Pixels, q: Vec2, repeat: bool, fx: &ColorEffect) -> Premul {
|
||||
} else if u < 0.0 || v < 0.0 || u >= w || v >= h {
|
||||
return [0.0; 4];
|
||||
}
|
||||
if !smooth {
|
||||
let c = px.at(u.floor() as i64, v.floor() as i64);
|
||||
return premultiply(fx.apply(Rgba::new(c[0], c[1], c[2], c[3])));
|
||||
}
|
||||
let (fx_, fy_) = (u - 0.5, v - 0.5);
|
||||
let (x0, y0) = (fx_.floor(), fy_.floor());
|
||||
let (tx, ty) = (fx_ - x0, fy_ - y0);
|
||||
@@ -168,6 +182,24 @@ mod tests {
|
||||
assert!((s2.at(99, 0)[0] - 0.5).abs() < 0.02);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmaps_without_smoothing_keep_hard_pixel_edges() {
|
||||
// A 2×1 image, black then white, drawn 10× larger: smoothed, the middle is a ramp;
|
||||
// without smoothing, each half is one flat colour up to the edge between them.
|
||||
let px = Arc::new(Pixels { width: 2, height: 1, rgba: vec![0, 0, 0, 255, 255, 255, 255, 255] });
|
||||
let paint = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY };
|
||||
let smooth = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px));
|
||||
let hard = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px)).smoothed(false);
|
||||
assert!(smooth.at(9, 5)[0] > 0.3 && smooth.at(9, 5)[0] < 0.7, "{:?}", smooth.at(9, 5));
|
||||
assert_eq!(hard.at(9, 5), [0.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(hard.at(10, 5), [1.0, 1.0, 1.0, 1.0]);
|
||||
assert_eq!(hard.at(0, 0), [0.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(hard.at(19, 9), [1.0, 1.0, 1.0, 1.0]);
|
||||
assert_eq!(hard.at(20, 5), [0.0; 4], "outside stays transparent");
|
||||
// Solid shaders ignore it.
|
||||
assert!(Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorEffect::default(), None).smoothed(false).is_solid().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmaps_sample_bilinear_once_or_tiled() {
|
||||
// 2×1: black, white.
|
||||
|
||||
@@ -46,16 +46,19 @@ pub struct Coverage {
|
||||
pub bounds: IRect,
|
||||
stride: usize,
|
||||
acc: Vec<f32>,
|
||||
/// The buffer holds coverage itself (hairlines, ADR 0048), not area to sum along rows.
|
||||
direct: bool,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
pub fn new(bounds: IRect) -> Coverage {
|
||||
let stride = bounds.width() + 2;
|
||||
Coverage { bounds, stride, acc: vec![0.0; stride * bounds.height()] }
|
||||
Coverage { bounds, stride, acc: vec![0.0; stride * bounds.height()], direct: false }
|
||||
}
|
||||
|
||||
/// Re-targets the buffer at `bounds`, reusing its allocation (one buffer per render band).
|
||||
pub fn reset(&mut self, bounds: IRect) {
|
||||
self.direct = false;
|
||||
self.bounds = bounds;
|
||||
self.stride = bounds.width() + 2;
|
||||
self.acc.clear();
|
||||
@@ -180,6 +183,24 @@ impl Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-targets the buffer at `bounds` for hairlines ([`Coverage::add_hairline`]): it then
|
||||
/// holds each pixel's coverage, and [`Coverage::resolve_row`] reads it as it is.
|
||||
pub fn reset_direct(&mut self, bounds: IRect) {
|
||||
self.direct = true;
|
||||
self.bounds = bounds;
|
||||
self.stride = bounds.width();
|
||||
self.acc.clear();
|
||||
self.acc.resize(self.stride * bounds.height(), 0.0);
|
||||
}
|
||||
|
||||
/// Adds a hairline along an open polyline ([`crate::hairline`]); the buffer must be in
|
||||
/// direct mode ([`Coverage::reset_direct`]).
|
||||
pub fn add_hairline(&mut self, pts: &[Vec2]) {
|
||||
if self.direct {
|
||||
crate::hairline::add_polyline(&mut self.acc, self.bounds, pts);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves row `y` (relative to the bounds) into coverage values in `out` (len = width).
|
||||
pub fn resolve_row(&self, y: usize, rule: FillRule, out: &mut [f32]) {
|
||||
let start = y * self.stride;
|
||||
@@ -187,6 +208,12 @@ impl Coverage {
|
||||
out.fill(0.0);
|
||||
return;
|
||||
};
|
||||
if self.direct {
|
||||
for (o, a) in out.iter_mut().zip(row) {
|
||||
*o = *a;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut sum = 0.0f32;
|
||||
for (o, a) in out.iter_mut().zip(row) {
|
||||
sum += a;
|
||||
|
||||
@@ -28,7 +28,7 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String {
|
||||
let mut body = String::new();
|
||||
let mut grad = 0usize;
|
||||
// Each bitmap is embedded once (by its pixels), then used by every fill that shows it.
|
||||
let mut images: Vec<(usize, String)> = Vec::new();
|
||||
let mut images: Vec<(usize, bool, String)> = Vec::new();
|
||||
|
||||
// Clips, in order (a parent always precedes its children; anything else clips all).
|
||||
for (i, parent) in dl.clip_parents.iter().enumerate() {
|
||||
@@ -82,7 +82,7 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String {
|
||||
continue;
|
||||
}
|
||||
if let Some(fill) = &item.fill
|
||||
&& let Some(paint) = paint_attr(fill, &item.transform, &item.color, &mut defs, &mut grad, item.image.as_ref(), &mut images)
|
||||
&& let Some(paint) = paint_attr(fill, &item.transform, &item.color, &mut defs, &mut grad, item.image.as_ref().map(|px| (px, item.smooth)), &mut images)
|
||||
{
|
||||
let _ = write!(body, "<path d=\"{d}\"{paint}{}{clip}/>", rule_attr("fill-rule", item.fill_rule));
|
||||
}
|
||||
@@ -340,7 +340,7 @@ fn effect_svg(f: &anicraft_doc::Filter, i: usize, prims: &mut String) {
|
||||
|
||||
/// The fill attribute for `paint`, defining a gradient in `defs` when needed. `None` when the
|
||||
/// paint draws nothing.
|
||||
fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n: &mut usize, image: Option<&std::sync::Arc<anicraft_doc::Pixels>>, images: &mut Vec<(usize, String)>) -> Option<String> {
|
||||
fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n: &mut usize, image: Option<(&std::sync::Arc<anicraft_doc::Pixels>, bool)>, images: &mut Vec<(usize, bool, String)>) -> Option<String> {
|
||||
let stops = match paint {
|
||||
Paint::Solid(c) => {
|
||||
let c = fx.apply(*c).sanitized();
|
||||
@@ -351,15 +351,17 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n
|
||||
// A pattern of the bitmap at its own pixel size, placed by the shape's transform
|
||||
// and the fill's image matrix.
|
||||
// (Opacity comes across; tint has no SVG equivalent and is left out.)
|
||||
let px = image?;
|
||||
// Without Allow Smoothing (ADR 0050) the image keeps hard pixel edges.
|
||||
let (px, smooth) = image?;
|
||||
let key = std::sync::Arc::as_ptr(px) as usize;
|
||||
let img_id = match images.iter().find(|(k, _)| *k == key) {
|
||||
Some((_, id)) => id.clone(),
|
||||
let img_id = match images.iter().find(|(k, sm, _)| *k == key && *sm == smooth) {
|
||||
Some((_, _, id)) => id.clone(),
|
||||
None => {
|
||||
let png = crate::encode_png(px.width, px.height, &px.rgba).ok()?;
|
||||
let id = format!("img{}", images.len());
|
||||
let _ = write!(defs, "<image id=\"{id}\" width=\"{}\" height=\"{}\" href=\"data:image/png;base64,{}\"/>", px.width, px.height, anicraft_doc::base64_encode(&png));
|
||||
images.push((key, id.clone()));
|
||||
let look = if smooth { "" } else { " image-rendering=\"pixelated\"" };
|
||||
let _ = write!(defs, "<image id=\"{id}\" width=\"{}\" height=\"{}\"{look} href=\"data:image/png;base64,{}\"/>", px.width, px.height, anicraft_doc::base64_encode(&png));
|
||||
images.push((key, smooth, id.clone()));
|
||||
id
|
||||
}
|
||||
};
|
||||
@@ -435,6 +437,7 @@ mod tests {
|
||||
guide: false,
|
||||
group: None,
|
||||
image: None,
|
||||
smooth: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,6 +557,7 @@ mod group_tests {
|
||||
guide: false,
|
||||
group: g,
|
||||
image: None,
|
||||
smooth: true,
|
||||
};
|
||||
let dl = DisplayList { 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 });
|
||||
|
||||
@@ -707,6 +707,9 @@ impl<'a> Builder<'a> {
|
||||
match bitmap {
|
||||
Some(mut b) => {
|
||||
b.id = BitmapId(self.doc.alloc_id());
|
||||
// Animate leaves out the default (smoothing on in current versions).
|
||||
b.smoothing = item.bool("allowSmoothing").unwrap_or(true);
|
||||
self.place_in_folder(name, anicraft_doc::LibraryItem::Bitmap(b.id));
|
||||
self.bitmaps.insert(name.to_string(), b.id);
|
||||
self.doc.bitmaps.push(Arc::new(b));
|
||||
}
|
||||
@@ -801,6 +804,27 @@ impl<'a> Builder<'a> {
|
||||
};
|
||||
let short = name.rsplit('/').next().unwrap_or(&name).to_string();
|
||||
self.doc.library.push(Arc::new(Symbol { id, name: short, kind, linkage, timeline }));
|
||||
self.place_in_folder(&name, anicraft_doc::LibraryItem::Symbol(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Library's folders (`<folders>`, so empty ones come across too), each a path such as
|
||||
/// `Characters/Hero` (ADR 0050).
|
||||
fn register_folders(&mut self, root: &X) {
|
||||
for f in root.list("folders").iter().filter(|f| f.name == "DOMFolderItem").take(anicraft_doc::library::MAX_FOLDERS) {
|
||||
if let Some(path) = f.attr("name") {
|
||||
self.doc.ensure_folder_path(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts `item` in the folder its library name's path names (`Characters/Ball` is in
|
||||
/// `Characters`), made if `<folders>` didn't list it.
|
||||
fn place_in_folder(&mut self, name: &str, item: anicraft_doc::LibraryItem) {
|
||||
if let Some((dir, _)) = name.rsplit_once('/')
|
||||
&& let Some(f) = self.doc.ensure_folder_path(dir)
|
||||
{
|
||||
self.doc.place_entry(anicraft_doc::LibraryEntry::Item(item), Some(f));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -837,6 +861,7 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do
|
||||
fps: root.f32("frameRate").unwrap_or(24.0).clamp(1.0, 120.0),
|
||||
background: color(&root, "backgroundColor", "__none"),
|
||||
};
|
||||
b.register_folders(&root);
|
||||
b.register_bitmaps(&root)?;
|
||||
b.register_symbols(&root)?;
|
||||
b.build_symbols();
|
||||
@@ -847,6 +872,9 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do
|
||||
let timeline = b.timeline(tl);
|
||||
b.doc.scenes.push(Arc::new(Scene { name, timeline }));
|
||||
}
|
||||
if !b.doc.library_tree.folders.is_empty() {
|
||||
b.report.keep("library folders");
|
||||
}
|
||||
if b.doc.scenes.is_empty() {
|
||||
let timeline = Timeline { layers: vec![Arc::new(Layer::new(LayerId(b.doc.alloc_id()), "Layer 1"))] };
|
||||
b.doc.scenes.push(Arc::new(Scene { name: "Scene 1".into(), timeline }));
|
||||
@@ -857,21 +885,48 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do
|
||||
/// Largest `.fla` archive read.
|
||||
pub const MAX_FLA_BYTES: u64 = crate::zip::MAX_ENTRY as u64 * 4;
|
||||
|
||||
/// Imports a `.fla` archive from its bytes (a file the browser handed over, say).
|
||||
/// The first bytes of a compound (OLE) file: a `.fla` saved by Flash CS4 or earlier.
|
||||
const OLE_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
|
||||
|
||||
/// Imports a `.fla` archive from its bytes (a file the browser handed over, say). Text is laid
|
||||
/// out with the fonts on this computer.
|
||||
pub fn import_fla(data: &[u8]) -> Result<(Document, Report), XflError> {
|
||||
fla_from(data, None)
|
||||
}
|
||||
|
||||
/// Imports a `.fla` archive, laying text out with `fonts` (tests, and hosts with their own
|
||||
/// font library).
|
||||
pub fn import_fla_with_fonts(data: &[u8], fonts: &Fonts) -> Result<(Document, Report), XflError> {
|
||||
fla_from(data, Some(fonts))
|
||||
}
|
||||
|
||||
fn fla_from(data: &[u8], fonts: Option<&Fonts>) -> Result<(Document, Report), XflError> {
|
||||
if data.len() as u64 > MAX_FLA_BYTES {
|
||||
return Err(XflError::NotXfl("the file is too large".into()));
|
||||
}
|
||||
if data.starts_with(&OLE_MAGIC) {
|
||||
return Err(XflError::NotXfl("this .fla was saved by Flash CS4 or earlier, in a format AniCraft can't read: open it in Animate and save it again".into()));
|
||||
}
|
||||
let archive = crate::zip::Archive::open(data)?;
|
||||
let read = |p: &str| -> Result<Option<Vec<u8>>, XflError> { Ok(archive.read(p)?) };
|
||||
import_with(&read)
|
||||
import_from(&read, fonts)
|
||||
}
|
||||
|
||||
/// Imports from disk: an XFL folder, its `.xfl` file, or a `.fla` archive.
|
||||
/// Whether the file at `path` starts as a zip archive or an old binary `.fla` does.
|
||||
fn looks_like_fla(path: &std::path::Path) -> bool {
|
||||
use std::io::Read;
|
||||
let mut head = [0u8; 8];
|
||||
let n = std::fs::File::open(path).and_then(|mut f| f.read(&mut head)).unwrap_or(0);
|
||||
head.get(..n).is_some_and(|h| h.starts_with(b"PK\x03\x04") || h.starts_with(b"PK\x05\x06") || h.starts_with(&OLE_MAGIC))
|
||||
}
|
||||
|
||||
/// Imports from disk: an XFL folder, its `.xfl` file (or any file in the folder, such as its
|
||||
/// `DOMDocument.xml`), or a `.fla` archive (recognised by its contents too, so a renamed one
|
||||
/// opens).
|
||||
pub fn import_path(path: &std::path::Path) -> Result<(Document, Report), XflError> {
|
||||
let meta = std::fs::metadata(path)?;
|
||||
let is_fla = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("fla"));
|
||||
if meta.is_file() && is_fla {
|
||||
if meta.is_file() && (is_fla || looks_like_fla(path)) {
|
||||
if meta.len() > MAX_FLA_BYTES {
|
||||
return Err(XflError::NotXfl("the file is too large".into()));
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ pub mod text;
|
||||
pub use anicraft_xml as xml;
|
||||
pub mod zip;
|
||||
|
||||
pub use import::{MAX_FLA_BYTES, Report, XflError, import_fla, import_path, import_with, import_with_fonts};
|
||||
pub use import::{MAX_FLA_BYTES, Report, XflError, import_fla, import_fla_with_fonts, import_path, import_with, import_with_fonts};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
+15
-3
@@ -101,7 +101,9 @@ fn stage_layers_frames_and_tweens() {
|
||||
// Frame scripts, on the scene's frames and inside symbols, are kept verbatim (ADR 0013
|
||||
// tier 1); these are in the subset that runs (tier 2).
|
||||
assert_eq!(report.runs.get("frame scripts in ActionScript 3.0"), Some(&2));
|
||||
assert!(report.kept.is_empty(), "{report:?}");
|
||||
// The symbol's path puts it in a Library folder (ADR 0050).
|
||||
assert_eq!(report.kept.keys().collect::<Vec<_>>(), ["library folders"], "{report:?}");
|
||||
assert_eq!(doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Symbol(doc.library[0].id))), "Characters/Ball");
|
||||
assert!(report.skipped.keys().all(|k| !k.contains("script")), "{report:?}");
|
||||
assert_eq!(ball.keyframes[1].script.as_ref().and_then(|s| s.source()).map(|s| s.text.as_str()), Some("stop();"));
|
||||
let inner = &doc.library[0].timeline.layers[0].keyframes[0];
|
||||
@@ -191,7 +193,7 @@ fn shapes_become_fills_and_strokes() {
|
||||
|
||||
#[test]
|
||||
fn a_fla_archive_imports_the_same() {
|
||||
let z = crate::zip::tests::make_zip(&[("DOMDocument.xml", DOC.as_bytes(), true), ("LIBRARY/Characters/Ball.xml", BALL.as_bytes(), true)]);
|
||||
let z = crate::zip::pack::write(&[crate::zip::pack::Raw::new("DOMDocument.xml", DOC.as_bytes(), true), crate::zip::pack::Raw::new("LIBRARY/Characters/Ball.xml", BALL.as_bytes(), true)], false);
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-xfl-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let fla = dir.join("scene.fla");
|
||||
@@ -257,9 +259,10 @@ fn png_2x1() -> Vec<u8> {
|
||||
}
|
||||
|
||||
const BITMAP_DOC: &str = r##"<DOMDocument width="200" height="100">
|
||||
<folders><DOMFolderItem name="Art" isExpanded="true"/><DOMFolderItem name="Empty/Inner"/></folders>
|
||||
<media>
|
||||
<DOMBitmapItem name="Art/photo.png" href="Art/photo.png" bitmapDataHRef="M 1 1.dat"/>
|
||||
<DOMBitmapItem name="packed.png" href="packed.png" bitmapDataHRef="M 2 2.dat"/>
|
||||
<DOMBitmapItem name="packed.png" href="packed.png" bitmapDataHRef="M 2 2.dat" allowSmoothing="false"/>
|
||||
<DOMBitmapItem name="private.jpg" href="private.jpg" bitmapDataHRef="M 3 3.dat"/>
|
||||
<DOMBitmapItem name="gone.png" href="gone.png"/>
|
||||
</media>
|
||||
@@ -309,6 +312,15 @@ fn bitmaps_come_across_when_their_image_is_png_or_jpeg() {
|
||||
// The renderer gets the pixels with the items.
|
||||
let list = evaluate(&doc, 0);
|
||||
assert_eq!(list.items.iter().filter(|i| i.image.is_some()).count(), 3);
|
||||
// Library folders come across (ADR 0050): the item's path places it, empty ones are kept,
|
||||
// and Allow Smoothing is read (on unless the file turns it off).
|
||||
let path = |i| doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Bitmap(i)));
|
||||
assert_eq!((path(doc.bitmaps[0].id).as_str(), path(doc.bitmaps[1].id).as_str()), ("Art/photo.png", "packed.png"));
|
||||
let folders: Vec<String> = doc.library_tree.folders.iter().map(|f| doc.entry_path(anicraft_doc::LibraryEntry::Folder(f.id))).collect();
|
||||
assert_eq!(folders, ["Art", "Empty", "Empty/Inner"]);
|
||||
assert_eq!(report.kept.get("library folders"), Some(&1));
|
||||
assert_eq!((doc.bitmaps[0].smoothing, doc.bitmaps[1].smoothing), (true, false));
|
||||
assert!(list.items.iter().any(|i| i.image.is_some() && !i.smooth));
|
||||
}
|
||||
|
||||
/// A square (0, 0)–(100, 100) shape-tweening to a triangle (200, 0), (300, 50), (200, 100),
|
||||
|
||||
+337
-105
@@ -1,169 +1,401 @@
|
||||
//! Reading files out of a `.fla` (a zip archive of an XFL folder).
|
||||
//! Reading files out of a `.fla` (a zip archive of an XFL folder), ADR 0009 and ADR 0054.
|
||||
//!
|
||||
//! Implements the parts of the published ZIP format (PKWARE APPNOTE) that `.fla` files use:
|
||||
//! the end-of-central-directory record, central directory entries and local headers, with
|
||||
//! "stored" and "deflate" entries (inflated by `miniz_oxide`). ZIP64 and encryption are refused
|
||||
//! with a clear error. Every offset and size is checked; sizes are capped so a zip bomb can't
|
||||
//! exhaust memory. Never panics.
|
||||
//! Implements the parts of the published ZIP format (PKWARE APPNOTE 6.3) that archive tools
|
||||
//! write: the end-of-central-directory record (and its ZIP64 form), central directory entries
|
||||
//! with ZIP64 sizes, local headers, data descriptors, "stored" and "deflate" entries (inflated
|
||||
//! by `miniz_oxide`), UTF-8 names (flag bit 11 or the Info-ZIP Unicode path field) and CP437
|
||||
//! names. Encryption, other compression methods and split archives are refused with a clear
|
||||
//! error.
|
||||
//!
|
||||
//! The archive is treated as hostile. Every offset and size is checked against the bytes it
|
||||
//! comes from; entries may not overlap each other or the central directory; a name that would
|
||||
//! leave the package (`..`, absolute or drive paths), is listed twice or is nested deeper than
|
||||
//! [`MAX_DEPTH`] refuses the archive; an entry may not claim more than deflate can produce from
|
||||
//! its bytes ([`MAX_RATIO`]), more than [`MAX_ENTRY`], or a size or checksum it doesn't have;
|
||||
//! and the archive hands out at most [`MAX_TOTAL`] bytes in all. Nothing is ever written to
|
||||
//! disk. Never panics.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Largest single entry inflated (bytes).
|
||||
pub const MAX_ENTRY: usize = 256 * 1024 * 1024;
|
||||
/// Most bytes one archive hands out, over every read (the import's memory budget).
|
||||
pub const MAX_TOTAL: u64 = 1024 * 1024 * 1024;
|
||||
/// Most entries an archive may list (files and folders).
|
||||
pub const MAX_ENTRIES: usize = 100_000;
|
||||
/// Most folders a path may be inside (Animate's library nests a few deep).
|
||||
pub const MAX_DEPTH: usize = 32;
|
||||
/// Largest size-to-compressed-size ratio believed: deflate itself can't pass about 1032 : 1,
|
||||
/// so an entry claiming more is a zip bomb or a damaged size, refused before inflating.
|
||||
pub const MAX_RATIO: u64 = 1024;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
#[derive(Debug, Clone, thiserror::Error, PartialEq)]
|
||||
pub enum ZipError {
|
||||
#[error("not a zip archive (no end-of-directory record)")]
|
||||
NotZip,
|
||||
#[error("the archive is damaged: {0}")]
|
||||
Damaged(&'static str),
|
||||
#[error("'{0}' uses an unsupported zip feature ({1})")]
|
||||
#[error("the archive is damaged: '{0}' {1}")]
|
||||
DamagedEntry(String, &'static str),
|
||||
#[error("the archive uses a zip feature AniCraft can't read ({0})")]
|
||||
UnsupportedArchive(&'static str),
|
||||
#[error("'{0}' uses a zip feature AniCraft can't read ({1})")]
|
||||
Unsupported(String, &'static str),
|
||||
#[error("'{0}' is too large to read")]
|
||||
TooLarge(String),
|
||||
#[error("the archive asks for more than {} MB in all", MAX_TOTAL / (1024 * 1024))]
|
||||
TooMuch,
|
||||
#[error("the archive lists more than {MAX_ENTRIES} files")]
|
||||
TooMany,
|
||||
#[error("'{0}' claims to expand more than compression allows (a zip bomb or a damaged archive)")]
|
||||
Bomb(String),
|
||||
#[error("'{0}' and '{1}' share bytes in the archive (a zip bomb or a damaged archive)")]
|
||||
Overlap(String, String),
|
||||
#[error("'{0}' points outside the document")]
|
||||
Unsafe(String),
|
||||
#[error("'{0}' is in the archive twice")]
|
||||
Duplicate(String),
|
||||
#[error("'{0}' is inside more than {MAX_DEPTH} folders")]
|
||||
TooDeep(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Entry {
|
||||
method: u16,
|
||||
flags: u16,
|
||||
crc: u32,
|
||||
comp: usize,
|
||||
size: usize,
|
||||
offset: usize,
|
||||
/// Where its (compressed) bytes start.
|
||||
data: usize,
|
||||
}
|
||||
|
||||
pub struct Archive<'a> {
|
||||
data: &'a [u8],
|
||||
entries: HashMap<String, Entry>,
|
||||
folders: usize,
|
||||
/// Bytes still to hand out ([`MAX_TOTAL`] at first).
|
||||
budget: Cell<u64>,
|
||||
}
|
||||
|
||||
const END: u32 = 0x0605_4b50;
|
||||
const END64: u32 = 0x0606_4b50;
|
||||
const LOCATOR64: u32 = 0x0706_4b50;
|
||||
const CENTRAL: u32 = 0x0201_4b50;
|
||||
const LOCAL: u32 = 0x0403_4b50;
|
||||
|
||||
fn get(d: &[u8], at: usize, len: usize) -> Option<&[u8]> {
|
||||
d.get(at..at.checked_add(len)?)
|
||||
}
|
||||
fn u16_at(d: &[u8], i: usize) -> Option<u16> {
|
||||
Some(u16::from_le_bytes(d.get(i..i + 2)?.try_into().ok()?))
|
||||
Some(u16::from_le_bytes(get(d, i, 2)?.try_into().ok()?))
|
||||
}
|
||||
fn u32_at(d: &[u8], i: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(d.get(i..i + 4)?.try_into().ok()?))
|
||||
Some(u32::from_le_bytes(get(d, i, 4)?.try_into().ok()?))
|
||||
}
|
||||
fn u64_at(d: &[u8], i: usize) -> Option<u64> {
|
||||
Some(u64::from_le_bytes(get(d, i, 8)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// The body of the extra field `id`, if `extra` has one.
|
||||
fn extra_field(mut extra: &[u8], id: u16) -> Option<&[u8]> {
|
||||
while extra.len() >= 4 {
|
||||
let (tag, len) = (u16_at(extra, 0)?, u16_at(extra, 2)? as usize);
|
||||
let body = get(extra, 4, len)?;
|
||||
if tag == id {
|
||||
return Some(body);
|
||||
}
|
||||
extra = extra.get(4 + len..)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// CRC-32 tables for eight bytes at a time ("slicing by 8"): `TABLES[0]` is the classic
|
||||
/// byte table, `TABLES[k][b]` the checksum of byte `b` followed by `k` zero bytes.
|
||||
const TABLES: [[u32; 256]; 8] = {
|
||||
let mut t = [[0u32; 256]; 8];
|
||||
let mut i = 0;
|
||||
while i < 256 {
|
||||
let mut c = i as u32;
|
||||
let mut k = 0;
|
||||
while k < 8 {
|
||||
c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
k += 1;
|
||||
}
|
||||
t[0][i] = c;
|
||||
i += 1;
|
||||
}
|
||||
let mut k = 1;
|
||||
while k < 8 {
|
||||
let mut i = 0;
|
||||
while i < 256 {
|
||||
let prev = t[k - 1][i];
|
||||
t[k][i] = (prev >> 8) ^ t[0][(prev & 0xff) as usize];
|
||||
i += 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
t
|
||||
};
|
||||
|
||||
/// CRC-32 (ISO-HDLC, the zip checksum), eight bytes at a time.
|
||||
pub fn crc32(data: &[u8]) -> u32 {
|
||||
let t = &TABLES;
|
||||
let mut c = !0u32;
|
||||
let (blocks, rest) = data.as_chunks::<8>();
|
||||
for b in blocks {
|
||||
let lo = c ^ u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
|
||||
c = t[7][(lo & 0xff) as usize] ^ t[6][((lo >> 8) & 0xff) as usize] ^ t[5][((lo >> 16) & 0xff) as usize] ^ t[4][(lo >> 24) as usize] ^ t[3][b[4] as usize] ^ t[2][b[5] as usize] ^ t[1][b[6] as usize] ^ t[0][b[7] as usize];
|
||||
}
|
||||
for &b in rest {
|
||||
c = t[0][((c ^ b as u32) & 0xff) as usize] ^ (c >> 8);
|
||||
}
|
||||
!c
|
||||
}
|
||||
|
||||
/// Code page 437, bytes 0x80 to 0xFF: the zip format's name encoding without the UTF-8 flag.
|
||||
const CP437: [char; 128] = [
|
||||
'Ç', 'ü', 'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å', //
|
||||
'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', '¢', '£', '¥', '₧', 'ƒ', //
|
||||
'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '⌐', '¬', '½', '¼', '¡', '«', '»', //
|
||||
'░', '▒', '▓', '│', '┤', '╡', '╢', '╖', '╕', '╣', '║', '╗', '╝', '╜', '╛', '┐', //
|
||||
'└', '┴', '┬', '├', '─', '┼', '╞', '╟', '╚', '╔', '╩', '╦', '╠', '═', '╬', '╧', //
|
||||
'╨', '╤', '╥', '╙', '╘', '╒', '╓', '╫', '╪', '┘', '┌', '█', '▄', '▌', '▐', '▀', //
|
||||
'α', 'ß', 'Γ', 'π', 'Σ', 'σ', 'µ', 'τ', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩', //
|
||||
'≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'ⁿ', '²', '■', '\u{a0}',
|
||||
];
|
||||
|
||||
/// An entry's name as text: the Info-ZIP Unicode path field when it matches the name, UTF-8
|
||||
/// when flag bit 11 says so, else CP437 as the format specifies. Many writers store UTF-8
|
||||
/// without setting the flag, so a name that is valid UTF-8 is read as UTF-8 (ASCII, which
|
||||
/// nearly every name is, reads the same either way).
|
||||
fn decode_name(raw: &[u8], utf8: bool, extra: &[u8]) -> Result<String, ZipError> {
|
||||
if let Some(up) = extra_field(extra, 0x7075)
|
||||
&& up.first() == Some(&1)
|
||||
&& u32_at(up, 1) == Some(crc32(raw))
|
||||
&& let Some(Ok(s)) = up.get(5..).map(std::str::from_utf8)
|
||||
{
|
||||
return Ok(s.to_string());
|
||||
}
|
||||
match std::str::from_utf8(raw) {
|
||||
Ok(s) => Ok(s.to_string()),
|
||||
Err(_) if utf8 => Err(ZipError::Damaged("an entry's name is not the UTF-8 it says it is")),
|
||||
Err(_) => Ok(raw.iter().map(|&b| if b < 0x80 { b as char } else { CP437.get((b - 0x80) as usize).copied().unwrap_or('\u{fffd}') }).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A name as a plain path inside the package: `\` read as `/`, empty and `.` parts dropped.
|
||||
/// Names that would leave the package are refused, though nothing is ever extracted: every
|
||||
/// lookup stays unambiguous, as the folder form's reader also refuses them.
|
||||
fn clean_path(name: &str) -> Result<String, ZipError> {
|
||||
let unix = name.replace('\\', "/");
|
||||
let shown = || name.chars().take(200).collect::<String>();
|
||||
if unix.starts_with('/') || unix.contains('\0') {
|
||||
return Err(ZipError::Unsafe(shown()));
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
for (i, part) in unix.split('/').enumerate() {
|
||||
match part {
|
||||
"" | "." => {}
|
||||
".." => return Err(ZipError::Unsafe(shown())),
|
||||
// `C:`, `C:x`: a drive.
|
||||
p if i == 0 && p.contains(':') => return Err(ZipError::Unsafe(shown())),
|
||||
p => parts.push(p),
|
||||
}
|
||||
}
|
||||
if parts.len() > MAX_DEPTH + 1 {
|
||||
return Err(ZipError::TooDeep(shown()));
|
||||
}
|
||||
Ok(parts.join("/"))
|
||||
}
|
||||
|
||||
fn method_name(method: u16) -> &'static str {
|
||||
match method {
|
||||
9 => "Deflate64 compression",
|
||||
12 => "bzip2 compression",
|
||||
14 => "LZMA compression",
|
||||
93 => "Zstandard compression",
|
||||
95 => "XZ compression",
|
||||
99 => "AES encryption",
|
||||
_ => "an unknown compression method",
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of the central directory: (entry count, its size, its offset, where it must end).
|
||||
fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> {
|
||||
// The end record is in the last 22 + 65535 bytes (it may carry a comment).
|
||||
let lo = data.len().saturating_sub(22 + 65_535);
|
||||
let eocd = (lo..data.len().saturating_sub(21)).rev().find(|&i| u32_at(data, i) == Some(END)).ok_or(ZipError::NotZip)?;
|
||||
let field16 = |o: usize| u16_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short"));
|
||||
let field32 = |o: usize| u32_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short"));
|
||||
let (disk, dir_disk, on_disk, count) = (field16(4)?, field16(6)?, field16(8)?, field16(10)?);
|
||||
let (size, offset) = (field32(12)?, field32(16)?);
|
||||
if count != 0xffff && size != 0xffff_ffff && offset != 0xffff_ffff {
|
||||
if disk != 0 || dir_disk != 0 || on_disk != count {
|
||||
return Err(ZipError::UnsupportedArchive("split across several files"));
|
||||
}
|
||||
return Ok((count.into(), size.into(), offset.into(), eocd));
|
||||
}
|
||||
// ZIP64: a locator just before the end record points at the ZIP64 end record.
|
||||
let locator = eocd.checked_sub(20).filter(|&l| u32_at(data, l) == Some(LOCATOR64)).ok_or(ZipError::Damaged("the ZIP64 end record is missing"))?;
|
||||
let missing = ZipError::Damaged("the ZIP64 end record is missing");
|
||||
let at = u64_at(data, locator + 8).and_then(|a| usize::try_from(a).ok()).filter(|&a| a < locator).ok_or(missing.clone())?;
|
||||
if u32_at(data, at) != Some(END64) {
|
||||
return Err(missing);
|
||||
}
|
||||
let cut = ZipError::Damaged("the ZIP64 end record is cut short");
|
||||
let (disk, dir_disk) = (u32_at(data, at + 16).ok_or(cut.clone())?, u32_at(data, at + 20).ok_or(cut.clone())?);
|
||||
let (on_disk, count) = (u64_at(data, at + 24).ok_or(cut.clone())?, u64_at(data, at + 32).ok_or(cut.clone())?);
|
||||
if disk != 0 || dir_disk != 0 || on_disk != count {
|
||||
return Err(ZipError::UnsupportedArchive("split across several files"));
|
||||
}
|
||||
Ok((count, u64_at(data, at + 40).ok_or(cut.clone())?, u64_at(data, at + 48).ok_or(cut)?, at))
|
||||
}
|
||||
|
||||
impl<'a> Archive<'a> {
|
||||
pub fn open(data: &'a [u8]) -> Result<Archive<'a>, ZipError> {
|
||||
// The end record is in the last 22 + 65535 bytes (it may carry a comment).
|
||||
let lo = data.len().saturating_sub(22 + 65_535);
|
||||
let eocd = (lo..data.len().saturating_sub(21)).rev().find(|&i| u32_at(data, i) == Some(0x0605_4b50)).ok_or(ZipError::NotZip)?;
|
||||
let count = u16_at(data, eocd + 10).ok_or(ZipError::Damaged("end record"))? as usize;
|
||||
let dir = u32_at(data, eocd + 16).ok_or(ZipError::Damaged("end record"))? as usize;
|
||||
if count == 0xffff || dir == 0xffff_ffff {
|
||||
return Err(ZipError::Unsupported("archive".into(), "ZIP64"));
|
||||
let (count, dir_size, dir_at, dir_limit) = find_end(data)?;
|
||||
let past = ZipError::Damaged("the central directory is outside the archive");
|
||||
let dir_at = usize::try_from(dir_at).map_err(|_| past.clone())?;
|
||||
let dir_end = usize::try_from(dir_size).ok().and_then(|s| dir_at.checked_add(s)).filter(|&e| e <= dir_limit).ok_or(past.clone())?;
|
||||
let dir = data.get(dir_at..dir_end).ok_or(past)?;
|
||||
if count > MAX_ENTRIES as u64 {
|
||||
return Err(ZipError::TooMany);
|
||||
}
|
||||
let mut entries = HashMap::with_capacity(count.min(100_000));
|
||||
let mut i = dir;
|
||||
let count = count as usize;
|
||||
// Every central entry is at least 46 bytes.
|
||||
let cut = ZipError::Damaged("the central directory is cut short");
|
||||
if count.saturating_mul(46) > dir.len() {
|
||||
return Err(cut);
|
||||
}
|
||||
let mut entries = HashMap::with_capacity(count);
|
||||
let mut folders = 0;
|
||||
// (start, end, name) of every entry's local header and data.
|
||||
let mut spans: Vec<(usize, usize, String)> = Vec::with_capacity(count);
|
||||
let mut i = 0usize;
|
||||
for _ in 0..count {
|
||||
if u32_at(data, i) != Some(0x0201_4b50) {
|
||||
return Err(ZipError::Damaged("central directory"));
|
||||
if u32_at(dir, i) != Some(CENTRAL) {
|
||||
return Err(cut);
|
||||
}
|
||||
let field = |o: usize| u32_at(data, i + o).ok_or(ZipError::Damaged("central directory"));
|
||||
let short = |o: usize| u16_at(data, i + o).ok_or(ZipError::Damaged("central directory"));
|
||||
let short = |o: usize| u16_at(dir, i + o).ok_or(cut.clone());
|
||||
let long = |o: usize| u32_at(dir, i + o).ok_or(cut.clone());
|
||||
let (flags, method) = (short(8)?, short(10)?);
|
||||
let (comp, size) = (field(20)? as usize, field(24)? as usize);
|
||||
let crc = long(16)?;
|
||||
let (comp32, size32, offset32) = (long(20)?, long(24)?, long(42)?);
|
||||
let (nlen, xlen, clen) = (short(28)? as usize, short(30)? as usize, short(32)? as usize);
|
||||
let offset = field(42)? as usize;
|
||||
let name = data.get(i + 46..i + 46 + nlen).ok_or(ZipError::Damaged("entry name"))?;
|
||||
let name = String::from_utf8_lossy(name).replace('\\', "/");
|
||||
entries.insert(name, Entry { method, flags, comp, size, offset });
|
||||
let raw_name = get(dir, i + 46, nlen).ok_or(cut.clone())?;
|
||||
let extra = get(dir, i + 46 + nlen, xlen).ok_or(cut.clone())?;
|
||||
get(dir, i + 46 + nlen + xlen, clen).ok_or(cut.clone())?;
|
||||
i += 46 + nlen + xlen + clen;
|
||||
|
||||
let name = decode_name(raw_name, flags & 0x0800 != 0, extra)?;
|
||||
let shown = || name.chars().take(200).collect::<String>();
|
||||
// ZIP64: each 32-bit field that overflowed is in the extra field, in this order.
|
||||
let (mut size, mut comp, mut offset) = (u64::from(size32), u64::from(comp32), u64::from(offset32));
|
||||
if size32 == u32::MAX || comp32 == u32::MAX || offset32 == u32::MAX {
|
||||
let z = extra_field(extra, 0x0001).ok_or_else(|| ZipError::DamagedEntry(shown(), "has no ZIP64 sizes"))?;
|
||||
let mut at = 0;
|
||||
for (wide, value) in [(size32, &mut size), (comp32, &mut comp), (offset32, &mut offset)] {
|
||||
if wide == u32::MAX {
|
||||
*value = u64_at(z, at).ok_or_else(|| ZipError::DamagedEntry(shown(), "has its ZIP64 sizes cut short"))?;
|
||||
at += 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
let outside = || ZipError::DamagedEntry(shown(), "is outside the archive");
|
||||
let offset = usize::try_from(offset).map_err(|_| outside())?;
|
||||
let comp = usize::try_from(comp).map_err(|_| outside())?;
|
||||
// An entry's size is checked when it is read: one too large to read may sit unused.
|
||||
let size = usize::try_from(size).unwrap_or(usize::MAX);
|
||||
|
||||
// Its local header, then its data, all before the central directory.
|
||||
if u32_at(data, offset) != Some(LOCAL) {
|
||||
return Err(ZipError::DamagedEntry(shown(), "has no local header"));
|
||||
}
|
||||
let lnlen = u16_at(data, offset + 26).ok_or_else(outside)? as usize;
|
||||
let lxlen = u16_at(data, offset + 28).ok_or_else(outside)? as usize;
|
||||
let start = offset + 30 + lnlen + lxlen;
|
||||
let end = start.checked_add(comp).filter(|&e| e <= dir_at).ok_or_else(outside)?;
|
||||
spans.push((offset, end, shown()));
|
||||
|
||||
let folder = name.ends_with('/') || name.ends_with('\\');
|
||||
let path = clean_path(&name)?;
|
||||
if folder || path.is_empty() {
|
||||
if size != 0 || comp > 2 {
|
||||
return Err(ZipError::DamagedEntry(shown(), "is a folder with data"));
|
||||
}
|
||||
folders += 1;
|
||||
continue;
|
||||
}
|
||||
if method == 8 && size as u64 > (comp as u64).saturating_mul(MAX_RATIO).saturating_add(4096) {
|
||||
return Err(ZipError::Bomb(shown()));
|
||||
}
|
||||
if method == 0 && flags & 0x41 == 0 && size != comp {
|
||||
return Err(ZipError::DamagedEntry(shown(), "is stored with two different sizes"));
|
||||
}
|
||||
if entries.insert(path, Entry { method, flags, crc, comp, size, data: start }).is_some() {
|
||||
return Err(ZipError::Duplicate(shown()));
|
||||
}
|
||||
}
|
||||
Ok(Archive { data, entries })
|
||||
// No two entries may share bytes (the overlapping-entries zip bomb).
|
||||
spans.sort_unstable_by_key(|s| s.0);
|
||||
if let Some(w) = spans.windows(2).find(|w| w[0].1 > w[1].0) {
|
||||
return Err(ZipError::Overlap(w[0].2.clone(), w[1].2.clone()));
|
||||
}
|
||||
Ok(Archive { data, entries, folders, budget: Cell::new(MAX_TOTAL) })
|
||||
}
|
||||
|
||||
/// The files' paths (`/`-separated, folders left out).
|
||||
pub fn names(&self) -> impl Iterator<Item = &str> {
|
||||
self.entries.keys().map(String::as_str)
|
||||
}
|
||||
|
||||
/// The bytes of entry `name` (path inside the archive, `/`-separated).
|
||||
/// How many files and folder entries the archive lists.
|
||||
pub fn counts(&self) -> (usize, usize) {
|
||||
(self.entries.len(), self.folders)
|
||||
}
|
||||
|
||||
/// The bytes of entry `name` (path inside the archive, `/`-separated), checked against
|
||||
/// its size and checksum.
|
||||
pub fn read(&self, name: &str) -> Result<Option<Vec<u8>>, ZipError> {
|
||||
let Some(e) = self.entries.get(name) else { return Ok(None) };
|
||||
if e.flags & 1 != 0 {
|
||||
if e.flags & 0x41 != 0 {
|
||||
return Err(ZipError::Unsupported(name.into(), "encryption"));
|
||||
}
|
||||
if !matches!(e.method, 0 | 8) {
|
||||
return Err(ZipError::Unsupported(name.into(), method_name(e.method)));
|
||||
}
|
||||
if e.size > MAX_ENTRY || e.comp > MAX_ENTRY {
|
||||
return Err(ZipError::TooLarge(name.into()));
|
||||
}
|
||||
let d = self.data;
|
||||
if u32_at(d, e.offset) != Some(0x0403_4b50) {
|
||||
return Err(ZipError::Damaged("local header"));
|
||||
let left = self.budget.get();
|
||||
if e.size as u64 > left {
|
||||
return Err(ZipError::TooMuch);
|
||||
}
|
||||
let nlen = u16_at(d, e.offset + 26).ok_or(ZipError::Damaged("local header"))? as usize;
|
||||
let xlen = u16_at(d, e.offset + 28).ok_or(ZipError::Damaged("local header"))? as usize;
|
||||
let start = e.offset + 30 + nlen + xlen;
|
||||
let raw = d.get(start..start + e.comp).ok_or(ZipError::Damaged("entry data"))?;
|
||||
match e.method {
|
||||
0 => Ok(Some(raw.to_vec())),
|
||||
8 => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.clamp(1, MAX_ENTRY)).map(Some).map_err(|_| ZipError::Damaged("deflate data")),
|
||||
_ => Err(ZipError::Unsupported(name.into(), "compression method")),
|
||||
let raw = get(self.data, e.data, e.comp).ok_or_else(|| ZipError::DamagedEntry(name.into(), "is outside the archive"))?;
|
||||
let out = match e.method {
|
||||
0 => raw.to_vec(),
|
||||
_ => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1)).map_err(|err| {
|
||||
let why = if err.status == miniz_oxide::inflate::TINFLStatus::HasMoreOutput { "expands past the size it gives" } else { "has damaged compressed data" };
|
||||
ZipError::DamagedEntry(name.into(), why)
|
||||
})?,
|
||||
};
|
||||
if out.len() != e.size {
|
||||
return Err(ZipError::DamagedEntry(name.into(), "is not the size it gives"));
|
||||
}
|
||||
if crc32(&out) != e.crc {
|
||||
return Err(ZipError::DamagedEntry(name.into(), "fails its checksum"));
|
||||
}
|
||||
self.budget.set(left - e.size as u64);
|
||||
Ok(Some(out))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
#[path = "../tests/support/fla.rs"]
|
||||
pub(crate) mod pack;
|
||||
|
||||
/// Builds a zip with stored and deflated entries (for tests).
|
||||
pub fn make_zip(files: &[(&str, &[u8], bool)]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut dir = Vec::new();
|
||||
for (name, body, deflate) in files {
|
||||
let data = if *deflate { miniz_oxide::deflate::compress_to_vec(body, 6) } else { body.to_vec() };
|
||||
let offset = out.len() as u32;
|
||||
let method: u16 = if *deflate { 8 } else { 0 };
|
||||
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&[20, 0, 0, 0]);
|
||||
out.extend_from_slice(&method.to_le_bytes());
|
||||
out.extend_from_slice(&[0; 8]); // time, date, crc (not checked)
|
||||
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.extend_from_slice(&data);
|
||||
dir.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
|
||||
dir.extend_from_slice(&[20, 0, 20, 0, 0, 0]);
|
||||
dir.extend_from_slice(&method.to_le_bytes());
|
||||
dir.extend_from_slice(&[0; 8]);
|
||||
dir.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
dir.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
dir.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
dir.extend_from_slice(&[0; 12]);
|
||||
dir.extend_from_slice(&offset.to_le_bytes());
|
||||
dir.extend_from_slice(name.as_bytes());
|
||||
}
|
||||
let dir_at = out.len() as u32;
|
||||
out.extend_from_slice(&dir);
|
||||
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
out.extend_from_slice(&(files.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&(files.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&(dir.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&dir_at.to_le_bytes());
|
||||
out.extend_from_slice(&[0, 0]);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_stored_and_deflated_entries() {
|
||||
let z = make_zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("LIBRARY\\Ball.xml", b"<DOMSymbolItem/>", false)]);
|
||||
let a = Archive::open(&z).unwrap();
|
||||
assert_eq!(a.read("DOMDocument.xml").unwrap().unwrap(), b"<DOMDocument/>");
|
||||
assert_eq!(a.read("LIBRARY/Ball.xml").unwrap().unwrap(), b"<DOMSymbolItem/>", "backslashes normalised");
|
||||
assert_eq!(a.read("missing").unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_archives_are_errors() {
|
||||
assert_eq!(Archive::open(b"not a zip").err(), Some(ZipError::NotZip));
|
||||
let mut z = make_zip(&[("a", b"hello", true)]);
|
||||
let n = z.len();
|
||||
// Point the directory past the end.
|
||||
z[n - 6] = 0xff;
|
||||
assert!(Archive::open(&z).is_err());
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
#[path = "zip_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,284 @@
|
||||
//! The zip reader against the layouts writers produce and the archives an attacker would
|
||||
//! (ADR 0054). Archives are made by the independent writer in `tests/support/fla.rs`.
|
||||
|
||||
use super::pack::{self, Raw, write};
|
||||
use super::*;
|
||||
|
||||
fn zip(files: &[(&str, &[u8], bool)]) -> Vec<u8> {
|
||||
write(&files.iter().map(|(n, b, d)| Raw::new(n, b, *d)).collect::<Vec<_>>(), false)
|
||||
}
|
||||
|
||||
/// The error opening `z`, or reading every file in it.
|
||||
fn error(z: &[u8]) -> ZipError {
|
||||
match Archive::open(z) {
|
||||
Err(e) => e,
|
||||
Ok(a) => {
|
||||
let names: Vec<String> = a.names().map(str::to_string).collect();
|
||||
names.iter().find_map(|n| a.read(n).err()).expect("an error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_stored_and_deflated_entries() {
|
||||
let z = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("LIBRARY\\Ball.xml", b"<DOMSymbolItem/>", false)]);
|
||||
let a = Archive::open(&z).unwrap();
|
||||
assert_eq!(a.read("DOMDocument.xml").unwrap().unwrap(), b"<DOMDocument/>");
|
||||
assert_eq!(a.read("LIBRARY/Ball.xml").unwrap().unwrap(), b"<DOMSymbolItem/>", "backslashes normalised");
|
||||
assert_eq!(a.read("missing").unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_checksum_matches_the_published_check_value() {
|
||||
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
|
||||
assert_eq!(crc32(b""), 0);
|
||||
let bytes: Vec<u8> = (0..5000u32).map(|i| (i * 7 + i / 13) as u8).collect();
|
||||
assert_eq!(crc32(&bytes), pack::crc32(&bytes), "the table matches the bitwise form");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_layout_a_writer_uses_reads_the_same() {
|
||||
let files: std::collections::BTreeMap<String, Vec<u8>> = [("DOMDocument.xml", "<DOMDocument/>"), ("LIBRARY/Café/Ünïcödé ★.xml", "<DOMSymbolItem/>"), ("bin/M 1 1.dat", "data")].iter().map(|(p, b)| (p.to_string(), b.as_bytes().to_vec())).collect();
|
||||
for v in pack::VARIANTS {
|
||||
let z = pack::pack(&files, v);
|
||||
let a = Archive::open(&z).unwrap_or_else(|e| panic!("{}: {e}", v.name));
|
||||
assert_eq!(a.counts().0, 3 + usize::from(v.mimetype), "{}", v.name);
|
||||
for (path, body) in &files {
|
||||
assert_eq!(a.read(path).unwrap_or_else(|e| panic!("{}: {e}", v.name)).as_deref(), Some(body.as_slice()), "{}: {path}", v.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_cp437_unless_flagged_or_utf8() {
|
||||
// "Café.xml" in CP437 (é is 0x82), not valid UTF-8, without the flag.
|
||||
let mut r = Raw::new("", b"x", false);
|
||||
(r.name, r.utf8) = (b"LIBRARY/Caf\x82.xml".to_vec(), false);
|
||||
let z = write(&[r.clone()], false);
|
||||
assert_eq!(Archive::open(&z).unwrap().names().collect::<Vec<_>>(), ["LIBRARY/Café.xml"]);
|
||||
assert_eq!(pack::cp437("LIBRARY/Café.xml").unwrap(), b"LIBRARY/Caf\x82.xml");
|
||||
// Flagged as UTF-8 but isn't: refused, not guessed.
|
||||
r.utf8 = true;
|
||||
assert!(matches!(Archive::open(&write(&[r], false)).err(), Some(ZipError::Damaged(_))));
|
||||
// A Unicode path field whose checksum doesn't match the name it stands in for is ignored.
|
||||
let mut r = Raw::new("plain.xml", b"x", false);
|
||||
r.utf8 = false;
|
||||
r.extra = [0x75, 0x70, 9, 0, 1, 0, 0, 0, 0, b'o', b't', b'h', b'r'].to_vec();
|
||||
assert_eq!(Archive::open(&write(&[r], false)).unwrap().names().collect::<Vec<_>>(), ["plain.xml"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_archives_are_errors() {
|
||||
assert_eq!(Archive::open(b"not a zip").err(), Some(ZipError::NotZip));
|
||||
assert_eq!(Archive::open(b"").err(), Some(ZipError::NotZip));
|
||||
let mut z = zip(&[("a", b"hello", true)]);
|
||||
let n = z.len();
|
||||
// Point the directory past the end.
|
||||
z[n - 6] = 0xff;
|
||||
assert!(Archive::open(&z).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_central_directory_is_damaged() {
|
||||
let z = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("b.xml", b"<b/>", true), ("c.xml", b"<c/>", false)]);
|
||||
let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize;
|
||||
let end = z.len() - 22;
|
||||
// Every cut inside the directory, keeping the end record (which still claims 3 entries).
|
||||
for cut in dir_at..end {
|
||||
let mut t = z[..cut].to_vec();
|
||||
t.extend_from_slice(&z[end..]);
|
||||
let e = Archive::open(&t).err().unwrap_or_else(|| panic!("cut at {cut} opened"));
|
||||
assert!(!e.to_string().is_empty());
|
||||
}
|
||||
// The end record says more entries than there are.
|
||||
let mut t = z.clone();
|
||||
t[end + 8] = 9;
|
||||
t[end + 10] = 9;
|
||||
assert_eq!(Archive::open(&t).err(), Some(ZipError::Damaged("the central directory is cut short")));
|
||||
// Cut short anywhere at all: an error, never a panic.
|
||||
for cut in 0..z.len() {
|
||||
let _ = Archive::open(&z[..cut]).map(|a| a.read("DOMDocument.xml"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_entries_are_refused() {
|
||||
// Two names for one local header (the overlapping-file zip bomb).
|
||||
let mut b = Raw::new("b.xml", b"<a/>", true);
|
||||
b.share = Some(0);
|
||||
let z = write(&[Raw::new("a.xml", b"<a/>", true), b], false);
|
||||
assert!(matches!(Archive::open(&z).err(), Some(ZipError::Overlap(..))), "{:?}", Archive::open(&z).err());
|
||||
// An entry whose stated compressed size runs into the next one.
|
||||
let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false), ("b.xml", b"bbbbbbbbbb", false)]);
|
||||
let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize;
|
||||
z[dir_at + 20] = 20; // a's compressed size, in its central record
|
||||
z[dir_at + 24] = 20;
|
||||
assert!(matches!(Archive::open(&z).err(), Some(ZipError::Overlap(..))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_never_reach_past_their_data() {
|
||||
// An entry's data running into the central directory, or past the end.
|
||||
for size in [64u32, 0xffff_fff0] {
|
||||
let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false)]);
|
||||
let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize;
|
||||
z[dir_at + 20..dir_at + 24].copy_from_slice(&size.to_le_bytes());
|
||||
assert_eq!(Archive::open(&z).err(), Some(ZipError::DamagedEntry("a.xml".into(), "is outside the archive")));
|
||||
}
|
||||
// A local header offset past the end.
|
||||
let mut z = zip(&[("a.xml", b"aaaaaaaaaa", false)]);
|
||||
let dir_at = u32_at(&z, z.len() - 6).unwrap() as usize;
|
||||
z[dir_at + 42..dir_at + 46].copy_from_slice(&0x7fff_0000u32.to_le_bytes());
|
||||
assert_eq!(Archive::open(&z).err(), Some(ZipError::DamagedEntry("a.xml".into(), "has no local header")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lying_sizes_and_checksums_are_damaged() {
|
||||
// Says 100 bytes, inflates to 1000.
|
||||
let body = vec![b'x'; 1000];
|
||||
let mut r = Raw::new("a.xml", &body, true);
|
||||
r.size = Some(100);
|
||||
assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "expands past the size it gives"));
|
||||
// Says 2000, inflates to 1000.
|
||||
let mut r = Raw::new("a.xml", &body, true);
|
||||
r.size = Some(2000);
|
||||
assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "is not the size it gives"));
|
||||
// A stored entry with two sizes.
|
||||
let mut r = Raw::new("a.xml", &body, false);
|
||||
r.size = Some(10);
|
||||
assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "is stored with two different sizes"));
|
||||
// The wrong checksum.
|
||||
let mut r = Raw::new("a.xml", &body, true);
|
||||
r.crc = Some(12345);
|
||||
assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "fails its checksum"));
|
||||
// Garbage instead of deflate data.
|
||||
let mut r = Raw::new("a.xml", &body, true);
|
||||
r.compressed = Some(vec![0xff; 40]);
|
||||
assert_eq!(error(&write(&[r], false)), ZipError::DamagedEntry("a.xml".into(), "has damaged compressed data"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compression_bombs_are_refused() {
|
||||
// A real 64 MB of zeros deflates past the ratio cap: refused before inflating.
|
||||
let zeros = vec![0u8; 64 << 20];
|
||||
let z = zip(&[("bomb.xml", &zeros, true)]);
|
||||
assert!(z.len() < 100_000, "{}", z.len());
|
||||
assert_eq!(Archive::open(&z).err(), Some(ZipError::Bomb("bomb.xml".into())));
|
||||
// A size claim no deflate stream of that length could meet.
|
||||
let mut r = Raw::new("a.xml", &[7; 100], true);
|
||||
r.size = Some(200 << 20);
|
||||
assert_eq!(Archive::open(&write(&[r], false)).err(), Some(ZipError::Bomb("a.xml".into())));
|
||||
// One entry larger than an entry may be, at a believable ratio: refused before inflating.
|
||||
let mut r = Raw::new("big.dat", b"", true);
|
||||
r.compressed = Some(vec![0; 300 << 10]);
|
||||
r.size = Some(MAX_ENTRY as u64 + 1);
|
||||
let z = write(&[r], false);
|
||||
assert_eq!(error(&z), ZipError::TooLarge("big.dat".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_archive_hands_out_at_most_its_budget() {
|
||||
let body = vec![b'a'; 4096];
|
||||
let z = zip(&[("a.xml", &body, true)]);
|
||||
let a = Archive::open(&z).unwrap();
|
||||
a.budget.set(10_000);
|
||||
assert!(a.read("a.xml").is_ok() && a.read("a.xml").is_ok());
|
||||
assert_eq!(a.read("a.xml").err(), Some(ZipError::TooMuch), "a third read passes 10,000 bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsafe_paths_are_refused() {
|
||||
for name in ["../escape.xml", "LIBRARY/../../escape.xml", "/etc/passwd", "\\Windows\\win.ini", "C:\\Windows\\win.ini", "C:escape.xml", "LIBRARY\\..\\..\\x", "a\0b"] {
|
||||
let z = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), (name, b"x", false)]);
|
||||
assert!(matches!(Archive::open(&z).err(), Some(ZipError::Unsafe(_))), "{name:?}: {:?}", Archive::open(&z).err());
|
||||
}
|
||||
// Harmless odd names are tidied, not refused.
|
||||
let z = zip(&[("./LIBRARY//a.xml", b"x", false)]);
|
||||
assert_eq!(Archive::open(&z).unwrap().names().collect::<Vec<_>>(), ["LIBRARY/a.xml"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_names_are_refused() {
|
||||
let z = zip(&[("LIBRARY/a.xml", b"one", false), ("LIBRARY\\a.xml", b"two", false)]);
|
||||
assert_eq!(Archive::open(&z).err(), Some(ZipError::Duplicate("LIBRARY\\a.xml".into())));
|
||||
// Folders listed twice are harmless.
|
||||
let z = zip(&[("LIBRARY/", b"", false), ("LIBRARY\\", b"", false), ("LIBRARY/a.xml", b"one", false)]);
|
||||
assert_eq!(Archive::open(&z).unwrap().counts(), (1, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_nested_folders_are_refused() {
|
||||
let ok = format!("{}a.xml", "f/".repeat(MAX_DEPTH));
|
||||
assert!(Archive::open(&zip(&[(&ok, b"x", false)])).is_ok());
|
||||
let deep = format!("{}a.xml", "f/".repeat(MAX_DEPTH + 1));
|
||||
assert!(matches!(Archive::open(&zip(&[(&deep, b"x", false)])).err(), Some(ZipError::TooDeep(_))));
|
||||
// As deep as a name can be: refused quickly, not recursed into.
|
||||
let deepest = "f/".repeat(30_000);
|
||||
assert!(matches!(Archive::open(&zip(&[(&deepest, b"", false)])).err(), Some(ZipError::TooDeep(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_features_say_what_they_are() {
|
||||
let mut r = Raw::new("a.xml", b"secret", false);
|
||||
r.flags = 1;
|
||||
assert_eq!(error(&write(&[r], false)), ZipError::Unsupported("a.xml".into(), "encryption"));
|
||||
let mut r = Raw::new("a.xml", b"x", false);
|
||||
r.method = Some(14);
|
||||
assert_eq!(error(&write(&[r], false)), ZipError::Unsupported("a.xml".into(), "LZMA compression"));
|
||||
// Split archives.
|
||||
let mut z = zip(&[("a.xml", b"x", false)]);
|
||||
let end = z.len() - 22;
|
||||
z[end + 4] = 1;
|
||||
assert_eq!(Archive::open(&z).err(), Some(ZipError::UnsupportedArchive("split across several files")));
|
||||
// Too many entries for the directory to hold, and more than the cap.
|
||||
let mut z = zip(&[("a.xml", b"x", false)]);
|
||||
let end = z.len() - 22;
|
||||
z[end + 8..end + 12].copy_from_slice(&[0xfe, 0xff, 0xfe, 0xff]);
|
||||
assert!(Archive::open(&z).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip64_archives_open_and_their_damage_is_named() {
|
||||
let mut a = Raw::new("a.xml", b"<a/>", true);
|
||||
a.zip64 = true;
|
||||
let mut b = Raw::new("b.xml", b"<b/>", false);
|
||||
(b.zip64, b.descriptor) = (true, true);
|
||||
let z = write(&[a.clone(), b], true);
|
||||
let arch = Archive::open(&z).unwrap();
|
||||
assert_eq!(arch.read("b.xml").unwrap().unwrap(), b"<b/>");
|
||||
// The locator gone.
|
||||
let mut t = z.clone();
|
||||
let loc = t.len() - 22 - 20;
|
||||
t[loc] = 0;
|
||||
assert_eq!(Archive::open(&t).err(), Some(ZipError::Damaged("the ZIP64 end record is missing")));
|
||||
// An entry that says ZIP64 without the extra field.
|
||||
a.zip64 = false;
|
||||
let mut t = write(&[a], false);
|
||||
let dir_at = u32_at(&t, t.len() - 6).unwrap() as usize;
|
||||
t[dir_at + 24..dir_at + 28].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert_eq!(Archive::open(&t).err(), Some(ZipError::DamagedEntry("a.xml".into(), "has no ZIP64 sizes")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_read_as_sentences() {
|
||||
let all = [
|
||||
ZipError::NotZip,
|
||||
ZipError::Damaged("the central directory is cut short"),
|
||||
ZipError::DamagedEntry("a.xml".into(), "fails its checksum"),
|
||||
ZipError::UnsupportedArchive("split across several files"),
|
||||
ZipError::Unsupported("a.xml".into(), "encryption"),
|
||||
ZipError::TooLarge("a.xml".into()),
|
||||
ZipError::TooMuch,
|
||||
ZipError::TooMany,
|
||||
ZipError::Bomb("a.xml".into()),
|
||||
ZipError::Overlap("a.xml".into(), "b.xml".into()),
|
||||
ZipError::Unsafe("../a.xml".into()),
|
||||
ZipError::Duplicate("a.xml".into()),
|
||||
ZipError::TooDeep("f/f/a.xml".into()),
|
||||
];
|
||||
for e in all {
|
||||
let s = e.to_string();
|
||||
assert!(s.len() > 12 && !s.contains("{") && s.chars().next().is_some_and(|c| !c.is_uppercase() || c == 'A'), "{s}");
|
||||
}
|
||||
assert_eq!(ZipError::TooMuch.to_string(), "the archive asks for more than 1024 MB in all");
|
||||
}
|
||||
@@ -83,7 +83,7 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[
|
||||
|
||||
/// What each package keeps without running (ADR 0013 tier 1: scripts outside the subset, and
|
||||
/// class names); packages not listed keep nothing.
|
||||
const KEPT: &[(&str, &[(&str, usize)])] = &[("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)])];
|
||||
const KEPT: &[(&str, &[(&str, usize)])] = &[("bitmaps", &[("library folders", 1)]), ("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)]), ("symbols", &[("library folders", 1)])];
|
||||
|
||||
/// The frame scripts each package brings that run (ADR 0013 tier 2: in the subset).
|
||||
const RUNS: &[(&str, &[(&str, usize)])] = &[
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 8.9 KiB After Width: | Height: | Size: 7.8 KiB |
@@ -0,0 +1,327 @@
|
||||
//! The XFL corpus as `.fla` archives (ADR 0054): every package, packed every way zip writers
|
||||
//! lay one out, imports exactly as its folder does (same document, same report); hostile
|
||||
//! archives built from the corpus never panic and fail with a readable error; and a generated
|
||||
//! 50 MB `.fla` measures import time (`cargo test --release -p anicraft-xfl --test fla --
|
||||
//! --ignored --nocapture`). The golden renders of the `.fla` forms are checked in
|
||||
//! `crates/engine/tests/xfl_corpus.rs`.
|
||||
|
||||
#[path = "support/fla.rs"]
|
||||
mod pack;
|
||||
|
||||
use anicraft_doc::{Document, evaluate};
|
||||
use anicraft_text::Fonts;
|
||||
use anicraft_xfl::{Report, XflError, import_fla_with_fonts, import_with_fonts};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn corpus() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus")
|
||||
}
|
||||
|
||||
fn cases() -> Vec<String> {
|
||||
let mut out: Vec<String> = std::fs::read_dir(corpus()).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
fn no_fonts() -> Fonts {
|
||||
Fonts::from_faces(Vec::new())
|
||||
}
|
||||
|
||||
fn from_folder(files: &BTreeMap<String, Vec<u8>>, fonts: &Fonts) -> (Document, Report) {
|
||||
let read = |p: &str| -> Result<Option<Vec<u8>>, XflError> { Ok(files.get(p).cloned()) };
|
||||
import_with_fonts(&read, fonts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_package_imports_identically_from_every_fla_variant() {
|
||||
let fonts = no_fonts();
|
||||
let mut checked = 0;
|
||||
for case in cases() {
|
||||
let files = pack::package(&corpus().join(&case));
|
||||
let (doc, report) = from_folder(&files, &fonts);
|
||||
for v in pack::VARIANTS {
|
||||
let fla = pack::pack(&files, v);
|
||||
let (d, r) = import_fla_with_fonts(&fla, &fonts).unwrap_or_else(|e| panic!("{case}, {}: {e}", v.name));
|
||||
assert!(d == doc, "{case}, {}: the document differs from the folder's", v.name);
|
||||
assert_eq!(r, report, "{case}, {}: the report differs", v.name);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, cases().len() * pack::VARIANTS.len());
|
||||
}
|
||||
|
||||
/// From disk, through the same entry point the app uses, with this computer's fonts: the
|
||||
/// folder, its `.xfl` file, its `DOMDocument.xml`, the `.fla`, and the `.fla` renamed.
|
||||
#[test]
|
||||
fn every_package_opens_the_same_from_disk_in_every_form() {
|
||||
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-fla-forms");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for case in cases() {
|
||||
let folder = corpus().join(&case);
|
||||
let (doc, report) = anicraft_xfl::import_path(&folder).unwrap_or_else(|e| panic!("{case}: {e}"));
|
||||
let fla = dir.join(format!("{case}.fla"));
|
||||
std::fs::write(&fla, pack::pack(&pack::package(&folder), &pack::VARIANTS[0])).unwrap();
|
||||
let renamed = dir.join(format!("{case} (copy).zip"));
|
||||
std::fs::copy(&fla, &renamed).unwrap();
|
||||
for path in [folder.join(format!("{case}.xfl")), folder.join("DOMDocument.xml"), fla, renamed] {
|
||||
let (d, r) = anicraft_xfl::import_path(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
assert!(d == doc && r == report, "{} opens differently from its folder", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Names outside ASCII, in every encoding: the symbols package with a library file renamed.
|
||||
#[test]
|
||||
fn non_ascii_names_import_identically_in_every_encoding() {
|
||||
let fonts = no_fonts();
|
||||
let mut files = pack::package(&corpus().join("symbols"));
|
||||
let doc_xml = String::from_utf8(files["DOMDocument.xml"].clone()).unwrap();
|
||||
let old = files.keys().find(|p| p.starts_with("LIBRARY/") && p.ends_with(".xml")).unwrap().clone();
|
||||
let href = old.trim_start_matches("LIBRARY/").to_string();
|
||||
let new_href = format!("Café ü/Ünïcödé ½ {href}");
|
||||
assert!(doc_xml.contains(&format!("href=\"{href}\"")), "{href}");
|
||||
files.insert("DOMDocument.xml".into(), doc_xml.replace(&format!("href=\"{href}\""), &format!("href=\"{new_href}\"")).into_bytes());
|
||||
let body = files.remove(&old).unwrap();
|
||||
files.insert(format!("LIBRARY/{new_href}"), body);
|
||||
let (doc, report) = from_folder(&files, &fonts);
|
||||
assert!(doc.library.len() >= 5, "the renamed symbol still imports");
|
||||
for v in pack::VARIANTS {
|
||||
let (d, r) = import_fla_with_fonts(&pack::pack(&files, v), &fonts).unwrap_or_else(|e| panic!("{}: {e}", v.name));
|
||||
assert!(d == doc && r == report, "{}", v.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_binary_fla_says_what_to_do() {
|
||||
let mut old = vec![0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
|
||||
old.resize(4096, 0);
|
||||
let e = anicraft_xfl::import_fla(&old).err().unwrap().to_string();
|
||||
assert!(e.contains("Flash CS4 or earlier") && e.contains("save it again"), "{e}");
|
||||
let e = anicraft_xfl::import_fla(b"PK\x03\x04 cut short").err().unwrap().to_string();
|
||||
assert_eq!(e, "not a zip archive (no end-of-directory record)");
|
||||
}
|
||||
|
||||
/// A small deterministic generator (xorshift64*).
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
(self.next() % n.max(1) as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// Imports a hostile archive: it may fail, with a readable error, but must not panic, and
|
||||
/// what it imports must evaluate.
|
||||
fn survive(fla: &[u8], fonts: &Fonts, what: &str, errors: &mut BTreeMap<String, usize>) {
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match import_fla_with_fonts(fla, fonts) {
|
||||
Ok((doc, _)) => {
|
||||
let n = doc.frame_count();
|
||||
for f in [0, n / 2, n.saturating_sub(1)] {
|
||||
let _ = evaluate(&doc, f);
|
||||
}
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
// Grouped by kind for the summary: `Zip(Bomb`, `Xml(…`.
|
||||
let kind: String = format!("{e:?}").split('(').take(2).collect::<Vec<_>>().join("(");
|
||||
Some((e.to_string(), kind))
|
||||
}
|
||||
}));
|
||||
match result {
|
||||
Err(_) => panic!("panicked on {what}"),
|
||||
Ok(Some((e, kind))) => {
|
||||
assert!(e.len() > 10 && !e.contains("Error") && !e.contains('{'), "{what}: an unreadable error: {e:?}");
|
||||
*errors.entry(kind).or_default() += 1;
|
||||
}
|
||||
Ok(None) => *errors.entry("(imported)".into()).or_default() += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Offsets of every central record in `z` (found through the end record, or its ZIP64 form).
|
||||
fn central_records(z: &[u8]) -> Vec<usize> {
|
||||
let end = z.len() - 22;
|
||||
let mut at = u32::from_le_bytes(z[end + 16..end + 20].try_into().unwrap()) as usize;
|
||||
if at == u32::MAX as usize {
|
||||
let record = u64::from_le_bytes(z[end - 12..end - 4].try_into().unwrap()) as usize;
|
||||
at = u64::from_le_bytes(z[record + 48..record + 56].try_into().unwrap()) as usize;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut i = at;
|
||||
while z.get(i..i + 4) == Some(&[0x50, 0x4b, 1, 2]) {
|
||||
out.push(i);
|
||||
let n = |o: usize| u16::from_le_bytes([z[i + o], z[i + o + 1]]) as usize;
|
||||
i += 46 + n(28) + n(30) + n(32);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A change to an archive's entries before it is written.
|
||||
type Edit = Box<dyn Fn(&mut Vec<pack::Raw>)>;
|
||||
|
||||
/// Each corpus package as a `.fla`, attacked: every header field of every entry set to edge
|
||||
/// values, random bytes changed in the headers and anywhere, cut short, entries pointed at each
|
||||
/// other, and names made unsafe.
|
||||
#[test]
|
||||
fn hostile_fla_archives_never_panic_and_fail_readably() {
|
||||
let fonts = no_fonts();
|
||||
let start = std::time::Instant::now();
|
||||
let mut errors = BTreeMap::new();
|
||||
let mut variants = 0;
|
||||
for case in cases() {
|
||||
let files = pack::package(&corpus().join(&case));
|
||||
for v in [&pack::VARIANTS[0], &pack::VARIANTS[7]] {
|
||||
let z = pack::pack(&files, v);
|
||||
let mut rng = Rng(0x9E37_79B9_7F4A_7C15 ^ (case.len() as u64) << 20 ^ z.len() as u64);
|
||||
let records = central_records(&z);
|
||||
assert!(records.len() >= files.len(), "{case}");
|
||||
// Header fields at edge values: (offset in the central record, width).
|
||||
const FIELDS: &[(usize, usize)] = &[(8, 2), (10, 2), (16, 4), (20, 4), (24, 4), (28, 2), (30, 2), (32, 2), (34, 2), (42, 4)];
|
||||
for &rec in records.iter().take(6) {
|
||||
for &(off, width) in FIELDS {
|
||||
for value in [0u32, 1, 0x7f, 0xffff, 0x7fff_ffff, 0xffff_ffff, rng.next() as u32] {
|
||||
let mut t = z.clone();
|
||||
t[rec + off..rec + off + width].copy_from_slice(&value.to_le_bytes()[..width]);
|
||||
survive(&t, &fonts, &format!("{case}: record at {rec}, field {off} = {value:#x}"), &mut errors);
|
||||
variants += 1;
|
||||
}
|
||||
}
|
||||
// The local header's lengths too.
|
||||
let local = u32::from_le_bytes(z[rec + 42..rec + 46].try_into().unwrap()) as usize;
|
||||
for (off, value) in [(26usize, 0xffffu16), (28, 0xffff), (28, 0), (18, 0xffff), (22, 0)] {
|
||||
let mut t = z.clone();
|
||||
if let Some(f) = t.get_mut(local + off..local + off + 2) {
|
||||
f.copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
survive(&t, &fonts, &format!("{case}: local header at {local}, field {off}"), &mut errors);
|
||||
variants += 1;
|
||||
}
|
||||
}
|
||||
// Random bytes in the central directory and end record, then anywhere.
|
||||
let dir_at = records.first().copied().unwrap_or(0);
|
||||
for n in 0..60 {
|
||||
let mut t = z.clone();
|
||||
let lo = if n < 40 { dir_at } else { 0 };
|
||||
for _ in 0..1 + rng.below(4) {
|
||||
let i = lo + rng.below(t.len() - lo);
|
||||
t[i] = rng.next() as u8;
|
||||
}
|
||||
survive(&t, &fonts, &format!("{case}: random bytes #{n}"), &mut errors);
|
||||
variants += 1;
|
||||
}
|
||||
// Cut short.
|
||||
for k in 0..24 {
|
||||
survive(&z[..z.len() * k / 24], &fonts, &format!("{case}: cut at {k}/24"), &mut errors);
|
||||
variants += 1;
|
||||
}
|
||||
}
|
||||
// Built hostile: names that leave the package, duplicates, overlaps, lying sizes.
|
||||
let mut entries = pack::entries(&files, &pack::VARIANTS[0]);
|
||||
let last = entries.len() - 1;
|
||||
let edits: Vec<(&str, Edit)> = vec![
|
||||
("a .. name", Box::new(move |e| e[last].name = b"LIBRARY/../../../x.xml".to_vec())),
|
||||
("an absolute name", Box::new(move |e| e[last].name = b"/etc/x.xml".to_vec())),
|
||||
("a drive name", Box::new(move |e| e[last].name = b"C:\\x.xml".to_vec())),
|
||||
("a duplicate", Box::new(|e| e.push(e[1].clone()))),
|
||||
("a duplicate by separator", Box::new(|e| {
|
||||
let mut d = e[1].clone();
|
||||
d.name = d.name.iter().map(|&c| if c == b'/' { b'\\' } else { c }).collect();
|
||||
e.push(d);
|
||||
})),
|
||||
("overlapping entries", Box::new(|e| {
|
||||
let mut d = e[1].clone();
|
||||
d.name = b"other.xml".to_vec();
|
||||
d.share = Some(1);
|
||||
e.push(d);
|
||||
})),
|
||||
("a lying size", Box::new(|e| e[1].size = Some(3))),
|
||||
("a lying checksum", Box::new(|e| e[1].crc = Some(1))),
|
||||
("a ratio bomb", Box::new(|e| e[1].size = Some(200 << 20))),
|
||||
("deep folders", Box::new(|e| e[1].name = "d/".repeat(200).into_bytes())),
|
||||
];
|
||||
for (what, edit) in &edits {
|
||||
let mut t = entries.clone();
|
||||
edit(&mut t);
|
||||
let z = pack::write(&t, false);
|
||||
let before = errors.get("(imported)").copied();
|
||||
survive(&z, &fonts, &format!("{case}: {what}"), &mut errors);
|
||||
assert_eq!(errors.get("(imported)").copied(), before, "{case}: {what} imported");
|
||||
variants += 1;
|
||||
}
|
||||
entries.clear();
|
||||
}
|
||||
assert!(variants > 5000, "{variants}");
|
||||
eprintln!("{variants} hostile .fla archives in {:?}: {errors:#?}", start.elapsed());
|
||||
}
|
||||
|
||||
/// A generated `.fla` of about 50 MB: 400 symbols with long edge lists (deflated XML) and 24
|
||||
/// noisy PNG bitmaps (stored), placed on a 240-frame timeline.
|
||||
fn big_fla() -> (Vec<u8>, usize) {
|
||||
let mut files = BTreeMap::new();
|
||||
let mut rng = Rng(42);
|
||||
let mut includes = String::new();
|
||||
for s in 0..400 {
|
||||
let mut edges = String::new();
|
||||
for e in 0..600 {
|
||||
let (x, y) = (rng.below(20_000), rng.below(20_000));
|
||||
edges.push_str(&format!("<Edge fillStyle1=\"1\" edges=\"!{x} {y}|{} {}|{} {}\"/>", x + 200, y + e, x + 100, y + 300));
|
||||
}
|
||||
let xml = format!("<DOMSymbolItem name=\"Symbol {s}\"><timeline><DOMTimeline name=\"Symbol {s}\"><layers><DOMLayer name=\"L\"><frames><DOMFrame index=\"0\"><elements><DOMShape><fills><FillStyle index=\"1\"><SolidColor color=\"#{:06X}\"/></FillStyle></fills><edges>{edges}</edges></DOMShape></elements></DOMFrame></frames></DOMLayer></layers></DOMTimeline></timeline></DOMSymbolItem>", rng.next() & 0xffffff);
|
||||
files.insert(format!("LIBRARY/Symbols/Symbol {s}.xml"), xml.into_bytes());
|
||||
includes.push_str(&format!("<Include href=\"Symbols/Symbol {s}.xml\"/>"));
|
||||
}
|
||||
let mut media = String::new();
|
||||
for b in 0..24 {
|
||||
let (w, h) = (1024u32, 512u32);
|
||||
let pixels: Vec<u8> = (0..w * h * 4).map(|_| rng.next() as u8).collect();
|
||||
let mut png = Vec::new();
|
||||
{
|
||||
let mut enc = png::Encoder::new(&mut png, w, h);
|
||||
enc.set_color(png::ColorType::Rgba);
|
||||
enc.set_compression(png::Compression::Fast);
|
||||
let mut wr = enc.write_header().unwrap();
|
||||
wr.write_image_data(&pixels).unwrap();
|
||||
}
|
||||
files.insert(format!("LIBRARY/Images/noise {b}.png"), png);
|
||||
media.push_str(&format!("<DOMBitmapItem name=\"Images/noise {b}.png\" href=\"Images/noise {b}.png\"/>"));
|
||||
}
|
||||
let mut frames = String::new();
|
||||
for f in 0..240 {
|
||||
frames.push_str(&format!("<DOMFrame index=\"{f}\"><elements><DOMSymbolInstance libraryItemName=\"Symbol {}\"/><DOMBitmapInstance libraryItemName=\"Images/noise {}.png\"/></elements></DOMFrame>", f % 400, f % 24));
|
||||
}
|
||||
let doc = format!("<DOMDocument width=\"1920\" height=\"1080\" frameRate=\"24\"><media>{media}</media><symbols>{includes}</symbols><timelines><DOMTimeline name=\"Scene 1\"><layers><DOMLayer name=\"Layer 1\"><frames>{frames}</frames></DOMLayer></layers></DOMTimeline></timelines></DOMDocument>");
|
||||
files.insert("DOMDocument.xml".into(), doc.into_bytes());
|
||||
let n = files.len();
|
||||
(pack::pack(&files, &pack::VARIANTS[2]), n)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "a measurement: run with --release -- --ignored --nocapture"]
|
||||
fn measure_importing_a_50_mb_fla() {
|
||||
let (fla, files) = big_fla();
|
||||
let fonts = no_fonts();
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let t = std::time::Instant::now();
|
||||
let a = anicraft_xfl::zip::Archive::open(&fla).unwrap();
|
||||
let open = t.elapsed();
|
||||
let names: Vec<String> = a.names().map(str::to_string).collect();
|
||||
let t = std::time::Instant::now();
|
||||
let bytes: usize = names.iter().map(|n| a.read(n).unwrap().map_or(0, |b| b.len())).sum();
|
||||
let read = t.elapsed();
|
||||
let t = std::time::Instant::now();
|
||||
let (doc, _) = import_fla_with_fonts(&fla, &fonts).unwrap();
|
||||
let import = t.elapsed();
|
||||
assert_eq!((doc.library.len(), doc.bitmaps.len()), (400, 24));
|
||||
times.push((open, read, bytes, import));
|
||||
}
|
||||
eprintln!("{:.1} MB .fla, {files} files:", fla.len() as f64 / 1e6);
|
||||
for (open, read, bytes, import) in times {
|
||||
eprintln!(" open {open:?}, read every entry {read:?} ({:.1} MB, {:.0} MB/s), import {import:?}", bytes as f64 / 1e6, bytes as f64 / 1e6 / read.as_secs_f64());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Test support: packs an XFL package into `.fla` (zip) archives in memory, in each of the ways
|
||||
//! zip writers lay one out (ADR 0054), and writes hand-made entries for hostile archives.
|
||||
//!
|
||||
//! Written from the published format (PKWARE APPNOTE 6.3), independently of the reader in
|
||||
//! `src/zip.rs` (it has its own checksum), so a misreading in one is caught by the other.
|
||||
//! Shared by the xfl crate's unit and corpus tests and the engine's golden tests (`#[path]`).
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// How a variant compresses its entries.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Compression {
|
||||
Deflate,
|
||||
Stored,
|
||||
/// XML deflated, images stored (as most writers do), the rest alternating.
|
||||
Mixed,
|
||||
}
|
||||
|
||||
/// How a variant writes entry names.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Names {
|
||||
/// UTF-8 with flag bit 11 set.
|
||||
Utf8Flag,
|
||||
/// UTF-8 without the flag (common, though the format says CP437).
|
||||
Utf8Unflagged,
|
||||
/// CP437 bytes without the flag, as the format specifies (names CP437 can't spell are
|
||||
/// written as UTF-8 with the flag).
|
||||
Cp437,
|
||||
/// An ASCII stand-in name with the real one in the Info-ZIP Unicode path field.
|
||||
UnicodeExtra,
|
||||
}
|
||||
|
||||
/// One way of packing a package.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Variant {
|
||||
pub name: &'static str,
|
||||
pub compression: Compression,
|
||||
/// An entry for every folder, before the files in it.
|
||||
pub folders: bool,
|
||||
/// The `mimetype` entry first, stored, as Animate writes it.
|
||||
pub mimetype: bool,
|
||||
/// `\` between folders, as some Windows tools write.
|
||||
pub backslashes: bool,
|
||||
pub names: Names,
|
||||
/// Sizes and checksums after the data (bit 3), as streaming writers do.
|
||||
pub descriptors: bool,
|
||||
/// ZIP64 sizes on every entry and a ZIP64 end record.
|
||||
pub zip64: bool,
|
||||
}
|
||||
|
||||
const BASE: Variant = Variant { name: "", compression: Compression::Deflate, folders: false, mimetype: false, backslashes: false, names: Names::Utf8Flag, descriptors: false, zip64: false };
|
||||
|
||||
/// Every variant each corpus package is checked in.
|
||||
pub const VARIANTS: &[Variant] = &[
|
||||
Variant { name: "as Animate writes it (mimetype first, deflated)", mimetype: true, ..BASE },
|
||||
Variant { name: "stored", compression: Compression::Stored, ..BASE },
|
||||
Variant { name: "mixed, with folder entries", compression: Compression::Mixed, folders: true, mimetype: true, ..BASE },
|
||||
Variant { name: "Windows separators, unflagged UTF-8 names", backslashes: true, folders: true, names: Names::Utf8Unflagged, ..BASE },
|
||||
Variant { name: "CP437 names", names: Names::Cp437, compression: Compression::Mixed, ..BASE },
|
||||
Variant { name: "Unicode path fields", names: Names::UnicodeExtra, ..BASE },
|
||||
Variant { name: "data descriptors", descriptors: true, compression: Compression::Mixed, ..BASE },
|
||||
Variant { name: "ZIP64", zip64: true, compression: Compression::Mixed, ..BASE },
|
||||
Variant { name: "everything at once", compression: Compression::Mixed, folders: true, mimetype: true, backslashes: true, names: Names::Cp437, descriptors: true, zip64: true },
|
||||
];
|
||||
|
||||
/// One entry as written. Fields a hostile test may change are public.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Raw {
|
||||
/// The name's bytes as stored.
|
||||
pub name: Vec<u8>,
|
||||
/// The uncompressed bytes.
|
||||
pub body: Vec<u8>,
|
||||
pub deflate: bool,
|
||||
/// General purpose flag bits besides 3 and 11 (bit 0: encrypted).
|
||||
pub flags: u16,
|
||||
pub utf8: bool,
|
||||
pub descriptor: bool,
|
||||
pub zip64: bool,
|
||||
/// Overrides: the method, the uncompressed size and the checksum the headers give.
|
||||
pub method: Option<u16>,
|
||||
pub size: Option<u64>,
|
||||
pub crc: Option<u32>,
|
||||
/// Extra field bytes in the central directory (besides ZIP64's).
|
||||
pub extra: Vec<u8>,
|
||||
/// Points this entry's central record at entry `n`'s local header instead of its own.
|
||||
pub share: Option<usize>,
|
||||
/// Stored as compressed bytes: these instead of compressing `body`.
|
||||
pub compressed: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Raw {
|
||||
pub fn new(name: &str, body: &[u8], deflate: bool) -> Raw {
|
||||
Raw { name: name.as_bytes().to_vec(), body: body.to_vec(), deflate, utf8: true, ..Raw::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// CRC-32 (ISO-HDLC), bit by bit.
|
||||
pub fn crc32(data: &[u8]) -> u32 {
|
||||
let mut c = !0u32;
|
||||
for &b in data {
|
||||
c ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 != 0 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
}
|
||||
|
||||
/// `s` in CP437, if every character is in it.
|
||||
pub fn cp437(s: &str) -> Option<Vec<u8>> {
|
||||
const HIGH: &str = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u{a0}";
|
||||
s.chars().map(|c| if c.is_ascii() { Some(c as u8) } else { HIGH.chars().position(|h| h == c).map(|i| 0x80 + i as u8) }).collect()
|
||||
}
|
||||
|
||||
fn le16(out: &mut Vec<u8>, v: u16) {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
fn le32(out: &mut Vec<u8>, v: u32) {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
fn le64(out: &mut Vec<u8>, v: u64) {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
/// Writes `entries` as a zip archive, with a ZIP64 end record if `zip64_end`.
|
||||
pub fn write(entries: &[Raw], zip64_end: bool) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut central = Vec::new();
|
||||
let mut offsets = Vec::new();
|
||||
// (time, date): 2025-11-11 12:00.
|
||||
let (time, date) = (0x6000u16, 0x5B6Bu16);
|
||||
for e in entries {
|
||||
let data = match &e.compressed {
|
||||
Some(c) => c.clone(),
|
||||
None if e.deflate => miniz_oxide::deflate::compress_to_vec(&e.body, 6),
|
||||
None => e.body.clone(),
|
||||
};
|
||||
let method = e.method.unwrap_or(if e.deflate { 8 } else { 0 });
|
||||
let crc = e.crc.unwrap_or_else(|| crc32(&e.body));
|
||||
let size = e.size.unwrap_or(e.body.len() as u64);
|
||||
let comp = data.len() as u64;
|
||||
let flags = e.flags | if e.descriptor { 8 } else { 0 } | if e.utf8 { 0x800 } else { 0 };
|
||||
let version: u16 = if e.zip64 { 45 } else { 20 };
|
||||
let offset = out.len() as u64;
|
||||
offsets.push(offset);
|
||||
// The local header.
|
||||
le32(&mut out, 0x0403_4b50);
|
||||
le16(&mut out, version);
|
||||
le16(&mut out, flags);
|
||||
le16(&mut out, method);
|
||||
le16(&mut out, time);
|
||||
le16(&mut out, date);
|
||||
let local_extra = if e.zip64 {
|
||||
let mut x = Vec::new();
|
||||
le16(&mut x, 1);
|
||||
le16(&mut x, 16);
|
||||
le64(&mut x, if e.descriptor { 0 } else { size });
|
||||
le64(&mut x, if e.descriptor { 0 } else { comp });
|
||||
x
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if e.descriptor {
|
||||
out.extend_from_slice(&[0; 12]);
|
||||
} else {
|
||||
le32(&mut out, crc);
|
||||
le32(&mut out, if e.zip64 { u32::MAX } else { comp as u32 });
|
||||
le32(&mut out, if e.zip64 { u32::MAX } else { size as u32 });
|
||||
}
|
||||
le16(&mut out, e.name.len() as u16);
|
||||
le16(&mut out, local_extra.len() as u16);
|
||||
out.extend_from_slice(&e.name);
|
||||
out.extend_from_slice(&local_extra);
|
||||
out.extend_from_slice(&data);
|
||||
if e.descriptor {
|
||||
le32(&mut out, 0x0807_4b50);
|
||||
le32(&mut out, crc);
|
||||
if e.zip64 {
|
||||
le64(&mut out, comp);
|
||||
le64(&mut out, size);
|
||||
} else {
|
||||
le32(&mut out, comp as u32);
|
||||
le32(&mut out, size as u32);
|
||||
}
|
||||
}
|
||||
// Its central record.
|
||||
let at = e.share.and_then(|n| offsets.get(n).copied()).unwrap_or(offset);
|
||||
let mut extra = Vec::new();
|
||||
if e.zip64 {
|
||||
le16(&mut extra, 1);
|
||||
le16(&mut extra, 24);
|
||||
le64(&mut extra, size);
|
||||
le64(&mut extra, comp);
|
||||
le64(&mut extra, at);
|
||||
}
|
||||
extra.extend_from_slice(&e.extra);
|
||||
le32(&mut central, 0x0201_4b50);
|
||||
le16(&mut central, version);
|
||||
le16(&mut central, version);
|
||||
le16(&mut central, flags);
|
||||
le16(&mut central, method);
|
||||
le16(&mut central, time);
|
||||
le16(&mut central, date);
|
||||
le32(&mut central, crc);
|
||||
le32(&mut central, if e.zip64 { u32::MAX } else { comp as u32 });
|
||||
le32(&mut central, if e.zip64 { u32::MAX } else { size as u32 });
|
||||
le16(&mut central, e.name.len() as u16);
|
||||
le16(&mut central, extra.len() as u16);
|
||||
le16(&mut central, 0); // comment
|
||||
le16(&mut central, 0); // disk
|
||||
le16(&mut central, 0); // internal attributes
|
||||
let folder = e.name.last().is_some_and(|&c| c == b'/' || c == b'\\');
|
||||
le32(&mut central, if folder { 0x10 } else { 0 });
|
||||
le32(&mut central, if e.zip64 { u32::MAX } else { at as u32 });
|
||||
central.extend_from_slice(&e.name);
|
||||
central.extend_from_slice(&extra);
|
||||
}
|
||||
let dir_at = out.len() as u64;
|
||||
out.extend_from_slice(¢ral);
|
||||
let n = entries.len() as u64;
|
||||
if zip64_end {
|
||||
let record = out.len() as u64;
|
||||
le32(&mut out, 0x0606_4b50);
|
||||
le64(&mut out, 44);
|
||||
le16(&mut out, 45);
|
||||
le16(&mut out, 45);
|
||||
le32(&mut out, 0);
|
||||
le32(&mut out, 0);
|
||||
le64(&mut out, n);
|
||||
le64(&mut out, n);
|
||||
le64(&mut out, central.len() as u64);
|
||||
le64(&mut out, dir_at);
|
||||
le32(&mut out, 0x0706_4b50);
|
||||
le32(&mut out, 0);
|
||||
le64(&mut out, record);
|
||||
le32(&mut out, 1);
|
||||
}
|
||||
le32(&mut out, 0x0605_4b50);
|
||||
le32(&mut out, 0); // disks
|
||||
let (count, size, at) = if zip64_end { (u16::MAX, u32::MAX, u32::MAX) } else { (n as u16, central.len() as u32, dir_at as u32) };
|
||||
le16(&mut out, count);
|
||||
le16(&mut out, count);
|
||||
le32(&mut out, size);
|
||||
le32(&mut out, at);
|
||||
le16(&mut out, 0);
|
||||
out
|
||||
}
|
||||
|
||||
/// The entries `files` (paths inside the package) become in `v`.
|
||||
pub fn entries(files: &BTreeMap<String, Vec<u8>>, v: &Variant) -> Vec<Raw> {
|
||||
let mut out = Vec::new();
|
||||
let named = |path: &str, body: &[u8], deflate: bool| {
|
||||
let shown = if v.backslashes { path.replace('/', "\\") } else { path.to_string() };
|
||||
let mut r = Raw::new(&shown, body, deflate);
|
||||
r.descriptor = v.descriptors;
|
||||
r.zip64 = v.zip64;
|
||||
match v.names {
|
||||
Names::Utf8Flag => {}
|
||||
Names::Utf8Unflagged => r.utf8 = false,
|
||||
Names::Cp437 => {
|
||||
if let Some(b) = cp437(&shown) {
|
||||
(r.name, r.utf8) = (b, false);
|
||||
}
|
||||
}
|
||||
Names::UnicodeExtra => {
|
||||
let stand_in: Vec<u8> = shown.chars().map(|c| if c.is_ascii() { c as u8 } else { b'_' }).collect();
|
||||
le16(&mut r.extra, 0x7075);
|
||||
le16(&mut r.extra, (5 + shown.len()) as u16);
|
||||
r.extra.push(1);
|
||||
le32(&mut r.extra, crc32(&stand_in));
|
||||
r.extra.extend_from_slice(shown.as_bytes());
|
||||
(r.name, r.utf8) = (stand_in, false);
|
||||
}
|
||||
}
|
||||
r
|
||||
};
|
||||
if v.mimetype {
|
||||
out.push(named("mimetype", b"application/vnd.adobe.xfl", false));
|
||||
}
|
||||
let mut made = std::collections::BTreeSet::new();
|
||||
for (i, (path, body)) in files.iter().enumerate() {
|
||||
if v.folders {
|
||||
let parts: Vec<&str> = path.split('/').collect();
|
||||
for k in 1..parts.len() {
|
||||
let folder = format!("{}/", parts[..k].join("/"));
|
||||
if made.insert(folder.clone()) {
|
||||
out.push(named(&folder, b"", false));
|
||||
}
|
||||
}
|
||||
}
|
||||
let image = [".png", ".jpg", ".jpeg", ".gif"].iter().any(|x| path.to_ascii_lowercase().ends_with(x));
|
||||
let deflate = match v.compression {
|
||||
Compression::Deflate => true,
|
||||
Compression::Stored => false,
|
||||
Compression::Mixed => path.ends_with(".xml") || (!image && i % 2 == 0),
|
||||
};
|
||||
out.push(named(path, body, deflate));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `files` packed as a `.fla` in variant `v`.
|
||||
pub fn pack(files: &BTreeMap<String, Vec<u8>>, v: &Variant) -> Vec<u8> {
|
||||
write(&entries(files, v), v.zip64)
|
||||
}
|
||||
|
||||
/// A package folder's files by their path inside it, leaving out its `golden/` renders.
|
||||
pub fn package(dir: &std::path::Path) -> BTreeMap<String, Vec<u8>> {
|
||||
fn walk(dir: &std::path::Path, prefix: &str, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||
let mut list: Vec<_> = std::fs::read_dir(dir).map(|r| r.flatten().collect()).unwrap_or_default();
|
||||
list.sort_by_key(|e| e.file_name());
|
||||
for e in list {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
let path = if prefix.is_empty() { name.clone() } else { format!("{prefix}/{name}") };
|
||||
if e.path().is_dir() {
|
||||
if path != "golden" {
|
||||
walk(&e.path(), &path, out);
|
||||
}
|
||||
} else if let Ok(b) = std::fs::read(e.path()) {
|
||||
out.insert(path, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
walk(dir, "", &mut out);
|
||||
out
|
||||
}
|
||||
@@ -25,6 +25,10 @@ work yet. Design decisions are in ADR 0022; the rules for contributors are in
|
||||
shortcut works, including Enter (play) and the arrows (nudge). With a button or checkbox
|
||||
focused, the other shortcuts still work but Enter, Space and the arrows belong to it. In a
|
||||
text field every key types. Esc leaves a field.
|
||||
* **Library items without dragging** (ADR 0053): after clicking a Library row, **Enter** places
|
||||
the selected items at the centre of the view on the active layer (sounds on its keyframe at
|
||||
the playhead), as dragging them onto the stage does; F2 renames and Delete deletes. Place on
|
||||
Stage is also a button under the list and in each row's right-click menu.
|
||||
* Frames are reached with `,` and `.` (previous and next), Home and End, F5/F6/F7 to insert,
|
||||
and Shift+`,`/`.`; layers with the layer rows (Tab from the timeline anchor) and the
|
||||
Up/Down buttons under them.
|
||||
|
||||
@@ -59,3 +59,10 @@ own timelines, nested to any depth.
|
||||
must never panic (`crates/xfl/tests/corpus.rs`), and golden renders of chosen frames by the
|
||||
CPU oracle with hand-worked colour probes (`crates/engine/tests/xfl_corpus.rs`, regenerated
|
||||
with `UPDATE_GOLDENS=1`). A feature the importer learns gets a corpus file in the same change.
|
||||
* **`.fla` archives** (ADR 0054): every corpus package, packed by an independent in-memory zip
|
||||
writer in nine layouts (Animate's `mimetype` first, stored, mixed with folder entries,
|
||||
Windows separators, CP437 and Unicode-path names, data descriptors, ZIP64, all at once),
|
||||
imports identically to its folder and renders the same goldens; a fuzz of 9,664 hostile
|
||||
archives built from the corpus never panics, and the zip reader refuses overlapping entries,
|
||||
lying sizes and checksums, ratio bombs, unsafe and duplicate paths and deep nesting with a
|
||||
readable error (`crates/xfl/src/zip_tests.rs`, `crates/xfl/tests/fla.rs`).
|
||||
@@ -95,6 +95,8 @@ hand from the public descriptions of the format.
|
||||
it can share our misreadings of the format. Where we were unsure (the default symbol type,
|
||||
the custom ease and shape-hint forms) this ADR says so, and a file saved by Animate that
|
||||
disagrees should become a corpus fix, not a special case.
|
||||
* Not in this slice: `.fla` (zip) variants of the corpus, sound and video items, motion tweens
|
||||
* `.fla` (zip) variants of the corpus are checked since ADR 0054: every package, packed nine
|
||||
ways, imports identically to its folder and renders the same goldens.
|
||||
* Not in this slice: sound and video items, motion tweens
|
||||
with property curves, and per-character text styles (all reported, and kept for their own
|
||||
slices).
|
||||
@@ -125,8 +125,8 @@ was copied.
|
||||
won). The move is at most 0.2, and merging again changes nothing (tested).
|
||||
* Not in this slice:
|
||||
* ~~selecting across layers~~ (ADR 0044);
|
||||
* snapping while drawing with the shape tools;
|
||||
* ~~snapping while drawing with the shape tools~~ (ADR 0045);
|
||||
* ~~a Snap to Objects switch~~ (ADR 0042);
|
||||
* ~~Subselection anchors and handles of connected raw shapes~~ (ADR 0042);
|
||||
* bending or moving points of raw shapes inside symbols;
|
||||
* ~~bending or moving points of raw shapes inside symbols~~ (ADR 0045);
|
||||
* the Free Transform tool's handles on raw parts.
|
||||
@@ -150,11 +150,11 @@ nothing was copied.
|
||||
* A Paint Bucket fill in merge drawing lies exactly along its lines. Deleting a line later
|
||||
joins fills of one colour, as in Animate.
|
||||
* Not in this slice:
|
||||
* deleting raw anchors (Delete says so), and adding them;
|
||||
* Make Smooth and Make Corner on raw anchors;
|
||||
* smooth handle pairs (a handle moves alone, as on drawing objects);
|
||||
* ~~deleting raw anchors (Delete says so), and adding them~~ (ADR 0045);
|
||||
* ~~Make Smooth and Make Corner on raw anchors~~ (ADR 0045);
|
||||
* ~~smooth handle pairs (a handle moves alone, as on drawing objects)~~ (ADR 0045);
|
||||
* width profiles in the merge;
|
||||
* Subselection inside symbols;
|
||||
* a default shortcut for Snap to Objects;
|
||||
* snapping while drawing with the shape tools;
|
||||
* a marquee across layers (ADR 0041).
|
||||
* ~~Subselection inside symbols~~ (ADR 0045: symbols open for editing in place);
|
||||
* ~~a default shortcut for Snap to Objects~~ (ADR 0045: Ctrl+Shift+/);
|
||||
* ~~snapping while drawing with the shape tools~~ (ADR 0045);
|
||||
* ~~a marquee across layers~~ (ADR 0044, for the Selection tool).
|
||||
@@ -0,0 +1,160 @@
|
||||
# ADR 0045: Raw points, snapping while drawing, and raw shapes inside symbols
|
||||
|
||||
* Status: accepted (2026-11-10)
|
||||
* Relates to: ADR 0031 (merge drawing), ADR 0041 (Selection tool on raw drawings), ADR 0042
|
||||
(Subselection and merging everywhere), ADR 0044 (selection across layers), ADR 0004
|
||||
(destructive actions), ADR 0001 (undo snapshots), issue #42 (sections 1 and 3)
|
||||
|
||||
## Context
|
||||
|
||||
ADR 0042 left these out of its slice:
|
||||
|
||||
* adding and deleting raw anchors (Delete only said it could not);
|
||||
* Make Smooth and Make Corner on raw anchors, and smooth handle pairs (a handle moved alone);
|
||||
* snapping while drawing with the shape tools;
|
||||
* a default shortcut for Snap to Objects;
|
||||
* Subselection (and, from ADR 0041, the Selection tool) inside symbols.
|
||||
|
||||
The last one needed more than the raw tools: AniCraft had no way to edit a symbol's timeline at
|
||||
all. In Animate a double-click on an instance opens the symbol **in place**: the rest of the
|
||||
stage dims, the timeline shows the symbol's layers, every tool works inside it, and the edit bar
|
||||
says where you are (`Scene 1 › Badge`).
|
||||
|
||||
Behaviour was learned from the issue, Adobe's public help pages and watching the program;
|
||||
nothing was copied.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Points are positions, as in ADR 0042.** A shared point is stored once in each raw shape
|
||||
that has it, so each command finds every copy near the position (within 1.5 × `SNAP`) and
|
||||
changes them alike. The pure parts are in `anicraft_geom::raw`: a path as subpaths of
|
||||
segments (`subpaths`, `from_subpaths`), the edges leaving a point (`edges_at`,
|
||||
`distinct_edges`), and the edits below.
|
||||
|
||||
2. **Adding a point** (`raw.add_point {x, y, slop?}`, the Pen's Alt-click and the Subselection
|
||||
double-click on a raw line or fill edge) splits the segment there in every raw shape that has
|
||||
that edge (de Casteljau, so the curve is unchanged; tested analytically). Nothing moved, so
|
||||
nothing merges. A point added on a **straight** line lasts while it is used: once a merge
|
||||
finds it still on a straight run (it was never moved), it is simplified away, as issue #42's
|
||||
continuous simplification asks. On a curve it stays.
|
||||
|
||||
3. **Deleting points** (`raw.delete_points {points}`, Delete or Backspace with Subselection,
|
||||
the point menu) works on the drawing's edges at each point, not on one shape:
|
||||
* **Two edges** (a corner, or a point along a line): they become one edge from the far end of
|
||||
one to the far end of the other: two lines a line, anything else the cubic that fits both
|
||||
best, keeping the directions they leave their far ends in (`join`, the fit `Path::merge_at`
|
||||
uses; deleting a point that adding made gives the curve back). **Every copy** of either
|
||||
edge becomes the new one: a fill's outline loses the corner, and a stroke that ended there
|
||||
now runs along the whole new edge. The drawing stays connected; the merge that follows
|
||||
joins the strokes that now overlap.
|
||||
* **One edge** (the free end of lines): the segment there goes.
|
||||
* **Three or more** (where lines cross or a line stands on another): the point is kept and
|
||||
the editor says why. Joining three edges into one has no single right answer.
|
||||
* What is left with nothing to show is removed: a subpath with no segments or no length, a
|
||||
filled outline with no area; a shape with no subpaths. So deleting a line's last points
|
||||
removes it.
|
||||
* One command, so one undo step (ADR 0004: undoable, no confirmation), merged again
|
||||
(`remerge_in_place`) like every raw edit.
|
||||
|
||||
*Rejected:* deleting the point from each shape on its own (`Path::remove_anchor` per copy).
|
||||
Each shape would fit its own curve, and a fill and its outline would part.
|
||||
|
||||
4. **Make Smooth and Make Corner** (`raw.convert_points {points, smooth}`, the point menu):
|
||||
smooth turns a point with two edges into one whose handles lie on one line, along the
|
||||
direction between the far ends, a third of each chord long (`Path::make_smooth`'s rule);
|
||||
corner draws every curve's handle there in onto the point. Each changed edge changes in
|
||||
every shape (`follow_edge`, built on ADR 0041's `follow`). A smooth point on a straight line
|
||||
is simplified away by the merge, as in point 2.
|
||||
|
||||
5. **Smooth handle pairs.** Dragging one handle of a smooth point (its two handles on one line,
|
||||
opposite, within 3°) turns the other to stay opposite, keeping its length: `raw.move_handle`
|
||||
and `path.move_points` take `smooth?: bool` (default true); **Alt** breaks the pair. The
|
||||
other handle is found among the edges at the point: exactly one other curve whose handle is
|
||||
opposite (a junction has no pair). Drawing objects behave the same, so both kinds of shape
|
||||
edit alike.
|
||||
|
||||
6. **Snapping while drawing.** `draw.snap {x, y, snap}` (no undo step) says where a point drawn
|
||||
at (x, y) goes: the nearest anchor within `snap`, else the nearest point on a line or fill
|
||||
edge, of what the stage shows near it (display-list items whose bounds reach the point, so it
|
||||
costs nothing far away). The Line, Rectangle, Oval, PolyStar and Pen tools snap their start
|
||||
and end (the Pen its knots, never its handles) within 10 screen pixels, and show the snap
|
||||
ring as you hover, where a press would start. Shift's constraint wins over snapping. Off when
|
||||
Snap to Objects is off (`ToolStyle::snap_radius`). Scripts pass exact coordinates; the query
|
||||
is there for them too.
|
||||
|
||||
7. **Snap to Objects is Ctrl+Shift+/**, Animate's chord. Where `/` and `?` share a key (US, UK
|
||||
layouts), the key arrives as `?`, so `Ctrl+Shift+?` is bound too (an engine alias). Neither
|
||||
clashed with a default (the keymap's clash test). ADR 0042's worry was the layout: on layouts
|
||||
where `/` needs Shift (German: Shift+7), Ctrl+Shift+that key arrives as `/`, which the first
|
||||
binding catches.
|
||||
|
||||
8. **Editing a symbol in place** (`crates/engine/src/editing.rs`):
|
||||
* The session keeps a stack of open symbols (`Session::editing`). While one is open,
|
||||
**every command works on its timeline** (`Session::timeline`; the 86 places that read
|
||||
the scene's timeline now read this): the active layer, the playhead and the selection are
|
||||
its, positions are in its space, the display list (picking, bounds, snapping) is its
|
||||
timeline evaluated alone (`anicraft_doc::evaluate_timeline`). So merge drawing, the
|
||||
Selection tool, Subselection, raw points, the Paint Bucket and the rest behave inside a
|
||||
symbol exactly as on the stage: they are the same commands.
|
||||
* `symbol.edit {id?, symbol?}` (Edit › Edit Symbols, **Ctrl+E**, a **double-click** on an
|
||||
instance with the Selection tool) opens the selected or given instance where it stands, at
|
||||
the frame a graphic shows (a movie clip or button at its first); `{symbol}` (a double-click on
|
||||
a symbol in the Library, as in Animate, or its right-click Edit Symbol; Place on stage still
|
||||
places it) opens one alone at the stage's centre. Ctrl+E with no instance selected goes
|
||||
back to the document, as in Animate. `symbol.exit {all?}` (Edit › Edit Document, a
|
||||
double-click on empty stage, the edit bar's path) closes one level or all, selecting the
|
||||
instance again.
|
||||
* Which symbol is open is view state, but **undo snapshots keep it**, so undoing a change
|
||||
made inside a symbol opens it again: the layer, frame and selection in the step belong to
|
||||
that timeline. A symbol that goes away (an undo, a deletion) closes. Changing scene closes
|
||||
every symbol. Placing or pasting a symbol inside itself (or inside a symbol it uses) is
|
||||
refused; a camera can't be added inside a symbol.
|
||||
* **What the stage draws** (`Session::stage_picture`): a picture document whose scene holds
|
||||
the open timeline at its playhead where the instance stands, over each timeline below it
|
||||
(without the instance it was opened from) at 35 % opacity. They are graphic instances of
|
||||
copies of those timelines, so the oracle and the GPU stage draw them unchanged, and the
|
||||
render cache keys them by a hash of the state and the open levels.
|
||||
* **The editor's view follows the instance** when it is only moved and scaled evenly: the
|
||||
stage's screen mapping becomes `origin + zoom · (t + k · p)`, which the shell's existing
|
||||
origin-and-zoom mapping holds exactly, so every tool, overlay and snap radius works
|
||||
unchanged. A rotated, skewed or flipped instance opens upright and unscaled at its
|
||||
registration point, with the artwork around it hidden (a picture that did not line up with
|
||||
the tools would mislead).
|
||||
* The edit bar shows `Scene 1 › Badge › Layer 1`; a click on a symbol goes back to it, the
|
||||
scene's menu goes back to the scene. A crosshair marks the registration point.
|
||||
|
||||
*Rejected:* a full affine view mapping in the shell (rotated in-place editing). Every tool's
|
||||
screen-space overlay assumes an axis-aligned mapping (selection boxes, Free Transform
|
||||
handles, marquees); bending them all is a slice of its own. *Rejected:* addressing a symbol's
|
||||
timeline through a `symbol` param on each command (as the Actions panel's commands do):
|
||||
every command and tool would need it, and the tools would still need a view of the symbol.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Issue #42's Subselection (§3) is complete on raw drawings, inside symbols too. The drawing
|
||||
tools snap as the issue's §1 describes.
|
||||
* Measured on 744 raw shapes (12 × 12 outlined, rounded squares and 12 lines; optimised debug
|
||||
build, `raw_points_timings`):
|
||||
|
||||
| Operation | Time |
|
||||
|---|---|
|
||||
| Add a point | 0.29 ms |
|
||||
| Delete a point (joined, merged again) | 0.30 ms |
|
||||
| Make Smooth | 0.34 ms |
|
||||
| Smooth handle pair drag frame | 0.14 ms |
|
||||
| Drawing snap (every frame while hovering) | 0.02 ms |
|
||||
| Open a symbol of all 744 shapes | 0.04 ms |
|
||||
| Its stage picture | 0.01 ms |
|
||||
| A point move inside it | 0.52 ms |
|
||||
|
||||
* `panic_hunt_every_command` also starts inside an open symbol with raw drawings, and renders
|
||||
the stage picture.
|
||||
* Not in this slice:
|
||||
* in-place editing of rotated, skewed or flipped instances (they open upright, alone);
|
||||
* the parent symbol's frame moving with the open one (a nested graphic shows the frame it
|
||||
was opened at), and onion skin and Edit Multiple Frames (ADR 0047) while a symbol is open in
|
||||
place: the stage then draws a picture of the symbol, so both switch off (`frames.*` commands
|
||||
still work on the open timeline). ADR 0051 turns both on there;
|
||||
* deleting a point where three or more edges meet;
|
||||
* width profiles in the merge (ADR 0042);
|
||||
* a marquee across layers with the Subselection tool (Animate keeps it on one layer too).
|
||||
@@ -112,6 +112,7 @@ and from watching the program; nothing was copied.
|
||||
* per-layer onion skin toggles, and onion skin inside a symbol being edited in place;
|
||||
* Edit Multiple Frames deleting, transforming (scale, rotate), copying or recolouring across
|
||||
keyframes; it moves only. Raw (merge) shapes moved there are not merged again with what
|
||||
they land on;
|
||||
they land on. (Done in ADR 0051, except recolouring; onion skin inside a symbol open in
|
||||
place too.)
|
||||
* a marker drag that also scrolls the timeline;
|
||||
* onion skin in Test Movie and exports (never: it is an editing aid).
|
||||
@@ -0,0 +1,179 @@
|
||||
# ADR 0048: GPU stage, fourth slice: tile binning on the GPU, and hairlines
|
||||
|
||||
* Status: accepted (2026-11-10)
|
||||
* Relates to: roadmap M3, ADR 0019 (GPU stage), ADR 0029 (no readback, masks and groups; binning
|
||||
kept on the CPU), ADR 0032 (bitmaps, filters, the default), ADR 0047 (onion skin outlines),
|
||||
ADR 0002 (the oracle's coverage), AGENTS.md rule 4 (the CPU renderer is the oracle)
|
||||
|
||||
## Context
|
||||
|
||||
Two costs were left in the GPU stage:
|
||||
|
||||
* **Binning on the CPU.** The CPU split every prepared edge into 16 × 16 tile pieces, summed
|
||||
16 floats of backdrop per tile, and uploaded it all. ADR 0029 kept it there because stage tiles
|
||||
spread it over every core; it was still the largest term of a heavy frame (10k shapes: 4.0 ms
|
||||
of 8.8 at 1080p, 10.6 of 16.7 at 4K; 50k shapes: 17–76 ms) and grew with every shape.
|
||||
* **Outlines.** Outline mode (an outlined layer, and onion skin's Outlines, ADR 0047) drew each
|
||||
item as a stroke of half a pixel: four edges per segment and a hexagon at every bend, all
|
||||
overlapping, so an outlined item had 5–10× the edges of its fill. On the 2,000-item stress
|
||||
scene with ±5 onion frames, outlines took 34–39 ms on the CPU stage against 16–17 tinted, and
|
||||
73 ms against 12.6 on the GPU stage.
|
||||
|
||||
## Decision
|
||||
|
||||
### 1. One tile format the GPU can compute: integer backdrops and left-edge steps
|
||||
|
||||
The per-row float backdrop (the winding of everything left of a tile, per pixel row) needed a
|
||||
float sum in a fixed order; on the GPU that means float atomics (which WGSL doesn't have) or
|
||||
serial work. The binning now describes the same winding as **Vello's tiles do** (its public
|
||||
design notes: a backdrop and "y-edges"):
|
||||
|
||||
* **Backdrop:** one integer per tile, the winding number just below its top-left corner. It is
|
||||
the sum of the directions of the pieces further left in the tile row that start on the row's
|
||||
top edge (exactly the edges crossing it).
|
||||
* **Left-edge steps:** where the outline passes from one tile column to another inside a row
|
||||
(consecutive pieces in different columns), each tile boundary between them gets one more
|
||||
piece, a vertical line on that tile's left edge from the crossing down to the row's bottom:
|
||||
upwards where the outline runs right (the winding left of the tile drops by one), downwards
|
||||
where it runs left. The fine shader treats it like any piece, so its coverage formula is
|
||||
unchanged.
|
||||
|
||||
Both come **from the split pieces themselves**, so they can never disagree. A first version
|
||||
computed the crossings geometrically, apart from the split; near a tile corner a rounding
|
||||
could count one crossing twice, which a stress frame showed (543 pixels off by up to 133/255).
|
||||
A test on stress frames at awkward scales now catches it.
|
||||
|
||||
Integers add up the same in any order, the CPU binning (the reference) and the GPU produce the
|
||||
same lists, and the CPU's own binning got smaller (no 64-byte backdrops).
|
||||
|
||||
### 2. Binning on the GPU
|
||||
|
||||
The CPU lays out only what is proportional to the fills and their points (`gpu_binning.rs`):
|
||||
|
||||
* the prepared polygons' points, one flat buffer, and each fill's tile range;
|
||||
* one GPU invocation per **row of tiles of each fill** (an op-row), with room for each tile of
|
||||
each fill's bounds (an op-tile);
|
||||
* per tile row, the fills overlapping it in drawing order (from their bounds), and per tile
|
||||
room for every fill whose bounds cover it (a 2D running sum over the bounds' corners);
|
||||
* an **upper bound of the pieces** per edge (its rows, twice its columns, slack), so every
|
||||
buffer is sized before the GPU runs and **nothing is read back**.
|
||||
|
||||
`bin.wgsl` then runs, in one compute pass:
|
||||
|
||||
1. `count`: each op-row walks its fill's edges, splits the ones in its row (the CPU's
|
||||
`split_edge`/`split_row`, line for line), adds the left-edge steps, and counts pieces per
|
||||
op-tile; the backdrop deltas are summed along the row. An op-row belongs to one invocation,
|
||||
so **no atomics**: counts and backdrops are exact.
|
||||
2. `scan_blocks`/`scan_add` (`scan.wgsl`): an exclusive prefix sum of the counts (the public
|
||||
work-efficient scan, Blelloch 1990: per workgroup, then the workgroups' totals, added back).
|
||||
3. `scatter`: the same walk, writing each piece at its op-tile's place, in walk order (the
|
||||
same every frame).
|
||||
4. `tiles`: one invocation per tile walks its row's fills in drawing order and keeps those
|
||||
with pieces or a backdrop there, as the entries the fine pass reads.
|
||||
|
||||
This is the count, prefix-sum and scatter structure of Vello's and Pathfinder's binning stages
|
||||
(public descriptions; no code or shaders copied), arranged per op-row instead of per segment
|
||||
so that it needs no atomics and is deterministic. The binding layout uses four storage buffers
|
||||
per stage, the smallest any device offers.
|
||||
|
||||
**Scope.** Fills inside a mask or a group still bin on the CPU: their tile streams carry clip
|
||||
and group control entries whose number depends on which fills reach each tile, which needs
|
||||
either a CPU pass over the candidates or a GPU stream pass with counted room. That is the next
|
||||
step. The CPU binning stays the reference and this fallback.
|
||||
|
||||
**When.** `Binning::Auto` (the default) bins on the GPU when the scene can take it, has at
|
||||
least 32,768 edges and the device runs Vulkan (below, Direct3D 12 measured slower in stage
|
||||
tiles; other backends aren't measured yet). Below that many edges the CPU bins a stage tile faster than the GPU's passes set up
|
||||
(measured: forcing the GPU on every 512 px tile made the 1,000-shape 4K stage 1.9× slower, and
|
||||
the 10k-shape one 1.3× slower). `ANICRAFT_GPU_BINNING=cpu|gpu|auto` overrides it for
|
||||
comparisons; `render_with`/`render_texture_with` take it per call (tests, the bench). The
|
||||
start-up self-test also renders its rectangles binned on the GPU; if that comes back wrong,
|
||||
only the binning stays on the CPU on that device (`gpu_binning_off` says why), and the tests
|
||||
require it to work wherever the GPU stage runs (lavapipe in CI included).
|
||||
|
||||
Limits: at most `MAX_VISITS` (2²⁶) edge visits by the per-row passes (a fill with very many
|
||||
edges over very many rows bins on the CPU, which splits each edge once), and every buffer
|
||||
within the device's binding size; otherwise the CPU bins. The work bound (`MAX_WORK`) counts
|
||||
the room made, an upper bound.
|
||||
|
||||
### 3. Hairlines in both renderers
|
||||
|
||||
Outline mode draws **hairlines**: the oracle's prepared fill carries the flattened polylines
|
||||
(closed ones repeat their first point) and `Fill::hairline`. A pixel's coverage is
|
||||
`1 − d`, clamped, where `d` is the distance from its centre to the nearest segment
|
||||
(`render::hairline`). That is exactly the area a one-pixel line covers for horizontal and
|
||||
vertical lines (a line through pixel centres covers them fully, one on a boundary half each
|
||||
side), a tent-filtered line in other directions (diagonals look up to about 12 % heavier),
|
||||
with round ends and joins and no darkening where segments overlap. Each segment is one piece
|
||||
to bin and test, where the stroked hairline was four plus a disc at every bend.
|
||||
|
||||
* The oracle computes it per segment over the rows and columns within reach (a direct-coverage
|
||||
mode of its accumulation buffer); the GPU's fine shader takes the nearest of the tile's
|
||||
segments (with a cheap box reject first) by the same steps (`seg_dist`).
|
||||
* The binning puts each segment, whole, into every tile with a pixel centre within reach
|
||||
(conservatively: two pixels around it); no backdrops.
|
||||
* This changes the oracle's outline mode slightly (anti-aliasing of 1 px lines); it is an
|
||||
editing aid, never exported (vector exports draw outlines as their own strokes), and the
|
||||
engine's tests and goldens are unchanged.
|
||||
|
||||
Not hairlines (yet): strokes thinner than a pixel. They keep a one-pixel stroke polygon faded
|
||||
by their width; drawing them as hairlines would change exported pictures and the XFL goldens,
|
||||
which is its own decision.
|
||||
|
||||
## Measured (2026-11-10, release, RTX 5090, 32 threads, a machine shared with other builds)
|
||||
|
||||
`cargo run --release -p anicraft-gpu --example gpu_bench`: *direct* is what the calling thread
|
||||
spends with `render_texture` (prepare + bin + upload and submit), *tiled* is the stage's way
|
||||
(512 px tiles in parallel until the GPU has finished). Before: binned on the CPU; after: as
|
||||
`Binning::Auto` bins (the GPU from 32,768 edges, on Vulkan). Best of three runs, Vulkan.
|
||||
|
||||
| Scene | Size | CPU oracle | Before: direct / tiled | After, binned on the CPU: direct / tiled | After, Auto: direct / tiled | Parity (mean / max, 1/255) |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Stress, 50 × 200 (≈10k shapes) | 1920×1080 | 9.8 ms | 9.0 / 7.4 ms | 8.6 / 5.5 ms | **3.9** / 5.5 ms | < 0.0001 / 1 |
|
||||
| Stress, 50 × 200 | 3840×2160 | 25.9 ms | 21.7 / 10.9 ms | 16.4 / 10.1 ms | **4.7** / 10.1 ms | < 0.0001 / 1 |
|
||||
| 1,000 shapes (binned on the CPU: few edges) | 3840×2160 | 16.9 ms | 2.2 / 4.5 ms | 1.6 / 4.2 ms | 1.7 / 4.5 ms | < 0.0001 / 1 |
|
||||
| 50,000 shapes (250 × 200) | 1920×1080 | 31.7 ms | 52.2 / 32.4 ms | 33.5 / 26.8 ms | **17.7** / 24.8 ms | < 0.0001 / 1 |
|
||||
| 50,000 shapes | 3840×2160 | 73.1 ms | 122.1 / 75.3 ms | 103.9 / 61.5 ms | **22.5** / **36.7** ms | < 0.0001 / 1 |
|
||||
| Masked stress (binned on the CPU: masks) | 3840×2160 | 72.4 ms | 13.8 / 12.3 ms | 12.0 / 10.7 ms | 11.3 / 10.5 ms | < 0.0001 / 1 |
|
||||
| Onion skin off (stress 20 × 100) | 1920×1080 | 5.0 ms | 2.1 / 2.7 ms | 1.8 / 2.2 ms | 1.1 / 2.3 ms | < 0.0001 / 1 |
|
||||
| Onion ±5, tinted (22,000 items) | 1920×1080 | 15.1 ms | 15.7 / 12.6 ms | 12.8 / 10.5 ms | 7.1 / 9.8 ms | < 0.0001 / 1 |
|
||||
| Onion ±5, tinted | 3840×2160 | 37.3 ms | 32.1 / 25.1 ms | 20.3 / 22.0 ms | 8.5 / 16.5 ms | 0.0001 / 1 |
|
||||
| Onion ±5, **outlines** | 1920×1080 | 20.0 ms (was 36.0) | 74.7 / 73.0 ms | 12.9 / 10.4 ms | 7.3 / **10.1** ms | < 0.0001 / 1 |
|
||||
| Onion ±5, **outlines** | 3840×2160 | 37.9 ms (was 60.2) | 135.4 / 95.4 ms | 20.3 / 18.1 ms | 8.6 / **15.3** ms | < 0.0001 / 1 |
|
||||
|
||||
*Before* is `main` before this slice (CPU binning with float backdrops, stroked hairlines),
|
||||
measured the same day on the same machine. In stage tiles the GPU binning wins once frames are
|
||||
heavy (50k shapes: 61.5 → 36.7 ms at 4K) and never loses below `AUTO_MIN_EDGES`; a whole frame
|
||||
in one texture gains most (10k shapes at 4K: 16.4 → 4.7 ms). **Outline mode is as fast as
|
||||
tinted onion skin** on the GPU stage: 10.1 vs 9.8 ms at 1080p in tiles, 15.3 vs 16.5 ms at 4K,
|
||||
7.3 vs 7.1 ms in one texture (it was 73 vs 12.6 ms in tiles).
|
||||
|
||||
On **Direct3D 12** (same card, `WGPU_BACKEND=dx12`, two runs) the GPU binning still wins in
|
||||
one texture (10k shapes at 4K: 17.5 → 6.3 ms; 50k: 154 → 30 ms) but loses in stage tiles
|
||||
(onion ±5 at 1080p: 9.7 → 14.4 ms tinted, 10.0 → 15.4 ms outlines; the passes cost more per
|
||||
dispatch there, as ADR 0032 saw for the fine pass), so `Binning::Auto` bins on the GPU on
|
||||
Vulkan only. With CPU binning, DX12's onion outlines take 10.1 ms in tiles against 10.0 tinted.
|
||||
|
||||
The CPU stage (the oracle through the render service's 256 px tiles, `onion_timings`, best of
|
||||
frames 12, 30 and 48) with hairlines: onion ±5 outlines **17.1 ms** against 14.8 tinted at
|
||||
1080p (was 34–39 against 16.2–17.2).
|
||||
|
||||
## Not in this slice
|
||||
|
||||
* GPU binning for fills inside masks and groups (their tile streams, ADR 0029).
|
||||
* Flattening and stroking on the GPU (preparation is now the largest CPU term of a heavy
|
||||
frame: 8–9 ms of 50k shapes).
|
||||
* Fewer, larger dispatches for the stage's tiles (each 512 px tile is its own submission, so the
|
||||
binning passes' set-up repeats per tile).
|
||||
* Hairlines for strokes thinner than a pixel (above).
|
||||
* Guide lines and selection outlines: the stage never renders guides, and selection outlines
|
||||
are drawn by the shell's painter, not the stage renderer.
|
||||
|
||||
## Consequences
|
||||
|
||||
* The tile format is one integer backdrop per tile plus left-edge steps, on the CPU and the GPU
|
||||
alike; `Binned` carries the op headers apart (`op_heads`) and, when the GPU bins, the plan.
|
||||
* A test compares the GPU's tile lists with the CPU's, tile by tile, entry by entry and pixel
|
||||
by pixel, on stress frames, outlined onion frames and the analytic scenes; GPU-binned frames
|
||||
are checked against the oracle read back and through a texture; on Vulkan and Direct3D 12.
|
||||
* `gpu_bench --check` enforces the GPU stage's timing budgets (docs/performance.md).
|
||||
@@ -0,0 +1,126 @@
|
||||
# ADR 0050: Library folders, item management and Swap Symbol
|
||||
|
||||
* Status: accepted (2026-11-10)
|
||||
* Relates to: ADR 0003 (file format), ADR 0004 (destructive actions), ADR 0009 (XFL import),
|
||||
ADR 0013 (scripts and linkage), ADR 0019/0032 (GPU stage), ADR 0028 (HTML canvas export),
|
||||
ADR 0045 (symbols edited in place), roadmap M2
|
||||
|
||||
## Context
|
||||
|
||||
The Library listed symbols, bitmaps and sounds in one flat list. It could place an item, delete
|
||||
a sound and (since ADR 0045) open a symbol for editing. Animate users keep hundreds of items in
|
||||
nested folders, rename them in place, duplicate symbols to make variants, swap one symbol for
|
||||
another on the stage, clean out what the movie no longer uses, and set per-item options such as
|
||||
a bitmap's smoothing. We learned how Animate does this from its public help pages and from
|
||||
watching the program. Nothing was copied.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **The organisation is a side table, not a field on each item.**
|
||||
`Document.library_tree: Arc<LibraryTree>` (`crates/doc/src/library.rs`) holds the folders
|
||||
(`LibraryFolder { id, name, parent }`) and a map from each item (`LibraryItem::Symbol |
|
||||
Bitmap | Sound`) to its folder. An item that isn't in the map is at the top level. We chose
|
||||
this over a `folder` field on `Symbol`, `Bitmap` and `Sound`:
|
||||
* Moving or renaming folders touches one small table, never a symbol (so undo snapshots stay
|
||||
O(changed) and symbol timelines keep their `Arc`s).
|
||||
* The three item structs, which many places build, are unchanged.
|
||||
* Older files have no `library_tree` and open with everything at the top level. A Library
|
||||
without folders writes nothing new (`skip_serializing_if`), so files stay the same until
|
||||
a folder is made.
|
||||
|
||||
Folder ids come from the document's id counter, like every other id. On load,
|
||||
`sanitize_library_tree` repairs a damaged tree: duplicate ids, missing parents, cycles and
|
||||
nesting deeper than 32 levels are fixed, and placements of items that aren't there are
|
||||
dropped. It touches nothing when the tree is sound. The fuzz checks that no command leaves a
|
||||
tree that a load would have to repair.
|
||||
|
||||
2. **Names are unique within a folder, ignoring case,** across items and folders, as in Animate.
|
||||
They can't be empty, can't be longer than 256 characters, and can't contain `/`, which joins
|
||||
a path (`Characters/Hero/Ball`). The engine checks this in `library.new_folder`,
|
||||
`library.rename`, `library.move` and `library.duplicate`. A move whose name is already in
|
||||
the target folder fails with a message naming it, and nothing moves (commands are atomic).
|
||||
We chose refusing over Animate's "replace existing items?" prompt: replacing destroys
|
||||
content, and a rename is one keystroke away. Older documents with duplicate names open as
|
||||
they are. Convert to Symbol now picks the next free "Symbol n".
|
||||
|
||||
3. **Commands** (`crates/engine/src/cmds_library.rs`), all in the existing `library` and
|
||||
`element` plug-in namespaces. Entries are named `{"symbol"|"bitmap"|"sound"|"folder": id}`.
|
||||
* `library.items`: every folder and item with path, kind, use count and whether it is unused.
|
||||
* `library.new_folder`, `library.rename`, `library.move`. A folder can't go inside itself,
|
||||
and nesting is limited to 32 levels.
|
||||
* `library.duplicate`: a copy right after the original, in the same folder, named
|
||||
"<name> copy" (then "copy 2", …). It gets fresh layer and element ids, with layer parents,
|
||||
motion tween targets and bone ends following them (`library::fresh_ids`). It has no
|
||||
linkage class, because a class names one symbol.
|
||||
* `library.delete`: deletes items and folders together with what they hold. What uses them
|
||||
goes too, as in Animate: instances of deleted symbols, shapes filled with deleted bitmaps,
|
||||
and deleted sounds on keyframes, on every timeline. Only the layers and keyframes that had
|
||||
a use are copied. Deleting the symbol that is open for editing closes it (ADR 0045).
|
||||
* `library.unused` (Select Unused Items) and `library.delete_unused`.
|
||||
* `library.set_smoothing`; `element.swap_symbol`. Linkage stays `script.set_class`
|
||||
(ADR 0013).
|
||||
|
||||
4. **Use count and unused have different meanings, on purpose.** Use count is the number of
|
||||
references on every timeline (scenes and symbols), counted once per keyframe: instances,
|
||||
bitmap fills and keyframe sounds. *Unused* means **not reachable from any scene**. A symbol
|
||||
used only inside a symbol that nothing places is unused, even though its count is above
|
||||
zero. One Delete Unused Items then clears a whole dead branch in one undo step, instead of
|
||||
peeling off one layer per run. Symbols with a linkage class count as reached, because scripts
|
||||
create them by name (ADR 0013). The row's tooltip and screen-reader name give both.
|
||||
|
||||
5. **Confirmations follow ADR 0004** (undoable tier, `crates/engine/src/confirm.rs`). Deleting
|
||||
asks only when something deleted is in use ("used 4 times in the movie; those uses go too")
|
||||
or when a folder holds items ("holds 5 items, deleted with it"). Deleting an unused item or
|
||||
an empty folder is routine and doesn't ask. Delete Unused Items always asks and names the
|
||||
first few items.
|
||||
|
||||
6. **Swap Symbol** replaces only the symbol an instance shows. Transform, colour effect,
|
||||
blending, filters, looping, actions and instance name stay, as in Animate. It is a button in
|
||||
Properties › Symbol ("Swap…", listing symbols by path). Inside a symbol open for editing, it
|
||||
refuses a symbol that would contain itself (`editing::would_nest`).
|
||||
|
||||
7. **Allow Smoothing** is a property of the bitmap (`Bitmap.smoothing`, on by default; only
|
||||
`false` is written). It reaches the renderers through `DisplayItem.smooth`. The CPU oracle
|
||||
samples the nearest pixel instead of bilinear (`Shader::smoothed`). The GPU stage uses bit 1
|
||||
of the bitmap's flag word in `fine.wgsl` and does the same, so oracle parity still holds.
|
||||
SVG export marks the image `image-rendering="pixelated"`, and the HTML page turns
|
||||
`imageSmoothingEnabled` off for that fill. XFL import reads `allowSmoothing`.
|
||||
|
||||
8. **XFL import keeps folders.** `<folders><DOMFolderItem name="A/B"/>` creates folders, empty
|
||||
ones included. Symbols and bitmaps go into the folder their library name's path names
|
||||
(`Characters/Ball` → `Ball` in `Characters`). The report lists "library folders" as kept.
|
||||
|
||||
9. **The panel (`src/library.rs`) holds only view state**: selection (Ctrl-click and
|
||||
Shift-click ranges), open folders, sort (Name, Type, Use count, Date added, ascending or
|
||||
descending; folders first), the search text, and the item being renamed. Everything that
|
||||
changes the document is a command.
|
||||
* "Date added" is the item's id order: ids only grow, so no clock is stored.
|
||||
* Searching opens every folder that leads to a match.
|
||||
* F2, or a double-click on the name, renames in place. Enter or clicking away keeps the new
|
||||
name; Esc cancels. A double-click on the icon edits a symbol (ADR 0045) or places an image
|
||||
or sound.
|
||||
* Rows drag onto a folder (into it), onto an item (into that item's folder) or below the
|
||||
list (to the top level).
|
||||
* F2 and Delete act on the Library only while the list was the last thing clicked, so
|
||||
Delete on the stage still clears artwork.
|
||||
* The preview shows a symbol's first frame rendered by the CPU oracle, a bitmap drawn with or
|
||||
without smoothing as on the stage, or a sound's waveform with a play button. Below it are
|
||||
the item's properties: a symbol's type and linkage class, a bitmap's Allow Smoothing, a
|
||||
sound's format.
|
||||
* Use counts are worked out once per document state.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Measured on 200,000 element keys plus 1,000 symbols in 50 folders, release build: use counts
|
||||
1.5 ms, unused items 1.7 ms, the whole `library.items` listing 5.0 ms (`library_tests.rs`).
|
||||
* Duplicates share no ids with their originals. Bone ids inside an armature are kept: they are
|
||||
scoped to their layer.
|
||||
* One XFL corpus golden changed: its checker bitmap says `allowSmoothing="false"` and is now
|
||||
drawn with hard edges, as Animate shows it.
|
||||
|
||||
## Not yet
|
||||
|
||||
(Dragging items onto the stage, choosing a folder in Convert to Symbol and Swap Bitmap came in
|
||||
ADR 0053.) Animate's Properties dialog (the properties are inline),
|
||||
linkage on bitmaps and sounds, bitmap compression settings, Update and Import of library items
|
||||
from another document (shared libraries), folder expansion saved in the file and sorting by size.
|
||||
@@ -0,0 +1,120 @@
|
||||
# ADR 0051: Edit Multiple Frames, complete; onion skin inside symbols
|
||||
|
||||
* Status: accepted (2026-11-11)
|
||||
* Relates to: ADR 0047 (onion skin and Edit Multiple Frames), ADR 0045 (symbols edited in place),
|
||||
ADR 0031 / 0041 (merge drawing, the Selection tool on raw shapes), ADR 0004 (destructive
|
||||
actions), ADR 0017 (plug-in policy), ADR 0040 (interface languages)
|
||||
|
||||
## Context
|
||||
|
||||
ADR 0047 shipped Edit Multiple Frames as a move-only tool. Raw (merge-drawing) shapes it moved
|
||||
were not merged again with what they landed on. ADR 0045 switched both onion skin and Edit
|
||||
Multiple Frames off while a symbol was open in place, because the stage then draws a picture
|
||||
document of the symbol rather than the scene. Artists coming from Animate expect the rest of
|
||||
Edit Multiple Frames: delete, cut, copy and paste across keyframes, Free Transform of the whole
|
||||
multi-frame selection about one pivot, Align, arrow nudges, and onion skin inside the symbol
|
||||
they are animating.
|
||||
|
||||
Behaviour was learned from Adobe's public help pages on onion skinning and Edit Multiple Frames
|
||||
and from watching the program. Nothing was copied.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Commands on explicit items.** As in ADR 0047, the multi-frame selection is a list of
|
||||
`FrameItem { layer, frame (the keyframe's first frame), element }` kept by the shell. Every
|
||||
edit is a `frames.*` command (`crates/engine/src/multi.rs`) taking `{first, last}` (the
|
||||
markers) and `items?`. An item that the markers don't show, or that sits on a hidden or
|
||||
locked layer, is refused and nothing changes. Without `items`, a command acts on everything
|
||||
shown. Each command is one undo step, and each answers with `items`, the selection
|
||||
afterwards (merged pieces get new ids), so a front end never has to ask again.
|
||||
* `frames.edit_multiple` (moved from `onion.rs`) moves. `frames.transform` takes a stage
|
||||
affine `{a..f}` (what Free Transform sends) or `{rotate, scale_x, scale_y, skew_x, skew_y,
|
||||
pivot?}`, where the pivot defaults to **the centre of every item's bounds together**: one
|
||||
shared pivot, so each keyframe's copy lands exactly where the same transform of the whole
|
||||
multi-frame picture puts it. `frames.align {edge, to_stage?}` lines the items up with the
|
||||
edge of their bounds together. With one item, or with To Stage, it aligns to the stage.
|
||||
So Align Left on a walk cycle lines every frame's figure up.
|
||||
* `frames.delete`, `frames.copy`, `frames.cut`. Delete is an undoable routine edit with a
|
||||
status-bar hint, like `edit.delete` (ADR 0004 tier 3). Whole keyframes are never removed.
|
||||
* `frames.paste` is **Paste in Place onto the keyframes between the markers**. Each copied
|
||||
chunk remembers the keyframe it came from (`ClipLayer::frame`, `None` for a copy made on
|
||||
one frame). A multi-frame copy goes back keyframe by keyframe, onto the target layer's
|
||||
keyframe covering the frame each chunk came from. If those keyframes are outside the
|
||||
markers, the chunk is skipped and counted. A one-frame copy goes onto every keyframe of the
|
||||
layer shown. Artwork from several layers goes back on those layers when they are all
|
||||
edited there; otherwise everything goes on the active layer (or `layer`). **Paste**
|
||||
(Ctrl+V) with Edit Multiple Frames on pastes onto the current frame, as Animate does, and
|
||||
the pasted artwork becomes the multi-frame selection. Without Edit Multiple Frames, a
|
||||
multi-frame copy pastes like any copy, and several keyframes of one layer count as one
|
||||
layer (`paste_targets` maps each distinct source layer once).
|
||||
* **Re-merge.** Raw shapes that moved, were transformed or aligned, or were pasted go back
|
||||
into the drawing **on their own keyframe** as `draw.drop` does on one frame: taken out,
|
||||
then `merge_in` on top of what they touch. The editing helpers work at the playhead, so
|
||||
`at_keyframe` runs them with the playhead on the keyframe's first frame and restores it.
|
||||
A drag passes `merge: false` on each step and calls `frames.merge {items}` when it ends,
|
||||
inside the same gesture, so the drag stays one undo step and shapes are not cut while
|
||||
they pass over others.
|
||||
* **Motion tweens.** A tween's object can be moved across frames (its path and X/Y keys move
|
||||
with it, `MotionTween::translate`). Scaling, rotating or skewing it on several frames is
|
||||
refused with a message, because its look comes from property keys, not one transform.
|
||||
* **Plug-ins** may call the document edits (`frames.edit_multiple/transform/align/delete/
|
||||
merge`). `frames.copy/cut/paste` are refused like every clipboard command.
|
||||
|
||||
*Rejected:* a multi-frame selection inside the engine (`Session::selection` with frames).
|
||||
Commands already take explicit items, so headless callers and agents get the same power with
|
||||
no second selection model to keep in step with undo. *Rejected:* a separate multi-frame
|
||||
clipboard. It would make Copy on one frame and Paste in Place across frames disagree about
|
||||
what was copied. One clipboard with a frame on each chunk keeps Animate's single clipboard.
|
||||
|
||||
2. **In the editor** (`src/onion.rs`). With Edit Multiple Frames on, the Edit menu, shortcuts
|
||||
and the stage's right-click menu act on the multi-frame selection: Cut, Copy, Paste (current
|
||||
frame), Paste in Place (every keyframe), Clear (Delete/Backspace), Select All, Deselect; the
|
||||
Align panel and Ctrl+Alt+1…6 (To Stage honoured); Rotate 90° and Flip about the shared
|
||||
centre. The **Free Transform** tool draws one box around the selection on every keyframe,
|
||||
with the pivot at its centre. Its handles scale (Shift proportional, Alt from the centre),
|
||||
rotate (Shift 15°) and move it all, one undo step per drag, merged on release. Arrow keys
|
||||
nudge, one step each, merged. Duplicate, Convert to Symbol, Break Apart, Arrange and
|
||||
Distribute are disabled there and say why. Status lines go through `trn!`.
|
||||
|
||||
3. **Onion skin inside symbols.** The open symbol's timeline is the timeline both features
|
||||
compose. `StagePicture::front` names the picture's top layer (the open symbol's instance),
|
||||
the timeline, its frame and its placement `at`. A render job made with `FrameJob::inside(
|
||||
front)` draws, when onion settings show anything, the timelines around the symbol as they
|
||||
are, then `onion::compose_timeline(symbol timeline, frame, skin, eval)` with
|
||||
`eval = evaluate_timeline_at(doc, tl, f, at)`. That is the instance's own evaluation with
|
||||
the symbol's layers as top-level ones, so onion frames still interleave layer by layer and
|
||||
Edit Multiple Frames keeps per-layer keyframes. `compose` for a scene is now this function on
|
||||
the scene's timeline. The job key mixes in the front, so the frame cache keeps symbol and
|
||||
scene looks apart. Markers, keyframes-only and every other option refer to the symbol's own
|
||||
timeline (the playhead and frame count the shell already uses there, ADR 0045). Picking and
|
||||
bounds were already in the symbol's space.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Edit Multiple Frames now does what Animate users use it for: re-posing, rescaling or
|
||||
re-aligning a whole animation, and cleaning up or copying artwork across keyframes. Raw
|
||||
drawings stay connected after a move.
|
||||
* Onion skin and Edit Multiple Frames work inside a symbol edited in place, rotated instances
|
||||
(opened upright, ADR 0045) included.
|
||||
* Measured (optimised dev build, `multi_timings`, 24 keyframes × (144 raw squares + 50
|
||||
objects) = 4,656 items shown):
|
||||
|
||||
| Operation | Time |
|
||||
|---|---|
|
||||
| List what is shown | 1.4 ms |
|
||||
| Move 1,200 objects (one drag step) | 2.8 ms |
|
||||
| Rotate 1,200 objects about the shared pivot | 2.9 ms |
|
||||
| Move and merge 288 raw squares across 24 keyframes | 5.6 ms |
|
||||
| Copy 1,200 objects, Paste in Place | 3.1 ms |
|
||||
| Delete everything shown | 1.8 ms |
|
||||
|
||||
The sample's spinning star with onion skin ±5 inside the symbol renders its tiles in 2.3 ms on
|
||||
the GPU stage.
|
||||
* Not in this slice:
|
||||
* Duplicate, Distribute, Arrange, Convert to Symbol and recolouring across keyframes;
|
||||
* scaling, rotating or skewing a motion tween's object on several frames (it moves);
|
||||
* Subselection, the Width tool and point edits across keyframes;
|
||||
* a pivot the artist can drag (it is the centre of the box, or the opposite handle with
|
||||
scale, as on one frame);
|
||||
* per-layer onion skin toggles, and onion skin of the parent timeline's frames around an
|
||||
open symbol (only the symbol's own frames are composed).
|
||||
@@ -0,0 +1,102 @@
|
||||
# ADR 0053: Library drag and drop, Swap Bitmap, Convert to Symbol folders, mixed Properties
|
||||
|
||||
* Status: accepted (2026-11-11)
|
||||
* Relates to: ADR 0050 (Library management), ADR 0044 (selection across layers), ADR 0045
|
||||
(symbols edited in place), ADR 0020/0039 (sounds on keyframes), ADR 0004 (destructive actions),
|
||||
ADR 0022 (accessibility), ADR 0040 (interface languages), roadmap M2
|
||||
|
||||
## Context
|
||||
|
||||
ADR 0050 left the everyday Library gestures Animate users reach for first: dragging an item
|
||||
onto the stage, swapping the bitmap an instance shows, choosing a folder when converting to a
|
||||
symbol. ADR 0044 showed "mixed" on only some Properties rows (Scale, Rotation, Alpha, Fill,
|
||||
Stroke, Style), so a selection of movie clips with different blending looked alike. Behaviour
|
||||
was learned from Adobe's public help pages and from watching the program; nothing was copied.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **One command places what a drop carries.** `library.place` takes one item
|
||||
(`{symbol | bitmap | sound: id, x?, y?}`, as before) or a list
|
||||
(`{items: [{symbol | bitmap | sound: id}, ..], x?, y?}`, up to 1,000). Symbols stand with
|
||||
their registration point on `x`/`y`, bitmaps are centred on it, all in the active layer's
|
||||
keyframe at the playhead (auto-key rules as for any edit), and everything placed is selected.
|
||||
A sound goes onto that keyframe (a blank keyframe is made on an empty frame, the span grows
|
||||
to the sound's length, as Place on Timeline did); a keyframe holds one sound, so two
|
||||
different sounds in one drop are refused. Positions are in the edited space, so inside a
|
||||
symbol open for editing (ADR 0045) a drop lands where the pointer is. Folders can't be
|
||||
placed; locked layers, folders, the camera and armature layers refuse as for drawing. One
|
||||
command means a drop of many items is one undo step, and the CLI, MCP and plug-ins (the
|
||||
`library` namespace) can do it too.
|
||||
|
||||
*Rejected:* a gesture of one `library.place` per item. It would be one undo step in the
|
||||
shell only, and a script dropping several items would get several.
|
||||
|
||||
2. **Dragging onto the stage.** Library rows already carry their selection as a drag payload
|
||||
(folder moves). The stage accepts the same payload: while it is over the stage the pointer
|
||||
shows a copy cursor, a cross where artwork lands and "Place on <layer>" (for sounds alone,
|
||||
"Put on <layer> at frame n"); the rows' names follow the pointer everywhere. Letting go runs
|
||||
`library.place` at the pointer, mapped into the edited space. Folders in the payload are
|
||||
left out. While previewing through the camera, artwork edits are paused (ADR 0027) and the
|
||||
drop says so instead.
|
||||
|
||||
3. **The keyboard way (ADR 0022).** Place on Stage (the Library's button, its right-click menu,
|
||||
and **Enter** while the list has the keyboard) places the selected rows at the **centre of
|
||||
the view** (what the stage shows, in the edited space), no longer the stage's centre: what
|
||||
you see is where it lands, as a drop at the centre would put it. With several rows selected
|
||||
it places them all, one undo step.
|
||||
|
||||
4. **Swap Bitmap** (`element.swap_bitmap {bitmap}`, per layer, ADR 0044's "where it applies"
|
||||
class). A bitmap placed from the Library is a rectangle of the bitmap's size filled with it
|
||||
(identity fill matrix, no repeat). Such a shape keeps its transform, so its top-left corner
|
||||
(Animate's registration point for bitmaps) stays put, takes the new bitmap's size, and its
|
||||
name follows when it was the old bitmap's. Any other bitmap-filled shape (painted with a
|
||||
bitmap fill) keeps its outline and fill transform, and only the bitmap changes. Properties
|
||||
shows a **Bitmap** row under Fill with the bitmap's name and size and **Swap…**, listing the
|
||||
Library's bitmaps by path, as Swap Symbol does.
|
||||
|
||||
5. **Convert to Symbol (F8) is a dialog** with Name, Type (Graphic, Movie clip, Button) and
|
||||
Folder (the Library's folders by path, or the top level). It offers the folder and type used
|
||||
last, while that folder still exists (view state, `convert_symbol::Last`, not saved).
|
||||
`modify.convert_to_symbol` takes `kind` and `folder`; a name the folder already holds gets a
|
||||
number ("Ball 2", `Document::unique_name`) rather than an error, and the dialog says so
|
||||
before you press OK. Without a name it is the next free "Symbol n" in that folder. Without
|
||||
`folder` it stays at the top level, so scripts behave as before.
|
||||
|
||||
6. **"Mixed" on every Properties row** that edits several elements (`src/mixed.rs`, pure and
|
||||
tested per row): Scale, Rotation, Alpha (the colour effect; tint has no row yet), Symbol
|
||||
(Swap…), Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke (colour and
|
||||
width), Width (profile) and Style. Each row compares only the elements it edits: Blending and
|
||||
Filters movie clips and buttons, Looping and First frame graphics, Fill, Stroke, Width and
|
||||
Style shapes, the Bitmap row bitmap fills. So a shape beside a movie clip never makes
|
||||
Blending mixed. Fill compares the whole paint (on beside off, two bitmaps, two gradients).
|
||||
Position never says mixed: with several elements it is the combined box (ADR 0044).
|
||||
|
||||
Editing a mixed row sets all, as the hint says. Choosing the value the field already shows
|
||||
applies it too when the row is mixed (otherwise a menu pick of the first element's value did
|
||||
nothing). For **Type**, `symbol.set_kind` without `symbol` now changes the symbols of
|
||||
**every** selected instance in one step (it was the first one's, ADR 0044 decision 2). The
|
||||
type belongs to the symbol, as in our model since ADR 0013, so this changes those symbols'
|
||||
other instances too, as picking the type in the Library does. Filters edits the first
|
||||
element's list and gives it to all.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Dragging from the Library to the stage, Place on Stage with Enter, Swap Bitmap, a folder in
|
||||
Convert to Symbol and mixed rows behave as an Animate user expects, headless included.
|
||||
* Tests: `crates/engine/src/place_tests.rs` (a drop of symbols, a bitmap and a sound in one
|
||||
undo step; positions; refusals that change nothing; locked layers; inside an open symbol;
|
||||
Swap Bitmap on a placed bitmap and on a tiled fill on two layers; Convert to Symbol into a
|
||||
folder, with clashing names, types and the file round trip), `src/mixed.rs` (one test per
|
||||
row group, including "editing a mixed row sets all"), `src/convert_symbol.rs` (the
|
||||
remembered folder). `panic_hunt_every_command` fuzzes mixed item lists, two sounds, far
|
||||
points, 1,500 items, and Swap Bitmap on a placed bitmap.
|
||||
* `library.place`'s result gains `elements` and `sound`; `element` stays. `symbol.set_kind`'s
|
||||
result gains `symbols`.
|
||||
|
||||
## Not yet
|
||||
|
||||
Dropping files from the desktop onto the stage, a ghost picture of the item while dragging
|
||||
(the name follows the pointer), snapping a drop to objects, a New Folder button in the Convert
|
||||
to Symbol dialog and a registration-point grid, Swap Bitmap from the Library's own menu
|
||||
(Animate's "Swap Bitmap" on the item, which swaps every use), "mixed" on text style rows and on
|
||||
the instance name and events, and a Colour Effect row with tint and brightness.
|
||||
@@ -0,0 +1,83 @@
|
||||
# ADR 0054: `.fla` packages: corpus variants and a hardened zip reader
|
||||
|
||||
* Status: accepted (2026-11-11)
|
||||
* Relates to: ADR 0009 (XFL import, own zip reader), ADR 0035 (the XFL corpus and golden
|
||||
renders), ADR 0036 (web build: a `.fla` handed over as bytes), roadmap M4
|
||||
|
||||
## Context
|
||||
|
||||
Artists open `.fla` files: a zip archive of the same XFL tree the corpus (ADR 0035) tests as
|
||||
folders. The zip reader from ADR 0009 read stored and deflate entries and capped entry sizes,
|
||||
but nothing tested it against the layouts real zip writers produce (folder entries, `\`
|
||||
separators, unflagged or CP437 names, data descriptors, ZIP64), and nothing tested it against
|
||||
an archive made to hurt: entries sharing bytes (the overlapping-file zip bomb), sizes and
|
||||
checksums that lie, names with `..`, absolute or drive paths, the same name twice, very deep
|
||||
folders, a central directory cut short. A `.fla` arrives from anywhere (mail, the web build's
|
||||
file picker), so it is hostile input.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Read what writers write.** The reader (`crates/xfl/src/zip.rs`, from PKWARE's APPNOTE
|
||||
6.3) takes stored and deflate entries; folder entries; `\` read as `/`; empty and `.` path
|
||||
parts dropped; data descriptors (sizes come from the central directory, which always has
|
||||
them); **ZIP64** end records and per-entry sizes (cheap to read, written by some tools for
|
||||
small files too, and refused archives would be a worse answer); names as UTF-8 when flag
|
||||
bit 11 or the Info-ZIP Unicode path field (0x7075, checked against the name's CRC) says so,
|
||||
else **CP437** as the format specifies, except that a name that is valid UTF-8 is read as
|
||||
UTF-8 (many writers store UTF-8 without the flag; ASCII reads the same either way, and CP437
|
||||
text that happens to be valid UTF-8 is vanishingly rare). A name flagged UTF-8 that isn't is
|
||||
an error, not a guess.
|
||||
2. **Refuse, with a sentence, what no honest writer makes.** Opening checks the whole archive
|
||||
before any entry is inflated: every offset and length is checked against the bytes it
|
||||
comes from; each entry's local header and data must end before the central directory, and
|
||||
**no two entries may share bytes** (sorted spans); a path that would leave the package is
|
||||
refused (`..`, leading `/` or `\`, a drive in the first part, NUL), as are **duplicate
|
||||
paths** (after `\` → `/`), paths inside more than **32 folders**, more than **100,000
|
||||
entries**, and split archives. Reading an entry refuses encryption and other methods by
|
||||
name ("LZMA compression"), and checks the result: an entry must inflate to exactly its
|
||||
stated size (inflation stops at that size) and match its **CRC-32**.
|
||||
3. **Bombs: a ratio cap, an entry cap and a total budget.** Deflate can't pass about 1032 : 1,
|
||||
so an entry claiming more than **1024 : 1** (plus 4 KB) is refused before inflating as a
|
||||
bomb or a damaged size; no entry inflates past **256 MB**; and one archive hands out at
|
||||
most **1 GiB** over every read, so a document that names one large entry many times can't
|
||||
multiply it. The `.fla` itself is capped at 1 GiB, as before.
|
||||
4. **Nothing is extracted.** The reader only answers lookups from the importer, in memory; it
|
||||
never writes a file, so path checks keep lookups unambiguous and match the folder reader,
|
||||
which also refuses `..`, empty parts and drives. Safe Rust slicing means no read leaves the
|
||||
archive's bytes.
|
||||
5. **Every file form opens the same.** `import_path` takes an XFL folder, the `.xfl` pointer
|
||||
file inside it (or any file there, such as `DOMDocument.xml`), or a `.fla`, recognised by
|
||||
its first bytes too, so a renamed archive opens. A `.fla` saved by Flash CS4 or earlier (a
|
||||
compound binary file) is named in the error, with what to do: open it in Animate and save
|
||||
it again. `import_fla_with_fonts` joins `import_with_fonts` for tests and hosts.
|
||||
6. **The corpus in every layout, by an independent writer.** `crates/xfl/tests/support/fla.rs`
|
||||
packs a package into `.fla` archives in memory, written from the specification separately
|
||||
from the reader (its own CRC), in nine variants: as Animate writes it (the stored
|
||||
`mimetype` entry first), stored, mixed (XML deflated, images stored) with folder entries,
|
||||
Windows separators with unflagged names, CP437 names, Unicode path fields, data
|
||||
descriptors, ZIP64, and all of these at once. Every package must import **identically**
|
||||
to its folder (the same `Document`, the same report), from bytes and from disk, and render
|
||||
the same golden frames (`crates/engine/tests/xfl_corpus.rs`); one package is also checked
|
||||
with library names outside ASCII in every encoding.
|
||||
7. **A fuzz built from the corpus.** `hostile_fla_archives_never_panic_and_fail_readably`
|
||||
sets every central header field of the first entries to edge values, changes random bytes
|
||||
(in the directory, then anywhere), cuts each archive short, and builds archives with unsafe
|
||||
names, duplicates, overlaps, lying sizes and checksums, ratio bombs and deep folders:
|
||||
9,664 archives per run, none may panic, every failure must be a readable sentence, and the
|
||||
built attacks must all be refused.
|
||||
8. **CRC-32 by slicing by 8** (eight table lookups per eight bytes, Kounavis and Berry, 2005):
|
||||
checking every entry costs little. On a generated 54.6 MB `.fla` (400 symbols, 24 stored
|
||||
PNGs, 65.8 MB inflated), reading every entry fell from 128–140 ms (byte-wise table) to
|
||||
53–54 ms, and the whole import from 388–458 ms to 311–328 ms (`docs/performance.md`).
|
||||
|
||||
## Consequences
|
||||
|
||||
* A damaged or hostile `.fla` fails at once with a sentence that names the entry and the
|
||||
problem, and never takes the app down or its memory.
|
||||
* A good archive that some writer lays out in a way we haven't seen fails loudly rather than
|
||||
importing wrongly; a real file that does should become a new variant in the packer, not a
|
||||
special case.
|
||||
* Not in this slice: archives with data before the first entry (self-extracting zips, whose
|
||||
offsets are shifted), an XFL folder zipped inside a top folder (`name/DOMDocument.xml`),
|
||||
encrypted archives and other compression methods (all refused with a clear error), and
|
||||
sound and video items (reported, as before).
|
||||
+11
-6
@@ -36,7 +36,7 @@ app/ workspace root; the root package is the desktop app
|
||||
doc L1 Document model + timeline evaluation (keyframes, tweens, easing, symbols) + player
|
||||
render L2 CPU oracle rasterizer, paints/gradients, compositor, PNG encode
|
||||
engine L3 Session (document + history + selection + playhead), command registry, file format
|
||||
gpu L3 wgpu stage renderer over the oracle's prepared fills (ADR 0019, 0029, 0031; shell feature `gpu-stage`, on by default)
|
||||
gpu L3 wgpu stage renderer over the oracle's prepared fills (ADR 0019, 0029, 0032, 0048; shell feature `gpu-stage`, on by default)
|
||||
cli L4 `anicraft-cli`: info / render / render-seq / commands / run / serve (JSON-lines)
|
||||
src/ L5 egui shell: menus (from registry), tools, stage, timeline, properties, library
|
||||
docs/ requirements, architecture, roadmap
|
||||
@@ -185,11 +185,16 @@ DisplayList ──► for each item:
|
||||
Output is bit-identical to serial. Numbers are in [performance.md](performance.md).
|
||||
|
||||
**GPU stage** ([ADR 0019](adr/0019-gpu-stage.md), [ADR 0029](adr/0029-gpu-stage-direct-masks-groups.md),
|
||||
[ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md); the shell's `gpu-stage` feature, on
|
||||
by default, and the default stage renderer): `render::prepare_scene` hands the oracle's own
|
||||
prepared fills, with their clips, groups, bitmap shaders and filtered layers, to `anicraft-gpu`, which bins edge pieces into
|
||||
16 × 16 tiles with per-row backdrops (CPU, parallel) and writes each tile's stream of entries
|
||||
in drawing order, with clip-coverage and group open/close entries. One compute pass computes
|
||||
[ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md), [ADR 0048](adr/0048-gpu-binning-and-hairlines.md);
|
||||
the shell's `gpu-stage` feature, on by default, and the default stage renderer):
|
||||
`render::prepare_scene` hands the oracle's own prepared fills, with their clips, groups, bitmap
|
||||
shaders and filtered layers, to `anicraft-gpu`, which bins edge pieces into 16 × 16 tiles with
|
||||
an integer backdrop per tile and steps on the tiles' left edges, and writes each tile's stream
|
||||
of entries in drawing order. Heavy scenes without masks or groups are binned on the GPU (count,
|
||||
prefix sum, scatter and tile-list passes; the CPU only lays out the points and the fills'
|
||||
ranges, and sizes every buffer up front, so nothing is read back); the rest, with their
|
||||
clip-coverage and group open/close entries, on the CPU, which is also the reference. Outline
|
||||
mode's hairlines are one piece per segment, covered by distance in both renderers. One compute pass computes
|
||||
each pixel's exact area coverage and composites it as the oracle's band compositor does (clip
|
||||
coverage, a per-pixel group stack, the W3C blend modes). On the window's wgpu device it draws
|
||||
each stage tile into a texture egui shows as it is (no readback); otherwise on a headless
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
cargo build # app + CLI (debug)
|
||||
cargo run # desktop app with the sample
|
||||
cargo run -- --screenshot shots/now.png # draw ~120 frames, save the window, exit
|
||||
cargo run -- --open <panel> --screenshot x.png # palette|shortcuts|files|confirm|selection|transform|points|pen|frames|span|bucket|sound|tlzoom|tlwide|prefs|licenses|zoom
|
||||
cargo run -- --open <panel> --screenshot x.png # palette|shortcuts|files|confirm|selection|transform|points|pen|frames|span|bucket|sound|tlzoom|tlwide|prefs|licenses|zoom|editmultiple|edittransform|onionsymbol
|
||||
cargo run -- --theme high-contrast --scale 200 --screenshot x.png # a palette and interface scale for one run (not saved)
|
||||
cargo test # every crate
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
|
||||
+75
-3
@@ -37,6 +37,11 @@ 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` |
|
||||
| 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` |
|
||||
| GPU stage, 50k shapes at 4K, one texture | < 33.3 ms | 22.5–23.8 ms ✅ | `gpu_bench --check` |
|
||||
| GPU stage, onion ±5 outlines / tinted at 1080p, stage tiles | ≤ 1.25 | 1.03–1.06 ✅ | `gpu_bench --check` |
|
||||
|
||||
**1080p render, back under budget (2026-11-06).** It had drifted to 19.4–20.2 ms (v0.1.0
|
||||
measured 18.0–18.9 ms on the same machine; the 16.5 ms of 2026-10-28 didn't reproduce).
|
||||
@@ -68,8 +73,16 @@ order (an append, then a reorder). One k-way merge by layer, each item moved onc
|
||||
to 0.85 ms, and evaluating the extra frames in parallel brought the whole to 3.0–3.3 ms. Output
|
||||
is unchanged (the onion tests compare items and pixels). The settings are part of every tile's
|
||||
key, so the frame cache keeps working: looking at the same frame again is 40 hits in 0.02 ms,
|
||||
and other settings are other pictures. Hairline outlines cost more to rasterize than fills, so
|
||||
outline mode on very heavy scenes is the slow case.
|
||||
and other settings are other pictures.
|
||||
|
||||
**Outlines as hairlines (2026-11-10, ADR 0048).** Outline mode drew half-pixel strokes (four
|
||||
edges per segment and a disc at every bend); it now draws hairlines, one edge per segment,
|
||||
covered by distance. Same test, same machine:
|
||||
|
||||
| Scene | Off | ±5 tinted, fading | ±5 outlines | Keyframes only ±5 | Edit Multiple Frames ±5 |
|
||||
|---|---|---|---|---|---|
|
||||
| Sample | 5.7 ms | 5.9 ms | 5.5 ms | 5.9 ms | 5.7 ms |
|
||||
| Stress 20 × 100 | 7.6 ms | 14.8 ms | **17.1 ms** (was 34–39) | 7.3 ms | 7.2 ms |
|
||||
|
||||
**Crash-recovery autosave (2026-11-09, ADR 0015).** `bench` now runs one autosave the way the
|
||||
app does: an `Autosaver` in a scratch recovery folder. The editing thread only hands over an
|
||||
@@ -84,6 +97,24 @@ flushed to disk, renamed).
|
||||
With the default "every minute or 25 changes", even the 262 MB document keeps the worker busy
|
||||
for about 1% of the time, and the UI never waits for it.
|
||||
|
||||
**Opening a 50 MB `.fla` (2026-11-11, ADR 0054; release, 32 threads, one used).** A generated
|
||||
archive (`measure_importing_a_50_mb_fla` in `crates/xfl/tests/fla.rs`: 400 symbols of 600
|
||||
edges each, deflated, and 24 noisy 1024 × 512 PNGs, stored; 54.6 MB, 425 files, 65.8 MB
|
||||
inflated), five runs each:
|
||||
|
||||
```sh
|
||||
cargo test --release -p anicraft-xfl --test fla -- --ignored --nocapture
|
||||
```
|
||||
|
||||
| Step | CRC-32 byte by byte | CRC-32 by slicing by 8 |
|
||||
|---|---|---|
|
||||
| Open (end record, central directory, every local header, overlap check) | 0.19–0.25 ms | 0.18–0.24 ms |
|
||||
| Read and check every entry (inflate, size, CRC) | 128–140 ms (471–516 MB/s) | 53–54 ms (1.22–1.24 GB/s) |
|
||||
| Whole import (read, XML, edges, library, timeline) | 388–458 ms | **311–328 ms** |
|
||||
|
||||
The checks on every entry (exact size, checksum) now cost about 30 ms of the import; the rest
|
||||
is parsing and building the document.
|
||||
|
||||
### GPU stage (M3, ADR 0019)
|
||||
|
||||
`cargo run --release -p anicraft-gpu --example gpu_bench` (2026-11-09, RTX 5090 over Vulkan,
|
||||
@@ -147,6 +178,44 @@ layer across a frame's tiles is next. The one large difference is a single pixel
|
||||
falls within float rounding of a non-repeating bitmap's edge (ADR 0032). Bitmaps are uploaded
|
||||
once per image and cached (256 MB budget), so after the first frame they cost no transfer.
|
||||
|
||||
### GPU stage, fourth slice: binning on the GPU, hairlines (M3, ADR 0048)
|
||||
|
||||
`cargo run --release -p anicraft-gpu --example gpu_bench` (2026-11-10, RTX 5090 over Vulkan,
|
||||
32 threads, a machine shared with other builds: best of three runs). *Direct* is the calling
|
||||
thread's time with `render_texture`, *tiled* the stage's way (512 px tiles in parallel until
|
||||
the GPU has finished).
|
||||
|
||||
| Scene | Size | CPU oracle | Before: direct / tiled | After, binned on the CPU: direct / tiled | After, Auto: direct / tiled | Parity (mean / max, 1/255) |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Stress, 50 × 200 (≈10k shapes) | 1920×1080 | 9.8 ms | 9.0 / 7.4 ms | 8.6 / 5.5 ms | **3.9** / 5.5 ms | < 0.0001 / 1 |
|
||||
| Stress, 50 × 200 | 3840×2160 | 25.9 ms | 21.7 / 10.9 ms | 16.4 / 10.1 ms | **4.7** / 10.1 ms | < 0.0001 / 1 |
|
||||
| 1,000 shapes (binned on the CPU: few edges) | 3840×2160 | 16.9 ms | 2.2 / 4.5 ms | 1.6 / 4.2 ms | 1.7 / 4.5 ms | < 0.0001 / 1 |
|
||||
| 50,000 shapes (250 × 200) | 1920×1080 | 31.7 ms | 52.2 / 32.4 ms | 33.5 / 26.8 ms | **17.7** / 24.8 ms | < 0.0001 / 1 |
|
||||
| 50,000 shapes | 3840×2160 | 73.1 ms | 122.1 / 75.3 ms | 103.9 / 61.5 ms | **22.5** / **36.7** ms | < 0.0001 / 1 |
|
||||
| Masked stress (binned on the CPU: masks) | 3840×2160 | 72.4 ms | 13.8 / 12.3 ms | 12.0 / 10.7 ms | 11.3 / 10.5 ms | < 0.0001 / 1 |
|
||||
| Onion skin off (stress 20 × 100) | 1920×1080 | 5.0 ms | 2.1 / 2.7 ms | 1.8 / 2.2 ms | 1.1 / 2.3 ms | < 0.0001 / 1 |
|
||||
| Onion ±5, tinted (22,000 items) | 1920×1080 | 15.1 ms | 15.7 / 12.6 ms | 12.8 / 10.5 ms | 7.1 / 9.8 ms | < 0.0001 / 1 |
|
||||
| Onion ±5, tinted | 3840×2160 | 37.3 ms | 32.1 / 25.1 ms | 20.3 / 22.0 ms | 8.5 / 16.5 ms | 0.0001 / 1 |
|
||||
| Onion ±5, **outlines** | 1920×1080 | 20.0 ms (was 36.0) | 74.7 / 73.0 ms | 12.9 / 10.4 ms | 7.3 / **10.1** ms | < 0.0001 / 1 |
|
||||
| Onion ±5, **outlines** | 3840×2160 | 37.9 ms (was 60.2) | 135.4 / 95.4 ms | 20.3 / 18.1 ms | 8.6 / **15.3** ms | < 0.0001 / 1 |
|
||||
|
||||
*Before* is `main` before this slice (CPU binning with float backdrops, stroked hairlines),
|
||||
measured the same day on the same machine. In stage tiles the GPU binning wins once frames are
|
||||
heavy (50k shapes: 61.5 → 36.7 ms at 4K) and never loses below `AUTO_MIN_EDGES`; a whole frame
|
||||
in one texture gains most (10k shapes at 4K: 16.4 → 4.7 ms). **Outline mode is as fast as
|
||||
tinted onion skin** on the GPU stage: 10.1 vs 9.8 ms at 1080p in tiles, 15.3 vs 16.5 ms at 4K,
|
||||
7.3 vs 7.1 ms in one texture (it was 73 vs 12.6 ms in tiles).
|
||||
|
||||
On **Direct3D 12** (same card, `WGPU_BACKEND=dx12`, two runs) the GPU binning still wins in
|
||||
one texture (10k shapes at 4K: 17.5 → 6.3 ms; 50k: 154 → 30 ms) but loses in stage tiles
|
||||
(onion ±5 at 1080p: 9.7 → 14.4 ms tinted, 10.0 → 15.4 ms outlines; the passes cost more per
|
||||
dispatch there, as ADR 0032 saw for the fine pass), so `Binning::Auto` bins on the GPU on
|
||||
Vulkan only. With CPU binning, DX12's onion outlines take 10.1 ms in tiles against 10.0 tinted.
|
||||
|
||||
The CPU stage (the oracle through the render service's 256 px tiles, `onion_timings`, best of
|
||||
frames 12, 30 and 48) with hairlines: onion ±5 outlines **17.1 ms** against 14.8 tinted at
|
||||
1080p (was 34–39 against 16.2–17.2).
|
||||
|
||||
### How budgets are enforced
|
||||
|
||||
* **Budgets that don't depend on the machine** (undo memory, snapshot sharing, file size,
|
||||
@@ -158,7 +227,8 @@ once per image and cached (256 MB budget), so after the first frame they cost no
|
||||
machine before a release and after performance work. A dedicated benchmark runner would
|
||||
let CI run it too.
|
||||
* The limits live in `TIME_BUDGETS` in `crates/cli/src/lib.rs`; keep that list and this
|
||||
table in step.
|
||||
table in step. The GPU stage's are `BUDGETS` in `crates/gpu/examples/gpu_bench.rs`
|
||||
(`--check`; the CLI has no GPU).
|
||||
|
||||
## Sound (2026-11-09, ADR 0020)
|
||||
|
||||
@@ -187,3 +257,5 @@ buffer is tiny; the stage never waits on sound.
|
||||
groups on the GPU, binning kept on the CPU
|
||||
* [ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md): bitmaps and filters on the GPU,
|
||||
Direct3D 12, and the GPU as the default stage renderer
|
||||
* [ADR 0048](adr/0048-gpu-binning-and-hairlines.md): tile binning on the GPU, one tile format
|
||||
for both binnings, and hairlines for outline mode
|
||||
+21
-11
@@ -9,14 +9,15 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| Dimension | Status |
|
||||
|---|---|
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. |
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. Not yet: per-layer onion toggles, deleting/transforming/copying across keyframes in Edit Multiple Frames, re-merging raw shapes moved there. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, ovLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click Line truncated
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatchLine truncated
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exportsLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click Line truncated
|
||||
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. |
|
||||
| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). Not yet: ActionScript variables, conditions, reading properties, `removeEventListener`, enter-frame and keyboard events, functions from other frames, event bubbling, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. |
|
||||
| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. |
|
||||
| Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. |
|
||||
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). |
|
||||
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buLine truncated
|
||||
| Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. |
|
||||
| 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. |
|
||||
| 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 (Graphite or High contrast), 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). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. |
|
||||
@@ -31,10 +32,10 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| M | Theme | Exit criteria |
|
||||
|---|---|---|
|
||||
| **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. |
|
||||
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. |
|
||||
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
|
||||
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); GPU binning deferred (not the bottleneck as tiles); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: shared filtered layers across tiles, an image atlas, GPU exports. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); not yet: `.fla` variants of the corpus, sound and video items; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. |
|
||||
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. |
|
||||
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
|
||||
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, fallback faces for letters the chosen font lacks, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039; button sounds and XFL sounds later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. |
|
||||
@@ -54,7 +55,7 @@ titled with its milestone.
|
||||
| Track | Next task | Depends on (all done) |
|
||||
|---|---|---|
|
||||
| M2 | Motion tweens with property curves and the Motion Editor | timeline evaluation, classic tweens |
|
||||
| M3 | GPU stage: filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032) | CPU oracle, tiled stage, GPU stage slices 1–3 |
|
||||
| M3 | GPU stage: GPU binning inside masks and groups, filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032, GPU binning and hairlines ✅ ADR 0048) | CPU oracle, tiled stage, GPU stage slices 1–4 |
|
||||
| M4 | Text from Animate files | XFL import, text engine (M5 first slice) |
|
||||
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); next: command macros, or growing the ActionScript subset (variables and conditions) | command registry, plug-in host, action IR and player |
|
||||
@@ -100,8 +101,17 @@ Next, in order:
|
||||
segment or fill moves what is connected, arrow keys; Snap to Objects (View › Snapping, the
|
||||
magnet); the Paint Bucket's fills (exact, up to the lines) and pasted raw shapes merge;
|
||||
raw shapes from Animate files come in raw; gradients take part in the merge. Not yet:
|
||||
width profiles in the merge, deleting or adding raw anchors, smooth handle pairs, a
|
||||
default Snap to Objects shortcut.
|
||||
width profiles in the merge.
|
||||
* ~~**Raw points and raw shapes inside symbols** (ADR 0045)~~ ✅: add a point on a raw line
|
||||
or fill edge (Pen Alt-click, Subselection double-click), shared by every shape on the edge;
|
||||
delete raw points (the shapes on them joined across, the drawing kept connected; a line's
|
||||
last points remove it); Make Smooth / Corner on raw points; smooth handle pairs (Alt breaks
|
||||
them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap while
|
||||
drawing; Snap to Objects is Ctrl+Shift+/; **symbols open for editing in place**
|
||||
(double-click an instance or a Library symbol, Ctrl+E; the edit bar's path back), where
|
||||
merge drawing, Selection and Subselection work as on the stage. Not yet: in-place editing
|
||||
of rotated instances (they open upright), deleting a point where three edges meet. (Onion
|
||||
skin and Edit Multiple Frames inside a symbol: ADR 0051 ✅.)
|
||||
1. M4 **XFL import, next slices**: ~~masks (with M2 mask layers)~~ ✅, ~~shape tweens~~ ✅,
|
||||
~~every scene~~ ✅, ~~bitmaps~~ ✅ (PNG/JPEG data), ~~text~~ ✅ (one style per line; per-character styles with
|
||||
the text model), motion tweens, and ~~a larger self-authored
|
||||
|
||||
+1
-1
@@ -352,7 +352,7 @@ mod tests {
|
||||
for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
|
||||
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
|
||||
}
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple"] {
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap"] {
|
||||
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
// The layer depth row shows on artwork layers once the scene has a camera.
|
||||
|
||||
@@ -444,7 +444,7 @@ fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&S
|
||||
fn frame_target(app: &mut App, ui: &mut egui::Ui, doc: &Document) -> Option<FrameTarget> {
|
||||
match app.actions.symbol {
|
||||
None => {
|
||||
let tl = doc.timeline(app.s.scene);
|
||||
let tl = app.s.timeline().clone();
|
||||
let layer = tl.layer(app.s.layer)?;
|
||||
let frame = app.s.frame;
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Keyframe"), |ui| {
|
||||
@@ -581,7 +581,7 @@ fn instance_tab(app: &mut App, ui: &mut egui::Ui, e: &Element) {
|
||||
ui.label(text(Type::Caption, tr!("Name it to address it from actions (letters, digits and _). Its events work without a name.")));
|
||||
}
|
||||
let ElementKind::Symbol { events, .. } = &e.kind else { return };
|
||||
let tl = doc.timeline(app.s.scene).clone();
|
||||
let tl = app.s.timeline().clone();
|
||||
let cx = Choices::new(&doc, &tl, true);
|
||||
ui.add_space(4.0);
|
||||
ui.label(text(Type::Caption, tr!("Its actions run on the timeline it is on: “this” is the main timeline.")));
|
||||
|
||||
+161
-40
@@ -121,8 +121,8 @@ impl Tool {
|
||||
pub fn hint(self) -> &'static str {
|
||||
match self {
|
||||
Tool::Select => tr_noop!("Click to select, drag to move, drag on empty space to marquee-select. Shift adds to the selection."),
|
||||
Tool::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. On drawing objects, double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay)."),
|
||||
Tool::Pen => tr_noop!("Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point. Alt-click a selected shape or a motion path to add a point to it."),
|
||||
Tool::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it; a smooth point's handles stay in line, Alt moves one alone); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. Double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay)."),
|
||||
Tool::Pen => tr_noop!("Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point. Alt-click a selected shape, a merged drawing's line or a motion path to add a point to it. Points snap to points and lines while Snap to Objects is on."),
|
||||
Tool::Text => tr_noop!("Click to type new text, or click text to edit it. Esc or a click elsewhere finishes. The options set the font, size and colour; double-click text with the Selection tool to edit it too."),
|
||||
Tool::Pencil => tr_noop!("Drag to draw freehand. The options bar sets Smooth, Straighten or Ink."),
|
||||
Tool::Brush => tr_noop!("Drag to paint filled shapes in the fill colour (a click paints a dab). [ and ] change the size; the options set the shape, smoothing and paint mode."),
|
||||
@@ -194,6 +194,9 @@ pub enum Drag {
|
||||
/// pointer at `last` last frame; or a marquee over them.
|
||||
MultiMove { last: egui::Pos2 },
|
||||
MultiMarquee { start: egui::Pos2, cur: egui::Pos2 },
|
||||
/// Free Transform on Edit Multiple Frames' selection (ADR 0051): as `Transform`, on every
|
||||
/// keyframe the selection is on, about one shared pivot.
|
||||
MultiTransform { kind: XfKind, start: egui::Pos2, bounds: [f32; 4], applied: anicraft_engine::geom::Affine },
|
||||
Shape { start: egui::Pos2, cur: egui::Pos2 },
|
||||
/// Subselection: dragging the selected points (stage position of the last frame).
|
||||
Points { last: egui::Pos2 },
|
||||
@@ -269,19 +272,7 @@ pub struct Shot {
|
||||
pub const SHOT_FRAMES: u32 = 120;
|
||||
|
||||
/// The item picked in the Library panel (view state).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LibraryItem {
|
||||
Symbol(anicraft_engine::doc::SymbolId),
|
||||
Bitmap(anicraft_engine::doc::BitmapId),
|
||||
Sound(anicraft_engine::doc::SoundId),
|
||||
}
|
||||
|
||||
impl LibraryItem {
|
||||
/// The first item in the Library: its first symbol, else its first bitmap, else sound.
|
||||
pub fn first(doc: &anicraft_engine::doc::Document) -> Option<LibraryItem> {
|
||||
doc.library.first().map(|s| LibraryItem::Symbol(s.id)).or_else(|| doc.bitmaps.first().map(|b| LibraryItem::Bitmap(b.id))).or_else(|| doc.sounds.first().map(|s| LibraryItem::Sound(s.id)))
|
||||
}
|
||||
}
|
||||
pub use anicraft_engine::doc::LibraryItem;
|
||||
|
||||
pub struct App {
|
||||
pub s: Session,
|
||||
@@ -303,6 +294,9 @@ pub struct App {
|
||||
pub last_tool: Tool,
|
||||
pub status: Option<Status>,
|
||||
pub prompt: Option<Prompt>,
|
||||
/// The Convert to Symbol dialog, and what it chose last (ADR 0053).
|
||||
pub convert: Option<crate::convert_symbol::ConvertDialog>,
|
||||
pub convert_last: crate::convert_symbol::Last,
|
||||
pub show_about: bool,
|
||||
pub show_files: bool,
|
||||
pub show_licenses: bool,
|
||||
@@ -317,6 +311,8 @@ pub struct App {
|
||||
/// Folders shown closed on the timeline (view state: not saved, not undoable).
|
||||
pub tl_collapsed: HashSet<anicraft_engine::doc::LayerId>,
|
||||
pub library_sel: Option<LibraryItem>,
|
||||
/// The Library panel's folders, selection, sorting, search and preview (ADR 0050).
|
||||
pub library: crate::library::LibraryView,
|
||||
/// Text being typed on the stage.
|
||||
pub text_edit: Option<TextEditing>,
|
||||
/// Font families on this computer, listed once on first need.
|
||||
@@ -460,7 +456,7 @@ impl App {
|
||||
let prefs = if shot_mode { prefs::Prefs::default() } else { prefs::Prefs::load() };
|
||||
let keymap = keymap::Keymap::new(&prefs.shortcuts);
|
||||
let shortcuts = keymap.table();
|
||||
let library_sel = LibraryItem::first(&session.doc);
|
||||
let library_sel = crate::library::first_item(&session.doc);
|
||||
let (recovery, recovery_err) = autosave::Recovery::start(shot_mode);
|
||||
// Text lays out with the fonts on this computer plus the embedded interface font (so new
|
||||
// text has the same default everywhere). Scan them now, off the UI thread.
|
||||
@@ -489,6 +485,8 @@ impl App {
|
||||
last_tool: Tool::Select,
|
||||
status: None,
|
||||
prompt: None,
|
||||
convert: None,
|
||||
convert_last: Default::default(),
|
||||
show_about: false,
|
||||
show_files: false,
|
||||
show_licenses: false,
|
||||
@@ -500,6 +498,7 @@ impl App {
|
||||
tl_last_layer: None,
|
||||
tl_collapsed: HashSet::new(),
|
||||
library_sel,
|
||||
library: Default::default(),
|
||||
text_edit: None,
|
||||
font_families: None,
|
||||
star_points: 5,
|
||||
@@ -575,7 +574,7 @@ impl App {
|
||||
/// through, so it says how to add one.
|
||||
pub fn toggle_camera_preview(&mut self) {
|
||||
self.camera_preview = !self.camera_preview;
|
||||
if self.camera_preview && self.s.doc.timeline(self.s.scene).camera_layer().is_none() {
|
||||
if self.camera_preview && self.s.timeline().camera_layer().is_none() {
|
||||
self.status_ok(tr!("Preview through camera is on; add a camera (the camera button on the timeline, or the Camera tool) to look through it."));
|
||||
}
|
||||
}
|
||||
@@ -784,6 +783,66 @@ impl App {
|
||||
self.scan_system_fonts();
|
||||
}
|
||||
Some("confirm") => self.request("layer.delete", json!({})),
|
||||
Some(which @ ("library" | "librarymenu")) => {
|
||||
// Library folders with an item inside, a copy, the item previewed (ADR 0050).
|
||||
let ball = self.s.doc.library.first().map(|s| s.id);
|
||||
let folder = self.run("library.new_folder", json!({"name": "Characters"})).and_then(|v| v["folder"].as_u64());
|
||||
self.run("library.new_folder", json!({"name": "Props"}));
|
||||
if let (Some(ball), Some(f)) = (ball, folder) {
|
||||
self.run("library.duplicate", json!({"symbol": ball.0}));
|
||||
self.run("library.move", json!({"items": [{"symbol": ball.0}], "to": f}));
|
||||
self.library.expanded.insert(anicraft_engine::doc::FolderId(f));
|
||||
self.library_sel = Some(LibraryItem::Symbol(ball));
|
||||
self.library.sel = vec![anicraft_engine::doc::LibraryEntry::Item(LibraryItem::Symbol(ball))];
|
||||
}
|
||||
if which == "librarymenu" {
|
||||
crate::library::select_unused(self);
|
||||
}
|
||||
}
|
||||
Some("convert") => {
|
||||
// Convert to Symbol with folders to choose from, the last one used offered again
|
||||
// (ADR 0053).
|
||||
let folder = self.run("library.new_folder", json!({"name": "Characters"})).and_then(|v| v["folder"].as_u64());
|
||||
self.run("library.new_folder", json!({"name": "Props"}));
|
||||
self.run("draw.rect", json!({"x": 820, "y": 120, "w": 140, "h": 90, "fill": "#e0a030", "object": true}));
|
||||
self.convert_last = crate::convert_symbol::Last { folder: folder.map(anicraft_engine::doc::FolderId), kind: anicraft_engine::doc::SymbolKind::MovieClip };
|
||||
crate::convert_symbol::open(self);
|
||||
}
|
||||
Some("mixed") => {
|
||||
// Two movie clips that differ in blending and filters, selected: those rows say
|
||||
// "mixed" (ADR 0053).
|
||||
if let Some(ball) = self.s.doc.library.first().map(|s| s.id.0) {
|
||||
self.run("edit.deselect", json!({}));
|
||||
self.run("symbol.set_kind", json!({"symbol": ball, "kind": "movie_clip"}));
|
||||
let id = |v: Option<Value>| v.and_then(|v| v["element"].as_u64()).unwrap_or(0);
|
||||
let a = id(self.run("library.place", json!({"symbol": ball, "x": 760, "y": 180})));
|
||||
let b = id(self.run("library.place", json!({"symbol": ball, "x": 900, "y": 220})));
|
||||
self.run("element.set_blend", json!({"mode": "multiply"}));
|
||||
self.run("element.set_filters", json!({"filters": [{"type": "glow"}]}));
|
||||
self.run("element.select", json!({"ids": [a, b]}));
|
||||
}
|
||||
}
|
||||
Some("bitmap") => {
|
||||
// Two placed bitmaps of different images, selected: the Bitmap row with Swap…
|
||||
// says "mixed" (ADR 0053).
|
||||
let dir = std::env::temp_dir().join("anicraft-shot-bitmaps");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let mut ids = Vec::new();
|
||||
for (name, w, h, px) in [("checker.png", 8u32, 8u32, [40u8, 120, 220, 255]), ("sunset.png", 12, 6, [230, 120, 40, 255])] {
|
||||
let path = dir.join(name);
|
||||
let Ok(png) = anicraft_engine::render::encode_png(w, h, &px.repeat((w * h) as usize)) else { continue };
|
||||
if std::fs::write(&path, png).is_err() {
|
||||
continue;
|
||||
}
|
||||
if let Some(b) = self.run("file.import_to_library", json!({"path": path.display().to_string(), "name": name})).and_then(|v| v["bitmap"].as_u64()) {
|
||||
let at = 700 + 160 * ids.len();
|
||||
if let Some(e) = self.run("library.place", json!({"bitmap": b, "x": at, "y": 200})).and_then(|v| v["element"].as_u64()) {
|
||||
ids.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.run("element.select", json!({"ids": ids}));
|
||||
}
|
||||
Some(which @ ("onion" | "onionmenu")) => {
|
||||
// Onion skin ±5 on a frame with frames before and after it, the markers on the
|
||||
// ruler; with its menu open, in outlines (ADR 0047).
|
||||
@@ -802,6 +861,30 @@ impl App {
|
||||
self.run("timeline.goto", json!({"frame": 12}));
|
||||
crate::onion::select_all(self);
|
||||
}
|
||||
Some("edittransform") => {
|
||||
// Free Transform on Edit Multiple Frames' selection (ADR 0051): one box, one
|
||||
// pivot, over the artwork on every keyframe between the markers.
|
||||
self.onion.preset(5);
|
||||
crate::onion::toggle_edit_multiple(self);
|
||||
self.run("timeline.goto", json!({"frame": 12}));
|
||||
self.tool = Tool::Transform;
|
||||
crate::onion::select_all(self);
|
||||
// The bouncing ball on its keyframes.
|
||||
let top = self.s.timeline().layers.first().map(|l| l.id);
|
||||
self.onion_ui.sel.retain(|it| Some(it.layer) == top);
|
||||
}
|
||||
Some("onionsymbol") => {
|
||||
// Onion skin inside a symbol open in place (ADR 0051): the sample's spinning star,
|
||||
// its own frames before and after its playhead around it.
|
||||
let star = self.s.timeline().layers.iter().flat_map(|l| l.keyframes.iter().flat_map(|k| k.elements.iter())).find(|e| e.name == "star").map(|e| e.id.0);
|
||||
if let Some(id) = star {
|
||||
self.run("element.select", json!({"ids": [id]}));
|
||||
self.run("symbol.edit", json!({}));
|
||||
self.run("timeline.goto", json!({"frame": 12}));
|
||||
}
|
||||
self.onion.ghosts = true;
|
||||
self.onion.preset(5);
|
||||
}
|
||||
Some("selection") => {
|
||||
// A selection across layers (ADR 0044): Select All takes every unlocked layer's
|
||||
// artwork; the timeline marks the layers, Properties says how many.
|
||||
@@ -984,6 +1067,49 @@ impl App {
|
||||
self.drag = Drag::RawHandle { id: h.id, cmd: h.cmd, slot: h.slot, last: egui::pos2(h.at.x + 40.0, h.at.y + 10.0) };
|
||||
}
|
||||
}
|
||||
Some("rawpoints") => {
|
||||
// Raw points (ADR 0045) on a new layer: an outlined square whose top-left corner
|
||||
// was deleted (the fill and its outline joined across the diagonal), and a point
|
||||
// added on its right side, pulled out and made smooth, selected with its handle
|
||||
// pair showing.
|
||||
self.run("layer.new", json!({}));
|
||||
self.run("draw.rect", json!({"x": 240, "y": 140, "w": 320, "h": 260, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false}));
|
||||
self.run("draw.ellipse", json!({"x": 640, "y": 170, "w": 240, "h": 200, "fill": "#3d8bfd", "stroke": "#1b2a4a", "stroke_width": 3, "object": false}));
|
||||
self.run("edit.deselect", json!({}));
|
||||
self.run("raw.delete_points", json!({"points": [[240, 140]]}));
|
||||
self.run("raw.add_point", json!({"x": 560, "y": 270}));
|
||||
self.run("raw.move_point", json!({"x": 560, "y": 270, "to_x": 620, "to_y": 270}));
|
||||
self.run("raw.convert_points", json!({"points": [[620, 270]], "smooth": true}));
|
||||
self.tool = Tool::Subselect;
|
||||
self.run("raw.subselect", json!({"x": 400, "y": 400, "slop": 4}));
|
||||
self.raw_ends = Vec::new();
|
||||
self.raw_anchors = vec![anicraft_engine::geom::Vec2::new(620.0, 270.0)];
|
||||
}
|
||||
Some("rawsnap") => {
|
||||
// Snapping while drawing (ADR 0045): a line being drawn from a corner of a raw
|
||||
// square, its end snapping onto the square's other corner (the ring).
|
||||
self.run("layer.new", json!({}));
|
||||
self.run("draw.rect", json!({"x": 240, "y": 140, "w": 320, "h": 260, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false}));
|
||||
self.run("edit.deselect", json!({}));
|
||||
self.tool = Tool::Line;
|
||||
self.drag = Drag::Shape { start: egui::pos2(240.0, 400.0), cur: egui::pos2(560.0, 140.0) };
|
||||
self.snap_ring = Some(anicraft_engine::geom::Vec2::new(560.0, 140.0));
|
||||
}
|
||||
Some("symboledit") => {
|
||||
// A symbol open for editing in place (ADR 0045): a raw drawing inside it, merged
|
||||
// with a line drawn across it there, its connected points showing under the
|
||||
// Subselection tool; the stage around it dimmed, the way back above.
|
||||
self.run("layer.new", json!({}));
|
||||
self.run("draw.rect", json!({"x": 260, "y": 160, "w": 300, "h": 220, "fill": "#e8553b", "stroke": "#1b2a4a", "stroke_width": 3, "object": false}));
|
||||
self.run("modify.convert_to_symbol", json!({"name": "Badge"}));
|
||||
self.run("symbol.edit", json!({}));
|
||||
self.run("draw.line", json!({"x0": -190, "y0": 40, "x1": 190, "y1": -40, "stroke": "#1b2a4a", "stroke_width": 3, "object": false}));
|
||||
self.run("draw.ellipse", json!({"x": 60, "y": -150, "w": 140, "h": 140, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false}));
|
||||
self.run("edit.deselect", json!({}));
|
||||
self.tool = Tool::Subselect;
|
||||
self.run("raw.subselect", json!({"x": 0, "y": 60, "slop": 4}));
|
||||
self.raw_ends = Vec::new();
|
||||
}
|
||||
Some(which @ ("brush" | "brushing")) => {
|
||||
// Brushed artwork on a new layer (ADR 0033): a pressure-tapered wave, a flat
|
||||
// calligraphic tip at 45°, square dabs, and a pink stroke painted behind a raw
|
||||
@@ -1051,7 +1177,7 @@ impl App {
|
||||
Some("frames") => {
|
||||
// Frames 8–20 selected on the top three layers, with a keyframe drag in progress:
|
||||
// 6 frames later and one layer down.
|
||||
let layers = &self.s.doc.timeline(self.s.scene).layers;
|
||||
let layers = &self.s.timeline().layers;
|
||||
if let (Some(a), Some(b)) = (layers.first(), layers.get(2)) {
|
||||
self.frame_sel = Some(timeline::FrameSel { anchor: (a.id, 7), head: (b.id, 19) });
|
||||
self.tl_drag = timeline::TlDrag::Move { grab: 10, by: 6, grab_row: 0, rows_by: 1 };
|
||||
@@ -1164,7 +1290,7 @@ impl App {
|
||||
}
|
||||
Some("span") => {
|
||||
// Stretching the Star layer's span by its end, with the length readout.
|
||||
if let Some(l) = self.s.doc.timeline(self.s.scene).layers.get(1)
|
||||
if let Some(l) = self.s.timeline().layers.get(1)
|
||||
&& let Some(k) = l.keyframes.first()
|
||||
{
|
||||
self.tl_drag = timeline::TlDrag::Span { layer: l.id, start: k.start, end: k.end(), to: k.end() + 6 };
|
||||
@@ -1273,7 +1399,7 @@ impl App {
|
||||
|
||||
/// Any modal (prompt, confirmation, close guard) is open: global shortcuts pause.
|
||||
pub fn modal_open(&self) -> bool {
|
||||
self.prompt.is_some() || self.confirm.is_some() || self.close_dialog || self.plugin_dialog.is_some()
|
||||
self.prompt.is_some() || self.convert.is_some() || self.confirm.is_some() || self.close_dialog || self.plugin_dialog.is_some()
|
||||
}
|
||||
|
||||
/// The single entry point for user-initiated commands: asks first when the engine says the
|
||||
@@ -1298,7 +1424,7 @@ impl App {
|
||||
if let Some(session) = restored {
|
||||
self.view.fit = true;
|
||||
self.frame_sel = None;
|
||||
self.library_sel = LibraryItem::first(&self.s.doc);
|
||||
self.library_sel = crate::library::first_item(&self.s.doc);
|
||||
self.decode_sounds();
|
||||
self.recovery.restored(&session);
|
||||
let name = self.s.path.as_deref().and_then(std::path::Path::file_name).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned());
|
||||
@@ -1315,7 +1441,7 @@ impl App {
|
||||
match id {
|
||||
"file.new" | "file.new_sample" | "file.open" => {
|
||||
self.view.fit = true;
|
||||
self.library_sel = LibraryItem::first(&self.s.doc);
|
||||
self.library_sel = crate::library::first_item(&self.s.doc);
|
||||
self.decode_sounds();
|
||||
match v.get("report").and_then(Value::as_str) {
|
||||
// An imported file: say what came across and what didn't, and that saving
|
||||
@@ -1327,7 +1453,7 @@ impl App {
|
||||
"file.recover" => {
|
||||
self.view.fit = true;
|
||||
self.frame_sel = None;
|
||||
self.library_sel = LibraryItem::first(&self.s.doc);
|
||||
self.library_sel = crate::library::first_item(&self.s.doc);
|
||||
self.recovery.restored(v["recovered"].as_str().unwrap_or(""));
|
||||
let name = v["name"].as_str().unwrap_or(tr!("Untitled"));
|
||||
self.status_ok(if v["original_newer"].as_bool() == Some(true) {
|
||||
@@ -1462,21 +1588,10 @@ impl App {
|
||||
self.status_err(crate::i18n::t(why));
|
||||
return;
|
||||
}
|
||||
// Edit Multiple Frames (ADR 0047) selects on every keyframe between the markers.
|
||||
if crate::onion::editing(self) {
|
||||
match id {
|
||||
"edit.select_all" => return crate::onion::select_all(self),
|
||||
"edit.deselect" => {
|
||||
self.onion_ui.sel.clear();
|
||||
return;
|
||||
}
|
||||
// This slice moves artwork across keyframes; other edits stay on one frame.
|
||||
"edit.delete" | "edit.cut" | "edit.copy" | "edit.duplicate" if !self.onion_ui.sel.is_empty() => {
|
||||
self.status_err(tr!("Edit Multiple Frames moves artwork on several keyframes; to delete, copy or duplicate it, turn Edit Multiple Frames off and work frame by frame."));
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Edit Multiple Frames (ADR 0047, 0051) selects and edits on every keyframe between the
|
||||
// markers: the Edit menu, Align and Transform act there.
|
||||
if crate::onion::editing(self) && crate::onion::invoke(self, id) {
|
||||
return;
|
||||
}
|
||||
if id == "timeline.paste_frames"
|
||||
&& let Some(p) = timeline::paste_params(self)
|
||||
@@ -1509,6 +1624,11 @@ impl App {
|
||||
self.show_plugins = true;
|
||||
return;
|
||||
}
|
||||
if id == "modify.convert_to_symbol" {
|
||||
// Name, type and Library folder (ADR 0053).
|
||||
crate::convert_symbol::open(self);
|
||||
return;
|
||||
}
|
||||
if id == "edit.paste" {
|
||||
// Paste in the centre of what you are looking at.
|
||||
let c = self.view_center_stage();
|
||||
@@ -1533,7 +1653,6 @@ impl App {
|
||||
"file.import_to_library" => Some((tr_noop!("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)"), "path", "sound.wav".to_string())),
|
||||
"file.import" => Some((tr_noop!("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)"), "path", "drawing.svg".to_string())),
|
||||
"plugin.install" => Some((tr_noop!("Install plug-in (.wasm file)"), "path", "plugin.wasm".to_string())),
|
||||
"modify.convert_to_symbol" => Some((tr_noop!("Convert to symbol — name"), "name", format!("Symbol {}", self.s.doc.library.len() + 1))), // i18n-exempt: a new symbol's default name is document text
|
||||
_ => None,
|
||||
};
|
||||
if let Some((title, key, text)) = prompt {
|
||||
@@ -1761,6 +1880,7 @@ impl App {
|
||||
crate::widthtool::consume_keys(self, ctx);
|
||||
crate::bone_tool::consume_keys(self, ctx);
|
||||
}
|
||||
crate::library::consume_keys(self, ctx);
|
||||
let mut fire: Vec<&'static str> = Vec::new();
|
||||
let mut tool = None;
|
||||
let mut play = false;
|
||||
@@ -1800,7 +1920,7 @@ impl App {
|
||||
self.status_ok(if self.align_to_stage { tr!("Align: to stage") } else { tr!("Align: to the selection") });
|
||||
}
|
||||
"view.select_all_frames" => {
|
||||
let layers = &self.s.doc.timeline(self.s.scene).layers;
|
||||
let layers = &self.s.timeline().layers;
|
||||
if let (Some(a), Some(b)) = (layers.first(), layers.last()) {
|
||||
let last = self.s.frame_count().saturating_sub(1);
|
||||
self.frame_sel = Some(timeline::FrameSel { anchor: (a.id, 0), head: (b.id, last) });
|
||||
@@ -2085,6 +2205,7 @@ impl App {
|
||||
crate::a11y::name_splitter(&ctx, "timeline", tr!("Resize the timeline"));
|
||||
|
||||
self.prompt_window(&ctx);
|
||||
crate::convert_symbol::window(self, &ctx);
|
||||
self.about_window(&ctx);
|
||||
dialogs::show_all(self, &ctx);
|
||||
autosave::window(self, &ctx);
|
||||
|
||||
+6
-6
@@ -35,7 +35,7 @@ pub struct Shown {
|
||||
|
||||
/// Every visible armature on the scene at the playhead, bottom layer first.
|
||||
pub fn shown(app: &App) -> Vec<Shown> {
|
||||
let tl = app.s.doc.timeline(app.s.scene);
|
||||
let tl = app.s.timeline();
|
||||
tl.layers
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -85,7 +85,7 @@ fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 {
|
||||
/// its layer and id.
|
||||
fn instance_at(app: &App, sp: Vec2, slop: f32, skip: Option<ElementId>) -> Option<(LayerId, ElementId)> {
|
||||
let dl = app.s.display_list();
|
||||
let tl = app.s.doc.timeline(app.s.scene);
|
||||
let tl = app.s.timeline();
|
||||
for item in dl.items.iter().rev() {
|
||||
if Some(item.element) == skip || item.guide || item.masks.is_some() {
|
||||
continue;
|
||||
@@ -120,7 +120,7 @@ pub fn select(app: &mut App, layer: LayerId, bone: Option<BoneId>) {
|
||||
pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag {
|
||||
let sp = xf.to_stage(press);
|
||||
if let Some((layer, id, Part::End)) = hit(app, xf, press)
|
||||
&& let Some(child) = app.s.doc.timeline(app.s.scene).layer(layer).and_then(|l| l.armature.as_ref()).and_then(|a| a.bone(id)).map(|b| b.child)
|
||||
&& let Some(child) = app.s.timeline().layer(layer).and_then(|l| l.armature.as_ref()).and_then(|a| a.bone(id)).map(|b| b.child)
|
||||
&& let Some(b) = shown(app).into_iter().find(|s| s.layer == layer).and_then(|s| s.bones.into_iter().find(|b| b.id == id))
|
||||
{
|
||||
// A chain joins end to start.
|
||||
@@ -163,7 +163,7 @@ pub fn click(app: &mut App, xf: Xf, p: Pos2) {
|
||||
/// isn't on an armature.
|
||||
pub fn select_drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option<Drag> {
|
||||
let sp = xf.to_stage(press);
|
||||
let tl = app.s.doc.timeline(app.s.scene);
|
||||
let tl = app.s.timeline();
|
||||
let (layer, bone, local) = match hit(app, xf, press) {
|
||||
Some((layer, id, _)) => (layer, Some(id), None),
|
||||
None => {
|
||||
@@ -178,7 +178,7 @@ pub fn select_drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option<Drag> {
|
||||
match bone {
|
||||
Some(id) => {
|
||||
select(app, layer, Some(id));
|
||||
let arm = app.s.doc.timeline(app.s.scene).layer(layer).and_then(|l| l.armature.clone())?;
|
||||
let arm = app.s.timeline().layer(layer).and_then(|l| l.armature.clone())?;
|
||||
if armature::movable_chain(&arm, id).is_empty() {
|
||||
app.status_ok(tr!("That bone is pinned (or hangs from a pinned bone): unpin it in Properties to drag it."));
|
||||
return Some(Drag::None);
|
||||
@@ -231,7 +231,7 @@ pub fn consume_keys(app: &mut App, ctx: &egui::Context) {
|
||||
/// Drops a selected bone that no longer exists.
|
||||
pub fn upkeep(app: &mut App) {
|
||||
if let Some(id) = app.bone_sel {
|
||||
let tl = app.s.doc.timeline(app.s.scene);
|
||||
let tl = app.s.timeline();
|
||||
if !tl.layers.iter().any(|l| l.kind == LayerKind::Armature && l.armature.as_ref().is_some_and(|a| a.bone(id).is_some())) {
|
||||
app.bone_sel = None;
|
||||
}
|
||||
|
||||
+4
-4
@@ -37,18 +37,18 @@ impl Geo {
|
||||
|
||||
/// The scene's camera at the playhead (the rest camera on a blank camera keyframe).
|
||||
pub fn camera(app: &App) -> Option<Camera> {
|
||||
app.s.doc.timeline(app.s.scene).camera_state_at(app.s.frame, &app.s.doc.stage)
|
||||
app.s.timeline().camera_state_at(app.s.frame, &app.s.doc.stage)
|
||||
}
|
||||
|
||||
/// Whether the stage shows the movie through the camera this frame.
|
||||
pub fn previewing(app: &App) -> bool {
|
||||
app.camera_preview && app.s.doc.timeline(app.s.scene).camera_layer().is_some()
|
||||
app.camera_preview && app.s.timeline().camera_layer().is_some()
|
||||
}
|
||||
|
||||
/// Picking the Camera tool adds a camera when the scene has none (as Animate does), once per
|
||||
/// pick: undoing the add leaves the tool in hand without adding it again.
|
||||
pub fn on_tool_change(app: &mut App) {
|
||||
if app.tool == Tool::Camera && app.last_tool != Tool::Camera && app.s.doc.timeline(app.s.scene).camera_layer().is_none() && app.run("camera.add", json!({})).is_some() {
|
||||
if app.tool == Tool::Camera && app.last_tool != Tool::Camera && app.s.timeline().camera_layer().is_none() && app.run("camera.add", json!({})).is_some() {
|
||||
app.status_ok(tr!("Added a camera. Drag on the stage to pan it, turn it with the round handle, zoom with the wheel. {undo} to undo.", undo = app.undo_key()));
|
||||
}
|
||||
app.last_tool = app.tool;
|
||||
@@ -150,7 +150,7 @@ pub fn tick(app: &mut App, ctx: &egui::Context, now: f64) {
|
||||
/// The camera frame (editing) or the camera-view marks (previewing), and the Camera tool's
|
||||
/// handles.
|
||||
pub fn draw(app: &App, painter: &egui::Painter, g: &Geo, hot: Option<Pos2>) {
|
||||
let tl = app.s.doc.timeline(app.s.scene);
|
||||
let tl = app.s.timeline();
|
||||
let Some(layer) = tl.camera_layer() else { return };
|
||||
let Some(cam) = camera(app) else { return };
|
||||
let color = to_color32(layer.color);
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! The Convert to Symbol dialog (F8, ADR 0053): name, type and Library folder, as in Animate.
|
||||
//! It remembers the folder and type last used, so a run of conversions lands together. What it
|
||||
//! changes is one `modify.convert_to_symbol`; the choices remembered are view state.
|
||||
|
||||
use crate::a11y::Named;
|
||||
use crate::app::App;
|
||||
use crate::theme::{FORM_LABEL_DOCK, Type, form_row, text};
|
||||
use anicraft_engine::doc::{Document, FolderId, LibraryEntry, SymbolKind};
|
||||
use egui::Key;
|
||||
use serde_json::json;
|
||||
|
||||
/// The dialog while it is open.
|
||||
pub struct ConvertDialog {
|
||||
pub name: String,
|
||||
pub kind: SymbolKind,
|
||||
pub folder: Option<FolderId>,
|
||||
/// The name field takes the keyboard on the first frame.
|
||||
focus: bool,
|
||||
}
|
||||
|
||||
/// What the last conversion chose (kept for the next one).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Last {
|
||||
pub folder: Option<FolderId>,
|
||||
pub kind: SymbolKind,
|
||||
}
|
||||
|
||||
/// The folder to offer: the one used last, while it is still in the Library.
|
||||
pub fn remembered(doc: &Document, last: Last) -> Option<FolderId> {
|
||||
last.folder.filter(|f| doc.folder(*f).is_some())
|
||||
}
|
||||
|
||||
/// Opens the dialog for the selection, with the next free "Symbol n" in the remembered folder.
|
||||
pub fn open(app: &mut App) {
|
||||
if app.s.selection.is_empty() {
|
||||
// The engine says why ("select something to convert").
|
||||
app.request("modify.convert_to_symbol", json!({}));
|
||||
return;
|
||||
}
|
||||
app.playing = false;
|
||||
let folder = remembered(&app.s.doc, app.convert_last);
|
||||
let name = app.s.doc.numbered_name(folder, "Symbol", app.s.doc.library.len() + 1); // i18n-exempt: a new symbol's default name is document text, as the engine gives it
|
||||
app.convert = Some(ConvertDialog { name, kind: app.convert_last.kind, folder, focus: true });
|
||||
}
|
||||
|
||||
fn kind_key(k: SymbolKind) -> &'static str {
|
||||
match k {
|
||||
SymbolKind::Graphic => "graphic",
|
||||
SymbolKind::MovieClip => "movie_clip",
|
||||
SymbolKind::Button => "button",
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `folder` is, as the dialog names it.
|
||||
fn folder_label(doc: &Document, folder: Option<FolderId>) -> String {
|
||||
match folder {
|
||||
Some(f) => doc.entry_path(LibraryEntry::Folder(f)),
|
||||
None => tr!("Library (top level)").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(d) = &mut app.convert else { return };
|
||||
let doc = &app.s.doc;
|
||||
if d.folder.is_some_and(|f| doc.folder(f).is_none()) {
|
||||
d.folder = None;
|
||||
}
|
||||
let mut folders: Vec<(FolderId, String)> = doc.library_tree.folders.iter().map(|f| (f.id, doc.entry_path(LibraryEntry::Folder(f.id)))).collect();
|
||||
folders.sort_by_key(|(_, p)| p.to_lowercase());
|
||||
let (mut submit, mut cancel) = (false, false);
|
||||
let title = tr!("Convert to Symbol");
|
||||
egui::Window::new(title).id(egui::Id::new("convert_symbol")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(380.0);
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Name"), |ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Symbol name"));
|
||||
if d.focus {
|
||||
r.request_focus();
|
||||
d.focus = false;
|
||||
}
|
||||
if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {
|
||||
submit = true;
|
||||
}
|
||||
});
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Type"), |ui| {
|
||||
egui::ComboBox::from_id_salt("convert_kind")
|
||||
.width(200.0)
|
||||
.selected_text(crate::panels::symbol_kind_label(d.kind))
|
||||
.show_ui(ui, |ui| {
|
||||
for k in [SymbolKind::Graphic, SymbolKind::MovieClip, SymbolKind::Button] {
|
||||
if ui.selectable_label(d.kind == k, crate::panels::symbol_kind_label(k)).clicked() {
|
||||
d.kind = k;
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Symbol type"));
|
||||
});
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Folder"), |ui| {
|
||||
egui::ComboBox::from_id_salt("convert_folder")
|
||||
.width(200.0)
|
||||
.selected_text(folder_label(doc, d.folder))
|
||||
.show_ui(ui, |ui| {
|
||||
egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| {
|
||||
if ui.selectable_label(d.folder.is_none(), tr!("Library (top level)")).clicked() {
|
||||
d.folder = None;
|
||||
}
|
||||
for (f, path) in &folders {
|
||||
if ui.selectable_label(d.folder == Some(*f), path.as_str()).clicked() {
|
||||
d.folder = Some(*f);
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr!("The Library folder the new symbol goes into (the next conversion offers it again)"))
|
||||
.set_name(tr!("Library folder"));
|
||||
});
|
||||
// A name the folder already has gets a number, as the engine gives it.
|
||||
let wanted = d.name.trim();
|
||||
if !wanted.is_empty() && doc.name_taken(d.folder, wanted, None) {
|
||||
let becomes = doc.unique_name(d.folder, wanted);
|
||||
ui.label(text(Type::Caption, tr!("{folder} already has “{name}”; the new symbol will be “{becomes}”.", folder = folder_label(doc, d.folder), name = wanted, becomes = becomes)));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(tr!("OK")).clicked() {
|
||||
submit = true;
|
||||
}
|
||||
if ui.button(tr!("Cancel")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) {
|
||||
cancel = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
if submit {
|
||||
accept(app);
|
||||
} else if cancel {
|
||||
app.convert = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// OK: converts with the dialog's choices and remembers the folder and type for next time.
|
||||
fn accept(app: &mut App) {
|
||||
let Some(d) = app.convert.take() else { return };
|
||||
let name = d.name.trim();
|
||||
let mut params = json!({"kind": kind_key(d.kind), "folder": d.folder.map(|f| f.0)});
|
||||
if !name.is_empty() {
|
||||
params["name"] = json!(name);
|
||||
}
|
||||
app.convert_last = Last { folder: d.folder, kind: d.kind };
|
||||
if let Some(f) = d.folder {
|
||||
app.library.expanded.extend(app.s.doc.folder_chain(f));
|
||||
}
|
||||
app.request("modify.convert_to_symbol", params);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_engine::Session;
|
||||
use anicraft_engine::doc::sample;
|
||||
|
||||
#[test]
|
||||
fn the_remembered_folder_is_offered_while_it_exists() {
|
||||
let mut s = Session::new(sample::demo());
|
||||
let f = FolderId(s.execute("library.new_folder", &json!({"name": "Props"})).unwrap()["folder"].as_u64().unwrap());
|
||||
let last = Last { folder: Some(f), kind: SymbolKind::MovieClip };
|
||||
assert_eq!(remembered(&s.doc, last), Some(f));
|
||||
s.execute("library.delete", &json!({"items": [{"folder": f.0}]})).unwrap();
|
||||
assert_eq!(remembered(&s.doc, last), None, "a deleted folder falls back to the top level");
|
||||
assert_eq!(remembered(&s.doc, Last::default()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ok_converts_into_the_folder_and_the_next_dialog_offers_it_again() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = App::with_context(&ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png")));
|
||||
// Nothing selected: no dialog, the engine says why.
|
||||
app.run("edit.deselect", json!({}));
|
||||
open(&mut app);
|
||||
assert!(app.convert.is_none());
|
||||
let f = FolderId(app.run("library.new_folder", json!({"name": "Props"})).unwrap()["folder"].as_u64().unwrap());
|
||||
app.run("draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "object": true}));
|
||||
open(&mut app);
|
||||
let d = app.convert.as_mut().expect("the dialog opens");
|
||||
assert_eq!(d.folder, None, "the top level the first time");
|
||||
assert!(d.name.starts_with("Symbol "));
|
||||
d.folder = Some(f);
|
||||
d.kind = SymbolKind::Button;
|
||||
d.name = " Lamp ".into();
|
||||
accept(&mut app);
|
||||
assert!(app.convert.is_none());
|
||||
let sym = app.s.doc.library.iter().find(|s| s.name == "Lamp").expect("converted, the name trimmed");
|
||||
assert_eq!(sym.kind, SymbolKind::Button);
|
||||
assert_eq!(app.s.doc.parent_of(LibraryEntry::Item(anicraft_engine::doc::LibraryItem::Symbol(sym.id))), Some(f));
|
||||
assert!(app.library.expanded.contains(&f), "the folder opens in the Library");
|
||||
// The next conversion offers Props and Button again; an empty name takes the default.
|
||||
app.run("draw.rect", json!({"x": 60, "y": 10, "w": 20, "h": 20, "object": true}));
|
||||
open(&mut app);
|
||||
let d = app.convert.as_mut().expect("the dialog opens");
|
||||
assert_eq!((d.folder, d.kind), (Some(f), SymbolKind::Button));
|
||||
d.name = String::new();
|
||||
accept(&mut app);
|
||||
assert_eq!(app.s.doc.library_children(Some(f)).len(), 2);
|
||||
// The dialog draws (the clash note too) without the document changing.
|
||||
app.run("draw.rect", json!({"x": 90, "y": 10, "w": 20, "h": 20, "object": true}));
|
||||
open(&mut app);
|
||||
if let Some(d) = app.convert.as_mut() {
|
||||
d.name = "Lamp".into();
|
||||
}
|
||||
let before = app.s.doc.clone();
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| window(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
assert!(app.convert.is_some());
|
||||
assert_eq!(app.s.doc, before);
|
||||
}
|
||||
}
|
||||
+20
-1
@@ -578,7 +578,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() {
|
||||
a.run("symbol.set_kind", serde_json::json!({"symbol": symbol, "kind": "movie_clip"}));
|
||||
a.run("element.set_filters", serde_json::json!({"filters": [{"type": "drop_shadow"}, {"type": "gradient_glow"}]}));
|
||||
}));
|
||||
for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple"] {
|
||||
for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol"] {
|
||||
found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] {
|
||||
@@ -623,6 +623,25 @@ fn status_lines_for_every_result_are_translated() {
|
||||
assert!(plain.is_empty(), "status lines in plain English:\n{}", plain.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_multiple_frames_status_lines_are_translated() {
|
||||
// The Edit menu with Edit Multiple Frames on (ADR 0051), as the status bar shows it.
|
||||
let (mut app, _ctx) = pseudo_app(|a, _| a.open_panel(Some("edittransform")));
|
||||
let mut plain = Vec::new();
|
||||
for id in ["edit.copy", "edit.cut", "edit.paste_in_place", "edit.duplicate", "edit.delete"] {
|
||||
app.status = None;
|
||||
app.invoke(id);
|
||||
match &app.status {
|
||||
Some(s) if !s.text.chars().any(pseudo::is_accented) => plain.push(format!("{id}: {:?}", s.text)),
|
||||
None => plain.push(format!("{id}: said nothing")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(plain.is_empty(), "status lines in plain English:
|
||||
{}", plain.join("
|
||||
"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_status_lines_are_translated() {
|
||||
// The Eraser's and Eyedropper's results on the sample (on the sun and the hills, and on
|
||||
|
||||
+1061
File diff suppressed because it is too large.
Load diff
+4
-1
@@ -30,11 +30,14 @@ mod envelope;
|
||||
mod erasertool;
|
||||
mod bone_tool;
|
||||
mod camera_tool;
|
||||
mod convert_symbol;
|
||||
mod dialogs;
|
||||
mod gpu_stage;
|
||||
mod icons;
|
||||
mod keymap;
|
||||
mod library;
|
||||
mod menus;
|
||||
mod mixed;
|
||||
mod motion_editor;
|
||||
mod panels;
|
||||
mod motion_path;
|
||||
@@ -176,7 +179,7 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!( // i18n-exempt: the --help console text
|
||||
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope]\n\
|
||||
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu]\n\
|
||||
--renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\
|
||||
|
||||
+9
-2
@@ -42,16 +42,23 @@ pub fn bar(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
|
||||
fn enabled(app: &App, id: &str) -> bool {
|
||||
// With Edit Multiple Frames on, the selection is on several keyframes (ADR 0051).
|
||||
if let Some(on) = crate::onion::enabled(app, id) {
|
||||
return on;
|
||||
}
|
||||
match id {
|
||||
"edit.undo" => app.s.can_undo(),
|
||||
"edit.redo" => app.s.can_redo(),
|
||||
"edit.delete" | "edit.duplicate" | "modify.convert_to_symbol" | "modify.break_apart" | "arrange.bring_to_front" | "arrange.send_to_back" => !app.s.selection.is_empty(),
|
||||
"layer.delete" => app.s.doc.timeline(app.s.scene).layers.len() > 1,
|
||||
"layer.delete" => app.s.timeline().layers.len() > 1,
|
||||
"scene.delete" => app.s.doc.scenes.len() > 1,
|
||||
// Ctrl+E opens the selected instance, or goes back to the document (ADR 0045).
|
||||
"symbol.exit" => !app.s.editing.is_empty(),
|
||||
"symbol.edit" => !app.s.editing.is_empty() || app.s.selected_elements().iter().any(|(_, e)| matches!(e.kind, anicraft_engine::doc::ElementKind::Symbol { .. })),
|
||||
"scene.prev" | "scene.move_up" => app.s.scene > 0,
|
||||
"scene.next" | "scene.move_down" => app.s.scene + 1 < app.s.doc.scenes.len(),
|
||||
"timeline.clear_keyframe" => match app.frame_sel {
|
||||
Some(sel) => sel.has_keys(&app.s.doc.timeline(app.s.scene).layers),
|
||||
Some(sel) => sel.has_keys(&app.s.timeline().layers),
|
||||
None => app.s.active_layer().is_some_and(|l| l.keyframe_starting_at(app.s.frame).is_some()),
|
||||
},
|
||||
"timeline.paste_frames" => !app.s.frame_clipboard.is_empty(),
|
||||
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
//! Which Properties rows say "mixed" for a selection of several elements (ADR 0053).
|
||||
//!
|
||||
//! A row is mixed when the selected elements it applies to differ there: the field shows the
|
||||
//! first one's value, and a change applies to all of them. Each row compares only the elements
|
||||
//! it edits (Blending only movie clips and buttons, Looping only graphics, Fill only shapes), so
|
||||
//! a shape beside a movie clip never makes Blending mixed. Pure, so every row is tested here.
|
||||
|
||||
use anicraft_engine::doc::{Document, Element, ElementKind, Paint, Shape, SymbolKind};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The rows whose values differ across the selection.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Mixed {
|
||||
pub scale: bool,
|
||||
pub rotation: bool,
|
||||
/// The colour effect (the Alpha row).
|
||||
pub alpha: bool,
|
||||
/// The instances show different symbols (the Symbol row, Swap…).
|
||||
pub symbol: bool,
|
||||
/// Their symbols are of different types.
|
||||
pub kind: bool,
|
||||
pub filters: bool,
|
||||
pub blend: bool,
|
||||
pub looping: bool,
|
||||
pub first_frame: bool,
|
||||
pub fill: bool,
|
||||
/// The bitmap a bitmap fill shows (Swap Bitmap).
|
||||
pub bitmap: bool,
|
||||
/// Stroke colour or width.
|
||||
pub stroke: bool,
|
||||
pub profile: bool,
|
||||
/// Line style, caps, joins and dashes.
|
||||
pub style: bool,
|
||||
}
|
||||
|
||||
/// Whether `values` holds two that differ.
|
||||
fn differ<T: PartialEq>(mut values: impl Iterator<Item = T>) -> bool {
|
||||
match values.next() {
|
||||
Some(first) => values.any(|v| v != first),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Close enough to show the same number in a field.
|
||||
fn near(a: f32, b: f32) -> bool {
|
||||
(a - b).abs() <= 1e-4
|
||||
}
|
||||
|
||||
fn differ_f32(values: impl Iterator<Item = f32>) -> bool {
|
||||
let v: Vec<f32> = values.collect();
|
||||
v.first().is_some_and(|f| v.iter().any(|x| !near(*x, *f)))
|
||||
}
|
||||
|
||||
/// What Properties shows as mixed for `all` (the selection, in order).
|
||||
pub fn of(doc: &Document, all: &[Arc<Element>]) -> Mixed {
|
||||
if all.len() < 2 {
|
||||
return Mixed::default();
|
||||
}
|
||||
let kind_of = |e: &Element| match &e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => doc.symbol(*symbol).map(|s| s.kind),
|
||||
_ => None,
|
||||
};
|
||||
let decomposed: Vec<_> = all.iter().map(|e| e.transform.decompose()).collect();
|
||||
let instances = || all.iter().filter(|e| matches!(e.kind, ElementKind::Symbol { .. }));
|
||||
// Blending and filters: movie clips and buttons (Animate offers them on those only).
|
||||
let clips = || all.iter().filter(|e| kind_of(e).is_some_and(|k| k != SymbolKind::Graphic));
|
||||
let graphics = || all.iter().filter(|e| kind_of(e) == Some(SymbolKind::Graphic));
|
||||
let shapes: Vec<&Shape> = all
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
ElementKind::Shape(s) => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let strokes = || shapes.iter().filter_map(|s| s.stroke.as_ref());
|
||||
Mixed {
|
||||
scale: differ_f32(decomposed.iter().map(|d| d.sx)) || differ_f32(decomposed.iter().map(|d| d.sy)),
|
||||
rotation: differ_f32(decomposed.iter().map(|d| d.rotation)),
|
||||
alpha: differ_f32(all.iter().map(|e| e.color.alpha)),
|
||||
symbol: differ(instances().filter_map(|e| match &e.kind {
|
||||
ElementKind::Symbol { symbol, .. } => Some(*symbol),
|
||||
_ => None,
|
||||
})),
|
||||
kind: differ(instances().map(|e| kind_of(e))),
|
||||
filters: differ(clips().filter_map(|e| match &e.kind {
|
||||
ElementKind::Symbol { filters, .. } => Some(filters),
|
||||
_ => None,
|
||||
})),
|
||||
blend: differ(clips().filter_map(|e| match &e.kind {
|
||||
ElementKind::Symbol { blend, .. } => Some(*blend),
|
||||
_ => None,
|
||||
})),
|
||||
looping: differ(graphics().filter_map(|e| match &e.kind {
|
||||
ElementKind::Symbol { loop_mode, .. } => Some(*loop_mode),
|
||||
_ => None,
|
||||
})),
|
||||
first_frame: differ(graphics().filter_map(|e| match &e.kind {
|
||||
ElementKind::Symbol { first_frame, .. } => Some(*first_frame),
|
||||
_ => None,
|
||||
})),
|
||||
fill: differ(shapes.iter().map(|s| s.fill.as_ref())),
|
||||
bitmap: differ(shapes.iter().filter_map(|s| match &s.fill {
|
||||
Some(Paint::Bitmap { bitmap, .. }) => Some(*bitmap),
|
||||
_ => None,
|
||||
})),
|
||||
// A shape without a line differs from one with a line.
|
||||
stroke: differ(shapes.iter().map(|s| s.stroke.as_ref().map(|st| (st.color, st.width.to_bits())))),
|
||||
profile: differ(strokes().map(|st| st.profile.as_ref())),
|
||||
style: differ(strokes().map(|st| &st.style)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_engine::Session;
|
||||
use anicraft_engine::doc::sample;
|
||||
use serde_json::json;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: serde_json::Value) -> serde_json::Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: &serde_json::Value) -> u64 {
|
||||
v["element"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// The selection's elements, in order, from every layer.
|
||||
fn selected(s: &Session) -> Vec<Arc<Element>> {
|
||||
s.selection.iter().filter_map(|(l, e)| s.elements_on(l).iter().find(|x| x.id == e).cloned()).collect()
|
||||
}
|
||||
|
||||
fn mixed(s: &Session) -> Mixed {
|
||||
of(&s.doc, &selected(s))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[u64]) {
|
||||
run(s, "element.select", json!({"ids": ids}));
|
||||
}
|
||||
|
||||
/// Two movie clips and a graphic of the sample's Ball and Star, on two layers, and two shapes.
|
||||
fn session() -> (Session, [u64; 3], [u64; 2]) {
|
||||
let mut s = Session::new(sample::demo());
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let sym = |s: &Session, n: &str| s.doc.library.iter().find(|x| x.name == n).unwrap().id.0;
|
||||
let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star"));
|
||||
let a = id(&run(&mut s, "library.place", json!({"symbol": ball, "x": 100, "y": 100})));
|
||||
let b = id(&run(&mut s, "library.place", json!({"symbol": ball, "x": 200, "y": 100})));
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
let g = id(&run(&mut s, "library.place", json!({"symbol": star, "x": 300, "y": 100})));
|
||||
run(&mut s, "symbol.set_kind", json!({"symbol": ball, "kind": "movie_clip"}));
|
||||
run(&mut s, "symbol.set_kind", json!({"symbol": star, "kind": "graphic"}));
|
||||
let r1 = id(&run(&mut s, "draw.rect", json!({"x": 10, "y": 300, "w": 20, "h": 20, "fill": "#ff0000", "stroke": "#000000", "stroke_width": 2, "object": true})));
|
||||
let r2 = id(&run(&mut s, "draw.rect", json!({"x": 60, "y": 300, "w": 20, "h": 20, "fill": "#ff0000", "stroke": "#000000", "stroke_width": 2, "object": true})));
|
||||
(s, [a, b, g], [r1, r2])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alike_elements_are_not_mixed_and_one_element_never_is() {
|
||||
let (mut s, [a, b, g], [r1, r2]) = session();
|
||||
select(&mut s, &[a, b, g, r1, r2]);
|
||||
// Positions differ, and so do the instances' symbols and types (Ball and Star): those
|
||||
// rows say mixed; nothing else does.
|
||||
assert_eq!(mixed(&s), Mixed { symbol: true, kind: true, ..Mixed::default() });
|
||||
select(&mut s, &[a, b]);
|
||||
assert_eq!(mixed(&s), Mixed::default());
|
||||
select(&mut s, &[a]);
|
||||
assert_eq!(mixed(&s), Mixed::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_rotation_and_alpha_rows() {
|
||||
let (mut s, [a, b, g], _) = session();
|
||||
select(&mut s, &[b]);
|
||||
run(&mut s, "element.set_transform", json!({"sx": 2.0}));
|
||||
select(&mut s, &[a, b, g]);
|
||||
assert!(mixed(&s).scale && !mixed(&s).rotation && !mixed(&s).alpha);
|
||||
select(&mut s, &[g]);
|
||||
run(&mut s, "element.set_transform", json!({"rotation": 30}));
|
||||
run(&mut s, "element.set_alpha", json!({"alpha": 0.5}));
|
||||
select(&mut s, &[a, g]);
|
||||
let m = mixed(&s);
|
||||
assert!(m.rotation && m.alpha && !m.scale);
|
||||
// Editing a mixed row sets all: then it isn't mixed any more.
|
||||
run(&mut s, "element.set_alpha", json!({"alpha": 0.25}));
|
||||
run(&mut s, "element.set_transform", json!({"rotation": 0}));
|
||||
assert!(!mixed(&s).alpha && !mixed(&s).rotation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_and_blending_rows_compare_movie_clips_only() {
|
||||
let (mut s, [a, b, g], [r1, _]) = session();
|
||||
select(&mut s, &[b]);
|
||||
run(&mut s, "element.set_blend", json!({"mode": "multiply"}));
|
||||
run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]}));
|
||||
select(&mut s, &[a, b, g, r1]);
|
||||
let m = mixed(&s);
|
||||
assert!(m.blend && m.filters);
|
||||
// A graphic and a shape beside one movie clip: nothing to compare.
|
||||
select(&mut s, &[b, g, r1]);
|
||||
let m = mixed(&s);
|
||||
assert!(!m.blend && !m.filters);
|
||||
// Setting either across the selection makes the movie clips alike.
|
||||
select(&mut s, &[a, b, g]);
|
||||
run(&mut s, "element.set_blend", json!({"mode": "screen"}));
|
||||
run(&mut s, "element.set_filters", json!({"filters": []}));
|
||||
let m = mixed(&s);
|
||||
assert!(!m.blend && !m.filters);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn looping_and_first_frame_rows_compare_graphics_only() {
|
||||
let (mut s, [a, _, g], _) = session();
|
||||
let star = s.doc.library.iter().find(|x| x.name == "Star").unwrap().id.0;
|
||||
let g2 = id(&run(&mut s, "library.place", json!({"symbol": star, "x": 400, "y": 100})));
|
||||
select(&mut s, &[g2]);
|
||||
run(&mut s, "element.set_loop", json!({"loop": "single_frame", "first_frame": 1}));
|
||||
select(&mut s, &[g, g2, a]);
|
||||
let m = mixed(&s);
|
||||
assert!(m.looping && m.first_frame);
|
||||
run(&mut s, "element.set_loop", json!({"loop": "play_once", "first_frame": 0}));
|
||||
let m = mixed(&s);
|
||||
assert!(!m.looping && !m.first_frame);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_and_type_rows_and_editing_the_type_sets_every_symbol() {
|
||||
let (mut s, [a, b, g], _) = session();
|
||||
select(&mut s, &[a, b]);
|
||||
assert!(!mixed(&s).symbol && !mixed(&s).kind);
|
||||
select(&mut s, &[a, g]);
|
||||
assert!(mixed(&s).symbol && mixed(&s).kind);
|
||||
// Type: every selected instance's symbol, in one undo step.
|
||||
let v = run(&mut s, "symbol.set_kind", json!({"kind": "button"}));
|
||||
assert_eq!(v["symbols"].as_array().map(Vec::len), Some(2));
|
||||
assert!(!mixed(&s).kind && mixed(&s).symbol);
|
||||
s.undo().unwrap();
|
||||
assert!(mixed(&s).kind);
|
||||
// Swap Symbol sets them all too.
|
||||
let ball = s.doc.library.iter().find(|x| x.name == "Ball").unwrap().id.0;
|
||||
run(&mut s, "element.swap_symbol", json!({"symbol": ball}));
|
||||
assert!(!mixed(&s).symbol);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_and_bitmap_rows() {
|
||||
let (mut s, _, [r1, r2]) = session();
|
||||
select(&mut s, &[r2]);
|
||||
run(&mut s, "element.set_fill", json!({"color": "#00ff00"}));
|
||||
select(&mut s, &[r1, r2]);
|
||||
assert!(mixed(&s).fill);
|
||||
run(&mut s, "element.set_fill", json!({"color": "#0000ff"}));
|
||||
assert!(!mixed(&s).fill);
|
||||
// Fill on beside fill off is mixed.
|
||||
select(&mut s, &[r1]);
|
||||
run(&mut s, "element.set_fill", json!({"color": null}));
|
||||
select(&mut s, &[r1, r2]);
|
||||
assert!(mixed(&s).fill);
|
||||
// Two placed bitmaps of different images.
|
||||
let mut ids = Vec::new();
|
||||
for (n, w) in [("a.png", 2), ("b.png", 3)] {
|
||||
let b = anicraft_engine::doc::BitmapId(s.doc.alloc_id());
|
||||
let png = anicraft_engine::render::encode_png(w, 2, &[0, 0, 255, 255].repeat(w as usize * 2)).unwrap();
|
||||
s.doc.bitmaps.push(Arc::new(anicraft_engine::doc::Bitmap::from_png(b, n, png).unwrap()));
|
||||
ids.push((b, id(&run(&mut s, "library.place", json!({"bitmap": b.0})))));
|
||||
}
|
||||
select(&mut s, &[ids[0].1, ids[1].1]);
|
||||
assert!(mixed(&s).bitmap && mixed(&s).fill);
|
||||
run(&mut s, "element.swap_bitmap", json!({"bitmap": ids[0].0.0}));
|
||||
assert!(!mixed(&s).bitmap);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_profile_and_style_rows() {
|
||||
let (mut s, _, [r1, r2]) = session();
|
||||
select(&mut s, &[r2]);
|
||||
run(&mut s, "element.set_stroke", json!({"width": 6}));
|
||||
select(&mut s, &[r1, r2]);
|
||||
assert!(mixed(&s).stroke && !mixed(&s).profile && !mixed(&s).style);
|
||||
run(&mut s, "element.set_stroke", json!({"width": 3}));
|
||||
assert!(!mixed(&s).stroke);
|
||||
select(&mut s, &[r1]);
|
||||
run(&mut s, "stroke.set_profile", json!({"profile": "taper_both"}));
|
||||
run(&mut s, "element.set_stroke", json!({"style": "dashed"}));
|
||||
select(&mut s, &[r1, r2]);
|
||||
let m = mixed(&s);
|
||||
assert!(m.profile && m.style && !m.stroke);
|
||||
run(&mut s, "stroke.set_profile", json!({"profile": "taper_both"}));
|
||||
run(&mut s, "element.set_stroke", json!({"style": "dashed"}));
|
||||
let m = mixed(&s);
|
||||
assert!(!m.profile && !m.style);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user