diff --git a/AGENTS.md b/AGENTS.md index 2c27987e..cbc67a0b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,8 @@ src/ L5 egui shell (app, menus, stage, timeline, panels, theme) ``` A crate depends only on lower layers. Nothing below `src/` may use egui, eframe or winit. +`src/architecture_tests.rs` enforces both, and that this map lists every crate with its layer: +a new crate needs a row here and in its `LAYERS` table. ## Standing rules (read `docs/product-principles.md`) diff --git a/docs/roadmap.md b/docs/roadmap.md index 3d4c5e6a..0505c3b7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -8,7 +8,7 @@ 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 by convention (an xtask check is planned). | +| 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 ``. No GPU path, filters or text yet. | | 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), auto-key when editing inside a tween, frame labels, graphic-symbol nesting with loop modes, onion skin (±2 frames), looping playback. **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). No motion editor yet; **motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **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. No brush or merge drawing yet. | @@ -26,7 +26,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---|---| | **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~~ ✅ (basic); ~~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; ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; MCP server; perf budgets (criterion) with CI enforcement; `xtask layers`. | +| **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; ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; MCP server; perf budgets (criterion) with CI enforcement; ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **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); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; Lottie export; ~~sprite sheet + JSON~~ ✅; MP4/WebM via ffmpeg pipe. | | **M5** | Rich media | Text engine (shaping via rustybuzz, glyph atlas); bitmap import and bitmap fills; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and blend modes on Movie Clips. | diff --git a/src/architecture_tests.rs b/src/architecture_tests.rs new file mode 100644 index 00000000..ce221b73 --- /dev/null +++ b/src/architecture_tests.rs @@ -0,0 +1,99 @@ +//! The layering rule from AGENTS.md, enforced: a crate depends only on crates in lower layers, +//! nothing below the shell uses the UI toolkit, and the workspace map in AGENTS.md matches the +//! crates that exist. + +use std::collections::BTreeMap; +use std::path::Path; + +/// Each crate's layer, as AGENTS.md documents it. The shell (`anicraft`, `src/`) is L5. +const LAYERS: &[(&str, u8)] = + &[("geom", 0), ("xml", 0), ("doc", 1), ("render", 2), ("xfl", 2), ("svg", 2), ("engine", 3), ("cli", 4)]; +const SHELL_LAYER: u8 = 5; +/// UI crates only the shell may use. +const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui-wgpu", "egui_glow"]; + +fn root() -> &'static Path { + Path::new(env!("CARGO_MANIFEST_DIR")) +} + +fn layer_of(name: &str) -> Option { + LAYERS.iter().find(|(n, _)| *n == name).map(|(_, l)| *l) +} + +/// Dependency names in a manifest's `[dependencies]`, `[dev-dependencies]` and +/// `[build-dependencies]` tables. +fn dependencies(manifest: &str) -> Vec { + let mut out = Vec::new(); + let mut in_deps = false; + for line in manifest.lines().map(str::trim) { + if line.starts_with('[') { + in_deps = matches!(line, "[dependencies]" | "[dev-dependencies]" | "[build-dependencies]"); + continue; + } + if !in_deps || line.is_empty() || line.starts_with('#') { + continue; + } + if let Some(name) = line.split(['=', '.', ' ']).next().filter(|n| !n.is_empty()) { + out.push(name.to_string()); + } + } + out +} + +#[test] +fn crates_depend_only_on_lower_layers_and_never_on_the_ui() { + let mut problems = Vec::new(); + let mut seen = Vec::new(); + for entry in std::fs::read_dir(root().join("crates")).expect("crates/ exists").flatten() { + let manifest = entry.path().join("Cargo.toml"); + let Ok(text) = std::fs::read_to_string(&manifest) else { continue }; + let name = entry.file_name().to_string_lossy().into_owned(); + seen.push(name.clone()); + let Some(own) = layer_of(&name) else { + problems.push(format!("crates/{name} has no layer: add it to LAYERS here and to the workspace map in AGENTS.md")); + continue; + }; + for dep in dependencies(&text) { + if UI_CRATES.contains(&dep.as_str()) { + problems.push(format!("crates/{name} (L{own}) depends on {dep}; only the shell may use the UI toolkit")); + } + if let Some(d) = dep.strip_prefix("anicraft-") + && let Some(l) = layer_of(d) + && l >= own + { + problems.push(format!("crates/{name} (L{own}) depends on anicraft-{d} (L{l}); a crate may use only lower layers")); + } + } + } + assert!(seen.len() >= LAYERS.len(), "expected every crate in LAYERS to exist, found {seen:?}"); + // The shell may use any crate. + for dep in dependencies(&std::fs::read_to_string(root().join("Cargo.toml")).unwrap_or_default()) { + if let Some(l) = dep.strip_prefix("anicraft-").and_then(layer_of) { + assert!(l < SHELL_LAYER); + } + } + assert!(problems.is_empty(), "layering broken:\n{}", problems.join("\n")); +} + +#[test] +fn the_workspace_map_in_agents_md_matches_the_crates() { + let agents = std::fs::read_to_string(root().join("AGENTS.md")).expect("AGENTS.md"); + let mut documented: BTreeMap = BTreeMap::new(); + for line in agents.lines() { + let mut words = line.split_whitespace(); + if let (Some(path), Some(layer)) = (words.next(), words.next()) + && let Some(name) = path.strip_prefix("crates/") + && let Some(l) = layer.strip_prefix('L').and_then(|n| n.parse::().ok()) + { + documented.insert(name.to_string(), l); + } + } + let expected: BTreeMap = LAYERS.iter().map(|(n, l)| (n.to_string(), *l)).collect(); + assert_eq!(documented, expected, "AGENTS.md's workspace map and the layers enforced here disagree"); +} + +#[test] +fn dependency_lines_are_read_from_every_table() { + let m = "[package]\nname = \"x\"\n\n[dependencies]\nanicraft-geom.workspace = true\nserde = { version = \"1\" }\n# a comment\n\n[dev-dependencies]\npng.workspace = true\n\n[lints]\nworkspace = true\n"; + assert_eq!(dependencies(m), ["anicraft-geom", "serde", "png"]); +} diff --git a/src/main.rs b/src/main.rs index 7c570aef..0df8d900 100644 --- a/src/main.rs +++ b/src/main.rs @@ -104,3 +104,5 @@ fn main() -> eframe::Result { #[cfg(test)] mod guidelines_tests; +#[cfg(test)] +mod architecture_tests;