diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml index eaf10e52..5dd670bd 100644 --- a/.github/workflows/web.yml +++ b/.github/workflows/web.yml @@ -33,6 +33,11 @@ jobs: command: | # Every crate builds for wasm32. cargo build --workspace --target wasm32-unknown-unknown --locked + # The sample plug-ins (examples/plugins; ADR 0017, 0088): built to WebAssembly, their own + # tests, and the engine running the built modules. + examples/plugins/build.sh + (cd examples/plugins && cargo test --locked) + ANICRAFT_EXAMPLE_PLUGINS="$PWD/examples/plugins/dist" cargo test -p anicraft-engine --test example_plugins --locked # wasm-bindgen CLI at the version Cargo.lock pins. version="$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' Cargo.lock)" cargo install wasm-bindgen-cli --version "$version" --locked diff --git a/examples/plugins/Cargo.lock b/examples/plugins/Cargo.lock index 82fc67c9..b524d388 100644 --- a/examples/plugins/Cargo.lock +++ b/examples/plugins/Cargo.lock @@ -25,6 +25,22 @@ dependencies = [ "serde_json", ] +[[package]] +name = "anicraft-plugin-stepped-ease" +version = "1.0.0" +dependencies = [ + "anicraft-plugin-sdk", + "serde_json", +] + +[[package]] +name = "anicraft-plugin-text-export" +version = "1.0.0" +dependencies = [ + "anicraft-plugin-sdk", + "serde_json", +] + [[package]] name = "itoa" version = "1.0.19" diff --git a/examples/plugins/Cargo.toml b/examples/plugins/Cargo.toml index ca7f6aac..5e85a117 100644 --- a/examples/plugins/Cargo.toml +++ b/examples/plugins/Cargo.toml @@ -2,7 +2,7 @@ # wasm32-unknown-unknown only. Build with ./build.sh. [workspace] resolver = "3" -members = ["sdk", "star-field", "jitter"] +members = ["sdk", "star-field", "jitter", "text-export", "stepped-ease"] [workspace.package] version = "1.0.0" diff --git a/examples/plugins/build.sh b/examples/plugins/build.sh index 38426af5..2111e64d 100755 --- a/examples/plugins/build.sh +++ b/examples/plugins/build.sh @@ -8,7 +8,7 @@ cd "$(dirname "$0")" cargo build --release --target wasm32-unknown-unknown out="${CARGO_TARGET_DIR:-target}/wasm32-unknown-unknown/release" mkdir -p dist -for name in star_field jitter; do +for name in star_field jitter text_export stepped_ease; do cp "$out/anicraft_plugin_$name.wasm" "dist/$name.wasm" echo "dist/$name.wasm: $(wc -c < "dist/$name.wasm") bytes" done diff --git a/examples/plugins/sdk/src/lib.rs b/examples/plugins/sdk/src/lib.rs index 01a70bca..35693ff9 100644 --- a/examples/plugins/sdk/src/lib.rs +++ b/examples/plugins/sdk/src/lib.rs @@ -1,13 +1,19 @@ //! Guest-side helpers for AniCraft WebAssembly plug-ins (ABI v1, `docs/plugins.md`). //! -//! A plug-in names its manifest and its `run` function with [`plugin!`] and talks to AniCraft -//! with [`command`], [`document`], [`selected_elements`] and [`log`]. The only `unsafe` a -//! plug-in needs is here: the two host imports and the raw pointers the exports receive. -//! Everything else is plain Rust; `std` is fine as long as nothing touches WASI (files, clock, -//! randomness), since AniCraft refuses modules with any other import. +//! A command plug-in names its manifest and its `run` function with [`plugin!`] and talks to +//! AniCraft with [`command`], [`document`], [`selected_elements`] and [`log`]. An exporter +//! names its export function with [`exporter!`] and reads frames with [`movie`] and [`frame`]; +//! an ease plug-in names its ease function with [`ease!`]. The only `unsafe` a plug-in needs is +//! here: the two host imports and the raw pointers the exports receive. Everything else is +//! plain Rust; `std` is fine as long as nothing touches WASI (files, clock, randomness), since +//! AniCraft refuses modules with any other import. +//! +//! Built for anything but WebAssembly (a plug-in's own `cargo test`), the host imports are +//! stand-ins that answer every request with an error, so the pure parts can be unit-tested. use serde_json::{Value, json}; +#[cfg(target_arch = "wasm32")] #[link(wasm_import_module = "anicraft")] unsafe extern "C" { /// Sends `len` bytes of JSON at `ptr`; returns the length of the response. @@ -18,6 +24,16 @@ unsafe extern "C" { fn host_response(ptr: *mut u8, cap: usize) -> i32; } +/// Outside AniCraft (native unit tests) there is no host: no response. +#[cfg(not(target_arch = "wasm32"))] +unsafe fn host_call(_: *const u8, _: usize) -> i32 { + 0 +} +#[cfg(not(target_arch = "wasm32"))] +unsafe fn host_response(_: *mut u8, _: usize) -> i32 { + 0 +} + /// Sends one request (`{"op": …}`) and returns its result, or the host's error message. pub fn request(req: &Value) -> Result { let bytes = serde_json::to_vec(req).map_err(|e| e.to_string())?; @@ -55,6 +71,19 @@ pub fn log(message: &str) { let _ = request(&json!({"op": "log", "message": message})); } +/// An exporter's movie: `{name, width, height, fps, background, from, to, frames, +/// total_frames, scenes}` (frames are 0-based movie frames). +pub fn movie() -> Result { + request(&json!({"op": "movie"})) +} + +/// Frame `index` of the export (0 = the first frame exported), evaluated: `{index, frame, +/// scene, scene_frame, items: [{layer, element, path, transform, fill, stroke, fill_rule, +/// alpha, color?, clip?, masks?, group?}], clips, groups}`. +pub fn frame(index: u64) -> Result { + request(&json!({"op": "frame", "index": index})) +} + /// A small deterministic random generator (SplitMix64). Plug-ins have no source of /// randomness, by design: a seed parameter makes every run, and every preview, repeatable. pub struct Rng(u64); @@ -105,6 +134,70 @@ macro_rules! plugin { }; } +/// Exports the entry points of an exporter plug-in: `exporter!(MANIFEST, export)` where +/// `export: fn(&serde_json::Value) -> Result, String>` gets the validated options and +/// returns the file's bytes. +#[macro_export] +macro_rules! exporter { + ($manifest:expr, $export:path) => { + #[unsafe(no_mangle)] + pub extern "C" fn ac_abi_version() -> i32 { + 1 + } + #[unsafe(no_mangle)] + pub extern "C" fn ac_manifest() -> i64 { + $crate::manifest_ptr($manifest) + } + #[unsafe(no_mangle)] + pub extern "C" fn ac_alloc(size: i32) -> i32 { + $crate::alloc(size) + } + #[unsafe(no_mangle)] + pub extern "C" fn ac_export(ptr: i32, len: i32) -> i64 { + $crate::export(ptr, len, $export) + } + }; +} + +/// Exports the entry points of an ease plug-in: `ease!(MANIFEST, ease)` where +/// `ease: fn(usize, f64) -> f64` is the eased progress of the manifest's ease number `index` at +/// time `t` (0..=1). AniCraft samples it when the plug-in loads; it gets no host calls. +#[macro_export] +macro_rules! ease { + ($manifest:expr, $ease:path) => { + #[unsafe(no_mangle)] + pub extern "C" fn ac_abi_version() -> i32 { + 1 + } + #[unsafe(no_mangle)] + pub extern "C" fn ac_manifest() -> i64 { + $crate::manifest_ptr($manifest) + } + #[unsafe(no_mangle)] + pub extern "C" fn ac_ease(index: i32, t: f64) -> f64 { + $ease(index.max(0) as usize, t) + } + }; +} + +#[doc(hidden)] +pub fn export(ptr: i32, len: i32, f: fn(&Value) -> Result, String>) -> i64 { + // SAFETY: the host wrote `len` bytes of options into the block it got from `ac_alloc`. + let bytes = unsafe { std::slice::from_raw_parts(ptr as usize as *const u8, len.max(0) as usize) }; + let options: Value = serde_json::from_slice(bytes).unwrap_or(Value::Null); + match f(&options) { + Ok(out) => { + // The instance is dropped after the export, so the file is never freed. + let out = std::mem::ManuallyDrop::new(out); + ((out.len() as i64) << 32) | (out.as_ptr() as usize as i64) + } + Err(e) => { + log(&e); + -1 + } + } +} + #[doc(hidden)] pub fn manifest_ptr(m: &'static str) -> i64 { ((m.len() as i64) << 32) | (m.as_ptr() as usize as i64) diff --git a/examples/plugins/stepped-ease/Cargo.toml b/examples/plugins/stepped-ease/Cargo.toml new file mode 100644 index 00000000..7e287907 --- /dev/null +++ b/examples/plugins/stepped-ease/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "anicraft-plugin-stepped-ease" +description = "Sample AniCraft ease plug-in: stepped eases, plain and smooth" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +# The rlib lets `cargo test` run the pure parts natively. +crate-type = ["cdylib", "rlib"] + +[dependencies] +anicraft-plugin-sdk.workspace = true +serde_json.workspace = true diff --git a/examples/plugins/stepped-ease/src/lib.rs b/examples/plugins/stepped-ease/src/lib.rs new file mode 100644 index 00000000..f78e50c8 --- /dev/null +++ b/examples/plugins/stepped-ease/src/lib.rs @@ -0,0 +1,81 @@ +//! Stepped Eases: an ease plug-in. Tweens that move in steps, as stop-motion and limited +//! animation do (on twos, on fours), with a smooth variant that eases each step. Each ease is +//! a pure function of time; AniCraft samples it once when the plug-in loads, and a tween that +//! uses one keeps the curve, so the movie plays the same without the plug-in. + +use anicraft_plugin_sdk as ac; + +const MANIFEST: &str = r#"{ + "id": "org.anicraft.stepped-ease", + "name": "Stepped Eases", + "version": "1.0.0", + "kind": "ease", + "author": "AniCraft contributors", + "description": "Tweens that move in steps, like stop motion, plain or with each step eased.", + "eases": [ + {"id": "steps2", "name": "Stepped 2"}, + {"id": "steps4", "name": "Stepped 4"}, + {"id": "steps8", "name": "Stepped 8"}, + {"id": "smooth-steps4", "name": "Smooth Steps 4"} + ] +}"#; + +ac::ease!(MANIFEST, ease); + +/// Ease `index` of the manifest at time `t`. +fn ease(index: usize, t: f64) -> f64 { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + match index { + 0 => steps(t, 2.0), + 1 => steps(t, 4.0), + 2 => steps(t, 8.0), + _ => smooth_steps(t, 4.0), + } +} + +/// `n` equal steps, holding each: 0 until 1/n, then 1/n, …; exactly 1 at the end. +fn steps(t: f64, n: f64) -> f64 { + if t >= 1.0 { 1.0 } else { (t * n).floor() / n } +} + +/// `n` steps, each eased in and out (smoothstep), so the motion settles between beats. +fn smooth_steps(t: f64, n: f64) -> f64 { + if t >= 1.0 { + return 1.0; + } + let x = t * n; + let (k, f) = (x.floor(), x - x.floor()); + (k + f * f * (3.0 - 2.0 * f)) / n +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn steps_hold_then_jump_and_end_at_one() { + assert_eq!([0.0, 0.2, 0.25, 0.49, 0.5, 0.99, 1.0].map(|t| ease(1, t)), [0.0, 0.0, 0.25, 0.25, 0.5, 0.75, 1.0]); + assert_eq!([0.0, 0.49, 0.5, 1.0].map(|t| ease(0, t)), [0.0, 0.0, 0.5, 1.0]); + assert_eq!(ease(2, 0.126), 0.125); + } + + #[test] + fn smooth_steps_pass_through_each_step_and_never_go_back() { + assert_eq!((ease(3, 0.0), ease(3, 0.25), ease(3, 1.0)), (0.0, 0.25, 1.0)); + assert!((ease(3, 0.125) - 0.125).abs() < 1e-12, "half way through the first step"); + let mut last = 0.0; + for i in 0..=1000 { + let v = ease(3, i as f64 / 1000.0); + assert!(v >= last && v.is_finite()); + last = v; + } + } + + #[test] + fn every_ease_is_finite_and_ends_on_its_keyframes() { + for i in 0..4 { + assert_eq!((ease(i, 0.0), ease(i, 1.0)), (0.0, 1.0)); + assert_eq!(ease(i, f64::NAN), 0.0); + } + } +} diff --git a/examples/plugins/text-export/Cargo.toml b/examples/plugins/text-export/Cargo.toml new file mode 100644 index 00000000..c0961aff --- /dev/null +++ b/examples/plugins/text-export/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "anicraft-plugin-text-export" +description = "Sample AniCraft exporter plug-in: the movie as readable text, one block per frame" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +# The rlib lets `cargo test` run the pure parts natively. +crate-type = ["cdylib", "rlib"] + +[dependencies] +anicraft-plugin-sdk.workspace = true +serde_json.workspace = true diff --git a/examples/plugins/text-export/src/lib.rs b/examples/plugins/text-export/src/lib.rs new file mode 100644 index 00000000..2e9b7229 --- /dev/null +++ b/examples/plugins/text-export/src/lib.rs @@ -0,0 +1,139 @@ +//! Plain Text Frames: an exporter plug-in. It writes the movie as a small, readable text file, +//! one block per frame: the shapes on it, where they are and how they are painted, and with +//! Detail › Paths their outlines as SVG path data. Handy for diffing animations in version +//! control, and a template for any export format: AniCraft hands it evaluated frames and +//! writes the bytes it returns. + +use anicraft_plugin_sdk as ac; +use serde_json::Value; +use std::fmt::Write as _; + +const MANIFEST: &str = r#"{ + "id": "org.anicraft.text-export", + "name": "Plain Text Frames", + "version": "1.0.0", + "kind": "exporter", + "author": "AniCraft contributors", + "description": "The movie as readable text, one block per frame: each shape, its position and paint (and outline, with Paths).", + "format": {"name": "Plain Text Frames", "extension": "txt"}, + "params": { + "detail": {"type": "choice", "options": ["Summary", "Shapes", "Paths"], "default": "Shapes", "label": "Detail"}, + "every": {"type": "int", "min": 1, "max": 100, "default": 1, "label": "Every nth frame"} + } +}"#; + +ac::exporter!(MANIFEST, export); + +fn export(options: &Value) -> Result, String> { + let movie = ac::movie()?; + let frames = movie["frames"].as_u64().unwrap_or(0); + let every = options["every"].as_u64().unwrap_or(1).max(1); + let mut list = Vec::new(); + let mut i = 0; + while i < frames { + list.push(ac::frame(i)?); + i += every; + } + Ok(text(&movie, &list, Detail::from(options["detail"].as_str().unwrap_or("Shapes"))).into_bytes()) +} + +/// How much of each frame the text shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Detail { + Summary, + Shapes, + Paths, +} + +impl Detail { + fn from(s: &str) -> Detail { + match s { + "Summary" => Detail::Summary, + "Paths" => Detail::Paths, + _ => Detail::Shapes, + } + } +} + +fn num(v: &Value) -> String { + let f = v.as_f64().unwrap_or(0.0); + let r = (f * 100.0).round() / 100.0; + if r == r.trunc() { format!("{}", r as i64) } else { format!("{r}") } +} + +/// A paint in a few words: `#ff8800ff`, `linear gradient (3 stops)`, `bitmap 2`, `none`. +fn paint(p: &Value) -> String { + match p["type"].as_str() { + Some("solid") => p["color"].as_str().unwrap_or("?").to_string(), + Some(kind @ ("linear" | "radial")) => format!("{kind} gradient ({} stops)", p["stops"].as_array().map_or(0, Vec::len)), + Some("bitmap") => format!("bitmap {}", num(&p["bitmap"])), + _ => "none".to_string(), + } +} + +/// The whole file: a header, then one block per frame. +fn text(movie: &Value, frames: &[Value], detail: Detail) -> String { + let mut out = String::new(); + let _ = writeln!(out, "# {} — {} × {} px at {} fps, frames {}–{} of {}", movie["name"].as_str().unwrap_or("Untitled"), num(&movie["width"]), num(&movie["height"]), num(&movie["fps"]), movie["from"].as_u64().unwrap_or(0) + 1, movie["to"].as_u64().unwrap_or(0) + 1, movie["total_frames"].as_u64().unwrap_or(0)); + let _ = writeln!(out, "# background {}", movie["background"].as_str().unwrap_or("?")); + for f in frames { + let items = f["items"].as_array().map_or(&[][..], Vec::as_slice); + let _ = writeln!(out, "\nframe {} (scene {}): {} shape{}", f["frame"].as_u64().unwrap_or(0) + 1, f["scene"].as_u64().unwrap_or(0) + 1, items.len(), if items.len() == 1 { "" } else { "s" }); + if detail == Detail::Summary { + continue; + } + for it in items { + let m = &it["transform"]; + let stroke = if it["stroke"].is_null() { "none".to_string() } else { format!("{} {}px", it["stroke"]["color"].as_str().unwrap_or("?"), num(&it["stroke"]["width"])) }; + let role = if it["masks"].is_null() { "" } else { " (mask)" }; + let _ = writeln!(out, " element {} on layer {}{role}: at ({}, {}) fill {} stroke {} alpha {}", num(&it["element"]), num(&it["layer"]), num(&m[4]), num(&m[5]), paint(&it["fill"]), stroke, num(&it["alpha"])); + if detail == Detail::Paths { + let _ = writeln!(out, " {}", it["path"].as_str().unwrap_or("")); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn movie() -> Value { + json!({"name": "walk", "width": 550, "height": 400, "fps": 24, "background": "#ffffffff", "from": 0, "to": 1, "frames": 2, "total_frames": 2}) + } + + fn frame(i: u64) -> Value { + json!({"index": i, "frame": i, "scene": 0, "items": [ + {"layer": 1, "element": 7, "path": "M0 0L10 0L10 10Z", "transform": [1, 0, 0, 1, 12.5, 40.004], "fill": {"type": "solid", "color": "#ff8800ff"}, "stroke": {"color": "#000000ff", "width": 2}, "alpha": 1}, + {"layer": 2, "element": 9, "path": "M0 0L5 5", "transform": [1, 0, 0, 1, 0, 0], "fill": {"type": "linear", "stops": [[0, "#000000ff"], [1, "#ffffffff"]]}, "stroke": null, "alpha": 0.5, "masks": 0} + ]}) + } + + #[test] + fn the_text_lists_each_frame_and_shape() { + let t = text(&movie(), &[frame(0), frame(1)], Detail::Shapes); + assert!(t.starts_with("# walk — 550 × 400 px at 24 fps, frames 1–2 of 2\n"), "{t}"); + assert!(t.contains("\nframe 2 (scene 1): 2 shapes\n"), "{t}"); + assert!(t.contains(" element 7 on layer 1: at (12.5, 40) fill #ff8800ff stroke #000000ff 2px alpha 1\n"), "{t}"); + assert!(t.contains(" element 9 on layer 2 (mask): at (0, 0) fill linear gradient (2 stops) stroke none alpha 0.5\n"), "{t}"); + assert!(!t.contains("M0 0")); + assert!(text(&movie(), &[frame(0)], Detail::Paths).contains(" M0 0L10 0L10 10Z\n")); + let summary = text(&movie(), &[frame(0)], Detail::Summary); + assert!(summary.ends_with("frame 1 (scene 1): 2 shapes\n") && !summary.contains("element"), "{summary}"); + } + + #[test] + fn odd_input_never_panics() { + let t = text(&json!({}), &[json!({}), json!({"items": [{}]}), json!(null)], Detail::Paths); + assert!(t.contains("frame 1 (scene 1): 0 shapes")); + assert_eq!(paint(&json!(null)), "none"); + } + + #[test] + fn the_manifest_is_valid_json() { + let m: Value = serde_json::from_str(MANIFEST).unwrap(); + assert_eq!((m["kind"].as_str(), m["format"]["extension"].as_str()), (Some("exporter"), Some("txt"))); + } +}