chore: merge main (GPU stage, SVG clips) into variable-width strokes; GPU parity covers width profiles (M7)

This commit is contained in:
Tanish Manku committed 2026-11-09 04:17:57 -07:00
commit d85e398c4a
43 files changed
+4218 -132

No files matched your search

+2 -1
View File
@@ -15,8 +15,9 @@ crates/doc L1 Document model, easing, timeline evaluation, sample scene
crates/text L1 Fonts on this computer, shaping and line layout into outlines (ADR 0012)
crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, PNG)
crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009)
crates/svg L2 SVG import: shapes, groups, use, styles, transforms, gradients → shapes
crates/svg L2 SVG import: shapes, groups, use, styles, gradients, clips/masks → mask layers, text
crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format
crates/gpu L3 wgpu stage renderer over the oracle's fills: tile binning, compute coverage (ADR 0019)
crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve/mcp
src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
```
+4
View File
@@ -20,6 +20,7 @@ shaders or SDK code).
| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | <https://github.com/googlefonts/noto-emoji> | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) |
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
| `assets/icons/anicraft-*.svg` (11 files: align, distribute, mask and masked layer, width tool) | Align panel, layer-type and Width tool icons | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style | MIT OR Apache-2.0 |
| `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
| `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) |
| `docs/images/` (screenshots and `sample-animation.gif`) | README | AniCraft contributors | Original work: AniCraft's own screenshots (`--screenshot`) and sample animation (`anicraft-cli gif`) | MIT OR Apache-2.0 |
@@ -66,6 +67,7 @@ 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). |
| Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | |
| Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. |
| Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. |
@@ -80,6 +82,8 @@ OR Apache-2.0) is noted in the table.
| 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. |
| SVG document import: shapes, styling and inheritance, transforms, viewBox and preserveAspectRatio, paint servers (gradients), `use` | `crates/svg` | W3C SVG 1.1 (§5, §6, §7, §9, §13) and SVG 2; CSS Color Module Level 3 (colour syntax and names) | W3C Royalty-Free Patent Policy. |
| SVG clip paths, masks and text: `clipPath`, `mask`, `text`/`tspan` positioning and text chunks, white-space handling | `crates/svg/src/clip.rs`, `crates/svg/src/text.rs` | W3C SVG 1.1 (§10, §14) and SVG 2 (§11 Text); W3C CSS Masking Module Level 1; CSS Fonts Level 3 (`font-family`, `font-weight`, `font-size` keywords) | W3C Royalty-Free Patent Policy. |
| Exact clipping of filled paths by a convex polygon | `crates/geom/src/clip.rs` | I. E. Sutherland and G. W. Hodgman, "Reentrant Polygon Clipping", CACM 17(1), 1974, extended to Bézier segments (de Casteljau subdivision, roots bracketed by critical points) | Published algorithm; no code taken. |
| Shape morphing (cubic normalization, subdivision to equal segment counts, winding and start-point alignment) | `crates/geom/src/morph.rs` | Standard curve-blending techniques from the public computer-graphics literature (de Casteljau subdivision, exact degree elevation) | |
| Affine QR decomposition for tweening | `crates/geom/src/affine.rs` | Standard linear algebra | |
| Least-squares cubic Bézier curve fitting (Pencil "Smooth") | `crates/geom/src/fit.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. |
+20
View File
@@ -15,6 +15,26 @@
param on `element.set_stroke`, the drawing commands and `paint.ink`.
* **Fixed**: perfectly horizontal or vertical lines inside a moved shape could not be picked
(their flat bounds were not transformed).
* **GPU stage, first slice** (M3, ADR 0019; build with `--features gpu-stage`). Preferences ›
Stage › Renderer (also View › Stage Rendering) can draw the stage on the graphics card
instead of the CPU. It draws fills, strokes and gradients from the CPU renderer's own
preparation and matches it to within one 8-bit step at a few edge pixels; masks, symbol
opacity, blend modes, filters and bitmaps still draw on the CPU, and the status bar says
which drew the stage and why. A 4K frame of 1,000 shapes takes about 9 ms instead of 18 ms.
Exports always use the CPU renderer. `ANICRAFT_STAGE_RENDERER=gpu|cpu` overrides the choice.
* **Clip paths, masks and text in SVG drawings** (ADR 0021). Import to Stage (Ctrl+R) now
brings clipped artwork across on mask layers: a drawing with clip paths comes in as a folder
named after the file, with each clipped group on a masked layer under a mask layer holding
the clip's shape, so you can move or reshape the mask afterwards. Clips that cut nothing
(the frame clip design tools add) are dropped, and clips inside clips are combined exactly
when they can be. Masks come across when they are solid shapes (white for luminance masks);
soft or faded masks are drawn unmasked and reported. Text comes in as text you can edit,
one block per positioned line, with its font, size, weight, italic, colour, letter spacing
and anchor (start, middle, end); fonts that aren't on this computer fall back to the default
and the status bar names them. A frame exported as SVG with masks imports back as the same
picture. Per-character positions, text on a path and dashed strokes are reported, not yet
imported.
* **Sound** (ADR 0020). Import WAV, Ogg Vorbis or MP3 sounds: **File › Import › Import to
Stage** puts one on a new layer at the playhead, its span as long as the sound; **Import to
Library** just adds it. A sound belongs to a keyframe, as in Animate: pick it under
Generated
+16
View File
@@ -204,6 +204,7 @@ dependencies = [
"anicraft-doc",
"anicraft-engine",
"anicraft-geom",
"anicraft-gpu",
"anicraft-render",
"cpal",
"eframe",
@@ -274,6 +275,20 @@ dependencies = [
"serde_json",
]
[[package]]
name = "anicraft-gpu"
version = "0.1.0"
dependencies = [
"anicraft-doc",
"anicraft-geom",
"anicraft-render",
"bytemuck",
"pollster 1.0.1",
"rayon",
"thiserror 2.0.21",
"wgpu",
]
[[package]]
name = "anicraft-plugins"
version = "0.1.0"
@@ -303,6 +318,7 @@ version = "0.1.0"
dependencies = [
"anicraft-doc",
"anicraft-geom",
"anicraft-text",
"anicraft-xml",
"thiserror 2.0.21",
]
+10
View File
@@ -25,6 +25,12 @@ anicraft-svg = { path = "crates/svg" }
anicraft-text = { path = "crates/text" }
anicraft-plugins = { path = "crates/plugins" }
anicraft-audio = { path = "crates/audio" }
anicraft-gpu = { path = "crates/gpu" }
# The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same
# (default) features, so the tree keeps one wgpu build.
wgpu = "30"
pollster = "1"
bytemuck = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
@@ -66,6 +72,9 @@ default-run = "anicraft"
# Plays sound during stage playback. Off: playback is silent (for builders without ALSA headers).
default = ["sound-output"]
sound-output = ["dep:cpal"]
# GPU stage renderer (ADR 0019), off by default: Preferences › Stage › Renderer can then hand
# the stage to the wgpu renderer. The CPU stays the default and the oracle.
gpu-stage = ["dep:anicraft-gpu"]
[[bin]]
name = "anicraft"
@@ -76,6 +85,7 @@ anicraft-geom.workspace = true
anicraft-doc.workspace = true
anicraft-render.workspace = true
anicraft-engine.workspace = true
anicraft-gpu = { workspace = true, optional = true }
eframe.workspace = true
egui.workspace = true
rfd.workspace = true
+102 -34
View File
@@ -7,6 +7,7 @@ use anicraft_render::{View, render};
use rayon::prelude::*;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Arc;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -191,9 +192,10 @@ fn export_png(s: &mut Session, p: &Value) -> Result<Value> {
/// Largest file Import to Stage reads.
const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024;
/// Import to Stage: the drawing's shapes become editable shapes on a new layer named after the
/// file, in a keyframe at the playhead, selected, as one undo step. Centred on the stage unless
/// `x`/`y` give its top-left corner.
/// Import to Stage: the drawing's shapes and text become editable elements on a new layer
/// named after the file, in a keyframe at the playhead, selected, as one undo step. A drawing
/// with clip paths or masks becomes a folder named after the file, with mask layers over the
/// artwork they clip (ADR 0021). Centred on the stage unless `x`/`y` give its top-left corner.
fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
let path = PathBuf::from(str_req(p, "path")?);
if crate::cmds_sound::is_sound(&path) {
@@ -214,7 +216,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
let drawing = import_image(s, &path, bytes)?;
(drawing, s.doc.bitmaps.last().map(|b| b.id.0))
};
if drawing.shapes.is_empty() {
if drawing.is_empty() {
return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary())));
}
let stage = s.doc.stage;
@@ -225,37 +227,108 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
}
let place = anicraft_geom::Affine::translate(x, y);
let name: String = path.file_stem().map_or_else(|| "Imported".into(), |n| n.to_string_lossy().chars().take(128).collect());
crate::cmds_timeline::new_layer(s, &json!({"name": name}))?;
let frame = s.frame;
let end = s.frame_count().max(frame + 1);
let mut elements = Vec::with_capacity(drawing.shapes.len());
for sh in drawing.shapes {
let id = anicraft_doc::ElementId(s.doc.alloc_id());
elements.push(std::sync::Arc::new(anicraft_doc::Element {
id,
name: sh.name,
transform: place.mul(&sh.transform),
color: anicraft_doc::ColorEffect { alpha: sh.alpha, ..Default::default() },
kind: anicraft_doc::ElementKind::Shape(sh.shape),
}));
}
let ids: Vec<anicraft_doc::ElementId> = elements.iter().map(|e| e.id).collect();
let layer = s.layer_mut(None)?;
let elements = |s: &mut Session, list: Vec<anicraft_svg::ImportedElement>| -> Vec<Arc<anicraft_doc::Element>> {
list.into_iter()
.map(|e| {
let id = anicraft_doc::ElementId(s.doc.alloc_id());
Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect { alpha: e.alpha, ..Default::default() }, kind: e.kind })
})
.collect()
};
// Empty before the playhead, the drawing from the playhead to the end of the timeline.
let mut key = anicraft_doc::Keyframe::new(frame, end - frame);
key.elements = elements;
layer.keyframes = if frame == 0 { vec![std::sync::Arc::new(key)] } else { vec![std::sync::Arc::new(anicraft_doc::Keyframe::new(0, frame)), std::sync::Arc::new(key)] };
layer.normalize();
let layer_id = layer.id;
let keys = |els: Vec<Arc<anicraft_doc::Element>>| -> Vec<Arc<anicraft_doc::Keyframe>> {
let mut key = anicraft_doc::Keyframe::new(frame, end - frame);
key.elements = els;
if frame == 0 { vec![Arc::new(key)] } else { vec![Arc::new(anicraft_doc::Keyframe::new(0, frame)), Arc::new(key)] }
};
let texts = drawing.elements().filter(|e| matches!(e.kind, anicraft_doc::ElementKind::Text(_))).count();
let count = drawing.elements().count();
let masks = drawing.layers.iter().filter(|l| l.mask.is_some()).count();
let (width, height, report) = (drawing.width, drawing.height, drawing.report);
let mut layers = drawing.layers;
let (layer_id, ids, made, folder) = if layers.len() == 1 && masks == 0 {
// One layer, named after the file, as Import to Stage always made.
crate::cmds_timeline::new_layer(s, &json!({"name": name}))?;
let els = elements(s, layers.pop().map(|l| l.elements).unwrap_or_default());
let ids: Vec<anicraft_doc::ElementId> = els.iter().map(|e| e.id).collect();
let layer = s.layer_mut(None)?;
layer.keyframes = keys(els);
layer.normalize();
(layer.id, ids, 1, None)
} else {
// 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);
if tl.layers.len() + made > 1000 {
return Err(EngineError::State(format!("importing {} would make {made} layers; a timeline holds at most 1000", path.display())));
}
// Above the active layer, beside it; above its whole mask group when it is masked.
let mut at = s.active_layer_index().unwrap_or(0);
let mut parent = tl.layers.get(at).and_then(|l| l.parent);
if let Some(m) = parent.and_then(|pid| tl.layer(pid)).filter(|m| m.kind == anicraft_doc::LayerKind::Mask) {
parent = m.parent;
at = tl.layers.iter().position(|l| l.id == m.id).unwrap_or(at);
}
let palette = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65];
let mut color = tl.layers.len();
let mut new_layer = |s: &mut Session, name: String, kind: anicraft_doc::LayerKind, parent: Option<anicraft_doc::LayerId>| {
let mut l = anicraft_doc::Layer::new(anicraft_doc::LayerId(s.doc.alloc_id()), name);
l.kind = kind;
l.parent = parent;
color += 1;
l.color = anicraft_doc::Rgba::hex(palette[color % palette.len()]);
l
};
let mut folder = new_layer(s, name, anicraft_doc::LayerKind::Folder, parent);
folder.keyframes.clear();
let fid = folder.id;
let mut stack = vec![folder];
let mut top: Option<(anicraft_doc::LayerId, Vec<anicraft_doc::ElementId>)> = None;
for (n, l) in layers.into_iter().enumerate().rev() {
let mut inside = Some(fid);
if let Some(mask) = l.mask {
let label = if mask.name.is_empty() { "Mask".to_string() } else { mask.name.clone() };
let mut ml = new_layer(s, label, anicraft_doc::LayerKind::Mask, Some(fid));
// Mask layers are locked, as Animate keeps them: the mask shows, its edge hides.
ml.locked = true;
ml.keyframes = keys(elements(s, mask.elements));
inside = Some(ml.id);
stack.push(ml);
}
let mut cl = new_layer(s, format!("Layer {}", n + 1), anicraft_doc::LayerKind::Normal, inside);
let els = elements(s, l.elements);
if top.is_none() {
top = Some((cl.id, els.iter().map(|e| e.id).collect()));
}
cl.keyframes = keys(els);
stack.push(cl);
}
let tl = s.doc.timeline_mut(s.scene);
for (k, l) in stack.into_iter().enumerate() {
tl.layers.insert((at + k).min(tl.layers.len()), Arc::new(l));
}
tl.repair_masks();
let (lid, ids) = top.unwrap_or((fid, Vec::new()));
s.layer = lid;
(lid, ids, made, Some(fid.0))
};
s.selection = ids.clone();
Ok(json!({
"layer": layer_id.0,
"elements": ids.len(),
"folder": folder,
"layers": made,
"masks": masks,
"texts": texts,
"elements": count,
"bitmap": bitmap,
"width": drawing.width,
"height": drawing.height,
"report": drawing.report.summary(),
"skipped": drawing.report.skipped,
"width": width,
"height": height,
"report": report.summary(),
"skipped": report.skipped,
"missing_fonts": report.missing_fonts,
}))
}
@@ -273,12 +346,7 @@ fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec<u8>) -> Resu
stroke: None,
fill_rule: anicraft_geom::FillRule::NonZero,
};
Ok(anicraft_svg::SvgImport {
width: w,
height: h,
shapes: vec![anicraft_svg::ImportedShape { name, transform: anicraft_geom::Affine::IDENTITY, alpha: 1.0, shape }],
report: anicraft_svg::Report::default(),
})
Ok(anicraft_svg::SvgImport::single(w, h, vec![anicraft_svg::ImportedElement { name, transform: anicraft_geom::Affine::IDENTITY, alpha: 1.0, kind: anicraft_doc::ElementKind::Shape(shape) }]))
}
/// Movie frame `frame` as a standalone SVG document (vectors, gradients and masks kept).
+140 -13
View File
@@ -7,6 +7,10 @@
//! drag or a fast pan never builds a backlog. Jobs carry a `Document` clone, which is O(layers)
//! thanks to structural sharing. Keys hash the document *state id*, so undoing back to a state
//! already rendered is a cache hit.
//!
//! The CPU oracle draws by default. A [`Rasterizer`] (the GPU stage, ADR 0019) can take over;
//! whatever it hands back (content it doesn't draw yet, or a failed device) the oracle draws, so
//! the picture is always complete. Keys include which rasterizer drew them.
use crate::history::StateId;
use anicraft_doc::{ColorEffect, DisplayList, Document, Rgba, evaluate_scene};
@@ -22,6 +26,8 @@ use std::time::Instant;
#[derive(Clone)]
pub struct FrameJob {
pub key: u64,
/// Which rasterizer the key was made for (0: the CPU oracle); see [`RenderService::job`].
pub raster: u64,
/// Identity of the evaluated scene (`scene_key`): tiles of one frame share it.
pub scene: u64,
pub doc: Document,
@@ -40,8 +46,16 @@ pub struct FrameImage {
pub ms: f32,
pub stats: RenderStats,
pub error: Option<String>,
/// Drawn by the rasterizer rather than the CPU oracle.
pub gpu: bool,
/// Why the oracle drew it although a rasterizer is set (for example "masks").
pub fallback: Option<String>,
}
/// Draws a display list as premultiplied RGBA8 in place of the CPU oracle, or says why it
/// can't (then the oracle draws it).
pub type Rasterizer = Arc<dyn Fn(&DisplayList, &View) -> Result<(Vec<u8>, RenderStats), String> + Send + Sync>;
/// Identity of an evaluated scene: the display list depends on these and nothing else.
pub fn scene_key(state: StateId, frame: u32, onion: bool) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
@@ -68,7 +82,20 @@ pub fn frame_key(state: StateId, frame: u32, view: &View, onion: bool) -> u64 {
/// 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: bool) -> FrameJob {
FrameJob { key: frame_key(state, frame, &view, onion), scene: scene_key(state, frame, onion), doc: doc.clone(), frame, view, onion }
FrameJob { key: frame_key(state, frame, &view, onion), raster: 0, scene: scene_key(state, frame, onion), doc: doc.clone(), frame, view, onion }
}
/// A job for rasterizer `raster` (from [`RenderService::raster_id`]; 0 is the CPU oracle, and
/// gives [`make_job`]'s key), keyed apart from other rasterizers' pictures.
pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
let mut j = make_job(state, doc, frame, view, onion);
if raster != 0 {
let mut h = std::collections::hash_map::DefaultHasher::new();
(j.key, raster).hash(&mut h);
j.key = h.finish();
j.raster = raster;
}
j
}
/// Movie frame `frame`'s display list, with ±2 onion-skin frames (tinted red before, green after)
@@ -94,10 +121,27 @@ pub fn display_list_with_onion(doc: &Document, frame: u32, onion: bool) -> Displ
dl
}
/// Renders a job against an already evaluated scene.
/// Renders a job against an already evaluated scene, on the CPU oracle.
pub fn render_job_with(job: &FrameJob, dl: &DisplayList) -> FrameImage {
render_job_by(job, dl, None)
}
/// Renders a job with `raster` when given (falling back to the oracle for what it hands back).
fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>) -> FrameImage {
let t0 = Instant::now();
// Last-resort guard: a renderer bug must not take the editor down with it.
let mut fallback = None;
if let Some(r) = raster {
// Last-resort guard: a renderer bug must not take the editor down with it.
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| r(dl, &job.view))) {
Ok(Ok((rgba, stats))) if rgba.len() == job.view.width as usize * job.view.height as usize * 4 => {
let ms = t0.elapsed().as_secs_f32() * 1000.0;
return FrameImage { key: job.key, frame: job.frame, width: job.view.width, height: job.view.height, rgba_premul: rgba, ms, stats, error: None, gpu: true, fallback: None };
}
Ok(Ok(_)) => fallback = Some("the GPU returned a wrong-sized image".to_string()),
Ok(Err(why)) => fallback = Some(why),
Err(_) => fallback = Some("the GPU renderer failed".to_string()),
}
}
let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render(dl, &job.view)));
let (rgba, stats, error) = match out {
Ok(Ok((pm, stats))) => (pm.to_premul_rgba8(), stats, None),
@@ -105,7 +149,7 @@ pub fn render_job_with(job: &FrameJob, dl: &DisplayList) -> FrameImage {
Err(_) => (Vec::new(), RenderStats::default(), Some("the renderer failed on this frame".into())),
};
let (width, height) = if error.is_none() { (job.view.width, job.view.height) } else { (0, 0) };
FrameImage { key: job.key, frame: job.frame, width, height, rgba_premul: rgba, ms: t0.elapsed().as_secs_f32() * 1000.0, stats, error }
FrameImage { key: job.key, frame: job.frame, width, height, rgba_premul: rgba, ms: t0.elapsed().as_secs_f32() * 1000.0, stats, error, gpu: false, fallback }
}
/// Renders a job synchronously, evaluating its scene.
@@ -115,18 +159,34 @@ pub fn render_job(job: &FrameJob) -> FrameImage {
/// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel.
pub fn render_batch(jobs: &[FrameJob]) -> Vec<FrameImage> {
render_batch_by(jobs, &RasterSlot::default())
}
/// [`render_batch`] with the service's rasterizer for the jobs made for it.
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_with_onion(&j.doc, j.frame, j.onion)));
}
jobs.par_iter()
.map(|j| match scenes.get(&j.scene) {
Some(dl) => render_job_with(j, dl),
None => render_job(j),
.map(|j| {
// A job made for another rasterizer (queued before a switch) is drawn by the oracle.
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_with_onion(&j.doc, j.frame, j.onion), raster),
}
})
.collect()
}
/// The rasterizer in use and its id (0 and `None`: the oracle).
#[derive(Clone, Default)]
struct RasterSlot {
id: u64,
raster: Option<Rasterizer>,
}
/// LRU cache of finished images, bounded by bytes.
pub struct FrameCache {
map: HashMap<u64, (Arc<FrameImage>, u64)>,
@@ -196,6 +256,7 @@ struct Queue {
struct Shared {
queue: Mutex<Queue>,
raster: Mutex<RasterSlot>,
wake: Condvar,
cache: Mutex<FrameCache>,
notify: Option<Box<dyn Fn() + Send + Sync>>,
@@ -216,7 +277,7 @@ impl RenderService {
/// Starts the worker. `notify` runs on the worker after each finished batch (the UI passes
/// "request a repaint"). If no thread can be spawned, requests render synchronously.
pub fn new(cache_bytes: usize, notify: Option<Box<dyn Fn() + Send + Sync>>) -> RenderService {
let shared = Arc::new(Shared { queue: Mutex::new(Queue::default()), wake: Condvar::new(), cache: Mutex::new(FrameCache::new(cache_bytes)), notify });
let shared = Arc::new(Shared { queue: Mutex::new(Queue::default()), raster: Mutex::new(RasterSlot::default()), wake: Condvar::new(), cache: Mutex::new(FrameCache::new(cache_bytes)), notify });
let s = shared.clone();
let worker = std::thread::Builder::new().name("anicraft-render".into()).spawn(move || worker_loop(&s)).ok();
RenderService { shared, worker }
@@ -230,6 +291,35 @@ impl RenderService {
self.shared.queue.lock().unwrap_or_else(PoisonError::into_inner)
}
fn slot(&self) -> RasterSlot {
self.shared.raster.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Draws with `raster` from now on (`None`: the CPU oracle). Pictures are keyed by who drew
/// them, so the stage keeps showing the previous ones as placeholders until the new ones
/// arrive, and switching back finds the oracle's pictures still cached.
pub fn set_rasterizer(&self, raster: Option<Rasterizer>) {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let mut s = self.shared.raster.lock().unwrap_or_else(PoisonError::into_inner);
s.id = if raster.is_some() { NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } else { 0 };
s.raster = raster;
}
/// Whether a rasterizer is set.
pub fn has_rasterizer(&self) -> bool {
self.slot().raster.is_some()
}
/// The rasterizer in use (0: the CPU oracle), for [`make_job_for`].
pub fn raster_id(&self) -> u64 {
self.slot().id
}
/// A job for the rasterizer in use ([`make_job_for`] with [`RenderService::raster_id`]).
pub fn job(&self, state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
make_job_for(self.raster_id(), state, doc, frame, view, onion)
}
/// Images that are ready, in order; the missing ones become the new urgent batch
/// (replacing any older pending batch).
pub fn request_batch(&self, jobs: Vec<FrameJob>) -> Vec<Option<Arc<FrameImage>>> {
@@ -252,7 +342,7 @@ impl RenderService {
}
if self.worker.is_none() {
// No thread available: render here, so the caller still gets pictures.
let imgs: Vec<Arc<FrameImage>> = render_batch(&missing).into_iter().map(Arc::new).collect();
let imgs: Vec<Arc<FrameImage>> = render_batch_by(&missing, &self.slot()).into_iter().map(Arc::new).collect();
let mut cache = self.cache();
for img in &imgs {
cache.insert(img.clone());
@@ -295,7 +385,7 @@ impl RenderService {
.collect();
(out, missing)
};
let fresh: Vec<Arc<FrameImage>> = render_batch(&missing).into_iter().map(Arc::new).collect();
let fresh: Vec<Arc<FrameImage>> = render_batch_by(&missing, &self.slot()).into_iter().map(Arc::new).collect();
{
let mut cache = self.cache();
for img in &fresh {
@@ -314,7 +404,7 @@ impl RenderService {
let key = job.key;
let frame = job.frame;
self.render_now_batch(vec![job]).into_iter().next().unwrap_or_else(|| {
Arc::new(FrameImage { key, frame, width: 0, height: 0, rgba_premul: Vec::new(), ms: 0.0, stats: RenderStats::default(), error: Some("render failed".into()) })
Arc::new(FrameImage { key, frame, width: 0, height: 0, rgba_premul: Vec::new(), ms: 0.0, stats: RenderStats::default(), error: Some("render failed".into()), gpu: false, fallback: None })
})
}
@@ -401,7 +491,8 @@ fn worker_loop(s: &Shared) {
let cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner);
jobs.iter().filter(|j| !cache.contains(j.key)).cloned().collect()
};
let imgs = render_batch(&todo);
let slot = s.raster.lock().unwrap_or_else(PoisonError::into_inner).clone();
let imgs = render_batch_by(&todo, &slot);
{
let mut cache = s.cache.lock().unwrap_or_else(PoisonError::into_inner);
for img in imgs {
@@ -527,11 +618,47 @@ mod tests {
}
}
#[test]
fn a_rasterizer_draws_what_it_can_and_the_oracle_the_rest() {
let doc = sample::demo();
let svc = RenderService::new(64 << 20, None);
let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) };
let cpu = svc.job(1, &doc, 9, view, false);
assert_eq!(cpu.key, make_job(1, &doc, 9, view, false).key, "no rasterizer: the oracle's keys");
// A stand-in GPU that paints everything one colour, and refuses onion-skinned frames.
let plain = display_list_with_onion(&doc, 9, false).items.len();
let flat: Rasterizer = Arc::new(move |dl: &DisplayList, v: &View| {
if dl.items.len() > plain {
return Err("too much".into());
}
Ok(([10u8, 20, 30, 255].repeat(v.width as usize * v.height as usize), RenderStats::default()))
});
svc.set_rasterizer(Some(flat));
assert!(svc.has_rasterizer());
let gpu = svc.job(1, &doc, 9, view, false);
assert_ne!(gpu.key, cpu.key, "pictures are keyed by who drew them");
let img = svc.render_now(gpu.clone());
assert!(img.gpu && img.fallback.is_none() && img.rgba_premul[..4] == [10, 20, 30, 255]);
// What it refuses, the oracle draws, saying why.
let onion = svc.job(1, &doc, 9, view, true);
let img = svc.render_now(onion.clone());
assert!(!img.gpu && img.fallback.as_deref() == Some("too much"));
assert_eq!(img.rgba_premul, render_job(&make_job(1, &doc, 9, view, true)).rgba_premul);
// Through the worker too; and a job made for an older rasterizer is drawn by the oracle.
let ahead = svc.job(1, &doc, 10, view, false);
svc.prefetch(vec![ahead.clone()]);
assert!(svc.wait_for(ahead.key, 10_000).is_some_and(|i| i.gpu));
svc.set_rasterizer(None);
let stale = FrameJob { key: 77, ..ahead };
assert!(!render_batch_by(&[stale], &svc.slot())[0].gpu);
assert_eq!(svc.job(1, &doc, 9, view, false).key, cpu.key, "back to the oracle's keys");
}
#[test]
fn cache_respects_budget_lru() {
let mut c = FrameCache::new(3 * 1000);
for k in 0..10u64 {
c.insert(Arc::new(FrameImage { key: k, frame: 0, width: 0, height: 0, rgba_premul: vec![0; 800], ms: 0.0, stats: RenderStats::default(), error: None }));
c.insert(Arc::new(FrameImage { key: k, frame: 0, width: 0, height: 0, rgba_premul: vec![0; 800], ms: 0.0, stats: RenderStats::default(), error: None, gpu: false, fallback: None }));
}
assert!(c.bytes() <= 3000);
assert!(c.contains(9) && !c.contains(0));
+67 -1
View File
@@ -1113,7 +1113,7 @@ fn opening_an_xfl_folder_imports_it_untitled() {
// It renders.
let dl = s.display_list();
assert!(dl.items.iter().any(|i| matches!(i.fill, Some(anicraft_doc::Paint::Solid(c)) if c == anicraft_doc::Rgba::hex(0xff8800))));
// Text comes across as an editable text block when this computer has fonts (ADR 0015),
// Text comes across as an editable text block when this computer has fonts (ADR 0014),
// with the missing family named.
if !anicraft_text::Fonts::get().families().is_empty() {
assert!(v["report"].as_str().unwrap().contains("Fonts not on this computer"), "{v}");
@@ -1217,6 +1217,72 @@ fn bring_forward_send_backward_and_remove_transform() {
assert_eq!(t.translation(), before);
}
#[test]
fn masked_frames_round_trip_through_svg_onto_mask_layers() {
// A drawing with a mask: a background, artwork under an ellipse mask, a layer on top.
let mut src = Session::default();
run(&mut src, "draw.rect", json!({"x": 0, "y": 0, "w": 640, "h": 360, "fill": "#20304a"}));
run(&mut src, "layer.new", json!({"name": "Art"}));
run(&mut src, "draw.rect", json!({"x": 100, "y": 60, "w": 400, "h": 240, "fill": "#ff6b4a"}));
run(&mut src, "draw.star", json!({"cx": 300, "cy": 180, "outer": 150, "inner": 60, "points": 5, "fill": "#ffd54a"}));
run(&mut src, "layer.new", json!({"name": "Mask"}));
run(&mut src, "draw.ellipse", json!({"x": 180, "y": 80, "w": 260, "h": 200}));
run(&mut src, "layer.toggle_mask", json!({}));
run(&mut src, "layer.new", json!({"name": "Top"}));
run(&mut src, "draw.rect", json!({"x": 20, "y": 20, "w": 60, "h": 60, "fill": "#66bb6a"}));
let dir = std::env::temp_dir().join(format!("anicraft-svg-mask-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let svg = dir.join("masked.svg");
std::fs::write(&svg, crate::cmds_file::frame_svg(&src.doc, 0)).unwrap();
// Import it at the origin of an empty document of the same size.
let mut s = Session::default();
let before = s.doc.timeline(s.scene).layers.len();
let v = run(&mut s, "file.import", json!({"path": svg.display().to_string(), "x": 0, "y": 0}));
assert_eq!((v["masks"].as_u64(), v["layers"].as_u64()), (Some(1), Some(5)), "{v}");
let tl = s.doc.timeline(s.scene);
use anicraft_doc::LayerKind;
let kinds: Vec<(LayerKind, usize)> = tl.layers.iter().take(5).map(|l| (l.kind, tl.depth(tl.layers.iter().position(|x| x.id == l.id).unwrap()))).collect();
assert_eq!(kinds, [(LayerKind::Folder, 0), (LayerKind::Normal, 1), (LayerKind::Mask, 1), (LayerKind::Normal, 2), (LayerKind::Normal, 1)], "folder › top art, mask › masked art, background");
assert_eq!(tl.layers[0].name, "masked");
assert_eq!(tl.layers.len(), before + 5);
assert_eq!(s.selection.len(), 2, "the top layer's artwork (exported as a fill and a stroke) is selected");
// The same picture comes back.
let a = anicraft_render::render_frame(&src.doc, 0, 0.5).unwrap().to_rgba8();
let b = anicraft_render::render_frame(&s.doc, 0, 0.5).unwrap().to_rgba8();
let worst = a.iter().zip(&b).map(|(x, y)| (i32::from(*x) - i32::from(*y)).unsigned_abs()).max().unwrap();
let mean = a.iter().zip(&b).map(|(x, y)| (i32::from(*x) - i32::from(*y)).unsigned_abs() as f64).sum::<f64>() / a.len() as f64;
assert!(mean < 0.01 && worst <= 2, "mean {mean:.3}, worst {worst} of 255");
// Exporting the import again gives the same masks.
assert_eq!(crate::cmds_file::frame_svg(&s.doc, 0).matches("<clipPath").count(), 1);
// One undo step removes the folder and all its layers.
s.undo().unwrap();
assert_eq!(s.doc.timeline(s.scene).layers.len(), before);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn imported_svg_text_is_editable_text() {
if anicraft_text::Fonts::get().families().is_empty() {
return;
}
let dir = std::env::temp_dir().join(format!("anicraft-svg-text-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let svg = dir.join("title.svg");
std::fs::write(&svg, r##"<svg width="300" height="80"><text x="150" y="50" text-anchor="middle" font-family="Zz Not Installed" font-size="32" fill="#ff0000">Title</text><rect width="10" height="10"/></svg>"##).unwrap();
let mut s = Session::default();
let v = run(&mut s, "file.import", json!({"path": svg.display().to_string()}));
assert_eq!((v["texts"].as_u64(), v["elements"].as_u64(), v["layers"].as_u64()), (Some(1), Some(2), Some(1)));
assert_eq!(v["missing_fonts"], json!(["Zz Not Installed"]));
assert!(v["report"].as_str().unwrap().contains("Fonts not on this computer"));
let text = s.visible_elements().into_iter().find(|e| matches!(e.kind, anicraft_doc::ElementKind::Text(_))).unwrap();
run(&mut s, "element.select", json!({"ids": [text.id.0]}));
run(&mut s, "text.edit", json!({"text": "Longer title"}));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn mask_layers_reveal_hide_pick_and_move_as_a_group() {
let mut s = Session::default();
+449
View File
@@ -0,0 +1,449 @@
//! Exact clipping of filled paths by a convex polygon.
//!
//! Sutherland and Hodgman's re-entrant polygon clipping (CACM 17(1), 1974), extended to Bézier
//! segments: each subpath is clipped against the polygon one edge's half-plane at a time. A
//! segment is split where it crosses the edge's line (its signed distance from the line is a
//! polynomial in `t` of the segment's degree, whose roots are bracketed between its critical
//! points and bisected), the pieces inside are kept as exact sub-curves (de Casteljau), and the
//! pieces outside become the straight run along the line between where they leave and come
//! back. For every point strictly inside the polygon the result winds as often as the original,
//! so the filled area is exactly the intersection, with either fill rule. Meant for fills: the
//! runs along the polygon are new edges, so a stroke of the result would differ.
use crate::{Path, PathCmd, Vec2};
/// The corners of `path` when it is one convex polygon of straight edges (three or more
/// corners that are not all on a line), in the path's order; `None` otherwise.
pub fn convex_polygon(path: &Path) -> Option<Vec<Vec2>> {
let mut pts: Vec<Vec2> = Vec::new();
let mut closed = false;
for (i, c) in path.cmds.iter().enumerate() {
match *c {
PathCmd::MoveTo(p) if i == 0 => pts.push(p),
PathCmd::LineTo(p) if !closed && i > 0 => pts.push(p),
PathCmd::Close if i > 0 => closed = true,
_ => return None,
}
}
if !pts.iter().all(|p| p.is_finite()) {
return None;
}
pts.dedup_by(|a, b| a.distance(*b) <= 1e-6);
while pts.len() > 1 && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.distance(*b) <= 1e-6) {
pts.pop();
}
// Drop corners on a straight run, then check that every turn goes the same way and the
// turns add up to one full turn (a pentagram turns one way too, twice around).
let scale = pts.iter().fold(0.0f32, |m, p| m.max(p.x.abs()).max(p.y.abs())).max(1.0);
let mut i = 0;
while pts.len() >= 3 && i < pts.len() {
let n = pts.len();
let (a, b, c) = (pts[(i + n - 1) % n], pts[i], pts[(i + 1) % n]);
if (b - a).cross(c - b).abs() <= 1e-7 * scale * scale {
pts.remove(i);
} else {
i += 1;
}
}
let n = pts.len();
if n < 3 {
return None;
}
let mut sign = 0.0f32;
let mut turning = 0.0f32;
for i in 0..n {
let (a, b, c) = (pts[i], pts[(i + 1) % n], pts[(i + 2) % n]);
let (u, v) = (b - a, c - b);
let cr = u.cross(v);
if sign == 0.0 {
sign = cr.signum();
} else if cr.signum() != sign {
return None;
}
turning += cr.atan2(u.dot(v));
}
((turning.abs() - std::f32::consts::TAU).abs() < 1e-2).then_some(pts)
}
#[derive(Clone, Copy, Debug)]
enum Seg {
Line(Vec2),
Quad(Vec2, Vec2),
Cubic(Vec2, Vec2, Vec2),
}
impl Seg {
fn end(&self) -> Vec2 {
match *self {
Seg::Line(p) | Seg::Quad(_, p) | Seg::Cubic(_, _, p) => p,
}
}
}
struct Contour {
start: Vec2,
segs: Vec<Seg>,
}
/// The subpaths of `path`, each closed (as a fill closes it).
fn contours(path: &Path) -> Vec<Contour> {
let mut out: Vec<Contour> = Vec::new();
let mut cur: Option<Contour> = None;
let mut last = Vec2::ZERO;
let finish = |c: Option<Contour>, out: &mut Vec<Contour>| {
if let Some(mut c) = c
&& !c.segs.is_empty()
{
if c.segs.last().is_some_and(|s| s.end() != c.start) {
c.segs.push(Seg::Line(c.start));
}
out.push(c);
}
};
for cmd in &path.cmds {
let seg = match *cmd {
PathCmd::MoveTo(p) => {
finish(cur.take(), &mut out);
cur = Some(Contour { start: p, segs: Vec::new() });
last = p;
continue;
}
PathCmd::Close => {
if let Some(c) = &cur {
last = c.start;
}
finish(cur.take(), &mut out);
continue;
}
PathCmd::LineTo(p) => Seg::Line(p),
PathCmd::QuadTo(a, p) => Seg::Quad(a, p),
PathCmd::CubicTo(a, b, p) => Seg::Cubic(a, b, p),
};
let c = cur.get_or_insert(Contour { start: last, segs: Vec::new() });
c.segs.push(seg);
last = seg.end();
}
finish(cur, &mut out);
out
}
/// A Bernstein polynomial's value at `t` (de Casteljau on its coefficients).
fn bernstein(c: &[f32], t: f32) -> f32 {
let mut v: [f32; 4] = [0.0; 4];
let n = c.len().min(4);
v[..n].copy_from_slice(&c[..n]);
for k in (1..n).rev() {
for i in 0..k {
v[i] = v[i] + (v[i + 1] - v[i]) * t;
}
}
v[0]
}
/// Where a Bernstein polynomial of degree 1 to 3 changes sign in (0, 1), sorted. Its critical
/// points split [0, 1] into monotone stretches, and each stretch whose ends differ in sign holds
/// one root, found by bisection.
fn sign_changes(c: &[f32]) -> Vec<f32> {
let mut breaks: Vec<f32> = Vec::with_capacity(4);
match *c {
[_, _, _, _] => {
// The derivative's Bernstein coefficients, as a power-basis quadratic.
let (e0, e1, e2) = (c[1] - c[0], c[2] - c[1], c[3] - c[2]);
let (a, b, k) = (e0 - 2.0 * e1 + e2, 2.0 * (e1 - e0), e0);
if a.abs() > 1e-12 {
let disc = b * b - 4.0 * a * k;
if disc >= 0.0 {
let q = -0.5 * (b + b.signum() * disc.sqrt());
breaks.push(q / a);
if q != 0.0 {
breaks.push(k / q);
}
}
} else if b.abs() > 1e-12 {
breaks.push(-k / b);
}
}
[_, _, _] => {
let (e0, e1) = (c[1] - c[0], c[2] - c[1]);
if (e0 - e1).abs() > 1e-12 {
breaks.push(e0 / (e0 - e1));
}
}
_ => {}
}
breaks.retain(|t| t.is_finite() && *t > 0.0 && *t < 1.0);
breaks.push(0.0);
breaks.push(1.0);
breaks.sort_by(f32::total_cmp);
let mut roots = Vec::new();
for w in breaks.windows(2) {
let (mut lo, mut hi) = (w[0], w[1]);
let (flo, fhi) = (bernstein(c, lo), bernstein(c, hi));
if flo == 0.0 && lo > 0.0 {
roots.push(lo);
}
if flo * fhi >= 0.0 {
continue;
}
for _ in 0..48 {
let mid = 0.5 * (lo + hi);
if (bernstein(c, mid) < 0.0) == (flo < 0.0) {
lo = mid;
} else {
hi = mid;
}
}
roots.push(0.5 * (lo + hi));
}
roots.dedup_by(|a, b| (*a - *b).abs() < 1e-7);
roots
}
fn split_quad(p: [Vec2; 3], t: f32) -> ([Vec2; 3], [Vec2; 3]) {
let a = p[0].lerp(p[1], t);
let b = p[1].lerp(p[2], t);
let m = a.lerp(b, t);
([p[0], a, m], [m, b, p[2]])
}
fn split_cubic(p: [Vec2; 4], t: f32) -> ([Vec2; 4], [Vec2; 4]) {
let (a, b, c) = (p[0].lerp(p[1], t), p[1].lerp(p[2], t), p[2].lerp(p[3], t));
let (d, e) = (a.lerp(b, t), b.lerp(c, t));
let m = d.lerp(e, t);
([p[0], a, d, m], [m, e, c, p[3]])
}
/// The piece of a segment (starting at `p0`) between `t0` and `t1`, without its start point.
fn piece(p0: Vec2, seg: Seg, t0: f32, t1: f32) -> Seg {
// Split at t1, then the first part at t0 / t1.
let u = if t1 > 0.0 { (t0 / t1).clamp(0.0, 1.0) } else { 0.0 };
match seg {
Seg::Line(p) => Seg::Line(p0.lerp(p, t1)),
Seg::Quad(a, p) => {
let (left, _) = split_quad([p0, a, p], t1);
let (_, r) = split_quad(left, u);
Seg::Quad(r[1], r[2])
}
Seg::Cubic(a, b, p) => {
let (left, _) = split_cubic([p0, a, b, p], t1);
let (_, r) = split_cubic(left, u);
Seg::Cubic(r[1], r[2], r[3])
}
}
}
fn point_at(p0: Vec2, seg: Seg, t: f32) -> Vec2 {
match seg {
Seg::Line(p) => p0.lerp(p, t),
Seg::Quad(a, p) => split_quad([p0, a, p], t).0[2],
Seg::Cubic(a, b, p) => split_cubic([p0, a, b, p], t).0[3],
}
}
/// `c` clipped to the half-plane where `dist ≥ 0`, with points outside projected onto its line.
fn clip_half(c: &Contour, dist: &dyn Fn(Vec2) -> f32, proj: &dyn Fn(Vec2) -> Vec2) -> Contour {
let mut out = Contour { start: if dist(c.start) >= 0.0 { c.start } else { proj(c.start) }, segs: Vec::with_capacity(c.segs.len() + 4) };
let mut p0 = c.start;
for &seg in &c.segs {
let ds: Vec<f32> = match seg {
Seg::Line(p) => vec![dist(p0), dist(p)],
Seg::Quad(a, p) => vec![dist(p0), dist(a), dist(p)],
Seg::Cubic(a, b, p) => vec![dist(p0), dist(a), dist(b), dist(p)],
};
if ds.iter().all(|d| *d >= 0.0) {
out.segs.push(seg);
} else if ds.iter().all(|d| *d <= 0.0) {
out.segs.push(Seg::Line(proj(seg.end())));
} else {
let mut ts = vec![0.0f32];
ts.extend(sign_changes(&ds));
ts.push(1.0);
for w in ts.windows(2) {
let (t0, t1) = (w[0], w[1]);
if t1 - t0 <= 1e-9 {
continue;
}
if bernstein(&ds, 0.5 * (t0 + t1)) >= 0.0 {
out.segs.push(piece(p0, seg, t0, t1));
} else {
out.segs.push(Seg::Line(proj(point_at(p0, seg, t1))));
}
}
}
p0 = seg.end();
}
out
}
/// The filled area of `path` inside the convex `polygon` (any orientation), exactly: curves
/// stay curves. Every subpath of the result is closed. An empty or degenerate polygon gives an
/// empty path.
pub fn clip_convex(path: &Path, polygon: &[Vec2]) -> Path {
let n = polygon.len();
let area2: f32 = (0..n).map(|i| polygon[i].cross(polygon[(i + 1) % n])).sum();
if n < 3 || !area2.is_finite() || area2.abs() <= 1e-12 {
return Path::new();
}
let s = area2.signum();
let mut cs = contours(path);
for i in 0..n {
let (a, b) = (polygon[i], polygon[(i + 1) % n]);
let e = b - a;
let len = e.length();
if len <= 1e-9 {
continue;
}
let dir = e * (1.0 / len);
// Signed distance, positive inside; projection onto the edge's line.
let dist = move |p: Vec2| s * dir.cross(p - a);
let proj = move |p: Vec2| a + dir * dir.dot(p - a);
cs = cs.iter().map(|c| clip_half(c, &dist, &proj)).collect();
}
let mut out = Path::new();
for c in cs {
// A contour left lying along the polygon's edges encloses nothing.
if c.segs.iter().all(|s| matches!(s, Seg::Line(_))) {
let mut pts = vec![c.start];
pts.extend(c.segs.iter().map(Seg::end));
let m = pts.len();
let area: f32 = (0..m).map(|i| pts[i].cross(pts[(i + 1) % m])).sum::<f32>() * 0.5;
let r = pts.iter().fold(crate::Rect::EMPTY, |mut r, p| {
r.include(*p);
r
});
if area.abs() <= 1e-6 * (r.width() * r.height()).max(1e-12) {
continue;
}
}
out.cmds.push(PathCmd::MoveTo(c.start));
for seg in c.segs {
out.cmds.push(match seg {
Seg::Line(p) => PathCmd::LineTo(p),
Seg::Quad(a, p) => PathCmd::QuadTo(a, p),
Seg::Cubic(a, b, p) => PathCmd::CubicTo(a, b, p),
});
}
out.cmds.push(PathCmd::Close);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Affine, FillRule};
fn square(x: f32, y: f32, w: f32) -> Vec<Vec2> {
vec![Vec2::new(x, y), Vec2::new(x + w, y), Vec2::new(x + w, y + w), Vec2::new(x, y + w)]
}
/// Area by sampling a fine grid of points (winding rule `rule`).
fn area(p: &Path, rule: FillRule) -> f32 {
let b = p.bounds();
let step = 0.25;
let mut n = 0u32;
let mut y = b.min.y + step * 0.5;
while y < b.max.y {
let mut x = b.min.x + step * 0.5;
while x < b.max.x {
if p.contains(Vec2::new(x, y), &Affine::IDENTITY, rule) {
n += 1;
}
x += step;
}
y += step;
}
n as f32 * step * step
}
#[test]
fn convex_polygons_are_recognised() {
assert_eq!(convex_polygon(&Path::rect(0.0, 0.0, 10.0, 5.0)).map(|p| p.len()), Some(4));
let mut tri = Path::new();
tri.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(5.0, 0.0)).line_to(Vec2::new(10.0, 0.0)).line_to(Vec2::new(0.0, 10.0));
assert_eq!(convex_polygon(&tri).map(|p| p.len()), Some(3), "an open polygon closes; a straight-through corner goes");
let mut bow = Path::new();
bow.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(10.0, 10.0)).line_to(Vec2::new(10.0, 0.0)).line_to(Vec2::new(0.0, 10.0)).close();
assert!(convex_polygon(&bow).is_none(), "self-crossing");
assert!(convex_polygon(&Path::star(0.0, 0.0, 10.0, 4.0, 5)).is_none(), "concave");
assert!(convex_polygon(&Path::ellipse(0.0, 0.0, 5.0, 5.0)).is_none(), "curved");
let mut two = Path::rect(0.0, 0.0, 1.0, 1.0);
two.cmds.extend(Path::rect(5.0, 5.0, 1.0, 1.0).cmds);
assert!(convex_polygon(&two).is_none(), "two subpaths");
assert!(convex_polygon(&Path::line(Vec2::ZERO, Vec2::new(1.0, 1.0))).is_none());
}
#[test]
fn rectangles_clip_to_their_overlap() {
let r = clip_convex(&Path::rect(0.0, 0.0, 10.0, 10.0), &square(5.0, 5.0, 10.0));
assert_eq!(r.bounds(), crate::Rect::new(5.0, 5.0, 10.0, 10.0));
assert!((area(&r, FillRule::NonZero) - 25.0).abs() < 0.01);
assert!(clip_convex(&Path::rect(0.0, 0.0, 1.0, 1.0), &square(5.0, 5.0, 1.0)).is_empty(), "no overlap, no contour");
// A shape around the whole polygon becomes the polygon.
let all = clip_convex(&Path::rect(-50.0, -50.0, 100.0, 100.0), &square(0.0, 0.0, 4.0));
assert!((area(&all, FillRule::NonZero) - 16.0).abs() < 0.01, "{all:?}");
assert!(clip_convex(&Path::rect(0.0, 0.0, 1.0, 1.0), &[Vec2::ZERO, Vec2::new(1.0, 1.0)]).is_empty());
}
#[test]
fn curves_stay_curves_and_areas_are_exact() {
// A circle of radius 10 cut by the half-plane x ≥ 0 (a big square): half the disc.
let circle = Path::ellipse(0.0, 0.0, 10.0, 10.0);
let half = clip_convex(&circle, &square(0.0, -20.0, 40.0));
assert!(half.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..))), "the arc is still a curve");
let full = area(&circle, FillRule::NonZero);
assert!((area(&half, FillRule::NonZero) - full / 2.0).abs() < 1.0, "{} vs {}", area(&half, FillRule::NonZero), full / 2.0);
// Every point of the result's curves lies inside the polygon.
let b = half.bounds();
assert!(b.min.x >= -1e-4 && b.max.x <= 10.0 + 1e-3, "{b:?}");
// A quarter: the circle inside a square at its centre.
let q = clip_convex(&circle, &square(0.0, 0.0, 30.0));
assert!((area(&q, FillRule::NonZero) - full / 4.0).abs() < 1.0);
// A wavy cubic crossing the line three times.
let mut wave = Path::new();
wave.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(3.0, 20.0), Vec2::new(6.0, -20.0), Vec2::new(10.0, 5.0)).line_to(Vec2::new(10.0, 10.0)).line_to(Vec2::new(0.0, 10.0)).close();
let cut = clip_convex(&wave, &square(-5.0, 2.0, 20.0));
let expect = {
// Sample the original, keeping points with y ≥ 2 inside the square.
let mut n = 0u32;
let mut y = -20.0f32 + 0.125;
while y < 20.0 {
let mut x = -5.0f32 + 0.125;
while x < 15.0 {
if y >= 2.0 && x <= 15.0 && wave.contains(Vec2::new(x, y), &Affine::IDENTITY, FillRule::NonZero) {
n += 1;
}
x += 0.25;
}
y += 0.25;
}
n as f32 * 0.0625
};
assert!((area(&cut, FillRule::NonZero) - expect).abs() < 1.5, "{} vs {expect}", area(&cut, FillRule::NonZero));
}
#[test]
fn holes_and_fill_rules_survive() {
// A ring (outer square, inner square the other way round) cut in half keeps its hole.
let mut ring = Path::rect(0.0, 0.0, 20.0, 20.0);
let mut inner = Path::new();
inner.move_to(Vec2::new(5.0, 5.0)).line_to(Vec2::new(5.0, 15.0)).line_to(Vec2::new(15.0, 15.0)).line_to(Vec2::new(15.0, 5.0)).close();
ring.cmds.extend(inner.cmds);
let cut = clip_convex(&ring, &square(10.0, -10.0, 40.0));
assert!((area(&cut, FillRule::NonZero) - (200.0 - 50.0)).abs() < 0.1);
assert!(!cut.contains(Vec2::new(12.0, 10.0), &Affine::IDENTITY, FillRule::NonZero), "the hole stays a hole");
// Even-odd: the same hole drawn the same way round.
let mut eo = Path::rect(0.0, 0.0, 20.0, 20.0);
eo.cmds.extend(Path::rect(5.0, 5.0, 10.0, 10.0).cmds);
let cut = clip_convex(&eo, &square(10.0, -10.0, 40.0));
assert!((area(&cut, FillRule::EvenOdd) - 150.0).abs() < 0.1);
// A rotated (diamond) polygon, and a path that never closes itself.
let diamond = [Vec2::new(10.0, 0.0), Vec2::new(20.0, 10.0), Vec2::new(10.0, 20.0), Vec2::new(0.0, 10.0)];
let mut open = Path::new();
open.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(20.0, 0.0)).line_to(Vec2::new(20.0, 20.0)).line_to(Vec2::new(0.0, 20.0));
let cut = clip_convex(&open, &diamond);
let pts: Vec<Vec2> = cut.cmds.iter().filter_map(|c| if let PathCmd::MoveTo(p) | PathCmd::LineTo(p) = c { Some(*p) } else { None }).collect();
let shoelace: f32 = (0..pts.len()).map(|i| pts[i].cross(pts[(i + 1) % pts.len()])).sum::<f32>() * 0.5;
assert!((shoelace.abs() - 200.0).abs() < 1e-3, "{shoelace}: {cut:?}");
}
}
+1
View File
@@ -5,6 +5,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod affine;
pub mod clip;
pub mod edit;
pub mod morph;
mod fit;
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "anicraft-gpu"
description = "AniCraft L3: wgpu stage renderer (tile-binned analytic coverage), checked against the CPU oracle"
version.workspace = true
edition.workspace = true
license.workspace = true
publish.workspace = true
repository.workspace = true
[dependencies]
anicraft-geom.workspace = true
anicraft-doc.workspace = true
anicraft-render.workspace = true
# The same wgpu the shell's egui-wgpu already builds (one wgpu in the tree, ADR 0019).
wgpu.workspace = true
# Blocks on wgpu's adapter/device futures (already in the tree through eframe).
pollster.workspace = true
# Plain-old-data views of the upload buffers (already in the tree through wgpu and egui).
bytemuck.workspace = true
rayon.workspace = true
thiserror.workspace = true
[lints]
workspace = true
+82
View File
@@ -0,0 +1,82 @@
//! GPU stage timings and parity against the CPU oracle (ADR 0019; 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
//! ```
//! Prints the adapter, then for each scene and size: CPU ms, GPU ms (prepare + bin + GPU),
//! the work the fine pass did, and how far the two pictures are apart.
use anicraft_doc::{Document, evaluate, sample};
use anicraft_gpu::{GpuRenderer, Output, compare_premul8};
use anicraft_render::{View, render};
use std::time::Instant;
fn arg(name: &str, default: u32) -> u32 {
let args: Vec<String> = std::env::args().collect();
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).and_then(|v| v.parse().ok()).unwrap_or(default)
}
fn main() {
let gpu = match GpuRenderer::new() {
Ok(g) => g,
Err(e) => {
println!("no GPU: {e}");
return;
}
};
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)),
("sample".into(), sample::demo()),
];
println!("{:<18} {:>10} {:>9} {:>9} {:>30} {:>9} {:>9} parity (mean / max / differing px)", "scene", "size", "CPU ms", "GPU ms", "prepare + bin + gpu", "entries", "pieces");
for (name, doc) in &scenes {
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 _ = render(&dl0, &v);
let lists: Vec<_> = (0..runs).map(|i| evaluate(doc, (i * 20) % frames)).collect();
let t = Instant::now();
for dl in &lists {
let _ = render(dl, &v);
}
let cpu_ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
let mut sum = [0.0f32; 3];
let mut work = (0, 0);
let t = Instant::now();
for dl in &lists {
if let Ok(f) = gpu.render(dl, &v, Output::Premul8) {
sum[0] += f.timings.prepare;
sum[1] += f.timings.bin;
sum[2] += f.timings.gpu;
work = (f.entries, f.pieces);
}
}
let gpu_ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
let n = runs as f32;
let parity = match (gpu.render(&dl0, &v, Output::Premul8), render(&dl0, &v)) {
(Ok(g), Ok((c, _))) => compare_premul8(&g.premul8, &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!(
"{:<18} {:>10} {:>9.2} {:>9.2} {:>30} {:>9} {:>9} {parity}",
name,
format!("{}×{}", v.width, v.height),
cpu_ms,
gpu_ms,
format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n),
work.0,
work.1
);
}
}
}
+469
View File
@@ -0,0 +1,469 @@
//! Tile binning: the CPU half of the GPU stage (ADR 0019).
//!
//! 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.
//!
//! 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.
use anicraft_geom::{FillRule, Vec2};
use anicraft_render::Fill;
use anicraft_render::paint::Shader;
use rayon::prelude::*;
/// A `vec4<f32>` as the shader sees it.
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.
pub const NONE: u32 = u32::MAX;
/// `vec4`s of paint data per fill.
pub const PAINT_VEC4S: usize = 4;
/// Gradient table entries (the oracle's LUT size).
pub const RAMP: usize = 256;
/// Paint kinds in an op header.
const SOLID: u32 = 0;
const LINEAR: u32 = 1;
const RADIAL: u32 = 2;
/// 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`]);
/// then each op's header `[kind, fill rule, ramp start in paints, 0]`.
/// * `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.
/// * `paints` (`vec4<f32>`): per op its colour, then the inverse paint transform and gradient
/// parameters; then the gradient tables (256 premultiplied colours each).
pub struct Binned {
pub tiles_x: u32,
pub tiles_y: u32,
pub index: Vec<u32>,
pub entries_at: u32,
pub ops_at: u32,
pub geo: Vec<[f32; 4]>,
pub paints: Vec<[f32; 4]>,
pub entries: usize,
pub pieces: usize,
}
/// 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.
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
/// the fill's first one, or −1 for the part left of the fill's tiles (backdrop only).
#[derive(Clone, Copy)]
struct Piece {
row: u32,
col: i32,
seg: [f32; 4],
}
/// Fills binned per parallel task.
const CHUNK: usize = 16;
/// Bins `fills` for a `width × height` surface.
pub fn bin(fills: &[Fill], width: u32, height: u32) -> Binned {
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 fills: 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>)> = fills
.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`, and each tile row's entries.
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();
}
let mut row_at = vec![0usize; ty + 1];
for r in 0..ty {
let n: usize = locals.iter().map(|(_, rows)| (rows[r + 1] - rows[r]) as usize).sum();
row_at[r + 1] = row_at[r] + n;
}
let total = row_at[ty];
let entries_at = 2 * tx * ty;
let ops_at = entries_at + 4 * total;
let mut index = vec![0u32; ops_at + 4 * fills.len()];
// Phase 2, parallel over tile rows: each row owns its tiles' headers and its entries.
{
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).enumerate().for_each(|(r, (head, out))| {
let first_tile = (r * tx) as u32;
let mut count = vec![0u32; tx];
let slices = || locals.iter().enumerate().map(|(c, (l, rows))| (c, l.entries.get(rows[r] as usize..rows[r + 1] as usize).unwrap_or(&[])));
for (_, es) in slices() {
for e in es {
if let Some(n) = count.get_mut((e[1] - first_tile) as usize) {
*n += 1;
}
}
}
let mut cursor = vec![0u32; tx];
let mut run = 0u32;
for (t, &n) in count.iter().enumerate() {
if let Some(h) = head.get_mut(2 * t..2 * t + 2) {
h.copy_from_slice(&[row_at[r] as u32 + run, n]);
}
cursor[t] = run;
run += n;
}
for (c, es) in slices() {
for &[op, tile, s0, n, bd] in es {
let Some(cur) = cursor.get_mut((tile - first_tile) as usize) else { continue };
let at = 4 * *cur as usize;
*cur += 1;
let bd = if bd == NONE { NONE } else { bd_at[c] + bd };
if let Some(slot) = out.get_mut(at..at + 4) {
slot.copy_from_slice(&[op, piece_at[c] + s0, n, bd]);
}
}
}
});
}
// 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.
rayon::spawn(move || drop(locals));
// Paints: a fixed record per op, then the gradient tables.
let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * fills.len());
let mut ramps: Vec<[f32; 4]> = Vec::new();
let ramps_at = (PAINT_VEC4S * fills.len()) as u32;
for (op, f) in fills.iter().enumerate() {
let rule = match f.rule {
FillRule::NonZero => 0,
FillRule::EvenOdd => 1,
};
let ramp = ramps_at + ramps.len() as u32;
let (kind, rec) = match &f.shader {
Shader::Solid(c) => (SOLID, [*c, [0.0; 4], [0.0; 4], [0.0; 4]]),
Shader::Linear { inv, start, dir, lut } => {
ramps.extend_from_slice(&lut[..]);
let m = inv.m;
(LINEAR, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], start.x, start.y], [dir.x, dir.y, 0.0, 0.0]])
}
Shader::Radial { inv, center, inv_radius, lut } => {
ramps.extend_from_slice(&lut[..]);
let m = inv.m;
(RADIAL, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]])
}
// `plain_fills` never hands these over; draw nothing rather than guess.
Shader::Bitmap { .. } | Shader::Image { .. } => (SOLID, [[0.0; 4]; 4]),
};
paints.extend_from_slice(&rec);
let at = ops_at + 4 * op;
if let Some(slot) = index.get_mut(at..at + 4) {
slot.copy_from_slice(&[kind, rule, ramp, 0]);
}
}
paints.extend_from_slice(&ramps);
Binned { tiles_x, tiles_y, index, entries_at: entries_at as u32, ops_at: ops_at as u32, geo, paints, entries: total, pieces }
}
/// 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 };
pieces.clear();
for poly in &f.polys {
let n = poly.len();
if n < 2 {
continue;
}
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);
}
}
if pieces.is_empty() {
return;
}
// Unstable (no allocation) yet deterministic: the order within a tile only affects rounding.
pieces.sort_unstable_by_key(|p| (p.row, p.col));
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.
while let Some(p) = pieces.get(i).filter(|p| p.row == row && p.col < 0) {
add_rows(&mut wind, &p.seg, row_y0);
i += 1;
}
let mut last_bd: Option<(u32, [f32; 16])> = None;
for col in 0..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 {
// 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 (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]);
}
// 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) {
i += 1;
}
}
}
/// 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;
}
}
}
/// 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>) {
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 y0 = p.y.max(r.ylo);
let y1 = q.y.min(r.yhi);
if y1 <= y0 {
return;
}
let dxdy = (q.x - p.x) / (q.y - p.y);
let x_at = |y: f32| p.x + (y - p.y) * dxdy;
let first = ((y0 - r.ylo) / T).floor().max(0.0) as u32;
let last = ((y1 - r.ylo) / T).ceil().max(0.0) as u32;
for row in first..last {
let ry0 = r.ylo + (row * TILE) as f32;
let ys = y0.max(ry0);
let ye = y1.min(ry0 + T);
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);
}
}
/// 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>) {
let mut push = |col: i32, u: Vec2, v: Vec2| {
if 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 });
};
// Points where the piece crosses a column boundary (or the range's edges), top to bottom.
let dx = e.x - s.x;
let at_x = |x: f32| -> Vec2 {
let t = ((x - s.x) / dx).clamp(0.0, 1.0);
Vec2::new(x, s.y + (e.y - s.y) * t)
};
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 {
push(-1, s, e);
return;
}
if lo >= r.xhi {
return; // wholly right of the fill's tiles: it covers none of their pixels
}
// Most pieces (flattened curves are short) lie inside one tile column.
let cl = col_of(lo);
if dx == 0.0 || (lo >= r.xlo && hi < r.xhi && cl == col_of(hi)) {
push(cl.clamp(0, r.ncols - 1), s, e);
return;
}
// Column boundaries strictly inside (lo, hi) (the range's left and right edges included),
// visited in the piece's direction of travel.
let kmin = (((lo - r.xlo) / T).floor() as i32 + 1).max(0);
let kmax = (((hi - r.xlo) / T).ceil() as i32 - 1).min(r.ncols);
let count = (kmax - kmin + 1).max(0);
let mut prev = s;
for j in 0..=count {
let next = if j == count {
e
} else {
let k = if dx > 0.0 { kmin + j } else { kmax - j };
let x = r.xlo + k as f32 * T;
if !(x > lo && x < hi) {
continue;
}
at_x(x)
};
let mid = 0.5 * (prev.x + next.x);
if mid < r.xlo {
push(-1, prev, next);
} else if mid < r.xhi {
push(col_of(mid).clamp(0, r.ncols - 1), prev, next);
}
prev = next;
}
}
/// 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)]
pub(crate) fn piece_cover(s: [f32; 4], px: f32, py: f32) -> f32 {
let (ylo, yhi) = (s[1].min(s[3]), s[1].max(s[3]));
let (ya, yb) = (ylo.max(py), yhi.min(py + 1.0));
if yb <= ya {
return 0.0;
}
let dxdy = (s[2] - s[0]) / (s[3] - s[1]);
let xa = s[0] + (ya - s[1]) * dxdy;
let xb = s[0] + (yb - s[1]) * dxdy;
let dir = if s[3] > s[1] { 1.0 } else { -1.0 };
dir * (yb - ya) * avg_clamp(px + 1.0 - xa, px + 1.0 - xb)
}
/// Mean of `clamp(u, 0, 1)` for `u` running linearly from `u0` to `u1` (no cancellation when
/// the two are close).
#[cfg(test)]
fn avg_clamp(u0: f32, u1: f32) -> f32 {
let (lo, hi) = (u0.min(u1), u0.max(u1));
if hi <= 0.0 {
return 0.0;
}
if lo >= 1.0 {
return 1.0;
}
let w = hi - lo;
if w < 1e-7 {
return lo.clamp(0.0, 1.0);
}
let (a, b) = (lo.max(0.0), hi.min(1.0));
((b - a) * (b + a) * 0.5 + (hi - 1.0).max(0.0)) / w
}
/// The colour a premultiplied record holds (tests).
#[cfg(test)]
pub(crate) fn solid_of(b: &Binned, op: usize) -> anicraft_render::paint::Premul {
b.paints.get(PAINT_VEC4S * op).copied().unwrap_or([0.0; 4])
}
+141
View File
@@ -0,0 +1,141 @@
// AniCraft GPU stage: fine rasterization (ADR 0019).
//
// 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.
struct Params {
// width, height, tiles across, output format (0: premultiplied RGBA8, 1: f32 RGBA)
size: vec4<u32>,
// where entries and op headers start in `index`
at: vec4<u32>,
// premultiplied background (zero when transparent)
bg: vec4<f32>,
}
@group(0) @binding(0) var<uniform> params: Params;
@group(0) @binding(1) var<storage, read> index: array<u32>;
@group(0) @binding(2) var<storage, read> geo: array<vec4<f32>>;
@group(0) @binding(3) var<storage, read> paints: array<vec4<f32>>;
@group(0) @binding(4) var<storage, read_write> out: array<u32>;
const NONE: u32 = 0xffffffffu;
const PAINT_VEC4S: u32 = 4u;
// Mean of clamp(u, 0, 1) for u running linearly from u0 to u1.
fn avg_clamp(u0: f32, u1: f32) -> f32 {
let lo = min(u0, u1);
let hi = max(u0, u1);
if hi <= 0.0 {
return 0.0;
}
if lo >= 1.0 {
return 1.0;
}
let w = hi - lo;
if w < 1e-7 {
return clamp(lo, 0.0, 1.0);
}
let a = max(lo, 0.0);
let b = min(hi, 1.0);
return ((b - a) * (b + a) * 0.5 + max(hi - 1.0, 0.0)) / w;
}
// Signed area of pixel (px, py) to the right of piece s = (x0, y0, x1, y1), tile-relative.
fn piece_cover(s: vec4<f32>, px: f32, py: f32) -> f32 {
let ylo = min(s.y, s.w);
let yhi = max(s.y, s.w);
let ya = max(ylo, py);
let yb = min(yhi, py + 1.0);
if yb <= ya {
return 0.0;
}
let dxdy = (s.z - s.x) / (s.w - s.y);
let xa = s.x + (ya - s.y) * dxdy;
let xb = s.x + (yb - s.y) * dxdy;
let dir = select(-1.0, 1.0, s.w > s.y);
return dir * (yb - ya) * avg_clamp(px + 1.0 - xa, px + 1.0 - xb);
}
fn fold(w: f32, rule: u32) -> f32 {
if rule == 0u {
return min(abs(w), 1.0);
}
let t = abs(w) % 2.0;
return select(t, 2.0 - t, t > 1.0);
}
fn shade(op: u32, kind: u32, ramp: u32, p: vec2<f32>) -> vec4<f32> {
let base = op * PAINT_VEC4S;
if kind == 0u {
return paints[base];
}
let m = paints[base + 1u];
let n = paints[base + 2u];
let g = paints[base + 3u];
// Pixel back to paint space: x' = a x + c y + e, y' = b x + d y + f.
let q = vec2<f32>(m.x * p.x + m.z * p.y + n.x, m.y * p.x + m.w * p.y + n.y);
var t: f32;
if kind == 1u {
t = dot(q - n.zw, g.xy);
} else {
t = length(q - n.zw) * g.z;
}
t = clamp(t, 0.0, 1.0);
let i = u32(t * 255.0 + 0.5) & 255u;
return paints[ramp + i];
}
@compute @workgroup_size(16, 16)
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
let width = params.size.x;
let height = params.size.y;
let tile = wg.y * params.size.z + wg.x;
let x = wg.x * 16u + lid.x;
let y = wg.y * 16u + lid.y;
let px = f32(lid.x);
let py = f32(lid.y);
let centre = vec2<f32>(f32(x) + 0.5, f32(y) + 0.5);
var c = params.bg;
let start = index[tile * 2u];
let count = index[tile * 2u + 1u];
for (var i = 0u; i < count; i++) {
let e = params.at.x + (start + i) * 4u;
let op = index[e];
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;
let cov = fold(w, index[h + 1u]);
if cov <= 1e-4 {
continue;
}
let s = shade(op, index[h], index[h + 2u], centre);
c = s * cov + c * (1.0 - s.a * cov);
}
if x >= width || y >= height {
return;
}
let at = y * width + x;
if params.size.w == 0u {
let q = vec4<u32>(clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)) * 255.0 + 0.5);
out[at] = q.x | (q.y << 8u) | (q.z << 16u) | (q.w << 24u);
} else {
out[at * 4u] = bitcast<u32>(c.x);
out[at * 4u + 1u] = bitcast<u32>(c.y);
out[at * 4u + 2u] = bitcast<u32>(c.z);
out[at * 4u + 3u] = bitcast<u32>(c.w);
}
}
+365
View File
@@ -0,0 +1,365 @@
//! AniCraft GPU stage renderer (layer L3, beside the engine; ADR 0019).
//!
//! Draws the same fills as the CPU oracle (`anicraft-render`) with wgpu compute: the oracle
//! prepares the fills ([`anicraft_render::plain_fills`]: flattening, strokes, paints and their
//! gradient tables), [`binning`] sorts their 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.
//! The output is the oracle's within float rounding (the parity tests check mean and maximum
//! error against it).
//!
//! What the plain path doesn't cover yet (masks, group opacity, blend modes, filters,
//! bitmaps) is reported as [`GpuError::NeedsFull`], and the caller renders that frame on the
//! CPU. The renderer owns a headless device, so it works without a window, in tests and on
//! machines where the window itself runs on OpenGL.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod binning;
use anicraft_doc::DisplayList;
use anicraft_render::{MAX_PIXELS, NeedsFull, Pixmap, RenderStats, View, paint::premultiply, plain_fills};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Instant;
use wgpu::util::DeviceExt;
#[derive(Debug, thiserror::Error)]
pub enum GpuError {
/// No adapter, no compute shaders, or the device could not be created.
#[error("no usable GPU: {0}")]
Unavailable(String),
/// This frame uses something the GPU path doesn't draw yet; render it on the CPU.
#[error("this frame needs the CPU renderer ({0})")]
NeedsFull(NeedsFull),
#[error("{0}")]
TooLarge(String),
/// Validation, out-of-memory, mapping or a lost device.
#[error("GPU error: {0}")]
Device(String),
}
/// What the renderer reads back.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Output {
/// Premultiplied RGBA8, rounded like [`Pixmap::to_premul_rgba8`] (what the stage uploads).
Premul8,
/// Premultiplied f32 RGBA, like the oracle's [`Pixmap`] (exports and parity tests).
Float,
}
/// A rendered frame.
pub struct GpuFrame {
pub width: u32,
pub height: u32,
/// Premultiplied RGBA8 ([`Output::Premul8`]).
pub premul8: Vec<u8>,
/// Premultiplied f32 pixels ([`Output::Float`]).
pub pixmap: Option<Pixmap>,
pub stats: RenderStats,
pub timings: Timings,
/// Tile entries and edge pieces the fine pass walked.
pub entries: usize,
pub pieces: usize,
}
/// Where a frame's time went (milliseconds).
#[derive(Clone, Copy, Debug, Default)]
pub struct Timings {
/// Cull, flatten, stroke and paint set-up (shared with the oracle, parallel).
pub prepare: f32,
/// Tile binning (parallel per fill) and buffer packing.
pub bin: f32,
/// Upload, compute pass, readback.
pub gpu: f32,
}
impl Timings {
pub fn total(&self) -> f32 {
self.prepare + self.bin + self.gpu
}
}
/// The renderer: a headless device and the fine pipeline.
pub struct GpuRenderer {
device: wgpu::Device,
queue: wgpu::Queue,
pipeline: wgpu::ComputePipeline,
layout: wgpu::BindGroupLayout,
limits: wgpu::Limits,
/// Adapter name and backend, for the status bar and reports.
pub adapter: String,
/// First error the device reported outside our error scopes (or its loss). Once set, the
/// renderer refuses to draw and callers fall back to the CPU.
broken: Arc<Mutex<Option<String>>>,
}
impl GpuRenderer {
/// Opens a headless device on the best adapter (high-performance first), builds the
/// pipeline and checks it with a small known render. `Err` means "use the CPU".
pub fn new() -> Result<GpuRenderer, GpuError> {
// A renderer bug must never take the caller down: wgpu reports misuse by panicking.
std::panic::catch_unwind(Self::open).unwrap_or_else(|_| Err(GpuError::Unavailable("the GPU driver failed while starting".into())))
}
fn open() -> Result<GpuRenderer, GpuError> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }))
.map_err(|e| GpuError::Unavailable(e.to_string()))?;
let info = adapter.get_info();
let name = format!("{} ({:?})", info.name, info.backend);
if !adapter.get_downlevel_capabilities().flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) {
return Err(GpuError::Unavailable(format!("{name} has no compute shaders")));
}
let have = adapter.limits();
let want = wgpu::Limits {
max_storage_buffer_binding_size: have.max_storage_buffer_binding_size,
max_buffer_size: have.max_buffer_size,
..wgpu::Limits::downlevel_defaults()
};
if have.max_storage_buffers_per_shader_stage < 4 || have.max_compute_invocations_per_workgroup < 256 || have.max_compute_workgroup_size_x < 16 || have.max_compute_workgroup_size_y < 16 {
return Err(GpuError::Unavailable(format!("{name} is below the compute limits the stage needs")));
}
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("anicraft-gpu"), required_limits: want.clone(), ..Default::default() }))
.map_err(|e| GpuError::Unavailable(format!("{name}: {e}")))?;
let broken: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
{
let b = broken.clone();
device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| {
let mut g = b.lock().unwrap_or_else(PoisonError::into_inner);
g.get_or_insert_with(|| e.to_string());
}));
let b = broken.clone();
device.set_device_lost_callback(move |_, msg| {
let mut g = b.lock().unwrap_or_else(PoisonError::into_inner);
g.get_or_insert_with(|| format!("device lost: {msg}"));
});
}
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("anicraft-fine"), source: wgpu::ShaderSource::Wgsl(include_str!("fine.wgsl").into()) });
let storage = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None },
count: None,
};
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("anicraft-fine"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
count: None,
},
storage(1, true),
storage(2, true),
storage(3, true),
storage(4, false),
],
});
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("anicraft-fine"), bind_group_layouts: &[Some(&layout)], immediate_size: 0 });
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("anicraft-fine"),
layout: Some(&pl),
module: &module,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
if let Some(e) = pollster::block_on(scope.pop()) {
return Err(GpuError::Unavailable(format!("{name}: the stage shader did not build: {e}")));
}
let r = GpuRenderer { device, queue, pipeline, layout, limits: want, adapter: name, broken };
r.self_test()?;
Ok(r)
}
/// A 24 × 20 render of two known rectangles must come back exactly: catches drivers that
/// build the pipeline but compute garbage.
fn self_test(&self) -> Result<(), GpuError> {
use anicraft_doc::{ColorEffect, DisplayItem, ElementId, LayerId, Paint, Rgba};
use anicraft_geom::{Affine, FillRule, Path};
let item = |x: f32, c: Rgba| DisplayItem {
path: Arc::new(Path::rect(x, 2.0, 8.0, 16.0)),
transform: Affine::IDENTITY,
fill: Some(Paint::Solid(c)),
stroke: None,
fill_rule: FillRule::NonZero,
color: ColorEffect::default(),
layer: LayerId(0),
element: ElementId(0),
outline: None,
clip: None,
masks: None,
guide: false,
group: None,
image: None,
};
let dl = DisplayList { items: vec![item(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), item(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5))], ..Default::default() };
let view = View { transform: Affine::IDENTITY, width: 24, height: 20, background: Some(Rgba::WHITE) };
let f = self.render(&dl, &view, Output::Premul8)?;
let px = |x: usize, y: usize| f.premul8.get((y * 24 + x) * 4..(y * 24 + x) * 4 + 4).map(<[u8]>::to_vec);
let ok = px(5, 10) == Some(vec![255, 0, 0, 255]) && px(18, 10) == Some(vec![128, 128, 255, 255]) && px(12, 1) == Some(vec![255; 4]);
if !ok {
return Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong", self.adapter)));
}
Ok(())
}
/// Whether the device has failed (lost, or an error outside a render); then use the CPU.
pub fn broken(&self) -> Option<String> {
self.broken.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Renders a display list. [`GpuError::NeedsFull`] means "draw this one on the CPU".
pub fn render(&self, dl: &DisplayList, view: &View, output: Output) -> Result<GpuFrame, GpuError> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.render_inner(dl, view, output))).unwrap_or_else(|_| Err(GpuError::Device("the GPU renderer failed on this frame".into())))
}
fn render_inner(&self, dl: &DisplayList, view: &View, output: Output) -> Result<GpuFrame, GpuError> {
if let Some(e) = self.broken() {
return Err(GpuError::Device(e));
}
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 (fills, stats) = plain_fills(dl, view).map_err(GpuError::NeedsFull)?;
let t1 = Instant::now();
let b = binning::bin(&fills, w, h);
// Free the prepared polygons on the pool, off this frame's path (as the oracle does).
rayon::spawn(move || drop(fills));
let t2 = Instant::now();
let (premul8, pixmap) = self.run(&b, view, output)?;
let t3 = Instant::now();
let ms = |a: Instant, b: Instant| (b - a).as_secs_f32() * 1000.0;
Ok(GpuFrame { width: w, height: h, premul8, pixmap, stats, timings: Timings { prepare: ms(t0, t1), bin: ms(t1, t2), gpu: ms(t2, t3) }, entries: b.entries, pieces: b.pieces })
}
fn run(&self, b: &binning::Binned, view: &View, output: Output) -> Result<(Vec<u8>, Option<Pixmap>), GpuError> {
let (w, h) = (view.width, view.height);
let px = u64::from(w) * u64::from(h);
let out_bytes = px * if output == Output::Float { 16 } else { 4 };
let index: &[u8] = bytemuck::cast_slice(&b.index);
let geo: &[u8] = bytemuck::cast_slice(&b.geo);
let paints: &[u8] = bytemuck::cast_slice(&b.paints);
let cap = self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size);
for (what, n) in [("tile lists", index.len() as u64), ("edges", geo.len() as u64), ("paints", paints.len() as u64), ("the image", out_bytes)] {
if n > cap {
return Err(GpuError::TooLarge(format!("{what} need {} MB, more than this GPU binds ({} MB)", n >> 20, cap >> 20)));
}
}
let bg = view.background.map_or([0.0; 4], premultiply);
let mut uniform = [0u32; 12];
uniform[..4].copy_from_slice(&[w, h, b.tiles_x, u32::from(output == Output::Float)]);
uniform[4..6].copy_from_slice(&[b.entries_at, b.ops_at]);
for (u, f) in uniform[8..].iter_mut().zip(bg) {
*u = f.to_bits();
}
let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
let valid = self.device.push_error_scope(wgpu::ErrorFilter::Validation);
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", index);
let gbuf = storage("geo", geo);
let pbuf = storage("paints", paints);
let obuf = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("out"), size: out_bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: out_bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("anicraft-fine"),
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: ibuf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 2, resource: gbuf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 3, resource: pbuf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 4, resource: obuf.as_entire_binding() },
],
});
let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-fine") });
{
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("anicraft-fine"), timestamp_writes: None });
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &bind, &[]);
pass.dispatch_workgroups(b.tiles_x, b.tiles_y, 1);
}
enc.copy_buffer_to_buffer(&obuf, 0, &read, 0, out_bytes);
self.queue.submit([enc.finish()]);
let (tx, rx) = std::sync::mpsc::channel();
read.slice(..).map_async(wgpu::MapMode::Read, move |r| {
let _ = tx.send(r);
});
let polled = self.device.poll(wgpu::PollType::wait_indefinitely());
let invalid = pollster::block_on(valid.pop());
let no_memory = pollster::block_on(oom.pop());
if let Some(e) = invalid.or(no_memory) {
return Err(GpuError::Device(e.to_string()));
}
polled.map_err(|e| GpuError::Device(e.to_string()))?;
match rx.recv() {
Ok(Ok(())) => {}
Ok(Err(e)) => return Err(GpuError::Device(e.to_string())),
Err(_) => return Err(GpuError::Device("the readback never completed".into())),
}
let result = {
let view = read.slice(..).get_mapped_range().map_err(|e| GpuError::Device(e.to_string()))?;
let bytes: &[u8] = &view;
match output {
Output::Premul8 => (bytes.to_vec(), None),
Output::Float => {
let mut pm = Pixmap::new(w, h).map_err(|e| GpuError::TooLarge(e.to_string()))?;
for (p, q) in pm.data.iter_mut().zip(bytes.as_chunks::<16>().0) {
for (c, v) in p.iter_mut().zip(q.as_chunks::<4>().0) {
*c = f32::from_le_bytes(*v);
}
}
(Vec::new(), Some(pm))
}
}
};
read.unmap();
Ok(result)
}
}
/// Mean and maximum per-channel difference of two premultiplied RGBA8 images, in 1/255 steps,
/// and how many pixels differ at all. `None` when the sizes differ.
pub fn compare_premul8(a: &[u8], b: &[u8]) -> Option<Diff> {
if a.len() != b.len() || !a.len().is_multiple_of(4) {
return None;
}
let mut sum = 0u64;
let mut max = 0u8;
let mut differing = 0usize;
for (p, q) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) {
let mut any = false;
for (x, y) in p.iter().zip(q) {
let d = x.abs_diff(*y);
sum += u64::from(d);
max = max.max(d);
any |= d > 0;
}
differing += usize::from(any);
}
let channels = a.len().max(1) as f64;
Some(Diff { mean: sum as f64 / channels, max, differing, pixels: a.len() / 4 })
}
/// How far two images are apart (see [`compare_premul8`]).
#[derive(Clone, Copy, Debug)]
pub struct Diff {
/// Mean absolute difference per channel, in 1/255 steps.
pub mean: f64,
/// Largest difference in any channel, in 1/255 steps.
pub max: u8,
pub differing: usize,
pub pixels: usize,
}
#[cfg(test)]
mod tests;
+306
View File
@@ -0,0 +1,306 @@
//! Parity with the CPU oracle.
//!
//! Two layers: the binning is checked everywhere by running the fine shader's arithmetic on the
//! CPU over the binned scene (no GPU needed), and the real GPU path is checked against the
//! oracle on the sample scene and analytic scenes when an adapter exists. Without one those
//! tests print why and pass, so CI machines without a GPU stay green.
use super::*;
use crate::binning::{Binned, PAINT_VEC4S, TILE, piece_cover, solid_of};
use anicraft_doc::{ColorEffect, DisplayItem, ElementId, GradientStop, LayerId, Paint, Rgba, Stroke, sample};
use anicraft_geom::{Affine, FillRule, Path, Vec2};
use anicraft_render::{paint::Premul, render};
use std::sync::OnceLock;
/// Mean-error target from the roadmap (M3): 1/255 per channel.
const MEAN_TARGET: f64 = 1.0;
fn item(path: Path, fill: Paint) -> DisplayItem {
DisplayItem {
path: Arc::new(path),
transform: Affine::IDENTITY,
fill: Some(fill),
stroke: None,
fill_rule: FillRule::NonZero,
color: ColorEffect::default(),
layer: LayerId(0),
element: ElementId(0),
outline: None,
clip: None,
masks: None,
guide: false,
group: None,
image: None,
}
}
fn list(items: Vec<DisplayItem>) -> DisplayList {
DisplayList { items, ..Default::default() }
}
fn view(w: u32, h: u32, bg: Option<Rgba>) -> View {
View { transform: Affine::IDENTITY, width: w, height: h, background: bg }
}
fn stops(colors: &[(f32, Rgba)]) -> Vec<GradientStop> {
colors.iter().map(|&(offset, color)| GradientStop { offset, color }).collect()
}
/// Analytic scenes: each stresses one part of the coverage or paint model.
fn scenes() -> Vec<(&'static str, DisplayList, View)> {
let red = Rgba::new(0.9, 0.1, 0.1, 1.0);
let blue = Rgba::new(0.1, 0.2, 0.9, 0.6);
let mut out = Vec::new();
// Fractional rectangle edges across tile boundaries and render bands.
out.push(("rects", list(vec![item(Path::rect(3.25, 20.5, 40.0, 61.75), Paint::Solid(red)), item(Path::rect(-30.0, 7.3, 64.6, 15.1), Paint::Solid(blue))]), view(96, 100, Some(Rgba::WHITE))));
// A circle (curves flattened by the oracle), on transparent.
out.push(("circle", list(vec![item(Path::ellipse(50.0, 50.0, 40.0, 40.0), Paint::Solid(Rgba::BLACK))]), view(100, 100, None)));
// Even-odd and non-zero holes from the same rings.
let mut ring = Path::rect(4.0, 4.0, 60.0, 60.0);
ring.cmds.extend(Path::rect(16.0, 16.0, 36.0, 36.0).cmds);
let mut eo = item(ring.clone(), Paint::Solid(red));
eo.fill_rule = FillRule::EvenOdd;
let mut nz = item(ring, Paint::Solid(blue));
nz.transform = Affine::translate(60.0, 10.0);
out.push(("fill rules", list(vec![eo, nz]), view(140, 80, Some(Rgba::WHITE))));
// A self-intersecting star: winding 2 in the middle.
let mut star = item(Path::star(40.0, 40.0, 36.0, 14.0, 5), Paint::Solid(Rgba::new(0.2, 0.6, 0.3, 1.0)));
star.fill_rule = FillRule::EvenOdd;
out.push(("star", list(vec![star]), view(80, 80, Some(Rgba::WHITE))));
// Gradients under rotation and scale.
let mut lin = item(Path::rect(0.0, 0.0, 100.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(100.0, 0.0), stops: stops(&[(0.0, red), (0.5, Rgba::WHITE), (1.0, blue)]) });
lin.transform = Affine::translate(70.0, 10.0).mul(&Affine::rotate(0.4)).mul(&Affine::scale(1.2, 0.8));
let rad = item(Path::ellipse(60.0, 90.0, 50.0, 30.0), Paint::Radial { center: Vec2::new(60.0, 90.0), radius: 50.0, stops: stops(&[(0.0, Rgba::WHITE), (1.0, Rgba::new(0.0, 0.0, 0.0, 0.3))]) });
out.push(("gradients", list(vec![lin, rad]), view(180, 130, Some(Rgba::new(0.9, 0.9, 0.85, 1.0)))));
// Strokes: wide, thin (sub-pixel, faded), on open and closed paths.
let mut wide = item(Path::line(Vec2::new(10.0, 20.0), Vec2::new(150.0, 70.0)), Paint::Solid(red));
wide.fill = None;
wide.stroke = Some(Stroke { color: Rgba::BLACK, width: 9.0, profile: None });
let mut thin = item(Path::ellipse(80.0, 50.0, 60.0, 30.0), Paint::Solid(Rgba::new(1.0, 0.9, 0.2, 1.0)));
thin.stroke = Some(Stroke { color: Rgba::new(0.1, 0.1, 0.4, 1.0), width: 0.4, profile: None });
out.push(("strokes", list(vec![thin, wide]), view(160, 100, Some(Rgba::WHITE))));
// Variable-width strokes (ADR 0018) come prepared by the oracle, so the GPU draws them alike.
let mut taper = item(Path::line(Vec2::new(10.0, 80.0), Vec2::new(150.0, 15.0)), Paint::Solid(red));
taper.fill = None;
taper.stroke = Some(Stroke::new(Rgba::BLACK, 12.0).with_profile(anicraft_doc::ProfilePreset::TaperBoth.profile()));
let mut bulge = item(Path::ellipse(80.0, 50.0, 55.0, 28.0), Paint::Solid(Rgba::new(0.3, 0.8, 0.5, 1.0)));
bulge.stroke = Some(Stroke::new(Rgba::new(0.1, 0.1, 0.4, 1.0), 8.0).with_profile(anicraft_doc::ProfilePreset::Bulge.profile()));
out.push(("variable-width strokes", list(vec![bulge, taper]), view(160, 100, Some(Rgba::WHITE))));
// Larger than the surface on every side; colour effects (onion-skin style tint and alpha).
let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red));
huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 };
out.push(("off-surface", list(vec![huge]), view(100, 80, Some(Rgba::WHITE))));
out
}
/// The fine shader's arithmetic, on the CPU, over a binned scene.
fn emulate(b: &Binned, v: &View) -> Vec<Premul> {
let (w, h) = (v.width as usize, v.height as usize);
let bg = v.background.map_or([0.0; 4], premultiply);
let mut out = vec![[0.0f32; 4]; w * h];
for y in 0..h {
for x in 0..w {
let tile = (y / TILE as usize) * b.tiles_x as usize + x / TILE as usize;
let (lx, ly) = (x % TILE as usize, y % TILE as usize);
let (start, count) = (b.index[2 * tile] as usize, b.index[2 * tile + 1] as usize);
let mut c = bg;
for i in 0..count {
let e = b.entries_at as usize + (start + i) * 4;
let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]);
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 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 } };
if cov <= 1e-4 {
continue;
}
let s = match b.index[hd] {
0 => solid_of(b, op),
kind => {
let base = op * PAINT_VEC4S;
let (m, nn, g) = (b.paints[base + 1], b.paints[base + 2], b.paints[base + 3]);
let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
let q = Vec2::new(m[0] * p.x + m[2] * p.y + nn[0], m[1] * p.x + m[3] * p.y + nn[1]);
let d = q - Vec2::new(nn[2], nn[3]);
let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { d.length() * g[2] };
let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255;
b.paints[b.index[hd + 2] as usize + i]
}
};
let sa = s[3] * cov;
for k in 0..4 {
c[k] = s[k] * cov + c[k] * (1.0 - sa);
}
}
out[y * w + x] = c;
}
}
out
}
fn f32_diff(a: &[Premul], b: &[Premul]) -> (f64, f32) {
let mut sum = 0.0f64;
let mut max = 0.0f32;
for (p, q) in a.iter().zip(b) {
for k in 0..4 {
let d = (p[k] - q[k]).abs();
sum += f64::from(d);
max = max.max(d);
}
}
(sum / (a.len().max(1) * 4) as f64, max)
}
#[test]
fn binned_coverage_matches_the_oracle_on_the_cpu() {
let mut all = scenes();
let doc = sample::demo();
for (f, s) in [(0u32, 0.5f32), (13, 0.37), (40, 1.0)] {
all.push(("sample", anicraft_doc::evaluate(&doc, f), View::stage(&doc, s)));
}
for (name, dl, v) in all {
let (fills, _) = plain_fills(&dl, &v).unwrap();
let b = binning::bin(&fills, v.width, v.height);
let (oracle, _) = render(&dl, &v).unwrap();
let (mean, max) = f32_diff(&emulate(&b, &v), &oracle.data);
assert!(mean < 1e-4 && max < 2e-3, "{name}: mean {mean:e}, max {max:e}");
}
}
#[test]
fn binning_shapes_the_scene_into_tiles() {
// One rectangle exactly covering tiles 1..3 × 1..2 of a 64 × 48 surface: its edges sit on
// tile boundaries, so the interior tiles carry a backdrop and no pieces.
let dl = list(vec![item(Path::rect(16.0, 16.0, 32.0, 16.0), Paint::Solid(Rgba::BLACK))]);
let v = view(64, 48, None);
let (fills, _) = plain_fills(&dl, &v).unwrap();
let b = binning::bin(&fills, 64, 48);
assert_eq!((b.tiles_x, b.tiles_y), (4, 3));
let count = |tx: usize, ty: usize| b.index[2 * (ty * 4 + tx) + 1];
assert_eq!((count(0, 1), count(1, 1), count(2, 1), count(3, 1)), (0, 1, 1, 0));
assert_eq!(count(1, 0) + count(1, 2), 0, "nothing above or below");
// Odd sizes: partial tiles at the right and bottom still bin.
let dl = list(vec![item(Path::ellipse(20.0, 10.0, 30.0, 30.0), Paint::Solid(Rgba::BLACK))]);
let v = view(37, 21, None);
let (fills, _) = plain_fills(&dl, &v).unwrap();
let b = binning::bin(&fills, 37, 21);
assert_eq!((b.tiles_x, b.tiles_y), (3, 2));
let (oracle, _) = render(&dl, &v).unwrap();
assert!(f32_diff(&emulate(&b, &v), &oracle.data).1 < 2e-3);
// Nothing to draw: an empty scene bins to empty tile lists.
let b = binning::bin(&[], 40, 40);
assert_eq!((b.entries, b.pieces), (0, 0));
assert!(b.index.iter().all(|&v| v == 0));
}
#[test]
fn degenerate_geometry_bins_without_trouble() {
// NaN and infinite points, zero-area polygons, edges far outside the surface.
let fills = vec![anicraft_render::Fill {
polys: vec![
vec![Vec2::new(f32::NAN, 0.0), Vec2::new(5.0, 5.0), Vec2::new(1.0, f32::INFINITY)],
vec![Vec2::new(3.0, 3.0), Vec2::new(3.0, 3.0), Vec2::new(3.0, 3.0)],
vec![Vec2::new(-1e9, -1e9), Vec2::new(1e9, 5.0), Vec2::new(-1e9, 1e9)],
vec![Vec2::new(1.0, 1.0)],
],
rule: FillRule::NonZero,
shader: anicraft_render::paint::Shader::Solid([1.0; 4]),
bounds: anicraft_render::raster::IRect { x0: 0, y0: 0, x1: 32, y1: 32 },
}];
let b = binning::bin(&fills, 32, 32);
assert!(b.geo.iter().flatten().all(|v| v.is_finite()));
}
// ----- the real GPU ----------------------------------------------------------------------------
/// One device for all tests; `None` (with the reason printed) when this machine has no usable
/// adapter.
fn gpu() -> Option<&'static GpuRenderer> {
static GPU: OnceLock<Option<GpuRenderer>> = OnceLock::new();
GPU.get_or_init(|| match GpuRenderer::new() {
Ok(g) => {
eprintln!("GPU parity tests on {}", g.adapter);
Some(g)
}
Err(e) => {
eprintln!("skipping GPU parity tests: {e}");
None
}
})
.as_ref()
}
#[test]
fn gpu_matches_the_oracle_on_analytic_scenes() {
let Some(g) = gpu() else { return };
for (name, dl, v) in scenes() {
let f = g.render(&dl, &v, Output::Premul8).unwrap();
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:?}");
// Float output agrees closely too.
let ff = g.render(&dl, &v, Output::Float).unwrap();
let (mean, max) = f32_diff(&ff.pixmap.unwrap().data, &oracle.data);
assert!(mean < 1e-4 && max < 4e-3, "{name} (f32): mean {mean:e}, max {max:e}");
}
}
#[test]
fn gpu_matches_the_oracle_on_the_sample_scene() {
let Some(g) = gpu() else { return };
let doc = sample::demo();
let frames = doc.frame_count();
for (f, s) in [(0u32, 1.0f32), (7, 0.5), (13, 0.37), (frames / 2, 1.5), (frames.saturating_sub(1), 0.25)] {
let dl = anicraft_doc::evaluate(&doc, f);
let v = View::stage(&doc, s);
let gpu = g.render(&dl, &v, Output::Premul8).unwrap();
let (oracle, st) = render(&dl, &v).unwrap();
let d = compare_premul8(&gpu.premul8, &oracle.to_premul_rgba8()).unwrap();
assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "frame {f} at {s}: {d:?}");
assert_eq!((gpu.stats.drawn, gpu.stats.culled), (st.drawn, st.culled));
}
}
#[test]
fn gpu_matches_the_oracle_on_many_shapes_and_tiles() {
let Some(g) = gpu() else { return };
let doc = sample::stress(6, 300, 24);
let dl = anicraft_doc::evaluate(&doc, 5);
// A whole frame and an offset, zoomed tile like the stage asks for.
for v in [View::stage(&doc, 0.5), View { transform: Affine::translate(-512.0, -256.0).mul(&Affine::scale(1.7, 1.7)), width: 512, height: 512, background: Some(doc.stage.background) }] {
let gpu = g.render(&dl, &v, Output::Premul8).unwrap();
let (oracle, _) = render(&dl, &v).unwrap();
let d = compare_premul8(&gpu.premul8, &oracle.to_premul_rgba8()).unwrap();
assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "{d:?}");
}
}
#[test]
fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() {
let Some(g) = gpu() else { return };
let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
clipped.clip = Some(0);
let dl = DisplayList { items: vec![clipped], clip_parents: vec![None], groups: Vec::new() };
assert!(matches!(g.render(&dl, &view(8, 8, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Clips))));
assert!(matches!(g.render(&list(vec![]), &view(0, 8, None), Output::Premul8), Err(GpuError::TooLarge(_))));
assert!(matches!(g.render(&list(vec![]), &view(100_000, 100_000, None), Output::Premul8), Err(GpuError::TooLarge(_))));
// An empty list is just the background; and the device is still fine afterwards.
let f = g.render(&list(vec![]), &view(20, 3, Some(Rgba::new(0.0, 1.0, 0.0, 1.0))), Output::Premul8).unwrap();
assert!(f.premul8.as_chunks::<4>().0.iter().all(|p| *p == [0, 255, 0, 255]));
assert!(g.broken().is_none());
}
#[test]
fn gpu_renders_from_many_threads_at_once() {
let Some(g) = gpu() else { return };
let doc = sample::demo();
let dl = anicraft_doc::evaluate(&doc, 9);
let v = View::stage(&doc, 0.25);
let first = g.render(&dl, &v, Output::Premul8).unwrap().premul8;
use rayon::prelude::*;
let all: Vec<Vec<u8>> = (0..8).into_par_iter().map(|_| g.render(&dl, &v, Output::Premul8).unwrap().premul8).collect();
assert!(all.iter().all(|a| *a == first), "deterministic under concurrency");
}
+93
View File
@@ -244,6 +244,75 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re
Ok((pm, stats))
}
/// Why a display list needs the full renderer rather than plain fills (see [`plain_fills`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NeedsFull {
/// Mask layers: items drawn inside a clip, or mask artwork.
Clips,
/// Group opacity, blend modes or filters (symbol instances composited on their own).
Groups,
/// Bitmap fills.
Bitmaps,
}
impl std::fmt::Display for NeedsFull {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
NeedsFull::Clips => "masks",
NeedsFull::Groups => "group opacity, blend modes or filters",
NeedsFull::Bitmaps => "bitmap fills",
})
}
}
/// One fill operation in surface pixels, exactly as this renderer prepares it: flattened at
/// [`TOLERANCE`], strokes already outlined by the stroker, the paint's shader (with its gradient
/// table) built, and pixel bounds clamped to the surface. Drawing every fill in order, with
/// analytic coverage, the fill rule and src-over, reproduces [`render`] for a display list that
/// [`plain_fills`] accepts. Other renderers (the GPU stage, ADR 0019) start from these, so the
/// geometry and the colours are the oracle's own.
pub struct Fill {
pub polys: Vec<Vec<Vec2>>,
pub rule: FillRule,
pub shader: Shader,
pub bounds: IRect,
}
/// The display list as plain fills, in drawing order, with the same culling and statistics as
/// [`render`]; or why it needs the full renderer (masks, groups, bitmaps).
pub fn plain_fills(dl: &DisplayList, view: &View) -> Result<(Vec<Fill>, RenderStats), NeedsFull> {
for it in &dl.items {
if it.clip.is_some() || it.masks.is_some() {
return Err(NeedsFull::Clips);
}
if it.group.is_some() {
return Err(NeedsFull::Groups);
}
if !it.guide && it.outline.is_none() && matches!(it.fill, Some(Paint::Bitmap { .. })) {
return Err(NeedsFull::Bitmaps);
}
}
let surface = IRect { x0: 0, y0: 0, x1: view.width as i32, y1: view.height as i32 };
let prepared: Vec<Vec<Prepared>> = dl.items.par_iter().map(|item| prepare(item, &view.transform, surface)).collect();
let mut stats = RenderStats { items: dl.items.len(), ..Default::default() };
let mut out = Vec::with_capacity(prepared.len());
for p in prepared {
if p.is_empty() {
stats.culled += 1;
}
for op in p {
if matches!(op.shader, Shader::Bitmap { .. } | Shader::Image { .. }) {
return Err(NeedsFull::Bitmaps);
}
stats.edges += op.polys.iter().map(Vec::len).sum::<usize>();
stats.pixels_touched += (op.bounds.width() * op.bounds.height()) as u64;
out.push(Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds });
}
}
stats.drawn = out.len();
Ok((out, stats))
}
/// A run of items inside a filtered group that has no filtered group around it.
struct FilteredRun {
group: u32,
@@ -782,6 +851,30 @@ mod tests {
assert!((0..100).all(|y| near(t.pixel(1, y).unwrap(), [0.75, 0.75, 0.75, 1.0])));
}
#[test]
fn plain_fills_match_the_renderers_preparation_and_name_what_needs_more() {
// A filled, stroked square and an off-screen circle: fill then stroke, one culled.
let mut sq = item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
sq.stroke = Some(anicraft_doc::Stroke { color: Rgba::WHITE, width: 2.0, profile: None });
let off = item(Path::ellipse(500.0, 500.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK));
let dl = list(vec![sq.clone(), off]);
let (fills, st) = plain_fills(&dl, &view(16, 16)).unwrap();
let (_, rst) = render(&dl, &view(16, 16)).unwrap();
assert_eq!(fills.len(), 2);
assert_eq!((st.drawn, st.culled, st.edges), (rst.drawn, rst.culled, rst.edges));
assert!(fills[0].shader.is_solid() == Some([0.0, 0.0, 0.0, 1.0]) && fills[1].shader.is_solid() == Some([1.0; 4]));
assert!(fills.iter().all(|f| f.bounds.x0 >= 0 && f.bounds.x1 <= 16));
// Masks, groups and bitmaps need the full renderer.
let mut clipped = sq.clone();
clipped.clip = Some(0);
assert_eq!(plain_fills(&list(vec![clipped]), &view(16, 16)).err(), Some(NeedsFull::Clips));
let mut grouped = sq.clone();
grouped.group = Some(0);
assert_eq!(plain_fills(&list(vec![grouped]), &view(16, 16)).err(), Some(NeedsFull::Groups));
let bm = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY });
assert_eq!(plain_fills(&list(vec![bm]), &view(16, 16)).err(), Some(NeedsFull::Bitmaps));
}
#[test]
fn guide_artwork_never_renders() {
let mut g = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "anicraft-svg"
description = "AniCraft SVG import: shapes, groups, transforms, styles and gradients into editable vector shapes"
description = "AniCraft SVG import: shapes, groups, transforms, styles, gradients, clip paths, masks and text into editable shapes, mask layers and text"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -11,6 +11,8 @@ repository.workspace = true
anicraft-geom.workspace = true
anicraft-doc.workspace = true
anicraft-xml.workspace = true
# Lays imported text out with the fonts on this computer (ADR 0012, ADR 0021).
anicraft-text.workspace = true
thiserror.workspace = true
[lints]
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Self-authored AniCraft test drawing (MIT OR Apache-2.0): clip paths, a mask and text. -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="480" height="270" viewBox="0 0 480 270">
<defs>
<clipPath id="frame"><rect width="480" height="270"/></clipPath>
<clipPath id="porthole"><circle cx="120" cy="125" r="80"/></clipPath>
<clipPath id="band"><rect x="0" y="95" width="480" height="60"/></clipPath>
<mask id="reveal" maskUnits="userSpaceOnUse" x="0" y="0" width="480" height="270">
<path d="M260 60 L440 60 L400 200 L300 200 Z" fill="#fff"/>
</mask>
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#2b5876"/><stop offset="1" stop-color="#4e4376"/>
</linearGradient>
</defs>
<g clip-path="url(#frame)">
<rect width="480" height="270" fill="#1d1f24"/>
<g id="sea" clip-path="url(#porthole)">
<rect x="20" y="25" width="200" height="200" fill="url(#sky)"/>
<circle cx="150" cy="95" r="26" fill="#ffd54a"/>
<path d="M20 160 Q70 140 120 160 T220 160 V230 H20 Z" fill="#4dd0e1"/>
<g clip-path="url(#band)"><circle cx="70" cy="120" r="40" fill="#ff6b4a" opacity="0.8"/></g>
</g>
<g id="stripes" mask="url(#reveal)">
<rect x="240" y="40" width="220" height="180" fill="#66bb6a"/>
<rect x="240" y="80" width="220" height="24" fill="#ba68c8"/>
<rect x="240" y="140" width="220" height="24" fill="#ffd54a"/>
</g>
<text x="350" y="245" font-family="Inter, Helvetica, Arial, sans-serif" font-size="22" font-weight="bold" fill="#ffffff" text-anchor="middle">Clipped <tspan fill="#ff6b4a">&amp;</tspan> masked</text>
<text x="24" y="258" font-family="'No Such Typeface', sans-serif" font-size="12" fill="#9aa0a6">AniCraft SVG import</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

+412
View File
@@ -0,0 +1,412 @@
//! Clip paths and masks → mask layers (ADR 0021).
//!
//! While the drawing is read, every drawn item collects the clip regions of the elements
//! around it: a `clipPath` (the union of its shapes' fills) or a `mask` whose content is
//! opaque (the union of its fills, cut to the mask's region). At the end, [`Builder::layers`]
//! resolves each item's regions:
//! * a convex region that contains the item cuts nothing and is dropped; a region that misses
//! it hides it (it is left out);
//! * one region left is the item's mask; several are intersected exactly when all but one are
//! convex polygons (`anicraft_geom::clip`), else one is kept and the report counts it;
//! * consecutive items with the same mask share one masked layer under one mask layer.
use crate::{Builder, ImportedElement, ImportedLayer, ImportedMask, Item, PaintSpec, Report, Style, declarations, get, hidden, length, local, name_of, paint_spec, transform};
use anicraft_doc::{ElementKind, Paint, Rgba, Shape};
use anicraft_geom::clip::{clip_convex, convex_polygon};
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
use anicraft_xml::Element as X;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
/// Most mask layers one drawing makes; clips past these are drawn unclipped and reported.
pub const MAX_MASKS: usize = 250;
/// Deepest chain of clip paths and masks that refer to further ones.
const MAX_NESTING: usize = 8;
/// A clip region in drawing space: the union of its parts' fills.
#[derive(Debug)]
pub(crate) struct Region {
/// Identifies the region: the clip element and the space it was used in.
key: String,
name: String,
parts: Vec<ImportedElement>,
/// The corners, when the region is one convex polygon.
convex: Option<Vec<Vec2>>,
/// Conservative drawing-space bounds.
bounds: Rect,
}
/// Conservative drawing-space bounds of an element's artwork.
fn element_bounds(e: &ImportedElement) -> Rect {
match &e.kind {
ElementKind::Shape(s) => s.path.bounds().inflate(s.stroke.as_ref().map_or(0.0, |st| st.width * 0.5)).transformed(&e.transform),
ElementKind::Text(t) => t.outline.bounds().union(&Rect::new(0.0, 0.0, t.box_width.max(0.0), t.box_height.max(0.0))).transformed(&e.transform),
ElementKind::Symbol { .. } => Rect::EMPTY,
}
}
/// A fill-only shape for mask artwork (its colour doesn't matter: a mask is its fills' area).
fn mask_part(name: String, path: Path, transform: Affine, rule: FillRule) -> ImportedElement {
let shape = Shape { path: Arc::new(path), fill: Some(Paint::Solid(Rgba::BLACK)), stroke: None, fill_rule: rule };
ImportedElement { name, transform, alpha: 1.0, kind: ElementKind::Shape(shape) }
}
impl Region {
fn new(key: String, name: &str, parts: Vec<ImportedElement>) -> Rc<Region> {
let bounds = parts.iter().fold(Rect::EMPTY, |r, p| r.union(&element_bounds(p)));
let convex = match parts.as_slice() {
[ImportedElement { kind: ElementKind::Shape(s), transform, .. }] => convex_polygon(&s.path.transformed(transform)),
_ => None,
};
Rc::new(Region { key, name: name.chars().take(128).collect(), parts, convex, bounds })
}
/// Whether the region is convex and holds all of `r`.
fn contains(&self, r: &Rect) -> bool {
let Some(poly) = &self.convex else { return false };
if !(r.min.x <= r.max.x && r.min.y <= r.max.y) {
return false;
}
let n = poly.len();
let area2: f32 = (0..n).map(|i| poly[i].cross(poly[(i + 1) % n])).sum();
let s = area2.signum();
let corners = [r.min, Vec2::new(r.max.x, r.min.y), r.max, Vec2::new(r.min.x, r.max.y)];
(0..n).all(|i| {
let (a, b) = (poly[i], poly[(i + 1) % n]);
let tol = 1e-3 * (b - a).length();
corners.iter().all(|p| s * (b - a).cross(*p - a) >= -tol)
})
}
/// This region cut to the convex region `other`, exactly.
fn intersect(&self, other: &Region) -> Rc<Region> {
let Some(poly) = &other.convex else { return Region::new(self.key.clone(), &self.name, self.parts.clone()) };
let mut parts = Vec::new();
for p in &self.parts {
let (path, rule) = match &p.kind {
ElementKind::Shape(s) => (s.path.transformed(&p.transform), s.fill_rule),
ElementKind::Text(t) => (t.outline.transformed(&p.transform), FillRule::NonZero),
ElementKind::Symbol { .. } => continue,
};
let cut = clip_convex(&path, poly);
if !cut.is_empty() {
parts.push(mask_part(p.name.clone(), cut, Affine::IDENTITY, rule));
}
}
Region::new(format!("{}&{}", self.key, other.key), &self.name, parts)
}
}
/// What an item's clips come to.
enum Effective {
/// Nothing of it shows.
Hidden,
Unclipped,
Masked(Rc<Region>),
}
/// The id in `url(#id)`.
fn url(v: &str) -> Option<String> {
match paint_spec(v) {
Some(PaintSpec::Url(id, _)) => Some(id),
_ => None,
}
}
/// A mask region attribute: a fraction or percentage of the bounding box.
fn fraction(v: Option<&str>, default: f32) -> f32 {
v.map(str::trim)
.and_then(|v| match v.strip_suffix('%') {
Some(p) => p.trim().parse::<f32>().ok().map(|p| p / 100.0),
None => v.parse::<f32>().ok(),
})
.filter(|x| x.is_finite())
.unwrap_or(default)
}
impl<'a> Builder<'a> {
/// Applies an element's `clip-path` and `mask` to what it drew (`items[start..]`); `m` is its
/// user space.
pub(crate) fn clip(&mut self, d: &[(String, String)], m: &Affine, start: usize, depth: usize) {
let clip = get(d, "clip-path").filter(|v| *v != "none").map(str::to_string);
let mask = get(d, "mask").filter(|v| *v != "none").map(str::to_string);
if clip.is_none() && mask.is_none() {
return;
}
let bbox = self.user_bbox(start, m);
let mut regions: Vec<Rc<Region>> = Vec::new();
if let Some(v) = clip {
match url(&v) {
Some(id) => match self.clip_path(&id, m, bbox) {
Some(r) => regions.extend(r),
None => self.report.skip("references to missing clip paths (drawn unclipped)"),
},
None => self.report.skip("CSS clip shapes (drawn unclipped)"),
}
}
if let Some(v) = mask {
match url(&v) {
Some(id) => match self.mask(&id, m, bbox, depth) {
Some(r) => regions.extend(r),
None => self.report.skip("references to missing masks (drawn unmasked)"),
},
None => self.report.skip("CSS mask images (drawn unmasked)"),
}
}
for it in self.items.iter_mut().skip(start) {
it.clips.extend(regions.iter().cloned());
}
}
/// The bounding box of `items[start..]` in the user space `m` maps from (the box
/// `objectBoundingBox` units refer to).
fn user_bbox(&self, start: usize, m: &Affine) -> Option<Rect> {
let inv = m.inverse()?;
let mut r = Rect::EMPTY;
for it in self.items.iter().skip(start) {
let to_user = inv.mul(&it.el.transform);
match &it.el.kind {
ElementKind::Shape(s) => {
for line in s.path.flatten(&to_user, 0.05) {
for p in line.points {
r.include(p);
}
}
}
ElementKind::Text(t) => r = r.union(&Rect::new(0.0, 0.0, t.box_width, t.box_height).transformed(&to_user)),
ElementKind::Symbol { .. } => {}
}
}
(r.min.x <= r.max.x && r.min.y <= r.max.y).then_some(r)
}
/// Whether `target` is already being read (a loop), or the chain is too long. Reports it.
fn looping(&mut self, target: &X) -> bool {
if self.resolving.iter().any(|r| std::ptr::eq(*r, target)) || self.resolving.len() >= MAX_NESTING {
self.report.skip("clip paths or masks that refer to themselves (ignored)");
return true;
}
false
}
/// The regions of `clipPath` `id` used in user space `m`: its own, and those of the clip
/// paths it is clipped by. `None` when there is no such clip path.
fn clip_path(&mut self, id: &str, m: &Affine, bbox: Option<Rect>) -> Option<Vec<Rc<Region>>> {
let target = self.ids.get(id).copied().filter(|t| local(&t.name) == "clipPath")?;
if self.looping(target) {
return Some(Vec::new());
}
let units = if target.attr("clipPathUnits") == Some("objectBoundingBox") {
match bbox {
Some(b) => Affine::translate(b.min.x, b.min.y).mul(&Affine::scale(b.width(), b.height())),
// Nothing to size the clip by: it clips everything.
None => return Some(vec![Region::new(format!("clip:{target:p}:empty"), id, Vec::new())]),
}
} else {
Affine::IDENTITY
};
let base = m.mul(&units).mul(&target.attr("transform").map_or(Affine::IDENTITY, transform));
let style = Style::default().with(target, &mut Report::default());
self.resolving.push(target);
let mut parts = Vec::new();
for c in &target.children {
self.clip_child(c, &base, &style, &mut parts, 0);
}
let mut out = vec![Region::new(format!("clip:{target:p}:{:?}", base.m), id, parts)];
let inner = get(&declarations(target), "clip-path").and_then(url);
if let Some(inner) = inner
&& let Some(r) = self.clip_path(&inner, m, bbox)
{
out.extend(r);
}
self.resolving.pop();
Some(out)
}
/// One child of a `clipPath`: a shape, text, or a `use` of one. Only its geometry counts.
fn clip_child(&mut self, c: &'a X, base: &Affine, style: &Style, parts: &mut Vec<ImportedElement>, uses: usize) {
let name = local(&c.name);
let d = declarations(c);
if name == anicraft_xml::TEXT_NODE || get(&d, "display") == Some("none") || hidden(&d) {
return;
}
if get(&d, "clip-path").is_some_and(|v| v != "none") {
self.report.skip("clip paths on the contents of a clip path (ignored)");
}
let style = style.with(c, &mut Report::default());
let t = base.mul(&c.attr("transform").map_or(Affine::IDENTITY, transform));
match name {
"use" if uses < crate::MAX_USE_DEPTH => {
let href = c.attr("href").or_else(|| c.attr("xlink:href")).unwrap_or("").trim_start_matches('#');
let Some(target) = self.ids.get(href).copied() else { return };
let (vw, vh) = self.viewport;
let x = c.attr("x").and_then(|v| length(v, vw)).unwrap_or(0.0);
let y = c.attr("y").and_then(|v| length(v, vh)).unwrap_or(0.0);
self.clip_child(target, &t.mul(&Affine::translate(x, y)), &style, parts, uses + 1);
}
"text" => parts.extend(self.text(c, &t, &style, 1.0)),
"path" | "rect" | "circle" | "ellipse" | "polyline" | "polygon" => {
if let Some((p, true)) = self.geometry(c, name)
&& !p.is_empty()
&& t.is_finite()
{
parts.push(mask_part(name_of(c), p, t, style.clip_rule));
}
}
_ => {}
}
}
/// The regions of `mask` `id` used in user space `m`: its content's fills, cut to its
/// region. `None` when there is no such mask; no regions when the mask is soft (reported).
fn mask(&mut self, id: &str, m: &Affine, bbox: Option<Rect>, depth: usize) -> Option<Vec<Rc<Region>>> {
let target = self.ids.get(id).copied().filter(|t| local(&t.name) == "mask")?;
if self.looping(target) {
return Some(Vec::new());
}
let everything = || Some(vec![Region::new(format!("mask:{target:p}:empty"), id, Vec::new())]);
// The mask's region: by default the bounding box grown by 10% on every side.
let rect = if target.attr("maskUnits") == Some("userSpaceOnUse") {
let (vw, vh) = self.viewport;
let len = |k: &str, reference: f32, d: f32| target.attr(k).and_then(|v| length(v, reference)).unwrap_or(d * reference);
let (x, y) = (len("x", vw, -0.1), len("y", vh, -0.1));
Rect::new(x, y, x + len("width", vw, 1.2), y + len("height", vh, 1.2))
} else {
let Some(b) = bbox else { return everything() };
let (x, y) = (fraction(target.attr("x"), -0.1), fraction(target.attr("y"), -0.1));
let (w, h) = (fraction(target.attr("width"), 1.2), fraction(target.attr("height"), 1.2));
let x0 = b.min.x + x * b.width();
let y0 = b.min.y + y * b.height();
Rect::new(x0, y0, x0 + w * b.width(), y0 + h * b.height())
};
if rect.is_empty() {
return everything();
}
let content_m = if target.attr("maskContentUnits") == Some("objectBoundingBox") {
let Some(b) = bbox else { return everything() };
m.mul(&Affine::translate(b.min.x, b.min.y)).mul(&Affine::scale(b.width(), b.height()))
} else {
*m
};
let alpha_mask = get(&declarations(target), "mask-type") == Some("alpha");
let style = Style::default().with(target, &mut Report::default());
self.resolving.push(target);
let mark = self.items.len();
self.children(target, &content_m, &style, 1.0, depth + 1, 0);
self.resolving.pop();
let content: Vec<Item> = self.items.drain(mark..).collect();
// Only an opaque mask is the coverage of its shapes: full alpha, no strokes, and for a
// luminance mask, white.
let opaque = |c: Rgba| c.a >= 0.999 && (alpha_mask || (c.r >= 0.996 && c.g >= 0.996 && c.b >= 0.996));
let mut parts = Vec::new();
let mut soft = false;
for it in content {
let e = it.el;
let ok = it.clips.is_empty()
&& e.alpha >= 0.999
&& match &e.kind {
ElementKind::Shape(s) => s.stroke.is_none() && matches!(s.fill, Some(Paint::Solid(c)) if opaque(c)),
ElementKind::Text(t) => opaque(t.color),
ElementKind::Symbol { .. } => false,
};
if !ok {
soft = true;
break;
}
parts.push(match &e.kind {
ElementKind::Shape(s) => mask_part(e.name.clone(), (*s.path).clone(), e.transform, s.fill_rule),
_ => e,
});
}
if soft {
self.report.skip("soft, faded or coloured masks (drawn unmasked)");
return Some(Vec::new());
}
let area = mask_part(String::new(), Path::rect(rect.min.x, rect.min.y, rect.width(), rect.height()), *m, FillRule::NonZero);
Some(vec![Region::new(format!("mask:{target:p}:{:?}", content_m.m), id, parts), Region::new(format!("maskarea:{target:p}:{:?}:{rect:?}", m.m), id, vec![area])])
}
/// What an item's clips come to (combinations are cached by key; `None` = hidden).
fn effective(&mut self, it: &Item, cache: &mut HashMap<String, Option<Rc<Region>>>) -> Effective {
let b = element_bounds(&it.el);
let mut keep: Vec<Rc<Region>> = Vec::new();
for r in &it.clips {
if r.parts.is_empty() || r.bounds.intersect(&b).is_empty() {
return Effective::Hidden;
}
if r.contains(&b) || keep.iter().any(|k| k.key == r.key) {
continue;
}
keep.push(r.clone());
}
// A convex region holding another region whole cuts nothing more.
let mut i = 0;
while keep.len() > 1 && i < keep.len() {
let holds = keep.get(i).is_some_and(|r| keep.iter().enumerate().any(|(j, o)| j != i && r.contains(&o.bounds)));
if holds {
keep.remove(i);
} else {
i += 1;
}
}
if keep.len() <= 1 {
return keep.pop().map_or(Effective::Unclipped, Effective::Masked);
}
let key = keep.iter().map(|r| r.key.as_str()).collect::<Vec<_>>().join("&");
let combined = match cache.get(&key) {
Some(c) => c.clone(),
None => {
let (curved, convex): (Vec<Rc<Region>>, Vec<Rc<Region>>) = keep.into_iter().partition(|r| r.convex.is_none());
if curved.len() > 1 {
self.report.skip("curved clips inside curved clips (drawn with the inner one)");
}
let mut rest = convex.into_iter();
let base = match curved.first() {
Some(c) => Some(c.clone()),
None => rest.next(),
};
let r = base.map(|base| rest.fold(base, |acc, c| acc.intersect(&c))).filter(|r| !r.parts.is_empty());
cache.insert(key, r.clone());
r
}
};
match combined {
Some(r) if !r.bounds.intersect(&b).is_empty() => Effective::Masked(r),
_ => Effective::Hidden,
}
}
/// The drawing as layers, bottom first: runs of items with the same mask.
pub(crate) fn layers(&mut self) -> Vec<ImportedLayer> {
let items = std::mem::take(&mut self.items);
let mut cache = HashMap::new();
let mut runs: Vec<(Option<Rc<Region>>, Vec<ImportedElement>)> = Vec::new();
let mut masks = 0usize;
for it in items {
let mut region = match self.effective(&it, &mut cache) {
Effective::Hidden => continue,
Effective::Unclipped => None,
Effective::Masked(r) => Some(r),
};
let same = |run: &(Option<Rc<Region>>, Vec<ImportedElement>), r: &Option<Rc<Region>>| match (&run.0, r) {
(None, None) => true,
(Some(a), Some(b)) => a.key == b.key,
_ => false,
};
if !runs.last().is_some_and(|run| same(run, &region)) && region.is_some() {
if masks >= MAX_MASKS {
self.report.skip("clip paths and masks past 250 per drawing (drawn unclipped)");
region = None;
} else {
masks += 1;
}
}
match runs.last_mut() {
Some(run) if same(run, &region) => run.1.push(it.el),
_ => runs.push((region, vec![it.el])),
}
}
runs.into_iter().map(|(r, elements)| ImportedLayer { mask: r.map(|r| ImportedMask { name: r.name.clone(), elements: r.parts.clone() }), elements }).collect()
}
}
+184
View File
@@ -0,0 +1,184 @@
//! Clip paths and masks → mask layers (ADR 0021), on self-authored drawings.
use super::*;
fn imp(svg: &str) -> SvgImport {
match import_with_fonts(svg.as_bytes(), &Fonts::from_faces(Vec::new())) {
Ok(i) => i,
Err(e) => panic!("{e}: {svg}"),
}
}
fn names(l: &ImportedLayer) -> Vec<&str> {
l.elements.iter().map(|e| e.name.as_str()).collect()
}
fn path_of(e: &ImportedElement) -> Path {
match &e.kind {
ElementKind::Shape(s) => s.path.transformed(&e.transform),
other => panic!("not a shape: {other:?}"),
}
}
/// Whether drawing-space point `p` is inside the mask layer's fills.
fn in_mask(m: &ImportedMask, p: Vec2) -> bool {
m.elements.iter().any(|e| match &e.kind {
ElementKind::Shape(s) => s.path.contains(p, &e.transform, s.fill_rule),
_ => false,
})
}
#[test]
fn a_clipped_group_becomes_a_masked_layer_under_its_mask() {
let i = imp(r##"<svg width="200" height="100">
<defs><clipPath id="round"><circle cx="50" cy="50" r="40"/></clipPath></defs>
<rect id="bg" width="200" height="100" fill="#eee"/>
<g clip-path="url(#round)"><rect id="a" width="100" height="100" fill="red" stroke="#000"/><rect id="b" x="20" y="20" width="30" height="30" fill="blue"/></g>
<rect id="top" x="150" width="10" height="10"/>
</svg>"##);
assert_eq!(i.layers.len(), 3, "{:?}", i.layers);
assert!(i.layers[0].mask.is_none() && i.layers[2].mask.is_none());
assert_eq!((names(&i.layers[0]), names(&i.layers[1]), names(&i.layers[2])), (vec!["bg"], vec!["a", "b"], vec!["top"]));
let mask = i.layers[1].mask.as_ref().expect("masked");
assert_eq!(mask.name, "round");
assert_eq!(mask.elements.len(), 1);
assert!(in_mask(mask, Vec2::new(50.0, 50.0)) && !in_mask(mask, Vec2::new(5.0, 5.0)));
let b = path_of(&mask.elements[0]).bounds();
assert!((b.min.x - 10.0).abs() < 1e-3 && (b.max.x - 90.0).abs() < 1e-3, "{b:?}");
// The artwork keeps its paint and stroke; the mask's own artwork is a plain fill.
assert!(matches!(&i.layers[1].elements[0].kind, ElementKind::Shape(s) if s.stroke.is_some()));
assert!(i.report.skipped.is_empty(), "{:?}", i.report);
assert_eq!(i.elements().count(), 4, "mask artwork isn't drawn");
}
#[test]
fn clips_that_cut_nothing_go_and_clips_that_hide_everything_drop_the_artwork() {
// A frame clip around the whole drawing (as design tools export) changes nothing.
let i = imp(r##"<svg width="100" height="100">
<clipPath id="frame"><rect width="100" height="100"/></clipPath>
<clipPath id="far"><rect x="500" y="500" width="10" height="10"/></clipPath>
<clipPath id="empty"/>
<g clip-path="url(#frame)"><rect id="a" x="10" y="10" width="20" height="20" stroke="#000" stroke-width="2"/></g>
<rect id="gone" width="10" height="10" clip-path="url(#far)"/>
<rect id="gone too" width="10" height="10" clip-path="url(#empty)"/>
<rect id="kept" width="10" height="10" clip-path="url(#nowhere)"/>
</svg>"##);
assert_eq!(i.layers.len(), 1, "{:?}", i.layers);
assert!(i.layers[0].mask.is_none());
assert_eq!(names(&i.layers[0]), ["a", "kept"]);
assert_eq!(i.report.skipped.get("references to missing clip paths (drawn unclipped)"), Some(&1));
}
#[test]
fn clips_inside_clips_intersect_exactly() {
// A circle clip inside a band clip: the mask is the circle cut to the band, still curved.
let i = imp(r##"<svg width="200" height="200">
<clipPath id="band"><rect x="0" y="40" width="200" height="40"/></clipPath>
<clipPath id="disc"><circle cx="60" cy="60" r="40"/></clipPath>
<g clip-path="url(#band)"><rect id="wide" width="200" height="200" fill="red"/><g clip-path="url(#disc)"><rect id="inner" width="200" height="200" fill="blue"/></g></g>
</svg>"##);
assert_eq!(i.layers.len(), 2, "{:?}", i.layers);
let (outer, inner) = (i.layers[0].mask.as_ref().unwrap(), i.layers[1].mask.as_ref().unwrap());
assert_eq!((outer.name.as_str(), inner.name.as_str()), ("band", "disc"));
let p = path_of(&inner.elements[0]);
assert!(p.cmds.iter().any(|c| matches!(c, anicraft_geom::PathCmd::CubicTo(..))), "the arcs stay curves");
let b = p.bounds();
assert!(b.min.y >= 40.0 - 1e-3 && b.max.y <= 80.0 + 1e-3 && b.min.x >= 20.0 - 1e-3 && b.max.x <= 100.0 + 1e-3, "{b:?}");
assert!(in_mask(inner, Vec2::new(60.0, 60.0)) && !in_mask(inner, Vec2::new(60.0, 30.0)) && !in_mask(inner, Vec2::new(150.0, 60.0)));
// Two curved clips can't be intersected exactly: one is kept, and the report says so.
let two = imp(r##"<svg width="200" height="200">
<clipPath id="a"><circle cx="60" cy="60" r="40"/></clipPath>
<clipPath id="b"><circle cx="90" cy="60" r="40"/></clipPath>
<g clip-path="url(#a)"><rect clip-path="url(#b)" width="200" height="200"/></g>
</svg>"##);
assert_eq!(two.layers.len(), 1);
assert_eq!(two.report.skipped.get("curved clips inside curved clips (drawn with the inner one)"), Some(&1));
}
#[test]
fn bounding_box_units_and_transforms_place_the_clip() {
let i = imp(r##"<svg width="200" height="200">
<clipPath id="oval" clipPathUnits="objectBoundingBox"><circle cx=".5" cy=".5" r=".5"/></clipPath>
<clipPath id="user"><rect x="0" y="0" width="10" height="10" transform="rotate(45)"/></clipPath>
<rect id="a" x="10" y="10" width="100" height="50" clip-path="url(#oval)"/>
<g transform="translate(150 150)"><rect id="b" x="-20" y="-20" width="40" height="40" clip-path="url(#user)"/></g>
</svg>"##);
assert_eq!(i.layers.len(), 2);
let oval = path_of(&i.layers[0].mask.as_ref().unwrap().elements[0]).bounds();
assert!((oval.min.x - 10.0).abs() < 1e-3 && (oval.max.x - 110.0).abs() < 1e-3 && (oval.min.y - 10.0).abs() < 1e-3 && (oval.max.y - 60.0).abs() < 1e-3, "{oval:?}");
// A userSpaceOnUse clip lives in the space of the element it clips (inside its group).
let user = i.layers[1].mask.as_ref().unwrap();
assert!(in_mask(user, Vec2::new(150.0, 155.0)) && !in_mask(user, Vec2::new(155.0, 150.0)), "rotated 45° about the group's origin");
}
#[test]
fn shapes_sharing_one_clip_share_one_mask_layer() {
// What SVG export writes: every masked path names the same clip.
let i = imp(r##"<svg width="100" height="100">
<defs><clipPath id="c0" clipPathUnits="userSpaceOnUse"><path d="M50 10 L90 90 L10 90 Z"/></clipPath></defs>
<path d="M0 0 H100 V100 H0 Z" fill="#00f" clip-path="url(#c0)"/>
<path d="M0 40 H100 V60 H0 Z" fill="#f00" clip-path="url(#c0)"/>
<path d="M0 0 H10 V10 H0 Z" fill="#0f0"/>
<path d="M0 0 H100 V100 H0 Z" fill="#00f" clip-path="url(#c0)" transform="translate(1 0)"/>
</svg>"##);
let shape: Vec<(bool, usize)> = i.layers.iter().map(|l| (l.mask.is_some(), l.elements.len())).collect();
assert_eq!(shape, [(true, 2), (false, 1), (true, 1)], "a clip in another space is another mask");
}
#[test]
fn opaque_masks_become_mask_layers_and_soft_ones_are_reported() {
let i = imp(r##"<svg width="100" height="100">
<mask id="white"><circle cx="50" cy="50" r="30" fill="white"/><rect x="0" y="0" width="10" height="10" style="fill:#fff"/></mask>
<mask id="alpha" style="mask-type:alpha"><circle cx="50" cy="50" r="30" fill="#123456"/></mask>
<mask id="grey"><circle cx="50" cy="50" r="30" fill="#808080"/></mask>
<mask id="faded"><circle cx="50" cy="50" r="30" fill="white" opacity="0.5"/></mask>
<mask id="tight" x="0.25" y="0.25" width="0.5" height="0.5"><rect width="100" height="100" fill="white"/></mask>
<rect id="a" width="100" height="100" mask="url(#white)"/>
<rect id="b" width="100" height="100" mask="url(#alpha)"/>
<rect id="c" width="100" height="100" mask="url(#grey)"/>
<rect id="d" width="100" height="100" mask="url(#faded)"/>
<rect id="e" width="100" height="100" mask="url(#tight)"/>
</svg>"##);
let shape: Vec<(Option<&str>, Vec<&str>)> = i.layers.iter().map(|l| (l.mask.as_ref().map(|m| m.name.as_str()), names(l))).collect();
assert_eq!(shape, [(Some("white"), vec!["a"]), (Some("alpha"), vec!["b"]), (None, vec!["c", "d"]), (Some("tight"), vec!["e"])]);
let white = i.layers[0].mask.as_ref().unwrap();
assert_eq!(white.elements.len(), 2, "the default mask region (bounding box + 10%) holds the content and cuts nothing");
assert!(in_mask(white, Vec2::new(5.0, 5.0)) && in_mask(white, Vec2::new(50.0, 50.0)) && !in_mask(white, Vec2::new(90.0, 10.0)));
assert_eq!(i.report.skipped.get("soft, faded or coloured masks (drawn unmasked)"), Some(&2));
// A mask region cuts the mask: the full-size rect becomes the middle quarter.
let tight = path_of(&i.layers[3].mask.as_ref().unwrap().elements[0]).bounds();
assert_eq!(tight, Rect::new(25.0, 25.0, 75.0, 75.0));
}
#[test]
fn loops_and_floods_of_clips_stay_bounded() {
let start = std::time::Instant::now();
let mut svg = String::from(r##"<svg width="100" height="100">
<clipPath id="self" clip-path="url(#self)"><rect width="50" height="50"/></clipPath>
<mask id="m"><rect width="100" height="100" fill="white" mask="url(#m)"/><use href="#user"/></mask>
<rect id="user" width="60" height="60" mask="url(#m)"/>
<rect width="80" height="80" clip-path="url(#self)"/>"##);
for k in 0..300 {
svg.push_str(&format!(r##"<clipPath id="c{k}"><circle cx="{}" cy="50" r="5"/></clipPath><rect width="100" height="100" clip-path="url(#c{k})"/>"##, 5 + k % 90));
}
svg.push_str("</svg>");
let i = imp(&svg);
assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed());
assert!(i.report.skipped.contains_key("clip paths or masks that refer to themselves (ignored)"), "{:?}", i.report);
assert!(i.layers.iter().filter(|l| l.mask.is_some()).count() <= clip::MAX_MASKS);
assert!(i.report.skipped.contains_key("clip paths and masks past 250 per drawing (drawn unclipped)"));
}
#[test]
fn the_fixture_drawing_comes_across_as_five_layers() {
let i = imp(include_str!("../fixtures/clips-masks-text.svg"));
let shape: Vec<Option<&str>> = i.layers.iter().map(|l| l.mask.as_ref().map(|m| m.name.as_str())).collect();
// The frame clip holds everything and goes; the sun and sea sit in the porthole, the red
// ball in the porthole cut to the band, the stripes under the mask.
assert_eq!(shape[..4], [None, Some("porthole"), Some("porthole"), Some("reveal")], "{shape:?}");
assert_eq!(i.layers[1].elements.len(), 3);
assert_eq!(i.layers[3].elements.len(), 3);
let ball = path_of(&i.layers[2].mask.as_ref().unwrap().elements[0]).bounds();
assert!(ball.min.y >= 95.0 - 1e-3 && ball.max.y <= 155.0 + 1e-3, "{ball:?}");
assert_eq!(i.report.skipped.get("text (no fonts on this computer)"), Some(&2), "{:?}", i.report);
}
+295 -53
View File
@@ -1,34 +1,55 @@
//! AniCraft SVG import (layer L2): an SVG drawing into editable vector shapes.
//! AniCraft SVG import (layer L2): an SVG drawing into editable vector shapes and text.
//!
//! Written from the public W3C SVG 1.1 / SVG 2 specifications. Supported: `svg`, `g`, `a`,
//! `switch`, `use`, `path`, `rect` (rounded), `circle`, `ellipse`, `line`, `polyline` and
//! `polygon`, read in document order. Styling comes from presentation attributes and `style=""`
//! declarations, with inheritance. Colours can be hex, `rgb()`/`rgba()`, CSS names, `none`,
//! `transparent` or `currentColor`. Also supported: `opacity`, `fill-opacity` and
//! Written from the public W3C SVG 1.1 / SVG 2 and CSS Masking specifications. Supported: `svg`,
//! `g`, `a`, `switch`, `use`, `path`, `rect` (rounded), `circle`, `ellipse`, `line`, `polyline`
//! and `polygon`, read in document order. Styling comes from presentation attributes and
//! `style=""` declarations, with inheritance. Colours can be hex, `rgb()`/`rgba()`, CSS names,
//! `none`, `transparent` or `currentColor`. Also supported: `opacity`, `fill-opacity` and
//! `stroke-opacity`, `fill-rule`, `stroke-width` with units, the transform list (`matrix`,
//! `translate`, `scale`, `rotate`, `skewX`, `skewY`), `viewBox` with `preserveAspectRatio`, and
//! linear and radial gradients (both unit systems, `gradientTransform`, stops inherited through
//! `href`).
//!
//! What AniCraft cannot represent yet is reported, never guessed silently: text, images,
//! filters, clip paths and masks (drawn unclipped), patterns, dashes, style sheets,
//! reflected/repeated gradients and skewed gradient transforms (approximated).
//! **Clip paths and masks** (`clip`, ADR 0015) become AniCraft mask layers: the drawing comes
//! out as layers, bottom first, and artwork under a clip is a masked layer under a mask layer
//! holding the clip's shapes. A clip that cuts nothing is dropped, artwork it hides entirely is
//! left out, and clips inside clips are intersected exactly when all but one are convex
//! polygons. A `mask` comes across when its content is opaque (and white, for a luminance mask),
//! so that it is the coverage of its shapes. **Text** (`text`) becomes text blocks laid out by
//! `anicraft-text`, one per text chunk, with the missing-font reporting of Animate import
//! (ADR 0014).
//!
//! What AniCraft cannot represent yet is reported, never guessed silently: images, filters,
//! soft masks, patterns, dashes, style sheets, text on a path, reflected/repeated gradients and
//! skewed gradient transforms (approximated).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use anicraft_doc::{GradientStop, Paint, Rgba, Shape, Stroke};
use anicraft_doc::{ElementKind, GradientStop, Paint, Rgba, Shape, Stroke};
use anicraft_geom::svg::parse_path_data;
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
use anicraft_text::{FaceMatch, Fonts};
use anicraft_xml::Element as X;
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::rc::Rc;
use std::sync::Arc;
mod clip;
mod text;
#[cfg(test)]
mod clip_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod text_tests;
/// Most shapes read from one file.
pub const MAX_SHAPES: usize = 200_000;
const MAX_DEPTH: usize = 64;
const MAX_USE_DEPTH: usize = 16;
/// Most elements visited while reading one file. Masks draw their content again, so this, not
/// the file's size, bounds the work.
const MAX_VISITS: usize = 2_000_000;
#[derive(Debug, thiserror::Error)]
pub enum SvgError {
@@ -38,35 +59,66 @@ pub enum SvgError {
NotSvg(String),
}
/// What could not come across, by kind ("2 text elements").
/// What could not come across, by kind ("2 images"), and the fonts the text asks for that
/// aren't on this computer.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Report {
pub skipped: BTreeMap<String, usize>,
/// Font families the drawing's text asks for that aren't on this computer.
pub missing_fonts: BTreeSet<String>,
/// The family that text was laid out in instead.
pub fallback_font: Option<String>,
}
impl Report {
fn skip(&mut self, what: &str) {
*self.skipped.entry(what.to_string()).or_default() += 1;
}
/// One line for a status bar.
/// One line for a status bar: "Imported. Not yet supported: 2 images. Fonts not on this
/// computer, drawn in Inter: Futura."
pub fn summary(&self) -> String {
if self.skipped.is_empty() {
if self.skipped.is_empty() && self.missing_fonts.is_empty() {
return "Imported everything in the drawing.".into();
}
let parts: Vec<String> = self.skipped.iter().map(|(k, n)| format!("{n} {k}")).collect();
format!("Imported. Not yet supported: {}.", parts.join(", "))
let mut out = String::from("Imported.");
if !self.skipped.is_empty() {
let parts: Vec<String> = self.skipped.iter().map(|(k, n)| format!("{n} {k}")).collect();
out.push_str(&format!(" Not yet supported: {}.", parts.join(", ")));
}
if !self.missing_fonts.is_empty() {
let names: Vec<&str> = self.missing_fonts.iter().map(String::as_str).collect();
let instead = self.fallback_font.as_deref().map(|f| format!(", drawn in {f}")).unwrap_or_default();
out.push_str(&format!(" Fonts not on this computer{instead}: {}.", names.join(", ")));
}
out
}
}
/// One shape, ready to become an element: its path in local coordinates, the local → drawing
/// transform, and the opacity of the shape and its groups.
/// One shape or text block, ready to become an element: its geometry in local coordinates,
/// the local → drawing transform, and the opacity of the element and its groups.
#[derive(Clone, Debug)]
pub struct ImportedShape {
pub struct ImportedElement {
/// The element's `id`, if it had one.
pub name: String,
pub transform: Affine,
pub alpha: f32,
pub shape: Shape,
/// A shape or a text block.
pub kind: ElementKind,
}
/// The artwork of a mask layer: its fills make the mask (ADR 0010).
#[derive(Clone, Debug)]
pub struct ImportedMask {
/// The clip path's or mask's `id`, if it had one.
pub name: String,
pub elements: Vec<ImportedElement>,
}
/// Artwork drawn together on one layer, bottom first; masked by `mask` when there is one.
#[derive(Clone, Debug)]
pub struct ImportedLayer {
pub mask: Option<ImportedMask>,
pub elements: Vec<ImportedElement>,
}
/// An imported drawing. Coordinates are SVG user units (CSS pixels) of the drawing, with the
@@ -75,13 +127,42 @@ pub struct ImportedShape {
pub struct SvgImport {
pub width: f32,
pub height: f32,
pub shapes: Vec<ImportedShape>,
/// Bottom layer first. A drawing without clips or masks is one unmasked layer.
pub layers: Vec<ImportedLayer>,
pub report: Report,
}
/// Reads an SVG document.
impl SvgImport {
/// A drawing of these elements on one layer.
pub fn single(width: f32, height: f32, elements: Vec<ImportedElement>) -> SvgImport {
SvgImport { width, height, layers: vec![ImportedLayer { mask: None, elements }], report: Report::default() }
}
/// Every element that draws (not mask artwork), bottom first.
pub fn elements(&self) -> impl Iterator<Item = &ImportedElement> {
self.layers.iter().flat_map(|l| l.elements.iter())
}
/// Whether nothing in the drawing could be imported.
pub fn is_empty(&self) -> bool {
self.layers.iter().all(|l| l.elements.is_empty())
}
}
/// Elements whose character data keeps its place among their children (SVG text content).
const TEXT_CONTENT: &[&str] = &["text", "tspan", "a", "textPath"];
/// Reads an SVG document, laying any text out with this computer's fonts.
pub fn import(bytes: &[u8]) -> Result<SvgImport, SvgError> {
let root = anicraft_xml::parse(bytes)?;
import_from(bytes, None)
}
/// Reads an SVG document, laying text out with `fonts` (tests, and hosts with their own font
/// library).
pub fn import_with_fonts(bytes: &[u8], fonts: &Fonts) -> Result<SvgImport, SvgError> {
import_from(bytes, Some(fonts))
}
fn import_from(bytes: &[u8], fonts: Option<&Fonts>) -> Result<SvgImport, SvgError> {
let root = anicraft_xml::parse_mixed(bytes, TEXT_CONTENT)?;
if local(&root.name) != "svg" {
return Err(SvgError::NotSvg(root.name.clone()));
}
@@ -92,14 +173,34 @@ pub fn import(bytes: &[u8]) -> Result<SvgImport, SvgError> {
let fallback = vb.map_or((300.0, 150.0), |r| (r.width(), r.height()));
let size = |key: &str, d: f32| root.attr(key).and_then(|v| length(v, d)).filter(|v| *v > 0.0).unwrap_or(d);
let (w, h) = (size("width", fallback.0), size("height", fallback.1));
let mut b = Builder { ids, report: Report::default(), shapes: Vec::new(), viewport: vb.map_or((w, h), |r| (r.width(), r.height())) };
let mut b = Builder {
ids,
report: Report::default(),
items: Vec::new(),
viewport: vb.map_or((w, h), |r| (r.width(), r.height())),
fonts,
faces: HashMap::new(),
visits: 0,
resolving: Vec::new(),
};
let base = match vb {
Some(r) => view_box_transform(r, w, h, root.attr("preserveAspectRatio").unwrap_or("")),
None => Affine::IDENTITY,
};
let style = Style::default().with(&root, &mut b.report);
b.children(&root, &base, &style, 1.0, 0, 0);
Ok(SvgImport { width: w, height: h, shapes: b.shapes, report: b.report })
let layers = b.layers();
Ok(SvgImport { width: w, height: h, layers, report: b.report })
}
/// The element's `id`, as an element name.
fn name_of(el: &X) -> String {
el.attr("id").unwrap_or("").chars().take(128).collect()
}
/// Whether `visibility` hides the element.
fn hidden(d: &[(String, String)]) -> bool {
get(d, "visibility").is_some_and(|v| v == "hidden" || v == "collapse")
}
/// An element name without its namespace prefix (`svg:path` → `path`).
@@ -347,16 +448,35 @@ fn paint_spec(v: &str) -> Option<PaintSpec> {
color(v).map(PaintSpec::Color)
}
/// Where a text chunk sits relative to its position (`text-anchor`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Anchor {
#[default]
Start,
Middle,
End,
}
/// Inherited presentation properties.
#[derive(Clone, Debug)]
struct Style {
fill: PaintSpec,
fill_opacity: f32,
fill_rule: FillRule,
clip_rule: FillRule,
stroke: PaintSpec,
stroke_opacity: f32,
stroke_width: f32,
current: Rgba,
/// The CSS `font-family` list, as written.
font_family: String,
font_size: f32,
bold: bool,
italic: bool,
anchor: Anchor,
letter_spacing: f32,
/// `xml:space="preserve"`: keep every space.
preserve: bool,
}
impl Default for Style {
@@ -365,20 +485,29 @@ impl Default for Style {
fill: PaintSpec::Color(Rgba::BLACK),
fill_opacity: 1.0,
fill_rule: FillRule::NonZero,
clip_rule: FillRule::NonZero,
stroke: PaintSpec::None,
stroke_opacity: 1.0,
stroke_width: 1.0,
current: Rgba::BLACK,
font_family: String::new(),
font_size: 16.0,
bold: false,
italic: false,
anchor: Anchor::Start,
letter_spacing: 0.0,
preserve: false,
}
}
}
/// An element's declarations: presentation attributes, overridden by `style=""`.
fn declarations(el: &X) -> Vec<(String, String)> {
const KEYS: [&str; 16] = [
const KEYS: &[&str] = &[
"fill",
"fill-opacity",
"fill-rule",
"clip-rule",
"stroke",
"stroke-opacity",
"stroke-width",
@@ -390,8 +519,17 @@ fn declarations(el: &X) -> Vec<(String, String)> {
"filter",
"clip-path",
"mask",
"mask-type",
"stop-color",
"stop-opacity",
"font-family",
"font-size",
"font-weight",
"font-style",
"text-anchor",
"letter-spacing",
"text-decoration",
"writing-mode",
];
let mut out: Vec<(String, String)> = KEYS.iter().filter_map(|k| el.attr(k).map(|v| (k.to_string(), v.trim().to_string()))).collect();
if let Some(style) = el.attr("style") {
@@ -419,6 +557,26 @@ fn opacity(v: &str) -> Option<f32> {
x.is_finite().then(|| x.clamp(0.0, 1.0))
}
/// A `font-size`: a keyword, a length, or relative to the parent's size (`em`, `ex`, `%`).
fn font_size(v: &str, parent: f32) -> Option<f32> {
let v = v.trim();
let keyword = match v {
"xx-small" => Some(9.0),
"x-small" => Some(10.0),
"small" => Some(13.0),
"medium" => Some(16.0),
"large" => Some(18.0),
"x-large" => Some(24.0),
"xx-large" => Some(32.0),
"larger" => Some(parent * 1.2),
"smaller" => Some(parent / 1.2),
_ => None,
};
let rel = |suffix: &str, k: f32| v.strip_suffix(suffix).and_then(|n| n.trim().parse::<f32>().ok()).map(|n| n * k);
let size = keyword.or_else(|| rel("em", parent)).or_else(|| rel("ex", parent * 0.5)).or_else(|| rel("%", parent / 100.0)).or_else(|| length(v, parent))?;
size.is_finite().then(|| size.clamp(0.0, 2000.0))
}
impl Style {
/// This style inherited by `el`, with `el`'s own declarations applied.
fn with(&self, el: &X, report: &mut Report) -> Style {
@@ -442,9 +600,53 @@ impl Style {
if let Some(w) = get(&d, "stroke-width").and_then(|v| length(v, 100.0)).filter(|w| *w >= 0.0) {
s.stroke_width = w;
}
match get(&d, "fill-rule") {
Some("evenodd") => s.fill_rule = FillRule::EvenOdd,
Some("nonzero") => s.fill_rule = FillRule::NonZero,
let rule = |v: Option<&str>, old: FillRule| match v {
Some("evenodd") => FillRule::EvenOdd,
Some("nonzero") => FillRule::NonZero,
_ => old,
};
s.fill_rule = rule(get(&d, "fill-rule"), s.fill_rule);
s.clip_rule = rule(get(&d, "clip-rule"), s.clip_rule);
if let Some(f) = get(&d, "font-family").filter(|f| !f.is_empty() && *f != "inherit") {
s.font_family = f.chars().take(512).collect();
}
if let Some(z) = get(&d, "font-size").and_then(|v| font_size(v, self.font_size)) {
s.font_size = z;
}
match get(&d, "font-weight") {
Some("bold" | "bolder") => s.bold = true,
Some("normal" | "lighter") => s.bold = false,
Some(n) => {
if let Ok(w) = n.trim().parse::<f32>() {
s.bold = w >= 600.0;
}
}
None => {}
}
match get(&d, "font-style") {
Some("italic" | "oblique") => s.italic = true,
Some("normal") => s.italic = false,
_ => {}
}
match get(&d, "text-anchor") {
Some("start") => s.anchor = Anchor::Start,
Some("middle") => s.anchor = Anchor::Middle,
Some("end") => s.anchor = Anchor::End,
_ => {}
}
match get(&d, "letter-spacing") {
Some("normal") => s.letter_spacing = 0.0,
Some(v) => {
let em = v.strip_suffix("em").and_then(|n| n.trim().parse::<f32>().ok()).map(|n| n * s.font_size);
if let Some(x) = em.or_else(|| length(v, s.font_size)).filter(|x| x.is_finite()) {
s.letter_spacing = x.clamp(-1000.0, 1000.0);
}
}
None => {}
}
match el.attr("xml:space") {
Some("preserve") => s.preserve = true,
Some("default") => s.preserve = false,
_ => {}
}
if get(&d, "stroke-dasharray").is_some_and(|v| v != "none") {
@@ -453,21 +655,34 @@ impl Style {
if get(&d, "filter").is_some_and(|v| v != "none") {
report.skip("filters");
}
if get(&d, "clip-path").is_some_and(|v| v != "none") || get(&d, "mask").is_some_and(|v| v != "none") {
report.skip("clip paths and masks (drawn unclipped)");
}
s
}
}
// ----- building ---------------------------------------------------------------------------------
/// Something drawn, and the clips (clip paths and masks) of everything around it, innermost
/// first. The clips are resolved into layers at the end ([`Builder::layers`]).
struct Item {
el: ImportedElement,
clips: Vec<Rc<clip::Region>>,
}
struct Builder<'a> {
ids: HashMap<&'a str, &'a X>,
report: Report,
shapes: Vec<ImportedShape>,
items: Vec<Item>,
/// The size percentages refer to (the viewBox, or the drawing size).
viewport: (f32, f32),
/// The fonts text is laid out with; this computer's, found on the first text.
fonts: Option<&'a Fonts>,
/// Font name → what it is on this computer, looked up once per name.
faces: HashMap<String, FaceMatch>,
/// Elements visited so far (see [`MAX_VISITS`]).
visits: usize,
/// The clip paths and masks being read, innermost last (a reference back to one of them is
/// a loop).
resolving: Vec<&'a X>,
}
impl<'a> Builder<'a> {
@@ -478,7 +693,14 @@ impl<'a> Builder<'a> {
}
fn node(&mut self, el: &'a X, parent: &Affine, inherited: &Style, alpha: f32, depth: usize, uses: usize) {
if depth > MAX_DEPTH || self.shapes.len() >= MAX_SHAPES {
if depth > MAX_DEPTH || self.items.len() >= MAX_SHAPES {
return;
}
self.visits += 1;
if self.visits > MAX_VISITS {
if self.visits == MAX_VISITS + 1 {
self.report.skip("parts of a drawing too complex to read (left out)");
}
return;
}
let d = declarations(el);
@@ -489,14 +711,11 @@ impl<'a> Builder<'a> {
// Containers that never draw by themselves.
match name {
"defs" | "linearGradient" | "radialGradient" | "stop" | "symbol" | "metadata" | "title" | "desc" | "clipPath" | "mask" | "marker" | "pattern" | "filter" | "script" => return,
anicraft_xml::TEXT_NODE => return,
"style" => {
self.report.skip("style sheets (inline styles are read)");
return;
}
"text" => {
self.report.skip("text elements");
return;
}
"image" => {
self.report.skip("images");
return;
@@ -510,6 +729,16 @@ impl<'a> Builder<'a> {
let style = inherited.with(el, &mut self.report);
let alpha = alpha * get(&d, "opacity").and_then(opacity).unwrap_or(1.0);
let m = parent.mul(&el.attr("transform").map_or(Affine::IDENTITY, transform));
let start = self.items.len();
self.draw(el, name, &d, &m, &style, alpha, depth, uses);
if self.items.len() > start {
self.clip(&d, &m, start, depth);
}
}
/// What `el` draws, into `items`.
#[allow(clippy::too_many_arguments)]
fn draw(&mut self, el: &'a X, name: &str, d: &[(String, String)], m: &Affine, style: &Style, alpha: f32, depth: usize, uses: usize) {
match name {
"svg" if depth > 0 => {
// A nested viewport: x/y offset, then its own viewBox.
@@ -523,9 +752,9 @@ impl<'a> Builder<'a> {
None => Affine::IDENTITY,
};
let m = m.mul(&Affine::translate(x, y)).mul(&inner);
self.children(el, &m, &style, alpha, depth, uses);
self.children(el, &m, style, alpha, depth, uses);
}
"svg" | "g" | "a" | "switch" => self.children(el, &m, &style, alpha, depth, uses),
"svg" | "g" | "a" | "switch" => self.children(el, m, style, alpha, depth, uses),
"use" => {
let href = el.attr("href").or_else(|| el.attr("xlink:href")).unwrap_or("").trim_start_matches('#');
let Some(target) = self.ids.get(href).copied() else {
@@ -544,29 +773,42 @@ impl<'a> Builder<'a> {
let inner = style.with(target, &mut self.report);
self.children(target, &m, &inner, alpha, depth, uses + 1);
} else {
self.node(target, &m, &style, alpha, depth + 1, uses + 1);
self.node(target, &m, style, alpha, depth + 1, uses + 1);
}
}
"text" => {
if hidden(d) {
return;
}
for el in self.text(el, m, style, alpha) {
self.items.push(Item { el, clips: Vec::new() });
}
}
_ => {
let Some((path, closed_shape)) = self.geometry(el, name) else { return };
if !m.is_finite() || path.is_empty() {
return;
}
if get(&d, "visibility").is_some_and(|v| v == "hidden" || v == "collapse") {
if !m.is_finite() || path.is_empty() || hidden(d) {
return;
}
let bounds = path.bounds();
let fill = if closed_shape { self.paint(&style.fill, style.fill_opacity, &style, &bounds) } else { None };
let stroke = self.stroke(&style, &bounds);
let fill = if closed_shape { self.paint(&style.fill, style.fill_opacity, style, &bounds) } else { None };
let stroke = self.stroke(style, &bounds);
if fill.is_none() && stroke.is_none() {
return;
}
self.shapes.push(ImportedShape {
name: el.attr("id").unwrap_or("").chars().take(128).collect(),
transform: m,
alpha,
shape: Shape { path: Arc::new(path), fill, stroke, fill_rule: style.fill_rule },
});
let shape = Shape { path: Arc::new(path), fill, stroke, fill_rule: style.fill_rule };
self.items.push(Item { el: ImportedElement { name: name_of(el), transform: *m, alpha, kind: ElementKind::Shape(shape) }, clips: Vec::new() });
}
}
}
/// The fonts to lay text out with: the ones given, else this computer's (scanned once).
fn fonts(&mut self) -> &'a Fonts {
match self.fonts {
Some(f) => f,
None => {
let f = Fonts::get();
self.fonts = Some(f);
f
}
}
}
+31 -5
View File
@@ -1,10 +1,36 @@
use super::*;
fn imp(svg: &str) -> SvgImport {
match import(svg.as_bytes()) {
/// An imported shape, flattened out of its layer.
#[derive(Clone, Debug)]
struct ImportedShape {
name: String,
transform: Affine,
alpha: f32,
shape: Shape,
}
/// An import whose layers are flattened into its shapes.
#[derive(Clone, Debug)]
struct Flat {
width: f32,
height: f32,
shapes: Vec<ImportedShape>,
report: Report,
}
fn imp(svg: &str) -> Flat {
let i = match import_with_fonts(svg.as_bytes(), &Fonts::from_faces(Vec::new())) {
Ok(i) => i,
Err(e) => panic!("{e}: {svg}"),
}
};
let shapes = i
.elements()
.filter_map(|e| match &e.kind {
ElementKind::Shape(s) => Some(ImportedShape { name: e.name.clone(), transform: e.transform, alpha: e.alpha, shape: s.clone() }),
_ => None,
})
.collect();
Flat { width: i.width, height: i.height, shapes, report: i.report }
}
fn solid(s: &ImportedShape) -> Rgba {
@@ -82,7 +108,7 @@ fn gradients_in_both_unit_systems_with_inherited_stops() {
<circle cx="50" cy="50" r="25" fill="url(#r)" fill-opacity="0.5"/>
<rect width="5" height="5" fill="url(#nothing) red"/>
</svg>"##);
let i = SvgImport { shapes: i.shapes[1..].to_vec(), ..i };
let i = Flat { shapes: i.shapes[1..].to_vec(), ..i };
match &i.shapes[0].shape.fill {
Some(Paint::Linear { start, end, stops }) => {
assert_eq!((*start, *end), (Vec2::new(20.0, 10.0), Vec2::new(60.0, 10.0)), "bounding-box units map onto the shape");
@@ -121,7 +147,7 @@ fn use_references_and_reported_leftovers() {
assert_eq!(first.transform.apply(Vec2::new(0.0, 0.0)), Vec2::new(10.0, 20.0));
assert_eq!(solid(first), Rgba::hex(0x123456));
assert_eq!(i.shapes.len(), 4, "the dot, the symbol's two rects and the plain rect");
for k in ["text elements", "images", "references to missing elements", "dashed strokes (drawn solid)", "filters", "clip paths and masks (drawn unclipped)", "style sheets (inline styles are read)"] {
for k in ["text (no fonts on this computer)", "images", "references to missing elements", "dashed strokes (drawn solid)", "filters", "references to missing clip paths (drawn unclipped)", "style sheets (inline styles are read)"] {
assert_eq!(i.report.skipped.get(k), Some(&1), "{k}: {:?}", i.report);
}
assert!(i.report.summary().starts_with("Imported. Not yet supported: "));
+320
View File
@@ -0,0 +1,320 @@
//! SVG text (`text`, `tspan`) → text blocks laid out by `anicraft-text` (ADR 0021).
//!
//! SVG places text in chunks: a chunk starts at the `text` element and at every `tspan` with
//! an absolute `x`, and runs on until the next one. Each chunk becomes one single-line text
//! block, placed by its baseline (`x`, `y`, plus a leading `dx`/`dy`) and its `text-anchor`.
//! An AniCraft block has one style, so a chunk whose pieces differ in style takes the style of
//! most of its visible characters, and the report counts it (as in ADR 0014). Whitespace is
//! collapsed as browsers do, unless `xml:space="preserve"`.
use crate::{Anchor, Builder, ImportedElement, PaintSpec, Style, declarations, get, hidden, length, local, name_of};
use anicraft_doc::{ElementKind, Paint, TextAlign, TextBlock};
use anicraft_geom::{Affine, Rect};
use anicraft_text::{Align, FaceMatch, Fonts, MAX_CHARS, TextError};
use anicraft_xml::Element as X;
use std::sync::Arc;
/// Most chunks read from one `text` element.
const MAX_CHUNKS: usize = 10_000;
/// Deepest nesting of `tspan`s read.
const MAX_TSPAN_DEPTH: usize = 32;
/// A run of text that starts at one position.
struct Chunk {
x: f32,
y: f32,
anchor: Anchor,
pieces: Vec<(String, Style)>,
chars: usize,
}
impl Chunk {
fn has_text(&self) -> bool {
self.pieces.iter().any(|(t, _)| !t.trim().is_empty())
}
}
/// What a `text` element used that AniCraft draws differently, reported once per element.
#[derive(Default)]
struct Flags {
per_char: bool,
rotated: bool,
on_path: bool,
decorated: bool,
vertical: bool,
cut: bool,
}
/// Whether two pieces would be drawn the same.
fn same_look(a: &Style, b: &Style) -> bool {
a.font_family == b.font_family && a.font_size == b.font_size && a.bold == b.bold && a.italic == b.italic && a.fill == b.fill && a.fill_opacity == b.fill_opacity && a.letter_spacing == b.letter_spacing
}
/// The CSS generic family a name stands for, as the device font `anicraft-text` knows.
fn generic(name: &str) -> Option<&'static str> {
match name.to_ascii_lowercase().as_str() {
"sans-serif" | "system-ui" | "ui-sans-serif" | "ui-rounded" | "-apple-system" | "blinkmacsystemfont" | "cursive" | "fantasy" => Some("_sans"),
"serif" | "ui-serif" => Some("_serif"),
"monospace" | "ui-monospace" => Some("_typewriter"),
_ => None,
}
}
/// The names in a `font-family` list, unquoted.
fn families(css: &str) -> Vec<String> {
css.split(',').map(|n| n.trim().trim_matches(['"', '\'']).trim().to_string()).filter(|n| !n.is_empty()).take(16).collect()
}
/// Collapses whitespace across the chunks as browsers do: line breaks and tabs are spaces,
/// runs of spaces are one, and spaces at the start go. `xml:space="preserve"` keeps them.
fn collapse(chunks: &mut [Chunk]) {
let mut prev_space = true;
for c in chunks {
for (t, st) in &mut c.pieces {
let mut out = String::with_capacity(t.len());
for ch in t.chars() {
let ch = if matches!(ch, '\n' | '\r' | '\t') { ' ' } else { ch };
if st.preserve {
out.push(ch);
} else if ch == ' ' {
if !prev_space {
out.push(' ');
}
} else {
out.push(ch);
}
prev_space = ch == ' ';
}
*t = out;
}
}
}
impl<'a> Builder<'a> {
/// The text blocks of a `text` element (whose own style is `style`), placed by `m`.
pub(crate) fn text(&mut self, el: &'a X, m: &Affine, style: &Style, alpha: f32) -> Vec<ImportedElement> {
let mut chunks: Vec<Chunk> = Vec::new();
let mut flags = Flags::default();
self.text_content(el, style, &mut chunks, &mut flags, 0);
collapse(&mut chunks);
let report = [
(flags.per_char, "per-character text positions (ignored)"),
(flags.rotated, "rotated characters (drawn upright)"),
(flags.on_path, "text on a path"),
(flags.decorated, "underlined or struck-through text (lines left out)"),
(flags.vertical, "vertical text (drawn horizontal)"),
(flags.cut, "text cut to 100,000 characters per block"),
];
for (on, what) in report {
if on {
self.report.skip(what);
}
}
let mut out = Vec::new();
for c in chunks {
if !c.has_text() {
continue;
}
// The style most of the visible characters have (the first on a tie).
let mut totals: Vec<(usize, usize)> = Vec::new();
for (i, (t, st)) in c.pieces.iter().enumerate() {
let n = t.chars().filter(|ch| !ch.is_whitespace()).count();
match totals.iter_mut().find(|(j, _)| c.pieces.get(*j).is_some_and(|(_, s)| same_look(s, st))) {
Some(e) => e.1 += n,
None => totals.push((i, n)),
}
}
let mut best: Option<(usize, usize)> = None;
for &(i, n) in &totals {
if best.is_none_or(|(_, b)| n > b) {
best = Some((i, n));
}
}
if totals.iter().filter(|(_, n)| *n > 0).count() > 1 {
self.report.skip("text with mixed styles (drawn in its main style)");
}
let Some((_, st)) = best.and_then(|(i, _)| c.pieces.get(i)) else { continue };
let st = st.clone();
let text: String = c.pieces.iter().map(|(t, _)| t.as_str()).collect();
match self.text_block(text, &st, alpha) {
Ok(Some((block, ascent))) => {
let w = block.box_width;
let shift = match c.anchor {
Anchor::Start => 0.0,
Anchor::Middle => -w * 0.5,
Anchor::End => -w,
};
let transform = m.mul(&Affine::translate(c.x + shift, c.y - ascent));
if !transform.is_finite() {
continue;
}
let name = if out.is_empty() { name_of(el) } else { String::new() };
let block_alpha = alpha;
let block = TextBlock { align: match c.anchor { Anchor::Start => TextAlign::Left, Anchor::Middle => TextAlign::Center, Anchor::End => TextAlign::Right }, ..block };
out.push(ImportedElement { name, transform, alpha: block_alpha, kind: ElementKind::Text(Arc::new(block)) });
}
Ok(None) => {}
Err(()) => break,
}
}
out
}
/// Reads `el`'s positions and content into chunks.
fn text_content(&mut self, el: &'a X, style: &Style, chunks: &mut Vec<Chunk>, flags: &mut Flags, depth: usize) {
let (vw, vh) = self.viewport;
let list = |key: &str, reference: f32| -> Vec<f32> { el.attr(key).map(|v| v.split([' ', ',', '\t', '\n', '\r']).filter(|p| !p.is_empty()).filter_map(|p| length(p, reference)).collect()).unwrap_or_default() };
let (xs, ys, dxs, dys) = (list("x", vw), list("y", vh), list("dx", vw), list("dy", vh));
if xs.len() > 1 || ys.len() > 1 || dxs.len() > 1 || dys.len() > 1 {
flags.per_char = true;
}
flags.rotated |= el.attr("rotate").is_some_and(|r| r.split([' ', ',']).any(|v| v.trim().parse::<f32>().is_ok_and(|a| a != 0.0)));
let d = declarations(el);
flags.decorated |= get(&d, "text-decoration").is_some_and(|v| v != "none");
flags.vertical |= get(&d, "writing-mode").is_some_and(|v| v.starts_with("tb") || v.starts_with("vertical"));
let root = depth == 0;
if root || !xs.is_empty() {
if chunks.len() >= MAX_CHUNKS {
flags.cut = true;
return;
}
let y = ys.first().copied().or_else(|| chunks.last().map(|c| c.y)).unwrap_or(0.0);
chunks.push(Chunk { x: xs.first().copied().unwrap_or(0.0), y, anchor: style.anchor, pieces: Vec::new(), chars: 0 });
} else if let Some(&y) = ys.first() {
// A new line without a new x continues after the text before it, which only the
// layout knows: kept on the line when there is text already.
match chunks.last_mut() {
Some(c) if !c.has_text() => c.y = y,
_ => flags.per_char = true,
}
}
let (dx, dy) = (dxs.first().copied().unwrap_or(0.0), dys.first().copied().unwrap_or(0.0));
if dx != 0.0 || dy != 0.0 {
match chunks.last_mut() {
Some(c) if !c.has_text() => {
c.x += dx;
c.y += dy;
}
_ => flags.per_char = true,
}
}
for child in &el.children {
match local(&child.name) {
anicraft_xml::TEXT_NODE => {
let Some(c) = chunks.last_mut() else { continue };
let room = MAX_CHARS.saturating_sub(c.chars);
let n = child.text.chars().count();
if n > room {
flags.cut = true;
}
c.chars += n.min(room);
c.pieces.push((child.text.chars().take(room).collect(), style.clone()));
}
"tspan" | "a" => {
let cd = declarations(child);
if get(&cd, "display") == Some("none") || hidden(&cd) || depth >= MAX_TSPAN_DEPTH {
continue;
}
let st = style.with(child, &mut self.report);
self.text_content(child, &st, chunks, flags, depth + 1);
}
"textPath" => flags.on_path = true,
_ => {}
}
}
}
/// Lays one chunk out: the block (aligned left, at the origin) and its first baseline.
/// `Ok(None)` draws nothing; `Err` means no text can be laid out at all.
fn text_block(&mut self, text: String, st: &Style, alpha: f32) -> Result<Option<(TextBlock, f32)>, ()> {
if st.font_size <= 0.0 || alpha <= 0.0 {
return Ok(None);
}
let unit = Rect::new(0.0, 0.0, 1.0, 1.0);
let color = match self.paint(&st.fill, st.fill_opacity, st, &unit) {
None => {
if st.stroke != PaintSpec::None {
self.report.skip("outlined text without a fill (left out)");
}
return Ok(None);
}
Some(Paint::Solid(c)) => c,
Some(other) => {
self.report.skip("gradient-filled text (drawn in one colour)");
other.primary_color()
}
};
if st.stroke != PaintSpec::None && st.stroke_width > 0.0 {
self.report.skip("strokes on text (left out)");
}
let fonts = self.fonts();
let face = self.face(fonts, &st.font_family);
let style = anicraft_text::Style {
family: face.family.clone().unwrap_or_default(),
size: st.font_size,
bold: st.bold || face.bold,
italic: st.italic || face.italic,
align: Align::Left,
letter_spacing: st.letter_spacing,
line_spacing: 0.0,
width: None,
};
let layout = match fonts.layout(&text, &style) {
Ok(l) => l,
Err(TextError::NoFonts) => {
self.report.skip("text (no fonts on this computer)");
return Err(());
}
Err(TextError::TooLong) => {
self.report.skip("text cut to 100,000 characters per block");
return Ok(None);
}
};
// A family that isn't installed falls back to the default, as the text engine does
// (ADR 0012), and the report names it.
if face.family.is_none() && !face.wanted.is_empty() {
self.report.missing_fonts.insert(face.wanted.clone());
self.report.fallback_font.get_or_insert_with(|| layout.family.clone());
}
let ascent = layout.ascent;
let block = TextBlock {
text,
font: layout.family,
size: style.size,
bold: style.bold,
italic: style.italic,
color,
align: TextAlign::Left,
letter_spacing: style.letter_spacing,
line_spacing: 0.0,
width: None,
outline: Arc::new(layout.outline),
box_width: layout.width,
box_height: layout.height,
};
Ok(Some((block, ascent)))
}
/// The installed face for a `font-family` list: its first installed family, or (when none
/// is) the first named family, uninstalled, for the report. No family is serif, as in
/// browsers.
fn face(&mut self, fonts: &Fonts, css: &str) -> FaceMatch {
let mut names = families(css);
if names.is_empty() {
names.push("serif".into());
}
let mut first: Option<FaceMatch> = None;
for n in &names {
let key = generic(n).unwrap_or(n);
let m = self.faces.entry(key.to_string()).or_insert_with(|| fonts.find_face(key)).clone();
if m.family.is_some() {
return m;
}
if first.is_none() && generic(n).is_none() {
first = Some(m);
}
}
// Only generic families, none installed: the default family, nothing to report.
first.unwrap_or(FaceMatch { family: None, wanted: String::new(), bold: false, italic: false })
}
}
+117
View File
@@ -0,0 +1,117 @@
//! SVG text → text blocks (ADR 0021), laid out with this computer's fonts.
use super::*;
use anicraft_doc::{TextAlign, TextBlock};
/// This computer's fonts, or `None` (and the test passes) on one without fonts.
fn fonts() -> Option<&'static Fonts> {
let f = Fonts::get();
f.resolve("").map(|_| f)
}
fn texts(svg: &str, fonts: &Fonts) -> (Vec<(ImportedElement, TextBlock)>, Report) {
let i = match import_with_fonts(svg.as_bytes(), fonts) {
Ok(i) => i,
Err(e) => panic!("{e}"),
};
let t = i
.elements()
.filter_map(|e| match &e.kind {
ElementKind::Text(t) => Some((e.clone(), (**t).clone())),
_ => None,
})
.collect();
(t, i.report)
}
/// Drawing-space bounds of a block's glyphs.
fn ink(e: &ImportedElement, t: &TextBlock) -> Rect {
t.outline.bounds().transformed(&e.transform)
}
#[test]
fn text_sits_on_its_baseline_in_its_style() {
let Some(fonts) = fonts() else { return };
let (t, report) = texts(r##"<svg width="300" height="100"><text id="title" x="10" y="50" font-family="'Zz No Such Face', sans-serif" font-size="24" font-weight="700" fill="#f00" fill-opacity="0.5" letter-spacing="2">Hello</text></svg>"##, fonts);
assert_eq!(t.len(), 1);
let (e, b) = &t[0];
assert_eq!((e.name.as_str(), b.text.as_str(), b.size, b.bold, b.italic, b.letter_spacing), ("title", "Hello", 24.0, true, false, 2.0));
assert_eq!(b.color, Rgba::hex(0xff0000).with_alpha(0.5));
assert_eq!(b.font, fonts.find_face("_sans").family.unwrap(), "the first installed family of the list");
let r = ink(e, b);
assert!((r.max.y - 50.0).abs() < 1.5, "letters stand on the baseline: {r:?}");
assert!(r.min.x >= 9.0 && r.min.x < 14.0, "{r:?}");
assert!(report.missing_fonts.is_empty(), "a later family in the list is installed: {report:?}");
assert!(report.skipped.is_empty(), "{report:?}");
}
#[test]
fn anchors_chunks_and_whitespace() {
let Some(fonts) = fonts() else { return };
let (t, report) = texts(
r##"<svg width="400" height="200" font-family="sans-serif">
<text x="200" y="40" text-anchor="middle" font-size="20"> Centred
title </text>
<text x="390" y="80" text-anchor="end" font-size="20">Right</text>
<text transform="translate(10 100)" font-size="16"><tspan x="0" y="0">Line one</tspan><tspan x="0" y="24" font-style="italic">Line two</tspan></text>
<text x="10" y="180" font-size="16" dx="5">Mostly plain <tspan font-weight="bold">bold</tspan> words</text>
</svg>"##,
fonts,
);
let words: Vec<&str> = t.iter().map(|(_, b)| b.text.as_str()).collect();
assert_eq!(words, ["Centred title ", "Right", "Line one", "Line two", "Mostly plain bold words"]);
let (e, b) = &t[0];
let c = ink(e, b).center().x;
assert!((c - 200.0).abs() < 2.0, "middle anchor centres the line: {c}");
assert_eq!(b.align, TextAlign::Center);
let r = ink(&t[1].0, &t[1].1);
assert!((r.max.x - 390.0).abs() < 2.0 && t[1].1.align == TextAlign::Right, "end anchor: {r:?}");
// Each positioned tspan is its own block, placed through the text's transform.
let (l1, l2) = (ink(&t[2].0, &t[2].1), ink(&t[3].0, &t[3].1));
assert!((l1.max.y - 100.0).abs() < 5.0 && (l2.max.y - 124.0).abs() < 5.0, "{l1:?} {l2:?}");
assert!(t[3].1.italic && !t[2].1.italic);
// A leading dx moves the chunk; the bold word is drawn in the main style and counted.
assert!(ink(&t[4].0, &t[4].1).min.x >= 14.0);
assert!(!t[4].1.bold);
assert_eq!(report.skipped.get("text with mixed styles (drawn in its main style)"), Some(&1), "{report:?}");
}
#[test]
fn missing_fonts_and_unsupported_text_are_reported() {
let Some(fonts) = fonts() else { return };
let (t, report) = texts(
r##"<svg width="400" height="200">
<text x="0" y="20" font-family="Zz Missing Face" font-size="12">One</text>
<text x="0" y="40" style="font-family: 'Zz Missing Face'; text-decoration: underline">Two</text>
<text x="0 10 20" y="60" stroke="#000">Three</text>
<text x="0" y="80"><textPath href="#p">Four</textPath></text>
<text x="0" y="100" fill="none" stroke="red">Outline</text>
<text x="0" y="120"> </text>
<text x="0" y="140" font-size="0">Tiny</text>
</svg>"##,
fonts,
);
assert_eq!(t.len(), 3, "{:?}", t.iter().map(|(_, b)| &b.text).collect::<Vec<_>>());
assert_eq!(report.missing_fonts.iter().map(String::as_str).collect::<Vec<_>>(), ["Zz Missing Face"]);
assert!(fonts.families().contains(report.fallback_font.as_ref().unwrap()));
assert!(report.summary().contains("Fonts not on this computer, drawn in"), "{}", report.summary());
for k in ["underlined or struck-through text (lines left out)", "per-character text positions (ignored)", "strokes on text (left out)", "text on a path", "outlined text without a fill (left out)"] {
assert_eq!(report.skipped.get(k), Some(&1), "{k}: {report:?}");
}
}
#[test]
fn text_can_be_a_clip_and_needs_fonts() {
let none = Fonts::from_faces(Vec::new());
let (t, report) = texts(r#"<svg width="10" height="10"><text>Hi</text></svg>"#, &none);
assert!(t.is_empty());
assert_eq!(report.skipped.get("text (no fonts on this computer)"), Some(&1));
let Some(fonts) = fonts() else { return };
let i = import_with_fonts(
br##"<svg width="300" height="100"><clipPath id="word"><text x="10" y="60" font-size="48" font-family="sans-serif">REVEAL</text></clipPath><rect width="300" height="100" fill="#4fa3ff" clip-path="url(#word)"/></svg>"##,
fonts,
)
.unwrap();
let mask = i.layers.iter().find_map(|l| l.mask.as_ref()).expect("a mask layer");
assert!(matches!(&mask.elements[0].kind, ElementKind::Text(b) if b.text == "REVEAL"), "the mask stays editable text");
}
+8 -1
View File
@@ -70,6 +70,9 @@ pub struct Layout {
/// line that continued the block would start `lines × line_height` below its top.
pub lines: usize,
pub line_height: f32,
/// From the top of the box to the first line's baseline (pixels), for placing text by its
/// baseline, as SVG does.
pub ascent: f32,
}
/// What a font name written by another program means on this computer: a PostScript name
@@ -366,7 +369,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option<Layout>
}
}
let height = (lines.len().max(1) as f32 - 1.0) * line_height + (metrics.ascent - metrics.descent);
Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing, lines: lines.len().max(1), line_height })
Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing, lines: lines.len().max(1), line_height, ascent })
}
/// Draws glyph outlines (font space, y up) into a path (pixels, y down) at a pen position.
@@ -518,5 +521,9 @@ mod tests {
assert!((one.line_height - three.line_height).abs() < 1e-3 && one.line_height >= 10.0);
assert!((three.height - one.height - 2.0 * one.line_height).abs() < 0.01);
assert_eq!(fonts.layout("", &style(20.0)).unwrap().lines, 1);
// The first baseline is inside the box, below its top by most of a line.
assert!(one.ascent > 10.0 && one.ascent < one.height, "{} in {}", one.ascent, one.height);
let b = one.outline.bounds();
assert!(b.max.y > one.ascent - 1.0 && b.min.y < one.ascent, "glyphs sit on the baseline: {b:?}");
}
}
+46 -3
View File
@@ -61,10 +61,17 @@ pub enum XmlError {
Syntax(usize, &'static str),
}
/// The name of the pseudo-elements that hold character data in mixed content (see
/// [`parse_mixed`]).
pub const TEXT_NODE: &str = "#text";
struct P<'a> {
s: &'a [u8],
i: usize,
count: usize,
/// Elements (by name without namespace prefix) whose character data is also kept in order
/// among their children, as [`TEXT_NODE`] children.
mixed: &'a [&'a str],
}
impl P<'_> {
@@ -193,9 +200,21 @@ impl P<'_> {
None => return self.err("unexpected end inside a tag"),
}
}
// Content: children until the matching end tag.
// Content: children until the matching end tag. In mixed content each stretch of
// character data also becomes a text node, so it keeps its place among the children.
let local = el.name.rsplit(':').next().unwrap_or(&el.name);
let mixed = self.mixed.contains(&local);
loop {
let before = el.text.len();
self.skip_misc(Some(&mut el.text))?;
if mixed && el.text.len() > before {
self.count += 1;
if self.count > MAX_ELEMENTS {
return Err(XmlError::TooMany);
}
let text = el.text.get(before..).unwrap_or_default().to_string();
el.children.push(Element { name: TEXT_NODE.to_string(), text, ..Element::default() });
}
if self.peek().is_none() {
return self.err("missing end tag");
}
@@ -207,7 +226,7 @@ impl P<'_> {
return self.err("mismatched end tag");
}
self.i += 1;
if !el.children.is_empty() && el.text.trim().is_empty() {
if !mixed && !el.children.is_empty() && el.text.trim().is_empty() {
el.text = String::new();
}
return Ok(el);
@@ -262,12 +281,20 @@ fn unescape(s: &str) -> String {
/// Parses a document and returns its root element.
pub fn parse(src: &[u8]) -> Result<Element, XmlError> {
parse_mixed(src, &[])
}
/// Parses a document whose `mixed` elements (named without namespace prefix, such as SVG's
/// `text` and `tspan`) have mixed content: their character data is also kept among their
/// children, in order, as [`TEXT_NODE`] elements whose `text` is that stretch (whitespace
/// included). Everything else is read as [`parse`] reads it.
pub fn parse_mixed(src: &[u8], mixed: &[&str]) -> Result<Element, XmlError> {
if src.len() > MAX_INPUT {
return Err(XmlError::TooLarge);
}
// A UTF-8 byte-order mark is allowed.
let src = src.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(src);
let mut p = P { s: src, i: 0, count: 0 };
let mut p = P { s: src, i: 0, count: 0, mixed };
p.skip_misc(None)?;
if p.peek().is_none() {
return p.err("no root element");
@@ -308,6 +335,22 @@ mod tests {
assert_eq!(texts, ["a <b>\rline 2", " ", "x<yz"]);
}
#[test]
fn mixed_content_keeps_text_in_order() {
let x = b"<svg><text x='1'>Hello <tspan>big</tspan> world&amp;<!-- c --> more</text>
<g>
</g></svg>";
let root = parse_mixed(x, &["text", "tspan"]).unwrap();
let t = &root.children[0];
let parts: Vec<(&str, &str)> = t.children.iter().map(|c| (c.name.as_str(), c.text.as_str())).collect();
assert_eq!(parts, [(TEXT_NODE, "Hello "), ("tspan", "big"), (TEXT_NODE, " world& more")]);
assert_eq!(t.children[1].children.len(), 1, "a tspan's own text is a node too");
assert_eq!(t.text, "Hello world& more", "the concatenation is kept as before");
assert_eq!(root.children.len(), 2, "elements not listed keep dropping whitespace");
assert!(root.children[1].children.is_empty());
assert_eq!(parse(x).unwrap().children[0].children.len(), 1, "plain parsing makes no text nodes");
}
#[test]
fn malformed_input_is_an_error_not_a_panic() {
for bad in [&b""[..], b"<", b"<a", b"<a b>", b"<a b='1>", b"<a></b>", b"<a><b></a>", b"<!-- open", b"<a>\xff\xfe"] {
+113
View File
@@ -0,0 +1,113 @@
# ADR 0019: GPU stage renderer (first slice)
* Status: accepted (2026-11-09)
* Relates to: roadmap M3, ADR 0002 (render pipeline), ADR 0007 (tiled stage), AGENTS.md rule 4
(the CPU renderer is the oracle)
## Context
The stage draws on the CPU (ADR 0002): 15 ms for a 1080p frame of 10k shapes on 32 threads,
about 18 ms for a simple scene at 4K. M3 asks for a wgpu renderer behind a feature flag that
draws the same display list, checked pixel for pixel against the CPU oracle, with the oracle
staying the default until parity is at most 1/255 mean error. egui already brings wgpu 30
(through `egui-wgpu`), so a second graphics stack is out of the question.
Parity is the hard requirement. The oracle computes **exact analytic area coverage** (signed
area accumulation, ADR 0002) in f32, with its own flattening, stroker and 256-entry gradient
tables. Any GPU approach that approximates coverage differently (MSAA, stencil-and-cover,
distance fields) disagrees with it at every anti-aliased edge.
## Options considered
| Option | Parity with the oracle | Work for a first slice | Verdict |
|---|---|---|---|
| Stencil-and-cover with 4×/8× MSAA (triangle fans into a stencil, then a covering quad) | Coverage quantized to 1/4 or 1/8: errors up to ±1/16 at every edge; fine mean, poor max | small | no: the max error never converges, and parity is the point |
| Full GPU pipeline as in Vello (flatten, bin, coarse and fine all in compute) | exact coverage in principle, but our flattening and stroker would be reimplemented in WGSL and drift from the oracle's | large (several shader stages, GPU prefix sums, dynamic memory) | later, stage by stage |
| **CPU prepares and bins, GPU computes coverage and composites** (the "hybrid" split of the public sparse-strips work) | **the oracle's own geometry and paints; the same coverage integral; only f32 rounding differs** | moderate | **chosen** |
## Decision
1. **Same input as the oracle.** `anicraft_render::plain_fills(dl, view)` returns the fills
exactly as `render` prepares them: culled, flattened at the oracle's tolerance, strokes
outlined by the oracle's stroker, shaders built (solid colours premultiplied, gradients as
the oracle's 256-entry tables), pixel bounds clamped. The GPU path never re-derives
geometry or colour.
2. **Tile binning on the CPU** (`anicraft-gpu::binning`, parallel per chunk of fills, then
parallel per tile row). The surface is cut into 16 × 16 tiles. Edges are split at tile rows
and columns; each piece lands in the tile it crosses. What a piece contributes to the tiles
to its right is a winding change per pixel row (it lies wholly to their left), summed along
the tile row into a **backdrop** of 16 values, as in the public sparse-strips and Vello
designs. A fill's tile needs only its own pieces and its backdrop; tiles inside a shape
carry a backdrop and no pieces; tiles outside get nothing. Each tile lists its entries in
drawing order.
3. **One compute pass** (`fine.wgsl`): a workgroup per tile, an invocation per pixel. For each
entry, coverage = backdrop + Σ over the tile's pieces of the exact signed area of the pixel
to the right of the piece: the integral the oracle's accumulation buffer computes, written
as the mean of `clamp(u, 0, 1)` over the piece so it has no cancellation. Then the oracle's
fill rule fold, its `coverage > 1e-4` cut-off, the paint (gradient index rounded as the
oracle's table lookup) and src-over in premultiplied f32. Output is premultiplied RGBA8
rounded like `Pixmap::to_premul_rgba8` (the stage) or f32 (tests, exports later).
4. **What the plain path doesn't draw yet goes to the CPU, per frame (per tile).** Masks
(clips), group opacity, blend modes, filters and bitmap fills make `plain_fills` answer
`NeedsFull`; the render service then draws that tile with the oracle and records why.
The picture is always complete and always the oracle's when the GPU steps back.
5. **A headless device of our own**, high-performance adapter first, compute shaders and
downlevel limits required, with a startup **self-test** (a known 24 × 20 render must come
back exactly) before it is trusted. Errors are captured in thread-local error scopes per
render; uncaptured errors and device loss mark the renderer broken, and from then on the CPU
draws. Every call is behind `catch_unwind`. Owning the device (rather than sharing egui's)
keeps a GPU-stage failure from ever touching the window's device, works when the window
itself fell back to OpenGL, and lets tests run without a window.
6. **Layering.** `crates/gpu` is **L3**, beside the engine: it builds on the oracle's
preparation (L2), and the shell (L5) wires it in. The engine stays GPU-free: its
`RenderService` takes any `Rasterizer` (`Fn(&DisplayList, &View) -> Result<RGBA8, why>`),
and jobs are keyed by which rasterizer drew them, so switching renderers re-renders while
the old tiles stand in, and switching back finds the CPU's pictures still cached.
7. **Behind a feature, off by default.** `cargo run --features gpu-stage` adds Preferences ›
Stage › Renderer (and View › Stage Rendering): *CPU (reference)* or *GPU (preview)*. The
status bar says who drew the visible tiles and why the CPU stepped in ("CPU for masks").
`ANICRAFT_STAGE_RENDERER=gpu|cpu` overrides the preference (also in `--screenshot` runs).
**Exports always use the CPU oracle.**
8. **Parity tests** (`crates/gpu/src/tests.rs`): the sample scene at five frames and zooms, a
10k-shape stress frame, an offset zoomed 512 px stage tile, and analytic scenes (fractional
rectangles across tiles, a circle, even-odd and non-zero rings, a self-intersecting star,
rotated linear and radial gradients, wide and sub-pixel strokes, shapes far larger than the
surface with a colour effect). Bounds: mean ≤ 1/16 of the roadmap's 1/255 target and max ≤
2/255 on RGBA8; mean < 1e-4 and max < 4e-3 on f32. A second layer runs the shader's
arithmetic on the CPU over the binned scene, so the binning is checked on every machine,
GPU or not. Without an adapter the GPU tests print why and pass.
## Measured (2026-11-09, release, RTX 5090 over Vulkan, 32 threads)
`cargo run --release -p anicraft-gpu --example gpu_bench`. GPU ms is the whole call
(prepare + bin + upload, compute, readback). Parity is against the oracle on the same frame.
| Scene | Size | CPU oracle | GPU stage (prepare + bin + GPU) | Parity (mean / max) |
|---|---|---|---|---|
| Stress, 50 layers × 200 shapes (≈10k drawn) | 1920×1080 | 11.3 ms | 13.6–14.3 ms (3.1 + 5.0 + 4.6) | < 0.0001 / 1 (of 255) |
| Stress, 50 × 200 | 3840×2160 | 26.6–27.3 ms | 22.1–22.4 ms (2.8 + 8.0 + 8.4) | < 0.0001 / 1 |
| 1,000 shapes | 1920×1080 | 4.4–4.6 ms | 2.8–2.9 ms | < 0.0001 / 1 |
| 1,000 shapes | 3840×2160 | 17.4–17.8 ms | **8.8–9.0 ms** | < 0.0001 / 1 |
| Sample scene | 3840×2160 | 18.2 ms | 8.8 ms | < 0.0001 / 1 |
At most 0.06 % of pixels differ at all, each by one 8-bit step. The M3 target of 4K at 60 fps
for 1,000 shapes (16.7 ms) is met with room; the 10k-shape frame is CPU-bound in preparation
and binning. The GPU share at 4K is mostly the 33 MB readback.
## Consequences and next steps
* **Parity holds by construction** for everything the plain path draws: same geometry, same
paints, same coverage integral. A renderer change on either side shows up in the tests.
* The GPU stays opt-in until the steps below make it the faster choice everywhere; then it
becomes the stage default (the oracle stays the reference and the export path).
* Not in this slice, in order:
1. **No readback**: render into a texture egui shows directly (share egui's device through
`eframe`'s render state, or copy across devices), removing the largest fixed cost.
2. **Masks, group opacity and blend modes** on the GPU: clip coverage and group layers as
extra entry kinds in the same pass (the oracle's band algorithm maps onto tiles).
3. **Binning on the GPU** (Vello-style coarse rasterization with prefix sums) for scenes of
tens of thousands of shapes; buffer reuse across frames.
4. Bitmaps (textures and the oracle's bilinear sampling), filters (compute blurs), and GPU
exports once parity covers them.
* Shared-`target/` builds note: the GPU crate builds with the wgpu the shell already builds
(same version, default features), so it adds no second wgpu.
+82
View File
@@ -0,0 +1,82 @@
# ADR 0021: Clip paths, masks and text from SVG drawings
* Status: accepted (2026-11-09)
* Relates to: roadmap M4 (SVG import), ADR 0010 (mask layers), ADR 0012 (text), ADR 0014
(text from Animate documents)
## Context
Import to Stage (`file.import`, `crates/svg`) brought an SVG drawing across as shapes on one
layer, and reported `clipPath`, `mask` and `text` as skipped (drawn unclipped, or not at
all). Those three are everywhere in real drawings: design tools wrap every frame in a clip,
illustrations crop artwork into shapes, icons use masks, and posters and diagrams carry text.
AniCraft already has the models to receive them: mask layers (ADR 0010: a mask layer's fills
reveal the normal layers under it) and text blocks (ADR 0012), with the font lookup and
reporting written for Animate documents (ADR 0014). AniCraft's own SVG export writes masks
as `clipPath`s, so a masked frame should also come back.
SVG clipping is more general than mask layers: clips nest (a clipped group inside a clipped
group), apply to single shapes, and a `mask` is a soft luminance (or alpha) image, not an
area. The behaviour here comes from the W3C SVG 1.1 / SVG 2 and CSS Masking specifications
and from self-authored drawings.
## Decision
1. **A clipped drawing becomes a folder of layers.** The importer reads the drawing in
order and every drawn item collects the clip regions of the elements around it. At the end
consecutive items with the same effective clip form one run; a run with a clip is a masked
layer under a mask layer holding the clip's shapes. Import to Stage puts the runs, top
first, in a folder named after the file (inserted where a new layer would go, above the
active mask group if the active layer is masked). A drawing with no clips still makes one
layer named after the file, as before. Mask layers come in locked, so the stage shows the
clean result; unlocking shows their edge as for any mask (ADR 0010). One undo step.
2. **Resolve clips exactly, or say so.** A clip is the union of its shapes' fills
(`clip-rule`, transforms, `use`, `clipPathUnits`, a `clip-path` on the `clipPath` itself).
For each item: a convex clip that contains the item cuts nothing and is dropped (the frame
clip of design-tool exports), a clip that misses it hides it (left out). Several clips left
are intersected exactly when all but one are convex polygons, by clipping the remaining
clip's shapes against the polygons (Sutherland–Hodgman extended to Bézier segments,
`anicraft_geom::clip`: curves stay curves, holes and fill rules survive). Two curved clips
can't be intersected without general path booleans: the inner one is kept and the report
counts it. Mask layers ignore strokes and opacity, which matches clip paths exactly.
3. **Masks come across when they are coverage.** A `mask` whose content is opaque (fill alpha
and opacity 1, no strokes, no clips inside, and white for the default luminance masks; any
colour for `mask-type: alpha`) equals the area of its fills, cut to the mask's region
(`maskUnits`, `x`/`y`/`width`/`height`, default the bounding box grown by 10%), so it
becomes a mask layer the same way. Any other mask is soft: the artwork is drawn unmasked and
the report counts "soft, faded or coloured masks". Soft masks need per-pixel mask values in
the renderer; they wait for that.
4. **Text becomes text blocks, one per text chunk.** A chunk starts at a `text` and at every
`tspan` with an absolute `x`; it is one single-line block placed by its baseline (`x`, `y`,
a leading `dx`/`dy`; `anicraft-text` now reports the first baseline) and `text-anchor`
(start, middle, end, also kept as the block's alignment). Style: `font-family` (the first
installed family of the list, generic families mapped to `_sans`, `_serif`,
`_typewriter`), `font-size` (lengths, keywords, `em`/`%`), `font-weight` (600 and up is
bold), `font-style`, `letter-spacing`, `fill` and `fill-opacity`, and `opacity`.
Whitespace collapses as in browsers unless `xml:space="preserve"`. A chunk whose pieces
differ in style takes the style of most of its visible characters and is counted, as for
Animate text (ADR 0014). With no `font-family` the text is serif, as browsers draw it.
When no family of the list is installed, the text falls back to the default family and the
report names the first one ("Fonts not on this computer, drawn in Inter: Futura."). Text
inside a `clipPath` stays a text block on the mask layer, so the mask stays editable.
5. **Report, don't guess.** Per-character positions (lists of `x`, `y`, `dx`, `dy`; a new
`y` mid-line), `rotate`, `textPath`, text decoration, vertical writing modes, strokes and
gradients on text, CSS clip shapes and mask images, clips on a clip's contents, clip loops,
and more than 250 masks in one drawing (the rest drawn unclipped) are counted. Masks draw
their content again, so the work is bounded by a count of visited elements (2 million), not
by the file size.
6. **Ordered text needs mixed content.** The shared XML reader keeps character data in order
among the children of elements named by the caller (`anicraft_xml::parse_mixed`, as
`#text` nodes); other elements, and XFL, read as before.
## Consequences
* Masked frames exported as SVG come back as the same picture on mask layers (tested: pixel
identical at half size), and typical design-tool exports lose their redundant frame clips.
* Imported clips are editable as AniCraft masks: move, reshape or unlock them like any mask.
* A drawing with many clips makes many layers (two per masked run), inside one folder.
* Text in SVG files is laid out with this computer's fonts once, on import, then stored as
outlines like all text (ADR 0012).
* Not yet: soft (luminance and alpha) masks, booleans between two curved clips, per-character
positions and rotation, text on a path, multi-line blocks from stacked chunks, dashes
(another track owns strokes), images and style sheets.
+9 -4
View File
@@ -34,6 +34,7 @@ app/ workspace root; the root package is the desktop app
doc L1 Document model + timeline evaluation (keyframes, tweens, easing, symbols)
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; shell feature `gpu-stage`)
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
@@ -47,10 +48,11 @@ app/ workspace root; the root package is the desktop app
| L1 | `anicraft-doc` | geom, audio |
| L2 | `anicraft-render` | geom, doc, rayon, png |
| L3 | `anicraft-engine` | geom, doc, render, serde_json |
| L3 | `anicraft-gpu` | geom, doc, render, wgpu (the version egui brings), pollster, bytemuck |
| L4 | `anicraft-cli` | engine (+ lower) |
| L5 | `anicraft` (shell) | engine (+ lower), eframe/egui |
Planned crates: `gpu` (L2, wgpu renderer), `io` (L3, XFL/SVG/Lottie/GIF),
Planned crates: `io` (L3, XFL/SVG/Lottie/GIF),
`automation` (L4, MCP), `testkit`.
## 3. Document model (`anicraft-doc`)
@@ -136,9 +138,12 @@ DisplayList ──► for each item:
rasterizes 32-row bands in parallel, each compositing all ops that touch it, in order.
Output is bit-identical to serial. Numbers are in [performance.md](performance.md).
Planned (see roadmap): sparse-strip coverage for huge shapes, tile binning, a glyph atlas for
text, wgpu renderer with the same coverage model, filters on Movie Clips, mask layers through
coverage multiplication.
**GPU stage** ([ADR 0019](adr/0019-gpu-stage.md), behind the shell's `gpu-stage` feature):
`render::plain_fills` hands the oracle's own prepared fills to `anicraft-gpu`, which bins edge
pieces into 16 × 16 tiles with per-row backdrops (CPU, parallel) and computes each pixel's
exact area coverage and src-over in one compute pass. Display lists with masks, groups or
bitmaps are drawn by the oracle instead. The engine's `RenderService` takes any `Rasterizer`
and falls back to the oracle per job, so the engine itself never depends on the GPU.
## 5. Engine (`anicraft-engine`)
+6
View File
@@ -22,6 +22,12 @@ Sound output (ADR 0020) uses `cpal`, which on Linux and the BSDs builds against
(Arch, FreeBSD). `cargo build --no-default-features` leaves sound output out (playback is
silent; import, waveforms and audio export still work). Tests never open an audio device.
### GPU stage (optional)
`cargo run --features gpu-stage` adds Preferences › Stage › Renderer (ADR 0019). The
`anicraft-gpu` crate builds and tests in every build (its GPU tests skip without an adapter);
`cargo run --release -p anicraft-gpu --example gpu_bench` prints timings and parity.
## Build footprint (biased for disk space, then time)
Measured on Windows, 32 threads, offline, from an empty target directory:
+1 -1
View File
@@ -90,7 +90,7 @@ used.
|---|---|---|
| Rendering algorithms (coverage accumulation, Bézier flattening, Porter–Duff, gradients) | Decades-old published techniques. The coverage approach is from Apache-2.0 open source (font-rs), whose licence includes a patent grant. | Implement from public papers and permissively licensed references only; credit them in `ATTRIBUTION.md`. |
| Animation features (keyframes, classic tweens, easing, onion skin, symbols) | Long-standing prior art in animation software since the 1990s. | No feature copies a specific proprietary implementation. |
| GPU renderer (M3) | Planned design follows published, Apache/MIT-licensed work (e.g. Vello's sparse strips). | Same rule: public papers and permissive code only. |
| GPU renderer (M3) | **As built** (ADR 0019): tile binning with per-row backdrops and per-pixel exact area coverage, written from the public descriptions of Vello and the sparse-strips work (Apache-2.0 OR MIT) and our own oracle's coverage integral; no third-party shader or code copied. Uses `wgpu` (MIT OR Apache-2.0), `pollster` and `bytemuck`, all already in the tree through eframe; no new licence. | Same rule: public papers and permissive code only. |
| PNG, GIF, SVG, WebP | Royalty-free (GIF's LZW patents expired in 2003–2004). | OK to implement. |
| **Video export** | H.264/HEVC/AAC are covered by patent pools. VP9, AV1 and Opus are royalty-free. | **Never bundle encoders for patent-pool codecs.** MP4/H.264 only by piping to a user-installed ffmpeg. Default to WebM (VP9/AV1). **As built** (`file.export_video`): AniCraft starts the user's ffmpeg (found via a parameter, `ANICRAFT_FFMPEG` or the PATH) with an argument list, never a shell, writes raw RGBA frames to its stdin, and ships no codec code; the default file type is `.webm` (VP9). |
| **Sound** (M5, ADR 0020) | WAV/PCM is unencumbered; Vorbis and Opus are royalty-free; the MP3 patents expired in 2017; AAC is in a patent pool. | Decode WAV, Ogg Vorbis and MP3 in-process (pure-Rust, permissive decoders; no encoders). The video soundtrack is encoded by the user's ffmpeg: Opus for WebM (the default), AAC only for MP4, never by code we ship. Exported audio is uncompressed WAV. |
+22
View File
@@ -65,6 +65,27 @@ 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.
### GPU stage (M3, ADR 0019)
`cargo run --release -p anicraft-gpu --example gpu_bench` (2026-11-09, RTX 5090 over Vulkan,
32 threads). GPU ms is the whole call: preparing the fills (shared with the oracle), binning,
upload, the compute pass and the readback. Parity is mean / max difference from the oracle per
8-bit channel.
| Scene | Size | CPU oracle | GPU stage (prepare + bin + GPU) | Parity |
|---|---|---|---|---|
| Stress, 50 × 200 (≈10k drawn) | 1920×1080 | 11.3 ms | 13.6–14.3 ms (3.1 + 5.0 + 4.6) | < 0.0001 / 1 |
| Stress, 50 × 200 | 3840×2160 | 26.6–27.3 ms | 22.1–22.4 ms (2.8 + 8.0 + 8.4) | < 0.0001 / 1 |
| 1,000 shapes | 1920×1080 | 4.4–4.6 ms | 2.8–2.9 ms | < 0.0001 / 1 |
| 1,000 shapes (M3 target: 4K at 60 fps) | 3840×2160 | 17.4–17.8 ms | 8.8–9.0 ms ✅ | < 0.0001 / 1 |
| Sample scene | 3840×2160 | 18.2 ms | 8.8 ms | < 0.0001 / 1 |
Binning went from 16 ms to 5 ms on the stress frame by binning fills in chunks with reused
scratch (no allocation per edge piece), freeing the per-chunk buffers on the pool, and
scattering the tile lists in parallel per tile row. What is left: CPU binning on very large
scenes (next: GPU binning) and the 33 MB readback at 4K (next: render into the texture egui
shows).
### How budgets are enforced
* **Budgets that don't depend on the machine** (undo memory, snapshot sharing, file size,
@@ -100,3 +121,4 @@ buffer is tiny; the stage never waits on sound.
* [ADR 0002](adr/0002-render-pipeline.md): render worker, frame cache, band parallelism, culling
* [ADR 0003](adr/0003-file-format-v2.md): compact file format with shared paths
* [ADR 0015](adr/0015-crash-recovery-autosave.md): crash-recovery autosave on a worker thread
* [ADR 0019](adr/0019-gpu-stage.md): GPU stage renderer (first slice), parity with the oracle
+5 -5
View File
@@ -9,13 +9,13 @@ 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; 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. No GPU path yet. |
| 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; 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. Not yet: no-readback textures, masks/groups/blend on the GPU, GPU binning, bitmaps and filters, GPU exports; the CPU stays the default and the oracle. |
| 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, 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, 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). **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, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. Headless: `timeline.create_motion_tween`, `motion.*`. Not yet: motion paths on the stage, retiming keys, rescaling keys with the span, XFL motion-tween import. **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. **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. No brush or merge drawing yet. |
| 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`. Not yet: frame scripts, exporter and easing kinds, background runs with cancel, a binary document view. |
| 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). Not yet: sound effects (fades, panning, envelopes) and per-layer volume/mute, sounds inside symbols, sounds from XFL, audio in Lottie/HTML, 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, 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), 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). No per-character styles, motion tweens or shape hints from XFL yet; frame scripts are counted in the import report but not kept yet (ADR 0013); **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; unsupported parts are reported. **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). |
| 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, 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), 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). No per-character styles, motion tweens or shape hints from XFL yet; frame scripts are counted in the import report but not kept yet (ADR 0013); **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; soft masks, per-character positions, text on a path and dashes 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). |
| 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. **Preferences** window: interface and data fonts (bundled default or any installed font), interface scale, 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. |
@@ -29,7 +29,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~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; motion paths on stage, 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 | 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. |
| **M3** | GPU stage *(in progress)* | ~~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); next: no-readback textures, masks/groups/blend modes on the GPU, GPU binning; becomes the default stage renderer once it covers the display list and is faster everywhere. |
| **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~~ ✅ (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, 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; effects, volume and sounds in symbols later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅ and ~~blend modes~~ ✅ on Movie Clips (bevel and gradient filters later). |
| **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; HTML canvas runtime export; button states in test-movie preview; 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, Actions panel, `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. |
@@ -50,7 +50,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 renderer, first slice, behind a feature flag with parity tests | CPU oracle, tiled stage |
| M3 | GPU stage: no-readback textures, then masks, group opacity and blend modes on the GPU (first slice ✅, ADR 0019) | CPU oracle, tiled stage, GPU stage first slice |
| 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); next: frame scripts and Test Movie on the plug-in host | command registry, plug-in host |
@@ -79,7 +79,7 @@ Next, in order:
~~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
corpus checked by render tests.
2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅. Next for SVG: text, clip paths and masks (onto mask layers), dashes.
2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅, ~~text, clip paths and masks (onto mask layers)~~ ✅ (ADR 0021). Next for SVG: dashes, soft (luminance) masks, per-character text positions and text on a path.
## Risks
+9 -1
View File
@@ -770,7 +770,15 @@ impl App {
}
let n = v["elements"].as_u64().unwrap_or(0);
let report = v["report"].as_str().unwrap_or("");
self.status_ok(format!("{n} {} on a new layer. {report} Ctrl+Z to undo.", if n == 1 { "shape" } else { "shapes" }));
let what = if n == 1 { "element" } else { "elements" };
let undo = platform::shortcut_label("Ctrl+Z");
// A drawing with clip paths or masks comes in as a folder of layers (ADR 0021).
let place = match (v["layers"].as_u64().unwrap_or(1), v["masks"].as_u64().unwrap_or(0)) {
(0 | 1, _) => "on a new layer".to_string(),
(l, 1) => format!("in a new folder of {l} layers with a mask"),
(l, m) => format!("in a new folder of {l} layers with {m} masks"),
};
self.status_ok(format!("{n} {what} {place}. {report} {undo} to undo."));
}
"file.export_sprite_sheet" => self.status_ok(format!("Exported {} frames to {} ({}×{} grid) and its frame map {}", v["frames"], v["written"].as_str().unwrap_or(""), v["columns"], v["rows"], v["map"].as_str().unwrap_or(""))),
"file.export_lottie" => {
+1 -1
View File
@@ -7,7 +7,7 @@ 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), ("plugins", 0), ("audio", 0), ("doc", 1), ("text", 1), ("render", 2), ("xfl", 2), ("svg", 2), ("engine", 3), ("cli", 4)];
&[("geom", 0), ("xml", 0), ("plugins", 0), ("audio", 0), ("doc", 1), ("text", 1), ("render", 2), ("xfl", 2), ("svg", 2), ("engine", 3), ("gpu", 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"];
+26 -1
View File
@@ -2,7 +2,7 @@
//! guard on close, the command palette (Ctrl+K) and the keyboard-shortcut sheet (F1).
use crate::app::{App, Tool};
use crate::prefs::{FontChoice, RenderMode};
use crate::prefs::{FontChoice, RenderMode, StageRenderer};
use crate::theme::{T, Type, text, with_type};
use anicraft_engine::confirm::Confirmation;
use anicraft_engine::{CommandSpec, commands};
@@ -418,6 +418,31 @@ fn preferences(app: &mut App, ctx: &egui::Context) {
}
});
});
if crate::gpu_stage::AVAILABLE {
ui.add_space(4.0);
form_row(ui, LW, "Renderer", |ui| {
ui.vertical(|ui| {
for (choice, name, tip) in StageRenderer::ALL {
crate::theme::radio_value(ui, &mut p.stage_renderer, choice, text(Type::Body, name));
form_note(ui, toggle_indent, text(Type::Caption, tip));
ui.add_space(2.0);
}
});
});
use crate::gpu_stage::State;
let status = match app.stage_cache.gpu.state() {
State::Off => None,
State::Starting => Some("Starting the graphics card…".to_string()),
State::Running(adapter) => Some(format!("Drawing on {adapter}.")),
State::Failed(why) => Some(format!("The graphics card can't draw the stage, so the CPU does: {why}")),
};
if crate::gpu_stage::wanted(p.stage_renderer) != p.stage_renderer {
form_note(ui, LW, text(Type::Caption, "ANICRAFT_STAGE_RENDERER is set, and it takes precedence over this choice."));
}
if let Some(s) = status {
form_note(ui, LW, text(Type::Caption, s));
}
}
});
section(ui, "prefs_timeline", Section::Rule, "Timeline", None, |ui| {
+136
View File
@@ -0,0 +1,136 @@
//! The GPU stage switch (ADR 0019). With the `gpu-stage` feature, Preferences › Stage ›
//! Renderer can hand the stage to the wgpu renderer (`anicraft-gpu`): it starts off the UI
//! thread, draws what it can, and the CPU oracle draws the rest (masks, symbol opacity, blend
//! modes, filters, bitmaps) and everything when the GPU is missing or fails. Without the feature
//! this is a stub and the CPU always draws. Exports never use it.
//!
//! `ANICRAFT_STAGE_RENDERER=gpu|cpu` overrides the preference (also in `--screenshot` runs,
//! which otherwise use default preferences).
use crate::prefs::StageRenderer;
use anicraft_engine::render_service::RenderService;
/// Where the GPU stage is.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(not(feature = "gpu-stage"), allow(dead_code))]
pub enum State {
/// The CPU draws (by choice, or because this build has no GPU stage).
Off,
Starting,
/// Drawing, on this adapter.
Running(String),
/// Could not start or stopped working; the CPU draws. The reason, for Preferences.
Failed(String),
}
/// Whether this build has the GPU stage at all.
pub const AVAILABLE: bool = cfg!(feature = "gpu-stage");
/// The renderer the user asked for, after the environment override.
pub fn wanted(pref: StageRenderer) -> StageRenderer {
match std::env::var("ANICRAFT_STAGE_RENDERER").ok().map(|v| v.to_ascii_lowercase()).as_deref() {
Some("gpu") => StageRenderer::Gpu,
Some("cpu") => StageRenderer::Cpu,
_ => pref,
}
}
#[derive(Default)]
pub struct GpuStage {
#[cfg(feature = "gpu-stage")]
imp: imp::Imp,
}
impl GpuStage {
pub fn state(&self) -> State {
#[cfg(feature = "gpu-stage")]
return self.imp.state.clone();
#[cfg(not(feature = "gpu-stage"))]
State::Off
}
/// Applies the choice to the render service (called every frame; cheap when nothing
/// changes). Starting the renderer happens on its own thread and repaints when done.
#[allow(unused_variables)]
pub fn sync(&mut self, pref: StageRenderer, svc: &RenderService, ctx: &egui::Context) {
#[cfg(feature = "gpu-stage")]
self.imp.sync(wanted(pref) == StageRenderer::Gpu, svc, ctx);
}
}
#[cfg(feature = "gpu-stage")]
mod imp {
use super::State;
use anicraft_engine::render_service::{Rasterizer, RenderService};
use anicraft_gpu::{GpuError, GpuRenderer, Output};
use std::sync::{Arc, mpsc};
pub struct Imp {
pub state: State,
renderer: Option<Arc<GpuRenderer>>,
starting: Option<mpsc::Receiver<Result<GpuRenderer, String>>>,
}
impl Default for Imp {
fn default() -> Self {
Imp { state: State::Off, renderer: None, starting: None }
}
}
impl Imp {
pub fn sync(&mut self, want: bool, svc: &RenderService, ctx: &egui::Context) {
if let Some(rx) = &self.starting
&& let Ok(r) = rx.try_recv()
{
self.starting = None;
match r {
Ok(g) => self.renderer = Some(Arc::new(g)),
Err(e) => self.state = State::Failed(e),
}
}
if let Some(g) = &self.renderer
&& let Some(e) = g.broken()
{
self.renderer = None;
self.state = State::Failed(e);
}
if want && self.renderer.is_none() && self.starting.is_none() && !matches!(self.state, State::Failed(_)) {
let (tx, rx) = mpsc::channel();
let ctx = ctx.clone();
let spawned = std::thread::Builder::new().name("anicraft-gpu-start".into()).spawn(move || {
let _ = tx.send(GpuRenderer::new().map_err(|e| e.to_string()));
ctx.request_repaint();
});
match spawned {
Ok(_) => {
self.starting = Some(rx);
self.state = State::Starting;
}
Err(e) => self.state = State::Failed(e.to_string()),
}
}
let drawing = self.renderer.as_ref().filter(|_| want);
match (drawing, svc.has_rasterizer()) {
(Some(g), false) => {
let g = g.clone();
self.state = State::Running(g.adapter.clone());
let raster: Rasterizer = Arc::new(move |dl, view| match g.render(dl, view, Output::Premul8) {
Ok(f) => Ok((f.premul8, f.stats)),
Err(GpuError::NeedsFull(why)) => Err(why.to_string()),
Err(e) => Err(e.to_string()),
});
svc.set_rasterizer(Some(raster));
ctx.request_repaint();
}
(None, true) => {
svc.set_rasterizer(None);
ctx.request_repaint();
}
_ => {}
}
if !want && !matches!(self.state, State::Failed(_)) {
self.state = State::Off;
}
}
}
}
+2
View File
@@ -9,6 +9,7 @@
mod app;
mod autosave;
mod dialogs;
mod gpu_stage;
mod icons;
mod keymap;
mod menus;
@@ -95,6 +96,7 @@ fn main() -> eframe::Result {
"anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|prefs|licenses|zoom|recovery|plugins]\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, in builds with the gpu-stage feature (ADR 0019)\n\
Headless use: anicraft-cli --help"
);
return Ok(());
+12
View File
@@ -175,6 +175,18 @@ fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpe
}
ui.label(text(Type::Caption, tip));
}
if crate::gpu_stage::AVAILABLE {
ui.separator();
for (choice, name, tip) in crate::prefs::StageRenderer::ALL {
if ui_item(ui, name, "", Some(app.prefs.stage_renderer == choice)) {
let mut p = app.prefs.clone();
p.stage_renderer = choice;
let ctx = ui.ctx().clone();
app.set_prefs(&ctx, p);
}
ui.label(text(Type::Caption, tip));
}
}
});
}
"Control" => {
+17 -1
View File
@@ -152,7 +152,7 @@ pub fn status_bar(app: &mut App, ui: &mut egui::Ui) {
ui.add_space(12.0);
}
let (ready, needed) = app.stage_cache.ready;
ui.label(small(format!("render {:.1} ms · tiles {ready}/{needed}", app.stage_cache.ms)));
ui.label(small(format!("render {:.1} ms{} · tiles {ready}/{needed}", app.stage_cache.ms, renderer_tag(app))));
if let Some(p) = app.cursor_stage {
ui.label(small(format!("x {:.0} y {:.0}", p.x, p.y)));
}
@@ -160,6 +160,22 @@ pub fn status_bar(app: &mut App, ui: &mut egui::Ui) {
});
}
/// Who draws the stage, when this build can draw it on the GPU (ADR 0019): " GPU", or " CPU"
/// with what kept the GPU out.
fn renderer_tag(app: &App) -> String {
use crate::gpu_stage::State;
if !crate::gpu_stage::AVAILABLE {
return String::new();
}
match (app.stage_cache.gpu.state(), &app.stage_cache.drawn_by) {
(State::Starting, _) => " · GPU starting".into(),
(State::Failed(_), _) => " · CPU (GPU unavailable)".into(),
(State::Running(_), Some((true, _))) => " · GPU".into(),
(State::Running(_), Some((false, Some(why)))) => format!(" · CPU for {why}"),
_ => " · CPU".into(),
}
}
// ----- right dock ---------------------------------------------------------------------------
fn rgb(c: Rgba) -> [u8; 3] {
+22 -1
View File
@@ -35,6 +35,24 @@ impl RenderMode {
];
}
/// Which renderer draws the stage (ADR 0019). The GPU only takes part in builds with the
/// `gpu-stage` feature; elsewhere the setting is kept but the CPU draws.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum StageRenderer {
/// The reference renderer: exact, and what every export uses.
#[default]
Cpu,
/// The graphics card, for what it draws today (the CPU draws the rest).
Gpu,
}
impl StageRenderer {
pub const ALL: [(StageRenderer, &'static str, &'static str); 2] = [
(StageRenderer::Cpu, "CPU (reference)", "The reference renderer. Exports always use it."),
(StageRenderer::Gpu, "GPU (preview)", "Draws the stage on the graphics card. Masks, symbol opacity, blend modes, filters and bitmaps still draw on the CPU; the picture is the same either way."),
];
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Prefs {
@@ -43,6 +61,7 @@ pub struct Prefs {
/// Interface scale (1.0 = 100%).
pub ui_scale: f32,
pub render_mode: RenderMode,
pub stage_renderer: StageRenderer,
/// Native open/save dialogs; off = a built-in path field (for Linux setups without an XDG
/// desktop portal).
pub native_dialogs: bool,
@@ -67,6 +86,7 @@ impl Default for Prefs {
data_font: FontChoice::Bundled,
ui_scale: 1.0,
render_mode: RenderMode::Auto,
stage_renderer: StageRenderer::Cpu,
native_dialogs: true,
timeline_start_gap: 0.0,
shortcuts: Default::default(),
@@ -191,7 +211,8 @@ mod tests {
assert_eq!(p.render_mode, RenderMode::Background);
assert_eq!(p.data_font, FontChoice::System("Consolas".into()));
assert!(p.native_dialogs, "missing fields keep their defaults");
let p = Prefs::from_json(r#"{"shortcuts": {"tool.pen": ["F9", "Ctrl+K"], "nope": ["F2"]}}"#);
assert_eq!(p.stage_renderer, StageRenderer::Cpu, "files from before the GPU stage draw on the CPU");
assert_eq!(Prefs::from_json(r#"{"stage_renderer": "Gpu"}"#).stage_renderer, StageRenderer::Gpu); let p = Prefs::from_json(r#"{"shortcuts": {"tool.pen": ["F9", "Ctrl+K"], "nope": ["F2"]}}"#);
assert_eq!(p.shortcuts.len(), 1);
assert_eq!(p.shortcuts.get("tool.pen"), Some(&vec!["F9".to_string()]));
// Older preference files have no autosave settings: autosave is on, every minute.
+17 -5
View File
@@ -11,7 +11,7 @@ use crate::prefs::RenderMode;
use crate::theme::{T, to_color32};
use anicraft_engine::geom::{Affine, Vec2};
use anicraft_engine::render::View;
use anicraft_engine::render_service::{DEFAULT_CACHE_BYTES, FrameImage, FrameJob, RenderService, make_job};
use anicraft_engine::render_service::{DEFAULT_CACHE_BYTES, FrameImage, FrameJob, RenderService, make_job_for};
use egui::{Color32, CursorIcon, Key, Modifiers, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde_json::json;
@@ -46,11 +46,15 @@ pub struct Cache {
pub service: Option<RenderService>,
/// Document state of the picture on screen (an edit makes it differ).
pub shown_state: Option<anicraft_engine::StateId>,
/// The GPU stage (ADR 0019), when this build has it and Preferences ask for it.
pub gpu: crate::gpu_stage::GpuStage,
/// Who drew the newest visible tiles: the GPU, or the CPU and why (status bar).
pub drawn_by: Option<(bool, Option<String>)>,
}
impl Default for Cache {
fn default() -> Self {
Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), service: None, shown_state: None }
Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), service: None, shown_state: None, gpu: Default::default(), drawn_by: None }
}
}
@@ -494,6 +498,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
app.stage_cache.service = Some(RenderService::new(DEFAULT_CACHE_BYTES, Some(Box::new(move || ctx.request_repaint()))));
}
if let Some(svc) = &app.stage_cache.service {
app.stage_cache.gpu.sync(app.prefs.stage_renderer, svc, ui.ctx());
}
// Jobs are keyed by who draws them, so a renderer switch re-renders (old tiles stand in).
let raster = app.stage_cache.service.as_ref().map_or(0, RenderService::raster_id);
// Tiles on a device-pixel grid at this zoom (ADR 0007).
let z = zoom * ppp;
let bg = app.s.doc.stage.background;
@@ -505,7 +514,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
// Render jobs take movie frames: the current scene starts at `start`.
let start = app.s.doc.scene_start(app.s.scene);
let frame = app.s.frame;
let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job(state, &app.s.doc, start + frame, t.view, onion); (t, j) }).collect();
let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &app.s.doc, start + frame, t.view, onion); (t, j) }).collect();
let keys: Vec<u64> = jobs.iter().map(|(_, j)| j.key).collect();
let missing: Vec<usize> = (0..jobs.len()).filter(|&i| !app.stage_cache.has(keys[i])).collect();
@@ -534,6 +543,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
for (&i, img) in missing.iter().zip(results) {
if let Some(img) = img {
ms += img.ms;
if img.error.is_none() {
app.stage_cache.drawn_by = Some((img.gpu, img.fallback.clone()));
}
if let Some(e) = app.stage_cache.upload(ui.ctx(), &img, jobs[i].0.rect, &keys) {
error = Some(e);
}
@@ -567,10 +579,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let n = app.s.frame_count().max(1);
for d in 1..=LOOKAHEAD.min(n - 1) {
let f = (frame + d) % n;
ahead.extend(jobs.iter().map(|(t, _)| make_job(state, &app.s.doc, start + f, t.view, false)));
ahead.extend(jobs.iter().map(|(t, _)| make_job_for(raster, state, &app.s.doc, start + f, t.view, false)));
}
} else {
ahead.extend(tiles_for(z, stage_px, px, 1, bg).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job(state, &app.s.doc, start + frame, t.view, onion)));
ahead.extend(tiles_for(z, stage_px, px, 1, bg).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job_for(raster, state, &app.s.doc, start + frame, t.view, onion)));
}
svc.prefetch(ahead);
}