From a1be44cfa1f0706ec2b66db5400dcd7d3646ee51 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 21:16:30 +0000 Subject: [PATCH] Auto: Pin workspace saves and preserve material export choices Hold the resolved save directory across SBS serialization and writes. Only clean up owned staging files and compare existing assets incrementally. Bound source assets before archive serialization, limit discarded SBS inflation, and account for shared graph depth. Decode preview inputs on demand and release failed browser downloads. Distinguish automatic and explicit output colors, borrow graphs while drawing export tabs, and preserve numeric export selectors and MCP option validation. --- Cargo.lock | 14 +- Cargo.toml | 4 +- README.md | 11 +- apps/materialcraft-cli/src/main.rs | 11 +- apps/materialcraft-cli/tests/published.rs | 46 +++-- crates/automation/src/headless.rs | 43 +++-- crates/automation/src/rpc.rs | 34 ++-- .../src/server/material_craft_mcp.rs | 13 +- .../parameter/material_export_params.rs | 15 +- crates/automation/src/workspace.rs | 176 ++++++++++++++---- crates/automation/tests/package_files.rs | 47 +++-- crates/engine/Cargo.toml | 3 + crates/engine/src/export_request.rs | 27 +-- crates/engine/src/file_cmds.rs | 4 +- crates/engine/src/graph_cmds.rs | 13 +- crates/engine/src/linked_files.rs | 24 ++- crates/engine/src/linked_resource.rs | 6 +- crates/engine/src/material_bake.rs | 37 ++-- crates/engine/src/material_cmds.rs | 7 + crates/engine/src/material_cmds.test.rs | 47 ++++- crates/engine/src/material_options.rs | 9 +- crates/eval/src/graph_execution.rs | 41 ++-- crates/eval/src/node_execution.rs | 3 +- crates/eval/src/tests.rs | 105 +++++++++++ crates/formats/src/image.rs | 7 +- crates/formats/src/material/archive.rs | 70 ++++++- crates/formats/src/material/mod.rs | 2 +- .../formats/src/material/snapshot_builder.rs | 130 ++++++------- crates/formats/src/sbs/embedded.rs | 129 +++++++------ crates/formats/src/sbs/embedded_error.rs | 28 +++ crates/formats/src/sbs/instance_interface.rs | 45 +++-- crates/formats/src/sbs/mod.rs | 1 + crates/formats/src/sbs/presets.rs | 3 + crates/formats/src/sbs/read.rs | 6 +- crates/formats/src/sbs/sbs_reader.rs | 18 +- crates/formats/src/sbs/tests.rs | 27 ++- crates/ui-egui/Cargo.toml | 5 +- crates/ui-egui/src/export/export_tests.rs | 14 +- crates/ui-egui/src/export/mod.rs | 45 +++-- crates/ui-egui/src/export/outputs.rs | 48 +++-- crates/ui-egui/src/material_craft_app.rs | 1 + crates/ui-egui/src/native_dialogs.test.rs | 3 +- crates/ui-egui/src/web_files.rs | 29 +-- crates/ui-egui/src/windows.test.rs | 1 + crates/ui-egui/tests/it/export_window.rs | 27 ++- crates/ui-egui/tests/resize.rs | 12 +- docs/control-protocol.md | 10 +- 47 files changed, 963 insertions(+), 438 deletions(-) create mode 100644 crates/formats/src/sbs/embedded_error.rs diff --git a/Cargo.lock b/Cargo.lock index 6a6a1c8c..7ebca689 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -999,6 +999,16 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-platform" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc" +dependencies = [ + "js-sys", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "craft-quit" version = "0.1.0" @@ -2874,6 +2884,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "tempfile", "thiserror 2.0.21", ] @@ -2954,6 +2965,7 @@ dependencies = [ "craft-atomic", "craft-dialogs", "craft-keymap", + "craft-platform", "craft-quit", "craft-ui", "craft-update", @@ -2963,7 +2975,6 @@ dependencies = [ "egui-phosphor", "egui_kittest", "image", - "js-sys", "log", "materialcraft-engine", "materialcraft-render", @@ -2973,7 +2984,6 @@ dependencies = [ "sha2", "sys-locale", "tempfile", - "wasm-bindgen", "wasm-bindgen-futures", "web-sys", "zip 2.6.1", diff --git a/Cargo.toml b/Cargo.toml index b96464d4..c5c26f4a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,15 +83,17 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"] cap-std = "4" getrandom = "0.3" # Shared Craft egui components from storytold/craft-libs -# MIT OR Apache-2.0; all shared dependencies use one reviewed revision +# MIT OR Apache-2.0 egui_kittest = "0.37" craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } +# MCMAT v3 uses its merged archive revision and the matching ZIP crate craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] } # Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0 craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] } # Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0 craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } +craft-platform = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } # The platform quit and the macOS Quit menu item: storytold/craft-libs, MIT OR Apache-2.0 craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] } craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" } diff --git a/README.md b/README.md index d6bf702e..fd9a7629 100644 --- a/README.md +++ b/README.md @@ -145,13 +145,12 @@ cargo run --release -p materialcraft # desktop app cargo run --release -p materialcraft -- package.sbs # open an SBS package cargo run --release -p materialcraft -- --control 7878 # + JSON control channel cargo run --release -p materialcraft-cli -- mcp # MCP server (stdio) -cargo run --release -p materialcraft-cli -- new wood wood.sbs -cargo run --release -p materialcraft-cli -- render wood.sbs wood.png --scene sphere --full --hq -cargo run --release -p materialcraft-cli -- export wood.sbs textures --format png --depth 16 -# Given a separate my.sbs with Materials/Oak and an exposed wear parameter: +cargo run --release -p materialcraft-cli -- new pbr surface.sbs --name Surface +cargo run --release -p materialcraft-cli -- render surface.sbs surface.png --scene sphere --full --hq +cargo run --release -p materialcraft-cli -- export surface.sbs textures --format png --depth 16 cargo run --release -p materialcraft-cli -- export my.sbs out --set wear=0.7 # with a graph input "wear" set first -cargo run --release -p materialcraft-cli -- publish my.sbs my.mcmat --graph Materials/Oak -cargo run --release -p materialcraft-cli -- export my.mcmat build/oak --profile materialx --size 2048 --set wear=0.7 +cargo run --release -p materialcraft-cli -- publish surface.sbs surface.mcmat --graph Surface +cargo run --release -p materialcraft-cli -- export surface.mcmat build/surface --profile materialx --size 512 cd apps/materialcraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index 3d1babcc..621a2fa4 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -187,9 +187,9 @@ fn graph_selector(selector: &str) -> Value { } fn output_size(size: &str) -> Result { - let pixels = |n: &str| n.parse::().map_err(|_| "--size expects pixels or WIDTHxHEIGHT".to_string()); + let pixels = |side: &str| side.parse::().map_err(|_| "--size expects pixels or WIDTHxHEIGHT".to_string()); match size.split_once('x') { - Some((w, h)) => Ok(json!([pixels(w)?, pixels(h)?])), + Some((width, height)) => Ok(json!([pixels(width)?, pixels(height)?])), None => Ok(json!(pixels(size)?)), } } @@ -201,6 +201,7 @@ fn cook_parameters(a: &Args) -> Result { if flag != "--set" && flag != "--input" { continue; } + let (id, value) = value.as_deref().and_then(|v| v.split_once('=')).filter(|(id, _)| !id.is_empty()).ok_or_else(|| format!("{flag} expects identifier=value"))?; if flag == "--set" { @@ -285,6 +286,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { if !r["failed"].is_null() { return Err("the batch stopped at an error".into()); } + if let Some(out) = save { h.save(Some(out)).map_err(|e| e.to_string())?; } @@ -323,7 +325,10 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { p["pattern"] = json!(a.get("--pattern")); p["profile"] = json!(a.get("--profile")); p["normalFormat"] = json!(a.get("--normal-format")); - p["displacementScale"] = json!(a.num::("--displacement-scale")?); + if let Some(scale) = a.num::("--displacement-scale")? { + p["displacementScale"] = serde_json::Number::from_f64(scale).ok_or("--displacement-scale must be finite")?.into(); + } + print(&h.export(&p).map_err(|e| e.to_string())?); } "render" => { diff --git a/apps/materialcraft-cli/tests/published.rs b/apps/materialcraft-cli/tests/published.rs index 75663592..ab2dd67f 100644 --- a/apps/materialcraft-cli/tests/published.rs +++ b/apps/materialcraft-cli/tests/published.rs @@ -13,19 +13,31 @@ fn run(dir: &Path, args: &[&str]) -> Value { #[test] fn a_published_graph_bakes_openpbr_variations_after_the_project_is_removed() { - let temporary = tempfile::tempdir().unwrap(); - let dir = temporary.path().to_path_buf(); - run(&dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]); - run(&dir, &["run", "source.sbs", "graph.exposed.add", r#"{"id":"tint","bind":{"node":1,"param":"color"}}"#, "-o", "studio.mcraft"]); - run(&dir, &["publish", "studio.mcraft", "oak.mcmat", "--graph", "Oak"]); + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + run(dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]); + run(dir, &["run", "source.sbs", "graph.exposed.add", r#"{"id":"tint","bind":{"node":1,"param":"color"}}"#, "-o", "studio.mcraft"]); + run(dir, &["publish", "studio.mcraft", "oak.mcmat", "--graph", "Oak"]); std::fs::remove_file(dir.join("studio.mcraft")).unwrap(); std::fs::remove_file(dir.join("source.sbs")).unwrap(); - let initial = run(&dir, &["info", "oak.mcmat"]); + + let invalid_scale = Command::new(env!("CARGO_BIN_EXE_materialcraft-cli")) + .current_dir(dir) + .args(["export", "oak.mcmat", "invalid", "--profile", "materialx", "--displacement-scale", "NaN"]) + .output() + .unwrap(); + + assert!(!invalid_scale.status.success(), "an invalid displacement scale produced a material"); + assert!(String::from_utf8_lossy(&invalid_scale.stderr).contains("displacement-scale")); + assert!(!dir.join("invalid").exists()); + + let initial = run(dir, &["info", "oak.mcmat"]); assert_eq!(initial["parameters"][0]["id"], "tint"); for (folder, size, tint) in [("small", 32, "#ff0000"), ("large", 64, "#0000ff")] { let report = - run(&dir, &["export", "oak.mcmat", "--out", folder, "--profile", "materialx", "--size", &size.to_string(), "--set", &format!("tint={tint}")]); + run(dir, &["export", "oak.mcmat", "--out", folder, "--profile", "materialx", "--size", &size.to_string(), "--set", &format!("tint={tint}")]); let maps = report["maps"].as_array().unwrap(); + assert_eq!(maps.len(), 6, "every output of the material template is exported"); let base = maps.iter().find(|m| m["usage"] == "baseColor").unwrap(); let relative = base["file"].as_str().unwrap(); assert_eq!(base["size"], json!([size, size])); @@ -42,21 +54,21 @@ fn a_published_graph_bakes_openpbr_variations_after_the_project_is_removed() { assert!((displacement.get(0, 0, false)[0] + 0.5).abs() < 1e-5); assert!(report["unmapped"].as_array().unwrap().iter().any(|id| id == "ambientocclusion")); } - let rectangular = run(&dir, &["cook", "oak.mcmat", "--size", "64x32"]); + let rectangular = run(dir, &["cook", "oak.mcmat", "--size", "64x32"]); assert_eq!(rectangular["outputs"][0]["size"], json!([64, 32])); - assert_eq!(run(&dir, &["info", "oak.mcmat"]), initial); + assert_eq!(run(dir, &["info", "oak.mcmat"]), initial); } #[test] fn failed_materialx_reexport_preserves_the_last_complete_material() { - let temporary = tempfile::tempdir().unwrap(); - let dir = temporary.path().to_path_buf(); - run(&dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]); - let export = |folder, size| run(&dir, &["export", "source.sbs", folder, "--profile", "materialx", "--size", size]); + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + run(dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]); + let export = |folder, size| run(dir, &["export", "source.sbs", folder, "--profile", "materialx", "--size", size]); let first = export("material", "32"); - let added = run(&dir, &["run", "source.sbs", "graph.node.add", r#"{"def":"output","params":{"identifier":"extra"}}"#, "-o", "source.sbs"]); + let added = run(dir, &["run", "source.sbs", "graph.node.add", r#"{"def":"output","params":{"identifier":"extra"}}"#, "-o", "source.sbs"]); let wire = json!({"from":1,"to":added["id"],"toPort":"input"}).to_string(); - run(&dir, &["run", "source.sbs", "graph.connect", &wire, "-o", "source.sbs"]); + run(dir, &["run", "source.sbs", "graph.connect", &wire, "-o", "source.sbs"]); let next = export("reference", "64"); let material = dir.join("material"); let original_files: Vec<_> = first["maps"] @@ -74,12 +86,14 @@ fn failed_materialx_reexport_preserves_the_last_complete_material() { std::fs::create_dir(&blocked).unwrap(); let failed = Command::new(env!("CARGO_BIN_EXE_materialcraft-cli")) - .current_dir(&dir) + .current_dir(dir) .args(["export", "source.sbs", "material", "--profile", "materialx", "--size", "64"]) .output() .unwrap(); assert!(!failed.status.success()); + let error = String::from_utf8_lossy(&failed.stderr); + assert!(error.contains(blocked.file_name().unwrap().to_str().unwrap()), "{error}"); assert_eq!(std::fs::read(material.join("material.mtlx")).unwrap(), document); for (name, bytes) in original_files { assert_eq!(std::fs::read(material.join(name)).unwrap(), bytes, "{name}"); diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index c269e9d5..bbf540f2 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -173,29 +173,32 @@ impl Headless { None => self.session.path.clone().ok_or_else(|| bad("the package has no file yet (new, or opened from another program): give a `path`"))?, }; - let destination = match &self.fs { - Filesystem::Workspace(workspace) => workspace.save_document_path(&path)?.to_string_lossy().into_owned(), - Filesystem::TrustedLocal => path.clone(), + let (destination, workspace_write) = match &self.fs { + Filesystem::Workspace(workspace) => { + let (destination, writer, save_path) = workspace.save_destination(&path)?; + (destination.to_string_lossy().into_owned(), Some((writer, save_path))) + } + Filesystem::TrustedLocal => (path.clone(), None), Filesystem::Denied => return Err(bad("file access is not granted")), }; let files = file_cmds::save_files_at(&self.session, &destination)?; let bytes = if file_cmds::is_mcraft(&path) { let bytes = files.zip().map_err(|error| bad(error.to_string()))?; - self.write(&path, &bytes)?; + if let Some((writer, save_path)) = &workspace_write { + writer.write(save_path, &bytes)?; + } else { + self.write(&path, &bytes)?; + } bytes.len() } else { - match &self.fs { - Filesystem::Denied => return Err(bad("file access is not granted")), - Filesystem::TrustedLocal => { - materialcraft_engine::formats::project::write_files(Path::new(&path), &files).map_err(|error| bad(error.to_string()))? - } - Filesystem::Workspace(workspace) => { - workspace.check_write(&path)?; - let parent = path.rsplit_once('/').map_or(String::new(), |(parent, _)| format!("{parent}/")); + match &workspace_write { + None => materialcraft_engine::formats::project::write_files(Path::new(&path), &files).map_err(|error| bad(error.to_string()))?, + Some((writer, save_path)) => { + let parent = save_path.rsplit_once('/').map_or(String::new(), |(parent, _)| format!("{parent}/")); for name in files.files.keys().filter(|name| *name != &files.entry) { - workspace.check_write(&format!("{parent}{name}"))?; + writer.check_write(&format!("{parent}{name}"))?; } - workspace.create_dir_all(&format!("{parent}resources"))?; + writer.create_dir_all(&format!("{parent}resources"))?; for (name, bytes) in &files.files { if name == &files.entry { continue; @@ -203,11 +206,11 @@ impl Headless { let target = format!("{parent}{name}"); if let Some((directory, _)) = target.rsplit_once('/') { - workspace.create_dir_all(directory)?; + writer.create_dir_all(directory)?; } - workspace.write_resource(&target, bytes.as_slice())?; + writer.write_resource(&target, bytes.as_slice())?; } - workspace.write(&path, files.xml().map_err(|error| bad(error.to_string()))?)?; + writer.write(save_path, files.xml().map_err(|error| bad(error.to_string()))?)?; } } files.xml().map_err(|error| bad(error.to_string()))?.len() @@ -254,7 +257,11 @@ impl Headless { } let gi = material_cmds::publish_graph(&self.session, p)?; - let bytes = material_cmds::material_bytes(&self.session, gi)?; + let bytes = if self.trusted() { + material_cmds::material_bytes(&self.session, gi)? + } else { + material_cmds::material_bytes_with_resource_limit(&self.session, gi, MAX_EXPORTED_MATERIAL_BYTES)? + }; if bytes.len() as u64 > MAX_EXPORTED_MATERIAL_BYTES { return Err(bad(format!("the material is {} bytes (limit {MAX_EXPORTED_MATERIAL_BYTES}); reduce source asset sizes", bytes.len()))); } diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 3a8882f0..f9821b82 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -272,9 +272,7 @@ mod tests { } /// 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); + fn workspace_session(base: &std::path::Path, write: bool) -> (std::path::PathBuf, std::path::PathBuf, Mutex) { let (inside, outside) = (base.join("inside"), base.join("outside")); std::fs::create_dir_all(&inside).unwrap(); std::fs::create_dir_all(&outside).unwrap(); @@ -289,24 +287,29 @@ mod tests { #[test] fn material_export_writes_a_portable_material_below_the_write_root() { - let (inside, _, h) = workspace_session("mat-ok", true); + let directory = tempfile::tempdir().unwrap(); + let (inside, _, h) = workspace_session(directory.path(), true); std::fs::create_dir(inside.join("out")).unwrap(); - let r = call(&h, "material.export", json!({"path": "out/brick"})).unwrap(); - assert_eq!(r["path"], "out/brick.mcmat"); + + let published = call(&h, "material.export", json!({"path": "out/brick"})).unwrap(); + + assert_eq!(published["path"], "out/brick.mcmat"); let bytes = std::fs::read(inside.join("out/brick.mcmat")).unwrap(); - assert_eq!(r["bytes"], bytes.len()); + assert_eq!(published["bytes"], bytes.len()); let (package, entry) = materialcraft_engine::formats::material::read_material(&bytes).unwrap(); assert!(package.graph(entry).unwrap().nodes.iter().any(|node| node.def == "output")); 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"})).unwrap(); - assert_eq!(r["path"], "again.MCMAT"); + + // Preserve the caller’s extension spelling when reopening the archive + let published = call(&h, "material.export", json!({"path": "again.MCMAT"})).unwrap(); + assert_eq!(published["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); + let directory = tempfile::tempdir().unwrap(); + let (inside, _, h) = workspace_session(directory.path(), 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}"); } @@ -319,7 +322,8 @@ mod tests { 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 directory = tempfile::tempdir().unwrap(); + let (inside, _, read_only) = workspace_session(directory.path(), 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); @@ -327,7 +331,8 @@ mod tests { #[test] fn material_export_cannot_escape_the_write_root() { - let (_inside, outside, h) = workspace_session("mat-escape", true); + let directory = tempfile::tempdir().unwrap(); + let (_inside, outside, h) = workspace_session(directory.path(), 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})); @@ -339,7 +344,8 @@ mod tests { assert!(call(&h, "material.export", json!({"path": "link/m.mcmat"})).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. + + // The generic command must enforce the same file access boundary let e = call(&h, "command.run", json!({"id": "file.exportMaterial", "params": {"path": abs}})).unwrap_err(); assert!(e.contains("disabled for automation"), "{e}"); } diff --git a/crates/automation/src/server/material_craft_mcp.rs b/crates/automation/src/server/material_craft_mcp.rs index 8b7e0260..387e02a0 100644 --- a/crates/automation/src/server/material_craft_mcp.rs +++ b/crates/automation/src/server/material_craft_mcp.rs @@ -299,21 +299,22 @@ mod tests { #[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 directory = tempfile::tempdir().unwrap(); + let write_root = directory.path().join("workspace"); + std::fs::create_dir(&write_root).unwrap(); let args = || Parameters(MaterialExportParams { path: "m".into(), graph: 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 ws = crate::AuthorizedWorkspace::new(None, Some(&write_root)).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()); + assert!(write_root.join("m.mcmat").is_file()); + let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None }); assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true)); - assert!(!base.parent().unwrap().join("m.mcmat").exists()); + assert!(!directory.path().join("m.mcmat").exists()); } /// Every sub-schema must be a JSON object. Claude Desktop's proxy rejects a boolean schema diff --git a/crates/automation/src/server/parameter/material_export_params.rs b/crates/automation/src/server/parameter/material_export_params.rs index 4e94b51a..8f156a07 100644 --- a/crates/automation/src/server/parameter/material_export_params.rs +++ b/crates/automation/src/server/parameter/material_export_params.rs @@ -4,6 +4,8 @@ use serde_json::Value; #[derive(Debug, Deserialize, Serialize, JsonSchema)] #[serde(deny_unknown_fields)] +// Some MCP clients reject boolean sub-schemas +#[schemars(extend("additionalProperties" = {"not": {}}))] pub struct MaterialExportParams { /// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The /// parent folder must exist @@ -19,11 +21,16 @@ mod tests { use serde_json::json; #[test] - fn material_publication_rejects_legacy_bake_size() { - for size in [json!(256), json!(null)] { - let error = serde_json::from_value::(json!({"path":"material", "size":size})).unwrap_err(); - assert!(error.to_string().contains("unknown field `size`")); + fn material_publication_rejects_bake_options() { + for (option, value) in [("size", json!(256)), ("size", json!(null)), ("values", json!({})), ("inputs", json!({})), ("preset", json!("Worn"))] { + let mut request = json!({"path":"material"}); + request[option] = value; + + let error = serde_json::from_value::(request).unwrap_err(); + + assert!(error.to_string().contains(&format!("unknown field `{option}`"))); } + let params = serde_json::from_value::(json!({"path":"material", "graph":"Materials/Oak"})).unwrap(); assert_eq!(params.graph, Some(json!("Materials/Oak"))); } diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 3ef95328..f3870e7a 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -36,21 +36,21 @@ impl AuthorizedWorkspace { Ok(self.read_path.as_ref().ok_or_else(|| denied("read"))?.join(relative_path(path)?)) } - /// Absolute destination identity for rebasing links; writes still use the capability. - pub(crate) fn save_document_path(&self, path: &str) -> Result { + /// Resolve a save once and keep its destination capability through serialization and writes. + pub(crate) fn save_destination(&self, path: &str) -> Result<(PathBuf, Self, String), AutomationError> { let relative = relative_path(path)?; let root = self.write.as_ref().ok_or_else(|| denied("write"))?; let parent = relative.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); - // A permitted directory symlink can change the number of parent traversals - // needed by saved links. Resolve it inside the same write capability. + + // Resolve directory symlinks inside the capability so rebased links use the correct depth let mut ancestor = parent; let mut suffix = PathBuf::new(); - let parent = loop { + let resolved_ancestor = loop { match root.canonicalize(ancestor) { - Ok(resolved) => break resolved.join(&suffix), + Ok(resolved) => break resolved, Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - // Preserve save-to-new-directory behavior without creating anything - // before serialization. Do not treat a dangling symlink as missing. + // Defer directory creation until after serialization + // Reject dangling symlinks match root.symlink_metadata(ancestor) { Err(missing) if missing.kind() == std::io::ErrorKind::NotFound => {} _ => return Err(file_error("resolve destination", path, error)), @@ -62,14 +62,24 @@ impl AuthorizedWorkspace { Err(error) => return Err(file_error("resolve destination", path, error)), } }; + let leaf = relative.file_name().ok_or_else(|| bad("missing destination filename"))?; - Ok(self.write_path.as_ref().ok_or_else(|| denied("write"))?.join(parent).join(leaf)) + let relative = suffix.join(leaf); + let save_path = relative.to_str().ok_or_else(|| bad("the save path must be UTF-8"))?.replace('\\', "/"); + let write_path = self.write_path.as_ref().ok_or_else(|| denied("write"))?.join(&resolved_ancestor); + + // Writes through this handle no longer traverse the original directory alias + let dir = root.open_dir(&resolved_ancestor).map_err(|error| file_error("resolve destination", path, error))?; + let destination = write_path.join(relative); + let workspace = Self { write: Some(Arc::new(dir)), write_path: Some(write_path), ..Self::default() }; + Ok((destination, workspace, save_path)) } pub(crate) fn read_dependency(&self, path: &str) -> Option> { if path.starts_with("sbs://") { return materialcraft_engine::formats::sbs::library::read(path).ok(); } + let relative = Path::new(path).strip_prefix(self.read_path.as_ref()?).ok()?; self.read(&relative.to_str()?.replace('\\', "/")).ok() } @@ -87,11 +97,13 @@ impl AuthorizedWorkspace { if metadata.len() > MAX_READ_BYTES { return Err(bad(format!("file too large: `{path}` is {} bytes (limit {MAX_READ_BYTES})", metadata.len()))); } + let mut bytes = Vec::new(); file.take(MAX_READ_BYTES + 1).read_to_end(&mut bytes).map_err(|e| file_error("read", path, e))?; if bytes.len() as u64 > MAX_READ_BYTES { return Err(bad(format!("file too large: `{path}` exceeds the {MAX_READ_BYTES}-byte limit"))); } + Ok(bytes) } @@ -103,17 +115,17 @@ impl AuthorizedWorkspace { let tmp = rel.with_file_name(format!(".{leaf}.{}.tmp", std::process::id())); let mut options = OpenOptions::new(); options.write(true).create_new(true); - let res = root - .open_with(&tmp, &options) - .and_then(|mut f| { - f.write_all(bytes)?; - f.sync_all() - }) - .and_then(|()| root.rename(&tmp, root, &rel)); - if let Err(e) = res { + + // Only the writer that acquired the staging file may remove it + let mut file = root.open_with(&tmp, &options).map_err(|error| file_error("write", path, error))?; + let written = file.write_all(bytes).and_then(|()| file.sync_all()); + drop(file); + + if let Err(error) = written.and_then(|()| root.rename(&tmp, root, &rel)) { let _ = root.remove_file(&tmp); - return Err(file_error("write", path, e)); + return Err(file_error("write", path, error)); } + Ok(()) } @@ -150,9 +162,7 @@ impl AuthorizedWorkspace { return Err(bad(format!("Resource filename collision: `{path}`"))); } - let mut existing = Vec::new(); - file.take(bytes.len() as u64 + 1).read_to_end(&mut existing).map_err(|error| file_error("read", path, error))?; - if existing != bytes { + if !resource_matches(file, bytes).map_err(|error| file_error("read", path, error))? { return Err(bad(format!("Resource filename collision: `{path}`"))); } } @@ -162,7 +172,28 @@ impl AuthorizedWorkspace { } } -// Keep capability-based resolution while preventing FIFO opens from waiting for a writer. +// A repeated save compares immutable assets without buffering a second copy +fn resource_matches(mut file: cap_std::fs::File, mut expected: &[u8]) -> std::io::Result { + const COMPARISON_BUFFER_BYTES: usize = 8 * 1024; + let mut buffer = [0; COMPARISON_BUFFER_BYTES]; + loop { + let count = match file.read(&mut buffer) { + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + result => result?, + }; + if count == 0 { + return Ok(expected.is_empty()); + } + + let Some(rest) = expected.strip_prefix(&buffer[..count]) else { + return Ok(false); + }; + + expected = rest; + } +} + +// Keep capability-based resolution while preventing FIFO opens from waiting for a writer fn regular_read_options() -> OpenOptions { let mut options = OpenOptions::new(); options.read(true); @@ -179,6 +210,7 @@ fn open_root(path: Option<&Path>, authority: &str) -> Result>, A if path.as_os_str().is_empty() { return Err(bad(format!("the automation {authority} root is empty"))); } + let dir = Dir::open_ambient_dir(path, ambient_authority()).map_err(|e| AutomationError::Io(format!("cannot open {authority} root `{}`: {e}", path.display())))?; Ok(Some(Arc::new(dir))) @@ -190,29 +222,36 @@ pub fn relative_path(raw: &str) -> Result { if raw.is_empty() { return Err(reject("empty")); } + if raw.contains('\\') { return Err(reject("backslash")); } + if raw.starts_with('/') { return Err(reject("absolute")); } + if raw.contains(':') { return Err(reject("drive, scheme or stream prefix")); } - for c in raw.split('/') { - if c.is_empty() || c == "." || c == ".." { + + for component in raw.split('/') { + if component.is_empty() || component == "." || component == ".." { return Err(reject("empty, `.` or `..` component")); } - if c.ends_with(['.', ' ']) || c.chars().any(char::is_control) { + + if component.ends_with(['.', ' ']) || component.chars().any(char::is_control) { return Err(reject("component ends in a dot or space, or has control characters")); } - let stem = c.split('.').next().unwrap_or(c).to_ascii_uppercase(); + + let stem = component.split('.').next().unwrap_or(component).to_ascii_uppercase(); let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$") || (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.ends_with(|ch: char| ch.is_ascii_digit())); if device { return Err(reject("reserved device name")); } } + Ok(PathBuf::from(raw)) } @@ -245,9 +284,7 @@ mod tests { use super::*; use serde_json::json; - fn roots(name: &str) -> (PathBuf, PathBuf, AuthorizedWorkspace) { - let base = std::env::temp_dir().join(format!("mc-ws-{}-{name}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); + fn roots(base: &Path) -> (PathBuf, PathBuf, AuthorizedWorkspace) { let (inside, outside) = (base.join("inside"), base.join("outside")); std::fs::create_dir_all(&inside).unwrap(); std::fs::create_dir_all(&outside).unwrap(); @@ -261,7 +298,8 @@ mod tests { use std::os::unix::fs::OpenOptionsExt; use std::time::Duration; for collision in [false, true] { - let (inside, _, ws) = roots(if collision { "fifo-collision" } else { "fifo-read" }); + let directory = tempfile::tempdir().unwrap(); + let (inside, _, ws) = roots(directory.path()); let path = inside.join("pipe"); assert!(std::process::Command::new("mkfifo").arg(&path).status().unwrap().success()); let (sender, receiver) = std::sync::mpsc::channel(); @@ -271,19 +309,20 @@ mod tests { }); let result = receiver.recv_timeout(Duration::from_secs(2)); if result.is_err() { - // Release the regression's blocked read before failing the test. + // Release the regression's blocked read before failing the test let writer = std::fs::OpenOptions::new().write(true).custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32).open(&path).unwrap(); drop(writer); } + worker.join().unwrap(); - std::fs::remove_dir_all(inside.parent().unwrap()).unwrap(); assert!(result.expect("FIFO open must not wait for a writer").is_err()); } } #[test] fn reads_and_writes_stay_in_the_root() { - let (inside, _, ws) = roots("valid"); + let directory = tempfile::tempdir().unwrap(); + let (inside, _, ws) = roots(directory.path()); std::fs::write(inside.join("a.txt"), b"canary").unwrap(); assert_eq!(ws.read("a.txt").unwrap(), b"canary"); ws.create_dir_all("out/deep").unwrap(); @@ -295,9 +334,39 @@ mod tests { assert!(ws.write("missing/c.txt", b"x").is_err(), "parent must exist"); } + #[test] + fn immutable_resources_compare_the_last_byte_of_a_partial_buffer() { + let directory = tempfile::tempdir().unwrap(); + let (inside, _, workspace) = roots(directory.path()); + let mut bytes = vec![17; 32 * 1024 + 1]; + workspace.write_resource("asset.bin", &bytes).unwrap(); + workspace.write_resource("asset.bin", &bytes).unwrap(); + + *bytes.last_mut().unwrap() = 42; + let collision = workspace.write_resource("asset.bin", &bytes).unwrap_err(); + + assert!(collision.to_string().contains("collision")); + assert_eq!(std::fs::read(inside.join("asset.bin")).unwrap().last(), Some(&17)); + } + + #[test] + fn a_busy_save_preserves_the_existing_staging_file() { + let directory = tempfile::tempdir().unwrap(); + let (inside, _, workspace) = roots(directory.path()); + let staging = inside.join(format!(".scene.sbs.{}.tmp", std::process::id())); + std::fs::write(&staging, b"pending save").unwrap(); + + let result = workspace.write("scene.sbs", b"second save"); + + assert!(result.is_err()); + assert_eq!(std::fs::read(staging).unwrap(), b"pending save"); + assert!(!inside.join("scene.sbs").exists()); + } + #[test] fn escapes_and_malformed_paths_are_rejected() { - let (_, outside, ws) = roots("reject"); + let directory = tempfile::tempdir().unwrap(); + let (_, outside, ws) = roots(directory.path()); let abs = outside.join("x.txt").display().to_string(); for p in ["", "/abs", "../x", "a/../../x", "a\\b", "C:/x", "a//b", "./a", "a:b", "NUL", "con.txt", "x/COM1.log", "dot.", abs.as_str()] { assert!(ws.read(p).is_err(), "read accepted {p:?}"); @@ -308,7 +377,8 @@ mod tests { #[test] fn authorities_are_separate_and_fail_closed() { - let (inside, _, _) = roots("separate"); + let directory = tempfile::tempdir().unwrap(); + let (inside, _, _) = roots(directory.path()); std::fs::write(inside.join("r.txt"), b"r").unwrap(); let ro = AuthorizedWorkspace::new(Some(&inside), None).unwrap(); assert!(ro.read("r.txt").is_ok()); @@ -320,7 +390,8 @@ mod tests { #[cfg(unix)] #[test] fn oversized_reads_are_rejected_without_allocating() { - let (inside, _, ws) = roots("oversized"); + let directory = tempfile::tempdir().unwrap(); + let (inside, _, ws) = roots(directory.path()); let file = std::fs::File::create(inside.join("huge.bin")).unwrap(); file.set_len(MAX_READ_BYTES + 1).unwrap(); let err = ws.read("huge.bin").unwrap_err().to_string(); @@ -330,7 +401,8 @@ mod tests { #[cfg(unix)] #[test] fn symlink_escape_is_rejected() { - let (inside, outside, ws) = roots("symlink"); + let directory = tempfile::tempdir().unwrap(); + let (inside, outside, ws) = roots(directory.path()); std::fs::write(outside.join("secret.txt"), b"s").unwrap(); std::os::unix::fs::symlink(&outside, inside.join("link")).unwrap(); assert!(ws.read("link/secret.txt").is_err()); @@ -338,10 +410,37 @@ mod tests { assert!(!outside.join("new.txt").exists()); } + #[cfg(unix)] + #[test] + fn save_keeps_the_resolved_destination_when_an_alias_is_retargeted() { + use std::os::unix::fs::symlink; + + let directory = tempfile::tempdir().unwrap(); + let (inside, _, workspace) = roots(directory.path()); + std::fs::create_dir(inside.join("original")).unwrap(); + std::fs::create_dir_all(inside.join("alternate/deep")).unwrap(); + let alias = inside.join("alias"); + symlink("original", &alias).unwrap(); + let (destination, writer, save_path) = workspace.save_destination("alias/scene.sbs").unwrap(); + + std::fs::remove_file(&alias).unwrap(); + symlink("alternate/deep", &alias).unwrap(); + let parent = save_path.rsplit_once('/').map_or(String::new(), |(parent, _)| format!("{parent}/")); + writer.create_dir_all(&format!("{parent}resources")).unwrap(); + writer.write_resource(&format!("{parent}resources/asset.bin"), b"asset").unwrap(); + writer.write(&save_path, b"source").unwrap(); + + assert_eq!(destination, inside.join("original/scene.sbs")); + assert_eq!(std::fs::read(destination).unwrap(), b"source"); + assert_eq!(std::fs::read(inside.join("original/resources/asset.bin")).unwrap(), b"asset"); + assert_eq!(std::fs::read_dir(inside.join("alternate/deep")).unwrap().count(), 0); + } + #[cfg(windows)] #[test] fn junction_escape_is_rejected() { - let (inside, outside, ws) = roots("junction"); + let directory = tempfile::tempdir().unwrap(); + let (inside, outside, ws) = roots(directory.path()); std::fs::write(outside.join("secret.txt"), b"s").unwrap(); let link = inside.join("junction"); let made = std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).output(); @@ -349,6 +448,7 @@ mod tests { eprintln!("skipping: cannot create a junction"); return; } + assert!(ws.read("junction/secret.txt").is_err()); assert!(ws.write("junction/new.txt", b"x").is_err()); assert!(!outside.join("new.txt").exists()); diff --git a/crates/automation/tests/package_files.rs b/crates/automation/tests/package_files.rs index f3a4a37e..5e421fdf 100644 --- a/crates/automation/tests/package_files.rs +++ b/crates/automation/tests/package_files.rs @@ -87,19 +87,31 @@ fn both_formats_save_and_reopen_using_separate_workspace_capabilities() { #[test] fn scoped_publication_resolves_linked_graphs_and_images_using_the_granted_read_root() { - use materialcraft_engine::core::{Graph, GraphInstance, GraphPort, Value}; - use materialcraft_engine::{formats, samples}; - let temporary = tempfile::tempdir().unwrap(); - let dir = temporary.path().to_path_buf(); + use materialcraft_engine::core::{Graph, GraphInstance, GraphPort, Resource, ResourceBytes, Value}; + use materialcraft_engine::{formats, image}; + + let directory = tempfile::tempdir().unwrap(); + let dir = directory.path(); let input = dir.join("input"); let output = dir.join("published"); std::fs::create_dir_all(input.join("parts")).unwrap(); std::fs::create_dir_all(&output).unwrap(); + + let image = image::Image::filled(2, 2, image::Kind::Color, [0.25, 0.5, 0.75, 1.0]); + let pixels = formats::encode(&image, "png", formats::Depth::U8, false).unwrap(); let mut helpers = Package::new("Helpers"); - helpers.graphs.push(samples::template("pbr", "Finish", 4).unwrap()); - let helper = formats::sbs::write_sbs(&helpers).unwrap(); - std::fs::write(input.join("parts/finish.sbs"), &helper).unwrap(); - std::fs::write(dir.join("outside.sbs"), &helper).unwrap(); + helpers.resources.push(Resource::new("finish", "finish.png", ResourceBytes::new(pixels.clone()))); + let mut finish = Graph::new("Finish"); + let bitmap = finish.add_node("bitmap", [0.0; 2]); + finish.node_mut(bitmap).unwrap().params.insert("resource".into(), Value::Text("finish".into())); + let finish_output = finish.add_node("output", [0.0; 2]); + finish.node_mut(finish_output).unwrap().params.insert("identifier".into(), Value::Text("basecolor".into())); + finish.connect(bitmap, "output", finish_output, "input").unwrap(); + helpers.graphs.push(finish); + let helper = formats::project::ProjectFiles::build(&helpers, "finish.sbs", false).unwrap(); + formats::project::write_files(&input.join("parts/finish.sbs"), &helper).unwrap(); + std::fs::write(dir.join("outside.sbs"), helper.xml().unwrap()).unwrap(); + for (project, dependency) in [("surface.sbs", "parts/finish.sbs"), ("missing.sbs", "../outside.sbs")] { let mut graph = Graph::new("Oak"); let call = graph.add_node("graph_instance", [0.; 2]); @@ -124,21 +136,22 @@ fn scoped_publication_resolves_linked_graphs_and_images_using_the_granted_read_r if project == "surface.sbs" { assert!(result.is_ok(), "{result:?}"); let (pkg, entry) = formats::material::read_material(&std::fs::read(output.join("surface.sbs.mcmat")).unwrap()).unwrap(); - assert_eq!(pkg.graph(entry).unwrap().name, "Oak"); + let entry = pkg.graph(entry).unwrap(); + assert_eq!(entry.name, "Oak"); assert_eq!(pkg.graphs.len(), 2); - assert!(pkg.graphs.iter().any(|graph| graph.name == "Finish")); - let calls: Vec<_> = pkg.graph(entry).unwrap().instances().collect(); - assert_eq!(calls.len(), 1); - assert!(calls[0].package.is_empty()); - assert!(pkg.graph_by_name(&calls[0].graph).is_some()); + let instance = entry.instances().next().unwrap(); + assert!(instance.package.is_empty()); + assert_eq!(entry.instances().count(), 1); + assert_eq!(pkg.graph_by_name(&instance.graph).unwrap().1.name, "Finish"); + assert_eq!(pkg.resources.len(), 1); + assert_eq!(pkg.resources[0].bytes.as_slice(), pixels); - // Saving under a different granted root rebases links from that actual - // destination, not from the process working directory or a relative path. + // Rebase links from the actual destination under the granted write root app.save(Some("saved.sbs")).unwrap(); let xml = std::fs::read_to_string(output.join("saved.sbs")).unwrap(); assert!(xml.contains("../input/parts/finish.sbs"), "{xml}"); assert_eq!(app.session.path.as_deref(), Some("saved.sbs")); - let workspace = AuthorizedWorkspace::new(Some(&dir), Some(&output)).unwrap(); + let workspace = AuthorizedWorkspace::new(Some(dir), Some(&output)).unwrap(); let mut reopened = Headless::new(Session::new(Package::new("Empty")), Filesystem::Workspace(workspace)); reopened.load("published/saved.sbs").unwrap(); let helper_path = input.join("parts/finish.sbs").canonicalize().unwrap().to_string_lossy().into_owned(); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4bae65a5..c74174fb 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -24,3 +24,6 @@ thiserror = { workspace = true } [target.'cfg(unix)'.dependencies] rustix.workspace = true + +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +tempfile = "3" diff --git a/crates/engine/src/export_request.rs b/crates/engine/src/export_request.rs index 1057559d..a46356d1 100644 --- a/crates/engine/src/export_request.rs +++ b/crates/engine/src/export_request.rs @@ -36,8 +36,7 @@ impl ExportRequest { /// Read `file.export` params, checking them against the session's package pub fn from_params(s: &Session, p: &J) -> Result { - // Keep file.export's historical numeric selector coercion (including JSON 1.0) - // while allowing the new exact SBS path selector without changing other commands. + // Preserve historical numeric selectors alongside exact SBS paths let graph_index = if p.get("graph").is_some_and(J::is_number) { u64p(p, "graph").and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(CMD, "`graph` must be a nonnegative index"))? } else { @@ -50,12 +49,14 @@ impl ExportRequest { return Err(bad(CMD, format!("unknown format `{format}`"))); } - let depth = match u64p(p, "depth") { - None => None, - Some(8) => Some(Depth::U8), - Some(16) => Some(Depth::U16), - Some(32) => Some(Depth::F32), - Some(depth) => return Err(bad(CMD, format!("depth must be 8, 16 or 32, not {depth}"))), + let depth = match p.get("depth") { + None | Some(J::Null) => None, + Some(value) => Some(match value.as_f64() { + Some(8.0) => Depth::U8, + Some(16.0) => Depth::U16, + Some(32.0) => Depth::F32, + _ => return Err(bad(CMD, format!("depth must be 8, 16 or 32, not {value}"))), + }), }; let identifiers = output_identifiers(graph); @@ -70,7 +71,7 @@ impl ExportRequest { format, pattern: strp(p, "pattern").unwrap_or("$(graph)_$(identifier)").to_string(), depth, - size: export_size(p.get("size"))?, + size: export_size(CMD, p.get("size"))?, outputs, color_spaces: color_spaces(p.get("colorSpaces"), &identifiers, &graph.name)?, }) @@ -127,7 +128,7 @@ fn known_output<'a>(identifier: &'a str, identifiers: &[String], graph: &str) -> } /// `size`: the larger side in pixels (0 = the graph's size) or `[width, height]` -pub(crate) fn export_size(value: Option<&J>) -> Result> { +pub(crate) fn export_size(command: &str, value: Option<&J>) -> Result> { let pixels = |value: &J| value.as_u64().or_else(|| value.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64)); let clamp = |pixels: u64| pixels.min(u64::from(u32::MAX)) as u32; @@ -136,14 +137,14 @@ pub(crate) fn export_size(value: Option<&J>) -> Result> { Some(J::Array(sides)) => match sides.as_slice() { [width, height] => match (pixels(width), pixels(height)) { (Some(width), Some(height)) => Ok(Some(ExportSize::Exact([clamp(width), clamp(height)]))), - _ => Err(bad(CMD, "`size` [width, height] takes two pixel counts")), + _ => Err(bad(command, "`size` [width, height] takes two pixel counts")), }, - _ => Err(bad(CMD, "`size` [width, height] takes two pixel counts")), + _ => Err(bad(command, "`size` [width, height] takes two pixel counts")), }, Some(value) => match pixels(value) { Some(0) => Ok(None), Some(side) => Ok(Some(ExportSize::LargerSide(clamp(side)))), - None => Err(bad(CMD, "`size` is a pixel count or [width, height]")), + None => Err(bad(command, "`size` is a pixel count or [width, height]")), }, } } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index a6f4fd0a..f2aba872 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -344,8 +344,8 @@ pub(crate) fn encode_outputs(graph: &materialcraft_core::Graph, cooked: &materia let node = graph.node(id)?; let output_format = if node.base.format == materialcraft_core::OutputFormat::Inherit { graph.format } else { node.base.format }; let depth = request.depth.unwrap_or_else(|| Depth::from_format(output_format)); - // Grayscale floating-point exports historically stored scene-linear samples, even - // for color usages. Keep that default; an explicit color-space choice still wins. + + // Keep grayscale float exports scene-linear unless the caller picks a color space let srgb = request.color_space(&identifier, usage).encodes_srgb() && !(image.kind() == craft_texture::Kind::Gray && matches!(request.format.as_str(), "exr" | "hdr") diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 11f0da2a..b6751f3a 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -2,7 +2,7 @@ use serde_json::{Value as J, json}; -use materialcraft_core::{MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value}; +use materialcraft_core::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value}; use crate::commands::{CommandSpec, always, bad, boolp, has_graph, has_selection, i64p, ids_param, strp, u64p}; use crate::{Result, Session, cmd}; @@ -235,16 +235,19 @@ fn preset_apply(s: &mut Session, p: &J) -> Result { s.edit("Apply preset", |s| { let g = s.graph_mut()?; let preset = g.presets.iter().find(|x| x.name == name).cloned().ok_or_else(|| bad("graph.preset.apply", format!("no preset `{name}`")))?; - for (k, v) in preset.values { - // Only inputs that still exist, with their current type - if g.exposed.iter().any(|e| e.id == k && e.default.type_name() == v.type_name()) { - g.inputs.insert(k, v); + for (identifier, value) in preset.values { + if preset_value_matches(g, &identifier, &value) { + g.inputs.insert(identifier, value); } } Ok(J::Null) }) } +pub(crate) fn preset_value_matches(graph: &Graph, identifier: &str, value: &Value) -> bool { + graph.exposed.iter().any(|input| input.id == identifier && input.default.type_name() == value.type_name()) +} + fn preset_delete(s: &mut Session, p: &J) -> Result { let name = preset_name(p, "graph.preset.delete")?; s.edit("Delete preset", |s| { diff --git a/crates/engine/src/linked_files.rs b/crates/engine/src/linked_files.rs index eec64691..957e927b 100644 --- a/crates/engine/src/linked_files.rs +++ b/crates/engine/src/linked_files.rs @@ -60,6 +60,7 @@ pub(crate) fn load_scoped(package: &mut Package, read: &dyn Fn(&str) -> Option Result crate::file_cmds::read_package_bytes(&bytes, path, &crate::file_cmds::linked_files(path)).map_err(|error| error.to_string()) } +const MAX_DEPENDENCY_READS: usize = 4096; + fn resolve(package: &mut Package, mut pending: Vec, read: &dyn Fn(&str) -> Result) -> Vec { use std::{collections::BTreeSet, sync::Arc}; + let mut visited = BTreeSet::new(); let mut warnings = Vec::new(); - let mut reads = 0; + let mut read_attempts = 0; while let Some(path) = pending.pop() { if !visited.insert(path.clone()) { continue; @@ -93,13 +97,13 @@ fn resolve(package: &mut Package, mut pending: Vec, read: &dyn Fn(&str) continue; } - // Cached snapshots need traversal, but must not consume the new-read budget. - // Count failed attempts too; visited still prevents repeated reads and cycles. - if reads >= 4096 { - warnings.push("linked material exceeds the package dependency limit".into()); + // Cached snapshots only need traversal, while failed reads still spend the allowance + if read_attempts == MAX_DEPENDENCY_READS { + warnings.push("linked material exceeds the package dependency read limit".into()); break; } - reads += 1; + + read_attempts += 1; match read(&path) { Ok(read) => { warnings.extend(read.warnings); @@ -127,7 +131,7 @@ mod tests { for cached_first in [true, false] { let mut package = Package::new("root"); let mut pending = vec!["new".to_string()]; - for i in 0..4096 { + for i in 0..MAX_DEPENDENCY_READS { let name = format!("cached{i}"); package.dependencies.insert(name.clone(), Arc::new(Package::new(&name))); pending.push(name); @@ -150,12 +154,12 @@ mod tests { #[test] fn failed_new_reads_still_spend_the_budget_and_duplicates_do_not() { let calls = Cell::new(0); - let pending = (0..4097).flat_map(|i| [format!("missing{i}"), format!("missing{i}")]).collect(); + let pending = (0..=MAX_DEPENDENCY_READS).flat_map(|i| [format!("missing{i}"), format!("missing{i}")]).collect(); let warnings = resolve(&mut Package::new("root"), pending, &|_| { calls.set(calls.get() + 1); Err("missing".into()) }); - assert_eq!(calls.get(), 4096); - assert!(warnings.last().unwrap().contains("dependency limit")); + assert_eq!(calls.get(), MAX_DEPENDENCY_READS); + assert!(warnings.last().unwrap().contains("dependency read limit")); } } diff --git a/crates/engine/src/linked_resource.rs b/crates/engine/src/linked_resource.rs index 90eb149f..465f27a3 100644 --- a/crates/engine/src/linked_resource.rs +++ b/crates/engine/src/linked_resource.rs @@ -13,7 +13,8 @@ pub(crate) fn read_regular(path: &std::path::Path) -> std::io::Result> { #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; - // A named pipe must reach the regular-file check without waiting for a writer. + + // A named pipe must reach the regular-file check without waiting for a writer open.custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32); } let file = open.open(path)?; @@ -22,13 +23,16 @@ pub(crate) fn read_regular(path: &std::path::Path) -> std::io::Result> { if !metadata.is_file() || metadata.len() > MAX_LINKED_RESOURCE_BYTES { return Err(invalid()); } + let mut data = Vec::new(); file.take(MAX_LINKED_RESOURCE_BYTES + 1).read_to_end(&mut data)?; if data.len() as u64 > MAX_LINKED_RESOURCE_BYTES { return Err(invalid()); } + Ok(data) } + /// Read resource paths relative to an SBS package, including portable library aliases. pub fn reader(path: &str) -> impl Fn(&str) -> Option> + use<> { let owner = path.to_string(); diff --git a/crates/engine/src/material_bake.rs b/crates/engine/src/material_bake.rs index 0ce88625..9349a5fd 100644 --- a/crates/engine/src/material_bake.rs +++ b/crates/engine/src/material_bake.rs @@ -68,10 +68,12 @@ pub(crate) fn check_publish(s: &Session, index: usize) -> Result<()> { if graph.function.is_some() { return Err(bad("file.exportMaterial", "select a material graph")); } + let cooked = MaterialOptions::default().cook(s, index, None, Some(1 << materialcraft_core::MIN_SIZE_LOG2))?; if !outputs(graph, &cooked).into_iter().any(|(id, _, _, image)| image.is_some() && graph.connections.iter().any(|wire| wire.to == id)) { return Err(bad("file.exportMaterial", format!("graph `{}` has no connected, cookable material outputs", graph.sbs_path()))); } + Ok(()) } @@ -88,45 +90,48 @@ pub fn cook(s: &Session, p: &J, read: impl Fn(&str) -> Result>) -> Resul /// Encode every file before the caller writes to its destination. Paths in the report are relative. pub fn export(s: &Session, p: &J, read: impl Fn(&str) -> Result>) -> Result<(Vec, J)> { + let option = |key| p.get(key).filter(|value| !value.is_null()); let request = ExportRequest::from_params(s, p)?; - let has = |key| p.get(key).is_some_and(|value| !value.is_null()); - if has("profile") { - if has("format") || has("pattern") { - return Err(bad("file.export", "named profiles choose their own format and filenames; omit format and pattern")); - } - } else if has("normalFormat") || has("displacementScale") { - return Err(bad("file.export", "normalFormat and displacementScale require an explicit export profile")); - } - let graph = s.pkg.graph(request.graph)?; - let options = MaterialOptions::from_params(graph, p, read)?; let selected = request.outputs.as_deref(); - let materialx = match p.get("profile").filter(|value| !value.is_null()) { + let materialx = match option("profile") { Some(value) if value == "materialx" => true, Some(value) if value == "maps" => false, Some(value) => return Err(bad("file.export", format!("unknown export profile {value}"))), None => { + if option("normalFormat").is_some() || option("displacementScale").is_some() { + return Err(bad("file.export", "normalFormat and displacementScale require an explicit export profile")); + } + + let options = MaterialOptions::from_params(graph, p, read)?; let cooked = options.cook(s, request.graph, selected, None)?; return Ok((crate::file_cmds::encode_outputs(graph, &cooked, &request)?, json!({}))); } }; - let scale = match p.get("displacementScale").filter(|value| !value.is_null()) { + if option("format").is_some() || option("pattern").is_some() { + return Err(bad("file.export", "named profiles choose their own format and filenames; omit format and pattern")); + } + + let scale = match option("displacementScale") { + Some(_) if !materialx => return Err(bad("file.export", "`displacementScale` requires the materialx profile")), Some(value) => { value.as_f64().map(|x| x as f32).filter(|x| x.is_finite() && *x >= 0.0).ok_or_else(|| bad("file.export", "invalid displacementScale"))? } None => 1.0, }; - let normal_y_down = match p.get("normalFormat").filter(|value| !value.is_null()) { + let normal_y_down = match option("normalFormat") { None => None, Some(value) if value == "opengl" => Some(false), Some(value) if value == "directx" => Some(true), Some(_) => return Err(bad("file.export", "normalFormat must be opengl or directx")), }; + let options = MaterialOptions::from_params(graph, p, read)?; let cooked = options.cook(s, request.graph, selected, None)?; let (files, mut report) = encode_maps(graph, &cooked, &request, materialx, scale, normal_y_down)?; - // Use the graph already selected by file.export, including its legacy numeric coercion. + + // Report the same graph selected by the legacy numeric coercion let mut interface = info(s, &json!({"graph": request.graph}))?; if let Some(params) = interface["parameters"].as_array_mut() { for parameter in params { @@ -197,6 +202,7 @@ fn encode_maps( let mut shader_inputs = BTreeSet::new(); for (id, usage, identifier, image) in outputs(graph, cooked) { let Some(image) = image.filter(|_| request.includes(&identifier) && !index.incoming(id).is_empty()) else { continue }; + let shader = shader_input(usage); let color = materialcraft_formats::material::srgb_usage(usage); let space = request.color_space(&identifier, usage); @@ -222,6 +228,7 @@ fn encode_maps( if float && request.color_spaces.get(&identifier).is_some_and(|space| space.encodes_srgb()) { return Err(bad("file.export", format!("EXR output `{identifier}` requires linear values; omit the sRGB override or select raw or linear"))); } + let (ext, depth) = if float { ("exr", Depth::F32) } else { @@ -236,7 +243,7 @@ fn encode_maps( let srgb = !float && space.encodes_srgb(); let bytes = encode(image, ext, depth, srgb)?; let file = if materialx { - // An interrupted re-export must leave every texture referenced by the previous document intact + // Keep every texture referenced by the last complete document until the new write succeeds const MAX_STEM_CHARS: usize = 32; let digest = Sha256::new().chain_update(stem.as_bytes()).chain_update([0]).chain_update(&bytes).finalize(); let prefix: String = stem.chars().take(MAX_STEM_CHARS).collect(); diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index 248ca69d..ec031d66 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -45,10 +45,17 @@ pub fn material_bytes(session: &Session, graph: usize) -> Result> { Ok(materialcraft_formats::material::write_material(&session.pkg, graph)?) } +/// Publish with an additional budget for the combined uncompressed source assets. +pub fn material_bytes_with_resource_limit(session: &Session, graph: usize, maximum_resource_bytes: u64) -> Result> { + crate::material_bake::check_publish(session, graph)?; + Ok(materialcraft_formats::material::write_material_with_resource_limit(&session.pkg, graph, maximum_resource_bytes)?) +} + pub fn publish_graph(s: &Session, p: &J) -> Result { if ["size", "values", "inputs", "preset"].iter().any(|key| p.get(key).is_some_and(|v| !v.is_null())) { return Err(bad("file.exportMaterial", "pass size, values, preset and image inputs when cooking or exporting outputs")); } + crate::graph_cmds::graph_index(s, p) } diff --git a/crates/engine/src/material_cmds.test.rs b/crates/engine/src/material_cmds.test.rs index 3065c8e4..5f27fc15 100644 --- a/crates/engine/src/material_cmds.test.rs +++ b/crates/engine/src/material_cmds.test.rs @@ -87,6 +87,7 @@ fn published_entry_cooks_independently_with_values_sizes_and_image_inputs() { let (original, _) = bake(&source); let (packed, report) = bake(&opened); assert_eq!(original.len(), 4); + assert_eq!(packed.len(), original.len()); assert_eq!(report["maps"][0]["size"], json!([size, size / 2])); for (a, b) in original.iter().zip(&packed) { assert_eq!(a.file, b.file); @@ -107,10 +108,8 @@ fn published_entry_cooks_independently_with_values_sizes_and_image_inputs() { assert!( material_bake::cook(&opened, &json!({"values":{"missing":0}}), |path| Err(crate::EngineError::Other(format!("unexpected file read: {path}")))).is_err() ); - assert!( - material_bake::cook(&opened, &json!({"inputs":{"missing":"x"}}), |path| Err(crate::EngineError::Other(format!("unexpected file read: {path}")))) - .is_err() - ); + let error = material_bake::cook(&opened, &json!({"inputs":{"missing":"x"}}), |path| panic!("unexpected file read: {path}")).unwrap_err(); + assert!(error.to_string().contains("unknown image input `missing`")); } #[test] @@ -138,7 +137,8 @@ fn preset_values_apply_before_explicit_overrides() { #[test] fn publishing_sbs_and_project_archives_survives_removing_the_entire_source_tree() { - let dir = std::env::temp_dir().join(format!("materialcraft-source-closure-{}", std::process::id())); + let directory = tempfile::tempdir().unwrap(); + let dir = directory.path(); let authored = dir.join("authored"); std::fs::create_dir_all(&authored).unwrap(); let source = fixture(); @@ -149,7 +149,8 @@ fn publishing_sbs_and_project_archives_survives_removing_the_entire_source_tree( } for ext in ["sbs", "mcraft"] { let path = authored.join(format!("studio.{ext}")); - // Save the independent project beside its library packages and their original bitmaps. + + // Save the independent project beside its library packages and their original bitmaps let files = materialcraft_formats::project::ProjectFiles::build(&source.pkg, &format!("studio.{ext}"), ext == "mcraft").unwrap(); if ext == "mcraft" { std::fs::write(&path, files.zip().unwrap()).unwrap(); @@ -175,7 +176,6 @@ fn publishing_sbs_and_project_archives_survives_removing_the_entire_source_tree( }; assert_eq!(bake(&source), bake(&viewer)); } - std::fs::remove_dir_all(dir).unwrap(); } #[test] @@ -337,6 +337,35 @@ fn an_openpbr_scalar_rejects_an_unrepresentable_srgb_override() { assert!(result.err().is_some_and(|error| error.to_string().contains("linear"))); } +#[test] +fn explicit_srgb_is_rejected_when_the_profile_requires_float_textures() { + let session = export_fixture("uniform", &[], "baseColor"); + let automatic = json!({"profile":"materialx","depth":32}); + let explicit_srgb = json!({"profile":"materialx","depth":32,"colorSpaces":{"result":"srgb"}}); + + let (_, report) = material_bake::export(&session, &automatic, material_bake::read_input).unwrap(); + let error = material_bake::export(&session, &explicit_srgb, material_bake::read_input).err().expect("an explicit sRGB override cannot produce linear EXR"); + + assert_eq!(report["maps"][0]["colorSpace"], "linear"); + assert!(report["maps"][0]["file"].as_str().unwrap().ends_with(".exr")); + assert!(error.to_string().contains("requires linear values")); +} + +#[test] +fn profile_controls_fail_when_the_requested_export_cannot_apply_them() { + let session = export_fixture("uniform", &[], "baseColor"); + + for (params, option) in [ + (json!({"profile":"maps","displacementScale":2}), "displacementScale"), + (json!({"profile":"maps","depth":8.4}), "depth"), + (json!({"profile":"maps","depth":"mistyped"}), "depth"), + ] { + let error = material_bake::export(&session, ¶ms, material_bake::read_input).err().expect("an unused option must be rejected"); + + assert!(error.to_string().contains(option), "{error}"); + } +} + #[test] fn legacy_grayscale_float_exports_keep_linear_defaults_and_explicit_overrides() { let session = export_fixture("uniform", &[("color", Value::Color([0.25; 4])), ("color_mode", Value::Bool(false))], "baseColor"); @@ -388,7 +417,7 @@ fn published_disabled_and_typed_instance_cooks_match_source() { let bytes = materialcraft_formats::material::write_material(&package, 0).unwrap(); let (opened, entry) = materialcraft_formats::material::read_material(&bytes).unwrap(); let cook = |pkg: Package, entry| { - // Cook the decoded package directly: Session::new refreshes interfaces and could mask a serialization defect. + // Cook without Session::new because it can reconstruct a missing interface let options = materialcraft_eval::Options::new(&|_| None); let cache = std::sync::Mutex::new(materialcraft_eval::Cache::default()); let cooked = materialcraft_eval::cook(&pkg, entry, &options, &cache); @@ -431,7 +460,7 @@ fn material_options_size_errors_name_the_material_command() { let error = MaterialOptions::from_params(session.graph().unwrap(), ¶meters, |_| Err(crate::EngineError::Other("unexpected image read".into()))).unwrap_err(); assert!(matches!(error, crate::EngineError::BadParams { cmd, msg } if cmd == "material.cook" && msg.contains("size"))); - let error = crate::export_request::export_size(parameters.get("size")).unwrap_err(); + let error = crate::export_request::export_size("file.export", parameters.get("size")).unwrap_err(); assert!(matches!(error, crate::EngineError::BadParams { cmd, msg } if cmd == "file.export" && msg.contains("size"))); } diff --git a/crates/engine/src/material_options.rs b/crates/engine/src/material_options.rs index 493a7a73..1b3d8c4c 100644 --- a/crates/engine/src/material_options.rs +++ b/crates/engine/src/material_options.rs @@ -18,21 +18,16 @@ pub struct MaterialOptions { impl MaterialOptions { pub fn from_params(graph: &Graph, p: &J, read: impl Fn(&str) -> Result>) -> Result { let invalid = |msg| bad("material.cook", msg); - let size = crate::export_request::export_size(p.get("size")).map_err(|error| match error { - crate::EngineError::BadParams { msg, .. } => invalid(msg), - other => other, - })?; - let mut options = Self { size, ..Default::default() }; + let mut options = Self { size: crate::export_request::export_size("material.cook", p.get("size"))?, ..Default::default() }; if let Some(value) = p.get("preset").filter(|v| !v.is_null()) { let name = value.as_str().ok_or_else(|| invalid("preset must be a name".into()))?; let preset = graph.presets.iter().find(|preset| preset.name == name).ok_or_else(|| invalid(format!("unknown preset `{name}`")))?; - // Match preset.apply: stale identifiers and changed parameter types are ignored. options.values.extend( preset .values .iter() - .filter(|(id, value)| graph.exposed.iter().any(|parameter| parameter.id == **id && parameter.default.type_name() == value.type_name())) + .filter(|(id, value)| crate::graph_cmds::preset_value_matches(graph, id, value)) .map(|(id, value)| (id.clone(), value.clone())), ); } diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index 1013b2e1..5ad60d26 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -1,7 +1,7 @@ use crate::{Cache, Cooked, Options, now_ms}; use crate::{node_execution::cook_node, prepared_graph::PreparedGraph}; use craft_texture::Image; -use materialcraft_core::{Package, Value}; +use materialcraft_core::{Graph, Node, Package, Value}; use std::{ collections::BTreeMap, sync::{Mutex, atomic::Ordering}, @@ -12,23 +12,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu let mut cooked = Cooked::default(); let Some(graph) = package.graphs.get(graph_index) else { return cooked }; - // Input nodes show their bound preview images; the caller's images win - let bound; - let options = if !graph.input_images.is_empty() { - let mut inputs: BTreeMap = graph - .input_images - .iter() - .filter_map(|(id, resource)| { - Some((id.clone(), (options.resource)(&craft_texture::resource_key(resource, graph.input_images_linear.contains(id)))?)) - }) - .collect(); - inputs.extend(options.inputs.iter().map(|(name, value)| (name.clone(), value.clone()))); - bound = Options { only: options.only.clone(), inputs, overrides: options.overrides.clone(), graph_stack: options.graph_stack.clone(), ..*options }; - &bound - } else { - options - }; - + let mut previews = BTreeMap::new(); let prepared = PreparedGraph::new(package, graph, options); // Exposed parameter values: the graph's own, then the caller's overrides @@ -50,9 +34,28 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu let Some(node) = prepared.index.node(id) else { continue }; - let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, cache); + let input = input_image(graph, node, options, &mut previews); + let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, input, cache); cooked.nodes.insert(id, result); } + cooked.ms = (now_ms() - started_ms) as f32; cooked } + +fn input_image<'a>(graph: &Graph, node: &Node, options: &'a Options<'_>, previews: &'a mut BTreeMap>) -> Option<&'a Image> { + if !node.def.starts_with("input_") { + return None; + } + + let identifier = crate::identifier(node); + if let Some(image) = options.inputs.get(&identifier) { + return Some(image); + } + + let resource = graph.input_images.get(&identifier)?; + let linear = graph.input_images_linear.contains(&identifier); + + // Nodes sharing an input also share its first lookup, including a missing preview + previews.entry(identifier).or_insert_with(|| (options.resource)(&craft_texture::resource_key(resource, linear))).as_ref() +} diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index faa29641..2ffeb294 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -32,6 +32,7 @@ pub(crate) fn cook_node( cooked: &Cooked, graph_variables: &BTreeMap, options: &Options, + input_image: Option<&Image>, cache: &Mutex, ) -> NodeResult { let (input_ports, output_ports) = prepared.ports(node.id); @@ -129,8 +130,6 @@ pub(crate) fn cook_node( let tile = base.tiling[0] && base.tiling[1]; - // Input nodes read the caller's image for their identifier - let input_image = node.def.starts_with("input_").then(|| options.inputs.get(&identifier(node))).flatten(); let resource_hash = match parameters.get("resource") { Some(Value::Text(name)) => package.resource(name).map_or(0, |r| r.bytes.content_hash()), _ => 0, diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 2892244d..79c6483c 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -47,6 +47,111 @@ fn cooks_and_caches() { assert_eq!(outputs(&p.graphs[0], &c).len(), 1); } +#[test] +fn material_overrides_skip_bound_preview_decodes_and_release_buffers() { + let mut graph = Graph::new("Bound inputs"); + graph.size = [4; 2]; + let identifiers = ["height", "curvature", "thickness"]; + let mut outputs = Vec::new(); + for identifier in identifiers { + let input = graph.add_node("input_grayscale", [0.0; 2]); + graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text(identifier.into())); + let output = graph.add_node("output", [0.0; 2]); + graph.connect(input, "output", output, "input").unwrap(); + graph.input_images.insert(identifier.into(), format!("preview_{identifier}")); + outputs.push(output); + } + let mut package = Package::new("Bound inputs"); + package.graphs.push(graph); + let preview_buffers = Mutex::new(Vec::new()); + let read_preview = |_: &str| { + let image = Image::filled(1024, 1024, Kind::Gray, [0.25; 4]); + preview_buffers.lock().unwrap().push(std::sync::Arc::downgrade(image.shared_data())); + Some(image) + }; + let cache = Mutex::new(Cache::new(0)); + + for value in [0.125, 0.5, 0.875] { + let mut options = Options::new(&read_preview); + let mut supplied_buffers = Vec::new(); + for identifier in &identifiers[..2] { + let image = Image::filled(16, 16, Kind::Gray, [value; 4]); + supplied_buffers.push(std::sync::Arc::downgrade(image.shared_data())); + options.inputs.insert((*identifier).into(), image); + } + + let result = cook(&package, 0, &options, &cache); + for (output, expected) in outputs.iter().zip([value, value, 0.25]) { + let image = result.image(*output, 0).unwrap(); + assert!((image.mean()[0] - expected).abs() < 0.005); + } + drop(result); + drop(options); + + assert!(supplied_buffers.iter().all(|buffer| buffer.upgrade().is_none())); + } + + let previews = preview_buffers.into_inner().unwrap(); + assert!(previews.iter().all(|buffer| buffer.upgrade().is_none())); + eprintln!("Decoded preview planes: {} ({} bytes of grayscale payload)", previews.len(), previews.len() * 1024 * 1024 * size_of::()); + assert_eq!(previews.len(), 3, "one fallback preview decode per cook"); +} + +#[test] +fn selected_outputs_decode_only_reachable_input_previews() { + let mut graph = Graph::new("Preview selection"); + graph.size = [4; 2]; + let mut outputs = Vec::new(); + for identifier in ["height", "roughness", "normal", "height"] { + let input = graph.add_node("input_grayscale", [0.0; 2]); + graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text(identifier.into())); + graph.input_images.insert(identifier.into(), identifier.into()); + let output = graph.add_node("output", [0.0; 2]); + graph.connect(input, "output", output, "input").unwrap(); + outputs.push(output); + } + + let mut package = Package::new("Preview selection"); + package.graphs.push(graph); + let mut counts = Vec::new(); + for (selected, expected) in [(vec![outputs[0], outputs[3]], 0.25), (vec![outputs[1]], 0.5), (vec![outputs[2]], 0.75)] { + let buffers = Mutex::new(Vec::new()); + let peak_planes = std::sync::atomic::AtomicUsize::new(0); + let read_preview = |name: &str| { + let value = match craft_texture::split_resource_key(name).0 { + "height" => 0.25, + "roughness" => 0.5, + "normal" => 0.75, + other => panic!("unexpected preview {other}"), + }; + let image = Image::filled(1024, 1024, Kind::Gray, [value; 4]); + let mut buffers = buffers.lock().unwrap(); + buffers.push(std::sync::Arc::downgrade(image.shared_data())); + peak_planes.fetch_max(buffers.iter().filter(|plane| plane.strong_count() > 0).count(), std::sync::atomic::Ordering::Relaxed); + Some(image) + }; + let mut options = Options::new(&read_preview); + options.only = Some(selected.clone()); + let cache = Mutex::new(Cache::new(0)); + + let result = cook(&package, 0, &options, &cache); + + for output in &outputs { + if selected.contains(output) { + assert!((result.image(*output, 0).unwrap().mean()[0] - expected).abs() < 0.005); + } else { + assert!(result.image(*output, 0).is_none()); + } + } + let buffers = buffers.into_inner().unwrap(); + assert!(buffers.iter().all(|buffer| buffer.upgrade().is_none())); + counts.push((buffers.len(), peak_planes.into_inner())); + } + + eprintln!("Decoded and peak live 1024-square grayscale previews per selection: {counts:?}"); + assert_eq!(counts, [(1, 1); 3]); +} + #[test] fn processor_tiling_variable_tracks_both_axes_and_invalidates_cached_values() { let mut function = materialcraft_core::FunctionGraph::default(); diff --git a/crates/formats/src/image.rs b/crates/formats/src/image.rs index b51eaab9..5fe5d126 100644 --- a/crates/formats/src/image.rs +++ b/crates/formats/src/image.rs @@ -64,8 +64,9 @@ pub fn encode(image: &Image, ext: &str, depth: Depth, srgb: bool) -> Result [f32; 4] { @@ -146,7 +147,7 @@ mod transfer_tests { assert_eq!(decoded.kind(), if srgb { Kind::Color } else { Kind::Gray }); assert!((decoded.data()[0] - 0.25).abs() < 0.003); if !srgb { - // Existing grayscale data imports stay linear even at the default setting. + // Existing grayscale data imports stay linear even at the default setting assert!((decode(&bytes, false).unwrap().data()[0] - 0.25).abs() < 0.003); } let stored = decode(&bytes, true).unwrap(); diff --git a/crates/formats/src/material/archive.rs b/crates/formats/src/material/archive.rs index 7054b5a9..5c0a8c46 100644 --- a/crates/formats/src/material/archive.rs +++ b/crates/formats/src/material/archive.rs @@ -10,7 +10,19 @@ pub fn is_material(bytes: &[u8]) -> bool { } pub fn write_material(package: &Package, entry: usize) -> Result> { + write_material_with_resource_limit(package, entry, craft_mcmat::Limits::default().max_total_bytes) +} + +/// Limit the aggregate source assets before generating the output archive. +pub fn write_material_with_resource_limit(package: &Package, entry: usize, maximum_resource_bytes: u64) -> Result> { let snapshot = super::snapshot(package, entry)?; + let mut remaining = maximum_resource_bytes; + for resource in &snapshot.resources { + remaining = remaining.checked_sub(resource.bytes.len() as u64).ok_or_else(|| { + FormatError::BadPackage(format!("material source assets exceed the {maximum_resource_bytes}-byte limit; reduce source asset sizes")) + })?; + } + let files = ProjectFiles::build(&snapshot, craft_mcmat::SOURCE_ENTRY, false)?; let resources = files.files.iter().filter(|(name, _)| **name != files.entry).map(|(name, bytes)| (name.as_str(), bytes.as_slice())); craft_mcmat::write(files.xml()?, resources).map_err(|err| FormatError::BadPackage(err.to_string())) @@ -38,18 +50,30 @@ pub fn read_material(bytes: &[u8]) -> Result<(Package, usize)> { Ok((pkg, entry)) } -// Linked aliases and inline SBS assets must share the same decoded-byte budget. +// Linked aliases and inline SBS assets share one decoded-byte budget fn read_source(material: &craft_mcmat::Material, budget: u64) -> Result { let remaining = Cell::new(budget); - sbs::SbsDocument::parse(&material.source)?.read_with_resource_budget( + let over_budget = Cell::new(false); + let mut read = sbs::SbsDocument::parse(&material.source)?.read_with_resource_budget( craft_mcmat::SOURCE_ENTRY, &|name| { let data = material.resources.get(name)?; - remaining.set(remaining.get().checked_sub(data.len() as u64)?); + let Some(bytes_left) = remaining.get().checked_sub(data.len() as u64) else { + over_budget.set(true); + return None; + }; + + remaining.set(bytes_left); Some(data.clone()) }, &remaining, - ) + )?; + + if over_budget.get() { + read.warnings.insert(0, "archive member exceeds the remaining material resource budget".into()); + } + + Ok(read) } /// Whether maps of `usage` hold colors (stored sRGB-encoded) rather than data (linear) @@ -74,6 +98,7 @@ pub fn srgb_usage(usage: &str) -> bool { mod tests { use super::*; use base64::Engine as _; + use materialcraft_core::{Graph, Resource, ResourceBytes, Value}; use std::io::Write; fn inline(bytes: &[u8]) -> String { @@ -93,6 +118,30 @@ mod tests { craft_mcmat::Material::open(&bytes, craft_mcmat::Limits::default()).unwrap() } + #[test] + fn publication_checks_the_combined_bytes_of_distinct_source_assets() { + const ASSET_BYTES: usize = 4096; + let mut package = Package::new("Assets"); + let mut graph = Graph::new("Root"); + for (index, name) in ["a", "b"].into_iter().enumerate() { + package.resources.push(Resource::new(name, format!("{name}.bin"), ResourceBytes::new(vec![index as u8; ASSET_BYTES]))); + let bitmap = graph.add_node("bitmap", [0.0; 2]); + graph.node_mut(bitmap).unwrap().params.insert("resource".into(), Value::Text(name.into())); + let output = graph.add_node("output", [0.0; 2]); + graph.connect(bitmap, "output", output, "input").unwrap(); + } + package.graphs.push(graph); + let total = (2 * ASSET_BYTES) as u64; + + let error = write_material_with_resource_limit(&package, 0, total - 1).unwrap_err(); + let archive = write_material_with_resource_limit(&package, 0, total).unwrap(); + let (reopened, _) = read_material(&archive).unwrap(); + + assert!(error.to_string().contains("material source assets exceed")); + assert!(archive.len() < ASSET_BYTES); + assert_eq!(reopened.resources.iter().map(|resource| resource.bytes.len()).sum::(), total as usize); + } + #[test] fn inline_budget_failure_does_not_substitute_a_different_linked_asset() { let content = inline(b"four").replace("", ""); @@ -119,6 +168,7 @@ mod tests { "" ); let read = read_source(&make_material(&content), 3).unwrap(); + assert!(read.warnings.is_empty()); assert_eq!(read.pkg.resources[0].bytes.as_slice(), b"abc"); } @@ -133,6 +183,7 @@ mod tests { "" ); let read = read_source(&make_material(&content), 3).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); assert_eq!(read.pkg.resources[0].bytes.as_slice(), b"abc"); } @@ -141,6 +192,7 @@ mod tests { fn repeated_oversized_inline_probes_exhaust_document_work() { let content = format!("{}{}{}", inline(b"four"), inline(b"four"), inline(b"")); let read = read_source(&make_material(&content), 3).unwrap(); + assert!(read.pkg.resources.is_empty()); assert!(read.warnings.iter().any(|warning| warning.contains("inflation work budget"))); } @@ -169,6 +221,16 @@ mod tests { } } + #[test] + fn archive_budget_errors_name_the_budget_rather_than_a_missing_member() { + let material = make_material(&format!("{}{}", linked("a"), linked("b"))); + + let read = read_source(&material, 5).unwrap(); + + assert!(read.warnings.first().unwrap().contains("resource budget")); + assert_eq!(read.pkg.resources.iter().map(|resource| resource.bytes.len()).sum::(), 3); + } + #[test] fn standalone_sbs_keeps_inline_compatibility_and_zero_length_is_free() { let material = make_material(&format!("{}{}", inline(b""), linked("member"))); diff --git a/crates/formats/src/material/mod.rs b/crates/formats/src/material/mod.rs index 02a1dcd4..00f36fb5 100644 --- a/crates/formats/src/material/mod.rs +++ b/crates/formats/src/material/mod.rs @@ -2,6 +2,6 @@ mod archive; mod image_input; mod snapshot_builder; -pub use archive::{MATERIAL_EXT, VERSION, is_material, read_material, srgb_usage, write_material}; +pub use archive::{MATERIAL_EXT, VERSION, is_material, read_material, srgb_usage, write_material, write_material_with_resource_limit}; pub use image_input::ImageInput; pub use snapshot_builder::{entry_graph, snapshot}; diff --git a/crates/formats/src/material/snapshot_builder.rs b/crates/formats/src/material/snapshot_builder.rs index 47093f2d..fdb602d5 100644 --- a/crates/formats/src/material/snapshot_builder.rs +++ b/crates/formats/src/material/snapshot_builder.rs @@ -5,6 +5,9 @@ use materialcraft_core::{Graph, GraphIndex, Package, Value}; use crate::{FormatError, Result}; +// Bound the combined graph and function traversal independently of cooking +const MAX_DEPENDENCY_DEPTH: usize = 32; + fn bad(message: impl Into) -> FormatError { FormatError::BadPackage(message.into()) } @@ -18,17 +21,18 @@ pub fn snapshot(package: &Package, entry: usize) -> Result { let mut result = Package::new(&graph.name); result.format_version.clone_from(&package.format_version); - let mut builder = SnapshotBuilder { root: package, result, paths: BTreeMap::new(), active: BTreeSet::new(), resources: BTreeMap::new(), nodes: 0 }; + let mut builder = SnapshotBuilder { root: package, result, completed: BTreeMap::new(), active: BTreeSet::new(), resources: BTreeMap::new(), nodes: 0 }; builder.copy_graph("", entry)?; Ok(builder.result) } -type Key = (String, usize); +type GraphKey = (String, usize); + struct SnapshotBuilder<'a> { root: &'a Package, result: Package, - paths: BTreeMap, - active: BTreeSet, + completed: BTreeMap, + active: BTreeSet, resources: BTreeMap<(String, String), String>, nodes: usize, } @@ -42,11 +46,9 @@ impl<'a> SnapshotBuilder<'a> { self.root.dependencies.get(owner).map(AsRef::as_ref).ok_or_else(|| bad(format!("missing source package `{owner}`"))) } - fn reference(&mut self, owner: &str, name: &str, height: &mut usize) -> Result { + fn reference(&mut self, owner: &str, name: &str) -> Result<(String, usize)> { let (index, _) = self.package(owner)?.graph_by_name(name).ok_or_else(|| bad(format!("missing or ambiguous graph `{name}` in `{owner}`")))?; - let (path, child_height) = self.copy_graph(owner, index)?; - *height = (*height).max(child_height + 1); - Ok(path) + self.copy_graph(owner, index) } fn copy_graph(&mut self, owner: &str, index: usize) -> Result<(String, usize)> { @@ -56,18 +58,17 @@ impl<'a> SnapshotBuilder<'a> { return Err(bad(format!("cyclic graph reference at `{}`", source.sbs_path()))); } - // Bound the complete path, including a shared tail copied on an earlier branch. - // Active entries are rejected above, so cached heights here are complete. - const MAX_DEPENDENCY_DEPTH: usize = 32; - if let Some((path, height)) = self.paths.get(&key) { - if self.active.len() + height > MAX_DEPENDENCY_DEPTH { - return Err(bad("published graph dependencies exceed the depth or graph count limit")); + if let Some((path, depth)) = self.completed.get(&key) { + // A shared subtree can be reached from a longer path than its first visit + if self.active.len() + depth > MAX_DEPENDENCY_DEPTH { + return Err(bad("published graph dependencies exceed the depth limit")); } - return Ok((path.clone(), *height)); + + return Ok((path.clone(), *depth)); } - // Bound publishing independently of the cooker's per-function and per-instance limits - if self.active.len() >= MAX_DEPENDENCY_DEPTH || self.paths.len() >= crate::sbs::MAX_GRAPHS { + let graph_count = self.completed.len() + self.active.len(); + if self.active.len() >= MAX_DEPENDENCY_DEPTH || graph_count >= crate::sbs::MAX_GRAPHS { return Err(bad("published graph dependencies exceed the depth or graph count limit")); } @@ -75,7 +76,7 @@ impl<'a> SnapshotBuilder<'a> { if graph.function.is_none() { let outputs: Vec<_> = graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect(); let index = GraphIndex::new(&graph); - if self.paths.is_empty() && !outputs.iter().any(|id| !index.incoming(*id).is_empty()) { + if graph_count == 0 && !outputs.iter().any(|id| !index.incoming(*id).is_empty()) { return Err(bad(format!("select a material graph with connected outputs: `{}`", graph.sbs_path()))); } @@ -92,14 +93,15 @@ impl<'a> SnapshotBuilder<'a> { return Err(bad("published graph exceeds the node count limit")); } - graph.folder = if self.paths.is_empty() { String::new() } else { format!("Dependencies/g{}", self.paths.len()) }; + graph.folder = if graph_count == 0 { String::new() } else { format!("Dependencies/g{graph_count}") }; let path = graph.sbs_path(); - self.paths.insert(key.clone(), (path.clone(), 0)); - let mut height = 1; self.active.insert(key.clone()); + let mut max_child_depth = 0; for instance in graph.instances_mut() { let package = if instance.package.is_empty() { owner } else { &instance.package }; - instance.graph = self.reference(package, &instance.graph, &mut height)?; + let (local_path, depth) = self.reference(package, &instance.graph)?; + instance.graph = local_path; + max_child_depth = max_child_depth.max(depth); instance.package.clear(); } for node in &mut graph.nodes { @@ -111,7 +113,9 @@ impl<'a> SnapshotBuilder<'a> { if let Some(instance) = &node.instance { node.params.insert("graph".into(), Value::Text(instance.graph.clone())); } else if let Some(Value::Text(target)) = node.params.get_mut("graph") { - *target = self.reference(owner, target, &mut height)?; + let (local_path, depth) = self.reference(owner, target)?; + *target = local_path; + max_child_depth = max_child_depth.max(depth); } else { return Err(bad(format!("missing graph reference in `{path}`"))); } @@ -122,6 +126,7 @@ impl<'a> SnapshotBuilder<'a> { let Some(Value::Text(name)) = node.params.get_mut("resource").filter(|v| !matches!(v, Value::Text(s) if s.is_empty())) else { return Err(bad(format!("missing resource for {} node {} in `{path}`", node.def, node.id.0))); }; + *name = self.resource(owner, name)?; } "text" => { @@ -138,10 +143,11 @@ impl<'a> SnapshotBuilder<'a> { *name = self.resource(owner, name)?; } + let depth = max_child_depth + 1; self.active.remove(&key); - self.paths.insert(key, (path.clone(), height)); + self.completed.insert(key, (path.clone(), depth)); self.result.graphs.push(graph); - Ok((path, height)) + Ok((path, depth)) } fn resource(&mut self, owner: &str, name: &str) -> Result { @@ -177,48 +183,44 @@ pub fn entry_graph(pkg: &Package) -> Result { mod tests { use super::*; - fn graph(name: &str, children: &[String]) -> Graph { - let mut graph = Graph::new(name); - if children.is_empty() { - let source = graph.add_node("uniform", [0.0; 2]); - let output = graph.add_node("output", [0.0; 2]); - graph.connect(source, "output", output, "input").unwrap(); - } - for child in children { - let source = graph.add_node("graph_instance", [0.0; 2]); - graph.node_mut(source).unwrap().params.insert("graph".into(), Value::Text(child.clone())); - let output = graph.add_node("output", [0.0; 2]); - graph.connect(source, "output", output, "input").unwrap(); - } - graph - } - - fn shared_tail(chain: usize, tail: usize, cached_first: bool) -> Package { - let mut package = Package::new("depth"); - let mut children = vec!["tail0".into(), "chain0".into()]; - if !cached_first { - children.reverse(); - } - package.graphs.push(graph("root", &children)); - for i in 0..chain { - let next = if i + 1 == chain { "tail0".into() } else { format!("chain{}", i + 1) }; - package.graphs.push(graph(&format!("chain{i}"), &[next])); - } - for i in 0..tail { - let children = if i + 1 == tail { vec![] } else { vec![format!("tail{}", i + 1)] }; - package.graphs.push(graph(&format!("tail{i}"), &children)); - } - package + fn connect_reference(graph: &mut Graph, target: &str) { + let instance = graph.add_node("graph_instance", [0.0; 2]); + graph.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text(target.into())); + let output = graph.add_node("output", [0.0; 2]); + graph.connect(instance, "output", output, "input").unwrap(); } #[test] - fn cached_graph_depth_is_independent_of_reference_order() { - for cached_first in [true, false] { - // Root + chain + shared tail: 32 is valid, 33 is not. The cached - // tail can itself contain dependencies, not just a leaf. - for tail in [1, 5] { - assert!(snapshot(&shared_tail(31 - tail, tail, cached_first), 0).is_ok()); - assert!(snapshot(&shared_tail(32 - tail, tail, cached_first), 0).is_err()); + fn depth_limit_applies_to_both_paths_through_a_shared_subtree() { + for depth in [MAX_DEPENDENCY_DEPTH, MAX_DEPENDENCY_DEPTH + 1] { + for cached_first in [true, false] { + let mut package = Package::new("Shared subtree"); + let mut root = Graph::new("Root"); + let targets = if cached_first { ["Shared", "Link0"] } else { ["Link0", "Shared"] }; + for target in targets { + connect_reference(&mut root, target); + } + + package.graphs.push(root); + let link_count = depth - 3; + for index in 0..link_count { + let mut link = Graph::new(&format!("Link{index}")); + let target = if index + 1 == link_count { "Shared".into() } else { format!("Link{}", index + 1) }; + connect_reference(&mut link, &target); + package.graphs.push(link); + } + + let mut shared = Graph::new("Shared"); + connect_reference(&mut shared, "Leaf"); + package.graphs.extend([shared, Graph::new("Leaf")]); + + let published = snapshot(&package, 0); + + if depth == MAX_DEPENDENCY_DEPTH { + assert_eq!(published.unwrap().graphs.len(), depth); + } else { + assert!(published.unwrap_err().to_string().contains("depth"), "cached first: {cached_first}"); + } } } } diff --git a/crates/formats/src/sbs/embedded.rs b/crates/formats/src/sbs/embedded.rs index de40aed8..d316ccdc 100644 --- a/crates/formats/src/sbs/embedded.rs +++ b/crates/formats/src/sbs/embedded.rs @@ -1,79 +1,70 @@ +use super::embedded_error::EmbeddedError; use crate::{FormatError, Result}; use base64::Engine as _; -use std::io::{Read, Write}; +use std::{ + cell::Cell, + io::{self, Read, Write}, +}; pub(super) fn base64_engine() -> base64::engine::GeneralPurpose { base64::engine::general_purpose::STANDARD } pub(super) fn decode_embedded(strdata: &str) -> std::result::Result, String> { - decode_embedded_bounded(strdata, crate::MAX_RESOURCE, &std::cell::Cell::new(crate::MAX_RESOURCE + 1)).map_err(|error| error.to_string()) + decode_embedded_bounded(strdata, crate::MAX_RESOURCE, &Cell::new(crate::MAX_RESOURCE + 1)).map_err(|error| error.to_string()) } -#[derive(Debug)] -pub(super) enum EmbeddedError { - Damaged(String), - Budget, - WorkBudget, -} -impl From for EmbeddedError { - fn from(message: String) -> Self { - Self::Damaged(message) - } -} -impl From<&str> for EmbeddedError { - fn from(message: &str) -> Self { - Self::Damaged(message.into()) - } -} -impl std::fmt::Display for EmbeddedError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Damaged(message) => f.write_str(message), - Self::WorkBudget => f.write_str("embedded resource exceeds the material inflation work budget"), - Self::Budget => f.write_str("embedded resource exceeds the remaining material resource budget"), - } - } -} - -pub(super) fn decode_embedded_bounded(strdata: &str, remaining: u64, work: &std::cell::Cell) -> std::result::Result, EmbeddedError> { - if work.get() == 0 { +pub(super) fn decode_embedded_bounded(strdata: &str, remaining_bytes: u64, inflation_work: &Cell) -> std::result::Result, EmbeddedError> { + let work_before = inflation_work.get(); + if work_before == 0 { return Err(EmbeddedError::WorkBudget); } - let raw = base64_engine().decode(strdata.split_whitespace().collect::()).map_err(|e| format!("bad base64: {e}"))?; + + let raw = match strdata.split_once(char::is_whitespace) { + Some((prefix, rest)) => base64_engine().decode(std::iter::once(prefix).chain(rest.split_whitespace()).collect::()), + None => base64_engine().decode(strdata), + } + .map_err(|error| format!("bad base64: {error}"))?; let (length, compressed) = raw.split_at_checked(4).ok_or("too short")?; - let length = u32::from_be_bytes([length[0], length[1], length[2], length[3]]) as usize; - if length as u64 > crate::MAX_RESOURCE { + let declared_bytes = u64::from(u32::from_be_bytes([length[0], length[1], length[2], length[3]])); + if declared_bytes > crate::MAX_RESOURCE { return Err("embedded resource exceeds the 256 MiB limit".into()); } - let mut out = Vec::new(); - - // Probe only one byte beyond the tighter cap. Corruption detected within that - // prefix remains damaged data regardless of the untrusted declared length. - // Stop at budget + 1; damage later in an oversized stream is not inspected. - let cap = (length as u64).min(remaining) + 1; - let work_before = work.get(); + // Read one probe byte beyond the tighter bound to detect overruns + let probe_limit = declared_bytes.min(remaining_bytes) + 1; let mut decoder = flate2::read::ZlibDecoder::new(compressed); - let result = decoder.by_ref().take(cap.min(work_before)).read_to_end(&mut out); - // Count discarded output and bytes produced before a checksum/error, not only - // successfully retained resources. Never restart inflation after exhaustion. - work.set(work_before.saturating_sub(decoder.total_out())); - result.map_err(|e| format!("bad compressed data: {e}"))?; - if out.len() > length { - return Err(format!("{} bytes where {length} were declared", out.len()).into()); + let mut limited = decoder.by_ref().take(probe_limit.min(work_before)); + let mut output = Vec::new(); + let result = if declared_bytes > remaining_bytes || declared_bytes >= work_before { + // Discard probe output that cannot become a retained asset + io::copy(&mut limited, &mut io::sink()) + } else { + limited.read_to_end(&mut output).map(|bytes| bytes as u64) + }; + + // Charge every emitted byte, including output produced before a checksum error + inflation_work.set(work_before.saturating_sub(decoder.total_out())); + let actual_bytes = result.map_err(|error| format!("bad compressed data: {error}"))?; + if actual_bytes > declared_bytes { + return Err(format!("{actual_bytes} bytes where {declared_bytes} were declared").into()); } - if work_before < cap && out.len() as u64 == work_before { + + if work_before < probe_limit && actual_bytes == work_before { return Err(EmbeddedError::WorkBudget); } - if out.len() as u64 > remaining { + + if actual_bytes > remaining_bytes { return Err(EmbeddedError::Budget); } - if out.len() != length { - return Err(format!("{} bytes where {length} were declared", out.len()).into()); + + if actual_bytes != declared_bytes { + return Err(format!("{actual_bytes} bytes where {declared_bytes} were declared").into()); } - Ok(out) + // ResourceBytes retains the vector and its capacity + output.shrink_to_fit(); + Ok(output) } pub(super) fn encode_embedded(bytes: &[u8]) -> Result { @@ -108,7 +99,7 @@ mod tests { assert!(decode_embedded("AA").unwrap_err().starts_with("bad base64:")); let encoded = encode_embedded(b"payload").unwrap(); - let spaced = encoded.chars().map(|c| format!("{c} \n")).collect::(); + let spaced = encoded.chars().map(|c| format!("{c} \n\u{2003}")).collect::(); assert_eq!(decode_embedded(&spaced).unwrap(), b"payload"); } @@ -119,24 +110,27 @@ mod tests { let mut raw = length.to_be_bytes().to_vec(); raw.push(255); let encoded = base64_engine().encode(raw); - assert!(matches!(decode_embedded_bounded(&encoded, 3, &std::cell::Cell::new(16)), Err(EmbeddedError::Damaged(_)))); + assert!(matches!(decode_embedded_bounded(&encoded, 3, &Cell::new(16)), Err(EmbeddedError::Damaged(_)))); } let encoded = encode_embedded(b"four").unwrap(); - assert!(matches!(decode_embedded_bounded(&encoded, 3, &std::cell::Cell::new(16)), Err(EmbeddedError::Budget))); - assert_eq!(decode_embedded_bounded(&encoded, 4, &std::cell::Cell::new(16)).unwrap(), b"four"); + + assert!(matches!(decode_embedded_bounded(&encoded, 3, &Cell::new(16)), Err(EmbeddedError::Budget))); + assert_eq!(decode_embedded_bounded(&encoded, 4, &Cell::new(16)).unwrap(), b"four"); } #[test] fn inflation_work_counts_discarded_prefixes_and_stops_before_next_decode() { - let work = std::cell::Cell::new(8); + let work = Cell::new(8); let encoded = encode_embedded(b"four").unwrap(); for expected in [4, 0] { assert!(matches!(decode_embedded_bounded(&encoded, 3, &work), Err(EmbeddedError::Budget))); assert_eq!(work.get(), expected); } - // Even invalid base64 is not inspected after work exhaustion. + + // Exhaustion stops the next resource before Base64 decoding assert!(matches!(decode_embedded_bounded("!!!!", 3, &work), Err(EmbeddedError::WorkBudget))); - let work = std::cell::Cell::new(2); + + let work = Cell::new(2); assert!(matches!(decode_embedded_bounded(&encoded, 4, &work), Err(EmbeddedError::WorkBudget))); assert_eq!(work.get(), 0); } @@ -145,7 +139,8 @@ mod tests { fn checksum_errors_charge_output_without_spending_retained_budget() { let mut raw = base64_engine().decode(encode_embedded(b"four").unwrap()).unwrap(); *raw.last_mut().unwrap() ^= 1; - let work = std::cell::Cell::new(8); + let work = Cell::new(8); + assert!(matches!(decode_embedded_bounded(&base64_engine().encode(raw), 4, &work), Err(EmbeddedError::Damaged(_)))); assert_eq!(work.get(), 4); } @@ -154,11 +149,23 @@ mod tests { fn proven_length_mismatch_precedes_retained_budget() { let mut raw = base64_engine().decode(encode_embedded(b"four").unwrap()).unwrap(); raw[..4].copy_from_slice(&3_u32.to_be_bytes()); - let work = std::cell::Cell::new(4); + let work = Cell::new(4); + assert!(matches!(decode_embedded_bounded(&base64_engine().encode(raw), 3, &work), Err(EmbeddedError::Damaged(_)))); assert_eq!(work.get(), 0); } + #[test] + fn retained_assets_release_spare_decompression_capacity() { + let bytes = vec![17; 2 << 20]; + let encoded = encode_embedded(&bytes).unwrap(); + + let decoded = decode_embedded(&encoded).unwrap(); + + assert_eq!(decoded, bytes); + assert!(decoded.capacity() < 2 * decoded.len(), "retained {} bytes for a {}-byte asset", decoded.capacity(), decoded.len()); + } + #[test] fn decompression_requires_the_declared_length() { let encoded = encode_embedded(&[1, 2, 3, 4]).unwrap(); diff --git a/crates/formats/src/sbs/embedded_error.rs b/crates/formats/src/sbs/embedded_error.rs new file mode 100644 index 00000000..7ddea4c2 --- /dev/null +++ b/crates/formats/src/sbs/embedded_error.rs @@ -0,0 +1,28 @@ +#[derive(Debug)] +pub(super) enum EmbeddedError { + Damaged(String), + Budget, + WorkBudget, +} + +impl From for EmbeddedError { + fn from(message: String) -> Self { + Self::Damaged(message) + } +} + +impl From<&str> for EmbeddedError { + fn from(message: &str) -> Self { + Self::Damaged(message.into()) + } +} + +impl std::fmt::Display for EmbeddedError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Damaged(message) => formatter.write_str(message), + Self::Budget => formatter.write_str("embedded resource exceeds the remaining material resource budget"), + Self::WorkBudget => formatter.write_str("embedded resource exceeds the material inflation work budget"), + } + } +} diff --git a/crates/formats/src/sbs/instance_interface.rs b/crates/formats/src/sbs/instance_interface.rs index a0ca0bff..3a9293d8 100644 --- a/crates/formats/src/sbs/instance_interface.rs +++ b/crates/formats/src/sbs/instance_interface.rs @@ -1,10 +1,10 @@ -//! Retain typed, including unconnected, material graph inputs when references become local. +//! Preserve typed graph inputs, including unconnected inputs, when localizing graph references. use super::xml::{child_element, child_value, children_named, xml_escape}; use materialcraft_core::GraphPort; use roxmltree::Node; use std::{collections::BTreeSet, fmt::Write}; -const MAX_INPUTS: usize = 4096; +pub(super) const MAX_INPUTS: usize = 4096; pub(super) fn read(element: Node<'_, '_>) -> Option, String>> { let interface = child_element(element, "materialcraftInterface")?; @@ -13,12 +13,14 @@ pub(super) fn read(element: Node<'_, '_>) -> Option, Strin let mut names = BTreeSet::new(); for port in children_named(interface, "input") { if inputs.len() == MAX_INPUTS { - return Err("Graph instance exceeds the 4096-input limit".into()); + return Err(format!("Graph instance exceeds the {MAX_INPUTS}-input limit")); } + let identifier = child_value(port, "identifier").unwrap_or(""); if identifier.is_empty() || !names.insert(identifier) { return Err("Invalid or duplicate graph input identifier".into()); } + let type_code = child_value(port, "type").and_then(|value| value.parse().ok()).ok_or("Invalid graph input type")?; inputs.push(GraphPort { identifier: identifier.into(), type_code }); } @@ -26,21 +28,19 @@ pub(super) fn read(element: Node<'_, '_>) -> Option, Strin })()) } -// XML 1.0 characters: escaping must not silently remove identifier characters. -fn xml_identifier_char(c: char) -> bool { - matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}') -} - pub(super) fn write(out: &mut String, inputs: &[GraphPort]) -> Result<(), String> { if inputs.len() > MAX_INPUTS { - return Err("Graph instance exceeds the 4096-input limit".into()); + return Err(format!("Graph instance exceeds the {MAX_INPUTS}-input limit")); } + + // Validate before writing because the XML escaper drops unsupported characters let mut names = BTreeSet::new(); for port in inputs { - if port.identifier.is_empty() || !port.identifier.chars().all(xml_identifier_char) || !names.insert(&port.identifier) { + if port.identifier.is_empty() || !port.identifier.chars().all(craft_xml::is_xml_char) || !names.insert(&port.identifier) { return Err("Invalid or duplicate graph input identifier".into()); } } + out.push_str(""); for port in inputs { let _ = write!(out, "", xml_escape(&port.identifier), port.type_code); @@ -60,13 +60,16 @@ mod tests { let document = roxmltree::Document::parse(&xml).unwrap(); read(document.root_element()).unwrap() }; + assert!(parse("").is_err()); assert!(parse("".repeat(2).as_str()).is_err()); + let mut body = String::new(); - for index in 0..4096 { + for index in 0..MAX_INPUTS { write!(body, "").unwrap(); } - assert_eq!(parse(&body).unwrap().len(), 4096); + + assert_eq!(parse(&body).unwrap().len(), MAX_INPUTS); body.push_str(""); assert!(parse(&body).is_err()); } @@ -82,16 +85,20 @@ mod writer_tests { let inputs = vec![GraphPort { identifier: "roughness".into(), type_code: 2 }, GraphPort { identifier: format!("roughness{invalid}"), type_code: 2 }]; let mut out = String::from("unchanged"); + assert!(write(&mut out, &inputs).is_err()); assert_eq!(out, "unchanged"); assert!(write(&mut out, &inputs[1..]).is_err()); assert_eq!(out, "unchanged"); } + let inputs = vec![GraphPort { identifier: "é😀<&\"'\t\n\r".into(), type_code: 2 }]; let mut xml = String::from(""); + write(&mut xml, &inputs).unwrap(); xml.push_str(""); let document = roxmltree::Document::parse(&xml).unwrap(); + assert_eq!(read(document.root_element()).unwrap().unwrap(), inputs); } @@ -99,19 +106,33 @@ mod writer_tests { fn writer_matches_reader_limits_and_refuses_before_appending() { let mut inputs: Vec<_> = (0..MAX_INPUTS).map(|index| GraphPort { identifier: format!("p{index}"), type_code: 2 }).collect(); let mut xml = String::from(""); + write(&mut xml, &inputs).unwrap(); xml.push_str(""); let document = roxmltree::Document::parse(&xml).unwrap(); + assert_eq!(read(document.root_element()).unwrap().unwrap(), inputs); + inputs.push(GraphPort { identifier: "extra".into(), type_code: 2 }); let mut out = String::from("unchanged"); assert!(write(&mut out, &inputs).unwrap_err().contains("4096")); assert_eq!(out, "unchanged"); + inputs.truncate(2); inputs[1].identifier = inputs[0].identifier.clone(); assert!(write(&mut out, &inputs).is_err()); + inputs[1].identifier.clear(); assert!(write(&mut out, &inputs).is_err()); assert_eq!(out, "unchanged"); } + + #[test] + fn writer_rejects_input_identifiers_that_xml_would_change() { + let mut xml = String::new(); + let inputs = [GraphPort { identifier: "roughness".into(), type_code: 2 }, GraphPort { identifier: "roughness\u{1f}".into(), type_code: 2 }]; + + assert!(write(&mut xml, &inputs).is_err()); + assert!(xml.is_empty()); + } } diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index 9209a61d..d9ea0b64 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -4,6 +4,7 @@ mod component_usage; mod connection; mod constant; mod embedded; +mod embedded_error; mod filter_map; mod function_graph; mod function_instance; diff --git a/crates/formats/src/sbs/presets.rs b/crates/formats/src/sbs/presets.rs index ab931a18..e3fbede1 100644 --- a/crates/formats/src/sbs/presets.rs +++ b/crates/formats/src/sbs/presets.rs @@ -12,6 +12,7 @@ pub(super) fn write(out: &mut String, graph: &Graph, uids: &HashMap if graph.presets.is_empty() { return; } + out.push_str(""); for preset in &graph.presets { let _ = write!(out, "