M13.1: branching history, puppet pin recording, WebAssembly plug-in API, ScriptUI model and hosts, File ▸ Scripts, deterministic render test
- engine: History keeps undone lines as branches; edit.history.list/goto; History panel tree; MCP history tool - puppet.recordPin / puppet.recordOptions; viewer Cmd-drag records; Record Options form - effects::plugin (EffectPlugin trait, register_plugin, API v1); effectcraft-plugin (wasmi, sandboxed, fuel-limited); effect.plugins.load/list - ScriptUI: engine scriptui model + layout + scriptui.* commands; script crate scriptui.js and script-host threads (dialogs block show()) - File ▸ Scripts: install script / ScriptUI panel, sample scripts, window.scriptPanel - host test: bit-identical renders across runs and thread counts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ebcb8c95ce
commit
89c9b1b6ee
@@ -0,0 +1,66 @@
|
||||
//! # effectcraft-plugin (L3)
|
||||
//!
|
||||
//! Loads **WebAssembly effect plug-ins** (plug-in API v1, see `docs/plugins.md`) into the effect
|
||||
//! registry ([`effectcraft_effects::plugin`]). A plug-in is a `.wasm` (or `.wat`) module with
|
||||
//! no imports that exports:
|
||||
//!
|
||||
//! | export | signature | |
|
||||
//! |---|---|---|
|
||||
//! | `memory` | memory | linear memory shared with the host |
|
||||
//! | `ec_api_version` | `() -> i32` | must return 1 |
|
||||
//! | `ec_manifest_ptr`, `ec_manifest_len` | `() -> i32` | a UTF-8 JSON [`PluginManifest`] in memory |
|
||||
//! | `ec_alloc` | `(bytes: i32) -> i32` | a buffer of at least `bytes` bytes, 8-byte aligned; it may reuse the previous one |
|
||||
//! | `ec_render` | `(pixels: i32, width: i32, height: i32, params: i32, nparams: i32, time: f64, scale: f64) -> i32` | process the pixels in place; 0 = ok |
|
||||
//!
|
||||
//! For each render the host asks `ec_alloc` for one buffer holding the parameters (`nparams`
|
||||
//! little-endian `f64`s) followed by the pixels (`width × height × 4` little-endian `f32`s,
|
||||
//! premultiplied RGBA, row-major), calls `ec_render`, and reads the pixels back.
|
||||
//!
|
||||
//! Modules run in the [wasmi](https://github.com/wasmi-labs/wasmi) interpreter (pure Rust,
|
||||
//! MIT/Apache-2.0) with deterministic floats, no imports (no files, network or clock) and a
|
||||
//! fuel limit per frame, so a plug-in can't escape its sandbox, hang the app, or render
|
||||
//! differently on another machine. The runtime is the `wasm` feature (on for the desktop app and
|
||||
//! the CLI); without it [`load_wasm`] says plug-ins are unavailable.
|
||||
|
||||
use effectcraft_effects::EffectSpec;
|
||||
pub use effectcraft_effects::plugin::{EffectPlugin, PLUGIN_API_VERSION, PluginFrame, PluginManifest, PluginParams, register_plugin};
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
mod wasm;
|
||||
|
||||
/// Whether this build can load WebAssembly plug-ins.
|
||||
pub fn wasm_available() -> bool {
|
||||
cfg!(feature = "wasm")
|
||||
}
|
||||
|
||||
/// Load and register a WebAssembly plug-in (`bytes` = a `.wasm` binary or `.wat` text;
|
||||
/// `source` = where it came from, for listings). Returns the registered effect.
|
||||
pub fn load_wasm(bytes: &[u8], source: &str) -> Result<&'static EffectSpec, String> {
|
||||
#[cfg(feature = "wasm")]
|
||||
{
|
||||
let p = wasm::WasmPlugin::new(bytes, source)?;
|
||||
register_plugin(std::sync::Arc::new(p))
|
||||
}
|
||||
#[cfg(not(feature = "wasm"))]
|
||||
{
|
||||
let _ = (bytes, source);
|
||||
Err("WebAssembly plug-ins are not available in this build".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// [`load_wasm`] for the engine's plug-in loader hook: `{id, name, category, version, api}`.
|
||||
pub fn loader(bytes: &[u8], source: &str) -> Result<serde_json::Value, String> {
|
||||
let spec = load_wasm(bytes, source)?;
|
||||
let m = effectcraft_effects::plugin::plugin(spec.id).map(|p| p.manifest().clone());
|
||||
Ok(serde_json::json!({
|
||||
"id": spec.id,
|
||||
"name": spec.name,
|
||||
"category": spec.category,
|
||||
"version": m.as_ref().map(|m| m.version.clone()).unwrap_or_default(),
|
||||
"api": PLUGIN_API_VERSION,
|
||||
"params": spec.params.len(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "wasm"))]
|
||||
mod tests;
|
||||
@@ -0,0 +1,164 @@
|
||||
//! WebAssembly plug-ins: load, register, render through the effect registry, sandbox limits.
|
||||
|
||||
use effectcraft_effects::{Buf, EffectCtx, EffectEnv, Image};
|
||||
use effectcraft_project::build::Ids;
|
||||
|
||||
use crate::load_wasm;
|
||||
|
||||
fn load_err(r: Result<&'static effectcraft_effects::EffectSpec, String>) -> String {
|
||||
match r {
|
||||
Err(e) => e,
|
||||
Ok(s) => panic!("unexpectedly loaded {}", s.id),
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in in WebAssembly text: multiplies RGB by `gain`, adds `lift` × `tint` when `on`.
|
||||
fn gain_module(id: &str, render_body: &str) -> String {
|
||||
let manifest = format!(
|
||||
r#"{{"api":1,"id":"{id}","name":"Gain {id}","category":"Test Plug-ins","version":"1.0","params":[{{"id":"gain","name":"Gain","type":"slider","default":0.5,"min":0,"max":4}},{{"id":"on","name":"Lift","type":"checkbox","default":false}},{{"id":"tint","name":"Tint","type":"color","default":[0,0,1,1]}}]}}"#
|
||||
);
|
||||
let len = manifest.len();
|
||||
let escaped = manifest.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
format!(
|
||||
r#"(module
|
||||
(memory (export "memory") 2)
|
||||
(data (i32.const 16) "{escaped}")
|
||||
(func (export "ec_api_version") (result i32) i32.const 1)
|
||||
(func (export "ec_manifest_ptr") (result i32) i32.const 16)
|
||||
(func (export "ec_manifest_len") (result i32) i32.const {len})
|
||||
(func (export "ec_alloc") (param $n i32) (result i32)
|
||||
(local $need i32)
|
||||
local.get $n
|
||||
i32.const 131071
|
||||
i32.add
|
||||
i32.const 16
|
||||
i32.shr_u
|
||||
memory.size
|
||||
i32.sub
|
||||
local.tee $need
|
||||
i32.const 0
|
||||
i32.gt_s
|
||||
if
|
||||
local.get $need
|
||||
memory.grow
|
||||
drop
|
||||
end
|
||||
i32.const 65536)
|
||||
(func (export "ec_render") (param $px i32) (param $w i32) (param $h i32) (param $params i32) (param $np i32) (param $t f64) (param $scale f64) (result i32)
|
||||
(local $i i32) (local $end i32) (local $g f32) (local $on f64)
|
||||
{render_body}
|
||||
local.get $params
|
||||
f64.load
|
||||
f32.demote_f64
|
||||
local.set $g
|
||||
local.get $params
|
||||
f64.load offset=8
|
||||
local.set $on
|
||||
local.get $px
|
||||
local.get $w
|
||||
local.get $h
|
||||
i32.mul
|
||||
i32.const 16
|
||||
i32.mul
|
||||
i32.add
|
||||
local.set $end
|
||||
local.get $px
|
||||
local.set $i
|
||||
block $done
|
||||
loop $l
|
||||
local.get $i
|
||||
local.get $end
|
||||
i32.ge_u
|
||||
br_if $done
|
||||
local.get $i
|
||||
local.get $i
|
||||
f32.load
|
||||
local.get $g
|
||||
f32.mul
|
||||
f32.store
|
||||
local.get $i
|
||||
local.get $i
|
||||
f32.load offset=4
|
||||
local.get $g
|
||||
f32.mul
|
||||
f32.store offset=4
|
||||
local.get $i
|
||||
local.get $i
|
||||
f32.load offset=8
|
||||
local.get $g
|
||||
f32.mul
|
||||
local.get $on
|
||||
local.get $params
|
||||
f64.load offset=32
|
||||
f64.mul
|
||||
f32.demote_f64
|
||||
f32.add
|
||||
f32.store offset=8
|
||||
local.get $i
|
||||
i32.const 16
|
||||
i32.add
|
||||
local.set $i
|
||||
br $l
|
||||
end
|
||||
end
|
||||
i32.const 0))"#
|
||||
)
|
||||
}
|
||||
|
||||
fn render(spec: &effectcraft_effects::EffectSpec, gain: f64, on: bool) -> Image {
|
||||
let mut next = 1;
|
||||
let g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [4.0, 2.0]);
|
||||
let mut params = effectcraft_effects::flatten_params(&g, &mut |p| p.value.clone());
|
||||
params.values.insert("gain".into(), effectcraft_keyframe::Value::Scalar(gain));
|
||||
params.values.insert("on".into(), effectcraft_keyframe::Value::Bool(on));
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [4.0, 2.0], seed: 1, adjustment: false, env: EffectEnv::default() };
|
||||
let buf = Buf { img: Image::filled(4, 2, [0.8, 0.6, 0.2, 1.0]), offset: [0.0; 2], scale: 1.0 };
|
||||
(spec.render)(&ctx, buf).img
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wasm_plugin_registers_and_renders() {
|
||||
let spec = load_wasm(gain_module("org.test.gain", "").as_bytes(), "gain.wat").unwrap();
|
||||
assert_eq!(spec.id, "org.test.gain");
|
||||
assert_eq!(spec.category, "Test Plug-ins");
|
||||
assert_eq!(spec.params.len(), 3);
|
||||
// Found like a built-in, listed under its own category.
|
||||
assert!(effectcraft_effects::find("org.test.gain").is_some());
|
||||
assert!(effectcraft_effects::lookup("Gain org.test.gain").is_some());
|
||||
assert!(effectcraft_effects::all().iter().any(|e| e.id == "org.test.gain"));
|
||||
assert!(effectcraft_effects::categories().contains(&"Test Plug-ins"));
|
||||
let img = render(spec, 0.5, false);
|
||||
assert_eq!(img.get(1, 1), [0.4, 0.3, 0.1, 1.0]);
|
||||
// The checkbox and colour parameters arrive flattened (tint blue = 1 → +1 on blue).
|
||||
let img = render(spec, 1.0, true);
|
||||
assert_eq!(img.get(3, 0), [0.8, 0.6, 1.2, 1.0]);
|
||||
// Deterministic, and safe to run on many threads at once (each takes an instance).
|
||||
let a: Vec<Image> = (0..8).map(|_| render(spec, 0.25, false)).collect();
|
||||
std::thread::scope(|sc| {
|
||||
let hs: Vec<_> = (0..4).map(|_| sc.spawn(|| render(spec, 0.25, false))).collect();
|
||||
for h in hs {
|
||||
assert_eq!(h.join().unwrap(), a[0]);
|
||||
}
|
||||
});
|
||||
assert!(a.iter().all(|i| *i == a[0]));
|
||||
// The same id can't be registered twice.
|
||||
assert!(load_err(load_wasm(gain_module("org.test.gain", "").as_bytes(), "again.wat")).contains("already registered"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wasm_plugins_are_sandboxed() {
|
||||
// A runaway loop runs out of fuel: the frame comes back unchanged instead of hanging.
|
||||
let spec = load_wasm(gain_module("org.test.spin", "(loop $spin br $spin)").as_bytes(), "spin.wat").unwrap();
|
||||
let img = render(spec, 0.5, false);
|
||||
assert_eq!(img.get(0, 0), [0.8, 0.6, 0.2, 1.0]);
|
||||
// No imports (files, clock, network…).
|
||||
let imports = r#"(module (import "env" "now" (func $now (result f64))) (memory (export "memory") 1))"#;
|
||||
assert!(load_err(load_wasm(imports.as_bytes(), "imports.wat")).contains("import"));
|
||||
// Garbage, wrong API version, bad manifests.
|
||||
assert!(load_wasm(b"\0asm nope", "bad.wasm").is_err());
|
||||
let v2 = gain_module("org.test.v2", "")
|
||||
.replace("(func (export \"ec_api_version\") (result i32) i32.const 1)", "(func (export \"ec_api_version\") (result i32) i32.const 2)");
|
||||
assert!(load_err(load_wasm(v2.as_bytes(), "v2.wat")).contains("API 2"));
|
||||
let reserved = gain_module("ec.blur.mine", "");
|
||||
assert!(load_err(load_wasm(reserved.as_bytes(), "reserved.wat")).contains("reserved"));
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! The wasmi-backed [`EffectPlugin`] (plug-in API v1 ABI, see the crate docs).
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use wasmi::{Config, Engine, Instance, Linker, Memory, Module, Store, TypedFunc, WasmParams, WasmResults};
|
||||
|
||||
use crate::{EffectPlugin, PLUGIN_API_VERSION, PluginFrame, PluginManifest, PluginParams};
|
||||
|
||||
/// Instruction budget per frame: a fixed allowance plus some per pixel. Generous for per-pixel
|
||||
/// work, but a runaway loop stops instead of hanging the render.
|
||||
const FUEL_BASE: u64 = 50_000_000;
|
||||
const FUEL_PER_PIXEL: u64 = 20_000;
|
||||
|
||||
type RenderFn = TypedFunc<(i32, i32, i32, i32, i32, f64, f64), i32>;
|
||||
|
||||
/// One instantiated module (renders running on several threads each take their own).
|
||||
struct Inst {
|
||||
store: Store<()>,
|
||||
instance: Instance,
|
||||
memory: Memory,
|
||||
alloc: TypedFunc<i32, i32>,
|
||||
render: RenderFn,
|
||||
}
|
||||
|
||||
impl Inst {
|
||||
fn func<P: WasmParams, R: WasmResults>(&self, name: &str) -> Result<TypedFunc<P, R>, String> {
|
||||
self.instance.get_typed_func::<P, R>(&self.store, name).map_err(|_| missing(name))
|
||||
}
|
||||
}
|
||||
|
||||
fn missing(name: &str) -> String {
|
||||
format!("the module exports no `{name}` (or with the wrong signature)")
|
||||
}
|
||||
|
||||
fn err(e: impl std::fmt::Display) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
fn instantiate(engine: &Engine, module: &Module) -> Result<Inst, String> {
|
||||
let mut store = Store::new(engine, ());
|
||||
store.set_fuel(FUEL_BASE).map_err(err)?;
|
||||
let linker = Linker::<()>::new(engine);
|
||||
let instance = linker.instantiate_and_start(&mut store, module).map_err(|e| format!("instantiation failed: {e}"))?;
|
||||
let memory = instance.get_memory(&store, "memory").ok_or("the module exports no `memory`")?;
|
||||
let alloc = instance.get_typed_func::<i32, i32>(&store, "ec_alloc").map_err(|_| missing("ec_alloc"))?;
|
||||
let render = instance.get_typed_func::<(i32, i32, i32, i32, i32, f64, f64), i32>(&store, "ec_render").map_err(|_| missing("ec_render"))?;
|
||||
Ok(Inst { store, instance, memory, alloc, render })
|
||||
}
|
||||
|
||||
/// A loaded WebAssembly effect plug-in.
|
||||
pub struct WasmPlugin {
|
||||
manifest: PluginManifest,
|
||||
source: String,
|
||||
engine: Engine,
|
||||
module: Module,
|
||||
/// Idle instances.
|
||||
pool: Mutex<Vec<Inst>>,
|
||||
}
|
||||
|
||||
impl WasmPlugin {
|
||||
pub fn new(bytes: &[u8], source: &str) -> Result<WasmPlugin, String> {
|
||||
let mut config = Config::default();
|
||||
config.consume_fuel(true);
|
||||
let engine = Engine::new(&config);
|
||||
let module = Module::new(&engine, bytes).map_err(|e| format!("not a valid WebAssembly module: {e}"))?;
|
||||
if let Some(i) = module.imports().next() {
|
||||
return Err(format!("plug-ins can't import anything (the module imports `{}.{}`)", i.module(), i.name()));
|
||||
}
|
||||
let mut inst = instantiate(&engine, &module)?;
|
||||
let version = inst.func::<(), i32>("ec_api_version")?;
|
||||
let v = version.call(&mut inst.store, ()).map_err(err)?;
|
||||
if v != PLUGIN_API_VERSION as i32 {
|
||||
return Err(format!("the module implements plug-in API {v}, this build implements API {PLUGIN_API_VERSION}"));
|
||||
}
|
||||
let ptr = inst.func::<(), i32>("ec_manifest_ptr")?.call(&mut inst.store, ()).map_err(err)?;
|
||||
let len = inst.func::<(), i32>("ec_manifest_len")?.call(&mut inst.store, ()).map_err(err)?;
|
||||
let mut text = vec![0u8; len.max(0) as usize];
|
||||
inst.memory.read(&inst.store, ptr as u32 as usize, &mut text).map_err(|e| format!("manifest out of bounds: {e}"))?;
|
||||
let manifest: PluginManifest = serde_json::from_slice(&text).map_err(|e| format!("bad manifest JSON: {e}"))?;
|
||||
manifest.validate()?;
|
||||
Ok(WasmPlugin { manifest, source: source.to_string(), engine, module, pool: Mutex::new(vec![inst]) })
|
||||
}
|
||||
|
||||
fn take(&self) -> Result<Inst, String> {
|
||||
if let Some(i) = self.pool.lock().ok().and_then(|mut p| p.pop()) {
|
||||
return Ok(i);
|
||||
}
|
||||
instantiate(&self.engine, &self.module)
|
||||
}
|
||||
|
||||
fn give_back(&self, inst: Inst) {
|
||||
if let Ok(mut p) = self.pool.lock() {
|
||||
p.push(inst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EffectPlugin for WasmPlugin {
|
||||
fn manifest(&self) -> &PluginManifest {
|
||||
&self.manifest
|
||||
}
|
||||
|
||||
fn source(&self) -> String {
|
||||
self.source.clone()
|
||||
}
|
||||
|
||||
fn render(&self, frame: &mut PluginFrame, params: &PluginParams, time: f64) -> Result<(), String> {
|
||||
let n = frame.pixels.len();
|
||||
let params_bytes = params.flat.len() * 8;
|
||||
let total = params_bytes + n * 16;
|
||||
if total > i32::MAX as usize {
|
||||
return Err("frame too large for a 32-bit plug-in".into());
|
||||
}
|
||||
let mut inst = self.take()?;
|
||||
inst.store.set_fuel(FUEL_BASE + FUEL_PER_PIXEL * n as u64).map_err(err)?;
|
||||
let base = inst.alloc.call(&mut inst.store, total as i32).map_err(err)? as u32 as usize;
|
||||
// Parameters, then pixels (little-endian, as WebAssembly memory is).
|
||||
let mut buf: Vec<u8> = Vec::with_capacity(total);
|
||||
for v in params.flat {
|
||||
buf.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
for px in frame.pixels.iter() {
|
||||
for c in px {
|
||||
buf.extend_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
}
|
||||
inst.memory.write(&mut inst.store, base, &buf).map_err(|e| format!("ec_alloc returned a buffer out of bounds: {e}"))?;
|
||||
let px_ptr = (base + params_bytes) as i32;
|
||||
let r = inst
|
||||
.render
|
||||
.call(&mut inst.store, (px_ptr, frame.width as i32, frame.height as i32, base as i32, params.flat.len() as i32, time, frame.scale))
|
||||
.map_err(|e| format!("ec_render trapped: {e}"));
|
||||
let r = match r {
|
||||
Ok(0) => {
|
||||
inst.memory.read(&inst.store, base + params_bytes, &mut buf[params_bytes..]).map_err(err)?;
|
||||
for (px, b) in frame.pixels.iter_mut().zip(buf[params_bytes..].chunks_exact(16)) {
|
||||
for (c, v) in px.iter_mut().zip(b.chunks_exact(4)) {
|
||||
*c = f32::from_le_bytes([v[0], v[1], v[2], v[3]]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Ok(code) => Err(format!("ec_render returned error {code}")),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
if r.is_ok() {
|
||||
self.give_back(inst);
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user