From 257ab55a686e43e49bb1aa20f8d96e29f3475946 Mon Sep 17 00:00:00 2001 From: AndreIsraelAO Date: Mon, 2 Nov 2026 22:59:57 -0300 Subject: [PATCH 01/33] Add Export outputs to the explorer graph context menu Fixes #22 --- crates/ui-egui/src/explorer.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index d0f4940e..8c50b844 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -55,7 +55,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { open = Some(i); } resp.context_menu(|ui| { - for (label, a) in [("Open", "open"), ("Duplicate", "duplicate"), ("Delete", "delete")] { + for (label, a) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] { if ui.button(tr(label)).clicked() { action = Some((a, i)); ui.close(); @@ -70,6 +70,11 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { Some(("open", i)) => { app.run("graph.open", json!({"graph": i})); } + Some(("export", i)) => { + // The export window works on the open graph. + app.run("graph.open", json!({"graph": i})); + app.ui.windows.export = true; + } Some(("duplicate", i)) => { app.run("graph.duplicate", json!({"graph": i})); } From 3a104b4e724d82b1b57ca6ed17b80d87322057c8 Mon Sep 17 00:00:00 2001 From: AndreIsraelAO Date: Tue, 3 Nov 2026 00:26:12 -0300 Subject: [PATCH 02/33] Add a resolution option to Export outputs Adds size to file.export and a Resolution selector to the export window. Only open the export window when the graph opened. Refs #22 --- crates/automation/src/headless.rs | 4 ++-- crates/engine/src/file_cmds.rs | 28 +++++++++++++++++++--------- crates/engine/tests/session.rs | 5 +++++ crates/ui-egui/src/explorer.rs | 5 +++-- crates/ui-egui/src/state.rs | 3 +++ crates/ui-egui/src/web_files.rs | 2 +- crates/ui-egui/src/windows.rs | 14 ++++++++++++-- 7 files changed, 45 insertions(+), 16 deletions(-) diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 3443f3f9..dc510b82 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -170,8 +170,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 { diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 392e3b49..e1af7462 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -31,7 +31,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, power of two, 16..8192; default the graph's), graph?} cooks the graph at full size and writes every output", has_graph, export ), @@ -150,9 +150,18 @@ 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 log2 = 31 - px.clamp(16, 8192).leading_zeros(); + pkg.graph_mut(gi)?.size = [log2, log2]; + } + let g = pkg.graph(gi)?; + let dec = s.resource_decoder(); + let cooked = { + let mut cache = s.cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &mut cache) + }; let mut out = Vec::new(); for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) { let Some(img) = img else { continue }; @@ -168,8 +177,8 @@ 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 fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option, Option)> { 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(); @@ -184,14 +193,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").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 { diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 5c108526..75f21c5f 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -83,6 +83,11 @@ 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); } diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 8c50b844..547cbb7e 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -72,8 +72,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } Some(("export", i)) => { // The export window works on the open graph. - app.run("graph.open", json!({"graph": i})); - app.ui.windows.export = true; + if app.run("graph.open", json!({"graph": i})).is_some() { + app.ui.windows.export = true; + } } Some(("duplicate", i)) => { app.run("graph.duplicate", json!({"graph": i})); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2b6d2a32..c328373a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -105,6 +105,8 @@ pub struct UiState { pub export_dir: String, pub export_format: String, pub export_depth: u32, + /// Export size in pixels; 0 = the graph's own size. + pub export_size: u32, pub export_pattern: String, /// Frame the whole graph on the next frame. #[serde(skip)] @@ -128,6 +130,7 @@ impl Default for UiState { export_dir: String::new(), export_format: "png".into(), export_depth: 0, + export_size: 0, export_pattern: "$(graph)_$(identifier)".into(), frame_all: true, } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index adaa1b9d..b5169055 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -198,7 +198,7 @@ mod web { /// Export outputs: one file downloads as is, several as `_outputs.zip`. pub fn export(app: &mut MaterialCraftApp, params: &serde_json::Value) { let result = materialcraft_engine::file_cmds::export_params(&app.session, params) - .and_then(|(gi, ext, pattern, depth)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth)) + .and_then(|(gi, ext, pattern, depth, size)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth, size)) .map_err(|e| e.to_string()) .and_then(|files| { let files: Vec<(String, Vec)> = files.into_iter().map(|f| (f.file, f.bytes)).collect(); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 931d19ca..1e42c8a8 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -197,7 +197,7 @@ fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) { fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { let mut open = true; let mut go = false; - modal(ctx, "export", tr("Export outputs"), &mut open, vec2(460.0, 260.0), |ui| { + modal(ctx, "export", tr("Export outputs"), &mut open, vec2(460.0, 290.0), |ui| { let tk = Tokens::get(ui.ctx()); let g = app.session.graph().map(|g| g.name.clone()).unwrap_or_default(); ui.label(RichText::new(format!("{}: {g}", tr("Graph"))).strong()); @@ -229,6 +229,16 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { ui.selectable_value(&mut app.ui.export_depth, d, tr(l)); } }); + let size_label = match app.ui.export_size { + 0 => tr("Graph's size").to_string(), + px => format!("{px} x {px}"), + }; + crate::widgets::combo(ui, tr("Resolution"), size_label, |ui| { + ui.selectable_value(&mut app.ui.export_size, 0, tr("Graph's size")); + for px in [256u32, 512, 1024, 2048, 4096, 8192] { + ui.selectable_value(&mut app.ui.export_size, px, format!("{px} x {px}")); + } + }); ui.horizontal(|ui| { ui.label(tr("File names")); let r = ui.add(egui::TextEdit::singleline(&mut app.ui.export_pattern).desired_width(260.0)); @@ -250,7 +260,7 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { app.toast(tr("Choose a folder to export to"), true); } else { let depth = if app.ui.export_depth == 0 { Value::Null } else { json!(app.ui.export_depth) }; - let p = json!({"dir": app.ui.export_dir, "format": app.ui.export_format, "pattern": app.ui.export_pattern, "depth": depth}); + let p = json!({"dir": app.ui.export_dir, "format": app.ui.export_format, "pattern": app.ui.export_pattern, "depth": depth, "size": if app.ui.export_size == 0 { Value::Null } else { json!(app.ui.export_size) }}); #[cfg(target_arch = "wasm32")] { crate::web_files::export(app, &p); From e816ad75bbd81a23e2b9958297fc0feeb838184c Mon Sep 17 00:00:00 2001 From: AndreIsraelAO Date: Tue, 3 Nov 2026 07:29:07 -0300 Subject: [PATCH 03/33] Keep export proportions and expose size in the CLI and MCP size is now the larger side in pixels and the other side keeps its proportion; 0 means the graph's size. Adds --size to the CLI export, size to the MCP outputs_export, and the docs line. The resolution combo shows the graph's real size. Refs #22 --- apps/materialcraft-cli/src/main.rs | 6 +++--- crates/automation/src/server.rs | 3 +++ crates/engine/src/file_cmds.rs | 15 ++++++++++----- crates/engine/src/session.rs | 2 +- crates/engine/tests/session.rs | 19 +++++++++++++++++++ crates/ui-egui/src/windows.rs | 9 +++++---- docs/control-protocol.md | 2 +- 7 files changed, 42 insertions(+), 14 deletions(-) diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index fef8f39e..5afe3fb2 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -30,7 +30,7 @@ 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] @@ -57,7 +57,7 @@ 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"], &[]), @@ -227,7 +227,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" => { diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index e23f3d18..5ecf5f3e 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -154,6 +154,9 @@ 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, diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index e1af7462..7d4bb5db 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -31,7 +31,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), size? (px, power of two, 16..8192; default the graph's), 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 ), @@ -153,8 +153,11 @@ pub struct Exported { 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 log2 = 31 - px.clamp(16, 8192).leading_zeros(); - pkg.graph_mut(gi)?.size = [log2, log2]; + 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 larger = g.size[0].max(g.size[1]); + g.size = g.size.map(|l| (l + target).saturating_sub(larger).max(4)); } let g = pkg.graph(gi)?; let dec = s.resource_decoder(); @@ -178,7 +181,9 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O } /// Export params: (graph index, extension, pattern, depth, size). -pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option, Option)> { +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(); @@ -193,7 +198,7 @@ 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}"))), }; - let size = u64p(p, "size").map(|px| px.min(u64::from(u32::MAX)) as u32); + 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)) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 040284df..2b0cc41b 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -313,7 +313,7 @@ impl Session { &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); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 75f21c5f..62849488 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -91,6 +91,25 @@ fn package_save_and_open_round_trip() { 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)); +} + /// Every command, run with empty and hostile params, returns Ok or Err but never panics. #[test] fn panic_hunt() { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 1e42c8a8..f82a03a8 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -229,14 +229,15 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { ui.selectable_value(&mut app.ui.export_depth, d, tr(l)); } }); + let graph_size = app.session.graph().map_or(String::new(), |g| format!("{} ({} x {})", tr("Graph's size"), 1u32 << g.size[0], 1u32 << g.size[1])); let size_label = match app.ui.export_size { - 0 => tr("Graph's size").to_string(), - px => format!("{px} x {px}"), + 0 => graph_size.clone(), + px => format!("{px} px"), }; crate::widgets::combo(ui, tr("Resolution"), size_label, |ui| { - ui.selectable_value(&mut app.ui.export_size, 0, tr("Graph's size")); + ui.selectable_value(&mut app.ui.export_size, 0, graph_size); for px in [256u32, 512, 1024, 2048, 4096, 8192] { - ui.selectable_value(&mut app.ui.export_size, px, format!("{px} x {px}")); + ui.selectable_value(&mut app.ui.export_size, px, format!("{px} px")); } }); ui.horizontal(|ui| { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8c0fba6c..7c1645e9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -25,7 +25,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: | `session.inspect` | all | package, graphs, the open graph's nodes (def, params, bindings, base, ports, cook error/size/mean/ms), wires, frames, comments, pins, exposed inputs, views, history | | `package.open {path}` / `package.save {path?}` | headless | workspace-scoped package I/O | | `bitmap.import {path, name?}` | headless | embed an image as a resource | -| `outputs.export {dir, format?, pattern?, depth?, graph?}` | headless | cook at full size and write every output | +| `outputs.export {dir, format?, pattern?, depth?, size?, graph?}` | headless | cook at full size and write every output | | `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii | | `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's screen position, fps, toasts | | `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click | From af83c228c32858156b6f7fffc27dbe052d1e764f Mon Sep 17 00:00:00 2001 From: Belligerently Date: Tue, 3 Nov 2026 09:59:48 -0500 Subject: [PATCH 04/33] Allow centered dialogs to move by their title bars --- crates/ui-egui/src/windows.rs | 3 +- crates/ui-egui/tests/dialogs.rs | 76 +++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/dialogs.rs diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f308f048..9d8395ef 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -105,7 +105,8 @@ fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui .collapsible(false) .resizable(false) .default_size(size) - .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) .show(ctx, body); } diff --git a/crates/ui-egui/tests/dialogs.rs b/crates/ui-egui/tests/dialogs.rs new file mode 100644 index 00000000..2957e820 --- /dev/null +++ b/crates/ui-egui/tests/dialogs.rs @@ -0,0 +1,76 @@ +//! Home and export dialogs start centered, but their title bars must allow movement. + +use egui::{Event, Modifiers, PointerButton, Rect, pos2, vec2}; +use egui_kittest::Harness; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; + +type State = (MaterialCraftApp, Rect); + +fn harness(id: &'static str, render: bool) -> Harness<'static, State> { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.ui.windows.home = id == "home"; + app.ui.windows.export = id == "export"; + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + move |ui, (app, rect): &mut State| { + app.step(&ui.ctx().clone()); + app.draw(ui); + *rect = ui.ctx().memory(|m| m.area_rect(egui::Id::unique(id))).unwrap_or(Rect::NOTHING); + }, + (app, Rect::NOTHING), + ); + h.run_steps(10); + h +} + +fn drag_title(h: &mut Harness<'static, State>) { + let from = h.state().1.min + vec2(120.0, 12.0); + h.event(Event::PointerMoved(from)); + h.step(); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + for step in 1..=8 { + h.event(Event::PointerMoved(from + vec2(10.0, 7.5) * step as f32)); + h.step(); + } + h.event(Event::PointerButton { pos: from + vec2(80.0, 60.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(10); +} + +#[test] +fn home_and_export_can_be_dragged_and_keep_their_position() { + for id in ["home", "export"] { + let mut h = harness(id, false); + let before = h.state().1; + assert!(before.is_finite()); + assert!(before.center().distance(pos2(800.0, 480.0)) < 3.0, "{id}: initial rectangle {before:?}"); + drag_title(&mut h); + let moved = h.state().1; + assert!(moved.min.distance(before.min + vec2(80.0, 60.0)) < 8.0, "{id}: did not follow the drag: {before:?} -> {moved:?}"); + // Later frames and reopening the same dialog must not snap it back to the center. + h.state_mut().0.ui.windows.home = false; + h.state_mut().0.ui.windows.export = false; + h.run_steps(3); + h.state_mut().0.ui.windows.home = id == "home"; + h.state_mut().0.ui.windows.export = id == "export"; + h.run_steps(10); + assert!(h.state().1.min.distance(moved.min) < 1.0, "{id}: reopening lost the dragged position"); + h.set_size(vec2(1500.0, 900.0)); + h.run_steps(10); + assert!(h.state().1.min.distance(moved.min) < 1.0, "{id}: resizing recentered the dialog"); + } +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn dialog_drag_snapshots() { + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + for id in ["home", "export"] { + let mut h = harness(id, true); + h.render().unwrap().save(dir.join(format!("{id}-centered.png"))).unwrap(); + drag_title(&mut h); + h.render().unwrap().save(dir.join(format!("{id}-moved.png"))).unwrap(); + } +} From 7feafbf533f707cb29a18e301d3b11566547f57e Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:55:02 +0100 Subject: [PATCH 05/33] 2D view: show the node you click A single click only changed the selection, and the 2D view prefers a node shown with a double-click, an output port or "View in 2D view" over the selection, so after any of those, clicks never changed the view until the graph was switched. A click that leaves a node selected now shows it; a deselecting Ctrl+click or a drag does not, and the node already shown keeps its chosen output port. Fixes #10 --- crates/ui-egui/src/graph_view.rs | 175 ++++++++++++++++++++++++++----- crates/ui-egui/src/view2d.rs | 8 +- 2 files changed, 148 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index b56f295e..70c0076d 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -4,9 +4,10 @@ //! Gestures: left-drag a node to move it (the selection moves together), drag from a port to wire //! it (dropping on empty canvas opens the node search, wired), drag an input to unplug and re-route //! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to -//! zoom, double-click a node to show it in the 2D view (a graph instance opens its graph), Space, Tab or -//! double-click the canvas for the node search, right-click for menus, drop library items to add -//! them. Every edit is an engine command; the gestures only draw previews until they commit. +//! zoom, click a node to show it in the 2D view (double-click a graph instance to open its graph), +//! Space, Tab or double-click the canvas for the node search, right-click for menus, drop library +//! items to add them. Every edit is an engine command; the gestures only draw previews until they +//! commit. use egui::{Align2, Color32, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; use egui_phosphor::regular as icon; @@ -822,6 +823,10 @@ fn handle_input( app.run("view.2d", json!({"node": id.0, "port": 0})); } } + } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { + // A click that leaves the node selected shows it, replacing a node shown earlier (a + // Ctrl+click that deselects it does not; the shown node keeps its chosen port). + app.run("view.2d", json!({"node": id.0})); } r.context_menu(|ui| node_menu(app, ui, *id)); } @@ -1087,33 +1092,147 @@ fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { mod tests { use super::*; + /// The whole app in an offscreen egui context, driven one frame at a time. + struct Frames { + ctx: egui::Context, + app: MaterialCraftApp, + time: f64, + } + + impl Frames { + /// `session` after a few frames, so the canvas is laid out. + fn new(session: materialcraft_engine::Session) -> Frames { + let mut f = Frames { ctx: egui::Context::default(), app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0 }; + for _ in 0..3 { + f.run(Vec::new(), egui::Modifiers::NONE); + } + f + } + + /// One frame with `events` while `modifiers` are held, in a desktop-sized window (egui's + /// default screen is so large that the 3D view's frame would exceed the texture limit). + fn run(&mut self, events: Vec, modifiers: egui::Modifiers) { + self.time += 0.05; + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0))); + let input = egui::RawInput { events, screen_rect, time: Some(self.time), ..Default::default() }; + let app = &mut self.app; + self.ctx + .run_ui(input, |ui| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }) + .textures_delta + .clear(); + } + + /// Press and release the primary button at `pos`, a second after any earlier click so + /// the two never pair into a double-click. + fn click(&mut self, pos: Pos2, modifiers: egui::Modifiers) { + self.time += 1.0; + self.run(vec![egui::Event::PointerMoved(pos)], modifiers); + for pressed in [true, false] { + self.run(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }], modifiers); + } + } + + /// The center of node `id` on screen last frame. + fn center(&self, id: NodeId) -> Pos2 { + self.app.graph.rects.iter().find(|(n, _)| *n == id).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("node {id:?} is not on screen")) + } + + /// The node the 2D view shows once the graph has cooked. + fn shown(&mut self) -> Option { + self.app.session.cook(); + self.app.session.view2d_image().map(|(id, _)| id) + } + } + + /// A graph with a Perlin noise, a checker and an RGBA split side by side, framed on screen. + fn three_nodes() -> (Frames, [NodeId; 3]) { + let mut s = materialcraft_engine::sample_session(); + materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap(); + let ids = ["perlin_noise", "checker", "rgba_split"].iter().enumerate().map(|(i, def)| { + let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap(); + NodeId(added["id"].as_u64().unwrap()) + }); + let ids: [NodeId; 3] = ids.collect::>().try_into().unwrap(); + s.selection.clear(); + (Frames::new(s), ids) + } + + #[test] + fn clicking_a_node_shows_it_in_the_2d_view() { + let (mut f, [noise, checker, _]) = three_nodes(); + // Shown explicitly first (a double-click, an output port or "View in 2D view"). + f.app.run("view.2d", json!({"node": noise.0})); + assert_eq!(f.shown(), Some(noise)); + let at = f.center(checker); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.app.session.view2d.node, Some(checker)); + assert_eq!(f.shown(), Some(checker)); + // And back. + let at = f.center(noise); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.view2d.node, Some(noise)); + assert_eq!(f.shown(), Some(noise)); + // Ctrl+click adds a node to the selection and shows it too. + let at = f.center(checker); + f.click(at, egui::Modifiers::CTRL); + assert_eq!(f.app.session.selection, vec![noise, checker]); + assert_eq!(f.shown(), Some(checker)); + } + + #[test] + fn ctrl_click_that_deselects_a_node_does_not_show_it() { + let (mut f, [noise, checker, _]) = three_nodes(); + f.app.session.selection = vec![noise, checker]; + f.app.run("view.2d", json!({"node": checker.0})); + let at = f.center(noise); + f.click(at, egui::Modifiers::CTRL); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.shown(), Some(checker)); + } + + #[test] + fn dragging_a_node_keeps_the_2d_view() { + let (mut f, [noise, checker, _]) = three_nodes(); + f.app.run("view.2d", json!({"node": noise.0})); + let before = f.app.session.graph().unwrap().node(checker).unwrap().pos; + let from = f.center(checker); + let none = egui::Modifiers::NONE; + f.run(vec![egui::Event::PointerMoved(from)], none); + f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none); + for step in 1..=8 { + f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none); + } + let to = from + vec2(40.0, 0.0); + f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none); + let after = f.app.session.graph().unwrap().node(checker).unwrap().pos; + let moved = 40.0 / f.app.ui.graph_camera.zoom; + assert!((after[0] - before[0] - moved).abs() < 1e-3 && after[1] == before[1], "the checker moved {before:?} -> {after:?}, not {moved} right"); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.shown(), Some(noise)); + } + + #[test] + fn clicking_the_shown_node_keeps_its_port() { + let (mut f, [_, _, split]) = three_nodes(); + f.app.run("view.2d", json!({"node": split.0, "port": 2})); + let at = f.center(split); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.selection, vec![split]); + assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2)); + } + #[test] fn tab_opens_search_in_the_full_workspace() { - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - let ctx = egui::Context::default(); - for _ in 0..3 { - ctx.run_ui(egui::RawInput::default(), |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - } - let pointer = app.graph.view.center(); - let input = egui::RawInput { - events: vec![ - egui::Event::PointerMoved(pointer), - egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, - ], - ..Default::default() - }; - ctx.run_ui(input, |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - assert!(app.graph.search.is_some()); + let mut f = Frames::new(materialcraft_engine::sample_session()); + let pointer = f.app.graph.view.center(); + let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE); + assert!(f.app.graph.search.is_some()); } #[test] diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index 2bb3d5cc..cc52172c 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -88,13 +88,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let (r, resp) = ui.allocate_exact_size(ui.available_size(), Sense::hover()); crate::widgets::name(&resp, egui::Role::Image, "2D view"); ui.painter().rect_filled(r, 0.0, tk.viewport); - ui.painter().text( - r.center(), - egui::Align2::CENTER_CENTER, - tr("Double-click a node to show it here"), - egui::FontId::proportional(12.0), - tk.viewport_text, - ); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), tk.viewport_text); return; }; let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key) From 4b97a81f7d0455d70d0a793ed4e8318260c8f07a Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:08:13 -0600 Subject: [PATCH 06/33] Formats: bound package load memory, check image size before decoding, guard parsers --- crates/formats/src/lib.rs | 143 +++++++++++++++++++++++++++++++++---- crates/formats/src/mesh.rs | 7 +- 2 files changed, 135 insertions(+), 15 deletions(-) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 304fa0eb..9013dc3e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -11,6 +11,7 @@ pub mod material; pub mod mesh; +use std::collections::HashMap; use std::io::{Cursor, Read, Write}; use std::sync::Arc; @@ -32,6 +33,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)] = @@ -63,6 +68,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") @@ -71,17 +81,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 = Arc::clone(shared); + 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 = Arc::new(data); + read.insert(name, Arc::clone(&data)); + 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); @@ -93,10 +123,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"))); @@ -108,14 +153,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) }) } @@ -272,4 +317,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!(Arc::ptr_eq(&pkg.resources[0].bytes, &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(); From 2bd4fd35b8bca2b814fc8c5b276d873f3e4c95ca Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:17:16 -0600 Subject: [PATCH 07/33] Control channel: harden the token file and the app's control server The app wrote its control token to the temp folder with default permissions from a hash-based generator, compared it with ==, spawned unlimited threads and let an unauthenticated client hold a connection for 10 minutes. The shared token file was opened with create+truncate, which follows a planted symlink. - Token files are created new (remove, then O_EXCL) with mode 0600; clients only read a regular, owner-only, non-symlink file. - The app's control server uses the shared security module: OS-random token, constant-time compare, bounded lines, at most 16 connections, one auth attempt within 10 s, close on malformed JSON before auth. - serve --port and the app bind before writing the token file. Ported from TextureCraft 5a065c1 and 836e3f2. --- Cargo.lock | 2 + Cargo.toml | 1 + apps/materialcraft-cli/src/main.rs | 18 +- apps/materialcraft/Cargo.toml | 1 + apps/materialcraft/src/control_server.rs | 254 ++++++++++++++++------- crates/automation/Cargo.toml | 3 + crates/automation/src/rpc.rs | 18 +- crates/automation/src/security.rs | 182 +++++++++++++++- docs/control-protocol.md | 10 +- 9 files changed, 400 insertions(+), 89 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ce3b0fc1..c0a22386 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2313,6 +2313,7 @@ dependencies = [ "egui", "image", "log", + "materialcraft-automation", "materialcraft-engine", "materialcraft-ui-egui", "serde_json", @@ -2332,6 +2333,7 @@ dependencies = [ "materialcraft-render", "rayon", "rmcp", + "rustix 1.1.6", "schemars", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 663ec4d4..284c1729 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 fef8f39e..6d2b24ec 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -274,14 +274,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())?, } diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 64a1ca49..7b5a2caa 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -12,6 +12,7 @@ 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 } diff --git a/apps/materialcraft/src/control_server.rs b/apps/materialcraft/src/control_server.rs index a094e2dc..0f841c43 100644 --- a/apps/materialcraft/src/control_server.rs +++ b/apps/materialcraft/src/control_server.rs @@ -1,42 +1,26 @@ //! 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)) { @@ -46,35 +30,65 @@ pub fn start(port: u16, ctx: egui::Context) -> Receiver { 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(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 127.0.0.1:{port}"); + std::thread::spawn(move || accept(listener, &token, &tx, &ctx)); 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; - } - if !line.ends_with('\n') && n as u64 >= MAX_REQUEST { - let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": "request too large"})); - break; + let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.to_string()); + std::thread::spawn(move || { + let _permit = permit; + serve(stream, &token, &tx, &ctx); + }); + } +} + +/// 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 +96,133 @@ 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"; + + /// 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/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/rpc.rs b/crates/automation/src/rpc.rs index 0c156b78..0d4253dd 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -18,7 +18,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] = &[ @@ -160,6 +162,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 +181,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() { diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 165fda18..41bec540 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::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/docs/control-protocol.md b/docs/control-protocol.md index 8c0fba6c..0713ee05 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -11,7 +11,15 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: 3. **The app's control channel** (`materialcraft --control `): one JSON request per line, `{"id", "method", "params"}` → `{"id", "ok": true, "result"}` or `{"id", "ok": false, "error"}`. The first request must be `{"method":"auth","params":{"token":"…"}}` with the token from - `MATERIALCRAFT_CONTROL_TOKEN` or the file `/materialcraft-control-.token`. + `MATERIALCRAFT_CONTROL_TOKEN` (16 to 1024 printable ASCII characters) or the file + `/materialcraft-control-.token`, a fresh random 256-bit token written after the port + is bound. On Unix the file is created new with mode 0600 (owner only); if an existing file there + cannot be replaced, the control server stays off and `MATERIALCRAFT_CONTROL_TOKEN` is the + alternative. Clients (`materialcraft-cli mcp --bridge`) refuse a token file that is a symlink, + not a regular file, not owned by them, or accessible to group or others. A connection gets one + authentication attempt, within 10 s; a wrong token, any other first request or malformed JSON + closes it. At most 16 connections are served at once. Whoever holds the token has full + engine-command authority, including host file access. Set `MATERIALCRAFT_NO_PREFS=1` for scripted runs so the user's layout is left alone. ## Methods From c4d74432186b7853be682f612eb57434e84bb221 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:19:15 -0600 Subject: [PATCH 08/33] Eval: key resources on content and graph instances on their whole sub-graph tree Resources carry a content hash (ResourceBytes); the decoder memo is keyed on it and pruned. Graphs that use themselves, directly or through other instanced graphs, give an explicit error. --- crates/core/src/lib.rs | 2 +- crates/core/src/package.rs | 81 ++++++++++++++++- crates/engine/src/file_cmds.rs | 5 +- crates/engine/src/session.rs | 17 ++-- crates/engine/tests/session.rs | 16 ++++ crates/eval/src/lib.rs | 155 ++++++++++++++++++++++++++++++--- crates/formats/src/lib.rs | 18 ++-- 7 files changed, 265 insertions(+), 29 deletions(-) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 890eeabe..860e1b8b 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, Node, NodeId, OutputFormat, Pin, Preset, SizeMode, }; -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 392e3b49..a8c555e9 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -4,7 +4,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}; @@ -76,6 +76,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(); @@ -224,7 +225,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/session.rs b/crates/engine/src/session.rs index 040284df..8339877b 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}; @@ -146,7 +146,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 { @@ -285,20 +285,27 @@ 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(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 5c108526..161a3ea4 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -187,3 +187,19 @@ fn camera_prefs_bound_the_pan_and_survive_hostile_values() { assert_eq!(s.camera, CameraPrefs::default()); 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}"); +} diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index b5d18df7..9a125d41 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -178,11 +178,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() } } } @@ -261,7 +263,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 @@ -288,14 +290,53 @@ 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 { +/// A hash of graph `gi` and everything it reaches: its own JSON, the content of every +/// resource its nodes name, and (recursively) every graph it instances. A cycle hashes as a +/// marker; `cook_instance` reports it as an error. +fn graph_tree_hash(pkg: &Package, gi: usize, stack: &mut Vec) -> u64 { + let Some(graph) = pkg.graphs.get(gi) else { return 0 }; + if stack.len() > MAX_DEPTH as usize { + return 1; + } + let mut h = DefaultHasher::new(); + 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" { + continue; + } + match instance_graph(pkg, n) { + Some((si, _)) if stack.contains(&si) => "cycle".hash(&mut h), + Some((si, _)) => { + stack.push(si); + graph_tree_hash(pkg, si, stack).hash(&mut h); + stack.pop(); + } + None => 0u64.hash(&mut h), + } + } + h.finish() +} + +fn cook_node( + pkg: &Package, + gi: usize, + graph: &Graph, + node: &Node, + done: &Cooked, + vars: &BTreeMap, + opts: &Options, + cache: &mut Cache, +) -> NodeResult { let (in_ports, out_ports) = ports(pkg, node); let def = find(&node.def); // Gather inputs by port order, with their keys. @@ -350,11 +391,10 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT // 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, &mut vec![si])) } else { 0 }; let key = hash_of(&( &node.def, serde_json::to_string(¶ms).unwrap_or_default(), @@ -375,7 +415,7 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT let img = img.resize(w, h, tile); Ok(vec![if node.def == "input_grayscale" { img.to_gray() } else { img }]) } 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) @@ -393,8 +433,25 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT } } +/// Whether graph `from` instances graph `target`, directly or through other instanced graphs. +/// `seen` holds the graphs already visited. +fn instances_reach(pkg: &Package, from: usize, target: usize, seen: &mut Vec) -> bool { + let Some(graph) = pkg.graphs.get(from) else { return false }; + graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)).any(|(si, _)| { + if si == target { + return true; + } + if seen.contains(&si) { + return false; + } + seen.push(si); + instances_reach(pkg, si, target, seen) + }) +} + fn cook_instance( pkg: &Package, + gi: usize, node: &Node, in_ports: &[Port], out_ports: &[Port], @@ -407,14 +464,19 @@ fn cook_instance( 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, &mut vec![sub_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()); } @@ -534,7 +596,78 @@ mod tests { let c = cook(&p, 0, &Options::new(&no_res), &mut 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 mut cache = Cache::default(); + let opts = Options::new(&no_res); + let first = cook(&p, 0, &opts, &mut 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, &mut cache); + assert!(!second.nodes[&top].cached); + assert!((second.image(out_a, 0).unwrap().mean()[0] - 0.8).abs() < 0.01); + } + + #[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 mut cache = Cache::default(); + let c = cook(&p, 0, &Options::new(&no_res), &mut 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 mut cache = Cache::default(); + let opts = Options::new(&res); + let first = cook(&p, 0, &opts, &mut 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, &mut cache); + assert!(!second.nodes[&bm].cached); + assert!((second.image(bm, 0).unwrap().mean()[0] - mean).abs() > 0.05); } #[test] diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 9013dc3e..3503b266 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -15,7 +15,7 @@ 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)] @@ -59,7 +59,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)?; } @@ -85,11 +85,11 @@ fn load_package_within(bytes: &[u8], max_total: u64) -> Result { 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(); + 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 = Arc::clone(shared); + r.bytes = shared.clone(); continue; } let mut data = Vec::new(); @@ -100,8 +100,8 @@ fn load_package_within(bytes: &[u8], max_total: u64) -> Result { if total > max_total { return Err(FormatError::BadPackage(format!("package resources exceed {max_total} bytes"))); } - let data = Arc::new(data); - read.insert(name, Arc::clone(&data)); + let data = ResourceBytes::new(data); + read.insert(name, data.clone()); r.bytes = data; } Ok(pkg) @@ -284,12 +284,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()); } @@ -348,7 +348,7 @@ mod tests { let pkg = load_package(&bytes).unwrap(); assert_eq!(pkg.resources.len(), 1000); assert_eq!(pkg.resources[0].bytes.len(), 1 << 20); - assert!(Arc::ptr_eq(&pkg.resources[0].bytes, &pkg.resources[999].bytes)); + assert!(pkg.resources[0].bytes.ptr_eq(&pkg.resources[999].bytes)); } #[test] From eef9f5397fe6c15340baff88a843b1a9b2f29a6b Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:23:07 -0600 Subject: [PATCH 09/33] Nodes: clamp parameters to hard limits before cooking --- crates/eval/src/lib.rs | 20 +++++++++++- crates/nodes/src/catalog.rs | 54 ++++++++++++++++++++++++++++++++ crates/nodes/src/filters.rs | 18 ++++++++--- crates/nodes/src/filters_more.rs | 3 +- crates/nodes/src/generators.rs | 3 +- crates/nodes/src/lib.rs | 47 ++++++++++++++++++++++++++- 6 files changed, 137 insertions(+), 8 deletions(-) diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index b5d18df7..369ff9f8 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; 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; @@ -346,6 +346,12 @@ 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(); @@ -495,6 +501,18 @@ mod tests { 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 mut cache = Cache::default(); + let c = cook(&p, 0, &Options::new(&no_res), &mut 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(); diff --git a/crates/nodes/src/catalog.rs b/crates/nodes/src/catalog.rs index aed5b9b0..719c98e1 100644 --- a/crates/nodes/src/catalog.rs +++ b/crates/nodes/src/catalog.rs @@ -352,6 +352,60 @@ pub fn categories() -> Vec<(&'static str, Vec<&'static str>)> { out } +/// How many slider spans the hard limit extends past each end of a parameter's range. +const HARD_SPAN: f32 = 16.0; + +/// Clamp `v` to `[lo, hi]`; a non-finite `v` becomes `fallback`. +fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 { + if v.is_finite() { v.clamp(lo, hi) } else { fallback } +} + +/// Clamp numeric parameters to hard limits: the declared slider range widened by +/// `HARD_SPAN` spans on each side (the editor lets values past the slider through, so the +/// slider range itself is not a limit). Non-finite values become the default. Keeps cooks +/// bounded whatever a file, binding, function or command supplies. +pub fn clamp_params(def: &NodeDef, params: &mut BTreeMap) { + for p in &def.params { + let Some(v) = params.get_mut(p.id) else { continue }; + if let Value::Enum(i) = v { + if !p.options.is_empty() { + *i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX)); + } + continue; + } + if let Value::Color(c) = v { + for x in c { + *x = clamp_finite(*x, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0); + } + continue; + } + if p.min >= p.max { + continue; + } + let span = p.max - p.min; + let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span); + // The default's component `i`, or 0 when the default is a different variant. + let fallback = |i: usize| match &p.default { + Value::Float(d) => [*d].get(i).copied(), + Value::Float2(d) => d.get(i).copied(), + Value::Float3(d) => d.get(i).copied(), + Value::Float4(d) => d.get(i).copied(), + _ => None, + }; + let clamp_at = |x: &mut f32, i: usize| *x = clamp_finite(*x, lo, hi, fallback(i).unwrap_or(0.0)); + let clamp_int = |x: &mut i32| *x = (*x as f32).clamp(lo, hi).round() as i32; + match v { + Value::Float(x) => clamp_at(x, 0), + Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Int(x) => clamp_int(x), + Value::Int2(a) => a.iter_mut().for_each(clamp_int), + _ => {} + } + } +} + /// Parameter values for a node: catalog defaults overlaid with `overrides`. pub fn resolve_params(def: &NodeDef, overrides: &BTreeMap) -> BTreeMap { let mut m: BTreeMap = def.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect(); diff --git a/crates/nodes/src/filters.rs b/crates/nodes/src/filters.rs index 84a6645e..702383b5 100644 --- a/crates/nodes/src/filters.rs +++ b/crates/nodes/src/filters.rs @@ -361,7 +361,8 @@ fn contrast_luminosity(ctx: &Ctx) -> CookResult { } fn exposure(ctx: &Ctx) -> CookResult { - let k = 2f32.powf(ctx.f("stops")); + // Past +-64 stops the result is all black/white anyway; this keeps 2^stops finite. + let k = 2f32.powf(ctx.f("stops").clamp(-64.0, 64.0)); per_value(ctx, |v| v * k) } @@ -504,7 +505,15 @@ fn anisotropic_blur(ctx: &Ctx) -> CookResult { Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))]) } +/// Most extra horizontal passes `blur_xy` runs: a cost bound, whatever sigma it is given. +const MAX_BLUR_PASSES: i64 = 64; +/// Widest horizontal kernel half-width `blur_xy` builds: a cost bound on the kernel allocation. +const MAX_KERNEL_RADIUS: i64 = 512; + fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image { + if !sx.is_finite() || !sy.is_finite() { + return img.clone(); + } // Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so // blur fully with the smaller sigma and add the extra along x by repeated small passes. let base = ops::gaussian(img, sy, tile); @@ -512,12 +521,12 @@ fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image { if extra < 0.1 { return base; } - let n = (extra / 2.0).ceil().max(1.0) as i64; + let n = ((extra / 2.0).ceil().max(1.0) as i64).min(MAX_BLUR_PASSES); let step = extra / (n as f32).sqrt(); let mut out = base; for _ in 0..n { let src = out.clone(); - let r = (step * 2.0).ceil() as i64; + let r = ((step * 2.0).ceil() as i64).clamp(1, MAX_KERNEL_RADIUS); let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * step * step)).exp()).collect(); let sum: f32 = k.iter().sum(); out = Image::generate(src.w, src.h, src.kind, |x, y| { @@ -687,7 +696,8 @@ fn edge_detect(ctx: &Ctx) -> CookResult { .map(|(a, b)| { let d = a.sqrt().max(b.sqrt()); let t = (1.0 - d / w).max(0.0); - t.powf(1.0 - round * 0.8) + // A non-positive exponent on t = 0 gives inf; in range (round <= 1) it is >= 0.2. + t.powf((1.0 - round * 0.8).max(0.01)) }) .collect(); Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) diff --git a/crates/nodes/src/filters_more.rs b/crates/nodes/src/filters_more.rs index 403f2bb0..68c39415 100644 --- a/crates/nodes/src/filters_more.rs +++ b/crates/nodes/src/filters_more.rs @@ -222,7 +222,8 @@ fn smoothstep_node(ctx: &Ctx) -> CookResult { } fn s_curve(ctx: &Ctx) -> CookResult { - let (k, p) = (1.0 + ctx.f("amount") * 4.0, ctx.f("pivot").clamp(0.01, 0.99)); + // A negative k on a zero base gives inf; clamp it (k = 0 gives the finite 1). + let (k, p) = ((1.0 + ctx.f("amount") * 4.0).max(0.0), ctx.f("pivot").clamp(0.01, 0.99)); per_channel(ctx, |v, _| { let v = v.clamp(0.0, 1.0); if v < p { p * (v / p).powf(k) } else { 1.0 - (1.0 - p) * ((1.0 - v) / (1.0 - p)).powf(k) } diff --git a/crates/nodes/src/generators.rs b/crates/nodes/src/generators.rs index 700a6a08..f30db65a 100644 --- a/crates/nodes/src/generators.rs +++ b/crates/nodes/src/generators.rs @@ -357,7 +357,8 @@ fn plasma(ctx: &Ctx) -> CookResult { fn turbulence(ctx: &Ctx) -> CookResult { let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).sqrt())]) + // A negative roughness makes `ridged` negative; clamp so the sqrt can't be NaN. + Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).max(0.0).sqrt())]) } fn creased(ctx: &Ctx) -> CookResult { diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index d51c3d95..a30494ac 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -28,12 +28,13 @@ pub mod svg; pub mod text; pub mod weathering; -pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, find, resolve_params}; +pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, clamp_params, find, resolve_params}; #[cfg(test)] mod tests { use std::collections::BTreeMap; + use materialcraft_core::Value; use materialcraft_image::{Image, Kind}; use super::*; @@ -72,6 +73,50 @@ mod tests { assert!(catalog().len() >= 200, "{} nodes", catalog().len()); } + /// Every node cooks with each numeric parameter at a hostile value (huge, negative huge, NaN): + /// the hard limits keep the cook bounded, finite and the right size. + #[test] + fn every_node_survives_hostile_params() { + use std::time::{Duration, Instant}; + + let mut slow: Vec<(String, Duration)> = Vec::new(); + let total = Instant::now(); + for def in catalog() { + if def.id == "graph_instance" { + continue; + } + for p in &def.params { + for h in [1e30_f32, -1e30, f32::NAN] { + let v = match p.default { + Value::Float(_) => Value::Float(h), + Value::Int(_) => Value::Int(h as i32), + Value::Float2(_) => Value::Float2([h, h]), + Value::Enum(_) => Value::Enum(h as u32), + _ => continue, + }; + let mut params = resolve_params(def, &BTreeMap::from([(p.id.to_string(), v)])); + clamp_params(def, &mut params); + let inputs = vec![None; def.inputs.len()]; + let no_res = |_: &str| None; + let vars = BTreeMap::new(); + let ctx = Ctx { w: 16, h: 16, seed: 7, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; + let t = Instant::now(); + let out = (def.cook)(&ctx).unwrap_or_else(|e| panic!("{}.{}={h}: {e}", def.id, p.id)); + let dt = t.elapsed(); + assert!(dt < Duration::from_secs(2), "{}.{}={h} took {dt:?}", def.id, p.id); + if dt > Duration::from_millis(250) { + slow.push((format!("{}.{}={h}", def.id, p.id), dt)); + } + for img in &out { + assert_eq!((img.w, img.h), (16, 16), "{}.{}={h}", def.id, p.id); + assert!(img.data.iter().all(|x| x.is_finite()), "{}.{}={h} produced a non-finite value", def.id, p.id); + } + } + } + } + eprintln!("hostile params: total {:?}; cooks over 250 ms: {slow:?}", total.elapsed()); + } + #[test] fn noises_tile() { for id in [ From 55f1a1c3232ac504833ddedcfc9e63a4b713e4d2 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:30:34 -0600 Subject: [PATCH 10/33] Engine: add cook benchmarks for input changes and parameter edits Baseline (noisy, concurrent load), input change: 1024 ~320 ms, 2048 ~1500 ms, 21 of 21 nodes re-cooked. --- crates/engine/tests/perf.rs | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 crates/engine/tests/perf.rs 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}"); + } +} From b991f4fb112d2b87f79925c972787248b809254b Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:30:34 -0600 Subject: [PATCH 11/33] Eval: key nodes only on the graph inputs they read An exposed-input change re-cooked 21 of 21 nodes in rusty_metal; now 1 (the reader). Input-change cook (noisy, concurrent load): 1024 ~320 ms -> ~0.1 ms, 2048 ~1500 ms -> ~0.2 ms. --- crates/engine/tests/session.rs | 16 ++++++++++++++ crates/eval/src/lib.rs | 40 +++++++++++++++++++++++++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 161a3ea4..79bb422a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -138,6 +138,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, _)| u64::from(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(); diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 9a125d41..9cc33761 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -327,6 +327,24 @@ fn graph_tree_hash(pkg: &Package, gi: usize, stack: &mut Vec) -> u64 { 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, @@ -403,7 +421,7 @@ fn cook_node( 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) { return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; @@ -692,4 +710,24 @@ mod tests { let c = cook(&p, 0, &opts, &mut 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 = &mut 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"); + } } From 2758d1d389da5c676aa1564a92cc9faacda55df6 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:37:56 -0600 Subject: [PATCH 12/33] Cook: cancel stale background cooks and lock the cache only around lookups The cooker sets the running cook's cancel flag when the graph changes again and starts the new cook at once; eval::cook takes &Mutex and locks per lookup/insert. --- crates/engine/src/material_cmds.rs | 5 +-- crates/engine/src/session.rs | 9 +---- crates/eval/src/lib.rs | 60 ++++++++++++++++-------------- crates/ui-egui/src/cook.rs | 29 ++++++++++++--- 4 files changed, 59 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index c5902b97..b8d55711 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]; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 8339877b..cf9d6cc5 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -311,11 +311,7 @@ impl Session { 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 } @@ -324,8 +320,7 @@ impl Session { 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/eval/src/lib.rs b/crates/eval/src/lib.rs index 9cc33761..d25a49e4 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, HashMap}; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; use materialcraft_core::{Graph, Node, NodeId, Package, SizeMode, Value}; @@ -253,8 +253,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 }; @@ -353,7 +359,7 @@ fn cook_node( done: &Cooked, vars: &BTreeMap, opts: &Options, - cache: &mut Cache, + cache: &Mutex, ) -> NodeResult { let (in_ports, out_ports) = ports(pkg, node); let def = find(&node.def); @@ -423,7 +429,7 @@ fn cook_node( input_img.map(image_key), 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(); @@ -443,7 +449,7 @@ fn cook_node( 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), @@ -477,7 +483,7 @@ 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()); @@ -560,17 +566,17 @@ 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); } @@ -580,10 +586,10 @@ mod tests { 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()); } @@ -610,8 +616,8 @@ 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.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&selfi].error); @@ -641,13 +647,13 @@ mod tests { let (a, top) = instancing("a", "b"); let mut p = Package::new("p"); p.graphs = vec![a, b, c]; - let mut cache = Cache::default(); + let cache = Mutex::new(Cache::default()); let opts = Options::new(&no_res); - let first = cook(&p, 0, &opts, &mut cache); + 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, &mut cache); + 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); } @@ -658,8 +664,8 @@ mod tests { let (y, _) = instancing("y", "x"); let mut p = Package::new("p"); p.graphs = vec![x, y]; - 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); assert!(c.nodes[&xi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&xi].error); } @@ -677,13 +683,13 @@ mod tests { // 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 mut cache = Cache::default(); + let cache = Mutex::new(Cache::default()); let opts = Options::new(&res); - let first = cook(&p, 0, &opts, &mut cache); + 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, &mut cache); + let second = cook(&p, 0, &opts, &cache); assert!(!second.nodes[&bm].cached); assert!((second.image(bm, 0).unwrap().mean()[0] - mean).abs() > 0.05); } @@ -700,14 +706,14 @@ 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); } @@ -718,7 +724,7 @@ mod tests { 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 = &mut Cache::default(); + 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); diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index 9b6e4100..57033c1b 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -10,6 +10,9 @@ use crate::MaterialCraftApp; #[derive(Default)] pub struct Cooker { rx: Option>, + /// Stops the running cook between nodes once its result is stale. + #[cfg(not(target_arch = "wasm32"))] + cancel: Option>, /// When the running cook started (app seconds). pub started: Option, } @@ -25,11 +28,25 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { if let Some(rx) = &app.cooker.rx { match rx.try_recv() { Ok(c) => { - app.session.cooked = c; + if c.cancelled { + // A stopped cook is partial: keep the previous results and cook again. + app.session.dirty = true; + } else { + app.session.cooked = c; + } app.cooker.rx = None; app.cooker.started = None; ctx.request_repaint(); } + Err(TryRecvError::Empty) if app.session.dirty => { + // The running cook is stale: stop it, ignore its result and cook the new state. + #[cfg(not(target_arch = "wasm32"))] + if let Some(flag) = &app.cooker.cancel { + flag.store(true, std::sync::atomic::Ordering::Relaxed); + } + app.cooker.rx = None; + app.cooker.started = None; + } Err(TryRecvError::Empty) => { ctx.request_repaint_after(std::time::Duration::from_millis(16)); return; @@ -55,20 +72,20 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let cache = s.cache.clone(); let dec = s.resource_decoder(); let (tx, rx) = std::sync::mpsc::channel(); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let thread_flag = flag.clone(); use materialcraft_engine::eval::Options; - use std::sync::PoisonError; let spawned = std::thread::Builder::new().name("materialcraft-cook".into()).spawn(move || { let mut opts = Options::new(&dec); opts.max_size = max; - let cooked = { - let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner); - materialcraft_engine::eval::cook(&pkg, gi, &opts, &mut cache) - }; + opts.cancel = Some(&thread_flag); + let cooked = materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache); let _ = tx.send(cooked); }); match spawned { Ok(_) => { app.cooker.rx = Some(rx); + app.cooker.cancel = Some(flag); app.cooker.started = Some(now); } Err(e) => { From 76684bc3a870c38efd8a8b69ca8915f76dabc6df Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:38:35 -0600 Subject: [PATCH 13/33] Cook: format and lint fixes --- crates/engine/tests/session.rs | 2 +- crates/eval/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 79bb422a..8f55883e 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -150,7 +150,7 @@ fn exposed_input_change_recooks_only_readers() { 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, _)| u64::from(id.0)).collect(); + 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"); } diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index d25a49e4..ebdbafa0 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -11,8 +11,8 @@ use std::collections::{BTreeMap, HashMap}; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::{Arc, Mutex}; 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}; From c9e3a9ea837eb51ab19cbedf0d03a0072fa57ee2 Mon Sep 17 00:00:00 2001 From: smittie2000 Date: Tue, 3 Nov 2026 22:55:23 +0200 Subject: [PATCH 14/33] fix(windows): a start that never opens a window says why instead of exiting silently Without a usable GPU, driver or desktop, no graphics backend can create a window and MaterialCraft exited with code 1 and nothing on screen. The reason now goes to the log and to an error dialog, as FilmCraft does since 0.14.0 (which unstuck it on WinGet). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + apps/materialcraft/Cargo.toml | 2 ++ apps/materialcraft/src/main.rs | 3 +++ apps/materialcraft/src/start_failure.rs | 36 +++++++++++++++++++++++++ 4 files changed, 42 insertions(+) create mode 100644 apps/materialcraft/src/start_failure.rs diff --git a/Cargo.lock b/Cargo.lock index ce3b0fc1..2cf4cdaa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2315,6 +2315,7 @@ dependencies = [ "log", "materialcraft-engine", "materialcraft-ui-egui", + "rfd", "serde_json", "winresource", ] diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 64a1ca49..d5783b90 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -18,6 +18,8 @@ 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/main.rs b/apps/materialcraft/src/main.rs index 5a27232c..781e79d0 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; @@ -118,6 +119,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..836ae6ba --- /dev/null +++ b/apps/materialcraft/src/start_failure.rs @@ -0,0 +1,36 @@ +//! 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. +pub(crate) fn message(error: &eframe::Error) -> String { + format!("MaterialCraft could not start its window: {error}\n\nUpdating the graphics driver usually fixes this.") +} + +/// 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 the_message_names_the_cause_and_what_to_do() { + let text = message(&eframe::Error::AppCreation("no adapter".into())); + assert!(text.starts_with("MaterialCraft could not start its window"), "{text}"); + assert!(text.contains("no adapter"), "{text}"); + assert!(text.contains("graphics driver"), "{text}"); + } +} From 73378cbfd8328ad58f5505f9395ead5756b04afd Mon Sep 17 00:00:00 2001 From: Belligerently Date: Tue, 3 Nov 2026 17:16:16 -0500 Subject: [PATCH 15/33] Keep typed numeric parameter values across frames --- crates/ui-egui/src/properties.rs | 4 +- crates/ui-egui/src/widgets.rs | 29 ++++- crates/ui-egui/tests/numeric_input.rs | 172 ++++++++++++++++++++++++++ 3 files changed, 198 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/tests/numeric_input.rs diff --git a/crates/ui-egui/src/properties.rs b/crates/ui-egui/src/properties.rs index aabd042a..4978b7b5 100644 --- a/crates/ui-egui/src/properties.rs +++ b/crates/ui-egui/src/properties.rs @@ -43,10 +43,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.set_width(ui.available_width()); let node = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().cloned()); - match node { + ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { Some(n) => node_props(app, ui, &n), None => graph_props(app, ui), - } + }); }); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 4b2d5dbd..1f86f196 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -20,26 +20,45 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { let tk = Tokens::get(ui.ctx()); let (lo, hi) = (*range.start(), *range.end()); let w = ui.available_width(); + let mut edited = false; ui.horizontal(|ui| { ui.label(RichText::new(label).color(tk.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut text = format!("{:.*}", decimals, value); - let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE)); + let id = ui.next_auto_id(); + // Keep incomplete input (such as "-") across frames while editing. + let draft = id.with("numeric-draft"); + let editing = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id)); + let mut text = editing.then(|| ui.data(|d| d.get_temp::(draft))).flatten().unwrap_or_else(|| format!("{:.*}", decimals, value)); + let r = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE)); name(&r, egui::Role::TextInput, label); - if r.lost_focus() + if (r.changed() || r.lost_focus()) + && !ui.input(|i| i.key_pressed(egui::Key::Escape)) && let Ok(v) = text.trim().parse::() && v.is_finite() { - *value = v.clamp(lo, hi); + let v = v.clamp(lo, hi); + edited = v != *value; + *value = v; } + let focused = r.has_focus(); + ui.data_mut(|d| { + if focused { + d.insert_temp(draft, text); + } else { + d.remove::(draft); + } + }); }); }); let (rect, mut resp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag()); + if edited { + resp.mark_changed(); + } let (v, l) = (*value as f64, label.to_string()); resp.widget_info(move || egui::WidgetInfo::slider(true, v, l.clone())); if (resp.dragged() || resp.clicked()) diff --git a/crates/ui-egui/tests/numeric_input.rs b/crates/ui-egui/tests/numeric_input.rs new file mode 100644 index 00000000..ec027f90 --- /dev/null +++ b/crates/ui-egui/tests/numeric_input.rs @@ -0,0 +1,172 @@ +//! Exact numeric edits must survive intervening frames and reach engine parameters. +use egui::{Event, Key, Modifiers, vec2}; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_engine::core::{NodeId, Value}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.run("file.new", json!({"template":"empty"})).unwrap(); + let id = NodeId(app.run("graph.node.add", json!({"def":"transformation"})).unwrap()["id"].as_u64().unwrap()); + app.session.reset_history(); + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(8); + (h, id) +} +fn focus_x(h: &mut Harness<'static, MaterialCraftApp>, index: usize) { + h.get_all(By::new().role(egui::accesskit::Role::TextInput).label("X")).nth(index).unwrap().click(); + h.step(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.step(); +} +fn type_text(h: &mut Harness<'static, MaterialCraftApp>, text: &str) { + h.event(Event::Text(text.into())); + h.step(); + h.run_steps(4); +} +fn pair(h: &Harness<'static, MaterialCraftApp>, id: NodeId, param: &str) -> [f32; 2] { + match h.state().session.graph().unwrap().node(id).unwrap().params.get(param) { + Some(Value::Float2(v)) => *v, + None => match materialcraft_engine::nodes::find("transformation").unwrap().params.iter().find(|p| p.id == param).unwrap().default { + Value::Float2(v) => v, + _ => panic!("not a pair"), + }, + other => panic!("unexpected value {other:?}"), + } +} +#[test] +fn scale_x_commits_on_enter_and_focus_loss_with_undo() { + for enter in [true, false] { + let (mut h, id) = harness(false); + focus_x(&mut h, 1); + type_text(&mut h, "4"); + if enter { + h.key_press(Key::Enter); + h.step(); + } else { + h.get_by_label("Node label").click(); + h.step(); + } + h.run_steps(5); + assert_eq!(pair(&h, id, "scale"), [4.0, 1.0], "Scale X did not persist (Enter={enter})"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]); + h.state_mut().run("edit.redo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + } +} +#[test] +fn a_negative_decimal_can_be_typed_across_frames() { + let (mut h, id) = harness(false); + focus_x(&mut h, 0); + for part in ["-", ".", "5"] { + type_text(&mut h, part); + } + h.key_press(Key::Enter); + h.step(); + h.run_steps(4); + assert_eq!(pair(&h, id, "offset"), [-0.5, 0.0]); + assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]); +} +#[test] +fn clicking_the_canvas_and_switching_nodes_keep_the_right_values() { + let (mut h, id) = harness(false); + focus_x(&mut h, 1); + type_text(&mut h, "4"); + let pos = h.state().graph.view.left_top() + vec2(20.0, 20.0); + h.event(Event::PointerMoved(pos)); + h.step(); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(4); + assert!(h.state().session.selection.is_empty()); + assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + h.state_mut().run("graph.select", json!({"ids": [id.0]})).unwrap(); + h.run_steps(4); + focus_x(&mut h, 1); + type_text(&mut h, "5"); + let other = NodeId(h.state_mut().run("graph.node.add", json!({"def":"transformation","at":[300,0]})).unwrap()["id"].as_u64().unwrap()); + h.run_steps(4); + h.key_press(Key::Enter); + h.step(); + assert_eq!(pair(&h, id, "scale"), [5.0, 1.0]); + assert_eq!(pair(&h, other, "scale"), [1.0, 1.0], "an edit leaked into the newly selected node"); +} + +#[test] +fn invalid_input_is_ignored_and_values_are_clamped() { + let (mut h, id) = harness(false); + focus_x(&mut h, 0); + type_text(&mut h, "NaN"); + h.key_press(Key::Enter); + h.step(); + h.run_steps(4); + assert_eq!(pair(&h, id, "offset"), [0.0, 0.0]); + focus_x(&mut h, 0); + type_text(&mut h, "123"); + h.key_press(Key::Enter); + h.step(); + h.run_steps(4); + assert_eq!(pair(&h, id, "offset"), [1.0, 0.0]); + focus_x(&mut h, 0); + type_text(&mut h, "-"); + h.key_press(Key::Escape); + h.step(); + h.run_steps(4); + assert_eq!(pair(&h, id, "offset"), [1.0, 0.0]); +} + +#[test] +fn integer_input_and_slider_track_both_update_the_node() { + let (mut h, id) = harness(false); + let input = By::new().role(egui::accesskit::Role::TextInput).label("Random seed"); + h.get(input).click(); + h.step(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.step(); + type_text(&mut h, "42"); + h.key_press(Key::Enter); + h.step(); + h.run_steps(4); + assert_eq!(h.state().session.graph().unwrap().node(id).unwrap().base.seed, 42); + let pos = h.get(By::new().role(egui::accesskit::Role::Slider).label("Random seed")).rect().center(); + h.event(Event::PointerMoved(pos)); + h.step(); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(4); + assert_eq!(h.state().session.graph().unwrap().node(id).unwrap().base.seed, 500); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn exact_scale_screenshot() { + let (mut h, id) = harness(true); + focus_x(&mut h, 1); + type_text(&mut h, "4"); + h.key_press(Key::Enter); + h.step(); + h.run_steps(8); + assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("scale-x-4.png")).unwrap(); +} From ef8ab335c2d5eb953a8d13b3eb911c00f1e50207 Mon Sep 17 00:00:00 2001 From: A-Gift-Of-Flame <76142225+A-Gift-Of-Flame@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:55:13 +0100 Subject: [PATCH 16/33] feat(automation): material_export MCP tool for portable .mcmat Sandboxed agents could not hand a material to TextureCraft: the workspace sandbox refuses `file.*` commands and there was no MCP tool for `.mcmat`. Add `material_export {path, graph?, size?, values?}` (RPC method `material.export`). It cooks the graph through the same engine code as `file.exportMaterial` and writes the `.mcmat` only through AuthorizedWorkspace (cap-std, `--write-root`): no write root, a malformed path or an escape is an error, the parent folder must exist, and the file is capped at what `package_open` may read back. Bridge mode refuses it like the other path tools. The engine gets a shared `material_request` helper so the command and the tool parse graph/size/values identically. Tests: file written and readable, bad requests, denied without a write root (Denied and read-only workspace), path escapes (`..`, absolute, backslash, drive, symlink) and the MCP tool end to end. docs/control-protocol.md lists the method and tool. Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/headless.rs | 23 ++++++++- crates/automation/src/rpc.rs | 82 +++++++++++++++++++++++++++++- crates/automation/src/server.rs | 46 ++++++++++++++++- crates/automation/src/workspace.rs | 7 +++ crates/engine/src/material_cmds.rs | 12 ++++- docs/control-protocol.md | 10 ++-- 6 files changed, 170 insertions(+), 10 deletions(-) diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 3443f3f9..137c0e5c 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -4,7 +4,8 @@ use std::path::Path; use materialcraft_engine::core::NodeId; -use materialcraft_engine::{Session, commands, file_cmds, inspect}; +use materialcraft_engine::formats::material::MATERIAL_EXT; +use materialcraft_engine::{Session, commands, file_cmds, inspect, material_cmds}; use materialcraft_render::{Lighting, Maps, Scene, Settings}; use serde_json::{Value, json}; @@ -182,6 +183,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 }; diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 0c156b78..4338f341 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`. @@ -32,6 +33,7 @@ pub const METHODS: &[&str] = &[ "package.save", "bitmap.import", "outputs.export", + "material.export", "render", ]; @@ -84,6 +86,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), @@ -253,6 +256,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/server.rs b/crates/automation/src/server.rs index e23f3d18..12abc3cb 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -159,6 +159,22 @@ pub struct ExportParams { 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). @@ -305,7 +321,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, @@ -426,6 +442,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 { @@ -467,7 +490,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 {} @@ -489,6 +512,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/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index c5902b97..bc313b6f 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -144,13 +144,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/docs/control-protocol.md b/docs/control-protocol.md index 8c0fba6c..2729cc99 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol and MCP -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials for TextureCraft) · **Target:** the professional node-based material workflow +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** minor (`material_export` MCP tool) · **Target:** the professional node-based material workflow Agents drive MaterialCraft three ways, all dispatching the same engine commands: @@ -26,6 +26,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: | `package.open {path}` / `package.save {path?}` | headless | workspace-scoped package I/O | | `bitmap.import {path, name?}` | headless | embed an image as a resource | | `outputs.export {dir, format?, pattern?, depth?, graph?}` | headless | cook at full size and write every output | +| `material.export {path, graph?, size?, values?}` | headless | cook and write a portable `.mcmat` (`.mcmat` appended when missing) below the write root: the workspace-scoped `file.exportMaterial` | | `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii | | `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's screen position, fps, toasts | | `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click | @@ -122,6 +123,9 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k `session_inspect`, `command_list`, `command_run`, `command_batch`, `library_list`, `graph_new`, `node_add`, `node_connect`, `node_param`, `package_open`, `package_save`, `bitmap_import`, -`outputs_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`, +`outputs_export`, `material_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`, `ui_screenshot`, `ui_inspect`, `ui_menu_invoke`, `ui_input`. `package_open` opens `.mcmat` files -too; exporting one is CLI-only for now (the workspace sandbox refuses `file.*` commands). +too, and `material_export` `{path, graph?, size?, values?}` writes one below `--write-root` (`path` is +relative, the parent folder must exist, `values` are exposed input values). The workspace sandbox +still refuses `file.*` commands, so a sandboxed agent exports through the tool, not `file.exportMaterial`; +mesh-map `inputs` stay a CLI feature. From 6f73fc7c7745db317ff5c36b432dc13fbdf2350f Mon Sep 17 00:00:00 2001 From: smittie2000 Date: Wed, 4 Nov 2026 06:50:35 +0200 Subject: [PATCH 17/33] start_failure: say the window could not start or stopped, and offer the driver as a likely fix The dialog is shown for any error run_native returns, including one after the window was up, so "could not start its window" and "updating the graphics driver usually fixes this" overstated what is known. From review. Co-Authored-By: Claude Opus 5.5 --- apps/materialcraft/src/start_failure.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/materialcraft/src/start_failure.rs b/apps/materialcraft/src/start_failure.rs index 836ae6ba..5552e0f0 100644 --- a/apps/materialcraft/src/start_failure.rs +++ b/apps/materialcraft/src/start_failure.rs @@ -10,9 +10,10 @@ //! 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. +/// What the dialog and the log say. Any error `run_native` returns lands here, also one after the +/// window was up, so graphics is only the likely cause, not the certain one. pub(crate) fn message(error: &eframe::Error) -> String { - format!("MaterialCraft could not start its window: {error}\n\nUpdating the graphics driver usually fixes this.") + 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. @@ -29,7 +30,7 @@ mod tests { #[test] fn the_message_names_the_cause_and_what_to_do() { let text = message(&eframe::Error::AppCreation("no adapter".into())); - assert!(text.starts_with("MaterialCraft could not start its window"), "{text}"); + assert!(text.starts_with("MaterialCraft's window could not start or stopped"), "{text}"); assert!(text.contains("no adapter"), "{text}"); assert!(text.contains("graphics driver"), "{text}"); } From 5a7fe7b6b6c7fbe03d8a8188533acf6d831425e2 Mon Sep 17 00:00:00 2001 From: smittie2000 Date: Wed, 4 Nov 2026 14:17:30 +0200 Subject: [PATCH 18/33] start_failure: an app start-up error doesn't blame the graphics From CodeRabbit: an error from the app creator (AppCreation, e.g. a --control file it can't write) comes after the window and renderer started, so "update the graphics driver" doesn't apply. It now says only that the app couldn't start; other errors keep the window/graphics text. Tested both ways (the new test fails with the AppCreation arm disabled). Co-Authored-By: Claude Opus 5.5 --- apps/materialcraft/src/start_failure.rs | 27 +++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/apps/materialcraft/src/start_failure.rs b/apps/materialcraft/src/start_failure.rs index 5552e0f0..17596045 100644 --- a/apps/materialcraft/src/start_failure.rs +++ b/apps/materialcraft/src/start_failure.rs @@ -10,10 +10,17 @@ //! 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, also one after the -/// window was up, so graphics is only the likely cause, not the certain one. +/// 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 { - 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.") + 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. @@ -28,10 +35,18 @@ mod tests { use super::*; #[test] - fn the_message_names_the_cause_and_what_to_do() { - let text = message(&eframe::Error::AppCreation("no adapter".into())); + 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 adapter"), "{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}"); + } } From d4492ac255c6a4a4765996b510baf020cedd7d03 Mon Sep 17 00:00:00 2001 From: GrosFineasss Date: Wed, 4 Nov 2026 15:32:30 +0200 Subject: [PATCH 19/33] Connect a wire dragged from an unconnected input Pressing an unconnected input started no gesture, so a wire could only be pulled from an output. It now starts a wire that ends on an output and runs the same graph.connect. Dropping it anywhere else changes nothing. Dragging from an output and unplugging a connected input work as before. Refs #13 Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/graph_view.rs | 71 ++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index e9407e65..fada148d 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -1,9 +1,10 @@ //! The graph editor: a pannable, zoomable canvas of node cards (colored header, live thumbnail, //! size label), bezier wires between typed ports, frames, comments and navigation pins. //! -//! Gestures: left-drag a node to move it (the selection moves together), drag from a port to wire -//! it (dropping on empty canvas opens the node search, wired), drag an input to unplug and re-route -//! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to +//! Gestures: left-drag a node to move it (the selection moves together), drag from an output to wire +//! it (dropping on empty canvas opens the node search, wired), drag from an unconnected input to an +//! output to wire it the other way, drag a connected input to unplug and re-route it, drag the empty +//! canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to //! zoom, double-click a node to show it in the 2D view (a graph instance opens its graph), Space, Tab or //! double-click the canvas for the node search, right-click for menus, drop library items to add //! them. Every edit is an engine command; the gestures only draw previews until they commit. @@ -35,6 +36,7 @@ enum Drag { Nodes { delta: Vec2 }, Box { start: Pos2 }, Wire { from: (NodeId, String), detached: Option<(NodeId, String)> }, + WireFromInput { to: (NodeId, String) }, Pan, Frame { id: u64, delta: Vec2, resize: bool, nodes: Vec }, Comment { id: u64, delta: Vec2 }, @@ -609,6 +611,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { bezier(&painter, src.pos, p, Stroke::new(2.0, tk.accent)); } } + Some(Drag::WireFromInput { to }) => { + if let (Some(p), Some(dst)) = (pointer, app.graph.ports.iter().find(|h| !h.output && h.node == to.0 && h.port == to.1)) { + bezier(&painter, p, dst.pos, Stroke::new(2.0, tk.accent)); + } + } _ => {} } @@ -689,6 +696,8 @@ fn handle_input( app.graph.drag = Some(Drag::Wire { from: (h.node, h.port.clone()), detached: None }); } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { app.graph.drag = Some(Drag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); + } else { + app.graph.drag = Some(Drag::WireFromInput { to: (h.node, h.port.clone()) }); } } else if let Some((id, title, grip)) = frames.iter().find(|(_, t, g)| t.contains(p) || g.contains(p)) { let resize = grip.contains(p) && !title.contains(p); @@ -784,6 +793,12 @@ fn handle_input( } } } + Drag::WireFromInput { to } => { + let source = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| h.output).cloned(); + if let Some(s) = source { + app.run("graph.connect", json!({"from": s.node.0, "fromPort": s.port, "to": to.0.0, "toPort": to.1})); + } + } Drag::Frame { id, delta, resize, nodes } => { if delta.length() > 0.5 && let Some(f) = app.session.graph().ok().and_then(|g| g.frames.iter().find(|f| f.id == id)).cloned() @@ -1119,6 +1134,56 @@ mod tests { assert!(app.graph.search.is_some()); } + #[test] + fn wires_connect_when_dragged_from_either_end() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + app.run("file.new", json!({"template": "empty"})); + let id = |v: Option| v.and_then(|v| v["id"].as_u64()).unwrap(); + let noise = id(app.run("graph.node.add", json!({"def": "perlin_noise", "at": [0, 0]}))); + let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); + let ctx = egui::Context::default(); + let frame = |app: &mut MaterialCraftApp, events: Vec| { + ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }) + .textures_delta + .clear(); + }; + for _ in 0..3 { + frame(&mut app, Vec::new()); + } + let port = |app: &MaterialCraftApp, node: u64, output: bool, name: &str| { + app.graph.ports.iter().find(|h| h.node.0 == node && h.output == output && h.port == name).map(|h| h.pos).unwrap() + }; + let output = port(&app, noise, true, "output"); + let foreground = port(&app, blend, false, "foreground"); + let background = port(&app, blend, false, "background"); + let empty = app.graph.view.left_top() + vec2(5.0, 5.0); + let drag = |app: &mut MaterialCraftApp, from: Pos2, to: Pos2| { + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(from)]); + frame(app, vec![button(from, true)]); + frame(app, vec![egui::Event::PointerMoved(to)]); + frame(app, vec![button(to, false)]); + }; + let source = |app: &MaterialCraftApp| app.session.graph().unwrap().input_of(NodeId(blend), "foreground").map(|c| (c.from.0, c.from_port.clone())); + + // From the input: only an output finishes the wire, and a miss changes nothing. + drag(&mut app, foreground, empty); + assert_eq!(source(&app), None); + assert!(app.graph.search.is_none()); + drag(&mut app, foreground, background); + assert_eq!(source(&app), None); + drag(&mut app, foreground, output); + assert_eq!(source(&app), Some((noise, "output".to_string()))); + + // From the output, as before. + app.run("graph.disconnect", json!({"to": blend, "toPort": "foreground"})); + drag(&mut app, output, foreground); + assert_eq!(source(&app), Some((noise, "output".to_string()))); + } + #[test] fn node_search_shortcuts_respect_hover_and_keyboard_focus() { for key in [egui::Key::Space, egui::Key::Tab] { From 1eaa87a3ede546b90015d77da16661027f2fc049 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 08:43:44 -0500 Subject: [PATCH 20/33] Apply interface scale after pointer release --- crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/tests/interface_scale.rs | 89 +++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/interface_scale.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5bce4e0e..4adc7092 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -217,7 +217,8 @@ impl MaterialCraftApp { self.styled = Some(style); } let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0); - if (ctx.zoom_factor() - scale).abs() > 1e-3 { + // Rescaling during a drag moves the control under the pointer and feeds back into its value. + if (ctx.zoom_factor() - scale).abs() > 1e-3 && !ctx.input(|i| i.pointer.any_down()) { ctx.set_zoom_factor(scale); } control::poll(self, ctx); diff --git a/crates/ui-egui/tests/interface_scale.rs b/crates/ui-egui/tests/interface_scale.rs new file mode 100644 index 00000000..90d22e03 --- /dev/null +++ b/crates/ui-egui/tests/interface_scale.rs @@ -0,0 +1,89 @@ +//! Changing interface scale must not move its slider under a held pointer. +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, pos2, vec2}; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; + +fn harness(scale: f32, render: bool) -> Harness<'static, MaterialCraftApp> { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.windows.preferences = true; + app.ui.prefs.ui_scale = scale; + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(10); + h +} + +// Keep the physical window and pointer fixed, just as a native window does when zoom changes. +fn point(h: &mut Harness<'static, MaterialCraftApp>, physical: Pos2, pressed: Option) { + let zoom = h.ctx.zoom_factor(); + let pos = physical / zoom; + h.input_mut().screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0) / zoom)); + h.event(Event::PointerMoved(pos)); + if let Some(pressed) = pressed { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.step(); +} + +fn drag_scale(h: &mut Harness<'static, MaterialCraftApp>, fraction: f32) { + let initial = h.ctx.zoom_factor(); + let track = h.get(By::new().role(egui::accesskit::Role::Slider).label("Interface scale")).rect(); + let start = track.center() * initial; + let target = pos2(track.left() + track.width() * fraction, track.center().y) * initial; + point(h, start, None); + point(h, start, Some(true)); + point(h, target, None); + let chosen = h.state().ui.prefs.ui_scale; + assert!((chosen - initial).abs() > 0.1, "the drag did not change the setting"); + for _ in 0..15 { + point(h, target, None); + assert!((h.state().ui.prefs.ui_scale - chosen).abs() < 0.001, "scale drifted under a stationary pointer"); + assert!((h.ctx.zoom_factor() - initial).abs() < 0.001, "zoom changed while dragging"); + } + point(h, target, Some(false)); + h.run_steps(5); + assert!((h.state().ui.prefs.ui_scale - chosen).abs() < 0.001, "release changed the chosen value"); + assert!((h.ctx.zoom_factor() - chosen).abs() < 0.001, "release did not apply the chosen scale"); +} + +#[test] +fn scale_drags_are_stable_and_apply_on_release() { + for (initial, fraction) in [(1.0, 0.7), (1.0, 0.1), (1.5, 0.2)] { + let mut h = harness(initial, false); + drag_scale(&mut h, fraction); + } +} + +#[test] +fn scale_track_click_applies_after_release() { + let mut h = harness(1.0, false); + let track = h.get(By::new().role(egui::accesskit::Role::Slider).label("Interface scale")).rect(); + let target = pos2(track.left() + track.width() * 0.8, track.center().y); + point(&mut h, target, None); + point(&mut h, target, Some(true)); + assert_eq!(h.ctx.zoom_factor(), 1.0); + point(&mut h, target, Some(false)); + h.run_steps(5); + assert!(h.state().ui.prefs.ui_scale > 1.5); + assert!((h.ctx.zoom_factor() - h.state().ui.prefs.ui_scale).abs() < 0.001); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn scale_drag_screenshot() { + let mut h = harness(1.0, true); + drag_scale(&mut h, 0.7); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("interface-scale-after-drag.png")).unwrap(); +} From 4c3363037656411cb71c28c202ca6853a7426747 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 13:13:08 -0500 Subject: [PATCH 21/33] Clarify node resolution while previewing --- crates/ui-egui/src/graph_view.rs | 18 ++++- crates/ui-egui/tests/preview_resolution.rs | 91 ++++++++++++++++++++++ 2 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/preview_resolution.rs diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index e9407e65..6845bf2e 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -520,7 +520,23 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let footer = Rect::from_min_max(pos2(sr.left(), body.bottom()), sr.max); if let Some(img) = result.and_then(|r| r.outputs.first()) { let bits = if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() }; - let txt = format!("{}x{} - {}{}", img.w, img.h, if img.is_gray() { "L" } else { "C" }, bits); + let format = format!("{}{}", if img.is_gray() { "L" } else { "C" }, bits); + let txt = if let Some(limit) = app.session.preview_size { + if error.is_none() { + let [pw, ph] = g.size_px(); + resp.clone().on_hover_text(format!( + "{} x {} ({format}bpc)\n{}: {pw} x {ph}\n{}: {limit} px\n{}", + img.w, + img.h, + tr("Parent size"), + tr("Preview limit"), + tr("Change Preview size while editing in Edit > Preferences. Exports use each node's configured output size.") + )); + } + format!("{}x{} {}", img.w, img.h, tr("Preview")) + } else { + format!("{}x{} - {format}", img.w, img.h) + }; painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), tk.text_dim); } if n.def == "output" { diff --git a/crates/ui-egui/tests/preview_resolution.rs b/crates/ui-egui/tests/preview_resolution.rs new file mode 100644 index 00000000..3054a712 --- /dev/null +++ b/crates/ui-egui/tests/preview_resolution.rs @@ -0,0 +1,91 @@ +//! Node cards distinguish editing previews from configured graph resolution. +use egui::{Event, epaint::Shape, vec2}; +use egui_kittest::Harness; +use materialcraft_engine::core::NodeId; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(preview: u32, render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.prefs.preview_size = preview; + app.ui.graph_camera.zoom = 1.0; + let id = NodeId(app.run("graph.node.add", json!({"def":"uniform"})).unwrap()["id"].as_u64().unwrap()); + app.apply_prefs(); + app.session.cook(); + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(10); + (h, id) +} + +fn texts(shape: &Shape, out: &mut Vec) { + match shape { + Shape::Text(t) => out.push(t.galley.text().to_owned()), + Shape::Vec(shapes) => { + for s in shapes { + texts(s, out); + } + } + _ => {} + } +} +fn painted(h: &Harness<'static, MaterialCraftApp>) -> Vec { + let mut out = Vec::new(); + for s in &h.output().shapes { + texts(&s.shape, &mut out); + } + out +} + +#[test] +fn node_resolution_explains_the_preview_cap() { + let (mut h, id) = harness(512, false); + let img = &h.state().session.cooked.nodes[&id].outputs[0]; + assert_eq!((img.w, img.h), (512, 512)); + assert_eq!(h.state().session.graph().unwrap().size, [10, 10]); + assert!(painted(&h).iter().any(|t| t == "512x512 Preview"), "missing preview label: {:?}", painted(&h)); + let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1; + h.event(Event::PointerMoved(rect.center())); + h.run_steps(90); + let text = painted(&h).join("\n"); + assert!(text.contains("Parent size: 1024 x 1024"), "{text}"); + assert!(text.contains("Preview limit: 512 px"), "{text}"); + assert!(text.contains("Edit > Preferences"), "{text}"); + assert!(text.contains("16bpc"), "format information lost: {text}"); + let full = h.state().session.cook_full(0); + let img = &full.nodes[&id].outputs[0]; + assert_eq!((img.w, img.h), (1024, 1024)); +} + +#[test] +fn full_size_mode_retains_the_resolution_and_format() { + let (h, id) = harness(0, false); + let img = &h.state().session.cooked.nodes[&id].outputs[0]; + assert_eq!((img.w, img.h), (1024, 1024)); + assert!(painted(&h).iter().any(|t| t == "1024x1024 - C16"), "{:?}", painted(&h)); + assert!(!painted(&h).iter().any(|t| t == "1024x1024 Preview")); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn preview_resolution_screenshots() { + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + for (preview, name) in [(512, "preview"), (0, "full-size")] { + let (mut h, id) = harness(preview, true); + h.render().unwrap().save(dir.join(format!("{name}.png"))).unwrap(); + if preview > 0 { + let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1; + h.event(Event::PointerMoved(rect.center())); + h.run_steps(90); + h.render().unwrap().save(dir.join("preview-tooltip.png")).unwrap(); + } + } +} From bdfc3daabd4cb02827e6f113598b867c1e31e85f Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Wed, 4 Nov 2026 21:58:48 +0000 Subject: [PATCH 22/33] cli: accept --automation-read-root / --automation-write-root (#55) materialcraft-cli mcp and serve now take the --automation-*-root spelling the other crafting apps use, as aliases of --read-root / --write-root. The parser stores them under the short names, so the last root given wins whichever spelling it used. Adds unit tests and a note in the protocol doc. Fixes #55 Co-Authored-By: Claude Opus --- apps/materialcraft-cli/src/main.rs | 47 +++++++++++++++++++++++++++--- docs/control-protocol.md | 3 +- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index 57868c09..349746d8 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -40,7 +40,8 @@ USAGE: render: real displacement from the height output, 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. @@ -60,10 +61,14 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("cook", &["--graph", "--set"], &["--full"]), ("export", &["--graph", "--set", "--format", "--depth", "--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() { @@ -301,3 +307,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/docs/control-protocol.md b/docs/control-protocol.md index 75488a5c..726cb5d6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -5,7 +5,8 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: 1. **MCP** (`materialcraft-cli mcp`): headless (an in-process session, files only below - `--read-root` / `--write-root`) or bridged to the running app (`--bridge `). + `--read-root` / `--write-root`, also spelled `--automation-read-root` / + `--automation-write-root` as in the other crafting apps; `serve` takes them too) or bridged to the running app (`--bridge `). 2. **JSON lines** (`materialcraft-cli serve`): the same methods on stdio, or on `127.0.0.1:` behind a token. 3. **The app's control channel** (`materialcraft --control `): one JSON request per line, From 9b51c35dd74189ced6e27e3558629ce351b77a90 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 19:14:56 -0500 Subject: [PATCH 23/33] Keep keyboard-selected node search results visible --- crates/ui-egui/src/graph_view.rs | 69 +++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index ee877da9..c3a1f2d9 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -1114,7 +1114,7 @@ fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &Cam) { pick = Some(d.id); } egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { - for (i, d) in list.iter().enumerate().take(60) { + for (i, d) in list.iter().enumerate() { let r = ui.add( egui::Button::selectable(i == s.sel, format!("{} ", d.label)) .right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)), @@ -1456,4 +1456,71 @@ mod tests { assert!(p.y > r.top() + HEADER_H && p.y < r.bottom() - FOOTER_H); } } + fn search_harness(render: bool) -> egui_kittest::Harness<'static, MaterialCraftApp> { + let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); + let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(10); + let pointer = h.state().graph.view.center(); + h.event(egui::Event::PointerMoved(pointer)); + h.step(); + h.key_press(egui::Key::Tab); + h.step(); + assert!(h.state().graph.search.is_some()); + h + } + + fn select_result_after_cutoff(h: &mut egui_kittest::Harness<'static, MaterialCraftApp>) -> &'static str { + for _ in 0..60 { + h.key_press(egui::Key::ArrowDown); + h.step(); + } + h.run_steps(3); // Let scroll_to_me bring the selected row into view. + let selected = h.state().graph.search.as_ref().unwrap().sel; + assert_eq!(selected, 60); + let def = matches("")[selected]; + let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap(); + fn visible(shape: &egui::epaint::Shape, clip: Rect, popup: Rect, label: &str) -> bool { + match shape { + egui::epaint::Shape::Text(t) => popup.contains(t.pos) && clip.contains(t.pos) && t.galley.text().trim_start().starts_with(label), + egui::epaint::Shape::Vec(v) => v.iter().any(|s| visible(s, clip, popup, label)), + _ => false, + } + } + assert!( + h.output().shapes.iter().any(|s| visible(&s.shape, s.clip_rect, popup, def.label)), + "keyboard-selected result {selected} ({}) is not visible in the popup", + def.label + ); + def.id + } + + #[test] + fn keyboard_search_selection_after_sixty_results_is_visible_and_inserts() { + let mut h = search_harness(false); + let expected = select_result_after_cutoff(&mut h); + h.key_press(egui::Key::Enter); + h.step(); + assert!(h.state().graph.search.is_none()); + let graph = h.state().session.graph().unwrap(); + assert_eq!(graph.nodes.len(), 1); + assert_eq!(graph.nodes[0].def, expected); + } + + #[test] + #[ignore = "requires an offscreen GPU"] + fn search_result_after_sixty_screenshot() { + let mut h = search_harness(true); + select_result_after_cutoff(&mut h); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("search-result-61.png")).unwrap(); + } } From ff310018eff28d1934ec7130a9e1759c6c5fd3c2 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 19:56:16 -0500 Subject: [PATCH 24/33] Make round parameter values reachable by dragging --- crates/ui-egui/src/widgets.rs | 9 ++- crates/ui-egui/tests/slider_round_values.rs | 89 +++++++++++++++++++++ 2 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/tests/slider_round_values.rs diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 4b2d5dbd..69f1546e 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -45,8 +45,13 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI if (resp.dragged() || resp.clicked()) && let Some(p) = resp.interact_pointer_pos() { - let t = ((p.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); - let v = lo + (hi - lo) * t; + let value_at = |x: f32| { + let t = ((x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); + f64::from(lo) + (f64::from(hi) - f64::from(lo)) * f64::from(t) + }; + // Use the same round-value aiming as egui's standard sliders, within one physical pixel. + let radius = ui.input(|i| i.aim_radius()); + let v = egui::emath::smart_aim::best_in_range_f64(value_at(p.x - radius), value_at(p.x + radius)) as f32; if (v - *value).abs() > f32::EPSILON { *value = v; resp.mark_changed(); diff --git a/crates/ui-egui/tests/slider_round_values.rs b/crates/ui-egui/tests/slider_round_values.rs new file mode 100644 index 00000000..8a257500 --- /dev/null +++ b/crates/ui-egui/tests/slider_round_values.rs @@ -0,0 +1,89 @@ +//! Pointer drags should reach nearby round values, as standard egui sliders do. +use egui::{Event, Modifiers, PointerButton, pos2, vec2}; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_engine::core::{NodeId, Value}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(ppp: f32, render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let id = NodeId(app.run("graph.node.add", json!({"def":"transformation"})).unwrap()["id"].as_u64().unwrap()); + app.session.reset_history(); + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(ppp).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(8); + (h, id) +} + +fn drag_near(h: &mut Harness<'static, MaterialCraftApp>, label: &str, index: usize, value: f32, lo: f32, hi: f32) { + let rect = h.get_all(By::new().role(egui::accesskit::Role::Slider).label(label)).nth(index).unwrap().rect(); + let start = pos2(rect.left() + rect.width() * 0.2, rect.center().y); + // Aim slightly off the exact value, within one physical pixel. + let target = pos2(rect.left() + 5.0 + (rect.width() - 10.0) * (value - lo) / (hi - lo) + 0.4 / h.ctx.pixels_per_point(), rect.center().y); + h.event(Event::PointerMoved(start)); + h.step(); + h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + h.event(Event::PointerMoved(start + vec2(10.0, 0.0))); + h.step(); + h.event(Event::PointerMoved(target)); + h.step(); + h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.step(); + h.run_steps(3); +} +fn rotation(h: &Harness<'static, MaterialCraftApp>, id: NodeId) -> f32 { + match h.state().session.graph().unwrap().node(id).unwrap().params.get("rotation") { + Some(Value::Float(v)) => *v, + None => 0.0, + other => panic!("unexpected rotation {other:?}"), + } +} + +#[test] +fn dragging_can_reach_exact_round_angles_at_multiple_pixel_scales() { + for ppp in [1.0, 2.0] { + for angle in [90.0, -90.0, 0.0, 360.0, -360.0] { + let (mut h, id) = harness(ppp, false); + drag_near(&mut h, "Rotation", 0, angle, -360.0, 360.0); + assert_eq!(rotation(&h, id), angle / 360.0, "angle={angle}, pixels_per_point={ppp}"); + if angle == 90.0 { + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(rotation(&h, id), 0.0); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!(rotation(&h, id), 0.25); + } + } + } +} + +#[test] +fn fractional_parameter_values_remain_reachable() { + let (mut h, id) = harness(1.0, false); + drag_near(&mut h, "X", 1, 1.5, 0.01, 10.0); + drag_near(&mut h, "X", 0, -0.5, -1.0, 1.0); + let n = h.state().session.graph().unwrap().node(id).unwrap(); + assert_eq!(n.params.get("scale"), Some(&Value::Float2([1.5, 1.0]))); + assert_eq!(n.params.get("offset"), Some(&Value::Float2([-0.5, 0.0]))); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn exact_angle_screenshot() { + let (mut h, id) = harness(1.0, true); + drag_near(&mut h, "Rotation", 0, 90.0, -360.0, 360.0); + assert_eq!(rotation(&h, id), 0.25); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("rotation-90.png")).unwrap(); +} From f421d10b3fbfaf199f2c58c1fe3c19f503230111 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 20:18:15 -0500 Subject: [PATCH 25/33] Recognize Histogram Scan and Auto Levels SBS aliases --- crates/formats/src/sbs.rs | 19 +++- crates/formats/tests/sbs_library_aliases.rs | 117 ++++++++++++++++++++ 2 files changed, 133 insertions(+), 3 deletions(-) create mode 100644 crates/formats/tests/sbs_library_aliases.rs diff --git a/crates/formats/src/sbs.rs b/crates/formats/src/sbs.rs index 5beb8207..ff6431b9 100644 --- a/crates/formats/src/sbs.rs +++ b/crates/formats/src/sbs.rs @@ -1074,8 +1074,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 +1091,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_alias = match def.id { + "histogram_scan" => Some("Input_1"), + "auto_levels" => Some("Input"), + _ => None, + }; + if let Some(alias) = input_alias { + inputs.insert(alias.to_string(), "input".to_string()); + } ReadNode { id, index, inputs, outputs, open_inputs: false } } diff --git a/crates/formats/tests/sbs_library_aliases.rs b/crates/formats/tests/sbs_library_aliases.rs new file mode 100644 index 00000000..a90a104f --- /dev/null +++ b/crates/formats/tests/sbs_library_aliases.rs @@ -0,0 +1,117 @@ +//! The reported library-node aliases must preserve imported settings and connections. +use materialcraft_core::{Graph, Package, Value}; +use materialcraft_formats::sbs::{read_sbs, write_sbs}; + +fn plain_xml(bytes: &[u8]) -> 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("