diff --git a/Cargo.lock b/Cargo.lock index 9e520a8c..a4c7da04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2313,8 +2313,10 @@ dependencies = [ "egui", "image", "log", + "materialcraft-automation", "materialcraft-engine", "materialcraft-ui-egui", + "rfd", "serde_json", "winresource", ] @@ -2332,6 +2334,7 @@ dependencies = [ "materialcraft-render", "rayon", "rmcp", + "rustix 1.1.6", "schemars", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 1bf7d2a7..0cca8f8e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,7 @@ eframe = { version = "0.37", default-features = false } egui = "0.37" wgpu = "30" rfd = "0.17" +rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] } zip = { version = "2", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils"] } tobj = { version = "4", default-features = false } diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index 57868c09..5cef46d0 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -30,17 +30,18 @@ USAGE: materialcraft-cli cook [--graph ] [--set =]... [--full] Cook a graph and print per-node timings and errors. materialcraft-cli export [--graph ] [--set =]... [--format ] - [--depth 8|16|32] [--pattern

] + [--depth 8|16|32] [--size ] [--pattern

] Cook at full size and write every output (png, jpg, tga, tif, bmp, webp, exr, hdr). materialcraft-cli render [--size x] [--view 3d|2d] [--scene ] [--node ] [--yaw ] [--pitch ] [--graph ] [--set =]... [--full] [--tiling ] [--hq [--displacement ]] Render the material on a 3D scene (rounded_cube, cube, sphere, cylinder, plane, torus, - material_ball), or one node's output (--view 2d), to PNG. No GPU needed. --hq is a beauty - render: real displacement from the height output, ambient occlusion and a key light. + material_ball), or one node's output (--view 2d), to PNG. No GPU needed. The height output + raises the surface; --hq is a beauty render with a finer mesh, ambient occlusion and a key light. materialcraft-cli mcp [--bridge ] [--token ] [--read-root

] [--write-root ] MCP server on stdio: headless (file access only below the roots), or bridged to - `materialcraft --control `. + `materialcraft --control `. --automation-read-root / --automation-write-root are + the same as --read-root / --write-root (mcp and serve). materialcraft-cli serve [--port ] [--read-root ] [--write-root ] JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token. @@ -58,12 +59,16 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("batch", &[], &[]), ("new", &["--size", "--name"], &[]), ("cook", &["--graph", "--set"], &["--full"]), - ("export", &["--graph", "--set", "--format", "--depth", "--pattern"], &[]), + ("export", &["--graph", "--set", "--format", "--depth", "--size", "--pattern"], &[]), ("render", &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--set", "--tiling", "--displacement"], &["--full", "--hq"]), - ("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]), - ("serve", &["--port", "--read-root", "--write-root"], &[]), + ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), + ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), ]; +/// (alias, flag): the `--automation-*-root` spelling the other crafting apps use, stored under the +/// short name so the last root given wins whichever spelling it used. +const ALIASES: &[(&str, &str)] = &[("--automation-read-root", "--read-root"), ("--automation-write-root", "--write-root")]; + struct Args { pos: Vec, flags: Vec<(String, Option)>, @@ -91,7 +96,8 @@ fn parse(cmd: &str, raw: &[String]) -> Result { while let Some(x) = it.next() { if valued.contains(&x.as_str()) { let v = it.next().ok_or_else(|| format!("{x} needs a value"))?; - a.flags.push((x.clone(), Some(v.clone()))); + let name = ALIASES.iter().find(|(alias, _)| alias == x).map_or(x.as_str(), |(_, flag)| flag); + a.flags.push((name.to_string(), Some(v.clone()))); } else if bare.contains(&x.as_str()) { a.flags.push((x.clone(), None)); } else if x.starts_with('-') && x.len() > 1 && x.parse::().is_err() { @@ -228,7 +234,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { let mut h = open(a.pos(0, "")?)?; select_graph(&mut h, a)?; let dir = a.pos(1, "")?; - let p = json!({"dir": dir, "graph": a.num::("--graph")?, "format": a.get("--format"), "depth": a.num::("--depth")?, "pattern": a.get("--pattern")}); + let p = json!({"dir": dir, "graph": a.num::("--graph")?, "format": a.get("--format"), "depth": a.num::("--depth")?, "size": a.num::("--size")?, "pattern": a.get("--pattern")}); print(&h.export(&p).map_err(|e| e.to_string())?); } "render" => { @@ -275,14 +281,16 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { let h = Arc::new(Mutex::new(Headless::new(Headless::default_session(), workspace(a)?))); match a.num::("--port")? { Some(port) => { - let (token, file) = server_token(port).map_err(|e| e.to_string())?; - rpc::serve_tcp(port, h, token, |addr| { - eprintln!("materialcraft-cli: serving JSON lines on {addr}"); - if let Some(f) = &file { - eprintln!("materialcraft-cli: token in {}", f.display()); - } - }) - .map_err(|e| e.to_string())?; + // Bind first: a port in use must not replace its server's token file, and port 0's + // token file is named after the port actually picked. + let listener = rpc::bind_tcp(port).map_err(|e| e.to_string())?; + let addr = listener.local_addr().map_err(|e| e.to_string())?; + let (token, file) = server_token(addr.port()).map_err(|e| e.to_string())?; + eprintln!("materialcraft-cli: serving JSON lines on {addr}"); + if let Some(f) = &file { + eprintln!("materialcraft-cli: token in {}", f.display()); + } + rpc::serve_listener(listener, h, token).map_err(|e| e.to_string())?; } None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(|e| e.to_string())?, } @@ -301,3 +309,36 @@ fn workspace(a: &Args) -> Result { let ws = AuthorizedWorkspace::new(r.map(std::path::Path::new), w.map(std::path::Path::new)).map_err(|e| e.to_string())?; Ok(Filesystem::Workspace(ws)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(v: &[&str]) -> Vec { + v.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn automation_root_flags_are_aliases_of_the_short_ones() { + for cmd in ["mcp", "serve"] { + let a = parse(cmd, &strings(&["--automation-read-root", "/r", "--automation-write-root", "/w"])).unwrap(); + assert_eq!((a.get("--read-root"), a.get("--write-root")), (Some("/r"), Some("/w")), "{cmd}"); + let a = parse(cmd, &strings(&["--read-root", "/r", "--write-root", "/w"])).unwrap(); + assert_eq!((a.get("--read-root"), a.get("--write-root")), (Some("/r"), Some("/w")), "{cmd}"); + } + } + + #[test] + fn the_last_root_flag_wins_whatever_its_spelling() { + let a = parse("mcp", &strings(&["--read-root", "/a", "--automation-read-root", "/b"])).unwrap(); + assert_eq!(a.get("--read-root"), Some("/b")); + let a = parse("mcp", &strings(&["--automation-write-root", "/a", "--write-root", "/b"])).unwrap(); + assert_eq!(a.get("--write-root"), Some("/b")); + } + + #[test] + fn automation_root_flags_need_a_value_and_stay_unknown_elsewhere() { + assert!(parse("mcp", &strings(&["--automation-read-root"])).is_err()); + assert!(parse("cook", &strings(&["--automation-read-root", "/r"])).is_err()); + } +} diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 64a1ca49..83f388f9 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -12,12 +12,15 @@ workspace = true [dependencies] materialcraft-engine = { workspace = true } +materialcraft-automation = { workspace = true } materialcraft-ui-egui = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] } egui = { workspace = true } image = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# A start that never opens a window says why in an error dialog (src/start_failure.rs). +rfd = { workspace = true } [build-dependencies] winresource = "0.1" diff --git a/apps/materialcraft/src/control_server.rs b/apps/materialcraft/src/control_server.rs index a094e2dc..c424f846 100644 --- a/apps/materialcraft/src/control_server.rs +++ b/apps/materialcraft/src/control_server.rs @@ -1,80 +1,109 @@ //! Loopback JSON-lines control server (`--control `): one request per line, //! `{"id", "method", "params"}`, one reply per line. The first request must be //! `{"method":"auth","params":{"token":"…"}}` with the token from `MATERIALCRAFT_CONTROL_TOKEN` -//! or, when that is unset, the token written to `/materialcraft-control-.token`. +//! or, when that is unset, the token written (owner-only) to +//! `/materialcraft-control-.token`. Token handling, request framing and connection +//! limits are shared with `materialcraft-cli serve` (`materialcraft_automation::security`). -use std::io::{BufRead, BufReader, Read, Write}; +use std::io::{BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::time::Duration; +use materialcraft_automation::security::{ + AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_CONNECTIONS, read_bounded_line, server_token, token_matches, +}; use materialcraft_ui_egui::ControlRequest; use serde_json::{Value, json}; -/// Requests larger than this are rejected (screenshots go the other way). -const MAX_REQUEST: u64 = 8 << 20; - -fn token(port: u16) -> String { - if let Ok(t) = std::env::var("MATERIALCRAFT_CONTROL_TOKEN") - && t.len() >= 16 - { - return t; - } - use std::hash::{BuildHasher, Hasher}; - let mut out = String::new(); - for i in 0..4u64 { - let mut h = std::collections::hash_map::RandomState::new().build_hasher(); - h.write_u64(i ^ u64::from(std::process::id())); - h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); - out.push_str(&format!("{:016x}", h.finish())); - } - let path = std::env::temp_dir().join(format!("materialcraft-control-{port}.token")); - if let Err(e) = std::fs::write(&path, &out) { - eprintln!("materialcraft: could not write the control token to {}: {e}", path.display()); - } else { - eprintln!("materialcraft: control token written to {}", path.display()); - } - out -} +/// How long an authenticated connection may stay idle. +const IDLE_TIMEOUT: Duration = Duration::from_secs(600); +/// Listen on `127.0.0.1:port` and return the requests for the UI thread to answer +/// ([`ControlRequest::reply`]). Bind or token failures are printed and leave the channel empty. pub fn start(port: u16, ctx: egui::Context) -> Receiver { - let (tx, rx) = channel::(); let listener = match TcpListener::bind(("127.0.0.1", port)) { Ok(l) => l, Err(e) => { eprintln!("materialcraft: control server failed to bind 127.0.0.1:{port}: {e}"); + return channel().1; + } + }; + start_listener(listener, ctx) +} + +fn start_listener(listener: TcpListener, ctx: egui::Context) -> Receiver { + let (tx, rx) = channel::(); + let addr = match listener.local_addr() { + Ok(addr) => addr, + Err(e) => { + eprintln!("materialcraft: could not determine the control port: {e}"); return rx; } }; - let token = token(port); - eprintln!("materialcraft: control server listening on 127.0.0.1:{port}"); - std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.clone()); - std::thread::spawn(move || serve(stream, &token, tx, ctx)); + // After binding, so an app that cannot listen never replaces another server's token. + let token = match server_token(addr.port()) { + Ok((token, Some(path))) => { + eprintln!("materialcraft: control token written to {}", path.display()); + token } - }); + Ok((token, None)) => token, + Err(e) => { + eprintln!("materialcraft: control server disabled: {e}"); + return rx; + } + }; + eprintln!("materialcraft: control server listening on {addr}"); + if let Err(e) = std::thread::Builder::new().name("materialcraft-control".into()).spawn(move || accept(listener, &token, &tx, &ctx)) { + eprintln!("materialcraft: could not start the control server: {e}"); + } rx } -fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context) { - let _ = stream.set_read_timeout(Some(Duration::from_secs(600))); - let Ok(read) = stream.try_clone() else { return }; - let mut reader = BufReader::new(read.take(u64::MAX)); - let mut out = stream; - let mut authed = false; - loop { - let mut line = String::new(); - let n = match reader.by_ref().take(MAX_REQUEST).read_line(&mut line) { - Ok(n) => n, - Err(_) => break, +/// Serve connections from `listener` (at most [`MAX_CONNECTIONS`] at once). +fn accept(listener: TcpListener, token: &str, tx: &Sender, ctx: &egui::Context) { + let limiter = ConnectionLimiter::default(); + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let Some(permit) = limiter.try_acquire(MAX_CONNECTIONS) else { + let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"})); + continue; }; - if n == 0 { - break; + let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.to_string()); + if let Err(e) = std::thread::Builder::new().name("materialcraft-control-client".into()).spawn(move || { + let _permit = permit; + serve(stream, &token, &tx, &ctx); + }) { + log::warn!("could not start a control connection: {e}"); } - if !line.ends_with('\n') && n as u64 >= MAX_REQUEST { - let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": "request too large"})); - break; + } +} + +/// Send `reply` with the request's `id`; false when the client is gone. +fn reply(out: &mut TcpStream, id: Value, mut reply: Value) -> bool { + if let Some(o) = reply.as_object_mut() { + o.insert("id".into(), id); + } + writeln!(out, "{reply}").is_ok() && out.flush().is_ok() +} + +/// One connection: `auth` first (within [`AUTH_TIMEOUT`], one attempt), then requests +/// forwarded to the UI thread one at a time until the client disconnects or idles out. +fn serve(stream: TcpStream, token: &str, tx: &Sender, ctx: &egui::Context) { + let Ok(mut deadline) = AuthDeadline::start(&stream, AUTH_TIMEOUT).map(Some) else { return }; + let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT)); + let Ok(read) = stream.try_clone() else { return }; + let mut reader = BufReader::new(read); + let mut out = stream; + let mut line = String::new(); + loop { + match read_bounded_line(&mut reader, &mut line) { + Ok(LineRead::Line) => {} + Ok(LineRead::TooLong) => { + reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"})); + return; + } + Ok(LineRead::Eof) | Err(_) => return, } if line.trim().is_empty() { continue; @@ -82,33 +111,145 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui:: let msg: Value = match serde_json::from_str(&line) { Ok(v) => v, Err(e) => { - let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")})); + let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": format!("bad JSON: {e}")})); + // Before `auth` a malformed line is the one refused attempt, as on `serve --port`. + if !sent || deadline.is_some() { + return; + } continue; } }; let id = msg.get("id").cloned().unwrap_or(Value::Null); let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); let params = msg.get("params").cloned().unwrap_or(json!({})); - let mut reply = if !authed { - let ok = method == "auth" && params.get("token").and_then(Value::as_str) == Some(token); - authed = ok; - if ok { json!({"ok": true}) } else { json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}) } - } else { - let (req, rrx) = ControlRequest::new(method, params); - if tx.send(req).is_err() { - break; + if deadline.is_some() { + let supplied = params.get("token").and_then(Value::as_str).unwrap_or_default(); + if method != "auth" || !token_matches(token, supplied) { + // One attempt per connection, as on `materialcraft-cli serve`. + reply(&mut out, id, json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"})); + return; } - ctx.request_repaint(); - rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})) - }; - if let Some(o) = reply.as_object_mut() { - o.insert("id".into(), id); + drop(deadline.take()); + if !reply(&mut out, id, json!({"ok": true})) { + return; + } + continue; } - if writeln!(out, "{reply}").is_err() || out.flush().is_err() || !authed { - if !authed { - continue; - } - break; + let (req, rrx) = ControlRequest::new(method, params); + if tx.send(req).is_err() { + return; + } + ctx.request_repaint(); + let answer = rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})); + if !reply(&mut out, id, answer) { + return; } } } + +#[cfg(test)] +mod tests { + use std::io::BufRead; + + use super::*; + + const TOKEN: &str = "0123456789abcdef0123456789abcdef"; + + #[test] + fn ephemeral_listener_uses_its_actual_port_for_the_token() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + assert_ne!(addr.port(), 0); + let _requests = start_listener(listener, egui::Context::default()); + let token = materialcraft_automation::security::client_token(addr.port(), None).unwrap(); + let (mut w, mut r) = connect(addr); + let auth = json!({"method": "auth", "params": {"token": token}}).to_string(); + assert_eq!(call(&mut w, &mut r, &auth).unwrap()["ok"], true); + } + + /// A server on a free port whose app side answers every request with its method name. + fn server() -> std::net::SocketAddr { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || accept(listener, TOKEN, &tx, &egui::Context::default())); + std::thread::spawn(move || { + for r in rx { + let _ = r.reply.send(json!({"ok": true, "result": r.method})); + } + }); + addr + } + + fn connect(addr: std::net::SocketAddr) -> (TcpStream, BufReader) { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + let r = BufReader::new(s.try_clone().unwrap()); + (s, r) + } + + fn call(w: &mut TcpStream, r: &mut BufReader, line: &str) -> Option { + writeln!(w, "{line}").ok()?; + let mut reply = String::new(); + (r.read_line(&mut reply).ok()? > 0).then(|| serde_json::from_str(&reply).unwrap()) + } + + #[test] + fn requests_need_the_token() { + let addr = server(); + // Anything before `auth` is refused and the connection closed. + let (mut w, mut r) = connect(addr); + let denied = call(&mut w, &mut r, r#"{"id":1,"method":"command.run","params":{"id":"file.open"}}"#).unwrap(); + assert_eq!(denied["ok"], false); + assert_eq!(denied["id"], 1); + assert!(call(&mut w, &mut r, r#"{"id":2,"method":"ping"}"#).is_none(), "closed after a refused request"); + // A wrong token is refused and gets no second try. + let (mut w, mut r) = connect(addr); + let wrong = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{}x"}}}}"#, &TOKEN[1..]); + assert_eq!(call(&mut w, &mut r, &wrong).unwrap()["ok"], false); + let right = format!(r#"{{"id":2,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#); + assert!(call(&mut w, &mut r, &right).is_none()); + // So is a malformed first line: no further lines before `auth`. + let (mut w, mut r) = connect(addr); + assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false); + assert!(call(&mut w, &mut r, &right).is_none(), "closed after malformed JSON before auth"); + // The right token unlocks the connection. + let (mut w, mut r) = connect(addr); + let ok = call(&mut w, &mut r, &right).unwrap(); + assert_eq!((ok["ok"].clone(), ok["id"].clone()), (json!(true), json!(2))); + let pong = call(&mut w, &mut r, r#"{"id":3,"method":"ping"}"#).unwrap(); + assert_eq!((pong["result"].clone(), pong["id"].clone()), (json!("ping"), json!(3))); + assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false); + assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection"); + } + + #[test] + fn connections_are_limited_and_idle_ones_time_out() { + let addr = server(); + let idle: Vec<_> = (0..MAX_CONNECTIONS).map(|_| connect(addr)).collect(); + // Let the server take every idle connection before the one over the limit. + std::thread::sleep(Duration::from_millis(300)); + // Read without writing: the server closes at once, and unread input would reset the + // connection before its reply arrives. + let (_, mut r) = connect(addr); + let mut full = String::new(); + r.read_line(&mut full).unwrap(); + assert_eq!(serde_json::from_str::(&full).unwrap()["error"], "too many connections"); + // Unauthenticated connections are closed after AUTH_TIMEOUT, which frees their slots. + for (_, mut r) in idle { + let mut rest = String::new(); + assert_eq!(r.read_line(&mut rest).unwrap(), 0); + } + // A slot frees once its thread has ended, which can trail the client's EOF a little. + let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#); + let authed = (0..50).any(|_| { + let (mut w, mut r) = connect(addr); + let ok = call(&mut w, &mut r, &right).is_some_and(|v| v["ok"] == true); + if !ok { + std::thread::sleep(Duration::from_millis(100)); + } + ok + }); + assert!(authed, "slots are freed after the auth deadline"); + } +} diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs index 4e9b18bf..90270a9b 100644 --- a/apps/materialcraft/src/main.rs +++ b/apps/materialcraft/src/main.rs @@ -6,6 +6,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod control_server; +mod start_failure; use materialcraft_engine::Session; use materialcraft_ui_egui::MaterialCraftApp; @@ -109,6 +110,8 @@ fn main() { ); if let Err(e) = r { eprintln!("materialcraft: {e}"); + // Say why instead of exiting silently (`start_failure`). + start_failure::report(&e); std::process::exit(1); } } diff --git a/apps/materialcraft/src/start_failure.rs b/apps/materialcraft/src/start_failure.rs new file mode 100644 index 00000000..17596045 --- /dev/null +++ b/apps/materialcraft/src/start_failure.rs @@ -0,0 +1,52 @@ +//! A window that can't start, or stops, says why instead of the app quitting silently. +//! +//! Without a usable GPU, graphics driver or desktop (a broken or very old driver, a remote or +//! virtual machine, a program started by a service or a test harness), the window's surface +//! can't be configured and eframe returns an error. MaterialCraft used to log it and exit with no +//! window, which looks like "the app doesn't open". +//! winget-pkgs validation starts installed programs without a desktop, so a version that fails +//! like this never reaches WinGet. +//! +//! Now the reason also goes to an error dialog, as FilmCraft does since 0.14.0. The dialog keeps +//! the process alive until it is dismissed; the exit code afterwards is still the error's. + +/// What the dialog and the log say. Any error `run_native` returns lands here. One from the app's +/// own start-up (`AppCreation`, e.g. a `--control` file it can't write) says only that it couldn't +/// start. Any other comes from the window or graphics, possibly after the window was up, so +/// graphics is named as the likely cause, not the certain one. +pub(crate) fn message(error: &eframe::Error) -> String { + match error { + eframe::Error::AppCreation(_) => format!("MaterialCraft could not start: {error}"), + _ => format!( + "MaterialCraft's window could not start or stopped with an error: {error}\n\nIf this keeps happening, updating the graphics driver often fixes it." + ), + } +} + +/// Logs the failure and shows it in a dialog, which stays until the user closes it. +pub(crate) fn report(error: &eframe::Error) { + let message = message(error); + log::error!("{message}"); + let _ = rfd::MessageDialog::new().set_title("MaterialCraft").set_description(&message).set_level(rfd::MessageLevel::Error).show(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_window_or_graphics_error_names_the_driver_as_the_likely_fix() { + let text = message(&eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable)); + assert!(text.starts_with("MaterialCraft's window could not start or stopped"), "{text}"); + assert!(text.contains("no valid format for the surface"), "{text}"); + assert!(text.contains("graphics driver"), "{text}"); + } + + #[test] + fn an_app_start_up_error_does_not_blame_the_graphics() { + let text = message(&eframe::Error::AppCreation("can't write the control file".into())); + assert!(text.starts_with("MaterialCraft could not start"), "{text}"); + assert!(text.contains("can't write the control file"), "{text}"); + assert!(!text.contains("graphics"), "{text}"); + } +} diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 994b5a61..d56a4fbd 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -24,5 +24,8 @@ base64 = { workspace = true } cap-std = { workspace = true } getrandom = { workspace = true } +[target.'cfg(unix)'.dependencies] +rustix = { workspace = true } + [dev-dependencies] rmcp = { workspace = true, features = ["client"] } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 93feac1c..d0265960 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -4,8 +4,9 @@ use std::path::Path; use materialcraft_engine::core::NodeId; -use materialcraft_engine::{Session, commands, file_cmds, inspect}; -use materialcraft_render::{Lighting, Maps, Scene, Settings}; +use materialcraft_engine::formats::material::MATERIAL_EXT; +use materialcraft_engine::{Session, commands, file_cmds, inspect, material_cmds}; +use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings, VIEW_TRIANGLES}; use serde_json::{Value, json}; use crate::budgets::{HQ_TRIANGLES, MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png}; @@ -42,10 +43,9 @@ pub struct RenderOptions { pub full: bool, /// 3D: UV repeats override (the session's view is not changed). pub tiling: Option, - /// 3D: beauty render: the height output displaces a subdivided mesh, with ray-traced - /// ambient occlusion, a shadowed key light and 3×3 supersampling. Slower; for stills. + /// 3D: beauty render: a finer displaced mesh, ray-traced ambient occlusion, a shadowed key light and 3×3 supersampling. pub hq: bool, - /// 3D, with `hq`: displacement depth in scene radii (default 0.04). + /// 3D, with `hq`: displacement depth in scene radii (default: the view's height depth). pub displacement: Option, } @@ -187,8 +187,8 @@ impl Headless { /// Export every output of a graph into folder `dir`. pub fn export(&mut self, p: &Value) -> Result { let dir = p.get("dir").and_then(Value::as_str).ok_or_else(|| bad("`dir` is required"))?; - let (gi, ext, pattern, depth) = file_cmds::export_params(&self.session, p)?; - let files = file_cmds::export_outputs(&self.session, gi, &ext, &pattern, depth)?; + let (gi, ext, pattern, depth, size) = file_cmds::export_params(&self.session, p)?; + let files = file_cmds::export_outputs(&self.session, gi, &ext, &pattern, depth, size)?; self.create_dir_all(dir)?; let mut written = Vec::new(); for f in files { @@ -199,6 +199,26 @@ impl Headless { Ok(json!({"files": written})) } + /// Cook a graph and write it as a portable `.mcmat` material (`.mcmat` appended when + /// missing) to `path`: `{path, graph?, size?, values?}`, the workspace-scoped + /// `file.exportMaterial`. The file is capped at what `package_open` may read back. + pub fn export_material(&mut self, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?; + let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") }; + match &self.fs { + Filesystem::Denied => return Err(bad("file access is not granted: start the server with --write-root ")), + Filesystem::Workspace(w) => w.check_write(&path)?, + Filesystem::TrustedLocal => {} + } + let (gi, options) = material_cmds::material_request(&self.session, "material.export", p)?; + let bytes = material_cmds::material_bytes(&self.session, gi, &options)?; + if bytes.len() as u64 > MAX_READ_BYTES { + return Err(bad(format!("the material is {} bytes (limit {MAX_READ_BYTES}); export a smaller `size`", bytes.len()))); + } + self.write(&path, &bytes)?; + Ok(json!({"path": path, "bytes": bytes.len()})) + } + /// Render the 3D view or a node's 2D output as PNG. pub fn render_png(&mut self, o: &RenderOptions) -> Result { let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE }; @@ -249,6 +269,8 @@ impl Headless { self.light = Some(Lighting::new(&v.environment)); } let tiling = o.tiling.unwrap_or(v.tiling).clamp(0.1, 64.0); + let depth = if o.hq { o.displacement.unwrap_or(v.height_scale) } else { v.height_scale }; + let relief = Relief { depth: depth.clamp(0.0, 0.5), level: v.height_level }; let mut settings = Settings { yaw: o.yaw.unwrap_or(v.yaw), pitch: o.pitch.unwrap_or(v.pitch), @@ -257,7 +279,6 @@ impl Headless { tiling, exposure: v.exposure, env_rotation: v.env_rotation, - height_scale: v.height_scale, show_env: false, supersample: 2, transparency: v.transparency, @@ -267,13 +288,7 @@ impl Headless { let (w, h) = (o.width.unwrap_or(1024).clamp(16, max), o.height.unwrap_or(768).clamp(16, max)); let maps = Maps::from_usages(self.session.material_maps()); let (Some((_, scene)), Some(light)) = (&self.scene, &self.light) else { return (w, h, vec![0; (w * h * 4) as usize]) }; - let displaced = match (o.hq, &maps.height) { - (true, Some(height)) => { - settings.height_scale = 0.0; - Some(Scene::displaced(&scene.mesh, height, tiling, o.displacement.unwrap_or(0.04).clamp(0.0, 0.5) * scene.radius, HQ_TRIANGLES)) - } - _ => None, - }; + let displaced = scene.with_relief(&maps, relief, tiling, if o.hq { HQ_TRIANGLES } else { VIEW_TRIANGLES }); if o.hq { settings.supersample = 3; settings.ao_rays = 8; diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 0c156b78..3befa2a5 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -4,8 +4,9 @@ //! //! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`, //! `session.inspect`, plus `command.batch {steps}`, `package.open {path}`, `package.save {path?}`, -//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}` -//! (workspace-scoped versions of the engine commands), `render {view?, width?, height?, yaw?, +//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`, +//! `material.export {path, graph?, size?, values?}` (workspace-scoped versions of the engine +//! commands; the last writes a portable `.mcmat`), `render {view?, width?, height?, yaw?, //! pitch?, scene?, node?, port?, full?}` (PNG base64, the shape of the app's `view.screenshot`) //! and `methods`. @@ -18,7 +19,9 @@ use serde_json::{Value, json}; use crate::budgets::json_text; use crate::headless::RenderOptions; -use crate::security::{ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches}; +use crate::security::{ + AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches, +}; use crate::{AutomationError, Headless, bad}; pub const METHODS: &[&str] = &[ @@ -32,6 +35,7 @@ pub const METHODS: &[&str] = &[ "package.save", "bitmap.import", "outputs.export", + "material.export", "render", ]; @@ -84,6 +88,7 @@ impl Headless { "package.save" => self.save(str_of(p, "path")), "bitmap.import" => self.import_bitmap(required(p, "path")?, str_of(p, "name")), "outputs.export" => self.export(p), + "material.export" => self.export_material(p), "render" => { let o = RenderOptions { view: str_of(p, "view").map(str::to_string), @@ -160,6 +165,7 @@ fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &st let mut w = stream; let mut line = String::new(); let mut authed = false; + let mut deadline = Some(AuthDeadline::start(&w, AUTH_TIMEOUT)?); loop { match read_bounded_line(&mut r, &mut line)? { LineRead::Eof => return Ok(()), @@ -178,15 +184,26 @@ fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &st if !authed { return write_reply(&mut w, &json!({"id": id, "ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"})); } + drop(deadline.take()); write_reply(&mut w, &json!({"id": id, "ok": true}))?; } } +/// Listen on `127.0.0.1:port` (0 picks a port). +pub fn bind_tcp(port: u16) -> Result { + TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}"))) +} + /// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared /// session. `ready` gets the bound address. pub fn serve_tcp(port: u16, h: Arc>, token: String, ready: impl FnOnce(std::net::SocketAddr)) -> Result<(), AutomationError> { - let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))?; + let listener = bind_tcp(port)?; ready(listener.local_addr().map_err(|e| AutomationError::Io(e.to_string()))?); + serve_listener(listener, h, token) +} + +/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session. +pub fn serve_listener(listener: TcpListener, h: Arc>, token: String) -> Result<(), AutomationError> { let limiter = ConnectionLimiter::default(); let token = Arc::new(token); for stream in listener.incoming() { @@ -196,10 +213,12 @@ pub fn serve_tcp(port: u16, h: Arc>, token: String, ready: impl continue; }; let (h, token) = (h.clone(), token.clone()); - std::thread::spawn(move || { + if let Err(e) = std::thread::Builder::new().name("materialcraft-rpc-client".into()).spawn(move || { let _permit = permit; let _ = serve_connection(&h, stream, &token); - }); + }) { + eprintln!("materialcraft: could not start an RPC connection: {e}"); + } } Ok(()) } @@ -253,6 +272,81 @@ mod tests { assert_eq!(r[6]["result"]["failed"]["index"], 1); } + /// A workspace session rooted at a fresh `inside` folder, with an `outside` sibling. + fn workspace_session(name: &str, write: bool) -> (std::path::PathBuf, std::path::PathBuf, Mutex) { + let base = std::env::temp_dir().join(format!("mc-rpc-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (inside, outside) = (base.join("inside"), base.join("outside")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let ws = crate::AuthorizedWorkspace::new(Some(&inside), write.then_some(inside.as_path())).unwrap(); + let h = Mutex::new(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws))); + (inside, outside, h) + } + + fn call(h: &Mutex, method: &str, params: Value) -> Result { + h.lock().unwrap().handle(method, ¶ms).map_err(|e| e.to_string()) + } + + #[test] + fn material_export_writes_a_portable_material_below_the_write_root() { + let (inside, _, h) = workspace_session("mat-ok", true); + std::fs::create_dir(inside.join("out")).unwrap(); + let r = call(&h, "material.export", json!({"path": "out/brick", "size": 32})).unwrap(); + assert_eq!(r["path"], "out/brick.mcmat"); + let bytes = std::fs::read(inside.join("out/brick.mcmat")).unwrap(); + assert_eq!(r["bytes"], bytes.len()); + let (m, source) = materialcraft_engine::formats::material::read_material(&bytes).unwrap(); + assert_eq!(m.size, [32, 32]); + assert!(m.maps.iter().any(|e| e.usage == "baseColor")); + assert!(!source.is_empty()); + assert_eq!(std::fs::read_dir(inside.join("out")).unwrap().count(), 1, "no temporary files left behind"); + // An explicit extension is kept (case-insensitively) and the file can be opened again. + let r = call(&h, "material.export", json!({"path": "again.MCMAT", "size": 16})).unwrap(); + assert_eq!(r["path"], "again.MCMAT"); + assert!(call(&h, "package.open", json!({"path": "again.MCMAT"})).is_ok()); + } + + #[test] + fn material_export_reports_bad_requests() { + let (inside, _, h) = workspace_session("mat-bad", true); + for bad in [json!({}), json!({"path": "m", "graph": 99}), json!({"path": "m", "values": {"no_such_input": 1}})] { + assert!(call(&h, "material.export", bad.clone()).is_err(), "{bad}"); + } + assert!(call(&h, "material.export", json!({"path": "missing/dir/m"})).is_err(), "parent must exist"); + assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0, "failed exports leave nothing behind"); + } + + #[test] + fn material_export_needs_a_write_root() { + let denied = session(); + let e = call(&denied, "material.export", json!({"path": "m.mcmat"})).unwrap_err(); + assert!(e.contains("not granted"), "{e}"); + let (inside, _, read_only) = workspace_session("mat-readonly", false); + let e = call(&read_only, "material.export", json!({"path": "m.mcmat"})).unwrap_err(); + assert!(e.contains("no write root"), "{e}"); + assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0); + } + + #[test] + fn material_export_cannot_escape_the_write_root() { + let (_inside, outside, h) = workspace_session("mat-escape", true); + let abs = outside.join("abs.mcmat").display().to_string(); + for p in ["../outside/m.mcmat", "a/../../outside/m.mcmat", "/tmp/m.mcmat", "a\\b.mcmat", "C:/m.mcmat", "./m.mcmat", abs.as_str()] { + let e = call(&h, "material.export", json!({"path": p, "size": 16})); + assert!(e.is_err(), "accepted {p:?}"); + } + #[cfg(unix)] + { + std::os::unix::fs::symlink(&outside, _inside.join("link")).unwrap(); + assert!(call(&h, "material.export", json!({"path": "link/m.mcmat", "size": 16})).is_err()); + } + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "nothing written outside the root"); + // The generic command path stays closed too: host paths are still refused. + let e = call(&h, "command.run", json!({"id": "file.exportMaterial", "params": {"path": abs}})).unwrap_err(); + assert!(e.contains("disabled for automation"), "{e}"); + } + #[test] fn tcp_requires_the_token() { use std::io::{BufRead, BufReader}; diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 165fda18..33040fee 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -1,10 +1,13 @@ //! Tokens and bounded framing for the loopback JSON-lines transports (the app's control channel //! and `materialcraft-cli serve` share the token conventions). -use std::io::BufRead; -use std::path::PathBuf; +use std::io::{BufRead, Read, Write}; +use std::net::{Shutdown, TcpStream}; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{RecvTimeoutError, Sender, channel}; +use std::time::Duration; use crate::{AutomationError, bad}; @@ -14,6 +17,10 @@ pub const TOKEN_ENV: &str = "MATERIALCRAFT_CONTROL_TOKEN"; pub const MAX_REQUEST_BYTES: usize = 8 << 20; /// Simultaneous TCP connections served by `serve --port`. pub const MAX_CONNECTIONS: usize = 16; +/// Largest token file read (a token is at most 1024 characters, plus whitespace). +const MAX_TOKEN_FILE_BYTES: u64 = 4096; +/// Time a TCP client has to authenticate before its connection is closed. +pub const AUTH_TIMEOUT: Duration = Duration::from_secs(10); /// Steps in one `command_batch`. pub const MAX_BATCH_STEPS: usize = 256; @@ -44,7 +51,7 @@ pub fn client_token(port: u16, supplied: Option) -> Result t, None => { let path = token_file(port); - std::fs::read_to_string(&path) + read_token_file(&path) .map_err(|e| bad(format!("no control token: set {TOKEN_ENV} or start the app with `--control {port}` so it writes {} ({e})", path.display())))? } }; @@ -54,7 +61,8 @@ pub fn client_token(port: u16, supplied: Option) -> Result Result<(String, Option), AutomationError> { if let Ok(t) = std::env::var(TOKEN_ENV) { validate_token(t.trim())?; @@ -62,13 +70,60 @@ pub fn server_token(port: u16) -> Result<(String, Option), AutomationEr } let token = generate_token()?; let path = token_file(port); + write_token_file(&path, &token).map_err(|e| { + AutomationError::Io(format!("cannot write the control token to {} ({e}); set {TOKEN_ENV} to a token of your own instead", path.display())) + })?; + Ok((token, Some(path))) +} + +/// Write `token` to a new file at `path`, readable by the owner only on Unix. Whatever was at +/// `path` is removed first and the file is created exclusively (`O_EXCL`, which never follows +/// a symlink), so a file or link planted in a shared temp folder can neither keep its +/// permissions nor redirect the write; one that cannot be removed (another user's, in a sticky +/// `/tmp`) fails the call. +fn write_token_file(path: &Path, token: &str) -> std::io::Result<()> { + match std::fs::remove_file(path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), + _ => {} + } let mut o = std::fs::OpenOptions::new(); - o.write(true).create(true).truncate(true); + o.write(true).create_new(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600); - let res = o.open(&path).and_then(|mut f| std::io::Write::write_all(&mut f, token.as_bytes())); - res.map_err(|e| AutomationError::Io(format!("cannot write the control token to {}: {e}", path.display())))?; - Ok((token, Some(path))) + let mut f = o.open(path)?; + f.write_all(token.as_bytes())?; + f.sync_all() +} + +/// Read a token file written by [`write_token_file`]. On Unix the file must be a regular file +/// (not a symlink, FIFO or device) owned by this user with no group or other permissions, so a +/// file another user planted is never trusted and a link can't make a client send one of its +/// own secrets as the token. +fn read_token_file(path: &Path) -> std::io::Result { + #[cfg(unix)] + let file = { + use rustix::fs::{Mode, OFlags}; + use std::os::unix::fs::MetadataExt; + let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC; + let file = std::fs::File::from(rustix::fs::open(path, flags, Mode::empty())?); + let meta = file.metadata()?; + let refuse = |why: &str| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("refusing the token file: {why}"))); + if !meta.is_file() { + return refuse("not a regular file"); + } + if meta.uid() != rustix::process::geteuid().as_raw() { + return refuse("owned by another user"); + } + if meta.mode() & 0o077 != 0 { + return refuse("readable or writable by other users"); + } + file + }; + #[cfg(not(unix))] + let file = std::fs::File::open(path)?; + let mut out = String::new(); + file.take(MAX_TOKEN_FILE_BYTES).read_to_string(&mut out)?; + Ok(out) } /// Compare equal-length tokens without an early exit. @@ -134,6 +189,27 @@ impl Drop for Permit { } } +/// Closes a connection that has not authenticated in time, so idle or trickling clients can't +/// hold the few connection slots. Drop it once the client is authenticated (or gone). +pub struct AuthDeadline { + _cancel: Sender<()>, +} + +impl AuthDeadline { + /// Shut `stream` down after `timeout` unless the returned deadline is dropped first. + pub fn start(stream: &TcpStream, timeout: Duration) -> std::io::Result { + let stream = stream.try_clone()?; + let (tx, rx) = channel::<()>(); + std::thread::Builder::new().name("materialcraft-auth-deadline".into()).spawn(move || { + // Dropping the deadline disconnects the channel and ends this thread at once. + if let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(timeout) { + let _ = stream.shutdown(Shutdown::Both); + } + })?; + Ok(AuthDeadline { _cancel: tx }) + } +} + #[cfg(test)] mod tests { use super::*; @@ -149,6 +225,76 @@ mod tests { assert!(client_token(1, Some(format!(" {a}\n"))).is_ok()); } + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("mc-token-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn token_files_round_trip_and_replace_old_ones() { + let dir = scratch("round-trip"); + let path = dir.join("t.token"); + write_token_file(&path, "first-token-0123456789").unwrap(); + assert_eq!(read_token_file(&path).unwrap(), "first-token-0123456789"); + write_token_file(&path, "second-token-0123456789").unwrap(); + assert_eq!(read_token_file(&path).unwrap(), "second-token-0123456789"); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn token_files_are_owner_only_even_over_an_open_file() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("perms"); + let path = dir.join("t.token"); + std::fs::write(&path, "old").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap(); + write_token_file(&path, "fresh-token-0123456789").unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn token_files_never_write_through_a_symlink() { + let dir = scratch("symlink-write"); + let (path, victim) = (dir.join("t.token"), dir.join("victim")); + std::fs::write(&victim, "keep me").unwrap(); + std::os::unix::fs::symlink(&victim, &path).unwrap(); + write_token_file(&path, "fresh-token-0123456789").unwrap(); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me"); + assert!(!std::fs::symlink_metadata(&path).unwrap().file_type().is_symlink()); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn unsafe_token_files_are_refused() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("refuse"); + // Readable by others: another user may have planted or read it. + let open = dir.join("open.token"); + std::fs::write(&open, "planted-token-0123456789").unwrap(); + std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(read_token_file(&open).is_err()); + // A symlink, even to an owner-only file: a client must not send that file as its token. + let secret = dir.join("secret"); + write_token_file(&secret, "private-0123456789abcdef").unwrap(); + let link = dir.join("link.token"); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + assert!(read_token_file(&link).is_err()); + // A FIFO is refused without blocking on open or read. + let fifo = dir.join("fifo.token"); + if std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) { + assert!(read_token_file(&fifo).is_err()); + } + // A directory is not a token. + assert!(read_token_file(&dir).is_err()); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn oversized_lines_are_skipped() { let input = format!("{}\n{{\"ok\":1}}\n", "x".repeat(MAX_REQUEST_BYTES + 10)); @@ -160,6 +306,26 @@ mod tests { assert!(matches!(read_bounded_line(&mut r, &mut line).unwrap(), LineRead::Eof)); } + #[test] + fn auth_deadline_closes_idle_connections_only() { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let idle = TcpStream::connect(addr).unwrap(); + let (server_idle, _) = listener.accept().unwrap(); + let _deadline = AuthDeadline::start(&server_idle, Duration::from_millis(200)).unwrap(); + let mut buf = [0u8; 1]; + idle.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + assert_eq!(std::io::Read::read(&mut &idle, &mut buf).unwrap(), 0, "closed by the deadline"); + + let kept = TcpStream::connect(addr).unwrap(); + let (server_kept, _) = listener.accept().unwrap(); + drop(AuthDeadline::start(&server_kept, Duration::from_millis(200)).unwrap()); + std::thread::sleep(Duration::from_millis(400)); + (&server_kept).write_all(b"x").unwrap(); + kept.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + assert_eq!(std::io::Read::read(&mut &kept, &mut buf).unwrap(), 1, "a met deadline leaves the connection open"); + } + #[test] fn limiter_releases() { let l = ConnectionLimiter::default(); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index b80cbed9..4d2dc1f6 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -154,11 +154,30 @@ pub struct ExportParams { /// 8, 16 or 32 bits (default: the graph's output format). #[serde(default, skip_serializing_if = "Option::is_none")] pub depth: Option, + /// Pixels of the larger side, rounded down to a power of two, 16 to 8192 (default: the graph's size). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, /// Graph index (default: the open graph). #[serde(default, skip_serializing_if = "Option::is_none")] pub graph: Option, } +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +pub struct MaterialExportParams { + /// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The + /// parent folder must exist. + pub path: String, + /// Graph index (default: the open graph). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub graph: Option, + /// Square size in pixels, rounded to a power of two from 16 to 8192 (default: the graph's size). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, + /// Exposed input values to cook with and embed, by input id (see `session_inspect`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub values: Option, +} + #[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] pub struct RenderParams { /// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output). @@ -189,11 +208,10 @@ pub struct RenderParams { /// 3D: UV repeats of the material on the scene for this render only. #[serde(default, skip_serializing_if = "Option::is_none")] pub tiling: Option, - /// 3D beauty render: real displacement from the height output, ambient occlusion and a - /// shadowed key light (slower). + /// 3D beauty render: a finer displaced mesh, ambient occlusion and a shadowed key light (slower). #[serde(default, skip_serializing_if = "Option::is_none")] pub hq: Option, - /// With `hq`: displacement depth in scene radii (default 0.04). + /// With `hq`: displacement depth in scene radii (default: the view's height depth). #[serde(default, skip_serializing_if = "Option::is_none")] pub displacement: Option, } @@ -305,7 +323,7 @@ impl MaterialcraftMcp { b.call(method, p).await } "package.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await, - "package.save" | "package.open" | "bitmap.import" | "outputs.export" | "command.batch" | "render" => { + "package.save" | "package.open" | "bitmap.import" | "outputs.export" | "material.export" | "command.batch" | "render" => { Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)"))) } _ => b.call(method, p).await, @@ -430,6 +448,13 @@ impl MaterialcraftMcp { to_result(self.call("outputs.export", params(&p)).await) } + #[tool(description = "Cook a graph at full size and write it as a portable .mcmat material (cooked maps, exposed inputs, \ + source package) to a path relative to the write root, for TextureCraft. Optional graph, size and exposed input values. \ + Returns {path, bytes}.")] + async fn material_export(&self, Parameters(p): Parameters) -> Result { + to_result(self.call("material.export", params(&p)).await) + } + #[tool(description = "Headless: render the material on the 3D view's scene, or a node's output (view 2d), as a PNG up to \ 2048 px a side. In bridge mode use view_screenshot.")] async fn view_render(&self, Parameters(p): Parameters) -> Result { @@ -471,7 +496,7 @@ impl MaterialcraftMcp { (usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \ (templates: pbr, bricks, wood, …) or package_open, browse nodes with library_list, build with node_add / node_connect \ / node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \ - view_render (3d, or 2d for one node), then package_save and outputs_export. Undo: command_run edit.undo." + view_render (3d, or 2d for one node), then package_save, outputs_export or material_export (.mcmat for TextureCraft). Undo: command_run edit.undo." )] impl ServerHandler for MaterialcraftMcp {} @@ -493,6 +518,25 @@ mod tests { assert!(mcp.call("session.inspect", json!({})).await.is_ok()); } + #[tokio::test(flavor = "multi_thread")] + async fn material_export_tool_writes_through_the_workspace_only() { + let base = std::env::temp_dir().join(format!("mc-mcp-{}-material", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let args = || Parameters(MaterialExportParams { path: "m".into(), graph: None, size: Some(16), values: None }); + + let denied = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied)); + assert_eq!(denied.material_export(args()).await.unwrap().is_error, Some(true)); + + let ws = crate::AuthorizedWorkspace::new(None, Some(&base)).unwrap(); + let mcp = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws))); + assert_eq!(mcp.material_export(args()).await.unwrap().is_error, Some(false)); + assert!(base.join("m.mcmat").is_file()); + let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None, size: Some(16), values: None }); + assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true)); + assert!(!base.parent().unwrap().join("m.mcmat").exists()); + } + #[test] fn oversized_replies_become_errors() { let r = ok_json(&json!("x".repeat(crate::budgets::MAX_RESPONSE_BYTES))); diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 61c18446..80812243 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -69,6 +69,13 @@ impl AuthorizedWorkspace { Ok(()) } + /// Fail now, before any expensive work, when [`write`](Self::write) to `path` cannot succeed + /// for lack of a write root or because the path is malformed. + pub fn check_write(&self, path: &str) -> Result<(), AutomationError> { + relative_path(path)?; + self.write.as_ref().map(|_| ()).ok_or_else(|| denied("write")) + } + /// Create a directory (and its parents) below the write root. pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> { let rel = relative_path(path)?; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index d1cc674e..caa14a9c 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -17,7 +17,7 @@ pub use graph::{ Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat, Pin, Preset, SizeMode, missing_ports, }; -pub use package::{PACKAGE_EXT, Package, Resource}; +pub use package::{PACKAGE_EXT, Package, Resource, ResourceBytes}; pub use value::{Curve, CurvePoint, Gradient, GradientKey, Value, linear_to_srgb, parse_color, srgb_to_linear}; #[derive(Debug, thiserror::Error)] diff --git a/crates/core/src/package.rs b/crates/core/src/package.rs index 44d0c361..e00541e2 100644 --- a/crates/core/src/package.rs +++ b/crates/core/src/package.rs @@ -1,5 +1,6 @@ //! Packages: the document. A package holds graphs and the resources (bitmaps) they use. +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; use serde::{Deserialize, Serialize}; @@ -18,7 +19,68 @@ pub struct Resource { pub file: String, /// The file's bytes (stored in the zip, not in `package.json`). #[serde(skip)] - pub bytes: Arc>, + pub bytes: ResourceBytes, +} + +impl Resource { + /// A resource named `name`, stored as `file` in the package. + pub fn new(name: impl Into, file: impl Into, bytes: ResourceBytes) -> Resource { + Resource { name: name.into(), file: file.into(), bytes } + } +} + +/// A resource's bytes with a hash of their whole content, computed once when the bytes are +/// set, so caches can key on content (two files of one size are not the same image). +#[derive(Clone, Debug)] +pub struct ResourceBytes { + bytes: Arc>, + hash: u64, +} + +impl ResourceBytes { + /// Take ownership of `bytes` and hash them. + pub fn new(bytes: Vec) -> ResourceBytes { + let mut h = DefaultHasher::new(); + bytes.hash(&mut h); + ResourceBytes { hash: h.finish(), bytes: Arc::new(bytes) } + } + + /// The bytes. + pub fn as_slice(&self) -> &[u8] { + &self.bytes + } + + /// Number of bytes. + pub fn len(&self) -> usize { + self.bytes.len() + } + + /// Whether there are no bytes. + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } + + /// Hash of the whole content. + pub fn content_hash(&self) -> u64 { + self.hash + } + + /// Whether both values share one allocation (cheap clones of one file). + pub fn ptr_eq(&self, other: &ResourceBytes) -> bool { + Arc::ptr_eq(&self.bytes, &other.bytes) + } +} + +impl Default for ResourceBytes { + fn default() -> Self { + ResourceBytes::new(Vec::new()) + } +} + +impl PartialEq for ResourceBytes { + fn eq(&self, other: &Self) -> bool { + self.hash == other.hash && self.bytes == other.bytes + } } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -66,3 +128,20 @@ impl Package { (1..).map(|i| format!("{base}_{i}")).find(|n| self.graph_by_name(n).is_none()).unwrap_or_else(|| base.to_string()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn same_length_same_prefix_bytes_hash_differently() { + let a = vec![7u8; 200]; + let mut b = a.clone(); + b[150] = 8; + let (a, b) = (ResourceBytes::new(a), ResourceBytes::new(b)); + assert_eq!(a.len(), b.len()); + assert_ne!(a.content_hash(), b.content_hash()); + assert_ne!(a, b); + assert_eq!(ResourceBytes::default(), ResourceBytes::new(Vec::new())); + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index b3cef862..e386d125 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -7,7 +7,7 @@ use serde_json::{Value as J, json}; -use materialcraft_core::{Package, Resource}; +use materialcraft_core::{Package, Resource, ResourceBytes}; use materialcraft_formats::{Depth, encode, output_name}; use crate::commands::{CommandSpec, always, bad, has_graph, strp, u64p}; @@ -50,7 +50,7 @@ pub(crate) fn specs() -> Vec { "Export outputs...", ["File"], Some("Ctrl+Shift+E"), - "{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), graph?} cooks the graph at full size and writes every output", + "{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px of the larger side, rounded down to a power of two, 16..8192; default the graph's size, keeping its proportions), graph?} cooks the graph at full size and writes every output", has_graph, export ), @@ -95,6 +95,7 @@ fn new_package(s: &mut Session, p: &J) -> Result { /// Make `pkg` the session's document (after open/new): history and views reset. pub fn replace_package(s: &mut Session, pkg: Package, path: Option) { s.pkg = pkg; + s.clear_decoded(); s.path = path; s.graph = 0; s.selection.clear(); @@ -265,9 +266,19 @@ pub struct Exported { } /// Cook graph `gi` at full size and encode every output (`pattern` names files). -pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: Option) -> Result> { - let g = s.pkg.graph(gi)?; - let cooked = s.cook_full(gi); +pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: Option, size: Option) -> Result> { + let mut pkg = s.pkg.clone(); + if let Some(px) = size { + let g = pkg.graph_mut(gi)?; + // The larger side becomes `px`; the other keeps its proportion. + let target = 31 - px.clamp(16, 8192).leading_zeros(); + let bounded = g.size.map(|l| l.clamp(4, 13)); + let larger = bounded[0].max(bounded[1]); + g.size = bounded.map(|l| (l + target).saturating_sub(larger).max(4)); + } + let g = pkg.graph(gi)?; + let dec = s.resource_decoder(); + let cooked = materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &s.cache); let mut out = Vec::new(); for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) { let Some(img) = img else { continue }; @@ -283,8 +294,10 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O Ok(out) } -/// Export params: (graph index, extension, pattern, depth). -pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option)> { +/// Export params: (graph index, extension, pattern, depth, size). +pub type ExportArgs = (usize, String, String, Option, Option); + +pub fn export_params(s: &Session, p: &J) -> Result { let gi = u64p(p, "graph").map_or(s.graph, |g| g as usize); s.pkg.graph(gi)?; let ext = strp(p, "format").unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); @@ -299,14 +312,15 @@ pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Optio Some(32) => Some(Depth::F32), Some(d) => return Err(bad("file.export", format!("depth must be 8, 16 or 32, not {d}"))), }; - Ok((gi, ext, pattern, depth)) + let size = u64p(p, "size").filter(|&px| px > 0).map(|px| px.min(u64::from(u32::MAX)) as u32); + Ok((gi, ext, pattern, depth, size)) } #[cfg(not(target_arch = "wasm32"))] fn export(s: &mut Session, p: &J) -> Result { let dir = strp(p, "dir").ok_or_else(|| bad("file.export", "`dir` is required"))?; - let (gi, ext, pattern, depth) = export_params(s, p)?; - let files = export_outputs(s, gi, &ext, &pattern, depth)?; + let (gi, ext, pattern, depth, size) = export_params(s, p)?; + let files = export_outputs(s, gi, &ext, &pattern, depth, size)?; std::fs::create_dir_all(dir).map_err(|e| bad("file.export", format!("{dir}: {e}")))?; let mut written = Vec::new(); for f in files { @@ -339,7 +353,7 @@ pub(crate) fn push_resource(pkg: &mut Package, file: &str, bytes: Vec, name: name = format!("{stem}_{i}"); i += 1; } - pkg.resources.push(Resource { name: name.clone(), file: format!("{name}_{file}"), bytes: std::sync::Arc::new(bytes) }); + pkg.resources.push(Resource::new(name.clone(), format!("{name}_{file}"), ResourceBytes::new(bytes))); name } diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index c5902b97..0f7f51e2 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -72,10 +72,7 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result)> = Vec::new(); let mut entries = Vec::new(); let mut size = [0, 0]; @@ -144,13 +141,21 @@ fn graph_param(s: &Session, p: &J) -> Result { Ok(gi) } +/// The graph and cook options a material export request asks for: `graph?`, `size?` (px) and +/// `values?` (exposed input values). Shared by `file.exportMaterial` and the workspace-scoped +/// automation export, which supply their own destination. +pub fn material_request(s: &Session, cmd: &str, p: &J) -> Result<(usize, MaterialOptions)> { + let gi = graph_param(s, p)?; + let o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(cmd, s.pkg.graph(gi)?, p)?, ..Default::default() }; + Ok((gi, o)) +} + #[cfg(not(target_arch = "wasm32"))] fn export_material(s: &mut Session, p: &J) -> Result { const CMD: &str = "file.exportMaterial"; let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") }; - let gi = graph_param(s, p)?; - let mut o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(CMD, s.pkg.graph(gi)?, p)?, ..Default::default() }; + let (gi, mut o) = material_request(s, CMD, p)?; for (id, file) in p.get("inputs").and_then(J::as_object).into_iter().flatten() { let file = file.as_str().ok_or_else(|| bad(CMD, format!("inputs.{id} must be an image path")))?; let bytes = std::fs::read(file).map_err(|e| bad(CMD, format!("{file}: {e}")))?; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7dbdeaea..d61f6595 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex, PoisonError}; -use materialcraft_core::{Graph, NodeId, Package}; +use materialcraft_core::{Graph, NodeId, Package, ResourceBytes}; use materialcraft_eval::{Cache, Cooked, Options}; use materialcraft_image::Image; use serde::{Deserialize, Serialize}; @@ -32,8 +32,10 @@ pub struct View3d { pub environment: String, pub env_rotation: f32, pub exposure: f32, - /// Parallax depth of the height output (0 = off). + /// How far the height output raises the surface (white above black), in mesh radii; 0 = off. pub height_scale: f32, + /// The height (0..1) that stays on the surface: 0 = the relief rises out of the mesh, 0.5 = centered on it. + pub height_level: f32, pub show_axis: bool, pub show_grid: bool, /// See through the mesh where the material's alpha (opacity output, else base color alpha) @@ -55,7 +57,8 @@ impl Default for View3d { environment: "studio".into(), env_rotation: 0.0, exposure: 0.0, - height_scale: 0.012, + height_scale: 0.04, + height_level: 0.0, show_axis: false, show_grid: false, transparency: true, @@ -158,7 +161,7 @@ pub struct Session { redo: Vec, /// Edits with the same key coalesce into one undo step (slider drags). merge_key: Option, - decoded: Arc>>, + decoded: Arc>>, } impl Session { @@ -298,40 +301,42 @@ impl Session { /// A decoder for the package's bitmap resources (memoized, shareable with worker threads). pub fn resource_decoder(&self) -> impl Fn(&str) -> Option + Sync + Send + 'static { - let res: Vec<(String, Arc>)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); + let res: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); let memo = self.decoded.clone(); + // Free images of resources that were deleted or replaced. + memo.lock().unwrap_or_else(PoisonError::into_inner).retain(|k, _| res.iter().any(|(_, b)| b.content_hash() == *k)); move |name: &str| { let (_, bytes) = res.iter().find(|(n, _)| n == name)?; - let key = format!("{name}:{}", bytes.len()); + let key = bytes.content_hash(); if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { return Some(i.clone()); } - let img = materialcraft_formats::decode(bytes).ok()?; + let img = materialcraft_formats::decode(bytes.as_slice()).ok()?; memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone()); Some(img) } } + /// Forget every decoded resource image (the package was replaced). + pub(crate) fn clear_decoded(&self) { + self.decoded.lock().unwrap_or_else(PoisonError::into_inner).clear(); + } + /// Cook the open graph now (at the preview size), on this thread. pub fn cook(&mut self) -> &Cooked { let dec = self.resource_decoder(); let mut opts = Options::new(&dec); opts.max_size = self.preview_size; - let cooked = { - let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); - materialcraft_eval::cook(&self.pkg, self.graph, &opts, &mut cache) - }; - self.cooked = cooked; + self.cooked = materialcraft_eval::cook(&self.pkg, self.graph, &opts, &self.cache); self.dirty = false; &self.cooked } - /// Cook graph `gi` at full size (exports), without touching the preview results. + /// Cook graph `gi` at full size, without touching the preview results. pub fn cook_full(&self, gi: usize) -> Cooked { let dec = self.resource_decoder(); let opts = Options::new(&dec); - let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); - materialcraft_eval::cook(&self.pkg, gi, &opts, &mut cache) + materialcraft_eval::cook(&self.pkg, gi, &opts, &self.cache) } /// Cook if the graph changed since the last cook. diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 5b3299e3..d1beb70d 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -29,7 +29,7 @@ pub(crate) fn specs() -> Vec { "3D view settings", [], None, - "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", + "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", always, view3d ), @@ -138,6 +138,9 @@ fn view3d(s: &mut Session, p: &J) -> Result { if let Some(t) = f32p(p, "heightScale") { v.height_scale = t.clamp(0.0, 0.5); } + if let Some(t) = f32p(p, "heightLevel") { + v.height_level = t.clamp(0.0, 1.0); + } if let Some(b) = boolp(p, "axis") { v.show_axis = b; } diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs new file mode 100644 index 00000000..99fc053b --- /dev/null +++ b/crates/engine/tests/perf.rs @@ -0,0 +1,55 @@ +//! Cook benchmarks (run with `--ignored --nocapture` in release). +use std::time::Instant; + +use materialcraft_engine::{Session, execute, sample_session}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + execute(s, id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +/// The `rusty_metal` template plus an exposed input `level` read by one unconnected `uniform`. +fn heavy(size: u64) -> (Session, u64) { + let mut s = sample_session(); + run(&mut s, "file.new", json!({"template": "rusty_metal", "size": size})); + s.preview_size = None; + let u = run(&mut s, "graph.node.add", json!({"def": "uniform", "params": {"mode": 1}}))["id"].as_u64().unwrap(); + run(&mut s, "graph.exposed.add", json!({"id": "level", "default": {"t": "float", "v": 0.25}})); + let f = json!({"nodes": [{"id": 1, "op": "get_var", "value": {"t": "text", "v": "level"}}], "output": 1}); + run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "function": f})); + (s, u) +} + +fn timed(s: &mut Session) -> (f64, usize, usize) { + let t = Instant::now(); + s.cook(); + let ms = t.elapsed().as_secs_f64() * 1000.0; + (ms, s.cooked.nodes.values().filter(|r| !r.cached).count(), s.cooked.nodes.len()) +} + +#[test] +#[ignore = "benchmark"] +fn bench_input_change() { + println!("size, cold_ms, warm_ms, input_change_ms, recooked_nodes, total_nodes"); + for size in [1024, 2048] { + let (mut s, _) = heavy(size); + let (cold, ..) = timed(&mut s); + let (warm, ..) = timed(&mut s); + run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75})); + let (change, recooked, total) = timed(&mut s); + println!("{size}, {cold:.1}, {warm:.1}, {change:.1}, {recooked}, {total}"); + } +} + +#[test] +#[ignore = "benchmark"] +fn bench_param_edit() { + println!("size, cold_ms, param_edit_ms, recooked_nodes, total_nodes"); + for size in [1024, 2048] { + let (mut s, u) = heavy(size); + let (cold, ..) = timed(&mut s); + run(&mut s, "graph.node.param", json!({"id": u, "param": "mode", "value": 0})); + let (edit, recooked, total) = timed(&mut s); + println!("{size}, {cold:.1}, {edit:.1}, {recooked}, {total}"); + } +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 60a98866..3d019a6e 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -83,9 +83,35 @@ fn package_save_and_open_round_trip() { let out = dir.join("tex"); let r = run(&mut s, "file.export", json!({"dir": out.to_str().unwrap(), "format": "png", "depth": 8})); assert_eq!(r["files"].as_array().unwrap().len(), 6); + let small = dir.join("small"); + run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64})); + let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path(); + let img = materialcraft_formats::decode(&std::fs::read(file).unwrap()).unwrap(); + assert_eq!((img.w, img.h), (64, 64)); let _ = std::fs::remove_dir_all(&dir); } +/// `file.export` `size` is the larger side in pixels; 0 means the graph's size and the proportions are kept. +#[test] +fn export_size_keeps_proportions_and_clamps() { + let mut s = sample_session(); + s.pkg.graphs[0].size = [7, 6]; + let dims = |s: &Session, size: Value| { + let (gi, ext, pattern, depth, size) = materialcraft_engine::file_cmds::export_params(s, &json!({"size": size})).unwrap(); + let files = materialcraft_engine::file_cmds::export_outputs(s, gi, &ext, &pattern, depth, size).unwrap(); + files.iter().map(|f| materialcraft_formats::decode(&f.bytes).unwrap()).map(|i| (i.w, i.h)).collect::>() + }; + for size in [json!(0), json!(null)] { + assert!(dims(&s, size).iter().all(|d| *d == (128, 64))); + } + assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 16))); + let parsed = |size: Value| materialcraft_engine::file_cmds::export_params(&s, &json!({"size": size})).unwrap().4; + assert_eq!(parsed(json!(0)), None); + assert_eq!(parsed(json!(u64::MAX)), Some(u32::MAX)); + s.pkg.graphs[0].size = [u32::MAX, u32::MAX]; + assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32))); +} + /// A scratch folder for one test, removed when dropped. struct TempDir(std::path::PathBuf); @@ -267,6 +293,22 @@ fn dynamic_parameters_follow_graph_inputs() { assert!((mean(&s) - 0.5).abs() < 0.05); } +#[test] +fn exposed_input_change_recooks_only_readers() { + let mut s = sample_session(); + run(&mut s, "file.new", json!({"template": "rusty_metal", "size": 64})); + s.preview_size = None; + let u = run(&mut s, "graph.node.add", json!({"def": "uniform", "params": {"mode": 1}}))["id"].as_u64().unwrap(); + run(&mut s, "graph.exposed.add", json!({"id": "level", "default": {"t": "float", "v": 0.25}})); + let f = json!({"nodes": [{"id": 1, "op": "get_var", "value": {"t": "text", "v": "level"}}], "output": 1}); + run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "function": f})); + s.cook(); + run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75})); + s.cook(); + let recooked: Vec = s.cooked.nodes.iter().filter(|(_, r)| !r.cached).map(|(id, _)| id.0).collect(); + assert_eq!(recooked, [u], "only the node reading `level` re-cooks"); +} + #[test] fn presets_store_and_restore_inputs() { let mut s = sample_session(); @@ -297,6 +339,24 @@ fn view3d_target_is_validated_clamped_and_reset() { assert_eq!(s.view3d.target, [0.0; 3]); } +/// The height output rises out of the mesh by default; depth and level are clamped and reset with the scene. +#[test] +fn view3d_height_depth_and_level_are_clamped_and_reset() { + let mut s = sample_session(); + assert_eq!(s.view3d.height_level, 0.0, "the relief rises out of the surface by default"); + assert!(s.view3d.height_scale > 0.0); + + let view = run(&mut s, "view.3d", json!({"heightScale": 0.1, "heightLevel": 0.5})); + assert_eq!((view["heightScale"].as_f64(), view["heightLevel"].as_f64()), (Some(0.1f32 as f64), Some(0.5))); + run(&mut s, "view.3d", json!({"heightScale": 9.0, "heightLevel": -3.0})); + assert_eq!((s.view3d.height_scale, s.view3d.height_level), (0.5, 0.0)); + run(&mut s, "view.3d", json!({"heightLevel": 7.0})); + assert_eq!(s.view3d.height_level, 1.0); + + run(&mut s, "view.3d.reset", json!({})); + assert_eq!(s.view3d.height_level, 0.0); +} + #[test] fn camera_prefs_bound_the_pan_and_survive_hostile_values() { use materialcraft_engine::CameraPrefs; @@ -317,6 +377,22 @@ fn camera_prefs_bound_the_pan_and_survive_hostile_values() { assert_eq!(CameraPrefs { pan_limit: f32::INFINITY, pan_speed: 2.0 }.sanitized().pan_speed, 2.0); } +#[test] +fn reimported_bitmap_shows_new_pixels() { + use materialcraft_formats::{Depth, encode}; + use materialcraft_image::{Image, Kind}; + let bmp = |v: f32| encode(&Image::filled(4, 4, Kind::Color, [v, v, v, 1.0]), "bmp", Depth::U8, true).unwrap(); + let (dark, light) = (bmp(0.1), bmp(0.9)); + assert_eq!(dark.len(), light.len(), "same-size files are the case under test"); + let mut s = sample_session(); + materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", dark, Some("tex")).unwrap(); + let before = s.resource_decoder()("tex").unwrap().data[0]; + s.undo(); + materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", light, Some("tex")).unwrap(); + let after = s.resource_decoder()("tex").unwrap().data[0]; + assert!(after - before > 0.5, "{before} -> {after}"); +} + #[test] fn a_wire_splits_with_a_reroute_dot_and_deletes() { let mut s = sample_session(); diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 5932bd7e..fb8e5246 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -9,14 +9,14 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; use materialcraft_core::{Graph, Node, NodeId, Package, SizeMode, Value}; use materialcraft_image::{Image, Kind}; -use materialcraft_nodes::{Ctx, NodeDef, PortKind, find, resolve_params}; +use materialcraft_nodes::{Ctx, NodeDef, PortKind, clamp_params, find, resolve_params}; /// Sub-graphs may nest this deep (a graph instancing itself would recurse forever). pub const MAX_DEPTH: u32 = 8; @@ -184,11 +184,13 @@ pub struct Options<'a> { /// Set from another thread to stop between nodes. pub cancel: Option<&'a AtomicBool>, pub depth: u32, + /// Graphs being cooked around this one, outermost first (cycle detection). + pub graph_stack: Vec, } impl<'a> Options<'a> { pub fn new(resource: &'a (dyn Fn(&str) -> Option + Sync)) -> Options<'a> { - Options { max_size: None, only: None, inputs: BTreeMap::new(), overrides: BTreeMap::new(), resource, cancel: None, depth: 0 } + Options { max_size: None, only: None, inputs: BTreeMap::new(), overrides: BTreeMap::new(), resource, cancel: None, depth: 0, graph_stack: Vec::new() } } } @@ -257,8 +259,14 @@ pub fn function_value(like: &Value, v: [f32; 4]) -> Option { }) } -/// Cook graph `gi` of `pkg`. -pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cooked { +/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written). +fn lock(cache: &Mutex) -> std::sync::MutexGuard<'_, Cache> { + cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Cook graph `gi` of `pkg`. The cache is locked only around lookups and inserts, never while a +/// node cooks, so other users of the cache are not blocked for the length of a cook. +pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &Mutex) -> Cooked { let t0 = now_ms(); let mut out = Cooked::default(); let Some(graph) = pkg.graphs.get(gi) else { return out }; @@ -267,7 +275,7 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook let opts = if opts.depth == 0 && !graph.input_images.is_empty() { let mut inputs: BTreeMap = graph.input_images.iter().filter_map(|(id, res)| Some((id.clone(), (opts.resource)(res)?))).collect(); inputs.extend(opts.inputs.iter().map(|(k, v)| (k.clone(), v.clone()))); - bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), ..*opts }; + bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), graph_stack: opts.graph_stack.clone(), ..*opts }; &bound } else { opts @@ -294,14 +302,68 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook break; } let Ok(node) = graph.node(id) else { continue }; - let r = cook_node(pkg, graph, node, &out, &vars, opts, cache); + let r = cook_node(pkg, gi, graph, node, &out, &vars, opts, cache); out.nodes.insert(id, r); } out.ms = (now_ms() - t0) as f32; out } -fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BTreeMap, opts: &Options, cache: &mut Cache) -> NodeResult { +/// Hash each reachable graph and its resource content once. An iterative walk keeps +/// deep chains and graphs with many shared instances bounded by the package size. +fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 { + let mut h = DefaultHasher::new(); + let mut pending = vec![gi]; + let mut seen = HashSet::new(); + while let Some(index) = pending.pop() { + if !seen.insert(index) { + continue; + } + let Some(graph) = pkg.graphs.get(index) else { continue }; + index.hash(&mut h); + serde_json::to_string(graph).unwrap_or_default().hash(&mut h); + for n in &graph.nodes { + if let Some(Value::Text(name)) = n.params.get("resource") { + pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h); + } + if n.def == "graph_instance" + && let Some((si, _)) = instance_graph(pkg, n) + { + pending.push(si); + } + } + } + h.finish() +} + +/// The graph inputs a node's cook can read: those named by `get_*` ops of its function-valued +/// parameters. Bindings and node functions are already folded into `params` before the key is +/// computed, so these are the only remaining readers of `vars` (`Ctx::vars` in the function nodes). +/// Matching every `get_*` op, not only `get_var`, over-approximates on purpose. +fn vars_read<'v>(params: &BTreeMap, vars: &'v BTreeMap) -> Vec<(&'v str, &'v Value)> { + let mut read: Vec<(&str, &Value)> = params + .values() + .filter_map(|v| if let Value::Function(g) = v { Some(g) } else { None }) + .flat_map(|g| g.nodes.iter()) + .filter(|n| n.op.starts_with("get_")) + .filter_map(|n| if let Some(Value::Text(name)) = &n.value { vars.get_key_value(name.as_str()) } else { None }) + .map(|(k, v)| (k.as_str(), v)) + .collect(); + read.sort_by_key(|(k, _)| *k); + read.dedup_by_key(|(k, _)| *k); + read +} + +fn cook_node( + pkg: &Package, + gi: usize, + graph: &Graph, + node: &Node, + done: &Cooked, + vars: &BTreeMap, + opts: &Options, + cache: &Mutex, +) -> NodeResult { let (in_ports, out_ports) = ports(pkg, node); let def = find(&node.def); // Gather inputs by port order, with their keys. @@ -352,15 +414,20 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT Err(e) => return fail(format!("function of `{param}`: {e}"), 0), } } + // Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook). + if let Some(d) = def + && node.def != "graph_instance" + { + clamp_params(d, &mut params); + } let tile = node.base.tiling[0] && node.base.tiling[1]; // Input nodes read the caller's image for their identifier. let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); let res_hash = match params.get("resource") { - Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| hash_of(&(r.bytes.len(), r.bytes.get(..64.min(r.bytes.len())).map(|b| b.to_vec())))), + Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()), _ => 0, }; - let sub_hash = - if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(_, g)| hash_of(&serde_json::to_string(g).unwrap_or_default())) } else { 0 }; + let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 }; let key = hash_of(&( &node.def, serde_json::to_string(¶ms).unwrap_or_default(), @@ -369,9 +436,9 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT res_hash, sub_hash, input_img.map(image_key), - serde_json::to_string(vars).unwrap_or_default(), + serde_json::to_string(&vars_read(¶ms, vars)).unwrap_or_default(), )); - if let Some(v) = cache.get(key) { + if let Some(v) = lock(cache).get(key) { return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; } let t0 = now_ms(); @@ -384,7 +451,7 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT let name = if node.label.is_empty() { "this node" } else { node.label.as_str() }; Err(format!("`{name}` is not in MaterialCraft's library yet: kept as a placeholder from the SBS file")) } else if node.def == "graph_instance" { - cook_instance(pkg, node, &in_ports, &out_ports, &inputs, ¶ms, (w, h), opts, cache) + cook_instance(pkg, gi, node, &in_ports, &out_ports, &inputs, ¶ms, (w, h), opts, cache) } else if let Some(d) = def { let ctx = Ctx { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; (d.cook)(&ctx) @@ -394,7 +461,7 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT match result { Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => { let v = Arc::new(imgs); - cache.put(key, v.clone()); + lock(cache).put(key, v.clone()); NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false } } Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key), @@ -402,8 +469,28 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT } } +/// Whether graph `from` reaches `target`, without recursive stack growth. +fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool { + let mut pending = vec![from]; + let mut seen = HashSet::new(); + while let Some(index) = pending.pop() { + if !seen.insert(index) { + continue; + } + let Some(graph) = pkg.graphs.get(index) else { continue }; + for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) { + if si == target { + return true; + } + pending.push(si); + } + } + false +} + fn cook_instance( pkg: &Package, + gi: usize, node: &Node, in_ports: &[Port], out_ports: &[Port], @@ -411,19 +498,24 @@ fn cook_instance( params: &BTreeMap, size: (u32, u32), opts: &Options, - cache: &mut Cache, + cache: &Mutex, ) -> Result, String> { if opts.depth >= MAX_DEPTH { return Err("graph instances nest too deep (does a graph use itself?)".into()); } - let (gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; + let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; + if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) { + return Err(format!("graph `{}` uses itself through a graph instance", sub.name)); + } let mut o = Options::new(opts.resource); o.max_size = opts.max_size; o.cancel = opts.cancel; o.depth = opts.depth + 1; + o.graph_stack = opts.graph_stack.clone(); + o.graph_stack.push(gi); o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect(); o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); - let cooked = cook(pkg, gi, &o, cache); + let cooked = cook(pkg, sub_gi, &o, cache); if cooked.cancelled { return Err("cancelled".into()); } @@ -489,30 +581,42 @@ mod tests { #[test] fn cooks_and_caches() { let (mut p, noise, blur, out) = sample(); - let mut cache = Cache::default(); + let cache = Mutex::new(Cache::default()); let opts = Options::new(&no_res); - let a = cook(&p, 0, &opts, &mut cache); + let a = cook(&p, 0, &opts, &cache); assert!(a.nodes.values().all(|r| r.error.is_none() && !r.cached)); assert_eq!(a.image(out, 0).map(|i| (i.w, i.h)), Some((64, 64))); // Same graph: everything from the cache. - let b = cook(&p, 0, &opts, &mut cache); + let b = cook(&p, 0, &opts, &cache); assert!(b.nodes.values().all(|r| r.cached)); // Editing the blur re-cooks the blur and the output, not the noise. p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(5.0)); - let c = cook(&p, 0, &opts, &mut cache); + let c = cook(&p, 0, &opts, &cache); assert!(c.nodes[&noise].cached && !c.nodes[&blur].cached && !c.nodes[&out].cached); assert_eq!(outputs(&p.graphs[0], &c).len(), 1); } + #[test] + fn hostile_param_is_clamped_before_cooking() { + let (mut p, noise, _, _) = sample(); + let blur = p.graphs[0].add_node("anisotropic_blur", [150.0, 100.0]); + p.graphs[0].connect(noise, "output", blur, "input").unwrap(); + p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1e30)); + let cache = Mutex::new(Cache::default()); + let c = cook(&p, 0, &Options::new(&no_res), &cache); + assert!(c.nodes[&blur].error.is_none(), "{:?}", c.nodes[&blur].error); + assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((64, 64))); + } + #[test] fn preview_cap_and_unknown_nodes() { let (mut p, _, _, out) = sample(); p.graphs[0].size = [10, 10]; let bad = p.graphs[0].add_node("no_such_node", [0.0, 0.0]); - let mut cache = Cache::default(); + let cache = Mutex::new(Cache::default()); let mut opts = Options::new(&no_res); opts.max_size = Some(128); - let c = cook(&p, 0, &opts, &mut cache); + let c = cook(&p, 0, &opts, &cache); assert_eq!(c.image(out, 0).map(|i| i.w), Some(128)); assert!(c.nodes[&bad].error.is_some()); } @@ -539,11 +643,113 @@ mod tests { // A graph instancing itself is refused, not a stack overflow. let selfi = g.add_node("graph_instance", [0.0, 200.0]); g.node_mut(selfi).unwrap().params.insert("graph".into(), Value::Text("g".into())); - let mut cache = Cache::default(); - let c = cook(&p, 0, &Options::new(&no_res), &mut cache); + let cache = Mutex::new(Cache::default()); + let c = cook(&p, 0, &Options::new(&no_res), &cache); let img = c.image(inst, 0).unwrap(); assert!((img.data[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data[0]); - assert!(c.nodes[&selfi].error.is_some() || c.nodes[&selfi].outputs.len() == 1); + assert!(c.nodes[&selfi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&selfi].error); + } + + /// A graph `name` holding one instance of `target` wired to an output. + fn instancing(name: &str, target: &str) -> (Graph, NodeId) { + let mut g = Graph::new(name); + g.size = [4, 4]; + let inst = g.add_node("graph_instance", [0.0, 0.0]); + g.node_mut(inst).unwrap().params.insert("graph".into(), Value::Text(target.into())); + let o = g.add_node("output", [100.0, 0.0]); + g.connect(inst, "output", o, "input").unwrap(); + (g, inst) + } + + #[test] + fn editing_a_nested_graph_recooks_the_top() { + let mut c = Graph::new("c"); + c.size = [4, 4]; + let u = c.add_node("uniform", [0.0, 0.0]); + c.node_mut(u).unwrap().params.insert("mode".into(), Value::Enum(1)); + c.node_mut(u).unwrap().params.insert("color".into(), Value::Color([0.2, 0.2, 0.2, 1.0])); + let o = c.add_node("output", [100.0, 0.0]); + c.connect(u, "output", o, "input").unwrap(); + let (b, _) = instancing("b", "c"); + let (a, top) = instancing("a", "b"); + let mut p = Package::new("p"); + p.graphs = vec![a, b, c]; + let cache = Mutex::new(Cache::default()); + let opts = Options::new(&no_res); + let first = cook(&p, 0, &opts, &cache); + let out_a = p.graphs[0].nodes.iter().find(|n| n.def == "output").unwrap().id; + assert!((first.image(out_a, 0).unwrap().mean()[0] - 0.2).abs() < 0.01); + p.graphs[2].node_mut(u).unwrap().params.insert("color".into(), Value::Color([0.8, 0.8, 0.8, 1.0])); + let second = cook(&p, 0, &opts, &cache); + assert!(!second.nodes[&top].cached); + assert!((second.image(out_a, 0).unwrap().mean()[0] - 0.8).abs() < 0.01); + } + + #[test] + fn deep_shared_instance_walks_stay_bounded() { + std::thread::Builder::new() + .stack_size(128 * 1024) + .spawn(|| { + let mut pkg = Package::new("deep"); + for index in 0..2000 { + let mut graph = Graph::new(&format!("g{index}")); + // Repeated references must visit the next graph only once. + for _ in 0..4 { + let id = graph.add_node("graph_instance", [0.0; 2]); + graph.node_mut(id).unwrap().params.insert("graph".into(), Value::Text(format!("g{}", index + 1))); + } + pkg.graphs.push(graph); + } + assert!(instances_reach(&pkg, 0, 1999)); + assert!(!instances_reach(&pkg, 0, 2000)); + let before = graph_tree_hash(&pkg, 0); + pkg.graphs[1999].seed = 42; + assert_ne!(before, graph_tree_hash(&pkg, 0)); + // A back edge must terminate both traversals too. + pkg.graphs[1999].nodes[0].params.insert("graph".into(), Value::Text("g0".into())); + assert!(instances_reach(&pkg, 1, 0)); + assert!(!instances_reach(&pkg, 0, 2000)); + assert_ne!(before, graph_tree_hash(&pkg, 0)); + }) + .unwrap() + .join() + .unwrap(); + } + + #[test] + fn mutual_instances_are_an_error() { + let (x, xi) = instancing("x", "y"); + let (y, _) = instancing("y", "x"); + let mut p = Package::new("p"); + p.graphs = vec![x, y]; + let cache = Mutex::new(Cache::default()); + let c = cook(&p, 0, &Options::new(&no_res), &cache); + assert!(c.nodes[&xi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&xi].error); + } + + #[test] + fn same_size_resources_key_differently() { + use materialcraft_core::{Resource, ResourceBytes}; + use std::sync::atomic::AtomicU8; + let mut g = Graph::new("g"); + g.size = [4, 4]; + let bm = g.add_node("bitmap", [0.0, 0.0]); + g.node_mut(bm).unwrap().params.insert("resource".into(), Value::Text("tex".into())); + let mut p = Package::new("p"); + p.graphs.push(g); + p.resources.push(Resource::new("tex", "tex.bin", ResourceBytes::new(vec![1; 100]))); + // Stands in for decoding: the first byte picks the shade. + let shade = AtomicU8::new(1); + let res = |_: &str| Some(Image::filled(4, 4, Kind::Gray, [f32::from(shade.load(Ordering::Relaxed)) / 10.0; 4])); + let cache = Mutex::new(Cache::default()); + let opts = Options::new(&res); + let first = cook(&p, 0, &opts, &cache); + let mean = first.image(bm, 0).unwrap().mean()[0]; + p.resources[0].bytes = ResourceBytes::new(vec![2; 100]); + shade.store(2, Ordering::Relaxed); + let second = cook(&p, 0, &opts, &cache); + assert!(!second.nodes[&bm].cached); + assert!((second.image(bm, 0).unwrap().mean()[0] - mean).abs() > 0.05); } #[test] @@ -558,14 +764,34 @@ mod tests { g.input_images.insert("curvature".into(), "curv".into()); p.graphs.push(g); let res = |n: &str| (n == "curv").then(|| Image::filled(4, 4, Kind::Color, [0.8, 0.8, 0.8, 1.0])); - let mut cache = Cache::default(); - let c = cook(&p, 0, &Options::new(&res), &mut cache); + let cache = Mutex::new(Cache::default()); + let c = cook(&p, 0, &Options::new(&res), &cache); let img = c.image(o, 0).unwrap(); assert!(img.is_gray() && (img.data[0] - 0.8).abs() < 1e-4, "bound image, as gray"); // The caller's image wins over the bound one. let mut opts = Options::new(&res); opts.inputs.insert("curvature".into(), Image::filled(4, 4, Kind::Gray, [0.1; 4])); - let c = cook(&p, 0, &opts, &mut cache); + let c = cook(&p, 0, &opts, &cache); assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4); } + + #[test] + fn input_change_recooks_only_readers() { + use materialcraft_core::function::{FnGraph, FnNode}; + let (mut p, noise, blur, out) = sample(); + let reader = p.graphs[0].add_node("pixel_processor", [0.0, 100.0]); + let get_a = FnNode { id: 1, op: "get_var".into(), inputs: vec![], value: Some(Value::Text("a".into())), pos: [0.0; 2] }; + p.graphs[0].node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(FnGraph { nodes: vec![get_a], output: Some(1) }))); + let cache = &Mutex::new(Cache::default()); + let mut opts = Options::new(&no_res); + opts.overrides.insert("a".into(), Value::Float(0.25)); + let first = cook(&p, 0, &opts, cache); + assert!(first.nodes.values().all(|r| r.error.is_none() && !r.cached)); + opts.overrides.insert("a".into(), Value::Float(0.75)); + let second = cook(&p, 0, &opts, cache); + for id in [noise, blur, out] { + assert!(second.nodes[&id].cached, "node {} does not read `a`", id.0); + } + assert!(!second.nodes[&reader].cached, "the reader must re-cook"); + } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index c7f3747d..605fcf70 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -12,10 +12,11 @@ pub mod material; pub mod mesh; pub mod sbs; +use std::collections::HashMap; use std::io::{Cursor, Read, Write}; use std::sync::Arc; -use materialcraft_core::{OutputFormat, Package}; +use materialcraft_core::{OutputFormat, Package, ResourceBytes}; use materialcraft_image::{Image, Kind, MAX_SIDE, linear_to_srgb, srgb_to_linear}; #[derive(Debug, thiserror::Error)] @@ -33,6 +34,10 @@ pub type Result = std::result::Result; /// Largest `package.json` and resource accepted when reading (allocation caps). const MAX_JSON: u64 = 64 << 20; const MAX_RESOURCE: u64 = 256 << 20; +/// Most resource records a package may list. +const MAX_RESOURCES: usize = 4096; +/// Most decompressed bytes a package may hold across `package.json` and all its resources. +const MAX_PACKAGE_BYTES: u64 = 2 << 30; /// Export file types: (extension, label). pub const EXPORT_FORMATS: &[(&str, &str)] = @@ -55,7 +60,7 @@ pub fn save_package(pkg: &Package) -> Result> { // Images are already compressed. let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); z.start_file(format!("resources/{}", safe_file_name(&r.file)), stored).map_err(io)?; - z.write_all(&r.bytes).map_err(|e| FormatError::Io(e.to_string()))?; + z.write_all(r.bytes.as_slice()).map_err(|e| FormatError::Io(e.to_string()))?; } z.finish().map_err(io)?; } @@ -64,6 +69,11 @@ pub fn save_package(pkg: &Package) -> Result> { /// Read a package from `.mcraft` bytes. pub fn load_package(bytes: &[u8]) -> Result { + load_package_within(bytes, MAX_PACKAGE_BYTES) +} + +/// [`load_package`] with an explicit cap on the total decompressed bytes. +fn load_package_within(bytes: &[u8], max_total: u64) -> Result { let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::BadPackage(e.to_string()))?; let mut json = Vec::new(); z.by_name("package.json") @@ -72,17 +82,37 @@ pub fn load_package(bytes: &[u8]) -> Result { .read_to_end(&mut json) .map_err(|e| FormatError::Io(e.to_string()))?; let mut pkg: Package = serde_json::from_slice(&json).map_err(|e| FormatError::BadPackage(e.to_string()))?; + if pkg.resources.len() > MAX_RESOURCES { + return Err(FormatError::BadPackage(format!("{} resources (limit {MAX_RESOURCES})", pkg.resources.len()))); + } + let mut total = json.len() as u64; + let mut read: HashMap = HashMap::new(); for r in &mut pkg.resources { let name = format!("resources/{}", safe_file_name(&r.file)); + if let Some(shared) = read.get(&name) { + r.bytes = shared.clone(); + continue; + } let mut data = Vec::new(); if let Ok(mut f) = z.by_name(&name) { f.by_ref().take(MAX_RESOURCE).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?; } - r.bytes = Arc::new(data); + total = total.saturating_add(data.len() as u64); + if total > max_total { + return Err(FormatError::BadPackage(format!("package resources exceed {max_total} bytes"))); + } + let data = ResourceBytes::new(data); + read.insert(name, data.clone()); + r.bytes = data; } Ok(pkg) } +/// Last-resort guard around third-party parsers: a panic inside them becomes an error. +pub(crate) fn guard(f: impl FnOnce() -> Result, err: impl FnOnce() -> FormatError) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(err())) +} + /// A file name with no path parts (resources live flat in `resources/`). pub fn safe_file_name(name: &str) -> String { let base = name.rsplit(['/', '\\']).next().unwrap_or(name); @@ -94,10 +124,25 @@ pub fn safe_file_name(name: &str) -> String { /// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale /// files stay grayscale). pub fn decode(bytes: &[u8]) -> Result { - // TGA has no signature: try it when the format cannot be guessed. - let img = image::load_from_memory(bytes) - .or_else(|e| image::load_from_memory_with_format(bytes, image::ImageFormat::Tga).map_err(|_| e)) - .map_err(|e| FormatError::Image(e.to_string()))?; + let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Image(e.to_string()))?; + if reader.format().is_none() { + // TGA has no signature: try it when the format cannot be guessed. + reader.set_format(image::ImageFormat::Tga); + } + let mut limits = image::Limits::default(); + limits.max_image_width = Some(MAX_SIDE); + limits.max_image_height = Some(MAX_SIDE); + limits.max_alloc = Some(1 << 30); + reader.limits(limits); + let img = guard( + || { + reader.decode().map_err(|e| match e { + image::ImageError::Limits(_) => FormatError::Image(format!("image is larger than {MAX_SIDE} pixels")), + e => FormatError::Image(e.to_string()), + }) + }, + || FormatError::Image("the decoder failed on this file".into()), + )?; let (w, h) = (img.width(), img.height()); if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels"))); @@ -109,14 +154,14 @@ pub fn decode(bytes: &[u8]) -> Result { let data: Vec = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); return Ok(Image { w, h, kind: Kind::Gray, data: Arc::new(data) }); } - let rgba = img.into_rgba32f(); - let data: Vec = rgba - .pixels() - .flat_map(|p| { - let [r, g, b, a] = p.0; - if float { [r, g, b, a] } else { [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), a] } - }) - .collect(); + let mut data = img.into_rgba32f().into_raw(); + if !float { + for px in data.chunks_exact_mut(4) { + for c in px.iter_mut().take(3) { + *c = srgb_to_linear(*c); + } + } + } Ok(Image { w, h, kind: Kind::Color, data: Arc::new(data) }) } @@ -240,12 +285,12 @@ mod tests { g.connect(a, "output", o, "input").unwrap(); p.graphs.push(g); let png = encode(&Image::filled(4, 4, Kind::Color, [1.0, 0.5, 0.0, 1.0]), "png", Depth::U8, true).unwrap(); - p.resources.push(Resource { name: "tex".into(), file: "../../evil/tex.png".into(), bytes: Arc::new(png) }); + p.resources.push(Resource::new("tex", "../../evil/tex.png", ResourceBytes::new(png))); let bytes = save_package(&p).unwrap(); let q = load_package(&bytes).unwrap(); assert_eq!(q.graphs, p.graphs); assert_eq!(q.resources[0].bytes, p.resources[0].bytes); - let img = decode(&q.resources[0].bytes).unwrap(); + let img = decode(q.resources[0].bytes.as_slice()).unwrap(); assert!((img.get(0, 0, false)[1] - 0.5).abs() < 0.01); assert!(load_package(b"not a zip").is_err()); } @@ -273,4 +318,76 @@ mod tests { assert_eq!(safe_file_name("../../etc/passwd"), "passwd"); assert_eq!(safe_file_name(".."), "resource"); } + + fn zip_with(json: &serde_json::Value, entries: &[(&str, usize)]) -> Vec { + let mut buf = Cursor::new(Vec::new()); + { + let mut z = zip::ZipWriter::new(&mut buf); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + z.start_file("package.json", opts).unwrap(); + z.write_all(json.to_string().as_bytes()).unwrap(); + for (name, len) in entries { + z.start_file(format!("resources/{name}"), opts).unwrap(); + z.write_all(&vec![0u8; *len]).unwrap(); + } + z.finish().unwrap(); + } + buf.into_inner() + } + + fn package_json(files: &[&str]) -> serde_json::Value { + let base = serde_json::to_value(Package::new("T")).unwrap(); + let mut v = base; + v["resources"] = files.iter().map(|f| serde_json::json!({ "name": "r", "file": f })).collect(); + v + } + + #[test] + fn many_records_share_one_entry() { + let files = vec!["big.bin"; 1000]; + let bytes = zip_with(&package_json(&files), &[("big.bin", 1 << 20)]); + let pkg = load_package(&bytes).unwrap(); + assert_eq!(pkg.resources.len(), 1000); + assert_eq!(pkg.resources[0].bytes.len(), 1 << 20); + assert!(pkg.resources[0].bytes.ptr_eq(&pkg.resources[999].bytes)); + } + + #[test] + fn too_many_resources_is_an_error() { + let files = vec!["a.bin"; MAX_RESOURCES + 1]; + let bytes = zip_with(&package_json(&files), &[("a.bin", 4)]); + assert!(load_package(&bytes).is_err()); + } + + #[test] + fn total_budget_is_enforced() { + let bytes = zip_with(&package_json(&["a.bin", "b.bin"]), &[("a.bin", 1 << 20), ("b.bin", 1 << 20)]); + assert!(load_package_within(&bytes, 3 << 19).is_err()); + assert!(load_package_within(&bytes, 3 << 20).is_ok()); + } + + #[test] + fn oversized_images_are_refused_before_decoding() { + let mut png = Cursor::new(Vec::new()); + image::GrayImage::new(8193, 1).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let err = decode(png.get_ref()).unwrap_err().to_string(); + assert!(err.contains("8192"), "{err}"); + } + + #[test] + fn tga_still_decodes() { + let mut tga = Cursor::new(Vec::new()); + image::RgbaImage::new(2, 2).write_to(&mut tga, image::ImageFormat::Tga).unwrap(); + let img = decode(tga.get_ref()).unwrap(); + assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color)); + } + + #[test] + fn decode_matches_previous_values() { + let mut png = Cursor::new(Vec::new()); + image::RgbImage::from_pixel(2, 2, image::Rgb([128, 128, 128])).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let img = decode(png.get_ref()).unwrap(); + let want = srgb_to_linear(128.0 / 255.0); + assert!((img.get(1, 1, false)[0] - want).abs() < 1e-4); + } } diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 2597dd0d..cfaca36c 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -47,7 +47,10 @@ pub fn load_mesh(name: &str, bytes: &[u8]) -> Result { fn obj(bytes: &[u8]) -> Result { let mut reader = std::io::BufReader::new(bytes); let opts = tobj::LoadOptions { triangulate: true, single_index: true, ..Default::default() }; - let (models, _) = tobj::load_obj_buf(&mut reader, &opts, |_| Ok((Vec::new(), Default::default()))).map_err(|e| bad(format!("OBJ: {e}")))?; + let (models, _) = crate::guard( + || tobj::load_obj_buf(&mut reader, &opts, |_| Ok((Vec::new(), Default::default()))).map_err(|e| bad(format!("OBJ: {e}"))), + || bad("the OBJ parser failed on this file"), + )?; let mut positions = Vec::new(); let mut normals = Vec::new(); let mut uvs = Vec::new(); @@ -75,7 +78,7 @@ fn obj(bytes: &[u8]) -> Result { } fn gltf(bytes: &[u8]) -> Result { - let (doc, buffers, _) = gltf::import_slice(bytes).map_err(|e| bad(format!("glTF: {e}")))?; + let (doc, buffers, _) = crate::guard(|| gltf::import_slice(bytes).map_err(|e| bad(format!("glTF: {e}"))), || bad("the glTF parser failed on this file"))?; let mut positions = Vec::new(); let mut normals = Vec::new(); let mut uvs = Vec::new(); diff --git a/crates/formats/src/sbs.rs b/crates/formats/src/sbs.rs index 5beb8207..0b559d74 100644 --- a/crates/formats/src/sbs.rs +++ b/crates/formats/src/sbs.rs @@ -5,12 +5,11 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; use std::fmt::Write as _; use std::io::{Read, Write}; -use std::sync::Arc; use base64::Engine as _; use materialcraft_core::{ BaseParams, Comment, Connection, ExposedParam, Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat, Package, Resource, - SizeMode, Value, linear_to_srgb, missing_ports, srgb_to_linear, + ResourceBytes, SizeMode, Value, linear_to_srgb, missing_ports, srgb_to_linear, }; use materialcraft_nodes::{PortKind, find}; use roxmltree::Node as XmlNode; @@ -776,7 +775,7 @@ impl<'text> Reader<'text, '_> { match bytes { Some(data) => { let ext = if kind == "svg" { "svg".to_string() } else { format }; - pkg.resources.push(Resource { name: name.clone(), file: crate::safe_file_name(&format!("{name}.{ext}")), bytes: Arc::new(data) }); + pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data))); } None => { let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing }; @@ -1074,8 +1073,13 @@ impl<'text> Reader<'text, '_> { if let Some(node) = node { for param in instance_params() { let param_name = child_value(param, "name").unwrap_or(""); - match def.param(param_name) { - Some(param_def) => self.set_param(node, param_name, ¶m_def.default, param_def.options.len(), param, &graph_name), + let id = match (def.id, param_name) { + ("histogram_scan", "Position") => "position", + ("histogram_scan", "Contrast") => "contrast", + _ => param_name, + }; + match def.param(id) { + Some(param_def) => self.set_param(node, id, ¶m_def.default, param_def.options.len(), param, &graph_name), None => self.warnings.add(format!("`{}`: parameter `{param_name}` has no MaterialCraft equivalent and was ignored", def.id)), } } @@ -1086,7 +1090,15 @@ impl<'text> Reader<'text, '_> { let port_for = |identifier: &str| if def.output_index(identifier).is_some() { identifier.to_string() } else { first_output.clone() }; let unbridged = output_uids.iter().filter(|(uid, _)| !bridgings.iter().any(|(b, _)| b == uid)).map(|(uid, _)| (uid.clone(), first_output.clone())); let outputs = bridgings.iter().map(|(uid, identifier)| (uid.clone(), port_for(identifier))).chain(unbridged).collect(); - let inputs = def.inputs.iter().map(|p| (p.id.to_string(), p.id.to_string())).collect(); + let mut inputs: HashMap<_, _> = def.inputs.iter().map(|p| (p.id.to_string(), p.id.to_string())).collect(); + let input_aliases: &[(&str, &str)] = match def.id { + "histogram_scan" => &[("Input_1", "input")], + "auto_levels" => &[("Input", "input")], + "flood_fill" => &[("mask", "input")], + "height_blend" => &[("height_top", "top"), ("height_bottom", "bottom")], + _ => &[], + }; + inputs.extend(input_aliases.iter().map(|&(alias, port)| (alias.to_string(), port.to_string()))); ReadNode { id, index, inputs, outputs, open_inputs: false } } @@ -1369,7 +1381,7 @@ pub fn write_sbs(pkg: &Package) -> Result> { if svg { "svg" } else { "bitmap" }, xml_escape(ext), resource.bytes.len(), - encode_embedded(&resource.bytes)? + encode_embedded(resource.bytes.as_slice())? ); } content.push_str(""); @@ -1853,7 +1865,7 @@ mod tests { let orange = materialcraft_image::Image::filled(4, 4, materialcraft_image::Kind::Color, [1.0, 0.5, 0.0, 1.0]); let png = crate::encode(&orange, "png", crate::Depth::U8, true).unwrap(); - pkg.resources.push(Resource { name: "tex".into(), file: "tex.png".into(), bytes: Arc::new(png) }); + pkg.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(png))); pkg } @@ -2076,7 +2088,7 @@ mod tests { assert!(read.warnings.iter().any(|w| w.contains("missing node `3D_perlin_noise`")), "{:?}", &read.warnings[..5]); assert!(read.pkg.resources.iter().any(|r| r.name == "Untitled_Bitmap" && !r.bytes.is_empty())); let svg = read.pkg.resources.iter().find(|r| r.name == "Untitled_Vector_Graphics").unwrap(); - assert!(String::from_utf8_lossy(&svg.bytes).contains(" String { + let text = String::from_utf8(bytes.to_vec()).unwrap(); + // Exercise XML import rather than the writer's embedded exact native-package copy. + format!("{}", text.split("