mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-25 03:53:23 +01:00
Merge pull request #17 from storytold/feat/svg-import
feat(import): Import to Stage for SVG drawings
This commit is contained in:
20 files changed
+1115
-12
No files matched your search
@@ -8,9 +8,11 @@ is written **AniCraft**; machine names are lowercase (`anicraft-*`). Read `docs/
|
||||
|
||||
```text
|
||||
crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing
|
||||
crates/xml L0 Bounded XML element reader shared by the importers (XFL, SVG)
|
||||
crates/doc L1 Document model, easing, timeline evaluation, sample scene
|
||||
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/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format
|
||||
crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/serve
|
||||
src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
|
||||
|
||||
@@ -57,6 +57,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs` | PKWARE APPNOTE.TXT (published ZIP specification); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries; no ZIP64 or encryption. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| De Casteljau subdivision, Ramer–Douglas–Peucker simplification | `crates/geom/src/edit.rs` | Public mathematical results (de Casteljau 1959; Ramer 1972; Douglas & Peucker 1973) | |
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Import to Stage** (File › Import, **Ctrl+R** as in Animate; `file.import`): SVG drawings
|
||||
come in as editable shapes on a new layer named after the file, at the playhead, centred
|
||||
and selected, as one undo step. Supported: paths and basic shapes, groups, `use` and
|
||||
symbols, transforms, `viewBox`, inline and attribute styles, opacity, and linear and radial
|
||||
gradients. Anything not supported yet (text, images, filters, clip paths, dashes…) is listed
|
||||
in the status bar.
|
||||
|
||||
* **SVG export** (File › Export › Export Frame as SVG…, `file.export_svg`): any frame as a
|
||||
standalone vector SVG, matching the stage. Shapes, strokes, solid and gradient fills, opacity
|
||||
and tint, masks (as clip paths, nested inside symbols) and outline-mode layers all come
|
||||
|
||||
Generated
+19
@@ -217,6 +217,7 @@ dependencies = [
|
||||
"anicraft-doc",
|
||||
"anicraft-geom",
|
||||
"anicraft-render",
|
||||
"anicraft-svg",
|
||||
"anicraft-xfl",
|
||||
"gif",
|
||||
"rayon",
|
||||
@@ -244,16 +245,34 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anicraft-svg"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anicraft-doc",
|
||||
"anicraft-geom",
|
||||
"anicraft-xml",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anicraft-xfl"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anicraft-doc",
|
||||
"anicraft-geom",
|
||||
"anicraft-xml",
|
||||
"miniz_oxide 0.8.9",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anicraft-xml"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
|
||||
@@ -20,6 +20,8 @@ anicraft-doc = { path = "crates/doc" }
|
||||
anicraft-render = { path = "crates/render" }
|
||||
anicraft-engine = { path = "crates/engine" }
|
||||
anicraft-xfl = { path = "crates/xfl" }
|
||||
anicraft-xml = { path = "crates/xml" }
|
||||
anicraft-svg = { path = "crates/svg" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
|
||||
@@ -12,6 +12,7 @@ anicraft-geom.workspace = true
|
||||
anicraft-doc.workspace = true
|
||||
anicraft-render.workspace = true
|
||||
anicraft-xfl.workspace = true
|
||||
anicraft-svg.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
@@ -27,6 +27,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
},
|
||||
},
|
||||
CommandSpec { id: "file.export_png", label: "Export Frame as PNG…", menu: "File/Export", shortcut: None, params: "{path, frame?, scale?}", mutates: false, run: export_png },
|
||||
CommandSpec {
|
||||
id: "file.import",
|
||||
label: "Import to Stage…",
|
||||
menu: "File/Import",
|
||||
shortcut: Some("Ctrl+R"),
|
||||
params: "{path (.svg), x?, y? (top-left on the stage; default: centred)}",
|
||||
mutates: true,
|
||||
run: import_to_stage,
|
||||
},
|
||||
CommandSpec { id: "file.export_svg", label: "Export Frame as SVG…", menu: "File/Export", shortcut: None, params: "{path, frame?, confirm?}", mutates: false, run: export_svg },
|
||||
CommandSpec {
|
||||
id: "file.export_png_sequence",
|
||||
@@ -150,6 +159,68 @@ fn export_png(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame}))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = PathBuf::from(str_req(p, "path")?);
|
||||
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
if ext.as_deref() != Some("svg") {
|
||||
return Err(EngineError::Param("Import to Stage reads SVG drawings (.svg) so far".into()));
|
||||
}
|
||||
let size = std::fs::metadata(&path)?.len();
|
||||
if size > MAX_IMPORT_BYTES {
|
||||
return Err(EngineError::Format(format!("{} is too large to import", path.display())));
|
||||
}
|
||||
let bytes = std::fs::read(&path)?;
|
||||
let drawing = anicraft_svg::import(&bytes).map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?;
|
||||
if drawing.shapes.is_empty() {
|
||||
return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary())));
|
||||
}
|
||||
let stage = s.doc.stage;
|
||||
let x = opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5);
|
||||
let y = opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5);
|
||||
if !(x.is_finite() && y.is_finite()) {
|
||||
return Err(EngineError::Param("'x' and 'y' must be numbers".into()));
|
||||
}
|
||||
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.doc.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)?;
|
||||
// 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;
|
||||
s.selection = ids.clone();
|
||||
Ok(json!({
|
||||
"layer": layer_id.0,
|
||||
"elements": ids.len(),
|
||||
"width": drawing.width,
|
||||
"height": drawing.height,
|
||||
"report": drawing.report.summary(),
|
||||
"skipped": drawing.report.skipped,
|
||||
}))
|
||||
}
|
||||
|
||||
/// A frame as a standalone SVG document (vectors, gradients and masks kept).
|
||||
pub fn frame_svg(doc: &Document, frame: u32) -> String {
|
||||
anicraft_render::svg::to_svg(&anicraft_doc::evaluate(doc, frame), &doc.stage)
|
||||
|
||||
@@ -506,7 +506,7 @@ fn step(s: &mut Session, d: i64) -> Result<Value> {
|
||||
Ok(json!({"frame": s.frame}))
|
||||
}
|
||||
|
||||
fn new_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn new_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = s.doc.timeline.layers.len() + 1;
|
||||
let name = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Layer {n}"));
|
||||
if s.doc.timeline.layers.len() >= 1000 {
|
||||
|
||||
@@ -314,6 +314,44 @@ fn svg_frame_export_writes_vectors_and_asks_before_replacing() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_round_trip_looks_the_same_and_imports_as_one_undo_step() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-svg-rt-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let svg = dir.join("scene.svg");
|
||||
let _ = std::fs::remove_file(&svg);
|
||||
let mut src = Session::new(sample::demo());
|
||||
run(&mut src, "file.export_svg", json!({"path": svg.display().to_string(), "frame": 10}));
|
||||
|
||||
// Import it into an empty document of the same size, at the playhead (frame 3).
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "timeline.insert_frame", json!({"count": 5}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 3}));
|
||||
let layers_before = s.doc.timeline.layers.len();
|
||||
let v = run(&mut s, "file.import", json!({"path": svg.display().to_string()}));
|
||||
assert!(v["elements"].as_u64().unwrap() >= 5);
|
||||
assert_eq!(s.doc.timeline.layers.len(), layers_before + 1);
|
||||
assert_eq!(s.active_layer().unwrap().name, "scene");
|
||||
assert_eq!(s.selection.len() as u64, v["elements"].as_u64().unwrap(), "the imported shapes are selected");
|
||||
assert!(anicraft_doc::evaluate(&s.doc, 2).items.is_empty(), "nothing before the playhead");
|
||||
|
||||
// Pixel for pixel (nearly): the same picture comes back.
|
||||
let a = anicraft_render::render_frame(&src.doc, 10, 0.25).unwrap().to_rgba8();
|
||||
let b = anicraft_render::render_frame(&s.doc, 3, 0.25).unwrap().to_rgba8();
|
||||
let diff = a.iter().zip(&b).map(|(x, y)| (i32::from(*x) - i32::from(*y)).unsigned_abs() as f64).sum::<f64>() / a.len() as f64;
|
||||
assert!(diff < 1.0, "mean difference {diff:.3} of 255");
|
||||
|
||||
// One undo step removes the whole import.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(s.doc.timeline.layers.len(), layers_before);
|
||||
// Anything but SVG, or a file that is not SVG, is refused cleanly.
|
||||
assert!(s.execute("file.import", &json!({"path": dir.join("x.png").display().to_string()})).is_err());
|
||||
let fake = dir.join("fake.svg");
|
||||
std::fs::write(&fake, "<html/>").unwrap();
|
||||
assert!(s.execute("file.import", &json!({"path": fake.display().to_string()})).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn animated_gif_export() {
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-gif-{}", std::process::id()));
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "anicraft-svg"
|
||||
description = "AniCraft SVG import: shapes, groups, transforms, styles and gradients into editable vector shapes"
|
||||
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-xml.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,761 @@
|
||||
//! AniCraft SVG import (layer L2): an SVG drawing into editable vector shapes.
|
||||
//!
|
||||
//! 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
|
||||
//! `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).
|
||||
#![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_geom::svg::parse_path_data;
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
|
||||
use anicraft_xml::Element as X;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(test)]
|
||||
mod 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;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SvgError {
|
||||
#[error(transparent)]
|
||||
Xml(#[from] anicraft_xml::XmlError),
|
||||
#[error("this is not an SVG drawing (its root element is <{0}>)")]
|
||||
NotSvg(String),
|
||||
}
|
||||
|
||||
/// What could not come across, by kind ("2 text elements").
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Report {
|
||||
pub skipped: BTreeMap<String, usize>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
fn skip(&mut self, what: &str) {
|
||||
*self.skipped.entry(what.to_string()).or_default() += 1;
|
||||
}
|
||||
/// One line for a status bar.
|
||||
pub fn summary(&self) -> String {
|
||||
if self.skipped.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(", "))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ImportedShape {
|
||||
/// The element's `id`, if it had one.
|
||||
pub name: String,
|
||||
pub transform: Affine,
|
||||
pub alpha: f32,
|
||||
pub shape: Shape,
|
||||
}
|
||||
|
||||
/// An imported drawing. Coordinates are SVG user units (CSS pixels) of the drawing, with the
|
||||
/// `viewBox` already applied; `width` × `height` is its size.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SvgImport {
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub shapes: Vec<ImportedShape>,
|
||||
pub report: Report,
|
||||
}
|
||||
|
||||
/// Reads an SVG document.
|
||||
pub fn import(bytes: &[u8]) -> Result<SvgImport, SvgError> {
|
||||
let root = anicraft_xml::parse(bytes)?;
|
||||
if local(&root.name) != "svg" {
|
||||
return Err(SvgError::NotSvg(root.name.clone()));
|
||||
}
|
||||
let mut ids: HashMap<&str, &X> = HashMap::new();
|
||||
index(&root, &mut ids, 0);
|
||||
// Size: width/height, else the viewBox, else the CSS default 300 × 150.
|
||||
let vb = root.attr("viewBox").and_then(view_box);
|
||||
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 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 })
|
||||
}
|
||||
|
||||
/// An element name without its namespace prefix (`svg:path` → `path`).
|
||||
fn local(name: &str) -> &str {
|
||||
name.rsplit(':').next().unwrap_or(name)
|
||||
}
|
||||
|
||||
fn index<'a>(el: &'a X, ids: &mut HashMap<&'a str, &'a X>, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
if let Some(id) = el.attr("id") {
|
||||
ids.entry(id).or_insert(el);
|
||||
}
|
||||
for c in &el.children {
|
||||
index(c, ids, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ----- values -----------------------------------------------------------------------------------
|
||||
|
||||
/// Numbers in an attribute (separated by spaces and/or commas, signs and exponents allowed).
|
||||
fn numbers(s: &str) -> Vec<f32> {
|
||||
let mut out = Vec::new();
|
||||
let b = s.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
let start = i;
|
||||
let c = b.get(i).copied().unwrap_or(b' ');
|
||||
if c.is_ascii_digit() || c == b'-' || c == b'+' || c == b'.' {
|
||||
i += 1;
|
||||
let mut seen_dot = c == b'.';
|
||||
let mut seen_e = false;
|
||||
while let Some(&d) = b.get(i) {
|
||||
let prev = b.get(i - 1).copied().unwrap_or(b' ');
|
||||
let ok = d.is_ascii_digit()
|
||||
|| (d == b'.' && !seen_dot && !seen_e)
|
||||
|| ((d == b'e' || d == b'E') && !seen_e)
|
||||
|| ((d == b'-' || d == b'+') && (prev == b'e' || prev == b'E'));
|
||||
if !ok {
|
||||
break;
|
||||
}
|
||||
seen_dot |= d == b'.';
|
||||
seen_e |= d == b'e' || d == b'E';
|
||||
i += 1;
|
||||
}
|
||||
if let Some(v) = s.get(start..i).and_then(|t| t.parse::<f32>().ok()).filter(|v| v.is_finite()) {
|
||||
out.push(v);
|
||||
}
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A length in user units. `%` is relative to `reference`; `em`/`ex` assume a 16 px font.
|
||||
fn length(v: &str, reference: f32) -> Option<f32> {
|
||||
let v = v.trim();
|
||||
// The unit is a known suffix, so exponents ("1e2px") still parse.
|
||||
let units: [(&str, f32); 9] =
|
||||
[("%", reference / 100.0), ("px", 1.0), ("pt", 96.0 / 72.0), ("pc", 16.0), ("mm", 96.0 / 25.4), ("cm", 96.0 / 2.54), ("in", 96.0), ("em", 16.0), ("ex", 8.0)];
|
||||
let (num, k) = units.iter().find_map(|(u, k)| v.strip_suffix(u).map(|n| (n, *k))).unwrap_or((v, 1.0));
|
||||
let n: f32 = num.trim().parse().ok().filter(|n: &f32| n.is_finite())?;
|
||||
Some(n * k).filter(|x| x.is_finite())
|
||||
}
|
||||
|
||||
fn view_box(s: &str) -> Option<Rect> {
|
||||
let n = numbers(s);
|
||||
let (x, y, w, h) = (*n.first()?, *n.get(1)?, *n.get(2)?, *n.get(3)?);
|
||||
(w > 0.0 && h > 0.0).then(|| Rect::new(x, y, x + w, y + h))
|
||||
}
|
||||
|
||||
/// The viewBox → viewport mapping for `preserveAspectRatio` (default `xMidYMid meet`).
|
||||
fn view_box_transform(vb: Rect, w: f32, h: f32, par: &str) -> Affine {
|
||||
let (sx, sy) = (w / vb.width(), h / vb.height());
|
||||
let mut words = par.split_whitespace();
|
||||
let align = words.next().unwrap_or("xMidYMid");
|
||||
if align == "none" {
|
||||
return Affine::scale(sx, sy).mul(&Affine::translate(-vb.min.x, -vb.min.y));
|
||||
}
|
||||
let slice = words.next() == Some("slice");
|
||||
let s = if slice { sx.max(sy) } else { sx.min(sy) };
|
||||
let frac = |key: &str| if align.contains(&format!("{key}Min")) { 0.0 } else if align.contains(&format!("{key}Max")) { 1.0 } else { 0.5 };
|
||||
let tx = (w - vb.width() * s) * frac("x");
|
||||
let ty = (h - vb.height() * s) * frac("Y");
|
||||
Affine::translate(tx, ty).mul(&Affine::scale(s, s)).mul(&Affine::translate(-vb.min.x, -vb.min.y))
|
||||
}
|
||||
|
||||
/// An SVG transform list.
|
||||
fn transform(s: &str) -> Affine {
|
||||
let mut m = Affine::IDENTITY;
|
||||
let mut rest = s;
|
||||
while let Some(open) = rest.find('(') {
|
||||
let name = rest.get(..open).unwrap_or("").trim().trim_start_matches(',').trim();
|
||||
let Some(close) = rest.get(open..).and_then(|r| r.find(')')).map(|c| c + open) else { break };
|
||||
let a = numbers(rest.get(open + 1..close).unwrap_or(""));
|
||||
let g = |i: usize| a.get(i).copied();
|
||||
let t = match (name, a.len()) {
|
||||
("matrix", 6..) => Affine { m: [a[0], a[1], a[2], a[3], a[4], a[5]] },
|
||||
("translate", 1..) => Affine::translate(a[0], g(1).unwrap_or(0.0)),
|
||||
("scale", 1..) => Affine::scale(a[0], g(1).unwrap_or(a[0])),
|
||||
("rotate", 1..) => {
|
||||
let r = Affine::rotate(a[0].to_radians());
|
||||
match (g(1), g(2)) {
|
||||
(Some(cx), Some(cy)) => Affine::translate(cx, cy).mul(&r).mul(&Affine::translate(-cx, -cy)),
|
||||
_ => r,
|
||||
}
|
||||
}
|
||||
("skewX", 1..) => Affine { m: [1.0, 0.0, a[0].to_radians().tan(), 1.0, 0.0, 0.0] },
|
||||
("skewY", 1..) => Affine { m: [1.0, a[0].to_radians().tan(), 0.0, 1.0, 0.0, 0.0] },
|
||||
_ => Affine::IDENTITY,
|
||||
};
|
||||
m = m.mul(&t);
|
||||
rest = rest.get(close + 1..).unwrap_or("");
|
||||
}
|
||||
if m.is_finite() { m } else { Affine::IDENTITY }
|
||||
}
|
||||
|
||||
fn named(name: &str) -> Option<u32> {
|
||||
Some(match name {
|
||||
"black" => 0x000000,
|
||||
"white" => 0xffffff,
|
||||
"red" => 0xff0000,
|
||||
"lime" => 0x00ff00,
|
||||
"green" => 0x008000,
|
||||
"blue" => 0x0000ff,
|
||||
"yellow" => 0xffff00,
|
||||
"cyan" | "aqua" => 0x00ffff,
|
||||
"magenta" | "fuchsia" => 0xff00ff,
|
||||
"gray" | "grey" => 0x808080,
|
||||
"silver" => 0xc0c0c0,
|
||||
"maroon" => 0x800000,
|
||||
"olive" => 0x808000,
|
||||
"purple" => 0x800080,
|
||||
"teal" => 0x008080,
|
||||
"navy" => 0x000080,
|
||||
"orange" => 0xffa500,
|
||||
"pink" => 0xffc0cb,
|
||||
"brown" => 0xa52a2a,
|
||||
"gold" => 0xffd700,
|
||||
"indigo" => 0x4b0082,
|
||||
"violet" => 0xee82ee,
|
||||
"coral" => 0xff7f50,
|
||||
"salmon" => 0xfa8072,
|
||||
"tomato" => 0xff6347,
|
||||
"crimson" => 0xdc143c,
|
||||
"khaki" => 0xf0e68c,
|
||||
"beige" => 0xf5f5dc,
|
||||
"ivory" => 0xfffff0,
|
||||
"tan" => 0xd2b48c,
|
||||
"chocolate" => 0xd2691e,
|
||||
"sienna" => 0xa0522d,
|
||||
"turquoise" => 0x40e0d0,
|
||||
"skyblue" => 0x87ceeb,
|
||||
"steelblue" => 0x4682b4,
|
||||
"royalblue" => 0x4169e1,
|
||||
"darkblue" => 0x00008b,
|
||||
"lightblue" => 0xadd8e6,
|
||||
"darkgreen" => 0x006400,
|
||||
"lightgreen" => 0x90ee90,
|
||||
"forestgreen" => 0x228b22,
|
||||
"darkred" => 0x8b0000,
|
||||
"darkgray" | "darkgrey" => 0xa9a9a9,
|
||||
"lightgray" | "lightgrey" => 0xd3d3d3,
|
||||
"dimgray" | "dimgrey" => 0x696969,
|
||||
"darkorange" => 0xff8c00,
|
||||
"orchid" => 0xda70d6,
|
||||
"plum" => 0xdda0dd,
|
||||
"lavender" => 0xe6e6fa,
|
||||
"slategray" | "slategrey" => 0x708090,
|
||||
"whitesmoke" => 0xf5f5f5,
|
||||
"gainsboro" => 0xdcdcdc,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A CSS colour (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`, `rgba()`, a name).
|
||||
fn color(v: &str) -> Option<Rgba> {
|
||||
let v = v.trim();
|
||||
let lower = v.to_ascii_lowercase();
|
||||
if let Some(h) = lower.strip_prefix('#') {
|
||||
let expand = |s: &str| s.chars().flat_map(|c| [c, c]).collect::<String>();
|
||||
return match h.len() {
|
||||
3 | 4 => Rgba::parse_hex(&expand(h)),
|
||||
6 | 8 => Rgba::parse_hex(h),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if let Some(args) = lower.strip_prefix("rgba(").or_else(|| lower.strip_prefix("rgb(")) {
|
||||
let args = args.trim_end_matches(')');
|
||||
let parts: Vec<&str> = args.split([',', ' ', '/']).filter(|p| !p.is_empty()).collect();
|
||||
let chan = |p: &str| -> Option<f32> {
|
||||
match p.strip_suffix('%') {
|
||||
Some(pc) => pc.parse::<f32>().ok().map(|x| x / 100.0),
|
||||
None => p.parse::<f32>().ok().map(|x| x / 255.0),
|
||||
}
|
||||
.filter(|x| x.is_finite())
|
||||
.map(|x| x.clamp(0.0, 1.0))
|
||||
};
|
||||
let alpha = |p: &str| -> Option<f32> {
|
||||
match p.strip_suffix('%') {
|
||||
Some(pc) => pc.parse::<f32>().ok().map(|x| x / 100.0),
|
||||
None => p.parse::<f32>().ok(),
|
||||
}
|
||||
.filter(|x| x.is_finite())
|
||||
.map(|x| x.clamp(0.0, 1.0))
|
||||
};
|
||||
let (r, g, b) = (chan(parts.first()?)?, chan(parts.get(1)?)?, chan(parts.get(2)?)?);
|
||||
let a = parts.get(3).map_or(Some(1.0), |p| alpha(p))?;
|
||||
return Some(Rgba::new(r, g, b, a));
|
||||
}
|
||||
if lower == "transparent" {
|
||||
return Some(Rgba::TRANSPARENT);
|
||||
}
|
||||
named(&lower).map(Rgba::hex)
|
||||
}
|
||||
|
||||
// ----- style ------------------------------------------------------------------------------------
|
||||
|
||||
/// What `fill` or `stroke` asks for.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum PaintSpec {
|
||||
None,
|
||||
Color(Rgba),
|
||||
CurrentColor,
|
||||
/// A paint server by id, with the fallback after it (`url(#g) red`).
|
||||
Url(String, Option<Rgba>),
|
||||
}
|
||||
|
||||
fn paint_spec(v: &str) -> Option<PaintSpec> {
|
||||
let v = v.trim();
|
||||
if v == "none" {
|
||||
return Some(PaintSpec::None);
|
||||
}
|
||||
if v.eq_ignore_ascii_case("currentcolor") {
|
||||
return Some(PaintSpec::CurrentColor);
|
||||
}
|
||||
if let Some(rest) = v.strip_prefix("url(") {
|
||||
let close = rest.find(')')?;
|
||||
let id = rest.get(..close)?.trim().trim_matches(['"', '\'']).trim_start_matches('#').to_string();
|
||||
let fallback = rest.get(close + 1..).map(str::trim).filter(|f| !f.is_empty()).and_then(color);
|
||||
return Some(PaintSpec::Url(id, fallback));
|
||||
}
|
||||
color(v).map(PaintSpec::Color)
|
||||
}
|
||||
|
||||
/// Inherited presentation properties.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Style {
|
||||
fill: PaintSpec,
|
||||
fill_opacity: f32,
|
||||
fill_rule: FillRule,
|
||||
stroke: PaintSpec,
|
||||
stroke_opacity: f32,
|
||||
stroke_width: f32,
|
||||
current: Rgba,
|
||||
}
|
||||
|
||||
impl Default for Style {
|
||||
fn default() -> Self {
|
||||
Style {
|
||||
fill: PaintSpec::Color(Rgba::BLACK),
|
||||
fill_opacity: 1.0,
|
||||
fill_rule: FillRule::NonZero,
|
||||
stroke: PaintSpec::None,
|
||||
stroke_opacity: 1.0,
|
||||
stroke_width: 1.0,
|
||||
current: Rgba::BLACK,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An element's declarations: presentation attributes, overridden by `style=""`.
|
||||
fn declarations(el: &X) -> Vec<(String, String)> {
|
||||
const KEYS: [&str; 16] = [
|
||||
"fill",
|
||||
"fill-opacity",
|
||||
"fill-rule",
|
||||
"stroke",
|
||||
"stroke-opacity",
|
||||
"stroke-width",
|
||||
"stroke-dasharray",
|
||||
"color",
|
||||
"opacity",
|
||||
"display",
|
||||
"visibility",
|
||||
"filter",
|
||||
"clip-path",
|
||||
"mask",
|
||||
"stop-color",
|
||||
"stop-opacity",
|
||||
];
|
||||
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") {
|
||||
for decl in style.split(';') {
|
||||
if let Some((k, v)) = decl.split_once(':') {
|
||||
let v = v.trim().trim_end_matches("!important").trim();
|
||||
out.retain(|(key, _)| key != k.trim());
|
||||
out.push((k.trim().to_ascii_lowercase(), v.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn get<'a>(d: &'a [(String, String)], key: &str) -> Option<&'a str> {
|
||||
d.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
fn opacity(v: &str) -> Option<f32> {
|
||||
let v = v.trim();
|
||||
let x = match v.strip_suffix('%') {
|
||||
Some(p) => p.parse::<f32>().ok()? / 100.0,
|
||||
None => v.parse::<f32>().ok()?,
|
||||
};
|
||||
x.is_finite().then(|| x.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
impl Style {
|
||||
/// This style inherited by `el`, with `el`'s own declarations applied.
|
||||
fn with(&self, el: &X, report: &mut Report) -> Style {
|
||||
let d = declarations(el);
|
||||
let mut s = self.clone();
|
||||
if let Some(c) = get(&d, "color").and_then(color) {
|
||||
s.current = c;
|
||||
}
|
||||
if let Some(p) = get(&d, "fill").and_then(paint_spec) {
|
||||
s.fill = p;
|
||||
}
|
||||
if let Some(p) = get(&d, "stroke").and_then(paint_spec) {
|
||||
s.stroke = p;
|
||||
}
|
||||
if let Some(o) = get(&d, "fill-opacity").and_then(opacity) {
|
||||
s.fill_opacity = o;
|
||||
}
|
||||
if let Some(o) = get(&d, "stroke-opacity").and_then(opacity) {
|
||||
s.stroke_opacity = o;
|
||||
}
|
||||
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,
|
||||
_ => {}
|
||||
}
|
||||
if get(&d, "stroke-dasharray").is_some_and(|v| v != "none") {
|
||||
report.skip("dashed strokes (drawn solid)");
|
||||
}
|
||||
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 ---------------------------------------------------------------------------------
|
||||
|
||||
struct Builder<'a> {
|
||||
ids: HashMap<&'a str, &'a X>,
|
||||
report: Report,
|
||||
shapes: Vec<ImportedShape>,
|
||||
/// The size percentages refer to (the viewBox, or the drawing size).
|
||||
viewport: (f32, f32),
|
||||
}
|
||||
|
||||
impl<'a> Builder<'a> {
|
||||
fn children(&mut self, el: &'a X, m: &Affine, style: &Style, alpha: f32, depth: usize, uses: usize) {
|
||||
for c in &el.children {
|
||||
self.node(c, m, style, alpha, depth + 1, uses);
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
return;
|
||||
}
|
||||
let d = declarations(el);
|
||||
if get(&d, "display") == Some("none") {
|
||||
return;
|
||||
}
|
||||
let name = local(&el.name);
|
||||
// Containers that never draw by themselves.
|
||||
match name {
|
||||
"defs" | "linearGradient" | "radialGradient" | "stop" | "symbol" | "metadata" | "title" | "desc" | "clipPath" | "mask" | "marker" | "pattern" | "filter" | "script" => 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;
|
||||
}
|
||||
"foreignObject" => {
|
||||
self.report.skip("embedded HTML");
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
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));
|
||||
match name {
|
||||
"svg" if depth > 0 => {
|
||||
// A nested viewport: x/y offset, then its own viewBox.
|
||||
let (vw, vh) = self.viewport;
|
||||
let x = el.attr("x").and_then(|v| length(v, vw)).unwrap_or(0.0);
|
||||
let y = el.attr("y").and_then(|v| length(v, vh)).unwrap_or(0.0);
|
||||
let w = el.attr("width").and_then(|v| length(v, vw)).unwrap_or(vw);
|
||||
let h = el.attr("height").and_then(|v| length(v, vh)).unwrap_or(vh);
|
||||
let inner = match el.attr("viewBox").and_then(view_box) {
|
||||
Some(vb) => view_box_transform(vb, w, h, el.attr("preserveAspectRatio").unwrap_or("")),
|
||||
None => Affine::IDENTITY,
|
||||
};
|
||||
let m = m.mul(&Affine::translate(x, y)).mul(&inner);
|
||||
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 {
|
||||
self.report.skip("references to missing elements");
|
||||
return;
|
||||
};
|
||||
if uses >= MAX_USE_DEPTH {
|
||||
self.report.skip("references nested too deeply");
|
||||
return;
|
||||
}
|
||||
let (vw, vh) = self.viewport;
|
||||
let x = el.attr("x").and_then(|v| length(v, vw)).unwrap_or(0.0);
|
||||
let y = el.attr("y").and_then(|v| length(v, vh)).unwrap_or(0.0);
|
||||
let m = m.mul(&Affine::translate(x, y));
|
||||
if local(&target.name) == "symbol" {
|
||||
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);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
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") {
|
||||
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);
|
||||
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 },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The element's path in its own coordinates, and whether it can be filled (lines can't).
|
||||
fn geometry(&mut self, el: &X, name: &str) -> Option<(Path, bool)> {
|
||||
let (vw, vh) = self.viewport;
|
||||
let diag = ((vw * vw + vh * vh) / 2.0).sqrt();
|
||||
let len = |key: &str, reference: f32| el.attr(key).and_then(|v| length(v, reference)).unwrap_or(0.0);
|
||||
match name {
|
||||
"path" => match parse_path_data(el.attr("d").unwrap_or("")) {
|
||||
Ok(p) => Some((p, true)),
|
||||
Err(_) => {
|
||||
self.report.skip("unreadable paths");
|
||||
None
|
||||
}
|
||||
},
|
||||
"rect" => {
|
||||
let (x, y, w, h) = (len("x", vw), len("y", vh), len("width", vw), len("height", vh));
|
||||
if !(w > 0.0 && h > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let rx = el.attr("rx").and_then(|v| length(v, vw));
|
||||
let ry = el.attr("ry").and_then(|v| length(v, vh));
|
||||
let (rx, ry) = match (rx, ry) {
|
||||
(Some(a), Some(b)) => (a, b),
|
||||
(Some(a), None) | (None, Some(a)) => (a, a),
|
||||
(None, None) => (0.0, 0.0),
|
||||
};
|
||||
Some((rounded_rect(x, y, w, h, rx.clamp(0.0, w / 2.0), ry.clamp(0.0, h / 2.0)), true))
|
||||
}
|
||||
"circle" => {
|
||||
let r = len("r", diag);
|
||||
(r > 0.0).then(|| (Path::ellipse(len("cx", vw), len("cy", vh), r, r), true))
|
||||
}
|
||||
"ellipse" => {
|
||||
let (rx, ry) = (len("rx", vw), len("ry", vh));
|
||||
(rx > 0.0 && ry > 0.0).then(|| (Path::ellipse(len("cx", vw), len("cy", vh), rx, ry), true))
|
||||
}
|
||||
"line" => Some((Path::line(Vec2::new(len("x1", vw), len("y1", vh)), Vec2::new(len("x2", vw), len("y2", vh))), false)),
|
||||
"polyline" | "polygon" => {
|
||||
let n = numbers(el.attr("points").unwrap_or(""));
|
||||
let mut p = Path::new();
|
||||
for (i, xy) in n.chunks_exact(2).enumerate() {
|
||||
let q = Vec2::new(xy.first().copied().unwrap_or(0.0), xy.get(1).copied().unwrap_or(0.0));
|
||||
if i == 0 { p.move_to(q) } else { p.line_to(q) };
|
||||
}
|
||||
if name == "polygon" && !p.is_empty() {
|
||||
p.close();
|
||||
}
|
||||
(n.len() >= 4).then_some((p, true))
|
||||
}
|
||||
other => {
|
||||
self.report.skip(&format!("<{other}> elements"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke(&mut self, style: &Style, bounds: &Rect) -> Option<Stroke> {
|
||||
if style.stroke_width <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let color = match self.paint(&style.stroke, style.stroke_opacity, style, bounds)? {
|
||||
Paint::Solid(c) => c,
|
||||
other => {
|
||||
self.report.skip("gradient strokes (drawn in one colour)");
|
||||
other.primary_color()
|
||||
}
|
||||
};
|
||||
Some(Stroke { color, width: style.stroke_width })
|
||||
}
|
||||
|
||||
/// A fill or stroke paint, with `opacity` folded in; `None` draws nothing.
|
||||
fn paint(&mut self, spec: &PaintSpec, opacity: f32, style: &Style, bounds: &Rect) -> Option<Paint> {
|
||||
let solid = |c: Rgba| (c.a * opacity > 0.0).then(|| Paint::Solid(c.with_alpha(c.a * opacity)));
|
||||
match spec {
|
||||
PaintSpec::None => None,
|
||||
PaintSpec::Color(c) => solid(*c),
|
||||
PaintSpec::CurrentColor => solid(style.current),
|
||||
PaintSpec::Url(id, fallback) => match self.gradient(id, opacity, bounds) {
|
||||
Some(p) => Some(p),
|
||||
None => {
|
||||
if !self.ids.get(id.as_str()).is_some_and(|e| matches!(local(&e.name), "linearGradient" | "radialGradient")) {
|
||||
self.report.skip("pattern or unknown fills");
|
||||
}
|
||||
fallback.and_then(solid)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient `id` as a paint for a shape with these local `bounds`.
|
||||
fn gradient(&mut self, id: &str, opacity: f32, bounds: &Rect) -> Option<Paint> {
|
||||
// Follow the href chain: attributes and stops come from the nearest gradient that has them.
|
||||
let mut chain: Vec<&X> = Vec::new();
|
||||
let mut cur = self.ids.get(id).copied();
|
||||
while let Some(g) = cur {
|
||||
if chain.len() >= 8 || !matches!(local(&g.name), "linearGradient" | "radialGradient") {
|
||||
break;
|
||||
}
|
||||
chain.push(g);
|
||||
let next = g.attr("href").or_else(|| g.attr("xlink:href")).map(|h| h.trim_start_matches('#'));
|
||||
cur = next.and_then(|h| self.ids.get(h).copied()).filter(|n| !chain.iter().any(|c| std::ptr::eq(*c, *n)));
|
||||
}
|
||||
let first = *chain.first()?;
|
||||
let attr = |key: &str| chain.iter().find_map(|g| g.attr(key));
|
||||
let stop_el = chain.iter().find(|g| g.children.iter().any(|c| local(&c.name) == "stop"))?;
|
||||
let mut stops: Vec<GradientStop> = Vec::new();
|
||||
let mut last = 0.0f32;
|
||||
for s in stop_el.children.iter().filter(|c| local(&c.name) == "stop") {
|
||||
let d = declarations(s);
|
||||
let off = s.attr("offset").and_then(self::opacity).unwrap_or(0.0).clamp(last, 1.0);
|
||||
last = off;
|
||||
let c = get(&d, "stop-color").and_then(color).unwrap_or(Rgba::BLACK);
|
||||
let a = get(&d, "stop-opacity").and_then(self::opacity).unwrap_or(1.0);
|
||||
stops.push(GradientStop { offset: off, color: c.with_alpha(c.a * a * opacity) });
|
||||
}
|
||||
if stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if stops.len() == 1 {
|
||||
return stops.first().map(|s| Paint::Solid(s.color));
|
||||
}
|
||||
let user = attr("gradientUnits") == Some("userSpaceOnUse");
|
||||
let (vw, vh) = self.viewport;
|
||||
// Gradient space → the shape's local space.
|
||||
let units = if user { Affine::IDENTITY } else { Affine::translate(bounds.min.x, bounds.min.y).mul(&Affine::scale(bounds.width().max(1e-6), bounds.height().max(1e-6))) };
|
||||
let g = units.mul(&attr("gradientTransform").map_or(Affine::IDENTITY, transform));
|
||||
if !g.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let coord = |key: &str, default: f32, reference: f32| -> f32 {
|
||||
match attr(key) {
|
||||
Some(v) if !user => v.trim().strip_suffix('%').and_then(|p| p.parse::<f32>().ok()).map(|p| p / 100.0).or_else(|| v.trim().parse().ok()).filter(|x: &f32| x.is_finite()).unwrap_or(default),
|
||||
Some(v) => length(v, reference).unwrap_or(default),
|
||||
None => if user { default * reference } else { default },
|
||||
}
|
||||
};
|
||||
if matches!(attr("spreadMethod"), Some("reflect" | "repeat")) {
|
||||
self.report.skip("reflected or repeated gradients (padded)");
|
||||
}
|
||||
let [a, b, c, d, _, _] = g.m;
|
||||
let similar = (a - d).abs() < 1e-3 * (a.abs() + d.abs() + 1e-6) && (b + c).abs() < 1e-3 * (b.abs() + c.abs() + 1e-6);
|
||||
let diag = ((vw * vw + vh * vh) / 2.0).sqrt();
|
||||
Some(match local(&first.name) {
|
||||
"linearGradient" => {
|
||||
let (p0, p1) = (Vec2::new(coord("x1", 0.0, vw), coord("y1", 0.0, vh)), Vec2::new(coord("x2", 1.0, vw), coord("y2", 0.0, vh)));
|
||||
// Exact when the transform keeps the gradient's bands perpendicular to its axis
|
||||
// (any similarity, or a stretch along the axis); otherwise the bands tilt.
|
||||
let (dir, band) = (g.apply_vector(p1 - p0), g.apply_vector((p1 - p0).perp()));
|
||||
if dir.dot(band).abs() > 1e-3 * dir.length() * band.length() {
|
||||
self.report.skip("stretched or skewed gradients (approximated)");
|
||||
}
|
||||
Paint::Linear { start: g.apply(p0), end: g.apply(p1), stops }
|
||||
}
|
||||
_ => {
|
||||
if !similar {
|
||||
self.report.skip("stretched or skewed gradients (approximated)");
|
||||
}
|
||||
let (cx, cy) = (coord("cx", 0.5, vw), coord("cy", 0.5, vh));
|
||||
let (fx, fy) = (coord("fx", cx, vw), coord("fy", cy, vh));
|
||||
if (fx - cx).abs() > 1e-4 || (fy - cy).abs() > 1e-4 {
|
||||
self.report.skip("off-centre radial gradients (centred)");
|
||||
}
|
||||
Paint::Radial { center: g.apply(Vec2::new(cx, cy)), radius: coord("r", 0.5, diag) * g.mean_scale(), stops }
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A rectangle with elliptical corners.
|
||||
fn rounded_rect(x: f32, y: f32, w: f32, h: f32, rx: f32, ry: f32) -> Path {
|
||||
if rx <= 0.0 || ry <= 0.0 {
|
||||
return Path::rect(x, y, w, h);
|
||||
}
|
||||
const K: f32 = 0.552_284_8;
|
||||
let (kx, ky) = (rx * K, ry * K);
|
||||
let (x1, y1) = (x + w, y + h);
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(x + rx, y))
|
||||
.line_to(Vec2::new(x1 - rx, y))
|
||||
.cubic_to(Vec2::new(x1 - rx + kx, y), Vec2::new(x1, y + ry - ky), Vec2::new(x1, y + ry))
|
||||
.line_to(Vec2::new(x1, y1 - ry))
|
||||
.cubic_to(Vec2::new(x1, y1 - ry + ky), Vec2::new(x1 - rx + kx, y1), Vec2::new(x1 - rx, y1))
|
||||
.line_to(Vec2::new(x + rx, y1))
|
||||
.cubic_to(Vec2::new(x + rx - kx, y1), Vec2::new(x, y1 - ry + ky), Vec2::new(x, y1 - ry))
|
||||
.line_to(Vec2::new(x, y + ry))
|
||||
.cubic_to(Vec2::new(x, y + ry - ky), Vec2::new(x + rx - kx, y), Vec2::new(x + rx, y))
|
||||
.close();
|
||||
p
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use super::*;
|
||||
|
||||
fn imp(svg: &str) -> SvgImport {
|
||||
match import(svg.as_bytes()) {
|
||||
Ok(i) => i,
|
||||
Err(e) => panic!("{e}: {svg}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn solid(s: &ImportedShape) -> Rgba {
|
||||
match &s.shape.fill {
|
||||
Some(Paint::Solid(c)) => *c,
|
||||
other => panic!("not solid: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_styles_and_inheritance() {
|
||||
let i = imp(r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100">
|
||||
<g fill="#ff0000" stroke="blue" stroke-width="4" opacity="0.5">
|
||||
<rect id="box" x="10" y="10" width="50" height="30"/>
|
||||
<circle cx="100" cy="50" r="20" style="fill: rgb(0, 128, 255); stroke:none"/>
|
||||
<ellipse cx="150" cy="50" rx="30" ry="10" fill="none"/>
|
||||
<line x1="0" y1="0" x2="200" y2="100"/>
|
||||
<polygon points="0,0 10,0 10,10" fill-rule="evenodd" fill-opacity="50%"/>
|
||||
</g>
|
||||
<path d="M0 0 L10 10" fill="currentColor" color="#00ff00" display="none"/>
|
||||
</svg>"##);
|
||||
assert_eq!((i.width, i.height), (200.0, 100.0));
|
||||
assert_eq!(i.shapes.len(), 5, "display:none is skipped");
|
||||
let r = &i.shapes[0];
|
||||
assert_eq!(r.name, "box");
|
||||
assert_eq!(solid(r), Rgba::hex(0xff0000));
|
||||
assert_eq!(r.shape.stroke, Some(Stroke { color: Rgba::hex(0x0000ff), width: 4.0 }));
|
||||
assert_eq!(r.alpha, 0.5, "group opacity reaches every child");
|
||||
assert_eq!(r.shape.path.bounds(), Rect::new(10.0, 10.0, 60.0, 40.0));
|
||||
let c = &i.shapes[1];
|
||||
assert!((solid(c).g - 128.0 / 255.0).abs() < 1e-4, "style= wins over the inherited fill");
|
||||
assert_eq!(c.shape.stroke, None);
|
||||
assert!(i.shapes[2].shape.fill.is_none() && i.shapes[2].shape.stroke.is_some(), "an unfilled ellipse keeps its stroke");
|
||||
assert!(i.shapes[3].shape.fill.is_none(), "lines are never filled");
|
||||
let p = &i.shapes[4];
|
||||
assert_eq!(p.shape.fill_rule, FillRule::EvenOdd);
|
||||
assert!((solid(p).a - 0.5).abs() < 1e-6);
|
||||
assert!(i.report.skipped.is_empty(), "{:?}", i.report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforms_view_box_and_units() {
|
||||
// A 2 × 1 inch drawing whose viewBox is 0..20 × 0..10: one unit = 9.6 px.
|
||||
let i = imp(r##"<svg width="2in" height="1in" viewBox="0 0 20 10">
|
||||
<g transform="translate(5 0) scale(2)"><rect width="1" height="1" transform="rotate(90)"/></g>
|
||||
</svg>"##);
|
||||
assert_eq!((i.width, i.height), (192.0, 96.0));
|
||||
let m = i.shapes[0].transform;
|
||||
let p = m.apply(Vec2::new(1.0, 0.0));
|
||||
// (1,0) → rotate 90° → (0,1) → scale 2 → (0,2) → translate → (5,2) → ×9.6
|
||||
assert!((p.x - 48.0).abs() < 1e-3 && (p.y - 19.2).abs() < 1e-3, "{p:?}");
|
||||
// meet centres a mismatched viewBox; none stretches it.
|
||||
let meet = imp(r#"<svg width="100" height="50" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>"#);
|
||||
let q = meet.shapes[0].transform.apply(Vec2::new(0.0, 0.0));
|
||||
assert!((q.x - 25.0).abs() < 1e-4 && q.y.abs() < 1e-4, "{q:?}");
|
||||
let none = imp(r#"<svg width="100" height="50" viewBox="0 0 10 10" preserveAspectRatio="none"><rect width="10" height="10"/></svg>"#);
|
||||
assert_eq!(none.shapes[0].transform.apply(Vec2::new(10.0, 10.0)), Vec2::new(100.0, 50.0));
|
||||
assert_eq!(transform("matrix(1 0 0 1 3 4) skewX(45)").apply(Vec2::new(0.0, 1.0)), Vec2::new(4.0, 5.0));
|
||||
assert_eq!(length("72pt", 0.0), Some(96.0));
|
||||
assert_eq!(length("50%", 300.0), Some(150.0));
|
||||
assert_eq!(length("3furlongs", 1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradients_in_both_unit_systems_with_inherited_stops() {
|
||||
let i = imp(r##"<svg width="100" height="100" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<defs>
|
||||
<linearGradient id="base"><stop offset="0" stop-color="#000"/><stop offset="100%" style="stop-color:#fff;stop-opacity:0.5"/></linearGradient>
|
||||
<linearGradient id="h" xlink:href="#base" x1="0" y1="0" x2="1" y2="0"/>
|
||||
<radialGradient id="r" gradientUnits="userSpaceOnUse" cx="50" cy="50" r="25" href="#base"/>
|
||||
<linearGradient id="diag" href="#base" x2="1" y2="1"/>
|
||||
</defs>
|
||||
<rect x="0" y="0" width="90" height="10" fill="url(#diag)"/>
|
||||
<rect x="20" y="10" width="40" height="80" fill="url(#h)"/>
|
||||
<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 };
|
||||
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");
|
||||
assert_eq!(stops.len(), 2);
|
||||
assert_eq!(stops[1].color, Rgba::WHITE.with_alpha(0.5));
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
match &i.shapes[1].shape.fill {
|
||||
Some(Paint::Radial { center, radius, stops }) => {
|
||||
assert_eq!((*center, *radius), (Vec2::new(50.0, 50.0), 25.0));
|
||||
assert_eq!(stops[0].color.a, 0.5, "fill-opacity folds into the stops");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(solid(&i.shapes[2]), Rgba::hex(0xff0000), "a missing paint server uses the fallback colour");
|
||||
// Only the diagonal gradient in the wide strip tilts (approximated): the tall box's
|
||||
// horizontal gradient stretches along its axis, which is exact. #nothing is unknown.
|
||||
assert_eq!(i.report.skipped.get("stretched or skewed gradients (approximated)"), Some(&1));
|
||||
assert_eq!(i.report.skipped.get("pattern or unknown fills"), Some(&1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn use_references_and_reported_leftovers() {
|
||||
let i = imp(r##"<svg width="100" height="100">
|
||||
<defs><circle id="dot" r="5" fill="#123456"/><symbol id="pair"><rect width="2" height="2"/><rect x="4" width="2" height="2"/></symbol></defs>
|
||||
<use href="#dot" x="10" y="20"/>
|
||||
<use xlink:href="#pair" x="50" y="50"/>
|
||||
<use href="#missing"/>
|
||||
<text x="0" y="10">Hello</text>
|
||||
<image href="photo.png" width="10" height="10"/>
|
||||
<rect width="10" height="10" stroke="#000" stroke-dasharray="2 2" filter="url(#f)" clip-path="url(#c)"/>
|
||||
<style>rect { fill: red }</style>
|
||||
</svg>"##);
|
||||
let first = &i.shapes[0];
|
||||
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)"] {
|
||||
assert_eq!(i.report.skipped.get(k), Some(&1), "{k}: {:?}", i.report);
|
||||
}
|
||||
assert!(i.report.summary().starts_with("Imported. Not yet supported: "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours() {
|
||||
assert_eq!(color("#f00"), Some(Rgba::hex(0xff0000)));
|
||||
assert_eq!(color("#ff000080").map(|c| (c.a * 255.0).round()), Some(128.0));
|
||||
assert_eq!(color("rgba(255, 0, 0, 0.25)"), Some(Rgba::new(1.0, 0.0, 0.0, 0.25)));
|
||||
assert_eq!(color("rgb(100%, 50%, 0%)"), Some(Rgba::new(1.0, 0.5, 0.0, 1.0)));
|
||||
assert_eq!(color("SteelBlue"), Some(Rgba::hex(0x4682b4)));
|
||||
assert_eq!(color("transparent"), Some(Rgba::TRANSPARENT));
|
||||
for bad in ["", "#12", "rgb(1,2)", "notacolour", "#ééé"] {
|
||||
assert_eq!(color(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_is_an_error_or_harmless() {
|
||||
assert!(matches!(import(b"<html/>"), Err(SvgError::NotSvg(_))));
|
||||
assert!(import(b"<svg").is_err());
|
||||
// Self-referencing uses, a reference loop between gradients, NaN-producing transforms
|
||||
// and absurd sizes: all finish quickly with nothing broken.
|
||||
let i = imp(r##"<svg width="-5" height="1e40">
|
||||
<g id="loop"><use href="#loop"/><rect width="1" height="1"/></g>
|
||||
<linearGradient id="a" href="#b"/><linearGradient id="b" href="#a"/>
|
||||
<rect width="1" height="1" fill="url(#a)" transform="scale(1e30) scale(1e30)"/>
|
||||
<rect width="1" height="1" transform="matrix(1 2)"/>
|
||||
<path d="M 0 0 L"/>
|
||||
</svg>"##);
|
||||
assert_eq!(i.width, 300.0, "a negative width falls back to the default");
|
||||
assert!(i.shapes.iter().all(|s| s.transform.is_finite()));
|
||||
assert!(i.shapes.len() < 40, "{}", i.shapes.len());
|
||||
assert!(i.report.skipped.contains_key("references nested too deeply"));
|
||||
assert!(i.report.skipped.contains_key("unreadable paths"));
|
||||
}
|
||||
@@ -10,6 +10,7 @@ repository.workspace = true
|
||||
[dependencies]
|
||||
anicraft-geom.workspace = true
|
||||
anicraft-doc.workspace = true
|
||||
anicraft-xml.workspace = true
|
||||
# Inflate for .fla (zip) archives; already in the tree through png (MIT OR Zlib OR Apache-2.0).
|
||||
miniz_oxide = "0.8"
|
||||
thiserror.workspace = true
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
|
||||
pub mod edges;
|
||||
pub mod import;
|
||||
pub mod xml;
|
||||
/// The shared XML reader (`anicraft-xml`), under its old path.
|
||||
pub use anicraft_xml as xml;
|
||||
pub mod zip;
|
||||
|
||||
pub use import::{Report, XflError, import_path, import_with};
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "anicraft-xml"
|
||||
description = "AniCraft L0: a small, bounded XML element reader shared by the XFL and SVG importers"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
thiserror.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,10 +1,11 @@
|
||||
//! A small, strict-enough XML reader for XFL documents.
|
||||
//! AniCraft XML (layer L0): a small, strict-enough XML element reader shared by the importers.
|
||||
//!
|
||||
//! XFL stores everything that matters in elements and attributes (even shape geometry is an
|
||||
//! attribute), so the reader builds a tree of elements with attributes and ignores text.
|
||||
//! It handles the prolog, comments, CDATA, doctype, processing instructions, the five
|
||||
//! standard entities and numeric character references. Limits on input size, depth and
|
||||
//! XFL and SVG keep everything that matters in elements and attributes (XFL even stores shape
|
||||
//! geometry as an attribute), so the reader builds a tree of elements with attributes and
|
||||
//! ignores text. It handles the prolog, comments, CDATA, doctype, processing instructions, the
|
||||
//! five standard entities and numeric character references. Limits on input size, depth and
|
||||
//! element count keep a hostile file from exhausting memory or the stack. Never panics.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
+3
-3
@@ -13,7 +13,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| 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, auto-key when editing inside a tween, frame labels, graphic-symbol nesting with loop modes, onion skin (±2 frames), looping playback. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. No scenes, folders, motion editor; guide layers are hidden but do not guide yet. |
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. No brush or merge drawing yet. |
|
||||
| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). No MCP yet. |
|
||||
| Files | `.anicraft` JSON load/save (v2), 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 and **mask layers** (including masks in folders); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. No bitmaps, text, motion/shape tweens or extra scenes from XFL yet; no SVG import, Lottie or video yet. |
|
||||
| Files | `.anicraft` JSON load/save (v2), 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 and **mask layers** (including masks in folders); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. No bitmaps, text, motion/shape tweens or extra scenes from XFL yet; **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. No Lottie or video yet. |
|
||||
| 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. 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. |
|
||||
@@ -28,7 +28,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| **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; layer folders, guide layers; ~~mask layers~~ ✅; Movie Clip and Button behaviours; group alpha / offscreen compositing; shape tween with shape hints; motion tween + Motion Editor curves; MCP server; perf budgets (criterion) with CI enforcement; `xtask layers`. |
|
||||
| **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); SVG import, ~~SVG frame export~~ ✅; Lottie export; sprite sheet + JSON; MP4/WebM via ffmpeg pipe. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; Lottie export; sprite sheet + JSON; MP4/WebM via ffmpeg pipe. |
|
||||
| **M5** | Rich media | Text engine (shaping via rustybuzz, glyph atlas); bitmap import and bitmap fills; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and blend modes on Movie Clips. |
|
||||
| **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); frame scripts on the same sandbox; HTML canvas runtime export; button states in test-movie preview; command macros. |
|
||||
| **M7** | Advanced animation | Bone/IK tool; camera layer with depth; variable-width strokes and brush library; asset warp; graph-based easing presets library. |
|
||||
@@ -57,7 +57,7 @@ Next, in order:
|
||||
1. M4 **XFL import, next slices**: ~~masks (with M2 mask layers)~~ ✅, motion tweens and shape
|
||||
tweens, more scenes, bitmaps and text (with M5), and a larger self-authored corpus checked
|
||||
by render tests.
|
||||
2. SVG import (the full SVG path reader is in place); ~~SVG frame export~~ ✅.
|
||||
2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅. Next for SVG: text, clip paths and masks (onto mask layers), dashes.
|
||||
|
||||
## Risks
|
||||
|
||||
|
||||
@@ -548,6 +548,11 @@ impl App {
|
||||
self.allow_close = true;
|
||||
}
|
||||
}
|
||||
"file.import" => {
|
||||
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" }));
|
||||
}
|
||||
"file.export_png" | "file.export_png_sequence" | "file.export_gif" | "file.export_svg" => self.status_ok(format!("Exported {}", v.get("written").or_else(|| v.get("dir")).and_then(Value::as_str).unwrap_or(""))),
|
||||
"edit.undo" => self.status_ok(format!("Undid {}", v["undone"].as_str().unwrap_or(""))),
|
||||
"edit.redo" => self.status_ok(format!("Redid {}", v["redone"].as_str().unwrap_or(""))),
|
||||
@@ -607,6 +612,7 @@ impl App {
|
||||
"file.export_png_sequence" => Some(("Export PNG sequence to folder", "dir", "frames".to_string())),
|
||||
"file.export_gif" => Some(("Export animated GIF", "path", "animation.gif".to_string())),
|
||||
"file.export_svg" => Some(("Export frame as SVG", "path", format!("frame_{:04}.svg", self.s.frame + 1))),
|
||||
"file.import" => Some(("Import to stage (SVG)", "path", "drawing.svg".to_string())),
|
||||
"modify.convert_to_symbol" => Some(("Convert to symbol — name", "name", format!("Symbol {}", self.s.doc.library.len() + 1))),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
+1
-1
@@ -189,7 +189,7 @@ impl Entry {
|
||||
|
||||
/// Commands the palette can run without extra input (everything optional, or prompted).
|
||||
fn runnable(c: &CommandSpec) -> bool {
|
||||
if matches!(c.id, "file.open" | "file.save_as" | "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename") {
|
||||
if matches!(c.id, "file.open" | "file.save_as" | "file.import" | "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename") {
|
||||
return true;
|
||||
}
|
||||
let inner = c.params.trim().trim_start_matches('{').trim_end_matches('}');
|
||||
|
||||
+1
-1
@@ -121,7 +121,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) {
|
||||
match cmd {
|
||||
"file.export_png" => ("PNG image", &["png"]),
|
||||
"file.export_gif" => ("Animated GIF", &["gif"]),
|
||||
"file.export_svg" => ("SVG image", &["svg"]),
|
||||
"file.export_svg" | "file.import" => ("SVG image", &["svg"]),
|
||||
// Opening also imports .fla archives and .xfl packages.
|
||||
"file.open" => ("Documents", &["anicraft", "fla", "xfl"]),
|
||||
_ => ("AniCraft document", &["anicraft"]),
|
||||
|
||||
Reference in new issue
Block a user