diff --git a/Cargo.toml b/Cargo.toml index 8c9bebdf..17f55903 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,14 +42,14 @@ rust-version = "1.95" repository = "https://github.com/storytold/materialcraft" [workspace.dependencies] -# Standard Base64 output; strict SBS decoding remains app-local. +# Standard Base64 output; strict SBS decoding remains app-local craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } craft-texture-dds = { package = "craft-texture", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "726ad0f8290bedb6ced60fa06200a6b574f9990d", features = ["dds"] } -# OBJ and glTF/GLB mesh reading for the 3D view; normalisation, UVs and tangents stay app-local. +# Read 3D meshes through craft-mesh; keep mesh processing app-local craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "57288edafdc45552e30481cc649021de446abfa0", default-features = false, features = ["obj", "gltf"] } # Shared XML escaping; SBS model and serialization policy stay app-local. craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } -# SVG: bounded parsing (usvg re-exported) and drawing (resvg) behind the shared checks. +# Bound SVG parsing and drawing through craft-svg craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "57288edafdc45552e30481cc649021de446abfa0", features = ["tree-render"] } # internal materialcraft-core = { path = "crates/core" } @@ -69,7 +69,6 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" # MIT OR Apache-2.0; stable content keys for persistent previews. glam = { version = "0.30", features = ["serde", "bytemuck"] } -bytemuck = { version = "1", features = ["derive"] } rayon = "1" log = "0.4" image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp", "gif", "pnm"] } diff --git a/README.md b/README.md index b577b346..9e9fc641 100644 --- a/README.md +++ b/README.md @@ -178,12 +178,13 @@ The details are in [`docs/control-protocol.md`](docs/control-protocol.md). MaterialCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the parity estimate by area, the remaining work and what's next. -**Current focus (2026-11-05):** primitive editing and native SBS save/load. The old Rust -procedural library has been removed. The replacement includes 30 main-graph entries, 85 function -operations and three pattern node kinds. Start with **File → New → Atomic sample**. +**Current focus (2026-11-16):** node behavior, regression coverage and SBS save/load. The old Rust +procedural library has been removed. The replacement includes 29 main-graph entries, 85 function +operations and four pattern node kinds. Start with **File → New → Atomic sample**. See [the primitive workflow](docs/atomic-workflow.md) for usage, validation scope and limitations. -Reference-app rendering parity and full SBS library loading are still pending. +The [catalog status](docs/node-catalog-parity.md) records implemented behavior and remaining work. +Full numerical compatibility and arbitrary SBS interoperability remain unestablished. **Workspace:** `crates/{core, image, geom, nodes, eval, formats, engine, render, automation, ui-egui}` and `apps/{materialcraft, materialcraft-cli, materialcraft-web}`. The egui frontend is its own diff --git a/ROADMAP.md b/ROADMAP.md index 37dcf3eb..3fb8c5d6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,25 +1,29 @@ # MaterialCraft roadmap -**Current focus (2026-11-08):** native primitive editing, reusable SBS functions and interoperable save/load. +**Current focus (2026-11-16):** node behavior, regression coverage and interoperable save/load. -The old Rust procedural library has been removed. The main catalog has 30 entries: 26 native +The old Rust procedural library has been removed. The main catalog has 29 entries: 25 native primitives and four graph input/output items. Functions have 85 operations; pattern graphs have Quadrant, Switch, Iterate and Dot. See [the primitive workflow](docs/atomic-workflow.md) for usage and limits. -Earlier percentage estimates and node counts are superseded by this change. Reference-app -rendering parity and arbitrary SBS round trips have not been established. +Earlier percentage estimates and node counts are superseded by this change. Full numerical +compatibility and arbitrary SBS round trips have not been established. The +[catalog status](docs/node-catalog-parity.md) records available nodes, implemented corrections +and behavior that remains untested. ## Next steps -1. Verify the original atomic sample in the reference application -2. Compare primitive outputs and parameter semantics against reference results -3. Validate the converted standard library in the reference application and establish redistribution rights +1. Extend atomic sample and SBS interoperability coverage +2. Resolve the primitive, processor and map gaps in the catalog status +3. Validate the converted standard library and establish redistribution rights 4. Extend the SBS library beyond reusable functions to processing graphs ## Progress log | Date | What landed | |---|---| +| 2026-11-16 | Corrected six atomic nodes: filter kernels and Float32 arithmetic, rectangular scaling, independent tiling, channel selection and save/load, and empty Text/SVG backgrounds. [Behavior and validation](docs/atomic-parity-improvements.md) | +| 2026-11-15 | Corrected node defaults, typed unconnected inputs, missing-texture output and SBS serialization; updated catalog counts and remaining validation scope | | 2026-11-08 | Explorer folder hierarchy and package/folder/graph context menus, native SBS empty folders and resource paths, undoable copy/move/rename/remove, and package reload/save-copy actions | | 2026-11-08 | Portable `sbs://` function instances in the Library, preserved package folders and missing references, and a converted library retaining all 171 supplied function bodies (2,334 nodes); external runtime equivalence and redistribution rights remain unverified | | 2026-11-02 | Cross-app materials: `.mcmat` portable materials, Send to TextureCraft, input-node preview images (mesh maps from TextureCraft), live re-cooks from TextureCraft through the CLI | diff --git a/apps/materialcraft-web/Cargo.toml b/apps/materialcraft-web/Cargo.toml index 5cdd92ac..68221c9c 100644 --- a/apps/materialcraft-web/Cargo.toml +++ b/apps/materialcraft-web/Cargo.toml @@ -19,9 +19,9 @@ materialcraft-ui-egui = { workspace = true } log = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] -# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. +# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] } -# The SBS library's `resources/`, which the browser build downloads at startup. +# The SBS library's `resources/`, which the browser build downloads at startup materialcraft-formats = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" diff --git a/apps/materialcraft-web/src/main.rs b/apps/materialcraft-web/src/main.rs index 08b00ce3..26e2e849 100644 --- a/apps/materialcraft-web/src/main.rs +++ b/apps/materialcraft-web/src/main.rs @@ -33,6 +33,7 @@ mod tests { fn loading_page_offers_a_reload_when_startup_stalls() { let html = include_str!("../index.html"); let (_, hint) = html.split_once("

").expect("stalled-startup hint in the loading element"); + assert!(hint.contains("failed to") && hint.contains("Reload"), "{hint}"); assert!(html.contains("animation: materialcraft-stalled"), "the hint appears after a delay"); assert!(html.contains("id=\"materialcraft_canvas\"") && html.contains("data-cargo-profile=\"wasm-release\"")); @@ -44,6 +45,7 @@ mod tests { #[test] fn loading_page_ships_the_library_resources_beside_the_wasm() { let html = include_str!("../index.html"); + assert!(html.contains(r#""#), "{html}"); } } diff --git a/apps/materialcraft-web/src/web.rs b/apps/materialcraft-web/src/web.rs index 9198c881..850b8d84 100644 --- a/apps/materialcraft-web/src/web.rs +++ b/apps/materialcraft-web/src/web.rs @@ -23,6 +23,7 @@ pub fn start() { log::error!("no document"); return; }; + let result = match document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::().ok()) { Some(canvas) => run(canvas).await, None => Err(format!("the page has no ")), @@ -42,7 +43,7 @@ pub fn start() { } async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { - // The WebAssembly has downloaded and compiled when this runs. + // The WebAssembly has downloaded and compiled when this runs step(0.3, "Downloading the material library…").await; download_library().await; step(0.5, "Preparing a new package…").await; @@ -60,7 +61,8 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { options, Box::new(|cc| { let mut app = MaterialCraftApp::new(cc, session); - // One thread cooks in the browser: keep previews small. + + // One thread cooks in the browser, so keep previews small app.ui.prefs.preview_size = app.ui.prefs.preview_size.clamp(128, 256); Ok(Box::new(app)) }), @@ -86,7 +88,7 @@ async fn download_library() { .as_ref() .and_then(|abort| window.set_timeout_with_callback_and_timeout_and_arguments_0(abort.as_ref().unchecked_ref(), LIBRARY_DOWNLOAD_TIMEOUT_MS).ok()); - // Every request starts before the first is awaited, so they download in parallel + // Start every fetch before awaiting its response let requests: Vec<_> = library::external_assets() .iter() .map(|relative| { @@ -115,6 +117,7 @@ async fn fetch_bytes(request: wasm_bindgen_futures::JsFuture) -> Result, let buffer = response.array_buffer().map_err(|e| format!("{e:?}"))?; let buffer = wasm_bindgen_futures::JsFuture::from(buffer).await.map_err(|e| format!("{e:?}"))?; + Ok(js_sys::Uint8Array::new(&buffer).to_vec()) } @@ -128,8 +131,8 @@ async fn step(progress: f32, status: &str) { if let Some(el) = document.get_element_by_id(PROGRESS_ID) { let _ = el.set_attribute("value", &progress.to_string()); } - // A timer longer than a frame lets the browser paint the step before work resumes. Not - // `requestAnimationFrame`: it never fires in a background tab, which would stall startup. + + // A timer lets background tabs resume even without animation frames let promise = js_sys::Promise::new(&mut |resolve, _| { if let Some(w) = web_sys::window() { let _ = w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, 20); @@ -157,7 +160,8 @@ fn capture_app_shortcuts() { if let Err(e) = window.add_event_listener_with_callback_and_add_event_listener_options("keydown", on_key.as_ref().unchecked_ref(), &options) { log::warn!("couldn't take over the browser's shortcuts: {e:?}"); } - // The listener lives as long as the page. + + // The listener lives as long as the page on_key.forget(); } diff --git a/crates/automation/tests/normal_maps.rs b/crates/automation/tests/normal_maps.rs index aadac01f..c2ed7934 100644 --- a/crates/automation/tests/normal_maps.rs +++ b/crates/automation/tests/normal_maps.rs @@ -11,36 +11,50 @@ use serde_json::json; #[test] fn generated_normal_conventions_produce_the_same_surface_when_matched() { let height = Image::gray(32, 32, |x, y| ((x as f32 * 0.15).sin() + (y as f32 * 0.25).sin()) * 0.25 + 0.5); - let gl = height_to_normal(&height, 8.0, false, false, false); - let dx = height_to_normal(&height, 8.0, true, false, false); + let opengl_normal = height_to_normal(&height, 8.0, false, false, false); + let directx_normal = height_to_normal(&height, 8.0, true, false, false); let normal_node = materialcraft_engine::nodes::find("normal").unwrap(); - assert_eq!(normal_node.param("opengl").unwrap().default.as_bool(), Some(true)); + + assert_eq!(normal_node.param("opengl").unwrap().default.as_bool(), Some(false)); + let maps = |normal| Maps { normal: Some(normal), base_color: Some(Image::filled(4, 4, Kind::Color, [0.5, 0.5, 0.5, 1.0])), ..Maps::default() }; let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio")); let settings = Settings::default(); - assert!(!settings.normal_y_flip); - let expected = render(&scene, &maps(gl), &light, &settings, 64, 48); - let flipped = maps(dx); - let matched = render(&scene, &flipped, &light, &Settings { normal_y_flip: true, ..settings }, 64, 48); - assert!(expected.iter().zip(&matched).all(|(a, b)| a.abs_diff(*b) <= 1)); - let wrong = render(&scene, &flipped, &light, &settings, 64, 48); - assert!(expected.iter().zip(&wrong).filter(|(a, b)| a.abs_diff(**b) > 2).count() > 20); + let expected = render(&scene, &maps(directx_normal.clone()), &light, &Settings { normal_y_flip: true, ..settings }, 64, 48); + let matched = render(&scene, &maps(opengl_normal), &light, &Settings { normal_y_flip: false, ..settings }, 64, 48); + + assert!(expected.iter().zip(&matched).all(|(actual, expected)| actual.abs_diff(*expected) <= 1)); + + let default_output = render(&scene, &maps(directx_normal.clone()), &light, &settings, 64, 48); + + assert!(expected.iter().zip(&default_output).all(|(actual, expected)| actual.abs_diff(*expected) <= 1)); + + let mismatched = render(&scene, &maps(directx_normal), &light, &Settings { normal_y_flip: false, ..settings }, 64, 48); + + assert!(expected.iter().zip(&mismatched).filter(|(actual, expected)| actual.abs_diff(**expected) > 2).count() > 20); + assert!(settings.normal_y_flip); } #[test] fn headless_render_honors_the_normal_y_command() { - let mut s = new_session(); - s.preview_size = Some(64); - let node = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color": [0.5, 0.75, 1.0, 1.0]}})).unwrap()["id"].as_u64().unwrap(); - execute(&mut s, "graph.node.add", &json!({"def": "output", "connectFrom": {"node": node}, "params": {"usage": 1}})).unwrap(); - let mut h = Headless::new(s, Filesystem::Denied); + let mut session = new_session(); + session.preview_size = Some(64); + let node = execute(&mut session, "graph.node.add", &json!({"def": "uniform", "params": {"color": [0.5, 0.75, 1.0, 1.0]}})).unwrap()["id"].as_u64().unwrap(); + execute(&mut session, "graph.node.add", &json!({"def": "output", "connectFrom": {"node": node}, "params": {"usage": 1}})).unwrap(); + let mut headless = Headless::new(session, Filesystem::Denied); let options = RenderOptions { width: Some(64), height: Some(48), ..RenderOptions::default() }; - let gl = h.render_png(&options).unwrap().png; - execute(&mut h.session, "view.3d", &json!({"normalYFlip": true})).unwrap(); - let wrong = h.render_png(&options).unwrap().png; - assert_ne!(gl, wrong); - execute(&mut h.session, "graph.node.param", &json!({"id": node, "param": "color", "value": [0.5, 0.25, 1.0, 1.0]})).unwrap(); - assert_eq!(gl, h.render_png(&options).unwrap().png); - execute(&mut h.session, "view.3d.reset", &json!({})).unwrap(); - assert_eq!(wrong, h.render_png(&options).unwrap().png); + let directx_render = headless.render_png(&options).unwrap().png; + + execute(&mut headless.session, "view.3d", &json!({"normalYFlip": false})).unwrap(); + let opengl_render = headless.render_png(&options).unwrap().png; + + assert_ne!(directx_render, opengl_render); + + execute(&mut headless.session, "graph.node.param", &json!({"id": node, "param": "color", "value": [0.5, 0.25, 1.0, 1.0]})).unwrap(); + + assert_eq!(directx_render, headless.render_png(&options).unwrap().png); + + execute(&mut headless.session, "view.3d.reset", &json!({})).unwrap(); + + assert_eq!(opengl_render, headless.render_png(&options).unwrap().png); } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 6d553cf2..e9897960 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -56,7 +56,7 @@ impl Default for View3d { exposure: 0.0, height_scale: 0.04, height_level: 0.0, - normal_y_flip: false, + normal_y_flip: true, show_axis: false, show_grid: false, transparency: true, diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 274a88fb..30131cfa 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -29,7 +29,7 @@ pub(crate) fn specs() -> Vec { "3D view settings", [], None, - "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", + "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default true/DirectX), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", always, view3d ), @@ -60,109 +60,117 @@ pub(crate) fn specs() -> Vec { ] } -fn view2d(s: &mut Session, p: &J) -> Result { - // Validate the channel before applying any part of the request. - let channel = strp(p, "channel"); +fn view2d(session: &mut Session, params: &J) -> Result { + // Validate the channel before applying any part of the request + let channel = strp(params, "channel"); if channel.is_some_and(|c| !["rgba", "r", "g", "b", "a"].contains(&c)) { return Err(bad("view.2d", "`channel` is rgba, r, g, b or a")); } - if let Some(n) = u64p(p, "node") { - s.graph()?.node(NodeId(n)).map_err(|_| bad("view.2d", format!("no node {n}")))?; - s.view2d.node = Some(NodeId(n)); - s.view2d.port = 0; + + if let Some(node) = u64p(params, "node") { + session.graph()?.node(NodeId(node)).map_err(|_| bad("view.2d", format!("no node {node}")))?; + session.view2d.node = Some(NodeId(node)); + session.view2d.port = 0; } - if let Some(port) = u64p(p, "port") { - s.view2d.port = port as usize; + if let Some(port) = u64p(params, "port") { + session.view2d.port = port as usize; } - if let Some(t) = boolp(p, "tiled") { - s.view2d.tiled = t; + if let Some(tiled) = boolp(params, "tiled") { + session.view2d.tiled = tiled; } - if let Some(h) = boolp(p, "histogram") { - s.view2d.histogram = h; + if let Some(histogram) = boolp(params, "histogram") { + session.view2d.histogram = histogram; } if let Some(c) = channel { - s.view2d.channel = c.into(); + session.view2d.channel = c.into(); } - Ok(serde_json::to_value(&s.view2d).unwrap_or(J::Null)) + + Ok(serde_json::to_value(&session.view2d).unwrap_or(J::Null)) } -fn view3d(s: &mut Session, p: &J) -> Result { - // Validated up front so a bad target changes nothing. - let target = match p.get("target") { +fn view3d(session: &mut Session, params: &J) -> Result { + // Validate up front so a bad target changes nothing + let target = match params.get("target") { None => None, Some(t) => { let xyz: Option> = t.as_array().filter(|a| a.len() == 3).map(|a| a.iter().filter_map(J::as_f64).map(|f| f as f32).filter(|f| f.is_finite()).collect()); match xyz.as_deref() { - Some(&[x, y, z]) => Some(s.camera.clamp_target([x, y, z])), + Some(&[x, y, z]) => Some(session.camera.clamp_target([x, y, z])), _ => return Err(bad("view.3d", "`target` is [x, y, z]")), } } }; - // A rejected environment must not leave a new scene applied. - let environment = strp(p, "environment"); - if let Some(e) = environment - && !ENVIRONMENTS.iter().any(|(id, _)| *id == e) + + // A rejected environment must not leave a new scene applied + let environment = strp(params, "environment"); + if let Some(environment) = environment + && !ENVIRONMENTS.iter().any(|(id, _)| *id == environment) { - return Err(bad("view.3d", format!("unknown environment `{e}`"))); + return Err(bad("view.3d", format!("unknown environment `{environment}`"))); } - if let Some(sc) = strp(p, "scene") { - if sc == "custom" && s.custom_mesh.is_none() { + + if let Some(scene) = strp(params, "scene") { + if scene == "custom" && session.custom_mesh.is_none() { return Err(bad("view.3d", "no mesh is loaded: use view.3d.loadMesh")); } - let v = &mut s.view3d; - if sc != "custom" && !SCENES.iter().any(|(id, _)| *id == sc) { - return Err(bad("view.3d", format!("unknown scene `{sc}`"))); + + let view = &mut session.view3d; + if scene != "custom" && !SCENES.iter().any(|(id, _)| *id == scene) { + return Err(bad("view.3d", format!("unknown scene `{scene}`"))); } - v.scene = sc.into(); + + view.scene = scene.into(); } - let v = &mut s.view3d; - if let Some(e) = environment { - v.environment = e.into(); + + let view = &mut session.view3d; + if let Some(environment) = environment { + view.environment = environment.into(); } - if let Some(t) = f32p(p, "tiling") { - v.tiling = t.clamp(0.1, 64.0); + if let Some(tiling) = f32p(params, "tiling") { + view.tiling = tiling.clamp(0.1, 64.0); } - if let Some(t) = f32p(p, "yaw") { - v.yaw = t.rem_euclid(360.0); + if let Some(yaw) = f32p(params, "yaw") { + view.yaw = yaw.rem_euclid(360.0); } - if let Some(t) = f32p(p, "pitch") { - v.pitch = t.clamp(-89.0, 89.0); + if let Some(pitch) = f32p(params, "pitch") { + view.pitch = pitch.clamp(-89.0, 89.0); } - if let Some(t) = f32p(p, "distance") { - v.distance = t.clamp(1.2, 20.0); + if let Some(distance) = f32p(params, "distance") { + view.distance = distance.clamp(1.2, 20.0); } - if let Some(t) = target { - v.target = t; + if let Some(target) = target { + view.target = target; } - if let Some(t) = f32p(p, "envRotation") { - v.env_rotation = t.rem_euclid(360.0); + if let Some(env_rotation) = f32p(params, "envRotation") { + view.env_rotation = env_rotation.rem_euclid(360.0); } - if let Some(t) = f32p(p, "exposure") { - v.exposure = t.clamp(-10.0, 10.0); + if let Some(exposure) = f32p(params, "exposure") { + view.exposure = exposure.clamp(-10.0, 10.0); } - if let Some(t) = f32p(p, "heightScale") { - v.height_scale = t.clamp(0.0, 0.5); + if let Some(height_scale) = f32p(params, "heightScale") { + view.height_scale = height_scale.clamp(0.0, 0.5); } - if let Some(t) = f32p(p, "heightLevel") { - v.height_level = t.clamp(0.0, 1.0); + if let Some(height_level) = f32p(params, "heightLevel") { + view.height_level = height_level.clamp(0.0, 1.0); } - if let Some(flip) = boolp(p, "normalYFlip") { - v.normal_y_flip = flip; + if let Some(flip) = boolp(params, "normalYFlip") { + view.normal_y_flip = flip; } - if let Some(b) = boolp(p, "axis") { - v.show_axis = b; + if let Some(show_axis) = boolp(params, "axis") { + view.show_axis = show_axis; } - if let Some(b) = boolp(p, "grid") { - v.show_grid = b; + if let Some(show_grid) = boolp(params, "grid") { + view.show_grid = show_grid; } - if let Some(b) = boolp(p, "transparency") { - v.transparency = b; + if let Some(transparency) = boolp(params, "transparency") { + view.transparency = transparency; } - if let Some(b) = boolp(p, "alphaView") { - v.alpha_view = b; + if let Some(alpha_view) = boolp(params, "alphaView") { + view.alpha_view = alpha_view; } - Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null)) + + Ok(serde_json::to_value(&session.view3d).unwrap_or(J::Null)) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/tests/it/atomics.rs b/crates/engine/tests/it/atomics.rs index 968fab93..dc5d7ac1 100644 --- a/crates/engine/tests/it/atomics.rs +++ b/crates/engine/tests/it/atomics.rs @@ -170,16 +170,21 @@ fn exposed_parameter_binding_remains_live_after_saving() { let mut session = Session::new(atomic_sample().unwrap()); let blur = session.graph().unwrap().nodes.iter().find(|node| node.def == "blur").unwrap().id; execute(&mut session, "graph.exposed.add", &json!({"id": "radius", "bind": {"node": blur.0, "param": "intensity"}})).unwrap(); - execute(&mut session, "graph.exposed.set", &json!({"id": "radius", "value": 4.0})).unwrap(); + + // At the 32-pixel preview, strength 4 covers only the center texel + execute(&mut session, "graph.exposed.set", &json!({"id": "radius", "value": 8.0})).unwrap(); let bytes = write_sbs(&session.pkg).unwrap(); let loaded = read_sbs(&bytes, "exposed.sbs", &|_| None).unwrap(); + assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings); + let mut loaded = Session::new(loaded.pkg); loaded.preview_size = Some(32); loaded.cook(); let before = loaded.cooked.image(blur, 0).unwrap().data.clone(); execute(&mut loaded, "graph.exposed.set", &json!({"id": "radius", "value": 0.0})).unwrap(); loaded.cook(); + assert_ne!(before, loaded.cooked.image(blur, 0).unwrap().data); } diff --git a/crates/engine/tests/it/graph_interaction.rs b/crates/engine/tests/it/graph_interaction.rs index e6575f97..974d030d 100644 --- a/crates/engine/tests/it/graph_interaction.rs +++ b/crates/engine/tests/it/graph_interaction.rs @@ -131,6 +131,7 @@ fn fx_map_starts_with_a_quadrant_and_grows_image_inputs_as_connected() { let mut session = new_session(); session.preview_size = Some(16); let source = add(&mut session, "uniform"); + execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap(); execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color_mode", "value": false})).unwrap(); let owner = add(&mut session, "fx_map"); let Value::PatternGraph(pattern) = &session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!("missing default pattern") }; @@ -204,24 +205,32 @@ fn terminal_outputs_cook_and_round_trip_without_source_pins() { let mut session = new_session(); session.preview_size = Some(16); let source = add(&mut session, "uniform"); + execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap(); let output = add(&mut session, "output"); execute(&mut session, "graph.connect", &json!({"from": source.0, "to": output.0})).unwrap(); + assert_eq!(session.input_ports(output), vec!["input"]); assert!(session.output_ports(output).is_empty()); + let before = session.pkg.clone(); + assert!(execute(&mut session, "graph.connect", &json!({"from": output.0, "to": source.0})).is_err()); assert_eq!(session.pkg, before); let read = read_sbs(&write_sbs(&session.pkg).unwrap(), "terminal_output.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let mut loaded = Session::new(read.pkg); loaded.preview_size = Some(16); loaded.cook(); let output = loaded.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id; + assert!(loaded.output_ports(output).is_empty()); assert!(loaded.cooked.nodes[&output].error.is_none()); assert!((loaded.cooked.image(output, 0).unwrap().mean()[0] - 0.5).abs() < 1e-5); execute(&mut loaded, "view.2d", &json!({"node": output.0})).unwrap(); + assert_eq!(loaded.view2d_image().unwrap().0, output); } @@ -234,6 +243,7 @@ fn processors_sample_dynamic_image_inputs_after_sbs_round_trip() { session.graph_mut().unwrap().format = materialcraft_engine::core::OutputFormat::F32; session.preview_size = Some(16); let source = add(&mut session, "uniform"); + execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap(); let processor = add(&mut session, definition); for index in 0..6 { execute(&mut session, "graph.connect", &json!({"from": source.0, "to": processor.0, "toPort": format!("input{index}")})).unwrap(); @@ -273,8 +283,10 @@ fn processors_sample_dynamic_image_inputs_after_sbs_round_trip() { fn background_pins_preserve_connected_images_through_sbs() { let mut session = new_session(); session.preview_size = Some(16); - let source = add(&mut session, "uniform"); for definition in ["text", "svg"] { + let source = add(&mut session, "uniform"); + execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap(); + execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color_mode", "value": definition == "svg"})).unwrap(); let target = add(&mut session, definition); if definition == "text" { execute(&mut session, "graph.node.param", &json!({"id": target.0, "param": "text", "value": ""})).unwrap(); @@ -283,13 +295,16 @@ fn background_pins_preserve_connected_images_through_sbs() { } let read = read_sbs(&write_sbs(&session.pkg).unwrap(), "backgrounds.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let mut loaded = Session::new(read.pkg); loaded.preview_size = Some(16); loaded.cook(); for node in loaded.graph().unwrap().nodes.iter().filter(|node| matches!(node.def.as_str(), "text" | "svg")) { - assert_eq!(loaded.input_ports(node.id), vec!["background"]); let image = loaded.cooked.image(node.id, 0).unwrap(); + + assert_eq!(loaded.input_ports(node.id), vec!["background"]); assert_eq!(image.is_gray(), node.def == "text"); assert!((image.mean()[0] - 0.5).abs() < 1e-5); assert!(loaded.cooked.nodes[&node.id].error.is_none()); diff --git a/crates/engine/tests/it/normal_maps.rs b/crates/engine/tests/it/normal_maps.rs index 42ada40c..fc31b908 100644 --- a/crates/engine/tests/it/normal_maps.rs +++ b/crates/engine/tests/it/normal_maps.rs @@ -2,16 +2,23 @@ use materialcraft_engine::{View3d, execute, new_session}; use serde_json::json; #[test] -fn normal_map_convention_is_inspectable_and_resets_to_opengl() { - let mut s = new_session(); - assert!(!s.view3d.normal_y_flip); - assert_eq!(materialcraft_engine::nodes::find("normal").unwrap().param("opengl").unwrap().default.as_bool(), Some(true)); - execute(&mut s, "view.3d", &json!({"normalYFlip": true})).unwrap(); - let inspection = execute(&mut s, "session.inspect", &json!({})).unwrap(); - assert_eq!(inspection["view3d"]["normalYFlip"], true); - let saved = serde_json::to_value(&s.view3d).unwrap(); - assert!(serde_json::from_value::(saved).unwrap().normal_y_flip); - assert!(!serde_json::from_value::(json!({"scene": "sphere"})).unwrap().normal_y_flip); - execute(&mut s, "view.3d.reset", &json!({})).unwrap(); - assert!(!s.view3d.normal_y_flip); +fn normal_map_convention_is_inspectable_and_resets_to_directx() { + let mut session = new_session(); + + assert!(session.view3d.normal_y_flip); + assert_eq!(materialcraft_engine::nodes::find("normal").unwrap().param("opengl").unwrap().default.as_bool(), Some(false)); + + execute(&mut session, "view.3d", &json!({"normalYFlip": false})).unwrap(); + let inspection = execute(&mut session, "session.inspect", &json!({})).unwrap(); + + assert_eq!(inspection["view3d"]["normalYFlip"], false); + + let saved = serde_json::to_value(&session.view3d).unwrap(); + + assert!(!serde_json::from_value::(saved).unwrap().normal_y_flip); + assert!(serde_json::from_value::(json!({"scene": "sphere"})).unwrap().normal_y_flip); + + execute(&mut session, "view.3d.reset", &json!({})).unwrap(); + + assert!(session.view3d.normal_y_flip); } diff --git a/crates/engine/tests/it/reset_drivers.rs b/crates/engine/tests/it/reset_drivers.rs index 8aaa9354..91cb2687 100644 --- a/crates/engine/tests/it/reset_drivers.rs +++ b/crates/engine/tests/it/reset_drivers.rs @@ -13,6 +13,7 @@ fn setup() -> (Session, NodeId) { let mut s = new_session(); s.preview_size = Some(32); let source = run(&mut s, "graph.node.add", json!({"def": "uniform"}))["id"].as_u64().unwrap(); + run(&mut s, "graph.node.param", json!({"id": source, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})); let levels = NodeId(run(&mut s, "graph.node.add", json!({"def": "levels", "connectFrom": {"node": source}}))["id"].as_u64().unwrap()); (s, levels) } diff --git a/crates/engine/tests/it/sbs_functions.rs b/crates/engine/tests/it/sbs_functions.rs index f0f1a9cc..b27eab7c 100644 --- a/crates/engine/tests/it/sbs_functions.rs +++ b/crates/engine/tests/it/sbs_functions.rs @@ -30,7 +30,9 @@ fn imported_expression_cooks_follows_inputs_and_survives_undo_and_save() { s.pkg = imported.pkg; s.pkg.graphs[0].format = materialcraft_engine::core::OutputFormat::F32; let levels = s.graph().unwrap().nodes[0].id; - let uniform = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color_mode": false}})).unwrap()["id"].as_u64().unwrap(); + let uniform = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color_mode": false, "color": [0.5, 0.5, 0.5, 1.0]}})).unwrap()["id"] + .as_u64() + .unwrap(); execute(&mut s, "graph.connect", &json!({"from": uniform, "to": levels.0})).unwrap(); let mean = |s: &mut materialcraft_engine::Session| { let levels = s.graph().unwrap().nodes.iter().find(|node| node.def == "levels").unwrap().id; diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index d46abadf..b4402612 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -265,21 +265,28 @@ fn dynamic_parameters_follow_graph_inputs() { let mut session = sample_session(); run(&mut session, "file.new", json!({"template": "empty"})); - let owner = NodeId(run(&mut session, "graph.node.add", json!({"def": "uniform", "params": {"color_mode": false}}))["id"].as_u64().unwrap()); + let owner = NodeId( + run(&mut session, "graph.node.add", json!({"def": "uniform", "params": {"color_mode": false, "color": Value::Color([0.5, 0.5, 0.5, 1.0])}}))["id"] + .as_u64() + .unwrap(), + ); run(&mut session, "graph.exposed.add", json!({"id": "level", "default": Value::Float4([0.25; 4])})); let function = FunctionGraph::input("level", ValueType::Float4); run(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": function})); let mean = session.cook().image(owner, 0).unwrap().mean()[0]; + assert!((mean - 0.25).abs() < 1e-4, "{mean}"); run(&mut session, "graph.exposed.set", json!({"id": "level", "value": Value::Float4([0.75; 4])})); let mean = session.cook().image(owner, 0).unwrap().mean()[0]; + assert!((mean - 0.75).abs() < 1e-4); // Removing the function restores the plain value assert!(execute(&mut session, "graph.node.function", &json!({"id": owner, "param": "nope"})).is_err()); run(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "remove": true})); let mean = session.cook().image(owner, 0).unwrap().mean()[0]; + assert!((mean - 0.5).abs() < 0.05); } diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index 4a098b46..b18a5093 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -114,7 +114,9 @@ pub(crate) fn cook_node( return fail(error, 0); } - if !node.functions.is_empty() || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map" | "transformation") { + if !node.functions.is_empty() + || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map" | "transformation" | "blur" | "directional_blur" | "sharpen") + { base.variables(variables.to_mut()); } diff --git a/crates/eval/tests/filter_tiling.rs b/crates/eval/tests/filter_tiling.rs new file mode 100644 index 00000000..2978b00f --- /dev/null +++ b/crates/eval/tests/filter_tiling.rs @@ -0,0 +1,41 @@ +use materialcraft_core::{Graph, OutputFormat, Package, ParameterInheritance, Value}; +use materialcraft_eval::{Cache, Options, cook}; +use materialcraft_image::Image; +use std::sync::Mutex; + +#[test] +fn atomic_filters_wrap_only_the_requested_axes_and_invalidate_cache() { + for operation in ["blur", "directional_blur", "sharpen"] { + let mut graph = Graph::new("Filter boundaries"); + graph.size = [4; 2]; + graph.format = OutputFormat::F32; + graph.tiling_mode = ParameterInheritance::Absolute; + let input = graph.add_node("input_grayscale", [0.0; 2]); + graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text("source".into())); + let filter = graph.add_node(operation, [100.0, 0.0]); + graph.node_mut(filter).unwrap().params.insert("intensity".into(), Value::Float(if operation == "sharpen" { 1.0 } else { 16.0 })); + graph.connect(input, "output", filter, "input").unwrap(); + let mut package = Package::new("Filter boundaries"); + package.graphs.push(graph); + let resource = |_: &str| None; + let mut options = Options::new(&resource); + options.inputs.insert("source".into(), Image::gray(16, 16, |x, y| if x == 0 && y == 0 { 0.5625 } else { 0.5 })); + let cache = Mutex::new(Cache::default()); + + for tiling in [[false, false], [true, false], [false, true], [true, true]] { + package.graphs[0].tiling = tiling; + + let cooked = cook(&package, 0, &options, &cache); + let image = cooked.image(filter, 0).unwrap(); + + assert_eq!(cooked.nodes[&filter].error, None); + assert!(!cooked.nodes[&filter].cached); + assert_eq!(image.get_gray(15, 0, false) != 0.5, tiling[0], "{operation}, x, {tiling:?}"); + assert_eq!(image.get_gray(0, 15, false) != 0.5, tiling[1] && operation != "directional_blur", "{operation}, y, {tiling:?}"); + + let cached = cook(&package, 0, &options, &cache); + + assert!(cached.nodes[&filter].cached); + } + } +} diff --git a/crates/formats/build.rs b/crates/formats/build.rs index d4a62952..2fdb8060 100644 --- a/crates/formats/build.rs +++ b/crates/formats/build.rs @@ -57,8 +57,8 @@ fn main() -> Result<()> { let mut files = Vec::new(); scan(&root, Path::new(""), &mut files)?; - // Web hosts cap single files (Cloudflare Pages at 25 MiB) and the bitmaps would push the wasm past it - // The browser build downloads `resources/` from beside the wasm instead + // Keep already-compressed bitmaps out of the size-capped wasm + // The browser downloads them from beside the wasm let browser = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|arch| arch == "wasm32"); let (downloaded, files): (Vec<_>, Vec<_>) = files.into_iter().partition(|relative| browser && relative.starts_with("resources")); let mut external = Vec::new(); @@ -95,5 +95,6 @@ fn main() -> Result<()> { } downloads.push_str("];\n"); std::fs::write(out.join("sbs_assets.rs"), format!("{assets}{packages}{downloads}"))?; + Ok(()) } diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 3b6636f0..e75974a3 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -27,6 +27,7 @@ fn check_vertex_bound(current: usize, added: usize) -> Result<()> { if current.checked_add(added).is_none_or(|total| total > MAX_VERTICES) { return Err(bad("the mesh is too large")); } + Ok(()) } @@ -48,22 +49,25 @@ fn finish(positions: Vec, normals: Option>, uvs: Vec, indi if positions.iter().any(|p| !p.is_finite()) { return Err(bad("the mesh has non-finite (NaN or infinite) positions")); } + if normals.iter().flatten().any(|n| !n.is_finite()) { return Err(bad("the mesh has non-finite (NaN or infinite) normals")); } + if uvs.iter().any(|u| !u.is_finite()) { return Err(bad("the mesh has non-finite (NaN or infinite) UVs")); } + Mesh::from_parts(positions, normals, uvs, indices, "material").map_err(|e| bad(e.to_string())) } /// Parse a mesh file by extension. pub fn load_mesh(name: &str, bytes: &[u8]) -> Result { - let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + let extension = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); let limits = limits(); - // Only self-contained files: a reference to another file (an MTL library, an external - // buffer) is declined, as the view has no folder to look in. - let scene = match ext.as_str() { + + // The view has no source folder for external file references + let scene = match extension.as_str() { "obj" => craft_mesh::obj::read(bytes, &limits, &mut craft_mesh::no_external).map_err(|e| read_error("OBJ", e))?, "glb" | "gltf" => craft_mesh::gltf::read(bytes, &limits, &mut craft_mesh::no_external).map_err(|e| read_error("glTF", e))?, other => return Err(bad(format!("unsupported mesh format `{other}` (OBJ, glTF or GLB)"))), @@ -72,19 +76,24 @@ pub fn load_mesh(name: &str, bytes: &[u8]) -> Result { if mesh.indices.is_empty() || mesh.positions.is_empty() { return Err(bad("the mesh has no triangles")); } + if mesh.triangle_count() > MAX_TRIANGLES { return Err(bad(format!("the mesh has {} triangles (limit {MAX_TRIANGLES})", mesh.triangle_count()))); } + if mesh.uvs.len() != mesh.positions.len() || mesh.uvs.iter().all(|u| *u == mesh.uvs[0]) { - // No usable UVs: a box projection keeps materials tiling across the surface. + // No usable UVs: a box projection keeps materials tiling across the surface mesh.uvs = box_uvs(&mesh); } + mesh.normalize_to(1.0); if mesh.normals.len() != mesh.positions.len() { mesh.compute_normals(); } + mesh.compute_tangents(); mesh.validate().map_err(|e| bad(e.to_string()))?; + Ok(mesh) } @@ -93,15 +102,18 @@ pub fn load_mesh(name: &str, bytes: &[u8]) -> Result { /// damaged mesh is reported rather than shown with holes. fn non_finite(scene: &Scene) -> Option<&'static str> { let f64s = |v: &[[f64; 3]]| v.iter().flatten().any(|x| !x.is_finite()); - if scene.meshes.iter().any(|m| f64s(&m.positions)) { + if scene.meshes.iter().any(|mesh| f64s(&mesh.positions)) { return Some("positions"); } - if scene.meshes.iter().any(|m| f64s(&m.normals)) { + + if scene.meshes.iter().any(|mesh| f64s(&mesh.normals)) { return Some("normals"); } - if scene.meshes.iter().flat_map(|m| m.uv_sets.first()).any(|s| s.iter().flatten().any(|x| !x.is_finite())) { + + if scene.meshes.iter().flat_map(|mesh| mesh.uv_sets.first()).any(|s| s.iter().flatten().any(|x| !x.is_finite())) { return Some("UVs"); } + None } @@ -116,6 +128,7 @@ fn scene_mesh(scene: &Scene, limits: &Limits) -> Result { if let Some(what) = non_finite(scene) { return Err(bad(format!("the mesh has non-finite (NaN or infinite) {what}"))); } + let instances = scene.instances(limits).map_err(|e| read_error("mesh", e))?; let mut world_positions = Vec::new(); let mut normals = Vec::new(); @@ -126,16 +139,16 @@ fn scene_mesh(scene: &Scene, limits: &Limits) -> Result { for (index, world) in instances { let Some(mesh) = scene.meshes.get(index) else { continue }; let unified = mesh.unified(); - let n = unified.positions.len(); - check_vertex_bound(world_positions.len(), n)?; + let vertex_count = unified.positions.len(); + check_vertex_bound(world_positions.len(), vertex_count)?; let Ok(base) = u32::try_from(world_positions.len()) else { return Err(bad("the mesh is too large")) }; world_positions.extend(unified.positions.iter().map(|p| craft_mesh::transform_point(&world, *p))); - if unified.normals.len() == n { + if unified.normals.len() == vertex_count { normals.extend(unified.normals.iter().map(|q| to_vec3(craft_mesh::transform_normal(&world, *q)))); } else { all_normals = false; } - if unified.uvs.len() == n { + if unified.uvs.len() == vertex_count { uvs.extend(unified.uvs.iter().map(|t| Vec2::from(*t))); } else { all_uvs = false; @@ -145,16 +158,20 @@ fn scene_mesh(scene: &Scene, limits: &Limits) -> Result { if indices.len() / 3 >= MAX_TRIANGLES { return Err(bad("the mesh is too large")); } + let [a, b, c] = tri.map(|i| i.saturating_add(base)); indices.extend(if mirror { [a, c, b] } else { [a, b, c] }); } } + let positions = to_f32_positions(&world_positions); let normals = (all_normals && normals.len() == positions.len()).then_some(normals); - // Partial UVs would hide the gap from the projection fallback: drop them all instead. + + // Partial UVs would hide the gap from the projection fallback: drop them all instead if !all_uvs || uvs.len() != positions.len() { uvs.clear(); } + finish(positions, normals, uvs, indices) } @@ -166,6 +183,7 @@ fn to_f32_positions(world: &[[f64; 3]]) -> Vec { if world.is_empty() { return Vec::new(); } + let mut lo = [f64::INFINITY; 3]; let mut hi = [f64::NEG_INFINITY; 3]; for p in world { @@ -212,41 +230,45 @@ mod tests { #[test] fn obj_quad_loads_with_uvs_and_tangents() { let obj = b"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; - let m = load_mesh("quad.obj", obj).unwrap(); - assert_eq!(m.triangle_count(), 2); - assert_eq!(m.tangents.len(), m.positions.len()); - assert!(m.radius() <= 1.0 + 1e-4); - // A mesh without UVs gets projected ones. - let m = load_mesh("tri.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n").unwrap(); - assert!(m.uvs.iter().any(|u| *u != m.uvs[0])); + let mesh = load_mesh("quad.obj", obj).unwrap(); + + assert_eq!(mesh.triangle_count(), 2); + assert_eq!(mesh.tangents.len(), mesh.positions.len()); + assert!(mesh.radius() <= 1.0 + 1e-4); + + // A mesh without UVs gets projected ones + let mesh = load_mesh("tri.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n").unwrap(); + + assert!(mesh.uvs.iter().any(|u| *u != mesh.uvs[0])); } - /// A glTF with 4 vertices (positions given by `pos`, optional UVs) and the given indices. - fn gltf_json(pos: [[f32; 3]; 4], uvs: Option<[[f32; 2]; 4]>, idx: &[u16]) -> Vec { + /// A glTF with 4 vertices (positions given by `positions`, optional UVs) and the given indices. + fn gltf_json(positions: [[f32; 3]; 4], uvs: Option<[[f32; 2]; 4]>, indices: &[u16]) -> Vec { use base64::Engine as _; - let mut buf: Vec = pos.iter().flatten().flat_map(|f| f.to_le_bytes()).collect(); - let uv_off = buf.len(); + let mut buffer: Vec = positions.iter().flatten().flat_map(|f| f.to_le_bytes()).collect(); + let uv_offset_bytes = buffer.len(); if let Some(uvs) = uvs { - buf.extend(uvs.iter().flatten().flat_map(|f| f.to_le_bytes())); + buffer.extend(uvs.iter().flatten().flat_map(|f| f.to_le_bytes())); } - let idx_off = buf.len(); - buf.extend(idx.iter().flat_map(|i| i.to_le_bytes())); - let b64 = base64::engine::general_purpose::STANDARD.encode(&buf); + let index_offset_bytes = buffer.len(); + buffer.extend(indices.iter().flat_map(|i| i.to_le_bytes())); + let encoded_buffer = base64::engine::general_purpose::STANDARD.encode(&buffer); let uv_attr = if uvs.is_some() { r#","TEXCOORD_0":1"# } else { "" }; - let uv_view = if uvs.is_some() { format!(r#"{{"buffer":0,"byteOffset":{uv_off},"byteLength":32}},"#) } else { String::new() }; + let uv_view = if uvs.is_some() { format!(r#"{{"buffer":0,"byteOffset":{uv_offset_bytes},"byteLength":32}},"#) } else { String::new() }; let uv_acc = if uvs.is_some() { r#"{"bufferView":1,"componentType":5126,"count":4,"type":"VEC2"},"# } else { "" }; - // View/accessor layout: with UVs, views are [pos, uv, idx] and accessors [pos, uv, idx]. + + // View/accessor layout: with UVs, views are [positions, uv, indices] and accessors [positions, uv, indices] let idx_view = if uvs.is_some() { 2 } else { 1 }; let idx_acc = if uvs.is_some() { 2 } else { 1 }; format!( r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}], "meshes":[{{"primitives":[{{"attributes":{{"POSITION":0{uv_attr}}},"indices":{idx_acc}}}]}}], "accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{uv_acc}{{"bufferView":{idx_view},"componentType":5123,"count":{},"type":"SCALAR"}}], -"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{uv_view}{{"buffer":0,"byteOffset":{idx_off},"byteLength":{}}}], -"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#, - idx.len(), - idx.len() * 2, - buf.len() +"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{uv_view}{{"buffer":0,"byteOffset":{index_offset_bytes},"byteLength":{}}}], +"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{encoded_buffer}"}}]}}"#, + indices.len(), + indices.len() * 2, + buffer.len() ) .into_bytes() } @@ -262,69 +284,72 @@ mod tests { obj.push_str("f 1 2 3\n"); let e = load_mesh("excess.obj", obj.as_bytes()).unwrap_err(); + assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}"); } #[test] fn gltf_primitives_sharing_a_large_accessor_stay_bounded() { use base64::Engine as _; - // One position accessor of 100_000 vertices, referenced by 121 - // primitives: copied once per primitive it would exceed MAX_VERTICES. - // Only the vertices the triangles use are kept, so the view gets 3. + + // Shared accessors must count only vertices used by triangles const COUNT: usize = 100_000; - let mut buf = vec![0u8; COUNT * 12]; - // Give the referenced triangle non-degenerate positions. + let mut buffer = vec![0u8; COUNT * 12]; + + // Give the referenced triangle non-degenerate positions for (i, v) in [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]].iter().enumerate() { - buf[i * 12..i * 12 + 12].copy_from_slice(&v.iter().flat_map(|f| f.to_le_bytes()).collect::>()); + buffer[i * 12..i * 12 + 12].copy_from_slice(&v.iter().flat_map(|f| f.to_le_bytes()).collect::>()); } - buf.extend([0u16, 1, 2].iter().flat_map(|i| i.to_le_bytes())); - let b64 = base64::engine::general_purpose::STANDARD.encode(&buf); - let prim = r#"{"attributes":{"POSITION":0},"indices":1}"#; - let prims = (0..121).map(|_| prim).collect::>().join(","); + buffer.extend([0u16, 1, 2].iter().flat_map(|i| i.to_le_bytes())); + let encoded_buffer = base64::engine::general_purpose::STANDARD.encode(&buffer); + let primitive = r#"{"attributes":{"POSITION":0},"indices":1}"#; + let primitives = (0..121).map(|_| primitive).collect::>().join(","); let gltf = format!( r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}], -"meshes":[{{"primitives":[{prims}]}}], +"meshes":[{{"primitives":[{primitives}]}}], "accessors":[{{"bufferView":0,"componentType":5126,"count":{COUNT},"type":"VEC3","min":[0.0,0.0,0.0],"max":[1.0,1.0,0.0]}},{{"bufferView":1,"componentType":5123,"count":3,"type":"SCALAR"}}], "bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":{}}},{{"buffer":0,"byteOffset":{},"byteLength":6}}], -"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#, +"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{encoded_buffer}"}}]}}"#, COUNT * 12, COUNT * 12, - buf.len() + buffer.len() ); - let m = load_mesh("shared.gltf", gltf.as_bytes()).unwrap(); - assert_eq!(m.positions.len(), 3); - assert_eq!(m.triangle_count(), 121); + let mesh = load_mesh("shared.gltf", gltf.as_bytes()).unwrap(); + + assert_eq!(mesh.positions.len(), 3); + assert_eq!(mesh.triangle_count(), 121); } #[test] fn obj_non_finite_normals_and_uvs_never_reach_the_mesh() { - // The shared OBJ reader drops a corner's NaN normal or UV; the view then computes normals - // and projects UVs, so nothing non-finite is drawn. + // Dropped invalid OBJ attributes are replaced with finite fallbacks for obj in [&b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvn nan 0 1\nf 1//1 2//1 3//1\n"[..], &b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvt nan 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"[..]] { - let m = load_mesh("x.obj", obj).unwrap(); - assert!(m.normals.iter().all(|n| n.is_finite()) && m.uvs.iter().all(|u| u.is_finite()), "{m:?}"); + let mesh = load_mesh("x.obj", obj).unwrap(); + + assert!(mesh.normals.iter().all(|n| n.is_finite()) && mesh.uvs.iter().all(|u| u.is_finite()), "{mesh:?}"); } - // A triangle on a NaN position is dropped; with nothing left the file is refused. + + // A triangle on a NaN position is dropped; with nothing left the file is refused assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv nan 1 0\nf 1 2 3\n").is_err()); } /// [`QUAD`] with the given vertex normals, placed by one node. fn gltf_with_normals(normals: [[f32; 3]; 4]) -> Vec { use base64::Engine as _; - let idx: [u16; 6] = [0, 1, 2, 0, 2, 3]; - let mut buf: Vec = QUAD.iter().flatten().flat_map(|f| f.to_le_bytes()).collect(); - buf.extend(normals.iter().flatten().flat_map(|f| f.to_le_bytes())); - buf.extend(idx.iter().flat_map(|i| i.to_le_bytes())); - let b64 = base64::engine::general_purpose::STANDARD.encode(&buf); + let indices: [u16; 6] = [0, 1, 2, 0, 2, 3]; + let mut buffer: Vec = QUAD.iter().flatten().flat_map(|f| f.to_le_bytes()).collect(); + buffer.extend(normals.iter().flatten().flat_map(|f| f.to_le_bytes())); + buffer.extend(indices.iter().flat_map(|i| i.to_le_bytes())); + let encoded_buffer = base64::engine::general_purpose::STANDARD.encode(&buffer); format!( r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}], "meshes":[{{"primitives":[{{"attributes":{{"POSITION":0,"NORMAL":1}},"indices":2}}]}}], "accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{{"bufferView":1,"componentType":5126,"count":4,"type":"VEC3"}},{{"bufferView":2,"componentType":5123,"count":6,"type":"SCALAR"}}], "bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{{"buffer":0,"byteOffset":48,"byteLength":48}},{{"buffer":0,"byteOffset":96,"byteLength":12}}], -"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#, - buf.len() +"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{encoded_buffer}"}}]}}"#, + buffer.len() ) .into_bytes() } @@ -333,6 +358,7 @@ mod tests { fn placed(gltf: Vec, node: &str) -> Vec { let base = String::from_utf8(gltf).unwrap(); let out = base.replace(r#""nodes":[{"mesh":0}]"#, &format!(r#""nodes":[{node}]"#)); + assert_ne!(base, out, "the node was not replaced"); out.into_bytes() } @@ -341,24 +367,28 @@ mod tests { fn gltf_non_finite_normals_are_rejected() { let mut nan_normals = [[0.0f32, 0.0, 1.0]; 4]; nan_normals[2][0] = f32::NAN; + assert!(load_mesh("x.gltf", &gltf_with_normals(nan_normals)).is_err()); + let mut inf_normals = [[0.0f32, 0.0, 1.0]; 4]; inf_normals[1][2] = f32::INFINITY; + assert!(load_mesh("x.gltf", &gltf_with_normals(inf_normals)).is_err()); } #[test] fn a_far_translation_keeps_the_quads_shape() { - // 2^25: an f32 ULP at this magnitude is 4, so a unit quad converted in world space - // would collapse to a point before normalize_to runs. + // At 2^25, f32 conversion before centering would collapse the unit quad let local = load_mesh("quad.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3])).unwrap(); let far = 33_554_432.0; let placed = placed(gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3]), &format!(r#"{{"mesh":0,"translation":[{far},{far},0]}}"#)); let distant = load_mesh("far.gltf", &placed).unwrap(); + + let local_extent = extent(&local); + let distant_extent = extent(&distant); + assert_eq!(distant.triangle_count(), local.triangle_count()); - let local_ext = extent(&local); - let distant_ext = extent(&distant); - assert!((distant_ext - local_ext).length() < 1e-4, "local={local_ext} far={distant_ext}"); + assert!((distant_extent - local_extent).length() < 1e-4, "local={local_extent} far={distant_extent}"); for (a, b) in local.positions.iter().zip(&distant.positions) { assert!(a.distance(*b) < 1e-4, "local={a} far={b}"); } @@ -366,48 +396,56 @@ mod tests { #[test] fn normals_follow_a_non_uniform_scale_by_the_inverse_transpose() { - // Stretched twice along x, a (1,1,0) normal leans towards y: (0.5,1,0), normalised. + // Stretched twice along x, a (1,1,0) normal leans towards y: (0.5,1,0), normalised let gltf = placed(gltf_with_normals([[1.0, 1.0, 0.0]; 4]), r#"{"mesh":0,"scale":[2,1,1]}"#); - let m = load_mesh("x.gltf", &gltf).unwrap(); + let mesh = load_mesh("x.gltf", &gltf).unwrap(); let want = Vec3::new(0.5, 1.0, 0.0).normalize(); - assert!(m.normals.iter().all(|n| n.distance(want) < 1e-5), "{:?}", m.normals); + + assert!(mesh.normals.iter().all(|n| n.distance(want) < 1e-5), "{:?}", mesh.normals); } #[test] fn a_mirrored_placement_keeps_its_triangles_facing_out() { let gltf = placed(gltf_with_normals([[0.0, 0.0, 1.0]; 4]), r#"{"mesh":0,"scale":[-1,1,1]}"#); - let m = load_mesh("x.gltf", &gltf).unwrap(); - for tri in m.indices.chunks(3) { - let [a, b, c] = [0, 1, 2].map(|k| m.positions[tri[k] as usize]); + let mesh = load_mesh("x.gltf", &gltf).unwrap(); + for tri in mesh.indices.chunks(3) { + let [a, b, c] = [0, 1, 2].map(|k| mesh.positions[tri[k] as usize]); let face = (b - a).cross(c - a); - assert!(face.dot(m.normals[tri[0] as usize]) > 0.0, "triangle {tri:?} faces in"); + + assert!(face.dot(mesh.normals[tri[0] as usize]) > 0.0, "triangle {tri:?} faces in"); } } #[test] fn a_placed_mesh_without_uvs_still_gets_projected_ones() { - // Two meshes: one with varied UVs, one with none, side by side. + // Two meshes: one with varied UVs, one with none, side by side let uvs = [[0.0f32, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; let base = String::from_utf8(gltf_json(QUAD, Some(uvs), &[0, 1, 2, 0, 2, 3])).unwrap(); let with = r#""meshes":[{"primitives":[{"attributes":{"POSITION":0,"TEXCOORD_0":1},"indices":2}]}]"#; + assert!(base.contains(with)); + let two = base .replace(with, r#""meshes":[{"primitives":[{"attributes":{"POSITION":0,"TEXCOORD_0":1},"indices":2}]},{"primitives":[{"attributes":{"POSITION":0},"indices":2}]}]"#) .replace(r#""scenes":[{"nodes":[0]}],"nodes":[{"mesh":0}]"#, r#""scenes":[{"nodes":[0,1]}],"nodes":[{"mesh":0},{"mesh":1,"translation":[2,0,0]}]"#); - let m = load_mesh("two.gltf", two.as_bytes()).unwrap(); - assert_eq!(m.positions.len(), 8); - let second = &m.uvs[4..]; + let mesh = load_mesh("two.gltf", two.as_bytes()).unwrap(); + + assert_eq!(mesh.positions.len(), 8); + let second = &mesh.uvs[4..]; assert!(second.iter().any(|u| *u != second[0]), "the mesh without UVs got one constant UV: {second:?}"); } #[test] fn a_bad_index_drops_its_whole_triangle_and_later_ones_keep_their_vertices() { - // Triangles: (0,1,2), (0,1,9) out of range, (0,2,3). - let m = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 1, 9, 0, 2, 3])).unwrap(); - assert_eq!(m.indices, vec![0, 1, 2, 0, 2, 3]); - // An index count that is not a multiple of 3 drops only the partial triangle. - let m = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3, 1, 2])).unwrap(); - assert_eq!(m.indices, vec![0, 1, 2, 0, 2, 3]); + // Triangles: (0,1,2), (0,1,9) out of range, (0,2,3) + let mesh = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 1, 9, 0, 2, 3])).unwrap(); + + assert_eq!(mesh.indices, vec![0, 1, 2, 0, 2, 3]); + + // An index count that is not a multiple of 3 drops only the partial triangle + let mesh = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3, 1, 2])).unwrap(); + + assert_eq!(mesh.indices, vec![0, 1, 2, 0, 2, 3]); } #[test] @@ -415,10 +453,13 @@ mod tests { let mut nan_pos = QUAD; nan_pos[2][0] = f32::NAN; let e = load_mesh("x.gltf", &gltf_json(nan_pos, None, &[0, 1, 2, 0, 2, 3])).unwrap_err(); + assert!(e.to_string().contains("non-finite"), "{e}"); + let mut nan_uv = [[0.0f32, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; nan_uv[1][1] = f32::NAN; let e = load_mesh("x.gltf", &gltf_json(QUAD, Some(nan_uv), &[0, 1, 2, 0, 2, 3])).unwrap_err(); + assert!(e.to_string().contains("non-finite"), "{e}"); } @@ -434,27 +475,33 @@ mod tests { fn gltf_with_nodes(roots: &str, nodes: &str) -> Vec { let base = String::from_utf8(gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3])).unwrap(); let placed = base.replace(r#""scenes":[{"nodes":[0]}],"nodes":[{"mesh":0}]"#, &format!(r#""scenes":[{{"nodes":{roots}}}],"nodes":{nodes}"#)); + assert_ne!(base, placed, "the node list was not replaced"); placed.into_bytes() } - fn extent(m: &Mesh) -> Vec3 { - let (lo, hi) = m.bounds(); + fn extent(mesh: &Mesh) -> Vec3 { + let (lo, hi) = mesh.bounds(); hi - lo } #[test] fn gltf_meshes_take_their_parent_nodes_transforms() { - // The quad sits under a parent that stretches it three times taller. + // The quad sits under a parent that stretches it three times taller let nested = gltf_with_nodes("[0]", r#"[{"scale":[1,3,1],"children":[1]},{"mesh":0}]"#); - let m = load_mesh("nested.gltf", &nested).unwrap(); - let size = extent(&m); + let mesh = load_mesh("nested.gltf", &nested).unwrap(); + let size = extent(&mesh); + assert!((size.y / size.x - 3.0).abs() < 1e-4, "{size}"); - // A mesh placed twice is drawn twice. + + // A mesh placed twice is drawn twice let twice = gltf_with_nodes("[0,1]", r#"[{"mesh":0},{"mesh":0,"translation":[5,0,0]}]"#); + assert_eq!(load_mesh("twice.gltf", &twice).unwrap().triangle_count(), 4); - // Nodes outside the scene are not drawn. + + // Nodes outside the scene are not drawn let unplaced = gltf_with_nodes("[0]", r#"[{"mesh":0},{"mesh":0,"translation":[5,0,0]}]"#); + assert_eq!(load_mesh("one.gltf", &unplaced).unwrap().triangle_count(), 2); } @@ -462,26 +509,31 @@ mod tests { fn glb_container_loads() { let json = String::from_utf8(gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3])).unwrap(); let glb = craft_mesh::gltf::glb_container(json.as_bytes(), &[]).unwrap(); + assert_eq!(load_mesh("quad.GLB", &glb).unwrap().triangle_count(), 2); } #[test] fn obj_polygons_split_corners_and_material_libraries() { - // A pentagon whose corners share positions but not UVs, naming a material library the - // view cannot open: it still loads, triangulated, with the file's UVs. + // Missing material libraries must not discard usable UVs let obj = b"mtllib missing.mtl\nv 0 0 0\nv 1 0 0\nv 1.5 1 0\nv 0.5 2 0\nv -0.5 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0.5 1\nvt 0 1\nusemtl paint\nf 1/1 2/2 3/3 4/4 5/5\n"; - let m = load_mesh("penta.obj", obj).unwrap(); - assert_eq!(m.triangle_count(), 3); - // OBJ stores v up; the view uses v down. - assert!(m.uvs.iter().any(|u| (u.y - 1.0).abs() < 1e-6)); - assert!(m.uvs.iter().any(|u| u.y.abs() < 1e-6)); + let mesh = load_mesh("penta.obj", obj).unwrap(); + + assert_eq!(mesh.triangle_count(), 3); + + // OBJ stores v up; the view uses v down + assert!(mesh.uvs.iter().any(|u| (u.y - 1.0).abs() < 1e-6)); + assert!(mesh.uvs.iter().any(|u| u.y.abs() < 1e-6)); } #[test] fn reader_errors_read_as_the_views_messages() { let e = read_error("OBJ", craft_mesh::Error::TooLarge("vertices".into())); + assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}"); + let e = read_error("OBJ", craft_mesh::Error::Malformed("bad face".into())); + assert!(e.to_string().contains("OBJ: bad face"), "{e}"); } diff --git a/crates/formats/src/sbs/embedded.rs b/crates/formats/src/sbs/embedded.rs index f7b09744..0364c121 100644 --- a/crates/formats/src/sbs/embedded.rs +++ b/crates/formats/src/sbs/embedded.rs @@ -31,6 +31,7 @@ pub(super) fn encode_embedded(bytes: &[u8]) -> Result { let mut encoder = flate2::write::ZlibEncoder::new(length.to_be_bytes().to_vec(), flate2::Compression::default()); encoder.write_all(bytes).map_err(|e| FormatError::Io(e.to_string()))?; let raw = encoder.finish().map_err(|e| FormatError::Io(e.to_string()))?; + Ok(craft_mime::transfer::base64(&raw)) } @@ -45,6 +46,7 @@ mod tests { let mut encoder = flate2::write::ZlibEncoder::new((len as u32).to_be_bytes().to_vec(), flate2::Compression::default()); encoder.write_all(&bytes).unwrap(); let raw = encoder.finish().unwrap(); + assert_eq!(encode_embedded(&bytes).unwrap(), base64_engine().encode(&raw)); assert_eq!(decode_embedded(&encode_embedded(&bytes).unwrap()).unwrap(), bytes); } @@ -54,8 +56,10 @@ mod tests { fn strict_decoder_policy_is_not_replaced_by_mime_tolerance() { assert!(decode_embedded("!!!!").unwrap_err().starts_with("bad base64:")); 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::(); + assert_eq!(decode_embedded(&spaced).unwrap(), b"payload"); } diff --git a/crates/formats/src/sbs/function_graph.rs b/crates/formats/src/sbs/function_graph.rs index 1a2304fa..ae8e9343 100644 --- a/crates/formats/src/sbs/function_graph.rs +++ b/crates/formats/src/sbs/function_graph.rs @@ -156,7 +156,12 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result") + } else { + constant_xml(value).ok_or("function data must be a scalar or vector constant")? + }; let _ = write!(output, "{constant}", xml_escape(&node.op)); } @@ -167,6 +172,7 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result"); + Ok(output) } diff --git a/crates/formats/src/sbs/library.rs b/crates/formats/src/sbs/library.rs index 9d302878..deeac423 100644 --- a/crates/formats/src/sbs/library.rs +++ b/crates/formats/src/sbs/library.rs @@ -52,6 +52,7 @@ pub fn resolve(owner: &str, reference: &str) -> Result { let uri = format!("sbs://{}", parts.join("/")); relative_path(&uri)?; + Ok(uri) } @@ -132,6 +133,7 @@ pub fn install(relative: &str, bytes: Vec) -> Result<(), String> { } DOWNLOADED.write().unwrap_or_else(std::sync::PoisonError::into_inner).insert(relative.into(), bytes); + Ok(()) } @@ -153,6 +155,7 @@ fn read_embedded(relative: &str) -> Result, String> { let Ok(index) = EMBEDDED_ASSETS.binary_search_by_key(&relative, |(name, _, _)| *name) else { return read_downloaded(relative); }; + let (_, compressed, size) = EMBEDDED_ASSETS.get(index).ok_or("invalid bundled asset index")?; if *size > MAX_ASSET_BYTES { return Err("bundled asset exceeds 256 MiB".into()); @@ -252,6 +255,7 @@ mod tests { } let mut unique = files.clone(); unique.dedup(); + assert_eq!(unique, files); assert!(files.iter().all(|file| relative_path(file).is_ok() && file.ends_with(".sbs"))); } diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs index eef7ac6f..e26823ff 100644 --- a/crates/formats/src/sbs/sbs_reader.rs +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -610,6 +610,12 @@ impl<'text> SbsReader<'text, '_> { let Some(param_value) = child_element(param, "paramValue") else { return }; if let Some(value) = sbs_constant(param_value) { + // Preserve selector bits until the cook can resolve them against connected image kinds + if node.def == "channels_shuffle" && matches!(id, "red" | "green" | "blue" | "alpha") { + node.params.insert(id.to_string(), Value::Enum(value.int(0) as u32)); + return; + } + match to_param_value(like, &value, options) { Some(value) => { node.params.insert(id.to_string(), value); @@ -635,12 +641,11 @@ impl<'text> SbsReader<'text, '_> { pub(super) fn read_filter_params(&mut self, node: &mut Node, filter: &FilterMap, params: Option, graph_name: &str) { let Some(def) = find(filter.def) else { return }; + // Store omitted native values explicitly for imported node inspection and round trips if filter.sbs == "uniform" { - // An omitted SBS output color is black; the editor's new-node preset is gray node.params.insert("color".into(), Value::Color([0.0, 0.0, 0.0, 1.0])); } if filter.sbs == "normal" { - // Native files omit these defaults; the editor's new-node preset differs node.params.insert("opengl".into(), Value::Bool(false)); node.params.insert("height_alpha".into(), Value::Bool(true)); } diff --git a/crates/formats/src/sbs/sbs_writer.rs b/crates/formats/src/sbs/sbs_writer.rs index 827173d6..390637ea 100644 --- a/crates/formats/src/sbs/sbs_writer.rs +++ b/crates/formats/src/sbs/sbs_writer.rs @@ -181,6 +181,16 @@ impl SbsWriter { let fallback = if node.def == "input_value" { Value::Float(0.0) } else { Value::Color([0.5, 0.5, 0.5, 1.0]) }; let value = node.params.get("default").unwrap_or(&fallback); + + // A color constant on a grayscale image input is rejected by native readers + // Retain legacy color authoring values by writing their first channel as a scalar + let gray_default; + let value = if node.def == "input_grayscale" { + gray_default = Value::Float(value.as_vec4().map_or(0.0, |color| color[0])); + &gray_default + } else { + value + }; let default = constant_xml(value).unwrap_or_default(); let code = match node.def.as_str() { "input_value" => exposed_type_code(value), @@ -335,7 +345,12 @@ impl SbsWriter { continue; } - if filter.sbs == "text" + if filter.sbs == "shuffle" + && let Value::Enum(selector) = value + { + // SBS integers are signed; keep every selector bit through a save/load + out.push_str(¶m_xml(sbs_name, &Value::Int(*selector as i32)).unwrap_or_default()); + } else if filter.sbs == "text" && *sbs_name == "fontdata" && let Value::Text(name) = value && let Some(resource) = package.resource(name) diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index 6b736c9c..5a4a7e84 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -8,6 +8,29 @@ fn no_linked_files(_: &str) -> Option> { None } +#[test] +fn shuffle_roundtrip_preserves_signed_channel_selectors() { + for selector in [-2_i32, -1, 8, 9, 16, 255] { + let xml = format!( + r#" + + + + "# + ); + + let loaded = read_sbs(xml.as_bytes(), "original.sbs", &no_linked_files).unwrap(); + let node = &loaded.pkg.graphs[0].nodes[0]; + + assert_eq!(node.params.get("red"), Some(&Value::Enum(selector as u32)), "selector {selector}"); + + let saved = write_sbs(&loaded.pkg).unwrap(); + let reloaded = read_sbs(&saved, "original.sbs", &no_linked_files).unwrap(); + + assert_eq!(reloaded.pkg.graphs[0].nodes[0].params.get("red"), node.params.get("red"), "saved selector {selector}"); + } +} + #[test] fn saved_dot_outputs_load_as_incomplete_functions() { let xml = r#" diff --git a/crates/formats/src/svg.rs b/crates/formats/src/svg.rs index db98c97c..0c0b69bf 100644 --- a/crates/formats/src/svg.rs +++ b/crates/formats/src/svg.rs @@ -48,6 +48,7 @@ pub(crate) fn decode(bytes: &[u8]) -> Result { let pixels = draw::render(&tree, usvg::Transform::identity(), width, height, 0, DRAW_BUDGET) .map_err(|refusal| FormatError::Image(format!("SVG not drawn: {}", refusal.message)))?; + Ok(Image::generate(width, height, Kind::Color, |x, y| { let pixel = pixels.pixel(x, y).map(|pixel| pixel.demultiply()); pixel.map_or([0.0; 4], |pixel| { @@ -78,15 +79,17 @@ mod tests { #[test] fn draws_a_shape_in_linear_light() { let image = decode(&svg(r##""##)).unwrap(); - assert_eq!((image.w, image.h), (4, 2)); + let left = image.get(0, 0, false); + + assert_eq!((image.w, image.h), (4, 2)); assert!((left[0] - 1.0).abs() < 1e-3 && left[1].abs() < 1e-3 && (left[3] - 1.0).abs() < 1e-3, "{left:?}"); assert_eq!(image.get(3, 1, false)[3], 0.0); } #[test] fn hostile_documents_are_errors_not_crashes() { - // Entities that expand past the shared bound (a "billion laughs"). + // Entities that expand past the shared bound (a "billion laughs") let mut laughs = String::from(r#""#); for level in 1..10 { let prev = char::from(b'a' + level - 1); @@ -94,12 +97,17 @@ mod tests { laughs.push_str(&format!("", format!("&{prev};").repeat(10))); } laughs.push_str(r#"]>&j;"#); + assert!(decode(laughs.as_bytes()).is_err()); - // Nesting deeper than the tree depth. + + // Nesting deeper than the tree depth let deep = format!("{}{}", "".repeat(200), "".repeat(200)); + assert!(decode(&svg(&deep)).is_err()); - // Larger than the image side limit. + + // Larger than the image side limit let huge = br#""#; + assert!(decode(huge).is_err()); assert!(decode(b" 0.9, "{:?}", shallow.get(1, 1, false)); + let deep = decode(&embedded(40)).unwrap(); + assert_eq!(deep.get(1, 1, false)[3], 0.0); - // The document alone past its own budget is refused. + + // The document alone past its own budget is refused assert!(decode(&svg(&nested_groups(40, ""))).is_err()); } @@ -131,6 +143,7 @@ mod tests { fn linked_files_are_not_read() { let linked = svg(r#""#); let image = decode(&linked).unwrap(); + assert_eq!(image.get(0, 0, false)[3], 0.0); } @@ -140,6 +153,7 @@ mod tests { let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); gz.write_all(&svg(r#""#)).unwrap(); let image = decode(&gz.finish().unwrap()).unwrap(); + assert!(image.get(1, 1, false)[2] > 0.9); } } diff --git a/crates/formats/tests/bitmap_imports.rs b/crates/formats/tests/bitmap_imports.rs index 6dc0064f..13bb562c 100644 --- a/crates/formats/tests/bitmap_imports.rs +++ b/crates/formats/tests/bitmap_imports.rs @@ -84,6 +84,7 @@ fn shared_dds_keeps_rgb_transfer_alpha_and_float_range() { assert!((converted.data[i] - materialcraft_image::srgb_to_linear(raw.data[i])).abs() < 1e-6); } assert_eq!(converted.data[3], raw.data[3]); + let mut floats = Vec::new(); dds::header::Header::new_image(1, 1, dds::Format::R32G32B32A32_FLOAT).write(&mut floats).unwrap(); for v in [-0.5_f32, 2.0, 0.25, 0.75] { diff --git a/crates/formats/tests/parity_function_loop.rs b/crates/formats/tests/parity_function_loop.rs new file mode 100644 index 00000000..2afd9ee8 --- /dev/null +++ b/crates/formats/tests/parity_function_loop.rs @@ -0,0 +1,26 @@ +use materialcraft_core::{FunctionGraph, Graph, Package, Value}; + +#[test] +fn function_loop_limit_uses_scalar_integer_data() { + let mut function = FunctionGraph::default(); + let initial = function.add_constant(Value::Float(0.25)); + let condition = function.add_constant(Value::Bool(true)); + let body = function.add_constant(Value::Float(0.75)); + function.output = Some(function.add("while", &[initial, condition, body], Some(Value::Int(3)))); + let mut graph = Graph::new("Loop serialization"); + graph.function = Some(function); + let mut package = Package::new("Original function data"); + package.graphs.push(graph); + + let bytes = materialcraft_formats::sbs::write_sbs(&package).unwrap(); + let text = String::from_utf8(bytes).unwrap(); + let document = roxmltree::Document::parse(&text).unwrap(); + let loop_node = document + .descendants() + .find(|node| node.has_tag_name("paramNode") && node.children().any(|child| child.has_tag_name("function") && child.attribute("v") == Some("while"))) + .unwrap(); + let limit = loop_node.descendants().find(|node| node.has_tag_name("constantValue")).unwrap().children().find(roxmltree::Node::is_element).unwrap(); + + assert_eq!(limit.tag_name().name(), "constantValueInt1"); + assert_eq!(limit.attribute("v"), Some("3")); +} diff --git a/crates/formats/tests/parity_input_defaults.rs b/crates/formats/tests/parity_input_defaults.rs new file mode 100644 index 00000000..5f04ffdc --- /dev/null +++ b/crates/formats/tests/parity_input_defaults.rs @@ -0,0 +1,26 @@ +use materialcraft_core::{Graph, Package, Value}; + +#[test] +fn grayscale_image_defaults_are_scalar_in_sbs() { + let mut package = Package::new("Grayscale defaults"); + let mut graph = Graph::new("defaults"); + graph.add_node("input_grayscale", [0.0, 0.0]); + let colored = graph.add_node("input_grayscale", [0.0, 100.0]); + graph.node_mut(colored).unwrap().params.insert("default".into(), Value::Color([0.25, 0.5, 0.75, 0.125])); + package.graphs.push(graph); + + let bytes = materialcraft_formats::sbs::write_sbs(&package).unwrap(); + let text = String::from_utf8(bytes).unwrap(); + let document = roxmltree::Document::parse(&text).unwrap(); + let defaults: Vec<_> = document + .descendants() + .filter(|node| node.has_tag_name("paraminput")) + .map(|node| { + let default = node.children().find(|node| node.has_tag_name("defaultValue")).unwrap(); + let constant = default.children().find(roxmltree::Node::is_element).unwrap(); + (constant.tag_name().name().to_string(), constant.attribute("v").unwrap().to_string()) + }) + .collect(); + + assert_eq!(defaults, vec![("constantValueFloat1".into(), "0.5".into()), ("constantValueFloat1".into(), "0.25".into())]); +} diff --git a/crates/nodes/examples/filter_timing.rs b/crates/nodes/examples/filter_timing.rs new file mode 100644 index 00000000..5e037034 --- /dev/null +++ b/crates/nodes/examples/filter_timing.rs @@ -0,0 +1,42 @@ +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use materialcraft_core::{OutputFormat, Value}; +use materialcraft_image::{Image, Kind}; +use materialcraft_nodes::{CookContext, find, resolve_params}; +use std::{collections::BTreeMap, time::Instant}; + +fn main() -> Result<(), String> { + const REPETITIONS: u32 = 3; + for side in [512, 1024] { + let inputs = [Some(Image::generate(side, side, Kind::Color, |x, y| { + [x as f32 / side as f32, y as f32 / side as f32, f32::from((x / 7 + y / 11) % 2 == 0), 0.75] + }))]; + for (operation, intensity) in [("blur", 32.0), ("directional_blur", 10.0), ("sharpen", 10.0)] { + let definition = find(operation).ok_or("missing filter definition")?; + let parameters = BTreeMap::from([("intensity".into(), Value::Float(intensity)), ("angle".into(), Value::Float(0.125))]); + let parameters = resolve_params(definition, ¶meters); + let resource = |_: &str| None; + let vars = BTreeMap::new(); + let context = CookContext { + w: side, + h: side, + seed: 0, + format: OutputFormat::F32, + tile: true, + inputs: &inputs, + params: ¶meters, + resource: &resource, + vars: &vars, + }; + + let start = Instant::now(); + for _ in 0..REPETITIONS { + std::hint::black_box((definition.cook)(&context)?); + } + println!("{operation} {side}x{side}: {:.3} ms/cook ({REPETITIONS} repetitions)", start.elapsed().as_secs_f64() * 1000.0 / f64::from(REPETITIONS)); + } + } + + Ok(()) +} diff --git a/crates/nodes/src/atomic/blur.rs b/crates/nodes/src/atomic/blur.rs index 089e58f0..41494b85 100644 --- a/crates/nodes/src/atomic/blur.rs +++ b/crates/nodes/src/atomic/blur.rs @@ -1,14 +1,22 @@ -use super::ATOMIC; -use crate::ops; +use super::{ATOMIC, box_filter}; use crate::{CookContext, CookResult, NodeDefinition, node}; use materialcraft_image::Kind; pub(super) fn definition() -> NodeDefinition { - node("blur", "Blur", ATOMIC).desc("Gaussian blur.").atomic().any_in("input", "Input").float("intensity", "Intensity", 2.0, 0.0, 32.0).any_out().cook(blur) + node("blur", "Blur", ATOMIC) + .desc("Box blur with fractional pixel coverage.") + .atomic() + .any_in("input", "Input") + .float("intensity", "Intensity", 10.0, 0.0, 32.0) + .any_out() + .cook(blur) } fn blur(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); - let sigma = context.f("intensity").max(0.0) * context.w as f32 / 256.0 * 0.5; - Ok(vec![ops::gaussian(&img, sigma, context.tile)]) + let input = context.any_or(0, Kind::Gray, [0.0; 4]); + const BASE_RESOLUTION: f32 = 256.0; + let radius = context.f("intensity").max(0.0) * context.w.min(context.h) as f32 / BASE_RESOLUTION; + let tile = context.tiling_axes(); + + Ok(vec![box_filter::axis(&box_filter::axis(&input, radius, true, tile[0]), radius, false, tile[1])]) } diff --git a/crates/nodes/src/atomic/box_filter.rs b/crates/nodes/src/atomic/box_filter.rs new file mode 100644 index 00000000..ddddab8f --- /dev/null +++ b/crates/nodes/src/atomic/box_filter.rs @@ -0,0 +1,90 @@ +use materialcraft_image::{Image, MAX_SIDE}; +use rayon::prelude::*; +use std::sync::Arc; + +pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) -> Image { + if !radius.is_finite() || radius <= 0.5 { + return input.clone(); + } + + // Bound work for hostile strengths to the largest supported image dimension + let radius = radius.min(MAX_SIDE as f32); + let extent = (radius + 0.5).floor() as i64; + let weight = 1.0 / (2.0 * f64::from(radius)); + let edge_weight = (0.5 - (extent as f64 - 0.5) * weight).max(0.0); + let (length, lines) = if horizontal { (input.w, input.h) } else { (input.h, input.w) }; + let channels = input.channels(); + let results: Vec> = (0..lines) + .into_par_iter() + .map(|line| { + let get = |position: i64| { + if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) } + }; + let mut output = vec![0.0; length as usize * channels]; + for channel in 0..channels { + // Count NaN, positive infinity and negative infinity separately + let mut sum = 0.0_f64; + let mut non_finite = [0_i64; 3]; + for position in (1 - extent)..extent { + accumulate(&mut sum, &mut non_finite, get(position)[channel], 1); + } + + for (position, pixel) in output.chunks_exact_mut(channels).enumerate() { + let position = position as i64; + let mut value = window_total(sum, non_finite) * weight; + if edge_weight > 0.0 { + value += (f64::from(get(position - extent)[channel]) + f64::from(get(position + extent)[channel])) * edge_weight; + } + pixel[channel] = value as f32; + accumulate(&mut sum, &mut non_finite, get(position + extent)[channel], 1); + accumulate(&mut sum, &mut non_finite, get(position - extent + 1)[channel], -1); + } + } + + output + }) + .collect(); + + let data = if horizontal { + results.into_iter().flatten().collect() + } else { + let mut data = Vec::with_capacity(input.w as usize * input.h as usize * channels); + for y in 0..input.h as usize { + for line in &results { + data.extend_from_slice(line.get(y * channels..(y + 1) * channels).unwrap_or(&[])); + } + } + + data + }; + + Image { w: input.w, h: input.h, kind: input.kind, integer_sampling: false, data: Arc::new(data) } +} + +fn accumulate(sum: &mut f64, non_finite: &mut [i64; 3], value: f32, sign: i64) { + if value.is_finite() { + *sum += f64::from(value) * sign as f64; + } else { + let index = if value.is_nan() { + 0 + } else if value.is_sign_positive() { + 1 + } else { + 2 + }; + non_finite[index] += sign; + } +} + +fn window_total(sum: f64, non_finite: [i64; 3]) -> f64 { + // A non-finite sample must stop affecting the running sum once it leaves the window + if non_finite[0] > 0 || (non_finite[1] > 0 && non_finite[2] > 0) { + f64::NAN + } else if non_finite[1] > 0 { + f64::INFINITY + } else if non_finite[2] > 0 { + f64::NEG_INFINITY + } else { + sum + } +} diff --git a/crates/nodes/src/atomic/channels_shuffle.rs b/crates/nodes/src/atomic/channels_shuffle.rs index 1014f546..edc402e1 100644 --- a/crates/nodes/src/atomic/channels_shuffle.rs +++ b/crates/nodes/src/atomic/channels_shuffle.rs @@ -1,5 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_core::Value; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { @@ -17,19 +18,36 @@ pub(super) fn definition() -> NodeDefinition { } fn channels_shuffle(context: &CookContext) -> CookResult { - let a = context.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let b = context.any_or(1, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let src = [context.i("red"), context.i("green"), context.i("blue"), context.i("alpha")]; + // Sampling clamps the unconnected fallback to its single zero pixel + let first_input = context.sized(0).unwrap_or_else(|| Image::filled(1, 1, Kind::Color, [0.0; 4])); + let second_input = context.sized(1).unwrap_or_else(|| Image::filled(1, 1, Kind::Color, [0.0; 4])); + let channel_sources = ["red", "green", "blue", "alpha"].map(|id| match context.value(id) { + Some(Value::Enum(index)) => *index, + _ => 0, + }); + Ok(vec![Image::generate(context.w, context.h, Kind::Color, |x, y| { - let (pa, pb) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - src.map(|s| match s { - 0..=3 => pa[s as usize], - 4..=7 => pb[(s - 4) as usize], - 9 => 1.0, - _ => 0.0, + let first_pixel = first_input.get(x as i64, y as i64, false); + let second_pixel = second_input.get(x as i64, y as i64, false); + + channel_sources.map(|selector| { + // Gray selection precedes the packed color swizzle, including for file values above seven + if selector < 4 && first_input.is_gray() { + return first_pixel[0]; + } + + if selector >= 4 && second_input.is_gray() { + return second_pixel[0]; + } + + const CHANNEL_MASK: u32 = 0b111; + match selector & CHANNEL_MASK { + channel @ 0..=3 => first_pixel[channel as usize], + channel => second_pixel[(channel - 4) as usize], + } }) })]) } const CHANNEL_SOURCES: &[&str] = - &["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha", "Black", "White"]; + &["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha"]; diff --git a/crates/nodes/src/atomic/directional_blur.rs b/crates/nodes/src/atomic/directional_blur.rs index 905c0d07..7a088cea 100644 --- a/crates/nodes/src/atomic/directional_blur.rs +++ b/crates/nodes/src/atomic/directional_blur.rs @@ -1,4 +1,4 @@ -use super::{ATOMIC, direction}; +use super::{ATOMIC, box_filter, direction}; use crate::{CookContext, CookResult, NodeDefinition, node}; use materialcraft_image::{Image, Kind}; @@ -18,23 +18,47 @@ fn directional_blur(context: &CookContext) -> CookResult { } pub(super) fn blur(context: &CookContext, angle: f32) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); - let len = context.f("intensity").max(0.0) * context.w as f32 / 256.0; - if len < 0.5 { - return Ok(vec![img]); + let input = context.any_or(0, Kind::Gray, [0.0; 4]); + const BASE_RESOLUTION: f32 = 256.0; + const MAX_HALF_SAMPLES: i32 = 512; + let radius = context.f("intensity").max(0.0) * context.w.min(context.h) as f32 / BASE_RESOLUTION; + if radius <= 0.5 { + return Ok(vec![input]); } + let (dx, dy) = direction(angle); - let n = (len.ceil() as i32).clamp(1, 512); - let (iw, ih) = (1.0 / context.w as f32, 1.0 / context.h as f32); - Ok(vec![Image::generate_uv(context.w, context.h, img.kind, |u, v| { - let mut acc = [0.0; 4]; - for i in -n..=n { - let t = i as f32 / n as f32 * len * 0.5; - let p = img.sample(u + dx * t * iw, v + dy * t * ih, context.tile); - for k in 0..4 { - acc[k] += p[k]; + + // Image-space rotation follows increasing rows + let dy = -dy; + let tile = context.tiling_axes(); + if dy == 0.0 { + return Ok(vec![box_filter::axis(&input, radius, true, tile[0])]); + } + + let major = dx.abs().max(dy.abs()); + let projected_radius = 0.5 + (radius - 0.5) * major; + let half_samples = (projected_radius + 0.5).floor().clamp(1.0, MAX_HALF_SAMPLES as f32) as i32; + + // Bound oblique sampling cost while preserving the extent of large kernels + let step = ((projected_radius - 0.5) / half_samples as f32).max(1.0); + let weight = step / (2.0 * projected_radius); + let edge_weight = (0.5 - (half_samples as f32 - 0.5) * weight).max(0.0); + let (inverse_width, inverse_height) = (1.0 / context.w as f32, 1.0 / context.h as f32); + + Ok(vec![Image::generate_uv(context.w, context.h, input.kind, |u, v| { + let mut pixel = [0.0; 4]; + for i in -half_samples..=half_samples { + let sample_weight = if i.abs() == half_samples { edge_weight } else { weight }; + if sample_weight == 0.0 { + continue; + } + + let offset = i as f32 * step / major; + let sample = input.sample_axes(u + dx * offset * inverse_width, v + dy * offset * inverse_height, tile); + for channel in 0..4 { + pixel[channel] += sample[channel] * sample_weight; } } - acc.map(|a| a / (2 * n + 1) as f32) + pixel })]) } diff --git a/crates/nodes/src/atomic/distance.rs b/crates/nodes/src/atomic/distance.rs index fda95f52..7b5aeb76 100644 --- a/crates/nodes/src/atomic/distance.rs +++ b/crates/nodes/src/atomic/distance.rs @@ -10,7 +10,7 @@ pub(super) fn definition() -> NodeDefinition { .gray_in("mask", "Mask input") .any_in("source", "Source input") .float("distance", "Maximum distance", 10.0, 0.0, 256.0) - .boolean("combine", "Combine distance with source", false) + .boolean("combine", "Combine distance with source", true) .any_out() .cook(distance) } diff --git a/crates/nodes/src/atomic/emboss.rs b/crates/nodes/src/atomic/emboss.rs index 66492a2e..efcf1d3c 100644 --- a/crates/nodes/src/atomic/emboss.rs +++ b/crates/nodes/src/atomic/emboss.rs @@ -10,25 +10,27 @@ pub(super) fn definition() -> NodeDefinition { .any_in("input", "Input") .gray_in("height", "Intensity input") .float("intensity", "Intensity", 5.0, 0.0, 32.0) - .angle("light_angle", "Light angle", 0.375) + .angle("light_angle", "Light angle", 0.0) .color("highlight", "Highlight color", [1.0, 1.0, 1.0, 1.0]) - .color("shadow", "Shadow color", [0.0, 0.0, 0.0, 1.0]) + .color("shadow", "Shadow color", [0.0; 4]) .any_out() .cook(emboss) } fn emboss(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]); - let hmap = context.gray_or(1, 0.0); - let (lx, ly) = direction(context.f("light_angle")); - let k = context.f("intensity") * context.w as f32 / 64.0; - let (hi, sh) = (context.v4("highlight"), context.v4("shadow")); - Ok(vec![Image::generate(context.w, context.h, img.kind, |x, y| { - let (gx, gy) = ops::slope(&hmap, x as i64, y as i64, context.tile); - let l = (-(gx * lx + gy * ly) * k).clamp(-1.0, 1.0); - let p = img.get(x as i64, y as i64, false); - let tint = if l >= 0.0 { hi } else { sh }; - let t = l.abs(); - [p[0] + (tint[0] - p[0]) * t, p[1] + (tint[1] - p[1]) * t, p[2] + (tint[2] - p[2]) * t, p[3]] + const INTENSITY_REFERENCE_WIDTH: f32 = 64.0; + let input = context.any_or(0, Kind::Gray, [0.0; 4]); + let height_map = context.gray_or(1, 0.0); + let (light_x, light_y) = direction(context.f("light_angle")); + let intensity = context.f("intensity") * context.w as f32 / INTENSITY_REFERENCE_WIDTH; + let (highlight, shadow) = (context.v4("highlight"), context.v4("shadow")); + + Ok(vec![Image::generate(context.w, context.h, input.kind, |x, y| { + let (gx, gy) = ops::slope(&height_map, x as i64, y as i64, context.tile); + let lighting = (-(gx * light_x + gy * light_y) * intensity).clamp(-1.0, 1.0); + let pixel = input.get(x as i64, y as i64, false); + let tint = if lighting >= 0.0 { highlight } else { shadow }; + let blend = lighting.abs(); + [pixel[0] + (tint[0] - pixel[0]) * blend, pixel[1] + (tint[1] - pixel[1]) * blend, pixel[2] + (tint[2] - pixel[2]) * blend, pixel[3]] })]) } diff --git a/crates/nodes/src/atomic/gradient_dynamic.rs b/crates/nodes/src/atomic/gradient_dynamic.rs index cd38bdc7..4f985cfc 100644 --- a/crates/nodes/src/atomic/gradient_dynamic.rs +++ b/crates/nodes/src/atomic/gradient_dynamic.rs @@ -8,17 +8,21 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .gray_in("input", "Grayscale input") .any_in("gradient", "Gradient input") - .float("position", "Position", 0.5, 0.0, 1.0) + .float("position", "Position", 0.0, 0.0, 1.0) .choice("orientation", "Orientation", &["Horizontal", "Vertical"], 0) .any_out() .cook(gradient_dynamic) } fn gradient_dynamic(context: &CookContext) -> CookResult { + let Some(gradient) = context.input(1) else { + return Ok(vec![Image::filled(context.w, context.h, Kind::Gray, [0.0; 4])]); + }; + let input = context.gray_or(0, 0.0); - let gradient = context.input(1).cloned().unwrap_or_else(|| Image::generate_uv(256, 1, Kind::Gray, |position, _| [position; 4])); let position = context.f("position"); let vertical = context.i("orientation") == 1; + Ok(vec![Image::generate(context.w, context.h, gradient.kind, |x, y| { let intensity = input.get_gray(i64::from(x), i64::from(y), false).clamp(0.0, 1.0); if vertical { gradient.sample(position, intensity, false) } else { gradient.sample(intensity, position, false) } diff --git a/crates/nodes/src/atomic/grayscale_conversion.rs b/crates/nodes/src/atomic/grayscale_conversion.rs index 4c37f363..151ea631 100644 --- a/crates/nodes/src/atomic/grayscale_conversion.rs +++ b/crates/nodes/src/atomic/grayscale_conversion.rs @@ -12,7 +12,7 @@ pub(super) fn definition() -> NodeDefinition { .float("blue", "Blue weight", 1.0 / 3.0, 0.0, 1.0) .float("alpha", "Alpha weight", 0.0, 0.0, 1.0) .boolean("flatten_alpha", "Flatten alpha", false) - .float("matte", "Matte level", 0.0, 0.0, 1.0) + .float("matte", "Matte level", 1.0, 0.0, 1.0) .gray_out() .cook(grayscale_conversion) } diff --git a/crates/nodes/src/atomic/hsl.rs b/crates/nodes/src/atomic/hsl.rs index f5ff6830..8846984b 100644 --- a/crates/nodes/src/atomic/hsl.rs +++ b/crates/nodes/src/atomic/hsl.rs @@ -16,10 +16,11 @@ pub(super) fn definition() -> NodeDefinition { } fn hsl(context: &CookContext) -> CookResult { - let image = context.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); + let image = context.any_or(0, Kind::Color, [0.0; 4]).to_color(); // The normalized slider spans one full turn in either direction from its midpoint let (hue_shift, saturation, lightness) = ((context.f("hue") - 0.5) * 2.0, context.f("saturation"), context.f("lightness")); + Ok(vec![image.map(Kind::Color, |pixel| { let [h, s, l] = ops::rgb_to_hsl(pixel); let s = if saturation <= 0.5 { s * saturation * 2.0 } else { s + (1.0 - s) * (saturation - 0.5) * 2.0 }; diff --git a/crates/nodes/src/atomic/mod.rs b/crates/nodes/src/atomic/mod.rs index aeb31097..07cb0968 100644 --- a/crates/nodes/src/atomic/mod.rs +++ b/crates/nodes/src/atomic/mod.rs @@ -1,6 +1,7 @@ mod bitmap; mod blend; mod blur; +mod box_filter; mod channels_shuffle; mod curve; mod directional_blur; diff --git a/crates/nodes/src/atomic/normal.rs b/crates/nodes/src/atomic/normal.rs index 99b4d835..c37dcc62 100644 --- a/crates/nodes/src/atomic/normal.rs +++ b/crates/nodes/src/atomic/normal.rs @@ -8,15 +8,17 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .gray_in("input", "Input") .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .boolean("opengl", "OpenGL normals", true) - .boolean("height_alpha", "Height in alpha", false) + .boolean("opengl", "OpenGL normals", false) + .boolean("height_alpha", "Height in alpha", true) .color_out() .cook(normal) } fn normal(context: &CookContext) -> CookResult { + const BASE_RESOLUTION: f32 = 256.0; let height_map = context.gray_or(0, 0.0); - let intensity = context.f("intensity") * context.w as f32 / 256.0; + let intensity = context.f("intensity") * context.w as f32 / BASE_RESOLUTION; + Ok(vec![height_to_normal(&height_map, intensity, !context.b("opengl"), context.tile, context.b("height_alpha"))]) } diff --git a/crates/nodes/src/atomic/pattern_map.rs b/crates/nodes/src/atomic/pattern_map.rs index 3d9360b7..555af1f7 100644 --- a/crates/nodes/src/atomic/pattern_map.rs +++ b/crates/nodes/src/atomic/pattern_map.rs @@ -10,9 +10,9 @@ pub(super) fn definition() -> NodeDefinition { .any_in("background", "Background") .any_in("pattern0", "Input image 0") .pattern_graph("pattern", "FX-Map graph", PatternGraph::with_root(PatternNodeKind::Quadrant)) - .float("roughness", "Roughness", 0.0, 0.0, 2.0) + .float("roughness", "Roughness", 1.0, 0.0, 2.0) .float("opacity", "Opacity", 1.0, 0.0, 10.0) - .boolean("color_mode", "Color output", false) + .boolean("color_mode", "Color output", true) .color("background", "Background color", [0.0; 4]) .float4("render_region", "Render region", [0.0, 1.0, 0.0, 1.0], -65536.0, 65536.0) .float4("tiling_region", "Tiling region", [0.0, 1.0, 0.0, 1.0], 0.0, 1.0) diff --git a/crates/nodes/src/atomic/sharpen.rs b/crates/nodes/src/atomic/sharpen.rs index ef2bd464..4542deb9 100644 --- a/crates/nodes/src/atomic/sharpen.rs +++ b/crates/nodes/src/atomic/sharpen.rs @@ -1,11 +1,10 @@ use super::ATOMIC; -use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("sharpen", "Sharpen", ATOMIC) - .desc("Unsharp mask.") + .desc("Sharpens local contrast with a four-neighbor Laplacian.") .atomic() .any_in("input", "Input") .float("intensity", "Intensity", 1.0, 0.0, 10.0) @@ -14,11 +13,38 @@ pub(super) fn definition() -> NodeDefinition { } fn sharpen(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); - let soft = ops::gaussian(&img, 1.0, context.tile); - let k = context.f("intensity"); - Ok(vec![Image::generate(context.w, context.h, img.kind, |x, y| { - let (a, b) = (img.get(x as i64, y as i64, false), soft.get(x as i64, y as i64, false)); - [a[0] + (a[0] - b[0]) * k, a[1] + (a[1] - b[1]) * k, a[2] + (a[2] - b[2]) * k, a[3]] + let input = context.any_or(0, Kind::Gray, [0.0; 4]); + let intensity = context.f("intensity"); + let tile = context.tiling_axes(); + let short_side = context.w.min(context.h) as f32; + let horizontal = intensity * short_side / context.w.max(1) as f32; + let vertical = intensity * short_side / context.h.max(1) as f32; + + Ok(vec![Image::generate(context.w, context.h, input.kind, |x, y| { + let (x, y) = (i64::from(x), i64::from(y)); + let center = input.get(x, y, false); + let left = input.get_axes(x - 1, y, tile); + let right = input.get_axes(x + 1, y, tile); + let top = input.get_axes(x, y - 1, tile); + let bottom = input.get_axes(x, y + 1, tile); + std::array::from_fn(|channel| { + // Keep the axial differences separate to preserve Float32 cancellation order + let twice_center = 2.0 * center[channel]; + let across = axial_difference(center[channel], twice_center, left[channel], right[channel]); + let down = axial_difference(center[channel], twice_center, top[channel], bottom[channel]); + + // Float outputs retain HDR values but discard negative sharpening lobes + (center[channel] + (across * horizontal + down * vertical)).max(0.0) + }) })]) } + +fn axial_difference(center: f32, twice_center: f32, first: f32, second: f32) -> f32 { + let difference = twice_center - (first + second); + if difference.is_finite() || ![center, first, second].iter().all(|value| value.is_finite()) { + return difference; + } + + // Finite HDR inputs can overflow both Float32 sums and turn their difference into NaN + (2.0 * f64::from(center) - (f64::from(first) + f64::from(second))) as f32 +} diff --git a/crates/nodes/src/atomic/text.rs b/crates/nodes/src/atomic/text.rs index 10c2fcc3..2e18efd4 100644 --- a/crates/nodes/src/atomic/text.rs +++ b/crates/nodes/src/atomic/text.rs @@ -118,9 +118,9 @@ pub(super) fn definition() -> NodeDefinition { .any_in("background", "Background") .boolean("color_mode", "Color output", false) .color("background", "Background color", [0.0, 0.0, 0.0, 1.0]) - .text("text", "Text", "MaterialCraft") + .text("text", "Text", "") .text("fontdata", "Font reference", "") - .float("fontsize", "Font size", 0.09, 0.0, 1.0) + .float("fontsize", "Font size", 0.25, 0.0, 1.0) .float2("position", "Position", [0.0; 2], -1.0, 1.0) .float4("matrix", "Transform matrix", [1.0, 0.0, 0.0, 1.0], -10.0, 10.0) .choice("alignment", "Alignment", &["Left", "Center", "Right"], 1) @@ -205,7 +205,7 @@ mod tests { #[test] fn renders_material_craft() { let def = find("text").unwrap(); - let p = resolve_params(def, &BTreeMap::new()); + let p = resolve_params(def, &BTreeMap::from([("text".into(), materialcraft_core::Value::Text("MaterialCraft".into()))])); let no_res = |_: &str| None; let vars = BTreeMap::new(); let context = CookContext { diff --git a/crates/nodes/src/atomic/uniform.rs b/crates/nodes/src/atomic/uniform.rs index fedde70a..b32b54f6 100644 --- a/crates/nodes/src/atomic/uniform.rs +++ b/crates/nodes/src/atomic/uniform.rs @@ -7,17 +7,18 @@ pub(super) fn definition() -> NodeDefinition { .desc("A single color or gray value.") .atomic() .generator() - .color("color", "Color", [0.5, 0.5, 0.5, 1.0]) + .color("color", "Color", [0.0, 0.0, 0.0, 1.0]) .boolean("color_mode", "Color output", true) .any_out() .cook(uniform) } fn uniform(context: &CookContext) -> CookResult { - let c = context.v4("color"); + let color = context.v4("color"); + Ok(vec![if !context.b("color_mode") { - Image::filled(context.w, context.h, Kind::Gray, [luminance(c); 4]) + Image::filled(context.w, context.h, Kind::Gray, [luminance(color); 4]) } else { - Image::filled(context.w, context.h, Kind::Color, c) + Image::filled(context.w, context.h, Kind::Color, color) }]) } diff --git a/crates/nodes/src/cook_context.rs b/crates/nodes/src/cook_context.rs index 5b0702ec..643129dd 100644 --- a/crates/nodes/src/cook_context.rs +++ b/crates/nodes/src/cook_context.rs @@ -19,6 +19,10 @@ pub struct CookContext<'a> { } impl CookContext<'_> { + pub fn tiling_axes(&self) -> [bool; 2] { + self.vars.get("$tiling").and_then(Value::as_i32).map_or([self.tile; 2], |mask| [mask & 1 != 0, mask & 2 != 0]) + } + pub fn value(&self, id: &str) -> Option<&Value> { self.params.get(id) } diff --git a/crates/nodes/src/function/catalog.rs b/crates/nodes/src/function/catalog.rs index d9532772..38e7ec44 100644 --- a/crates/nodes/src/function/catalog.rs +++ b/crates/nodes/src/function/catalog.rs @@ -100,10 +100,10 @@ pub fn default_value(id: &str) -> Option { Some(match id { "const_bool" => Value::Bool(false), - "const_float1" => Value::Float(0.5), + "const_float1" => Value::Float(0.0), "const_float2" => Value::Float2([0.0; 2]), "const_float3" => Value::Float3([0.0; 3]), - "const_float4" => Value::Float4([0.0, 0.0, 0.0, 1.0]), + "const_float4" => Value::Float4([0.0; 4]), "const_int1" => Value::Int(0), "const_int2" => Value::Int2([0; 2]), "const_int3" => Value::Int3([0; 3]), @@ -114,7 +114,7 @@ pub fn default_value(id: &str) -> Option { "swizzle3" | "iswizzle3" => Value::Int3([0, 1, 2]), "swizzle4" | "iswizzle4" => Value::Int4([0, 1, 2, 3]), "samplecol" | "samplelum" => Value::Int2([0, 0]), - "while" => Value::Int(100), + "while" => Value::Int(super::DEFAULT_LOOP_LIMIT), _ => return None, }) } diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs index 9f82f4dc..133510f0 100644 --- a/crates/nodes/src/function/compile.rs +++ b/crates/nodes/src/function/compile.rs @@ -46,7 +46,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu }; let names: Vec<_> = super::input_identifiers(node).collect(); - // An operation computes with zero on an input nothing is connected to; a call needs a source default instead + // Operations use zero for absent inputs; calls require source defaults let missing_input = node .instance .as_ref() @@ -55,7 +55,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu return Err(format!("{} ({id}) requires connected inputs: {}", super::node_label(node), names.join(", "))); } - // Preserved legacy connectors must not evaluate a duplicate random or stateful input twice + // Legacy connectors must not evaluate stateful inputs twice let ports: Vec<_> = names .into_iter() .zip(&node.inputs) @@ -79,7 +79,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu connected } else { let sibling = if node.op == "ifelse" { - // The condition is Boolean; absent value branches must use a value-port type. + // Absent value branches must use a value-port type ports.iter().skip(1).find_map(|(_, input)| { input.and_then(|id| indices.get(&id)).and_then(|index| instructions.get(*index)).map(|instruction| instruction.type_code) }) @@ -88,11 +88,18 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu }; let mut connected = connected.into_iter(); let mut inputs = Vec::with_capacity(ports.len()); - for (name, input) in &ports { + for (slot, (name, input)) in ports.iter().enumerate() { let index = match input { Some(_) => connected.next().ok_or("unresolved function input")?, None => { - let (definition, value) = unconnected(name, sibling.unwrap_or(node.type_code))?; + let sibling_type_code = ports + .get(if slot == 0 { 1 } else { 0 }) + .and_then(|(_, input)| **input) + .and_then(|id| indices.get(&id)) + .and_then(|index| instructions.get(*index)) + .map(|instruction| instruction.type_code); + let kind = super::unconnected_input::value_type(&node.op, name, sibling.unwrap_or(node.type_code), sibling_type_code); + let (definition, value) = unconnected(kind)?; let type_code = super::value_type::type_code(&value); instructions.push(Instruction { id: 0, @@ -154,6 +161,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu } let output = indices.get(&output).copied().ok_or("missing result instruction")?; + Ok(Program { instructions, output, seed }) } @@ -173,11 +181,10 @@ fn loop_members(instructions: &[Instruction], index: usize) -> Vec { member.iter().enumerate().filter(|(_, member)| **member).map(|(index, _)| index).collect() } -/// The constant an unconnected input `name` reads: false for a condition, otherwise zero of the type its node works with -fn unconnected(name: &str, type_code: u32) -> Result<(&'static super::FunctionDefinition, materialcraft_core::Value), String> { +/// The constant an unconnected input reads: false or zero of the operand type +fn unconnected(value_type: materialcraft_core::ValueType) -> Result<(&'static super::FunctionDefinition, materialcraft_core::Value), String> { use materialcraft_core::ValueType; - let value_type = if matches!(name, "cond" | "condition") { ValueType::Boolean } else { ValueType::from_code(type_code).unwrap_or(ValueType::Float) }; let operation = match value_type { ValueType::Boolean => "const_bool", ValueType::Integer => "const_int1", @@ -191,5 +198,6 @@ fn unconnected(name: &str, type_code: u32) -> Result<(&'static super::FunctionDe ValueType::String => "const_string", }; let definition = catalog::definition(operation).ok_or("missing constant operation")?; + Ok((definition, value_type.default_value())) } diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index bf58c57e..6d163b82 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -5,6 +5,9 @@ const MAX_EXPANDED_NODES: usize = 131_072; const MAX_CALL_DEPTH: usize = 16; +// Keep absent loop limits aligned with fresh-node defaults +const DEFAULT_LOOP_LIMIT: i32 = 32; + mod arithmetic; mod catalog; mod compile; @@ -24,6 +27,10 @@ mod processor; mod program; mod resolve_instances; mod system_variable; +mod unconnected_input; +#[cfg(test)] +#[path = "unconnected.test.rs"] +mod unconnected_tests; pub mod value_type; mod vector; mod warnings; diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index 2d8282d2..96003c4a 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -169,7 +169,7 @@ impl Program { } LoopCondition { instruction: index, iteration, last } => { let exit = value_type::boolean(&state.values.pop().ok_or("missing loop condition")?)?; - let maximum = self.instruction(index)?.value.as_ref().and_then(Value::as_i32).unwrap_or(100); + let maximum = self.instruction(index)?.value.as_ref().and_then(Value::as_i32).unwrap_or(super::DEFAULT_LOOP_LIMIT); if exit || (maximum >= 0 && iteration >= maximum as u32) { state.values.push(last); } else { diff --git a/crates/nodes/src/function/unconnected.test.rs b/crates/nodes/src/function/unconnected.test.rs new file mode 100644 index 00000000..f30ef160 --- /dev/null +++ b/crates/nodes/src/function/unconnected.test.rs @@ -0,0 +1,75 @@ +use super::{EvaluationContext, EvaluationState, compile, definition}; +use materialcraft_core::{FunctionGraph, Value}; + +#[test] +fn unconnected_typed_operations_use_their_operand_types() { + for (operation, expected) in [ + ("vector3", Value::Float3([0.0; 3])), + ("vector4", Value::Float4([0.0; 4])), + ("ivector2", Value::Int2([0; 2])), + ("ivector3", Value::Int3([0; 3])), + ("ivector4", Value::Int4([0; 4])), + ("iswizzle1", Value::Int(0)), + ("iswizzle4", Value::Int4([0; 4])), + ("tofloat", Value::Float(0.0)), + ("tofloat2", Value::Float2([0.0; 2])), + ("tofloat3", Value::Float3([0.0; 3])), + ("tofloat4", Value::Float4([0.0; 4])), + ("toint2", Value::Int2([0; 2])), + ("toint3", Value::Int3([0; 3])), + ("toint4", Value::Int4([0; 4])), + ("and", Value::Bool(false)), + ("or", Value::Bool(false)), + ("not", Value::Bool(true)), + ("atan2", Value::Float(0.0)), + ("samplelum", Value::Float(0.0)), + ("samplecol", Value::Float4([0.0; 4])), + ] { + let mut graph = FunctionGraph::default(); + let id = graph.add(operation, &[], None); + graph.nodes.first_mut().unwrap().inputs.resize(definition(operation).unwrap().inputs.len(), None); + graph.output = Some(id); + let variables = Default::default(); + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables }; + + let value = compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()); + + assert_eq!(value, Ok(expected), "{operation}"); + } +} + +#[test] +fn partially_connected_vectors_fill_only_the_missing_components() { + for (operation, first, last, expected) in [ + ("vector3", Some(Value::Float2([0.25, 0.75])), None, Value::Float3([0.25, 0.75, 0.0])), + ("vector4", None, Some(Value::Float2([0.25, 0.75])), Value::Float4([0.0, 0.0, 0.25, 0.75])), + ("ivector4", Some(Value::Int(7)), None, Value::Int4([7, 0, 0, 0])), + ] { + let mut graph = FunctionGraph::default(); + let inputs = [first.map(|value| graph.add_constant(value)), last.map(|value| graph.add_constant(value))]; + let id = graph.add(operation, &[], None); + graph.nodes.last_mut().unwrap().inputs = inputs.to_vec(); + graph.output = Some(id); + let variables = Default::default(); + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables }; + + assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()), Ok(expected), "{operation}"); + } +} + +#[test] +fn partially_connected_dot_uses_the_connected_vector_width() { + for vector in [Value::Float3([1.0, 2.0, 3.0]), Value::Float4([1.0, 2.0, 3.0, 4.0])] { + for connected_slot in 0..2 { + let mut graph = FunctionGraph::default(); + let source = graph.add_constant(vector.clone()); + let dot = graph.add("dot", &[], None); + graph.nodes.last_mut().unwrap().inputs = if connected_slot == 0 { vec![Some(source), None] } else { vec![None, Some(source)] }; + graph.output = Some(dot); + let variables = Default::default(); + let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables }; + + assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()), Ok(Value::Float(0.0))); + } + } +} diff --git a/crates/nodes/src/function/unconnected_input.rs b/crates/nodes/src/function/unconnected_input.rs new file mode 100644 index 00000000..b1d78092 --- /dev/null +++ b/crates/nodes/src/function/unconnected_input.rs @@ -0,0 +1,63 @@ +use materialcraft_core::ValueType; + +/// Missing operands have their port's type, which can differ from the result. +pub(super) fn value_type(operation: &str, input_name: &str, inferred_type_code: u32, sibling_type_code: Option) -> ValueType { + if matches!(input_name, "cond" | "condition") || matches!(operation, "and" | "or" | "not") { + return ValueType::Boolean; + } + + if operation == "dot" { + return sibling_type_code + .and_then(ValueType::from_code) + .filter(|kind| matches!(kind, ValueType::Float | ValueType::Float2 | ValueType::Float3 | ValueType::Float4)) + .unwrap_or(ValueType::Float2); + } + + if matches!(operation, "samplelum" | "samplecol" | "atan2") { + return ValueType::Float2; + } + + if operation == "cartesian" || (operation == "mulscalar" && input_name == "scalar") { + return ValueType::Float; + } + + let component_count = operation.chars().last().and_then(|character| character.to_digit(10)).unwrap_or(1); + if operation.starts_with("tofloat") { + return numeric_type(true, component_count); + } + + if operation.starts_with("toint") { + return numeric_type(false, component_count); + } + + if operation.contains("swizzle") { + return numeric_type(operation.starts_with('i'), 1); + } + + if operation.contains("vector") { + let sibling_width = sibling_type_code.and_then(ValueType::from_code).map(|kind| match kind { + ValueType::Integer2 | ValueType::Float2 => 2, + ValueType::Integer3 | ValueType::Float3 => 3, + ValueType::Integer4 | ValueType::Float4 => 4, + _ => 1, + }); + let width = sibling_width + .map_or(if input_name == "componentslast" { 1 } else { component_count.saturating_sub(1) }, |width| component_count.saturating_sub(width)); + return numeric_type(operation.starts_with('i'), width); + } + + ValueType::from_code(inferred_type_code).unwrap_or(ValueType::Float) +} + +fn numeric_type(is_integer: bool, component_count: u32) -> ValueType { + match (is_integer, component_count) { + (true, 2) => ValueType::Integer2, + (true, 3) => ValueType::Integer3, + (true, 4) => ValueType::Integer4, + (true, _) => ValueType::Integer, + (false, 2) => ValueType::Float2, + (false, 3) => ValueType::Float3, + (false, 4) => ValueType::Float4, + (false, _) => ValueType::Float, + } +} diff --git a/crates/nodes/src/parameter.rs b/crates/nodes/src/parameter.rs index fd6f5fd3..d3ca0554 100644 --- a/crates/nodes/src/parameter.rs +++ b/crates/nodes/src/parameter.rs @@ -16,49 +16,54 @@ fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 { if v.is_finite() { v.clamp(lo, hi) } else { fallback } } -pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap) { - for p in &def.params { - let Some(v) = params.get_mut(p.id) else { continue }; - if let Value::Enum(i) = v { - // (an enum without options has nothing to choose from: its default stands) - *i = match (p.options.len().checked_sub(1), &p.default) { - (Some(last), _) => (*i).min(u32::try_from(last).unwrap_or(u32::MAX)), - (None, Value::Enum(d)) => *d, +pub fn clamp_params(definition: &NodeDefinition, params: &mut BTreeMap) { + for parameter in &definition.params { + let Some(value) = params.get_mut(parameter.id) else { continue }; + if let Value::Enum(index) = value { + // Shuffle resolves out-of-range selectors against the connected image kinds + if definition.id == "channels_shuffle" && matches!(parameter.id, "red" | "green" | "blue" | "alpha") { + continue; + } + + // An enum without options keeps its default + *index = match (parameter.options.len().checked_sub(1), ¶meter.default) { + (Some(last), _) => (*index).min(u32::try_from(last).unwrap_or(u32::MAX)), + (None, Value::Enum(default)) => *default, (None, _) => 0, }; continue; } - if let Value::Color(c) = v { - for x in c { - *x = clamp_finite(*x, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0); + if let Value::Color(components) = value { + for component in components { + *component = clamp_finite(*component, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0); } continue; } // An unconstrained Input Value accepts any number; reject only nonnumeric values - let ranged = p.min < p.max; - let span = p.max - p.min; - let (lo, hi) = if ranged { (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span) } else { (f32::MIN, f32::MAX) }; + let ranged = parameter.min < parameter.max; + let span = parameter.max - parameter.min; + let (lo, hi) = if ranged { (parameter.min - HARD_SPAN * span, parameter.max + HARD_SPAN * span) } else { (f32::MIN, f32::MAX) }; - // The default's component `i`, or 0 when the default is a different variant - let fallback = |i: usize| match &p.default { - Value::Float(d) => [*d].get(i).copied(), - Value::Float2(d) => d.get(i).copied(), - Value::Float3(d) => d.get(i).copied(), - Value::Float4(d) => d.get(i).copied(), + // The default's component at `index`, or 0 for a different variant + let fallback = |index: usize| match ¶meter.default { + Value::Float(default) => [*default].get(index).copied(), + Value::Float2(default) => default.get(index).copied(), + Value::Float3(default) => default.get(index).copied(), + Value::Float4(default) => default.get(index).copied(), _ => None, }; - let clamp_at = |x: &mut f32, i: usize| *x = clamp_finite(*x, lo, hi, fallback(i).unwrap_or(0.0)); - let clamp_int = |x: &mut i32| *x = (*x as f32).clamp(lo, hi).round() as i32; - match v { - Value::Float(x) => clamp_at(x, 0), - Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), - Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), - Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), - Value::Int(x) if ranged => clamp_int(x), - Value::Int2(a) if ranged => a.iter_mut().for_each(clamp_int), + let clamp_at = |component: &mut f32, index: usize| *component = clamp_finite(*component, lo, hi, fallback(index).unwrap_or(0.0)); + let clamp_int = |component: &mut i32| *component = (*component as f32).clamp(lo, hi).round() as i32; + match value { + Value::Float(component) => clamp_at(component, 0), + Value::Float2(components) => components.iter_mut().enumerate().for_each(|(index, component)| clamp_at(component, index)), + Value::Float3(components) => components.iter_mut().enumerate().for_each(|(index, component)| clamp_at(component, index)), + Value::Float4(components) => components.iter_mut().enumerate().for_each(|(index, component)| clamp_at(component, index)), + Value::Int(component) if ranged => clamp_int(component), + Value::Int2(components) if ranged => components.iter_mut().for_each(clamp_int), _ => {} } } diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index e3b61a1c..b0999dde 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -8,7 +8,16 @@ fn cook(graph: PatternGraph) -> crate::CookResult { fn cook_with_variables(graph: PatternGraph, variables: &BTreeMap) -> crate::CookResult { let definition = find("fx_map").unwrap(); - let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))])); + + // These traversal fixtures measure unattenuated grayscale stamps + let parameters = resolve_params( + definition, + &BTreeMap::from([ + ("pattern".into(), Value::PatternGraph(Box::new(graph))), + ("roughness".into(), Value::Float(0.0)), + ("color_mode".into(), Value::Bool(false)), + ]), + ); let context = CookContext { format: materialcraft_core::OutputFormat::F32, w: 16, @@ -214,7 +223,14 @@ fn a_full_nine_level_quadtree_renders_one_pattern_per_pixel() { } graph.nodes.last_mut().unwrap().parameters.insert("patterntype".into(), Value::Int(2)); let definition = find("fx_map").unwrap(); - let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))])); + let parameters = resolve_params( + definition, + &BTreeMap::from([ + ("pattern".into(), Value::PatternGraph(Box::new(graph))), + ("roughness".into(), Value::Float(0.0)), + ("color_mode".into(), Value::Bool(false)), + ]), + ); let context = CookContext { format: materialcraft_core::OutputFormat::F32, w: 256, @@ -322,7 +338,14 @@ fn a_pixel_on_the_seam_of_two_patterns_is_drawn_once() { graph.nodes[1].parameters.insert("patterntype".into(), Value::Int(0)); square(&mut graph, 2); let definition = find("fx_map").unwrap(); - let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))])); + let parameters = resolve_params( + definition, + &BTreeMap::from([ + ("pattern".into(), Value::PatternGraph(Box::new(graph))), + ("roughness".into(), Value::Float(0.0)), + ("color_mode".into(), Value::Bool(false)), + ]), + ); let variables = BTreeMap::new(); // Two pixels a side put every pixel center on the corner of four of the sixteen squares diff --git a/crates/nodes/src/raster/composite.rs b/crates/nodes/src/raster/composite.rs index c22ef2a3..36f61408 100644 --- a/crates/nodes/src/raster/composite.rs +++ b/crates/nodes/src/raster/composite.rs @@ -1,13 +1,28 @@ -use materialcraft_image::{Image, Kind}; +use materialcraft_image::{Image, Kind, luminance}; use crate::CookContext; pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { - let background = context.any_or(0, Kind::Color, context.v4("background")); - let image = Image::generate(context.w, context.h, Kind::Color, |x, y| { + let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; + let background = match context.input(0) { + Some(image) if image.kind == kind => image.resize(context.w, context.h, context.tile), + + // An incompatible connection replaces the constant background with empty pixels + Some(_) => Image::filled(1, 1, kind, [0.0; 4]), + None => Image::filled(1, 1, Kind::Color, context.v4("background")), + }; + let gray_background = background.is_gray(); + + // Clamped sampling broadcasts constant backgrounds from one pixel + Image::generate(context.w, context.h, kind, |x, y| { let foreground = foreground(x, y); let background = background.get(i64::from(x), i64::from(y), false); let foreground_alpha = foreground[3].clamp(0.0, 1.0); + if foreground_alpha == 0.0 { + // Empty content must preserve hidden RGB in a transparent background + return if kind == Kind::Gray && !gray_background { [luminance(background), 0.0, 0.0, 0.0] } else { background }; + } + let background_alpha = background[3].clamp(0.0, 1.0) * (1.0 - foreground_alpha); let alpha = foreground_alpha + background_alpha; if alpha <= 0.0 { @@ -15,8 +30,7 @@ pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> } let channel = |index: usize| (foreground[index] * foreground_alpha + background[index] * background_alpha) / alpha; - [channel(0), channel(1), channel(2), alpha] - }); - - if context.b("color_mode") { image } else { image.to_gray() } + let pixel = [channel(0), channel(1), channel(2), alpha]; + if kind == Kind::Gray { [luminance(pixel), 0.0, 0.0, 0.0] } else { pixel } + }) } diff --git a/crates/nodes/tests/atomic_filter_parity.rs b/crates/nodes/tests/atomic_filter_parity.rs new file mode 100644 index 00000000..ce507cd2 --- /dev/null +++ b/crates/nodes/tests/atomic_filter_parity.rs @@ -0,0 +1,156 @@ +use materialcraft_core::{OutputFormat, Value}; +use materialcraft_image::{Image, Kind}; +use materialcraft_nodes::{CookContext, find, resolve_params}; +use std::collections::BTreeMap; + +fn cook(id: &str, inputs: &[Option], values: &[(&str, Value)], size: [u32; 2], tile: bool) -> Image { + let definition = find(id).unwrap(); + let values = values.iter().map(|(key, value)| ((*key).into(), value.clone())).collect(); + let params = resolve_params(definition, &values); + let resource = |_: &str| None; + let vars = BTreeMap::new(); + let context = CookContext { w: size[0], h: size[1], seed: 0, format: OutputFormat::F32, tile, inputs, params: ¶ms, resource: &resource, vars: &vars }; + (definition.cook)(&context).unwrap().remove(0) +} + +#[test] +fn shuffle_reads_grayscale_from_every_selected_channel() { + let inputs = [Some(Image::filled(3, 5, Kind::Gray, [0.25; 4])), Some(Image::filled(3, 5, Kind::Gray, [0.75; 4]))]; + for channel in 0..8 { + let params = ["red", "green", "blue", "alpha"].map(|key| (key, Value::Enum(channel))); + + let output = cook("channels_shuffle", &inputs, ¶ms, [3, 5], true); + + assert_eq!(output.get(1, 2, false), [if channel < 4 { 0.25 } else { 0.75 }; 4], "channel {channel}"); + } +} + +#[test] +fn shuffle_wraps_selectors_over_the_eight_input_channels() { + let inputs = [Some(Image::filled(3, 5, Kind::Color, [0.125, 0.25, 0.375, 0.5])), Some(Image::filled(3, 5, Kind::Color, [0.625, 0.75, 0.875, 1.0]))]; + for channel in [0, 3, 4, 7, 8, 9, 10, 16, 255] { + let params = ["red", "green", "blue", "alpha"].map(|key| (key, Value::Enum(channel))); + + let output = cook("channels_shuffle", &inputs, ¶ms, [3, 5], true); + + assert_eq!(output.get(1, 2, false), [(channel % 8 + 1) as f32 / 8.0; 4], "channel {channel}"); + } + assert_eq!(find("channels_shuffle").unwrap().param("red").unwrap().options.len(), 8); +} + +#[test] +fn shuffle_resolves_out_of_range_selectors_after_input_kind() { + for kinds in [[Kind::Gray, Kind::Gray], [Kind::Color, Kind::Gray], [Kind::Gray, Kind::Color]] { + let inputs = [Some(Image::filled(3, 5, kinds[0], [0.125, 0.25, 0.375, 0.5])), Some(Image::filled(3, 5, kinds[1], [0.625, 0.75, 0.875, 1.0]))]; + let params = [("red", Value::Enum(8)), ("green", Value::Enum(9)), ("blue", Value::Enum(11)), ("alpha", Value::Enum(u32::MAX - 1))]; + + let output = cook("channels_shuffle", &inputs, ¶ms, [3, 5], true); + + let expected = if kinds[1] == Kind::Gray { [0.625; 4] } else { [0.125, 0.125, 1.0, 0.875] }; + + assert_eq!(output.get(1, 2, false), expected, "kinds {kinds:?}"); + } +} + +#[test] +fn sharpen_preserves_float_order_on_ramps() { + let input = Image::gray(16, 16, |x, _| x as f32 / 15.0); + + let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true); + + // Float32 ramps distinguish the Laplacian's arithmetic order + for (x, bits) in [(1, 0x3d88_8889), (3, 0x3e4c_cccb), (7, 0x3eee_eeed), (13, 0x3f5d_ddde)] { + assert_eq!(output.get_gray(x, 7, false).to_bits(), bits, "column {x}"); + } +} + +#[test] +fn sharpen_preserves_finite_hdr_constant() { + let constant = 2.0e38; + let input = Image::filled(16, 16, Kind::Gray, [constant; 4]); + + let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true); + + assert!(output.data.iter().all(|value| value.to_bits() == constant.to_bits())); +} + +#[test] +fn blur_uses_fractional_box_coverage() { + let input = Image::gray(16, 16, |x, y| f32::from(x == 8 && y == 8)); + + let output = cook("blur", &[Some(input)], &[("intensity", Value::Float(10.0))], [16, 16], true); + + // A 0.625-pixel radius covers the center pixel and one eighth of each neighbor + for (x, y, expected) in [(8, 8, 0.64), (7, 8, 0.08), (8, 7, 0.08), (7, 7, 0.01), (6, 8, 0.0)] { + assert!((output.get_gray(x, y, false) - expected).abs() < 1e-7, "at {x},{y}"); + } +} + +#[test] +fn blur_preserves_finite_hdr_constant() { + let input = Image::filled(16, 16, Kind::Gray, [1.0e38; 4]); + + let output = cook("blur", &[Some(input)], &[("intensity", Value::Float(64.0))], [16, 16], true); + + assert!(output.data.iter().all(|value| value.is_finite() && (*value - 1.0e38).abs() < 1.0e32)); +} + +#[test] +fn directional_blur_uses_full_radius_and_fractional_endpoints() { + let input = Image::gray(256, 256, |x, y| f32::from(x == 128 && y == 128)); + + let output = cook("directional_blur", &[Some(input)], &[("intensity", Value::Float(4.0))], [256, 256], true); + + for offset in -4..=4 { + let expected = if offset == -4 || offset == 4 { 0.0625 } else { 0.125 }; + + assert_eq!(output.get_gray(128 + offset, 128, false), expected, "offset {offset}"); + } + assert_eq!(output.get_gray(128, 129, false), 0.0); +} + +#[test] +fn sharpen_has_center_gain_and_clamps_negative_lobes() { + let input = Image::gray(16, 16, |x, y| f32::from(x == 8 && y == 8)); + + let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true); + + assert_eq!(output.get_gray(8, 8, false), 5.0); + assert!(output.data.iter().all(|value| *value >= 0.0)); +} + +#[test] +fn empty_raster_preserves_transparent_rgb_and_rejects_mismatched_background_kind() { + for id in ["text", "svg"] { + let pixel = [0.25, 0.5, 0.75, 0.0]; + let color = Some(Image::filled(16, 16, Kind::Color, pixel)); + let gray = Some(Image::filled(16, 16, Kind::Gray, [0.25; 4])); + + let output = cook(id, std::slice::from_ref(&color), &[("color_mode", Value::Bool(true))], [16, 16], true); + + assert_eq!(output.get(0, 0, false), pixel, "{id} transparent color"); + + let output = cook(id, &[color], &[("color_mode", Value::Bool(false))], [16, 16], true); + + assert_eq!(output.get_gray(0, 0, false), 0.0, "{id} color into gray"); + + let output = cook(id, &[gray], &[("color_mode", Value::Bool(true))], [16, 16], true); + + assert_eq!(output.get(0, 0, false), [0.0; 4], "{id} gray into color"); + } +} + +#[test] +fn rectangular_filters_scale_from_the_shorter_side() { + for size in [[32, 16], [16, 32]] { + let input = Image::gray(size[0], size[1], |x, y| f32::from(x == size[0] / 2 && y == size[1] / 2)); + for (operation, expected) in [("blur", 0.64), ("directional_blur", 0.8)] { + let output = cook(operation, &[Some(input.clone())], &[("intensity", Value::Float(10.0))], size, true); + + assert!((output.get_gray(i64::from(size[0] / 2), i64::from(size[1] / 2), false) - expected).abs() < 1e-7, "{operation}, {size:?}"); + } + let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], size, true); + + assert_eq!(output.get_gray(i64::from(size[0] / 2), i64::from(size[1] / 2), false), 4.0, "{size:?}"); + } +} diff --git a/crates/nodes/tests/brick_primitives.rs b/crates/nodes/tests/brick_primitives.rs index e25f65a9..de220818 100644 --- a/crates/nodes/tests/brick_primitives.rs +++ b/crates/nodes/tests/brick_primitives.rs @@ -3,8 +3,15 @@ use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find, resolve_params}; use std::collections::BTreeMap; -fn cook(def: &str, values: BTreeMap, inputs: &[Option]) -> Image { +fn cook(def: &str, mut values: BTreeMap, inputs: &[Option]) -> Image { let definition = find(def).unwrap(); + + // Geometry and maximum-blend fixtures use unattenuated grayscale patterns + if def == "fx_map" { + values.entry("roughness".into()).or_insert(Value::Float(0.0)); + values.entry("color_mode".into()).or_insert(Value::Bool(false)); + } + let params = resolve_params(definition, &values); let context = CookContext { format: materialcraft_core::OutputFormat::F32, diff --git a/crates/nodes/tests/parity_unconnected.rs b/crates/nodes/tests/parity_unconnected.rs new file mode 100644 index 00000000..f34bcc81 --- /dev/null +++ b/crates/nodes/tests/parity_unconnected.rs @@ -0,0 +1,56 @@ +use materialcraft_core::{OutputFormat, Value}; +use materialcraft_image::Kind; +use materialcraft_nodes::{CookContext, find, resolve_params}; +use std::collections::BTreeMap; + +#[test] +fn absent_textures_have_zero_pixels_and_expected_kinds() { + for (id, kind, pixel) in [ + ("channels_shuffle", Kind::Color, [0.0; 4]), + ("hsl", Kind::Color, [0.0; 4]), + ("emboss", Kind::Gray, [0.0, 0.0, 0.0, 1.0]), + ("gradient_dynamic", Kind::Gray, [0.0, 0.0, 0.0, 1.0]), + ] { + let definition = find(id).unwrap(); + let params = resolve_params(definition, &BTreeMap::new()); + let resource = |_: &str| None; + let vars = BTreeMap::new(); + for (w, h) in [(16, 16), (32, 16), (3, 5)] { + let context = CookContext { w, h, seed: 0, format: OutputFormat::F32, tile: true, inputs: &[], params: ¶ms, resource: &resource, vars: &vars }; + + let outputs = (definition.cook)(&context).unwrap(); + let image = outputs.first().unwrap(); + + assert_eq!(image.kind, kind, "{id}"); + for y in 0..h { + for x in 0..w { + assert_eq!(image.get(x.into(), y.into(), false), pixel, "{id} at {x},{y}"); + } + } + } + } +} + +#[test] +fn fresh_catalog_defaults_have_expected_values() { + for (id, parameter, expected) in [ + ("uniform", "color", Value::Color([0.0, 0.0, 0.0, 1.0])), + ("blur", "intensity", Value::Float(10.0)), + ("distance", "combine", Value::Bool(true)), + ("emboss", "light_angle", Value::Float(0.0)), + ("emboss", "shadow", Value::Color([0.0; 4])), + ("fx_map", "roughness", Value::Float(1.0)), + ("fx_map", "color_mode", Value::Bool(true)), + ("gradient_dynamic", "position", Value::Float(0.0)), + ("grayscale_conversion", "matte", Value::Float(1.0)), + ("normal", "opengl", Value::Bool(false)), + ("normal", "height_alpha", Value::Bool(true)), + ("text", "fontsize", Value::Float(0.25)), + ("text", "text", Value::Text(String::new())), + ] { + assert_eq!(find(id).unwrap().param(parameter).unwrap().default, expected, "{id}.{parameter}"); + } + for (op, expected) in [("const_float1", Value::Float(0.0)), ("const_float4", Value::Float4([0.0; 4])), ("while", Value::Int(32))] { + assert_eq!(materialcraft_nodes::function::default_value(op), Some(expected), "{op}"); + } +} diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index a013e61f..41d0d727 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -247,7 +247,7 @@ impl Default for Settings { tiling: 1.0, exposure: 0.0, env_rotation: 0.0, - normal_y_flip: false, + normal_y_flip: true, show_env: false, supersample: 1, ao_rays: 0, diff --git a/crates/ui-egui/tests/it/normal_maps.rs b/crates/ui-egui/tests/it/normal_maps.rs index 8ecde36f..fcb427be 100644 --- a/crates/ui-egui/tests/it/normal_maps.rs +++ b/crates/ui-egui/tests/it/normal_maps.rs @@ -11,43 +11,48 @@ fn app() -> MaterialCraftApp { app } -fn settle(h: &mut Harness<'static, MaterialCraftApp>, after: u64) { - for _ in 0..300 { - h.step(); - let app = h.state(); +fn settle(harness: &mut Harness<'static, MaterialCraftApp>, after: u64) { + const RENDER_ATTEMPTS: usize = 300; + const POLL_INTERVAL: Duration = Duration::from_millis(10); + for _ in 0..RENDER_ATTEMPTS { + harness.step(); + let app = harness.state(); if app.view3d.renders > after && !app.session.dirty && !app.cooker.busy() && !app.view3d.busy() { return; } - std::thread::sleep(Duration::from_millis(10)); + + std::thread::sleep(POLL_INTERVAL); } panic!("the normal-map preview did not finish rendering"); } -fn toggle(h: &mut Harness<'static, MaterialCraftApp>) { - h.get_by_label("Display").click(); - h.run_steps(4); - h.get_by_label("Flip normal map Y (DirectX)").click(); - h.run_steps(4); +fn toggle(harness: &mut Harness<'static, MaterialCraftApp>) { + harness.get_by_label("Display").click(); + harness.run_steps(4); + harness.get_by_label("Flip normal map Y (DirectX)").click(); + harness.run_steps(4); } #[test] #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] fn normal_convention_snapshot() { - let mut h = Harness::builder().with_size(vec2(1400.0, 860.0)).wgpu().build_ui_state( + let mut harness = Harness::builder().with_size(vec2(1400.0, 860.0)).wgpu().build_ui_state( |ui, app: &mut MaterialCraftApp| { app.step(&ui.ctx().clone()); app.draw(ui); }, app(), ); - settle(&mut h, 0); - let rendered = h.state().view3d.renders; - toggle(&mut h); - settle(&mut h, rendered); - h.get_by_label("Display").click(); - h.run_steps(4); - assert!(h.state().session.view3d.normal_y_flip); - let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("MC_SNAPSHOT_DIR")); - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("normal-convention.png")).unwrap(); + settle(&mut harness, 0); + let rendered = harness.state().view3d.renders; + toggle(&mut harness); + settle(&mut harness, rendered); + harness.get_by_label("Display").click(); + harness.run_steps(4); + + assert!(!harness.state().session.view3d.normal_y_flip); + + let snapshot_dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&snapshot_dir).unwrap(); + harness.render().unwrap().save(snapshot_dir.join("normal-convention.png")).unwrap(); } diff --git a/docs/architecture.md b/docs/architecture.md index d3ab9e42..c9fec52b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,7 +12,7 @@ L0 core document model: Package → Graph → Node / Connection / Frame / L0 image Image: grayscale or RGBA f32 planes behind an Arc (copy-on-write, free to share); wrap/clamp sampling, bilinear, box/bilinear resampling, sRGB, 8-bit display L0 geom meshes, primitives (rounded cube, sphere, cylinder, plane, torus, material ball), BVH, camera -L1 nodes 30 main-graph entries (NodeDefinition), 85 function operations, four pattern node kinds; +L1 nodes 29 main-graph entries (NodeDefinition), 85 function operations, four pattern node kinds; shared image operations and iterative function/pattern execution L2 eval cooking: topological order, output sizes (relative to input / parent, absolute, preview cap), parameter resolution (defaults, overrides, bindings to exposed inputs), the diff --git a/docs/atomic-parity-improvements.md b/docs/atomic-parity-improvements.md new file mode 100644 index 00000000..45cbbbfe --- /dev/null +++ b/docs/atomic-parity-improvements.md @@ -0,0 +1,62 @@ +# Atomic node corrections + +These changes correct filtering, channel selection and empty-content compositing in +MaterialCraft. Catalog membership and bundled SBS assets are unchanged. + +## Behavior changes + +- Blur uses a separable box filter with fractional endpoint coverage and bounded running + sums. Non-finite samples stop affecting a window after they leave it. +- Directional Blur uses the full radius, weighted endpoints and image-space rotation. + Its sampling budget is bounded for large strengths. +- Sharpen uses a four-neighbor Laplacian, processes alpha, clamps negative lobes and retains + HDR output. Explicit Float32 operation order preserves cancellation behavior on ramps. +- All three filters scale from the shorter image dimension and honor horizontal and + vertical tiling independently. Tiling changes invalidate the cook cache. +- Channels Shuffle supplies a grayscale scalar through all ordinary channel selections, + including alpha. Color inputs retain their alpha. Signed and oversized saved selectors + remain intact until input kinds determine channel selection. +- Empty Text/SVG content preserves background pixels, including hidden RGB under zero + alpha. Incompatible background kinds produce empty pixels; matching gray backgrounds + retain their scalar values. + +Channels Shuffle now offers eight input-channel choices. Graphs using the former +Black/White choices follow the corrected selector behavior. Use a Uniform Color input +for constant channels. + +## Regression coverage + +Local tests cover fractional filter footprints, directional extent, sharpen gain and +Float32 cancellation, rectangular images, independent tiling and cache invalidation, +gray/color channel selection, signed-selector round trips and transparent backgrounds: + +- [Filter and channel tests](../crates/nodes/tests/atomic_filter_parity.rs) +- [Tiling and cache tests](../crates/eval/tests/filter_tiling.rs) +- [SBS round-trip tests](../crates/formats/src/sbs/tests.rs) + +Save/load fixtures use explicit blur strengths and compatible background kinds so their +binding and connection-preservation assertions retain their purpose. + +## Remaining limits + +Full numerical compatibility remains unestablished. Open work includes oblique sampling, +floating-point rounding and quantization, mixed input/output resolutions, non-default +Sharpen alpha behavior and nonempty Text/SVG rasterization. Processor and map execution +limits are summarized in the [catalog status](node-catalog-parity.md). + +## Validation + +Recorded release tests for nodes, formats, eval and engine pass, including +`every_node_cooks` and `panic_hunt`. Formatting, +workspace Clippy with `--all-targets -- -D warnings`, dependency layers and all ten wasm +checks pass. + +These checks cover the listed crates and targets; other build and runtime environments +have not been validated by this local run. + +The optional `filter_timing` example benchmarks MaterialCraft's Blur, Directional Blur +and Sharpen on generated images at 512 and 1024 pixels. It uses no external application: + +```sh +cargo run -p materialcraft-nodes --release --example filter_timing +``` diff --git a/docs/atomic-workflow.md b/docs/atomic-workflow.md index 65462e53..ec5b95a8 100644 --- a/docs/atomic-workflow.md +++ b/docs/atomic-workflow.md @@ -61,10 +61,15 @@ cargo +1.96.0 run -p materialcraft-engine --release --example atomic_sample -- e | Context | Entries | |---|---:| -| Main graph | 26 native primitives, including processors and reroute, plus 4 input/output items | +| Main graph | 25 native primitives, including processors and reroute, plus 4 input/output items | | Functions | 85 native operations | | FX-Map graph | Quadrant (`paramset`), Switch (`markov2`), Iterate (`addnode`), Dot (`passthrough`) | +The former count of 26 primitives included `motion_blur`, removed in commit `a0032d6`. +It was a MaterialCraft wrapper around Directional Blur. The count of 25 includes Dot/reroute. +The [catalog status](node-catalog-parity.md) records the current 25 primitives plus four +input/output entries. + Image primitives have individual files in `crates/nodes/src/atomic/`. Function evaluation and pattern traversal have separate modules. Document types each live in their own file under `crates/core/src/`. SBS parsing and writing live under `crates/formats/src/sbs/`. @@ -82,9 +87,9 @@ SBS library reference resolution is outside this change. ## Current limits -- Reopening the generated SBS in the reference application has not been verified -- Native IDs, ports and types are mapped, but numerical parity with the reference renderer has - not been established, including pattern shapes, blending, sampling and random sequences +- SBS version-header compatibility remains unresolved +- Node IDs, ports and types are mapped. The [catalog status](node-catalog-parity.md) records + remaining numerical and interoperability gaps; broad rendering parity is unestablished - Text renders the original built-in stroke font; external font references produce an explicit error. SVG supports vector geometry, without external images or font loading - Some native parameter variants and package/editor metadata remain unsupported; import reports diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b4ec34d1..59341559 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -116,7 +116,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `graph.node.reset` | `{id?, param?, base?}` removes the driver and restores defaults; omit `param` to reset the selected parameter section | | `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values | | `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance | -| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default false/OpenGL), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | +| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default true/DirectX), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | | `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) | | `library.list` | `{filter?, category?}`: every node with ports and parameters | | `library.tree` | `{filter?, category? (Top or Top/Sub), canvas? (material\|function\|pattern)}`: the Library panel's category tree and its entries. Each entry has `id`, `label`, `category`, `type` (`node`, `comment`, `frame`, `pin`, `instance`, `operation`, `functionInstance`, `pattern`, `bitmap`), the `canvas` that takes it (`any` for shared graph items), `missing` when MaterialCraft lacks the library package it needs, and `warning` when it can be added but is incomplete | diff --git a/docs/gaps.md b/docs/gaps.md index d172809a..35b367aa 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,5 +1,10 @@ # Gaps +The [catalog status](node-catalog-parity.md) records implemented corrections and untested +behavior, including all 954 loaded package function bodies. The +[atomic corrections](atomic-parity-improvements.md) cover filters, channel selection and +empty Text/SVG backgrounds. Sampling, precision, processor and map gaps remain open. + > The assessment below predates the 2026-11-05 primitive rewrite. Its old library counts and > compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and > [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation. diff --git a/docs/node-catalog-parity.md b/docs/node-catalog-parity.md new file mode 100644 index 00000000..a41dd15c --- /dev/null +++ b/docs/node-catalog-parity.md @@ -0,0 +1,57 @@ +# Node catalog status + +MaterialCraft is a clean-room implementation. This page summarizes available catalogs, +implemented corrections and remaining compatibility work. + +## Inventory + +| Catalog | Entries | +|---|---:| +| Main graph | 29: 25 primitives and four input/output items | +| Function graph | 85 operations | +| FX-Map graph | Quadrant, Switch, Iterate and Dot | +| Loaded package functions | 954, including 689 hidden entries | + +The earlier count of 26 primitives included the removed `motion_blur` wrapper around +Directional Blur. The current count of 25 includes Dot/reroute. These corrections change +no catalog membership. + +Package counts describe availability. Function-body behavior and redistribution rights +require separate verification; the 954 loaded package function bodies remain untested. + +## Implemented corrections + +- Missing function operands use their input types, including vectors, casts, Boolean + operations and sampler coordinates. Partially connected vectors retain connected lanes. +- Missing textures produce appropriate zero pixels and image kinds in Channels Shuffle, + HSL, Emboss and Dynamic Gradient. +- Fresh-node defaults are corrected for Uniform Color, function constants, loop limits + and several image and pattern nodes. +- Grayscale image-input defaults serialize as scalars. Function loop limits use the scalar + integer tag. Channel selector values survive signed SBS save/load. +- Filter kernels, rectangular scaling, independent tiling, channel selection and empty + Text/SVG backgrounds are covered in [atomic node corrections](atomic-parity-improvements.md). + +Regression coverage lives in the nodes, formats and eval test suites. These tests execute +MaterialCraft code and use original procedural fixtures. + +## Remaining work + +Full behavioral parity is unestablished. Outstanding areas include: + +- Filter sampling, image boundaries and output sizing. +- Scalar/vector conversions, invalid-input handling, overflow and precision policy. +- Function execution order, shared state, loop behavior and variable scope. +- Random sequences, sampler coordinates and explicit addressing modes. +- FX-Map shape rasterization, roughness/depth weighting and assignment scope. +- Nonempty text/vector rendering, arbitrary SBS round trips and version-header compatibility. + +Exhaustive parameter combinations, deeply nested processors/maps, arbitrary non-finite +payloads, dynamic resource selection and every resolution/aspect ratio remain untested. +Local safety tests cover cycles, allocation limits and execution budgets. + +## Validation limits + +Release suites for nodes, formats, eval and engine pass locally, including the +SBS resource-substitution test. Formatting, workspace Clippy, dependency layers +and wasm checks pass. Other targets and runtime environments remain unverified. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 82e26ec1..a411a502 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,5 +1,11 @@ # Parity with the reference workflow +The [catalog status](node-catalog-parity.md) covers 29 main-graph entries, 85 function +operations, four map kinds and 954 loaded package functions. The +[atomic corrections](atomic-parity-improvements.md) describe filter, channel-selection +and background fixes with local regression coverage. Full numerical parity remains +unestablished. + > The assessment below predates the 2026-11-05 primitive rewrite. Its old library counts and > compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and > [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation. diff --git a/docs/wires-and-alpha.md b/docs/wires-and-alpha.md index ebcffde1..0c513f11 100644 --- a/docs/wires-and-alpha.md +++ b/docs/wires-and-alpha.md @@ -86,11 +86,11 @@ session. ## Alpha in the 3D view -The 3D view reads OpenGL normal maps by default, matching the Normal node's default format. -For a DirectX normal map, enable **Display ▸ Flip normal map Y (DirectX)**, or run -`view.3d {"normalYFlip": true}`. Choose the corresponding format in the Normal node's properties. +The 3D view reads DirectX normal maps by default, matching the Normal node's default format. +For an OpenGL normal map, disable **Display ▸ Flip normal map Y (DirectX)**, or run +`view.3d {"normalYFlip": false}`. Choose the corresponding format in the Normal node's properties. The setting affects both the interactive view and headless renders, appears as `view3d.normalYFlip` -in `session.inspect`, and returns to OpenGL when the scene is reset. +in `session.inspect`, and returns to DirectX when the scene is reset.

The same sphere in the alpha channel view: the opaque grid lines are white and the clear gaps black