From 9744afda8342dab14aec7246068bc5edae36f16a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:59:55 -0800 Subject: [PATCH 1/3] Image: use craft-texture's image planes and sampling Replace the local materialcraft-image crate with craft-texture from storytold/craft-libs (storytold/craft-libs#1216), with its parallel feature on. engine re-exports it as `engine::image`. Every craft-libs dependency moves to the same revision, 29fb8f8e. The image fields are private in craft-texture. Callers read them through width(), height(), kind() and data(), and decoders, the pixel processor and the pattern raster build images with Image::from_data, which rejects an empty size or a buffer of the wrong length with an error. This changes some pixels at the edges of the float range: - a repeated sample far from the origin keeps its phase instead of stopping at a clamped texel position - generate_uv spreads its coordinates over the clamped size - bilinear samples and box downsampling of values near f32::MAX stay finite - linear_to_srgb(NaN) returns NaN instead of -0.055 The box blur's running sum in nodes/src/ops.rs now uses f64 as well, so a blur of values near f32::MAX no longer overflows. #225 fixes the generate_uv fault in the local crate; craft-texture includes that fix. --- AGENTS.md | 2 +- Cargo.lock | 45 +- Cargo.toml | 21 +- README.md | 2 +- crates/automation/src/headless.rs | 2 +- crates/engine/Cargo.toml | 2 +- crates/engine/src/graph_cmds.rs | 2 +- crates/engine/src/inspect.rs | 4 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/material_cmds.rs | 10 +- crates/engine/src/material_options.rs | 2 +- crates/engine/src/material_preview.rs | 2 +- crates/engine/src/session.rs | 4 +- crates/engine/src/session.test.rs | 6 +- crates/engine/tests/it/atomics.rs | 8 +- crates/engine/tests/it/export_names.rs | 2 +- crates/engine/tests/it/parameter_functions.rs | 12 +- crates/engine/tests/it/subgraph_seed.rs | 10 +- crates/engine/tests/session.rs | 12 +- crates/eval/Cargo.toml | 2 +- crates/eval/src/cache_key.rs | 14 +- crates/eval/src/cooked.rs | 2 +- crates/eval/src/graph_execution.rs | 4 +- crates/eval/src/graph_instance.rs | 4 +- crates/eval/src/graph_output.rs | 2 +- crates/eval/src/node_execution.rs | 2 +- crates/eval/src/node_output.rs | 4 +- crates/eval/src/options.rs | 2 +- crates/eval/src/resource_decoder.rs | 2 +- crates/eval/src/tests.rs | 57 +-- crates/eval/src/value_execution.rs | 2 +- crates/formats/Cargo.toml | 2 +- crates/formats/src/dds_image.rs | 4 +- crates/formats/src/image.rs | 17 +- crates/formats/src/sbs/tests.rs | 2 +- crates/formats/src/svg.rs | 2 +- crates/formats/src/tests.rs | 6 +- crates/formats/tests/bitmap_imports.rs | 18 +- crates/formats/tests/project_packages.rs | 2 +- crates/image/Cargo.toml | 13 - crates/image/src/lib.rs | 384 ------------------ crates/nodes/Cargo.toml | 2 +- crates/nodes/src/atomic/bitmap.rs | 2 +- crates/nodes/src/atomic/blend.rs | 2 +- crates/nodes/src/atomic/blur.rs | 2 +- crates/nodes/src/atomic/channels_shuffle.rs | 2 +- crates/nodes/src/atomic/curve.rs | 4 +- crates/nodes/src/atomic/directional_blur.rs | 4 +- crates/nodes/src/atomic/directional_warp.rs | 4 +- crates/nodes/src/atomic/distance.rs | 8 +- crates/nodes/src/atomic/dot.rs | 2 +- crates/nodes/src/atomic/emboss.rs | 4 +- crates/nodes/src/atomic/gradient_dynamic.rs | 4 +- crates/nodes/src/atomic/gradient_map.rs | 2 +- .../nodes/src/atomic/grayscale_conversion.rs | 2 +- crates/nodes/src/atomic/hsl.rs | 2 +- crates/nodes/src/atomic/input_color.rs | 2 +- crates/nodes/src/atomic/input_grayscale.rs | 2 +- crates/nodes/src/atomic/levels.rs | 4 +- crates/nodes/src/atomic/normal.rs | 4 +- crates/nodes/src/atomic/output.rs | 4 +- crates/nodes/src/atomic/sharpen.rs | 4 +- crates/nodes/src/atomic/text.rs | 2 +- crates/nodes/src/atomic/transformation.rs | 4 +- crates/nodes/src/atomic/uniform.rs | 2 +- crates/nodes/src/atomic/warp.rs | 4 +- crates/nodes/src/cook_context.rs | 4 +- .../nodes/src/function/evaluation_context.rs | 2 +- crates/nodes/src/function/operation.rs | 2 +- crates/nodes/src/function/processor.rs | 7 +- crates/nodes/src/function/tests.rs | 2 +- crates/nodes/src/lib.rs | 2 +- crates/nodes/src/ops.rs | 48 ++- crates/nodes/src/pattern/raster.rs | 16 +- crates/nodes/src/pattern/tests.rs | 2 +- crates/nodes/src/raster/composite.rs | 2 +- crates/nodes/src/tests.rs | 65 ++- crates/nodes/tests/distance.rs | 10 +- crates/render/Cargo.toml | 2 +- crates/render/src/preview.rs | 6 +- crates/ui-egui/src/export/export_tests.rs | 2 +- crates/ui-egui/src/graph/canvas.rs | 8 +- crates/ui-egui/src/levels_editor.rs | 6 +- crates/ui-egui/src/view2d.rs | 32 +- crates/ui-egui/tests/it/preview_resolution.rs | 6 +- crates/ui-egui/tests/it/resolution.rs | 8 +- crates/ui-egui/tests/snapshot.rs | 4 +- docs/architecture.md | 4 +- xtask/src/layers.rs | 4 +- xtask/src/main.rs | 1 - 90 files changed, 348 insertions(+), 672 deletions(-) delete mode 100644 crates/image/Cargo.toml delete mode 100644 crates/image/src/lib.rs diff --git a/AGENTS.md b/AGENTS.md index 2d250fe..f89a659 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,7 +89,7 @@ file first, then `docs/`. ```text crates/ - core image geom L0 document model (package, graphs, nodes, values, function graphs); float images; meshes, BVH, camera + core geom L0 document model (package, graphs, nodes, values, function graphs); meshes, BVH, camera nodes L1 the node library: native primitive definitions + CPU cooks, function evaluator and pattern graphs eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); native .sbs packages, bitmaps, texture export engine render L3 Session + command registry (every action is a command), inspect, samples; the 3D preview renderer (CPU PBR + IBL) diff --git a/Cargo.lock b/Cargo.lock index 4fadfc6..cb4631b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -810,7 +810,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -823,12 +823,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "fixed_decimal", "icu_decimal", @@ -851,7 +851,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "egui", "serde", @@ -861,7 +861,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "craft-keymap", "craft-quit", @@ -874,7 +874,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "dispatch2", "egui", @@ -882,10 +882,19 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-texture" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -906,7 +915,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "chrono", "dunce", @@ -933,7 +942,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=29fb8f8e860677e375263f9c8f4debe129d7add4#29fb8f8e860677e375263f9c8f4debe129d7add4" dependencies = [ "egui", "objc2 0.6.5", @@ -2664,11 +2673,11 @@ dependencies = [ name = "materialcraft-engine" version = "0.4.1" dependencies = [ + "craft-texture", "materialcraft-core", "materialcraft-eval", "materialcraft-formats", "materialcraft-geom", - "materialcraft-image", "materialcraft-nodes", "serde", "serde_json", @@ -2679,8 +2688,8 @@ dependencies = [ name = "materialcraft-eval" version = "0.4.1" dependencies = [ + "craft-texture", "materialcraft-core", - "materialcraft-image", "materialcraft-nodes", "serde", "serde_json", @@ -2692,13 +2701,13 @@ version = "0.4.1" dependencies = [ "base64 0.22.1", "bytemuck", + "craft-texture", "dds", "flate2", "gltf", "image", "materialcraft-core", "materialcraft-geom", - "materialcraft-image", "materialcraft-nodes", "resvg", "roxmltree 0.20.0", @@ -2720,20 +2729,12 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "materialcraft-image" -version = "0.4.1" -dependencies = [ - "rayon", - "thiserror 2.0.21", -] - [[package]] name = "materialcraft-nodes" version = "0.4.1" dependencies = [ + "craft-texture", "materialcraft-core", - "materialcraft-image", "rayon", ] @@ -2741,9 +2742,9 @@ dependencies = [ name = "materialcraft-render" version = "0.4.1" dependencies = [ + "craft-texture", "materialcraft-core", "materialcraft-geom", - "materialcraft-image", "rayon", ] diff --git a/Cargo.toml b/Cargo.toml index a5be53c..14ab52c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,6 @@ resolver = "3" members = [ "crates/core", - "crates/image", "crates/geom", "crates/nodes", "crates/eval", @@ -20,7 +19,6 @@ exclude = ["vendor"] # The web app only builds for wasm32 (trunk); everything else is the default. default-members = [ "crates/core", - "crates/image", "crates/geom", "crates/nodes", "crates/eval", @@ -45,7 +43,6 @@ repository = "https://github.com/storytold/materialcraft" resvg = { version = "0.47", default-features = false } # internal materialcraft-core = { path = "crates/core" } -materialcraft-image = { path = "crates/image" } materialcraft-geom = { path = "crates/geom" } materialcraft-nodes = { path = "crates/nodes" } materialcraft-eval = { path = "crates/eval" } @@ -86,18 +83,20 @@ getrandom = "0.3" # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, every craft-libs crate pinned to one rev. egui_kittest = "0.37" -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["serde"] } # Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0. -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["egui"] } # Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0. -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4" } # The platform quit and the macOS Quit menu item: storytold/craft-libs, MIT OR Apache-2.0. -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["egui"] } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4" } # Who draws the window frame, and an app-drawn strip as the title bar: storytold/craft-libs, MIT OR Apache-2.0. -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["egui"] } # Release checks and self-updates for the desktop app: storytold/craft-libs, MIT OR Apache-2.0. -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["egui"] } +# Float image planes and texture sampling for node cooking: storytold/craft-libs, MIT OR Apache-2.0. +craft-texture = { git = "https://github.com/storytold/craft-libs", rev = "29fb8f8e860677e375263f9c8f4debe129d7add4", features = ["parallel"] } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] @@ -154,7 +153,7 @@ strip = "debuginfo" opt-level = "s" # Node cooking and the vector math under it run per pixel. -[profile.wasm-release.package.materialcraft-image] +[profile.wasm-release.package.craft-texture] opt-level = 3 [profile.wasm-release.package.materialcraft-nodes] opt-level = 3 diff --git a/README.md b/README.md index b577b34..0dc9428 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,7 @@ operations and three pattern node kinds. Start with **File → New → Atomic sa 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. -**Workspace:** `crates/{core, image, geom, nodes, eval, formats, engine, render, automation, ui-egui}` +**Workspace:** `crates/{core, geom, nodes, eval, formats, engine, render, automation, ui-egui}` and `apps/{materialcraft, materialcraft-cli, materialcraft-web}`. The egui frontend is its own crate, so the UI can be swapped without touching the engine; [`docs/architecture.md`](docs/architecture.md) explains how it fits together. diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 836fcdf..4c34f3c 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -270,7 +270,7 @@ impl Headless { None => self.session.view2d_image().map(|(_, i)| i).ok_or_else(|| bad("nothing to show: the graph has no outputs; pass `node`"))?, }; - let (w, h) = (o.width.unwrap_or(img.w).clamp(16, max), o.height.unwrap_or(img.h).clamp(16, max)); + let (w, h) = (o.width.unwrap_or(img.width()).clamp(16, max), o.height.unwrap_or(img.height()).clamp(16, max)); let img = img.resize(w, h, true); Ok((w, h, img.to_rgba8_display())) } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 5eb7c48..309cbd3 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-nodes = { workspace = true } materialcraft-eval = { workspace = true } materialcraft-formats = { workspace = true } diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 5f115af..a05ee94 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -168,7 +168,7 @@ fn cook(s: &mut Session, p: &J) -> Result { "nodes": cooked.nodes.iter().map(|(id, r)| { let n = g.node(*id).ok(); json!({"id": id.0, "def": n.map(|n| n.def.clone()), "ms": r.ms, "cached": r.cached, "error": r.error, - "size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.w, i.h])}) + "size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.width(), i.height()])}) }).collect::>(), })) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index d410c29..1f7f242 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -32,7 +32,7 @@ pub fn session(session: &Session, requested_graph: Option) -> J { "error": entry.error, "ms": entry.ms, "cached": entry.cached, "base": entry.base, "baseValues": entry.base_values, "parameters": entry.parameters, "value": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_value), - "size": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.w, image.h]), + "size": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.width(), image.height()]), "kind": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| if image.is_gray() { "gray" } else { "color" }), "mean": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| image.mean()), })); @@ -81,7 +81,7 @@ pub fn session(session: &Session, requested_graph: Option) -> J { "assignments": session.material_preview, "channels": session.material_preview.sources(&session.pkg).into_iter().map(|(channel, source)| { let image = session.material_image(&source); - json!({"channel": channel, "source": source, "size": image.map(|image| [image.w, image.h]), "mean": image.map(|image| image.mean())}) + json!({"channel": channel, "source": source, "size": image.map(|image| [image.width(), image.height()]), "mean": image.map(|image| image.mean())}) }).collect::>(), }, "previewSize": session.preview_size, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7557cc8..d882eac 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -82,10 +82,10 @@ pub use color_space::ColorSpace; pub use export_request::ExportRequest; pub use export_size::ExportSize; +pub use craft_texture as image; pub use materialcraft_core as core; pub use materialcraft_eval as eval; pub use materialcraft_formats as formats; -pub use materialcraft_image as image; pub use materialcraft_nodes as nodes; mod engine_error; diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index d262c67..d42f868 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -3,14 +3,14 @@ use std::collections::BTreeMap; use serde_json::{Value as J, json}; +#[cfg(test)] +use craft_texture::Image; use materialcraft_core::ComponentUsage; use materialcraft_core::Graph; #[cfg(any(test, not(target_arch = "wasm32")))] use materialcraft_core::Value; use materialcraft_formats::material::{FORMAT, ImageInput, Manifest, MapEntry, Parameter, PresetEntry, VERSION, portable, srgb_usage}; use materialcraft_formats::{Depth, encode}; -#[cfg(test)] -use materialcraft_image::Image; #[cfg(not(target_arch = "wasm32"))] use crate::commands::u64p; @@ -81,7 +81,7 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result = s.group("Temporary", |s| { execute(s, "graph.node.param", &json!({"id": id.0, "param": "color", "value": [0.1, 0.8, 0.2, 1.0]}))?; s.cook(); @@ -195,5 +195,5 @@ fn a_failed_group_recooks_if_it_cooked_a_temporary_document() { }); assert!(result.is_err()); s.cook_if_dirty(); - assert_eq!(s.cooked.image(id, 0).unwrap().data, before); + assert_eq!(s.cooked.image(id, 0).unwrap().data(), before.as_slice()); } diff --git a/crates/engine/tests/it/atomics.rs b/crates/engine/tests/it/atomics.rs index 968fab9..08069ad 100644 --- a/crates/engine/tests/it/atomics.rs +++ b/crates/engine/tests/it/atomics.rs @@ -70,8 +70,8 @@ fn atomic_sample_round_trips_through_native_fields_and_cooks_identically() { assert!(result.error.is_none(), "{}: {:?}", after.def, result.error); match (original.cooked.image(before.id, 0), loaded.cooked.image(after.id, 0)) { (Some(before), Some(after)) => { - assert_eq!((before.w, before.h, before.kind), (after.w, after.h, after.kind)); - let error = before.data.iter().zip(after.data.iter()).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max); + assert_eq!((before.width(), before.height(), before.kind()), (after.width(), after.height(), after.kind())); + let error = before.data().iter().zip(after.data()).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max); assert!(error < 1e-5, "pixel error {error}"); } (None, None) => assert_eq!(original.cooked.value(before.id, 0), loaded.cooked.value(after.id, 0)), @@ -177,10 +177,10 @@ fn exposed_parameter_binding_remains_live_after_saving() { let mut loaded = Session::new(loaded.pkg); loaded.preview_size = Some(32); loaded.cook(); - let before = loaded.cooked.image(blur, 0).unwrap().data.clone(); + let before = loaded.cooked.image(blur, 0).unwrap().data().to_vec(); 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); + assert_ne!(before.as_slice(), loaded.cooked.image(blur, 0).unwrap().data()); } #[test] diff --git a/crates/engine/tests/it/export_names.rs b/crates/engine/tests/it/export_names.rs index c9c8065..e1c15ce 100644 --- a/crates/engine/tests/it/export_names.rs +++ b/crates/engine/tests/it/export_names.rs @@ -104,7 +104,7 @@ fn unique_export_writes_both_maps_with_their_expected_pixels() { assert_eq!(result["files"].as_array().unwrap().len(), 2); for (name, value) in [("first.png", 0.2), ("second.png", 0.8)] { let image = formats::decode(&std::fs::read(dir.0.join(name)).unwrap(), false).unwrap(); - assert_eq!((image.w, image.h), (16, 16)); + assert_eq!((image.width(), image.height()), (16, 16)); assert!((image.get(0, 0, false)[0] - value).abs() < 0.001, "{name}"); } } diff --git a/crates/engine/tests/it/parameter_functions.rs b/crates/engine/tests/it/parameter_functions.rs index 2aed371..849ec5c 100644 --- a/crates/engine/tests/it/parameter_functions.rs +++ b/crates/engine/tests/it/parameter_functions.rs @@ -25,7 +25,7 @@ fn output_size_function_controls_resolution_and_survives_sbs() { let cooked = session.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (128, 32)); + assert_eq!((image.width(), image.height()), (128, 32)); assert!(cooked.nodes[&owner].error.is_none()); let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); @@ -36,7 +36,7 @@ fn output_size_function_controls_resolution_and_survives_sbs() { let owner = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "uniform").unwrap().id; let cooked = reopened.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (128, 32)); + assert_eq!((image.width(), image.height()), (128, 32)); } #[test] @@ -90,7 +90,7 @@ fn native_dynamic_output_size_is_not_discarded_on_load() { let cooked = session.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (64, 32)); + assert_eq!((image.width(), image.height()), (64, 32)); } #[test] @@ -120,7 +120,7 @@ fn inherited_size_functions_use_nominal_input_size_before_preview_capping() { assert_eq!(cooked.nodes[&owner].error, None); assert_eq!(cooked.nodes[&owner].base.size, [256, 64]); assert_eq!(cooked.nodes[&owner].base_values[&BaseParameter::OutputSize], Value::Int2([1, 0])); - assert_eq!((cooked.image(owner, 0).unwrap().w, cooked.image(owner, 0).unwrap().h), (16, 4)); + assert_eq!((cooked.image(owner, 0).unwrap().width(), cooked.image(owner, 0).unwrap().height()), (16, 4)); command( &mut session, @@ -265,7 +265,7 @@ fn instance_parameter_functions_work_without_stored_literals_and_use_instance_si assert_eq!(result.nodes[&owner].error, None); assert!(result.nodes[&owner].outputs.iter().any(|output| output.as_value() == Some(&Value::Float2([64.0, 32.0])))); assert!((result.image(owner, 0).unwrap().get_gray(0, 0, false) - 0.75).abs() < 1e-6); - assert_eq!((result.image(owner, 0).unwrap().w, result.image(owner, 0).unwrap().h), (64, 32)); + assert_eq!((result.image(owner, 0).unwrap().width(), result.image(owner, 0).unwrap().height()), (64, 32)); assert!(!session.graph().unwrap().node(owner).unwrap().params.contains_key("amount")); let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); @@ -335,7 +335,7 @@ fn base_functions_inherit_from_the_primary_input_and_bypasses_keep_input_dimensi let cooked = session.cook(); let image = cooked.image(blend, 0).unwrap(); - assert_eq!((image.w, image.h), (16, 16)); + assert_eq!((image.width(), image.height()), (16, 16)); assert_eq!(cooked.nodes[&blend].base.size, [32, 32]); assert_eq!(cooked.nodes[&output].base.size, [32, 32]); } diff --git a/crates/engine/tests/it/subgraph_seed.rs b/crates/engine/tests/it/subgraph_seed.rs index 070f5fc..569dec9 100644 --- a/crates/engine/tests/it/subgraph_seed.rs +++ b/crates/engine/tests/it/subgraph_seed.rs @@ -26,20 +26,20 @@ fn grouping_noise_preserves_pixels_seed_and_undo() { // Force an actual cook instead of relying on the pre-grouping cache entry. s.cache.lock().unwrap().clear(); let after = s.cook().image(output, 0).unwrap().clone(); - assert!(before.data == after.data, "grouping changed the material at graph seed {seed}"); - assert_eq!((after.w, after.h), (64, 32)); + assert!(before.data() == after.data(), "grouping changed the material at graph seed {seed}"); + assert_eq!((after.width(), after.height()), (64, 32)); assert_eq!(s.pkg.graphs[1].seed, seed); let grouped_graphs = s.pkg.graphs.clone(); run(&mut s, "edit.undo", json!({})); assert_eq!(s.pkg.graphs, before_graphs); - assert_eq!(s.cook().image(output, 0).unwrap().data, before.data); + assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data()); run(&mut s, "edit.redo", json!({})); assert_eq!(s.pkg.graphs, grouped_graphs); - assert_eq!(s.cook().image(output, 0).unwrap().data, before.data); + assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data()); let bytes = formats::sbs::write_sbs(&s.pkg).unwrap(); let mut reopened = Session::new(formats::sbs::read_sbs(&bytes, "seed.sbs", &|_| None).unwrap().pkg); reopened.preview_size = None; let reopened_output = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id; - assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data, before.data); + assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data(), before.data()); } } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index d46abad..d967e07 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -87,7 +87,7 @@ fn package_save_and_open_round_trip() { run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64})); let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path(); let img = materialcraft_formats::decode(&std::fs::read(file).unwrap(), false).unwrap(); - assert_eq!((img.w, img.h), (64, 64)); + assert_eq!((img.width(), img.height()), (64, 64)); let _ = std::fs::remove_dir_all(&dir); } @@ -101,7 +101,7 @@ fn export_size_keeps_proportions_and_clamps() { let dims = |s: &Session, size: Value| { let request = ExportRequest::from_params(s, &json!({"size": size})).unwrap(); let files = materialcraft_engine::file_cmds::export_outputs(s, &request).unwrap(); - files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.w, i.h)).collect::>() + files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.width(), i.height())).collect::>() }; let parsed = |s: &Session, size: Value| ExportRequest::from_params(s, &json!({"size": size})).map(|request| request.size); @@ -369,17 +369,17 @@ fn camera_prefs_bound_the_pan_and_survive_hostile_values() { #[test] fn reimported_bitmap_shows_new_pixels() { + use craft_texture::{Image, Kind}; use materialcraft_formats::{Depth, encode}; - use materialcraft_image::{Image, Kind}; let bmp = |v: f32| encode(&Image::filled(4, 4, Kind::Color, [v, v, v, 1.0]), "bmp", Depth::U8, true).unwrap(); let (dark, light) = (bmp(0.1), bmp(0.9)); assert_eq!(dark.len(), light.len(), "same-size files are the case under test"); let mut s = sample_session(); materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", dark, Some("tex")).unwrap(); - let before = s.resource_decoder()("tex").unwrap().data[0]; + let before = s.resource_decoder()("tex").unwrap().data()[0]; s.undo(); materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", light, Some("tex")).unwrap(); - let after = s.resource_decoder()("tex").unwrap().data[0]; + let after = s.resource_decoder()("tex").unwrap().data()[0]; assert!(after - before > 0.5, "{before} -> {after}"); } @@ -423,7 +423,7 @@ fn every_template_is_opaque_in_the_3d_view() { s.cook(); for (usage, img) in s.material_maps() { if usage == "baseColor" && !img.is_gray() { - let min = img.data.chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min); + let min = img.data().chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min); assert!(min >= 0.999, "{id}: base color alpha goes down to {min}"); } } diff --git a/crates/eval/Cargo.toml b/crates/eval/Cargo.toml index e30a1ef..54e97be 100644 --- a/crates/eval/Cargo.toml +++ b/crates/eval/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-nodes = { workspace = true } serde_json = { workspace = true } serde = { workspace = true } diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index fb0d8a2..a0d3aed 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -1,25 +1,25 @@ use crate::{Cache, identifier}; +use craft_texture::Image; use materialcraft_core::{Node, Package, Value}; -use materialcraft_image::Image; use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::{Arc, Mutex}; pub(crate) fn image_key(i: &Image, cache: &Mutex) -> u64 { - let ptr = Arc::as_ptr(&i.data) as usize; - let shape = (i.w, i.h, i.kind.channels()); + let ptr = Arc::as_ptr(i.shared_data()) as usize; + let shape = (i.width(), i.height(), i.channels()); if let Some(key) = cache .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .input_hashes .get(&ptr) - .and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, &i.data) && saved.shape == shape).map(|_| saved.key)) + .and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, i.shared_data()) && saved.shape == shape).map(|_| saved.key)) { return key; } let mut h = DefaultHasher::new(); - (shape, i.data.len()).hash(&mut h); - for value in i.data.iter() { + (shape, i.data().len()).hash(&mut h); + for value in i.data() { value.to_bits().hash(&mut h); } let key = h.finish(); @@ -30,7 +30,7 @@ pub(crate) fn image_key(i: &Image, cache: &Mutex) -> u64 { cache.input_hashes.clear(); } } - cache.input_hashes.insert(ptr, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(&i.data), shape, key }); + cache.input_hashes.insert(ptr, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(i.shared_data()), shape, key }); key } diff --git a/crates/eval/src/cooked.rs b/crates/eval/src/cooked.rs index c64675b..3c7e075 100644 --- a/crates/eval/src/cooked.rs +++ b/crates/eval/src/cooked.rs @@ -1,6 +1,6 @@ use crate::NodeResult; +use craft_texture::Image; use materialcraft_core::NodeId; -use materialcraft_image::Image; use std::collections::BTreeMap; /// Results of a cook, by node diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index 9f1b364..c3c18c8 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -1,7 +1,7 @@ use crate::{Cache, Cooked, Options, now_ms}; use crate::{node_execution::cook_node, prepared_graph::PreparedGraph}; +use craft_texture::Image; use materialcraft_core::{Package, Value}; -use materialcraft_image::Image; use std::{ collections::BTreeMap, sync::{Mutex, atomic::Ordering}, @@ -19,7 +19,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu .input_images .iter() .filter_map(|(id, resource)| { - Some((id.clone(), (options.resource)(&materialcraft_image::resource_key(resource, graph.input_images_linear.contains(id)))?)) + Some((id.clone(), (options.resource)(&craft_texture::resource_key(resource, graph.input_images_linear.contains(id)))?)) }) .collect(); inputs.extend(options.inputs.iter().map(|(name, value)| (name.clone(), value.clone()))); diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index db0fd83..d7f75ba 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -64,8 +64,8 @@ pub(crate) fn cook_instance( let root_resource = opts.resource_root.unwrap_or(opts.resource); let resource = |name: &str| match &node.instance { Some(instance) if !instance.package.is_empty() => { - let (name, linear) = materialcraft_image::split_resource_key(name); - root_resource(&materialcraft_image::resource_key(&format!("{}\0{name}", instance.package), linear)) + let (name, linear) = craft_texture::split_resource_key(name); + root_resource(&craft_texture::resource_key(&format!("{}\0{name}", instance.package), linear)) } _ => (opts.resource)(name), }; diff --git a/crates/eval/src/graph_output.rs b/crates/eval/src/graph_output.rs index e96e0ff..46f0862 100644 --- a/crates/eval/src/graph_output.rs +++ b/crates/eval/src/graph_output.rs @@ -9,7 +9,7 @@ pub fn output_usage(node: &Node) -> &'static str { }; ComponentUsage::from_index(index).id } -use materialcraft_image::Image; +use craft_texture::Image; /// The graph's output nodes with their usage id and image, in node order pub fn outputs<'c>(graph: &Graph, cooked: &'c Cooked) -> Vec<(NodeId, &'static str, String, Option<&'c Image>)> { diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index f94f790..59b542c 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -6,8 +6,8 @@ use crate::{ prepared_graph::PreparedGraph, value_execution::evaluate_value, }; +use craft_texture::{Image, Kind}; use materialcraft_core::{Node, Package, Value}; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find}; use std::{ collections::BTreeMap, diff --git a/crates/eval/src/node_output.rs b/crates/eval/src/node_output.rs index d9c6f0e..15d6e66 100644 --- a/crates/eval/src/node_output.rs +++ b/crates/eval/src/node_output.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; #[derive(Clone, Debug, PartialEq)] pub enum NodeOutput { @@ -24,7 +24,7 @@ impl NodeOutput { pub(crate) fn memory_bytes(&self) -> usize { match self { - Self::Image(image) => image.data.len().saturating_mul(size_of::()), + Self::Image(image) => image.data().len().saturating_mul(size_of::()), Self::Value(Value::Text(text)) => size_of::().saturating_add(text.len()), Self::Value(_) => size_of::(), } diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs index 8505d4d..9beb3f0 100644 --- a/crates/eval/src/options.rs +++ b/crates/eval/src/options.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::{NodeId, Value}; -use materialcraft_image::Image; use std::collections::BTreeMap; use std::sync::atomic::AtomicBool; diff --git a/crates/eval/src/resource_decoder.rs b/crates/eval/src/resource_decoder.rs index 7ddbefa..0ec3781 100644 --- a/crates/eval/src/resource_decoder.rs +++ b/crates/eval/src/resource_decoder.rs @@ -1,4 +1,4 @@ -use materialcraft_image::Image; +use craft_texture::Image; /// Decodes an image resource by name within the current package pub type ResourceDecoder<'a> = dyn Fn(&str) -> Option + Sync + 'a; diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index aff7994..46c55a2 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -1,6 +1,6 @@ use crate::{cache_key::graph_tree_hash, graph_instance::instances_reach}; +use craft_texture::{Image, Kind, Limits}; use materialcraft_core::{NodeId, Package, Value}; -use materialcraft_image::{Image, Kind}; use std::sync::Mutex; use std::sync::atomic::Ordering; @@ -31,7 +31,7 @@ fn cooks_and_caches() { let opts = Options::new(&no_res); let a = cook(&p, 0, &opts, &cache); assert!(a.nodes.values().all(|r| r.error.is_none() && !r.cached)); - assert_eq!(a.image(out, 0).map(|i| (i.w, i.h)), Some((64, 64))); + assert_eq!(a.image(out, 0).map(|i| (i.width(), i.height())), Some((64, 64))); // Same graph: everything from the cache let b = cook(&p, 0, &opts, &cache); assert!(b.nodes.values().all(|r| r.cached)); @@ -76,7 +76,7 @@ fn hostile_param_is_clamped_before_cooking() { let cache = Mutex::new(Cache::default()); let c = cook(&p, 0, &Options::new(&no_res), &cache); assert!(c.nodes[&blur].error.is_none(), "{:?}", c.nodes[&blur].error); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((64, 64))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((64, 64))); } #[test] @@ -88,7 +88,7 @@ fn preview_cap_and_unknown_nodes() { let mut opts = Options::new(&no_res); opts.max_size = Some(128); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(out, 0).map(|i| i.w), Some(128)); + assert_eq!(c.image(out, 0).map(|i| i.width()), Some(128)); assert!(c.nodes[&bad].error.is_some()); } @@ -119,7 +119,7 @@ fn graph_instances_cook_their_subgraph() { let cache = Mutex::new(Cache::default()); let c = cook(&p, 0, &Options::new(&no_res), &cache); let img = c.image(inst, 0).unwrap(); - assert!((img.data[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data[0]); + assert!((img.data()[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data()[0]); assert!(c.nodes[&selfi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&selfi].error); } @@ -240,12 +240,12 @@ fn input_nodes_read_bound_preview_images() { let cache = Mutex::new(Cache::default()); let c = cook(&p, 0, &Options::new(&res), &cache); let img = c.image(o, 0).unwrap(); - assert!(img.is_gray() && (img.data[0] - 0.8).abs() < 1e-4, "bound image, as gray"); + assert!(img.is_gray() && (img.data()[0] - 0.8).abs() < 1e-4, "bound image, as gray"); // The caller's image wins over the bound one let mut opts = Options::new(&res); opts.inputs.insert("curvature".into(), Image::filled(4, 4, Kind::Gray, [0.1; 4])); let c = cook(&p, 0, &opts, &cache); - assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4); + assert!((c.image(o, 0).unwrap().data()[0] - 0.1).abs() < 1e-4); } #[test] @@ -317,14 +317,16 @@ use std::sync::Arc; #[test] fn cached_input_fingerprint_tracks_copy_on_write_and_shape() { let cache = Mutex::new(Cache::default()); - let mut image = Image::filled(128, 128, Kind::Gray, [0.0; 4]); + let image = Image::filled(128, 128, Kind::Gray, [0.0; 4]); let first = image_key(&image, &cache); assert_eq!(image_key(&image, &cache), first); - Arc::make_mut(&mut image.data)[1] = 1.0; + let mut data = image.data().to_vec(); + data[1] = 1.0; + let image = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap(); let changed = image_key(&image, &cache); assert_ne!(changed, first); - image.w = 64; - image.h = 256; + // The same buffer read as another shape. + let image = Image::from_data(64, 256, Kind::Gray, Arc::clone(image.shared_data()), &Limits::default()).unwrap(); let reshaped = image_key(&image, &cache); assert_ne!(reshaped, changed); @@ -340,9 +342,9 @@ fn preview_cap_does_not_compound_downscaling() { let mut opts = Options::new(&no_res); opts.max_size = Some(512); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(noise, 0).map(|i| (i.w, i.h)), Some((512, 512))); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((128, 128))); - assert_eq!(c.image(out, 0).map(|i| (i.w, i.h)), Some((128, 128))); + assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((512, 512))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 128))); + assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 128))); } #[test] fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { @@ -354,9 +356,9 @@ fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { let mut opts = Options::new(&no_res); opts.max_size = Some(128); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(noise, 0).map(|i| (i.w, i.h)), Some((128, 64))); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((128, 64))); - assert_eq!(c.image(out, 0).map(|i| (i.w, i.h)), Some((128, 64))); + assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((128, 64))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 64))); + assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 64))); } #[test] fn changed_unsampled_input_recooks() { @@ -371,18 +373,19 @@ fn changed_unsampled_input_recooks() { let cache = Mutex::new(Cache::default()); let first = cook(&p, 0, &opts, &cache); assert!(!first.nodes[&input].cached); - let mut changed = image; - Arc::make_mut(&mut changed.data)[1] = 1.0; + let mut data = image.data().to_vec(); + data[1] = 1.0; + let changed = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap(); opts.inputs.insert("input".into(), changed); let second = cook(&p, 0, &opts, &cache); assert!(!second.nodes[&input].cached); - assert_eq!(second.image(input, 0).unwrap().data[1], 1.0); + assert_eq!(second.image(input, 0).unwrap().data()[1], 1.0); } #[test] fn linear_input_images_and_bitmap_nodes_request_data_reads() { // The decoder returns 0.5 for a linear request and 0.2 for an sRGB one. let res = |k: &str| { - let (name, linear) = materialcraft_image::split_resource_key(k); + let (name, linear) = craft_texture::split_resource_key(k); (name == "m").then(|| Image::filled(4, 4, Kind::Color, [if linear { 0.5 } else { 0.2 }; 4])) }; let mut p = Package::new("p"); @@ -397,7 +400,7 @@ fn linear_input_images_and_bitmap_nodes_request_data_reads() { let first = |p: &Package| { let cache = Mutex::new(Cache::default()); let c = cook(p, 0, &Options::new(&res), &cache); - (c.image(i, 0).unwrap().data[0], c.image(b, 0).unwrap().data[0]) + (c.image(i, 0).unwrap().data()[0], c.image(b, 0).unwrap().data()[0]) }; assert_eq!(first(&p), (0.2, 0.2), "default is sRGB, as before"); p.graphs[0].input_images_linear.insert("n".into()); @@ -451,7 +454,7 @@ fn bound_input_image_linear_flag_change_recooks_instance() { p.graphs = vec![top, sub]; p.resources.push(Resource::new("curv", "curv.bin", ResourceBytes::new(vec![1; 100]))); let res = |k: &str| { - let (name, linear) = materialcraft_image::split_resource_key(k); + let (name, linear) = craft_texture::split_resource_key(k); (name == "curv").then(|| Image::filled(4, 4, Kind::Gray, [if linear { 0.5 } else { 0.2 }; 4])) }; let cache = Mutex::new(Cache::default()); @@ -459,14 +462,14 @@ fn bound_input_image_linear_flag_change_recooks_instance() { let first = cook(&p, 0, &opts, &cache); assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error); assert!(!first.nodes[&inst].cached); - let first_value = first.image(inst, 0).unwrap().data[0]; + let first_value = first.image(inst, 0).unwrap().data()[0]; assert!((first_value - 0.2).abs() < 1e-4, "sRGB bound image should reach the instance, got {first_value}"); let second = cook(&p, 0, &opts, &cache); assert!(second.nodes[&inst].cached, "an unchanged instance should be served from the cache"); p.graphs[1].input_images_linear.insert("in".into()); let third = cook(&p, 0, &opts, &cache); assert!(!third.nodes[&inst].cached, "toggling input_images_linear must recook the instance"); - let third_value = third.image(inst, 0).unwrap().data[0]; + let third_value = third.image(inst, 0).unwrap().data()[0]; assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}"); } @@ -549,7 +552,7 @@ fn enabled_generators_use_parent_size_and_inherit_other_input_base_parameters() assert_eq!(result.error, None, "{definition}"); assert_eq!(result.base.size, [64, 32], "{definition}, dynamic: {dynamic}"); - assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((16, 8))); + assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some((16, 8))); assert_eq!(result.base.seed, 17); assert_eq!(result.base.format, OutputFormat::F32); assert_eq!(result.base.tiling, [false, true]); @@ -567,7 +570,7 @@ fn enabled_generators_use_parent_size_and_inherit_other_input_base_parameters() assert_eq!(cooked.nodes[&generator].error, None); assert_eq!(cooked.nodes[&generator].base.size, cooked.nodes[&background].base.size); - assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((8, 16))); + assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some((8, 16))); } } } diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs index 6ed651c..9813f85 100644 --- a/crates/eval/src/value_execution.rs +++ b/crates/eval/src/value_execution.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; use std::collections::BTreeMap; pub(crate) fn evaluate_value( diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 37f3339..d9364ce 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-geom = { workspace = true } materialcraft-nodes = { workspace = true } gltf = { workspace = true } diff --git a/crates/formats/src/dds_image.rs b/crates/formats/src/dds_image.rs index cba769b..c2bbd6d 100644 --- a/crates/formats/src/dds_image.rs +++ b/crates/formats/src/dds_image.rs @@ -1,5 +1,5 @@ use crate::{FormatError, Result}; -use materialcraft_image::{Image, Kind, MAX_SIDE, srgb_to_linear}; +use craft_texture::{Image, Kind, Limits, MAX_SIDE, srgb_to_linear}; pub(crate) fn decode(bytes: &[u8], linear: bool) -> Result { let error = |message: String| FormatError::Image(message); @@ -20,5 +20,5 @@ pub(crate) fn decode(bytes: &[u8], linear: bool) -> Result { } } } - Ok(Image { w: size.width, h: size.height, kind: Kind::Color, data: std::sync::Arc::new(data) }) + Image::from_data(size.width, size.height, Kind::Color, data, &Limits::default()).map_err(|e| error(e.to_string())) } diff --git a/crates/formats/src/image.rs b/crates/formats/src/image.rs index f3fabdd..872316f 100644 --- a/crates/formats/src/image.rs +++ b/crates/formats/src/image.rs @@ -1,7 +1,6 @@ use crate::{Depth, FormatError, Result, guard}; -use materialcraft_image::{Image, Kind, MAX_SIDE, linear_to_srgb, srgb_to_linear}; +use craft_texture::{Image, Kind, Limits, MAX_SIDE, linear_to_srgb, srgb_to_linear}; use std::io::Cursor; -use std::sync::Arc; /// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale files stay grayscale) pub fn decode(bytes: &[u8], linear: bool) -> Result { @@ -41,7 +40,7 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { if gray { let l = img.into_luma16(); let data: Vec = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); - return Ok(Image { w, h, kind: Kind::Gray, data: Arc::new(data) }); + return Image::from_data(w, h, Kind::Gray, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string())); } let mut data = img.into_rgba32f().into_raw(); @@ -52,21 +51,21 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { } } } - Ok(Image { w, h, kind: Kind::Color, data: Arc::new(data) }) + Image::from_data(w, h, Kind::Color, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string())) } /// Encode `img` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result> { let ext = ext.trim_start_matches('.').to_ascii_lowercase(); - let enc = |v: f32| if srgb && img.kind == Kind::Color { linear_to_srgb(v) } else { v }; - let (w, h) = (img.w, img.h); - let color = img.kind == Kind::Color; + let enc = |v: f32| if srgb && img.kind() == Kind::Color { linear_to_srgb(v) } else { v }; + let (w, h) = (img.width(), img.height()); + let color = img.kind() == Kind::Color; let px = |i: usize| -> [f32; 4] { if color { - let s = img.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + let s = img.data().get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); [enc(s[0]), enc(s[1]), enc(s[2]), s[3]] } else { - let v = img.data.get(i).copied().unwrap_or(0.0); + let v = img.data().get(i).copied().unwrap_or(0.0); [v, v, v, 1.0] } }; diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index ff9745b..98ee19e 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -59,7 +59,7 @@ fn sample_package() -> Package { }); pkg.graphs.push(graph); - let orange = materialcraft_image::Image::filled(4, 4, materialcraft_image::Kind::Color, [1.0, 0.5, 0.0, 1.0]); + let orange = craft_texture::Image::filled(4, 4, craft_texture::Kind::Color, [1.0, 0.5, 0.0, 1.0]); let png = crate::encode(&orange, "png", crate::Depth::U8, true).unwrap(); pkg.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(png))); pkg diff --git a/crates/formats/src/svg.rs b/crates/formats/src/svg.rs index 284272b..dc4d21a 100644 --- a/crates/formats/src/svg.rs +++ b/crates/formats/src/svg.rs @@ -1,5 +1,5 @@ use crate::{FormatError, Result}; -use materialcraft_image::{Image, Kind, MAX_SIDE, srgb_to_linear}; +use craft_texture::{Image, Kind, MAX_SIDE, srgb_to_linear}; use resvg::{tiny_skia, usvg}; pub(crate) fn decode(bytes: &[u8]) -> Result { diff --git a/crates/formats/src/tests.rs b/crates/formats/src/tests.rs index e8fe792..972ddc0 100644 --- a/crates/formats/src/tests.rs +++ b/crates/formats/src/tests.rs @@ -1,5 +1,5 @@ use super::*; -use materialcraft_image::{Image, Kind, srgb_to_linear}; +use craft_texture::{Image, Kind, srgb_to_linear}; use std::io::Cursor; #[test] @@ -11,7 +11,7 @@ fn export_every_format() { for i in [&img, &gray] { let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}")); let back = decode(&b, false).unwrap_or_else(|e| panic!("{ext} decode: {e}")); - assert_eq!((back.w, back.h), (8, 8)); + assert_eq!((back.width(), back.height()), (8, 8)); } } } @@ -39,7 +39,7 @@ fn tga_still_decodes() { let mut tga = Cursor::new(Vec::new()); ::image::RgbaImage::new(2, 2).write_to(&mut tga, ::image::ImageFormat::Tga).unwrap(); let img = decode(tga.get_ref(), false).unwrap(); - assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color)); + assert_eq!((img.width(), img.height(), img.kind()), (2, 2, Kind::Color)); } #[test] diff --git a/crates/formats/tests/bitmap_imports.rs b/crates/formats/tests/bitmap_imports.rs index 5ec5438..1d8e11f 100644 --- a/crates/formats/tests/bitmap_imports.rs +++ b/crates/formats/tests/bitmap_imports.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_formats::{BITMAP_EXTENSIONS, BITMAP_FORMATS, Depth, decode, encode}; -use materialcraft_image::{Image, Kind}; use std::io::Cursor; #[test] @@ -23,7 +23,7 @@ fn common_bitmap_formats_decode() { let bytes = encode(&pixels, extension, Depth::U8, true).unwrap(); let image = decode(&bytes, false).unwrap(); - assert_eq!((image.w, image.h), (4, 4), "{extension}"); + assert_eq!((image.width(), image.height()), (4, 4), "{extension}"); } // GIF and TIFF import only, so another writer makes them @@ -31,15 +31,15 @@ fn common_bitmap_formats_decode() { let mut bytes = Cursor::new(Vec::new()); image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut bytes, format).unwrap(); - assert_eq!(decode(bytes.get_ref(), false).unwrap().w, 2, "{format:?}"); + assert_eq!(decode(bytes.get_ref(), false).unwrap().width(), 2, "{format:?}"); } assert!(encode(&pixels, "tif", Depth::U8, true).is_err(), "TIFF is not an export format"); for pgm in [&b"P2\n2 1\n255\n0 255\n"[..], &b"P5\n2 1\n255\n\0\xff"[..]] { let image = decode(pgm, false).unwrap(); - assert_eq!(image.kind, Kind::Gray); - assert_eq!(image.data.as_slice(), &[0.0, 1.0]); + assert_eq!(image.kind(), Kind::Gray); + assert_eq!(image.data(), &[0.0, 1.0]); } } @@ -61,12 +61,12 @@ fn dds_supports_compressed_uncompressed_and_float_textures() { encoder.finish().unwrap(); let image = decode(&bytes, true).unwrap(); - assert_eq!((image.w, image.h), (4, 4)); - assert!(image.data.iter().all(|value| value.is_finite())); - assert!((image.data[0] - 64.0 / 255.0).abs() < 0.05, "{format:?}"); + assert_eq!((image.width(), image.height()), (4, 4)); + assert!(image.data().iter().all(|value| value.is_finite())); + assert!((image.data()[0] - 64.0 / 255.0).abs() < 0.05, "{format:?}"); if format == dds::Format::R32G32B32A32_FLOAT { - assert_eq!(decode(&bytes, false).unwrap().data, image.data, "float DDS stays linear"); + assert_eq!(decode(&bytes, false).unwrap().data(), image.data(), "float DDS stays linear"); } assert!(decode(&bytes[..bytes.len() / 2], true).is_err()); diff --git a/crates/formats/tests/project_packages.rs b/crates/formats/tests/project_packages.rs index feb3345..4c8a33f 100644 --- a/crates/formats/tests/project_packages.rs +++ b/crates/formats/tests/project_packages.rs @@ -9,7 +9,7 @@ const SVG: &[u8] = br#" Package { let mut package = Package::new("Surface"); - let pixels = materialcraft_image::Image::filled(2, 2, materialcraft_image::Kind::Color, [0.2, 0.4, 0.8, 1.0]); + let pixels = craft_texture::Image::filled(2, 2, craft_texture::Kind::Color, [0.2, 0.4, 0.8, 1.0]); let png = encode(&pixels, "png", Depth::U8, true).unwrap(); package.resources.push(Resource::new("Texture", "texture.png", ResourceBytes::new(png))); package.resources.push(Resource::new("Shape", "shape.svg", ResourceBytes::new(SVG.to_vec()))); diff --git a/crates/image/Cargo.toml b/crates/image/Cargo.toml deleted file mode 100644 index c8f371a..0000000 --- a/crates/image/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "materialcraft-image" -description = "MaterialCraft image buffers: grayscale and color float planes, sampling, resampling, conversions" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lints] -workspace = true - -[dependencies] -rayon = { workspace = true } -thiserror = { workspace = true } diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rs deleted file mode 100644 index 396f1e5..0000000 --- a/crates/image/src/lib.rs +++ /dev/null @@ -1,384 +0,0 @@ -//! # materialcraft-image -//! -//! Image buffers for node cooking, L0: an [`Image`] is a grayscale (1 channel) or color (RGBA) -//! plane of `f32`, shared copy-on-write through an `Arc` so cached node outputs cost nothing to -//! hand around. Values are linear and usually 0..1 (HDR formats may exceed it). Sampling wraps or -//! clamps per axis ("tiling"); everything per pixel runs in parallel rows (rayon). -#![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -use std::sync::Arc; - -use rayon::prelude::*; - -/// Largest side an image may have (an allocation cap for hostile sizes). -pub const MAX_SIDE: u32 = 8192; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Kind { - Gray, - Color, -} - -impl Kind { - pub fn channels(self) -> usize { - match self { - Kind::Gray => 1, - Kind::Color => 4, - } - } -} - -#[derive(Debug, thiserror::Error)] -pub enum ImageError { - #[error("image size {0}x{1} is outside 1..={MAX_SIDE}")] - BadSize(u32, u32), -} - -#[derive(Clone, Debug)] -pub struct Image { - pub w: u32, - pub h: u32, - pub kind: Kind, - /// Row-major, `kind.channels()` floats per pixel. - pub data: Arc>, -} - -impl PartialEq for Image { - fn eq(&self, o: &Image) -> bool { - self.w == o.w && self.h == o.h && self.kind == o.kind && (Arc::ptr_eq(&self.data, &o.data) || self.data == o.data) - } -} - -/// Clamp a requested size into the allowed range. -pub fn clamp_size(w: u32, h: u32) -> (u32, u32) { - (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE)) -} - -#[inline] -fn wrap(i: i64, n: u32, tile: bool) -> usize { - let n = n as i64; - if tile { i.rem_euclid(n) as usize } else { i.clamp(0, n - 1) as usize } -} - -impl Image { - /// A constant image. - pub fn filled(w: u32, h: u32, kind: Kind, v: [f32; 4]) -> Image { - let (w, h) = clamp_size(w, h); - let n = (w * h) as usize; - let data = match kind { - Kind::Gray => vec![v[0]; n], - Kind::Color => v.iter().copied().cycle().take(n * 4).collect(), - }; - Image { w, h, kind, data: Arc::new(data) } - } - - /// Generate every pixel with `f(x, y)` (pixel indices) in parallel rows. - pub fn generate(w: u32, h: u32, kind: Kind, f: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { - let (w, h) = clamp_size(w, h); - let c = kind.channels(); - let mut data = vec![0.0f32; (w * h) as usize * c]; - data.par_chunks_mut(w as usize * c).enumerate().for_each(|(y, row)| { - for x in 0..w as usize { - let p = f(x as u32, y as u32); - row[x * c..x * c + c].copy_from_slice(&p[..c]); - } - }); - Image { w, h, kind, data: Arc::new(data) } - } - - /// Generate from normalized coordinates (pixel centers, 0..1). - pub fn generate_uv(w: u32, h: u32, kind: Kind, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { - let (iw, ih) = (1.0 / w.max(1) as f32, 1.0 / h.max(1) as f32); - Image::generate(w, h, kind, |x, y| f((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih)) - } - - pub fn gray(w: u32, h: u32, f: impl Fn(u32, u32) -> f32 + Sync) -> Image { - Image::generate(w, h, Kind::Gray, |x, y| [f(x, y), 0.0, 0.0, 0.0]) - } - - pub fn channels(&self) -> usize { - self.kind.channels() - } - - pub fn is_gray(&self) -> bool { - self.kind == Kind::Gray - } - - /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). - #[inline] - pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { - let (x, y) = (wrap(x, self.w, tile), wrap(y, self.h, tile)); - let i = y * self.w as usize + x; - match self.kind { - Kind::Gray => { - let v = self.data.get(i).copied().unwrap_or(0.0); - [v, v, v, 1.0] - } - Kind::Color => { - let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); - [s[0], s[1], s[2], s[3]] - } - } - } - - /// The gray value, or the Rec. 709 luminance of a color image. - #[inline] - pub fn get_gray(&self, x: i64, y: i64, tile: bool) -> f32 { - let p = self.get(x, y, tile); - match self.kind { - Kind::Gray => p[0], - Kind::Color => luminance(p), - } - } - - /// Bilinear sample at normalized `(u, v)`; pixel centers sit at `(i + 0.5) / w`. - #[inline] - pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let fx = u * self.w as f32 - 0.5; - let fy = v * self.h as f32 - 0.5; - if !fx.is_finite() || !fy.is_finite() { - return [0.0, 0.0, 0.0, 1.0]; - } - // Huge but finite coordinates would saturate the i64 cast and overflow at `+ 1`. - let (fx, fy) = (fx.clamp(-1.0e9, 1.0e9), fy.clamp(-1.0e9, 1.0e9)); - let (x0, y0) = (fx.floor(), fy.floor()); - let (tx, ty) = (fx - x0, fy - y0); - let (x0, y0) = (x0 as i64, y0 as i64); - let a = self.get(x0, y0, tile); - let b = self.get(x0 + 1, y0, tile); - let c = self.get(x0, y0 + 1, tile); - let d = self.get(x0 + 1, y0 + 1, tile); - let mut o = [0.0; 4]; - for k in 0..4 { - let top = a[k] + (b[k] - a[k]) * tx; - let bot = c[k] + (d[k] - c[k]) * tx; - o[k] = top + (bot - top) * ty; - } - o - } - - #[inline] - pub fn sample_gray(&self, u: f32, v: f32, tile: bool) -> f32 { - let p = self.sample(u, v, tile); - match self.kind { - Kind::Gray => p[0], - Kind::Color => luminance(p), - } - } - - /// Nearest sample at normalized `(u, v)`. - #[inline] - pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let x = (u * self.w as f32).floor(); - let y = (v * self.h as f32).floor(); - if !x.is_finite() || !y.is_finite() { - return [0.0, 0.0, 0.0, 1.0]; - } - self.get(x as i64, y as i64, tile) - } - - /// Map every pixel (as RGBA) to a new image of `kind`, same size. - pub fn map(&self, kind: Kind, f: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Image { - Image::generate(self.w, self.h, kind, |x, y| f(self.get(x as i64, y as i64, false))) - } - - /// This image as grayscale (luminance of a color image). - pub fn to_gray(&self) -> Image { - match self.kind { - Kind::Gray => self.clone(), - Kind::Color => self.map(Kind::Gray, |p| [luminance(p), 0.0, 0.0, 0.0]), - } - } - - /// This image as RGBA (gray copied to RGB, alpha 1). - pub fn to_color(&self) -> Image { - match self.kind { - Kind::Color => self.clone(), - Kind::Gray => self.map(Kind::Color, |p| p), - } - } - - pub fn to_kind(&self, kind: Kind) -> Image { - match kind { - Kind::Gray => self.to_gray(), - Kind::Color => self.to_color(), - } - } - - /// Resample to `w × h` (bilinear when enlarging, box-filtered when shrinking). - pub fn resize(&self, w: u32, h: u32, tile: bool) -> Image { - let (w, h) = clamp_size(w, h); - if w == self.w && h == self.h { - return self.clone(); - } - if w <= self.w && h <= self.h && self.w.is_multiple_of(w) && self.h.is_multiple_of(h) { - let (fx, fy) = ((self.w / w) as i64, (self.h / h) as i64); - let inv = 1.0 / (fx * fy) as f32; - return Image::generate(w, h, self.kind, |x, y| { - let mut s = [0.0; 4]; - for j in 0..fy { - for i in 0..fx { - let p = self.get(x as i64 * fx + i, y as i64 * fy + j, tile); - for k in 0..4 { - s[k] += p[k]; - } - } - } - s.map(|v| v * inv) - }); - } - Image::generate_uv(w, h, self.kind, |u, v| self.sample(u, v, tile)) - } - - /// Raw float access for gray images (`None` for color). - pub fn gray_data(&self) -> Option<&[f32]> { - (self.kind == Kind::Gray).then_some(self.data.as_slice()) - } - - /// 8-bit sRGB-encoded RGBA for display (gray shown as is; color through the sRGB curve). - pub fn to_rgba8_display(&self) -> Vec { - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let n = (self.w * self.h) as usize; - let mut out = vec![0u8; n * 4]; - out.par_chunks_mut(4).enumerate().for_each(|(i, px)| match self.kind { - Kind::Gray => { - let v = q(self.data.get(i).copied().unwrap_or(0.0)); - px.copy_from_slice(&[v, v, v, 255]); - } - Kind::Color => { - let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); - px.copy_from_slice(&[q(linear_to_srgb(s[0])), q(linear_to_srgb(s[1])), q(linear_to_srgb(s[2])), q(s[3])]); - } - }); - out - } - - /// Mean of each channel (as RGBA), e.g. for tests and auto levels. - pub fn mean(&self) -> [f32; 4] { - let c = self.channels(); - let n = (self.w * self.h) as f64; - let mut s = [0f64; 4]; - for px in self.data.chunks(c) { - for (k, v) in px.iter().enumerate() { - s[k] += *v as f64; - } - } - if c == 1 { - let m = (s[0] / n) as f32; - return [m, m, m, 1.0]; - } - s.map(|v| (v / n) as f32) - } - - /// Minimum and maximum over all channels (alpha excluded). - pub fn range(&self) -> (f32, f32) { - let c = self.channels(); - let mut lo = f32::INFINITY; - let mut hi = f32::NEG_INFINITY; - for px in self.data.chunks(c) { - for v in px.iter().take(c.min(3)) { - lo = lo.min(*v); - hi = hi.max(*v); - } - } - if lo > hi { (0.0, 0.0) } else { (lo, hi) } - } -} - -/// Rec. 709 luminance of a linear RGB(A) pixel. -#[inline] -pub fn luminance(p: [f32; 4]) -> f32 { - 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2] -} - -#[inline] -pub fn linear_to_srgb(v: f32) -> f32 { - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 } -} - -#[inline] -pub fn srgb_to_linear(v: f32) -> f32 { - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } -} - -/// Encode the bitmap name and its requested color space without ambiguity. -/// Plain sRGB names remain readable by simple resource callbacks. -pub fn resource_key(name: &str, linear: bool) -> String { - if linear { - format!("\u{1}L{name}") - } else if name.starts_with('\u{1}') { - format!("\u{1}S{name}") - } else { - name.to_string() - } -} - -/// Split a key made by [`resource_key`] into its name and data-map flag. -pub fn split_resource_key(key: &str) -> (&str, bool) { - if let Some(name) = key.strip_prefix("\u{1}L") { - (name, true) - } else if let Some(name) = key.strip_prefix("\u{1}S") { - (name, false) - } else { - (key, false) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sample_survives_huge_coordinates() { - let img = Image::gray(8, 8, |x, _| x as f32); - for u in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN] { - for tile in [true, false] { - let p = img.sample(u, u, tile); - assert!(p.iter().all(|c| c.is_finite())); - } - } - } - - #[test] - fn resource_keys_round_trip() { - for name in ["n", "", "\u{1}Lnormal", "\u{1}Sn", "n\u{1}linear"] { - for linear in [false, true] { - assert_eq!(split_resource_key(&resource_key(name, linear)), (name, linear)); - } - } - } - - #[test] - fn sample_wraps_and_clamps() { - let img = Image::gray(4, 1, |x, _| x as f32); - assert_eq!(img.get(-1, 0, true)[0], 3.0); - assert_eq!(img.get(-1, 0, false)[0], 0.0); - // Halfway between the last and the (wrapped) first pixel. - assert!((img.sample(1.0, 0.5, true)[0] - 1.5).abs() < 1e-5); - } - - #[test] - fn resize_box_and_bilinear() { - let img = Image::gray(4, 4, |x, _| if x < 2 { 0.0 } else { 1.0 }); - let small = img.resize(2, 2, true); - assert_eq!(small.data.as_slice(), &[0.0, 1.0, 0.0, 1.0]); - let big = small.resize(8, 8, false); - assert_eq!(big.w, 8); - assert!(big.data[0] < big.data[7]); - } - - #[test] - fn hostile_sizes_are_clamped() { - let img = Image::filled(0, u32::MAX, Kind::Gray, [0.5; 4]); - assert_eq!((img.w, img.h), (1, MAX_SIDE)); - assert_eq!(img.sample(f32::NAN, 0.0, true), [0.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn conversions() { - let c = Image::filled(2, 2, Kind::Color, [1.0, 1.0, 1.0, 1.0]); - assert!((c.to_gray().data[0] - 1.0).abs() < 1e-5); - assert_eq!(c.to_rgba8_display()[0], 255); - } -} diff --git a/crates/nodes/Cargo.toml b/crates/nodes/Cargo.toml index 437bb96..daf743e 100644 --- a/crates/nodes/Cargo.toml +++ b/crates/nodes/Cargo.toml @@ -10,5 +10,5 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } rayon = { workspace = true } diff --git a/crates/nodes/src/atomic/bitmap.rs b/crates/nodes/src/atomic/bitmap.rs index 1a98ada..ab07409 100644 --- a/crates/nodes/src/atomic/bitmap.rs +++ b/crates/nodes/src/atomic/bitmap.rs @@ -15,7 +15,7 @@ pub(super) fn definition() -> NodeDefinition { fn bitmap(context: &CookContext) -> CookResult { let name = context.text("resource"); - let image = match (context.resource)(&materialcraft_image::resource_key(name, context.i("colour_space") == 1)) { + let image = match (context.resource)(&craft_texture::resource_key(name, context.i("colour_space") == 1)) { Some(image) => image.resize(context.w, context.h, context.tile), None if name.is_empty() => context.gen_color(|u, v| { let c = if ((u * 8.0) as i32 + (v * 8.0) as i32) % 2 == 0 { 0.8 } else { 0.2 }; diff --git a/crates/nodes/src/atomic/blend.rs b/crates/nodes/src/atomic/blend.rs index 3c890e4..a6f4684 100644 --- a/crates/nodes/src/atomic/blend.rs +++ b/crates/nodes/src/atomic/blend.rs @@ -2,7 +2,7 @@ use super::ATOMIC; use crate::ops; use crate::ops::BLEND_MODES; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("blend", "Blend", ATOMIC) diff --git a/crates/nodes/src/atomic/blur.rs b/crates/nodes/src/atomic/blur.rs index 089e58f..90604c9 100644 --- a/crates/nodes/src/atomic/blur.rs +++ b/crates/nodes/src/atomic/blur.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::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) diff --git a/crates/nodes/src/atomic/channels_shuffle.rs b/crates/nodes/src/atomic/channels_shuffle.rs index 1014f54..546fc9b 100644 --- a/crates/nodes/src/atomic/channels_shuffle.rs +++ b/crates/nodes/src/atomic/channels_shuffle.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("channels_shuffle", "Channels shuffle", ATOMIC) diff --git a/crates/nodes/src/atomic/curve.rs b/crates/nodes/src/atomic/curve.rs index da61d43..6060202 100644 --- a/crates/nodes/src/atomic/curve.rs +++ b/crates/nodes/src/atomic/curve.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("curve", "Curve", ATOMIC).desc("Remaps values through a tone curve.").atomic().any_in("input", "Input").curve("curve", "Curve").any_out().cook(curve) @@ -18,5 +18,5 @@ fn curve(context: &CookContext) -> CookResult { let b = lut.get(i + 1).copied().unwrap_or(a); a + (b - a) * (t - i as f32) }; - Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) + Ok(vec![img.map(img.kind(), |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) } diff --git a/crates/nodes/src/atomic/directional_blur.rs b/crates/nodes/src/atomic/directional_blur.rs index 905c0d0..32c576f 100644 --- a/crates/nodes/src/atomic/directional_blur.rs +++ b/crates/nodes/src/atomic/directional_blur.rs @@ -1,6 +1,6 @@ use super::{ATOMIC, direction}; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("directional_blur", "Directional blur", ATOMIC) @@ -26,7 +26,7 @@ pub(super) fn blur(context: &CookContext, angle: f32) -> CookResult { 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| { + 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; diff --git a/crates/nodes/src/atomic/directional_warp.rs b/crates/nodes/src/atomic/directional_warp.rs index 9489b61..e7a4722 100644 --- a/crates/nodes/src/atomic/directional_warp.rs +++ b/crates/nodes/src/atomic/directional_warp.rs @@ -1,6 +1,6 @@ use super::{ATOMIC, direction}; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("directional_warp", "Directional warp", ATOMIC) @@ -19,7 +19,7 @@ fn directional_warp(context: &CookContext) -> CookResult { let map = context.gray_or(1, 0.0); let (dx, dy) = direction(context.f("angle")); let k = context.f("intensity") / 256.0; - Ok(vec![Image::generate_uv(context.w, context.h, img.kind, |u, v| { + Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| { let m = map.sample_gray(u, v, context.tile) * k; img.sample(u + dx * m, v + dy * m, context.tile) })]) diff --git a/crates/nodes/src/atomic/distance.rs b/crates/nodes/src/atomic/distance.rs index fda95f5..8d5dae6 100644 --- a/crates/nodes/src/atomic/distance.rs +++ b/crates/nodes/src/atomic/distance.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Image; +use craft_texture::Image; pub(super) fn definition() -> NodeDefinition { node("distance", "Distance", ATOMIC) @@ -18,16 +18,16 @@ pub(super) fn definition() -> NodeDefinition { fn distance(context: &CookContext) -> CookResult { let mask = context.gray_or(0, 0.0); let maxd = (context.f("distance").max(0.0) * context.w as f32 / 256.0).max(1e-3); - let data = mask.data.clone(); + let data = mask.shared_data().clone(); let inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5; let Some(src) = context.sized(1) else { let d2 = ops::distance_sq(context.w, context.h, inside, context.tile); - return Ok(vec![ops::gray_from(context.w, context.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]); + return Ok(vec![ops::gray_from(context.w, context.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())?]); }; // Propagate the exact nearest site without gaps from gradient-walk stalls let (d2, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile); let combine = context.b("combine"); - Ok(vec![Image::generate(context.w, context.h, src.kind, |x, y| { + Ok(vec![Image::generate(context.w, context.h, src.kind(), |x, y| { let i = y as usize * context.w as usize + x as usize; let site = sites.get(i).copied().unwrap_or(usize::MAX); let mut c = if site == usize::MAX { diff --git a/crates/nodes/src/atomic/dot.rs b/crates/nodes/src/atomic/dot.rs index 73f4293..8938d28 100644 --- a/crates/nodes/src/atomic/dot.rs +++ b/crates/nodes/src/atomic/dot.rs @@ -1,6 +1,6 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("dot", "Dot", GRAPH_ITEMS).desc("A reroute point for wires.").atomic().any_in("input", "Input").any_out().cook(passthrough) diff --git a/crates/nodes/src/atomic/emboss.rs b/crates/nodes/src/atomic/emboss.rs index 66492a2..1169151 100644 --- a/crates/nodes/src/atomic/emboss.rs +++ b/crates/nodes/src/atomic/emboss.rs @@ -1,7 +1,7 @@ use super::{ATOMIC, direction}; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("emboss", "Emboss", ATOMIC) @@ -23,7 +23,7 @@ fn emboss(context: &CookContext) -> CookResult { 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| { + 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); diff --git a/crates/nodes/src/atomic/gradient_dynamic.rs b/crates/nodes/src/atomic/gradient_dynamic.rs index cd38bdc..d0ce93a 100644 --- a/crates/nodes/src/atomic/gradient_dynamic.rs +++ b/crates/nodes/src/atomic/gradient_dynamic.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("gradient_dynamic", "Gradient (Dynamic)", ATOMIC) @@ -19,7 +19,7 @@ fn gradient_dynamic(context: &CookContext) -> CookResult { 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| { + 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/gradient_map.rs b/crates/nodes/src/atomic/gradient_map.rs index 38677f5..fce31a5 100644 --- a/crates/nodes/src/atomic/gradient_map.rs +++ b/crates/nodes/src/atomic/gradient_map.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Kind, luminance}; use materialcraft_core::Gradient; -use materialcraft_image::{Kind, luminance}; pub(super) fn definition() -> NodeDefinition { node("gradient_map", "Gradient map", ATOMIC) diff --git a/crates/nodes/src/atomic/grayscale_conversion.rs b/crates/nodes/src/atomic/grayscale_conversion.rs index f4b9fa1..3e27cb0 100644 --- a/crates/nodes/src/atomic/grayscale_conversion.rs +++ b/crates/nodes/src/atomic/grayscale_conversion.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("grayscale_conversion", "Grayscale conversion", ATOMIC) diff --git a/crates/nodes/src/atomic/hsl.rs b/crates/nodes/src/atomic/hsl.rs index f174f2b..a38ac73 100644 --- a/crates/nodes/src/atomic/hsl.rs +++ b/crates/nodes/src/atomic/hsl.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("hsl", "HSL", ATOMIC) diff --git a/crates/nodes/src/atomic/input_color.rs b/crates/nodes/src/atomic/input_color.rs index b3dc487..547f49c 100644 --- a/crates/nodes/src/atomic/input_color.rs +++ b/crates/nodes/src/atomic/input_color.rs @@ -1,7 +1,7 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; use materialcraft_core::ComponentUsage; -use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("input_color", "Input color", GRAPH_ITEMS) diff --git a/crates/nodes/src/atomic/input_grayscale.rs b/crates/nodes/src/atomic/input_grayscale.rs index 202263a..cdb941f 100644 --- a/crates/nodes/src/atomic/input_grayscale.rs +++ b/crates/nodes/src/atomic/input_grayscale.rs @@ -1,7 +1,7 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; use materialcraft_core::ComponentUsage; -use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("input_grayscale", "Input grayscale", GRAPH_ITEMS) diff --git a/crates/nodes/src/atomic/levels.rs b/crates/nodes/src/atomic/levels.rs index 079f7b4..743ad74 100644 --- a/crates/nodes/src/atomic/levels.rs +++ b/crates/nodes/src/atomic/levels.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("levels", "Levels", ATOMIC) @@ -24,7 +24,7 @@ fn levels(context: &CookContext) -> CookResult { let output_low = context.v4("out_low"); let output_high = context.v4("out_high"); - Ok(vec![image.map(image.kind, |pixel| { + Ok(vec![image.map(image.kind(), |pixel| { std::array::from_fn(|channel| levels_fn(pixel[channel], low[channel], mid[channel], high[channel], output_low[channel], output_high[channel])) })]) } diff --git a/crates/nodes/src/atomic/normal.rs b/crates/nodes/src/atomic/normal.rs index 6739c21..7505a18 100644 --- a/crates/nodes/src/atomic/normal.rs +++ b/crates/nodes/src/atomic/normal.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("normal", "Normal", ATOMIC) @@ -22,7 +22,7 @@ fn normal(context: &CookContext) -> CookResult { } pub fn height_to_normal(h: &Image, k: f32, directx: bool, tile: bool, alpha_height: bool) -> Image { - Image::generate(h.w, h.h, Kind::Color, |x, y| { + Image::generate(h.width(), h.height(), Kind::Color, |x, y| { let (dx, dy) = ops::slope(h, x as i64, y as i64, tile); let (nx, ny, nz) = (-dx * k, dy * k, 1.0); let l = (nx * nx + ny * ny + nz * nz).sqrt(); diff --git a/crates/nodes/src/atomic/output.rs b/crates/nodes/src/atomic/output.rs index 62202a2..a0b3433 100644 --- a/crates/nodes/src/atomic/output.rs +++ b/crates/nodes/src/atomic/output.rs @@ -1,7 +1,7 @@ use super::GRAPH_ITEMS; use super::dot::passthrough; use crate::{NodeDefinition, PortKind, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("output", "Output", GRAPH_ITEMS) @@ -17,6 +17,6 @@ pub fn output_kind(def: &NodeDefinition, port: usize, inputs: &[Option]) match def.outputs.get(port).map(|p| p.kind) { Some(PortKind::Gray) => Kind::Gray, Some(PortKind::Color) => Kind::Color, - _ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind), + _ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind()), } } diff --git a/crates/nodes/src/atomic/sharpen.rs b/crates/nodes/src/atomic/sharpen.rs index ef2bd46..ec639b7 100644 --- a/crates/nodes/src/atomic/sharpen.rs +++ b/crates/nodes/src/atomic/sharpen.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("sharpen", "Sharpen", ATOMIC) @@ -17,7 +17,7 @@ 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| { + 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]] })]) diff --git a/crates/nodes/src/atomic/text.rs b/crates/nodes/src/atomic/text.rs index 84088c4..2ebb1f1 100644 --- a/crates/nodes/src/atomic/text.rs +++ b/crates/nodes/src/atomic/text.rs @@ -208,7 +208,7 @@ mod tests { let vars = BTreeMap::new(); let context = CookContext { w: 256, h: 256, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; let img = &text(&context).unwrap()[0]; - let lit = img.data.iter().filter(|value| **value > 0.5).count(); + let lit = img.data().iter().filter(|value| **value > 0.5).count(); assert!(lit > 300, "{lit} pixels"); // Centered: nothing in the top and bottom quarters assert!((0..256).all(|x| img.get(x, 20, false)[0] == 0.0 && img.get(x, 236, false)[0] == 0.0)); diff --git a/crates/nodes/src/atomic/transformation.rs b/crates/nodes/src/atomic/transformation.rs index 695ab30..2eb4099 100644 --- a/crates/nodes/src/atomic/transformation.rs +++ b/crates/nodes/src/atomic/transformation.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("transformation", "Transformation 2D", ATOMIC) @@ -26,7 +26,7 @@ fn transformation(context: &CookContext) -> CookResult { let nearest = context.i("filtering") == 1; let matte = context.v4("matte"); - Ok(vec![Image::generate_uv(context.w, context.h, input.kind, |u, v| { + Ok(vec![Image::generate_uv(context.w, context.h, input.kind(), |u, v| { let x = u - 0.5 - offset[0]; let y = v - 0.5 - offset[1]; let source_u = (matrix[3] * x - matrix[1] * y) / determinant + 0.5; diff --git a/crates/nodes/src/atomic/uniform.rs b/crates/nodes/src/atomic/uniform.rs index fedde70..5a41542 100644 --- a/crates/nodes/src/atomic/uniform.rs +++ b/crates/nodes/src/atomic/uniform.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind, luminance}; +use craft_texture::{Image, Kind, luminance}; pub(super) fn definition() -> NodeDefinition { node("uniform", "Uniform color", ATOMIC) diff --git a/crates/nodes/src/atomic/warp.rs b/crates/nodes/src/atomic/warp.rs index bbd1f36..f0a5d7f 100644 --- a/crates/nodes/src/atomic/warp.rs +++ b/crates/nodes/src/atomic/warp.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("warp", "Warp", ATOMIC) @@ -18,7 +18,7 @@ fn warp(context: &CookContext) -> CookResult { let img = context.any_or(0, Kind::Gray, [0.0; 4]); let grad = context.gray_or(1, 0.0); let k = context.f("intensity"); - Ok(vec![Image::generate_uv(context.w, context.h, img.kind, |u, v| { + Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| { let (x, y) = ((u * context.w as f32) as i64, (v * context.h as f32) as i64); let (dx, dy) = ops::slope(&grad, x, y, context.tile); img.sample(u + dx * k, v + dy * k, context.tile) diff --git a/crates/nodes/src/cook_context.rs b/crates/nodes/src/cook_context.rs index bef04af..e8177ca 100644 --- a/crates/nodes/src/cook_context.rs +++ b/crates/nodes/src/cook_context.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_core::{Curve, FunctionGraph, Gradient, Value}; -use materialcraft_image::{Image, Kind}; use std::collections::BTreeMap; /// Where a cook runs: output size, seed, tiling, inputs and resolved parameters @@ -93,7 +93,7 @@ impl CookContext<'_> { /// The kind an "Any" output takes: the main input's, else `fallback` pub fn main_kind(&self, fallback: Kind) -> Kind { - self.inputs.iter().flatten().next().map_or(fallback, |i| i.kind) + self.inputs.iter().flatten().next().map_or(fallback, |i| i.kind()) } /// A gray image from `f(u, v)` at the output size diff --git a/crates/nodes/src/function/evaluation_context.rs b/crates/nodes/src/function/evaluation_context.rs index 449b685..1a5eba0 100644 --- a/crates/nodes/src/function/evaluation_context.rs +++ b/crates/nodes/src/function/evaluation_context.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; use std::collections::BTreeMap; /// Inputs shared by one function evaluation diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs index f83052d..5281d66 100644 --- a/crates/nodes/src/function/operation.rs +++ b/crates/nodes/src/function/operation.rs @@ -98,7 +98,7 @@ pub(crate) fn evaluate( let index = usize::try_from(setting[0]).map_err(|_| "negative image index")?; let pixel = match context.images.get(index).and_then(Option::as_ref) { Some(image) if setting[1] == 0 => { - image.get((position[0] * image.w as f32).floor() as i64, (position[1] * image.h as f32).floor() as i64, context.tile) + image.get((position[0] * image.width() as f32).floor() as i64, (position[1] * image.height() as f32).floor() as i64, context.tile) } Some(image) => image.sample(position[0], position[1], context.tile), None => [0.0; 4], diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs index 801bd2b..9e33735 100644 --- a/crates/nodes/src/function/processor.rs +++ b/crates/nodes/src/function/processor.rs @@ -1,9 +1,8 @@ use super::{EvaluationContext, EvaluationState, compile}; use crate::{CookContext, CookResult}; +use craft_texture::{Image, Kind, Limits}; use materialcraft_core::Value; -use materialcraft_image::{Image, Kind}; use rayon::prelude::*; -use std::sync::Arc; fn pixel(value: Value, gray: bool) -> Result<[f32; 4], String> { let values = super::value_type::floats(&value)?; @@ -25,7 +24,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { let gray = !context.b("color_mode"); let kind = if gray { Kind::Gray } else { Kind::Color }; - let (width, height) = materialcraft_image::clamp_size(context.w, context.h); + let (width, height) = craft_texture::clamp_size(context.w, context.h); let channels = kind.channels(); let mut data = vec![0.0; width as usize * height as usize * channels]; data.par_chunks_mut(width as usize * channels).enumerate().try_for_each_init(EvaluationState::default, |state, (y, row)| -> Result<(), String> { @@ -44,5 +43,5 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { } Ok(()) })?; - Ok(vec![Image { w: width, h: height, kind, data: Arc::new(data) }]) + Ok(vec![Image::from_data(width, height, kind, data, &Limits::default()).map_err(|e| e.to_string())?]) } diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 244a36e..0ba26e8 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_core::{FunctionGraph, Value}; -use materialcraft_image::{Image, Kind}; use std::collections::{BTreeMap, BTreeSet}; use super::{EvaluationContext, EvaluationState, FUNCTIONS, compile, default_value}; diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index db54747..d1a26b4 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -33,7 +33,7 @@ pub use parameter_descriptor::ParameterDescriptor; pub use port_definition::PortDefinition; pub use port_kind::PortKind; -pub type CookResult = Result, String>; +pub type CookResult = Result, String>; pub type Cook = fn(&CookContext<'_>) -> CookResult; #[cfg(test)] diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index c6a84ad..7486db4 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -1,9 +1,7 @@ //! Image operations shared by many nodes: Gaussian blur, Euclidean distance transform, slopes, //! color space helpers and blend modes. -use std::sync::Arc; - -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind, Limits}; use rayon::prelude::*; /// Gaussian blur with standard deviation `sigma` (pixels). Small sigmas use a sampled kernel; @@ -12,7 +10,7 @@ pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { if sigma.is_nan() || sigma <= 0.05 || !sigma.is_finite() { return img.clone(); } - let sigma = sigma.min(img.w.max(img.h) as f32); + let sigma = sigma.min(img.width().max(img.height()) as f32); if sigma < 3.0 { let r = (sigma * 3.0).ceil() as i64; let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); @@ -37,7 +35,7 @@ pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { fn convolve_1d(src: &Image, k: &[f32], r: i64, horizontal: bool, tile: bool) -> Image { let c = src.channels(); - Image::generate(src.w, src.h, src.kind, |x, y| { + Image::generate(src.width(), src.height(), src.kind(), |x, y| { let mut acc = [0.0f32; 4]; for (i, kv) in k.iter().enumerate() { let o = i as i64 - r; @@ -55,26 +53,27 @@ fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { if r <= 0 { return src.clone(); } - let (w, h) = (src.w as usize, src.h as usize); + let (w, h) = (src.width() as usize, src.height() as usize); let c = src.channels(); - let inv = 1.0 / (2 * r + 1) as f32; + let inv = 1.0 / (2 * r + 1) as f64; let mut data = vec![0.0f32; w * h * c]; let line_len = if horizontal { w } else { h }; let lines = if horizontal { h } else { w }; - let get = |line: usize, i: i64, ch: usize| -> f32 { + // The running sum is kept in f64, so a window of finite values near `f32::MAX` does not overflow. + let get = |line: usize, i: i64, ch: usize| -> f64 { let n = line_len as i64; let i = if tile { i.rem_euclid(n) } else { i.clamp(0, n - 1) } as usize; let (x, y) = if horizontal { (i, line) } else { (line, i) }; - src.data.get((y * w + x) * c + ch).copied().unwrap_or(0.0) + f64::from(src.data().get((y * w + x) * c + ch).copied().unwrap_or(0.0)) }; let results: Vec> = (0..lines) .into_par_iter() .map(|line| { let mut out = vec![0.0f32; line_len * c]; for ch in 0..c { - let mut sum: f32 = (-r..=r).map(|i| get(line, i, ch)).sum(); + let mut sum: f64 = (-r..=r).map(|i| get(line, i, ch)).sum(); for i in 0..line_len { - out[i * c + ch] = sum * inv; + out[i * c + ch] = (sum * inv) as f32; sum += get(line, i as i64 + r + 1, ch) - get(line, i as i64 - r, ch); } } @@ -88,7 +87,8 @@ fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { data[dst..dst + c].copy_from_slice(&vals[i * c..i * c + c]); } } - Image { w: src.w, h: src.h, kind: src.kind, data: Arc::new(data) } + // `data` has the size and kind of `src`, which is a valid image. + Image::from_data(src.width(), src.height(), src.kind(), data, &Limits::default()).unwrap_or_else(|_| src.clone()) } /// Squared Euclidean distance (pixels) from every pixel to the nearest pixel where `inside` is @@ -337,9 +337,10 @@ pub fn blend_px(mode: i32, bg: [f32; 4], fg: [f32; 4], opacity: f32, use_alpha: o } -/// A gray image of the output size from per-pixel values. -pub fn gray_from(w: u32, h: u32, v: Vec) -> Image { - Image { w, h, kind: Kind::Gray, data: Arc::new(v) } +/// A gray image of the output size from per-pixel values, or an error when the size is out of +/// range or `v` does not hold one value per pixel. +pub fn gray_from(w: u32, h: u32, v: Vec) -> Result { + Image::from_data(w, h, Kind::Gray, v, &Limits::default()).map_err(|e| e.to_string()) } #[cfg(test)] @@ -370,6 +371,23 @@ mod tests { assert!((flat.get(3, 3, false)[1] - 0.4).abs() < 1e-5); } + #[test] + fn box_blur_of_large_hdr_values_stays_finite() { + let value = 0.75 * f32::MAX; + let blurred = gaussian(&Image::filled(16, 4, Kind::Gray, [value; 4]), 5.0, true); + for x in 0..16 { + let v = blurred.get(x, 1, false)[0]; + assert!(v.is_finite() && (v / value - 1.0).abs() < 1e-5, "pixel {x} is {v}"); + } + } + + #[test] + fn gray_from_rejects_an_empty_size_and_a_wrong_value_count() { + assert!(gray_from(0, 4, Vec::new()).is_err()); + assert!(gray_from(2, 2, vec![0.0; 3]).is_err()); + assert_eq!(gray_from(2, 2, vec![0.5; 4]).map(|image| image.mean()[0]), Ok(0.5)); + } + #[test] fn edt_exact() { let d = distance_sq(9, 1, |i| i == 4, false); diff --git a/crates/nodes/src/pattern/raster.rs b/crates/nodes/src/pattern/raster.rs index 368693f..f923fa4 100644 --- a/crates/nodes/src/pattern/raster.rs +++ b/crates/nodes/src/pattern/raster.rs @@ -1,4 +1,4 @@ -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind, Limits}; use std::sync::Arc; use super::{pattern_stamp::PatternStamp, shape}; @@ -7,14 +7,16 @@ use crate::CookContext; const MAX_SAMPLES: u64 = 256_000_000; pub(super) fn render(context: &CookContext, stamps: &[PatternStamp]) -> Result { - let (width, height) = materialcraft_image::clamp_size(context.w, context.h); + let (width, height) = craft_texture::clamp_size(context.w, context.h); let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; - let mut image = + let background = context.input(0).map(|image| image.resize(width, height, context.tile)).unwrap_or_else(|| Image::filled(width, height, kind, context.v4("background"))); - image = if kind == Kind::Gray { image.to_gray() } else { image.to_color() }; + let background = if kind == Kind::Gray { background.to_gray() } else { background.to_color() }; let channels = kind.channels(); let opacity = context.f("opacity").max(0.0); - let pixels = Arc::make_mut(&mut image.data); + let data = Arc::clone(background.shared_data()); + drop(background); + let mut pixels = Arc::unwrap_or_clone(data); let mut budget = MAX_SAMPLES; for stamp in stamps { @@ -63,7 +65,7 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp]) -> Result { let uv = local.map(|coordinate| coordinate * 0.5 + 0.5); if stamp.filtering == 0 { - input.get((uv[0] * input.w as f32) as i64, (uv[1] * input.h as f32) as i64, false) + input.get((uv[0] * input.width() as f32) as i64, (uv[1] * input.height() as f32) as i64, false) } else { input.sample(uv[0], uv[1], false) } @@ -92,5 +94,5 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp]) -> Result], w: u32, h: u32, resource: &(dyn Fn(&str) -> Option + Sync)) -> CookResult { + let params = resolve_params(def, &BTreeMap::new()); + let vars = BTreeMap::new(); + let ctx = CookContext { w, h, seed: 7, tile: false, inputs, params: ¶ms, resource, vars: &vars }; + (def.cook)(&ctx) +} + +/// A request wider than the size limit spreads the normalized coordinates over the clamped width. +#[test] +fn an_oversized_transformation_covers_the_whole_input() { + let ramp = Image::gray(8192, 1, |x, _| x as f32 / 8191.0); + let out = cook_sized(find("transformation").unwrap(), &[Some(ramp)], 16384, 1, &|_| None).unwrap(); + let last = out[0].get(8191, 0, false)[0]; + assert!(last > 0.99, "the last pixel reads the ramp at {last}"); +} + +/// Bilinear resampling between finite values of opposite sign near the float limit stays finite. +#[test] +fn transformation_resamples_extreme_neighbors_to_finite_values() { + let extremes = Image::gray(2, 1, |x, _| if x == 0 { f32::MAX } else { -f32::MAX }); + let out = cook_sized(find("transformation").unwrap(), &[Some(extremes)], 4, 1, &|_| None).unwrap(); + for x in 0..4 { + let value = out[0].get(x, 0, false)[0]; + assert!(value.is_finite(), "pixel {x} is {value}"); + } +} + +/// A repeated input offset far past its edge keeps the offset's phase: an offset near 2^31 lands on +/// the same place as an offset of zero, halfway between the last and the first column. +#[test] +fn directional_warp_repeats_a_far_offset_with_its_phase() { + let stripes = Image::gray(3, 3, |x, _| [0.0, 1.0, 4.0][x as usize]); + // Intensity 10 scales the map by 10 / 256, so this map moves every pixel by about 2^31. + let far = Image::filled(3, 3, Kind::Gray, [2_147_483_648.0 * 25.6; 4]); + let out = cook(find("directional_warp").unwrap(), &[Some(stripes), Some(far)], 3).unwrap(); + for x in 0..3 { + assert_eq!(out[0].get_gray(x, 1, false), 2.0, "pixel {x}"); + } +} + +/// Shrinking a bitmap of large HDR values averages them without overflowing. +#[test] +fn bitmap_shrinks_large_hdr_values_without_overflow() { + let hdr = |_: &str| Some(Image::filled(2, 2, Kind::Color, [0.75 * f32::MAX, 0.75 * f32::MAX, 0.75 * f32::MAX, 1.0])); + let out = cook_sized(find("bitmap").unwrap(), &[], 1, 1, &hdr).unwrap(); + let pixel = out[0].get(0, 0, false); + assert!(pixel.iter().all(|value| value.is_finite()), "{pixel:?}"); + assert!((pixel[0] / (0.75 * f32::MAX) - 1.0).abs() < 1e-6, "{pixel:?}"); +} diff --git a/crates/nodes/tests/distance.rs b/crates/nodes/tests/distance.rs index 2da519a..8bdf5f0 100644 --- a/crates/nodes/tests/distance.rs +++ b/crates/nodes/tests/distance.rs @@ -1,13 +1,13 @@ use std::collections::BTreeMap; +use craft_texture::{Image, Kind}; use materialcraft_core::Value; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find, resolve_params}; fn cook(mask: Image, source: Option, tile: bool, combine: bool, distance: f32) -> Image { let def = find("distance").unwrap(); let params = resolve_params(def, &BTreeMap::from([("distance".into(), Value::Float(distance)), ("combine".into(), Value::Bool(combine))])); - let (w, h) = (mask.w, mask.h); + let (w, h) = (mask.width(), mask.height()); let inputs = [Some(mask), source]; let vars = BTreeMap::new(); let resource = |_: &str| None; @@ -22,7 +22,7 @@ fn tiled_distance_spreads_source_across_stationary_gradient() { // This is within range of the only mask pixel, but the symmetric distance field has zero // slope here. A gradient walk stopped on the black source background instead of the seed. assert_eq!(output.get_gray(16, 16, false), 1.0); - assert!(output.data.iter().all(|&v| v == 1.0)); + assert!(output.data().iter().all(|&v| v == 1.0)); } #[test] @@ -54,9 +54,9 @@ fn distance_handles_empty_full_masks_and_no_source() { let empty = Image::filled(7, 5, Kind::Gray, [0.0; 4]); let full = Image::filled(7, 5, Kind::Gray, [1.0; 4]); let source = Image::generate(7, 5, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 5.0, 0.4, 0.7]); - assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data.iter().all(|&v| v == 0.0)); + assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data().iter().all(|&v| v == 0.0)); assert_eq!(cook(full, Some(source), tile, true, 256.0).get(3, 2, false), [3.0 / 7.0, 2.0 / 5.0, 0.4, 0.7]); - assert!(cook(empty, None, tile, true, 256.0).data.iter().all(|&v| v == 0.0)); + assert!(cook(empty, None, tile, true, 256.0).data().iter().all(|&v| v == 0.0)); let mask = Image::gray(7, 5, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 }); let ramp = cook(mask, None, tile, false, 512.0 / 7.0); assert_eq!(ramp.get_gray(0, 0, false), 1.0); diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index a2fe2a0..5e6791c 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -11,5 +11,5 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } materialcraft-geom = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } rayon = { workspace = true } diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index 7ba30ba..8b0ba90 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -8,9 +8,9 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use crate::{Displacement, Relief}; +use craft_texture::{Image, linear_to_srgb}; use materialcraft_geom::glam::{Vec2, Vec3}; use materialcraft_geom::{Bvh, Mesh, OrbitCamera}; -use materialcraft_image::{Image, linear_to_srgb}; use rayon::prelude::*; use crate::ibl::{self, EnvImage}; @@ -94,7 +94,7 @@ impl Scene { } // Pre-filtered so detail finer than the mesh (left to the normal map) does not spike the silhouette - let height = height.resize(height.w.min(512), height.h.min(512), true); + let height = height.resize(height.width().min(512), height.height().min(512), true); let level = if displacement.level.is_finite() { displacement.level.clamp(0.0, 1.0) } else { 0.0 }; let depth = if displacement.depth.is_finite() { displacement.depth } else { 0.0 }; let tiling = if displacement.tiling.is_finite() { displacement.tiling.max(0.01) } else { 1.0 }; @@ -538,7 +538,7 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett #[cfg(test)] mod tests { use super::*; - use materialcraft_image::Kind; + use craft_texture::Kind; #[test] fn renders_a_material_on_every_scene() { diff --git a/crates/ui-egui/src/export/export_tests.rs b/crates/ui-egui/src/export/export_tests.rs index 28d6efd..e18d1f6 100644 --- a/crates/ui-egui/src/export/export_tests.rs +++ b/crates/ui-egui/src/export/export_tests.rs @@ -78,7 +78,7 @@ fn batch_writes_every_material_graph_at_the_output_size() { assert_eq!(files(&directory), ["New_graph_base_color.png", "New_graph_height.png", "Second_mask.png"]); let image = materialcraft_engine::formats::decode(&std::fs::read(directory.join("Second_mask.png")).unwrap(), true).unwrap(); - assert_eq!((image.w, image.h), (64, 32)); + assert_eq!((image.width(), image.height()), (64, 32)); let _ = std::fs::remove_dir_all(directory); } diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 850b382..3fc935d 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -241,15 +241,15 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let [width, height] = graph.size_px(); resp.clone().on_hover_text(format!( "{} x {} ({bits}bpc)\n{}: {width} x {height}\n{}: {limit} px\n{}", - img.w, - img.h, + img.width(), + img.height(), tr("Parent size"), tr("Preview limit"), tr("Change Preview size while editing in Edit > Preferences. Exports use each node's configured output size.") )); - format!("{}x{} {}", img.w, img.h, tr("Preview")) + format!("{}x{} {}", img.width(), img.height(), tr("Preview")) } else { - format!("{}x{} - {format}", img.w, img.h) + format!("{}x{} - {format}", img.width(), img.height()) }; painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), theme.text_dim); } diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs index 986edb7..bdd4290 100644 --- a/crates/ui-egui/src/levels_editor.rs +++ b/crates/ui-egui/src/levels_editor.rs @@ -16,10 +16,10 @@ const MIN_SPAN: f32 = 0.004; /// Histograms of an image's values in 0..1, clamped: one for a gray image, else R, G and B pub fn histogram(img: &Image) -> Vec<[u32; BINS]> { - let channels = if img.kind == Kind::Gray { 1 } else { 3 }; - let stride = img.kind.channels(); + let channels = if img.kind() == Kind::Gray { 1 } else { 3 }; + let stride = img.channels(); let mut h = vec![[0u32; BINS]; channels]; - for px in img.data.chunks(stride) { + for px in img.data().chunks(stride) { for (c, bins) in h.iter_mut().enumerate() { let v = px.get(c).copied().unwrap_or(0.0); let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index e65308b..0537797 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -47,7 +47,7 @@ fn rgba8(img: &Image, channel: &str) -> Vec { _ => None, }; match pick { - Some(k) if img.kind == Kind::Color => base.chunks(4).flat_map(|p| [p[k], p[k], p[k], 255]).collect(), + Some(k) if img.kind() == Kind::Color => base.chunks(4).flat_map(|p| [p[k], p[k], p[k], 255]).collect(), _ => base, } } @@ -95,23 +95,24 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let texture_limit = ctx.input(|i| i.max_texture_side).max(1); let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key) ^ (texture_limit as u64).rotate_left(32) - ^ (img.w as u64).rotate_left(16) - ^ img.h as u64 + ^ (img.width() as u64).rotate_left(16) + ^ img.height() as u64 ^ (app.session.view2d.port as u64).wrapping_mul(0x9e37) ^ (app.session.view2d.channel.len() as u64 * 31) ^ app.session.view2d.channel.bytes().next().unwrap_or(0) as u64; if app.view2d.tex.as_ref().is_none_or(|(k, _)| *k != key) { let px = rgba8(&img, &app.session.view2d.channel); // Keep source pixels for readout/screenshots, but respect the renderer's upload limit. - let ci = if img.w.max(img.h) as usize > texture_limit { - let scale = texture_limit as f64 / f64::from(img.w.max(img.h)); - let display = img.resize((f64::from(img.w) * scale).floor().max(1.0) as u32, (f64::from(img.h) * scale).floor().max(1.0) as u32, false); - ColorImage::from_rgba_unmultiplied([display.w as usize, display.h as usize], &rgba8(&display, &app.session.view2d.channel)) + let ci = if img.width().max(img.height()) as usize > texture_limit { + let scale = texture_limit as f64 / f64::from(img.width().max(img.height())); + let display = + img.resize((f64::from(img.width()) * scale).floor().max(1.0) as u32, (f64::from(img.height()) * scale).floor().max(1.0) as u32, false); + ColorImage::from_rgba_unmultiplied([display.width() as usize, display.height() as usize], &rgba8(&display, &app.session.view2d.channel)) } else { - ColorImage::from_rgba_unmultiplied([img.w as usize, img.h as usize], &px) + ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], &px) }; app.view2d.tex = Some((key, ctx.load_texture("view2d", ci, TextureOptions::NEAREST))); - app.view2d.shown = Some((img.w, img.h, px)); + app.view2d.shown = Some((img.width(), img.height(), px)); } let avail = ui.available_size(); let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 20.0).max(40.0)), Sense::click_and_drag()); @@ -122,7 +123,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { app.ui.image_camera = app.ui.image_camera.sanitized(); let cam = &mut app.ui.image_camera; let tiles = if app.session.view2d.tiled { 3.0 } else { 1.0 }; - let fit_zoom = ((rect.width() - 16.0) / (img.w as f32 * tiles)).min((rect.height() - 16.0) / (img.h as f32 * tiles)).max(0.01); + let fit_zoom = ((rect.width() - 16.0) / (img.width() as f32 * tiles)).min((rect.height() - 16.0) / (img.height() as f32 * tiles)).max(0.01); if cam.fit { cam.zoom = fit_zoom; cam.offset = [0.0, 0.0]; @@ -146,11 +147,11 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let d = resp.drag_delta(); cam.offset = [cam.offset[0] + d.x, cam.offset[1] + d.y]; } - let size = vec2(img.w as f32, img.h as f32) * cam.zoom; + let size = vec2(img.width() as f32, img.height() as f32) * cam.zoom; let center = rect.center() + vec2(cam.offset[0], cam.offset[1]); let full = Rect::from_center_size(center, size * tiles); // A checker behind transparent images. - if img.kind == Kind::Color && app.session.view2d.channel == "rgba" { + if img.kind() == Kind::Color && app.session.view2d.channel == "rgba" { let cell = 8.0; let vis = full.intersect(rect); let mut y = vis.top(); @@ -181,15 +182,16 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { // Info line: size, format, zoom and the pixel under the pointer. let info = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 20.0)); let bits = app.session.cooked.nodes.get(&id).map_or("16", |result| result.base.format.bits()); - let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.w, img.h, if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0); + let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.width(), img.height(), if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0); if let Some(ptr) = resp.hover_pos() { let local = (ptr - (center - size * 0.5)) / cam.zoom; let (x, y) = (local.x.floor() as i64, local.y.floor() as i64); let v = img.get(x, y, true); if img.is_gray() { - text += &format!(" ({}, {}) {:.3}", x.rem_euclid(img.w as i64), y.rem_euclid(img.h as i64), v[0]); + text += &format!(" ({}, {}) {:.3}", x.rem_euclid(img.width() as i64), y.rem_euclid(img.height() as i64), v[0]); } else { - text += &format!(" ({}, {}) {:.3} {:.3} {:.3} {:.3}", x.rem_euclid(img.w as i64), y.rem_euclid(img.h as i64), v[0], v[1], v[2], v[3]); + text += + &format!(" ({}, {}) {:.3} {:.3} {:.3} {:.3}", x.rem_euclid(img.width() as i64), y.rem_euclid(img.height() as i64), v[0], v[1], v[2], v[3]); } } ui.painter().rect_filled(info, 0.0, tk.panel); diff --git a/crates/ui-egui/tests/it/preview_resolution.rs b/crates/ui-egui/tests/it/preview_resolution.rs index 59c3532..c8e414f 100644 --- a/crates/ui-egui/tests/it/preview_resolution.rs +++ b/crates/ui-egui/tests/it/preview_resolution.rs @@ -48,7 +48,7 @@ fn painted(h: &Harness<'static, MaterialCraftApp>) -> Vec { fn node_resolution_explains_the_preview_cap() { let (mut h, id) = harness(512, false); let img = h.state().session.cooked.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (512, 512)); + assert_eq!((img.width(), img.height()), (512, 512)); assert_eq!(h.state().session.graph().unwrap().size, [10, 10]); assert!(painted(&h).iter().any(|t| t == "512x512 Preview"), "missing preview label: {:?}", painted(&h)); let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1; @@ -61,14 +61,14 @@ fn node_resolution_explains_the_preview_cap() { assert!(text.contains("16bpc"), "format information lost: {text}"); let full = h.state().session.cook_full(0); let img = full.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (1024, 1024)); + assert_eq!((img.width(), img.height()), (1024, 1024)); } #[test] fn full_size_mode_retains_the_resolution_and_format() { let (h, id) = harness(0, false); let img = h.state().session.cooked.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (1024, 1024)); + assert_eq!((img.width(), img.height()), (1024, 1024)); assert!(painted(&h).iter().any(|t| t == "1024x1024 - C16"), "{:?}", painted(&h)); assert!(!painted(&h).iter().any(|t| t == "1024x1024 Preview")); } diff --git a/crates/ui-egui/tests/it/resolution.rs b/crates/ui-egui/tests/it/resolution.rs index 64231d5..40140ae 100644 --- a/crates/ui-egui/tests/it/resolution.rs +++ b/crates/ui-egui/tests/it/resolution.rs @@ -25,8 +25,8 @@ fn choose_4k(h: &mut Harness<'static, MaterialCraftApp>) { h.step(); let app = h.state(); let (_, image) = app.session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (4096, 4096)); - assert!(app.session.material_maps().iter().all(|(_, image)| (image.w, image.h) == (4096, 4096))); + assert_eq!((image.width(), image.height()), (4096, 4096)); + assert!(app.session.material_maps().iter().all(|(_, image)| (image.width(), image.height()) == (4096, 4096))); assert!(!app.session.material_maps().is_empty()); assert_eq!(app.view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); } @@ -66,7 +66,7 @@ fn four_k_preview_refreshes_texture_after_size_change() { h.state_mut().ui.prefs.preview_size = 4096; h.step(); let (_, image) = h.state().session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (4096, 4096)); + assert_eq!((image.width(), image.height()), (4096, 4096)); assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); h.state_mut().session.preview_size = Some(256); h.state_mut().session.cook(); @@ -74,7 +74,7 @@ fn four_k_preview_refreshes_texture_after_size_change() { h.state_mut().ui.prefs.preview_size = 256; h.step(); let (_, image) = h.state().session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (256, 256)); + assert_eq!((image.width(), image.height()), (256, 256)); assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((256, 256))); } diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 9ef06c6..58de37c 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1223,7 +1223,7 @@ fn named_outputs_select_without_loading_and_open_on_double_click() { app.run("view.2d", json!({"node": source})).unwrap(); app.run("graph.select", json!({"ids": [source]})).unwrap(); app.session.cook(); - let material = app.session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::>(); + let material = app.session.material_maps().into_iter().map(|(name, image)| (name, image.shared_data().clone())).collect::>(); let view3d = serde_json::to_value(&app.session.view3d).unwrap(); let mut harness = harness(app, 1600.0, 960.0); settle(&mut harness, 5); @@ -1248,7 +1248,7 @@ fn named_outputs_select_without_loading_and_open_on_double_click() { assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]); assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); assert_eq!(serde_json::to_value(&harness.state().session.view3d).unwrap(), view3d); - let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::>(); + let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.shared_data().clone())).collect::>(); assert_eq!(current, material); save(&mut harness, &directory, "named-output-preview"); } diff --git a/docs/architecture.md b/docs/architecture.md index d357c06..690a311 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,8 +9,8 @@ them). Everything below the UI is plain Rust with no UI toolkit and builds for ```text L0 core document model: Package → Graph → Node / Connection / Frame / Comment / Pin / ExposedParameter; Value (float, vectors, int, bool, color, enum, text, curve, gradient, function graph) -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 image the craft-texture crate from storytold/craft-libs: grayscale or RGBA f32 planes behind an + Arc (free to share); repeat/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; shared image operations and iterative function/pattern execution diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 99f4764..c551092 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -12,7 +12,7 @@ use serde_json::Value; /// Library crates by directory under `crates/` (package `materialcraft-`) and their layer. pub const TABLE: &[(&str, u8)] = - &[("core", 0), ("image", 0), ("geom", 0), ("nodes", 1), ("eval", 2), ("formats", 2), ("engine", 3), ("render", 3), ("automation", 4), ("ui-egui", 5)]; + &[("core", 0), ("geom", 0), ("nodes", 1), ("eval", 2), ("formats", 2), ("engine", 3), ("render", 3), ("automation", 4), ("ui-egui", 5)]; /// Binaries and build tooling on top of every layer: exempt from the rules. pub const EXEMPT: &[&str] = &["materialcraft", "materialcraft-cli", "materialcraft-web", "xtask"]; @@ -149,7 +149,7 @@ mod tests { fn downward_graph_passes() { let g = [ c("materialcraft-core", &[("serde", Normal, false)]), - c("materialcraft-nodes", &[("materialcraft-core", Normal, true), ("materialcraft-image", Normal, true)]), + c("materialcraft-nodes", &[("materialcraft-core", Normal, true), ("materialcraft-geom", Normal, true)]), c("materialcraft-engine", &[("materialcraft-eval", Normal, true), ("materialcraft-geom", Dev, true)]), c("materialcraft-render", &[("materialcraft-nodes", Normal, true), ("wgpu", Normal, false)]), c("materialcraft-ui-egui", &[("materialcraft-automation", Normal, true), ("egui", Normal, false), ("wgpu", Normal, false)]), diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 240fd0e..c3cfe00 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -111,7 +111,6 @@ fn cmd_layers() -> Result<(), String> { /// Packages that must build for wasm32-unknown-unknown, in dependency order. const WASM_PACKAGES: &[&str] = &[ "materialcraft-core", - "materialcraft-image", "materialcraft-geom", "materialcraft-nodes", "materialcraft-eval", From 06a2af7eeacc1f6c1eef496b759bc8cf96b977df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:31:03 -0800 Subject: [PATCH 2/3] Image: blur keeps images made with raised limits The sampled-kernel and box passes of `ops::gaussian` built their output with the default limits. For an image wider or taller than 8192 pixels, made with a raised `max_side`, the sampled pass clamped its output to 8192 pixels and the box pass returned the unblurred source. Both passes now build their output with limits that admit the source's size. --- crates/nodes/src/ops.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index 7486db4..c538220 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -33,9 +33,19 @@ pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { out } +/// The default limits, raised to admit `src`, so a pass over an image made with raised limits +/// returns an image of the same size. +fn limits_for(src: &Image) -> Limits { + let mut limits = Limits::default(); + limits.max_side = limits.max_side.max(src.width()).max(src.height()); + limits.max_pixels = limits.max_pixels.max(u64::from(src.width()) * u64::from(src.height())); + limits.max_bytes = limits.max_bytes.max(size_of_val(src.data()) as u64); + limits +} + fn convolve_1d(src: &Image, k: &[f32], r: i64, horizontal: bool, tile: bool) -> Image { let c = src.channels(); - Image::generate(src.width(), src.height(), src.kind(), |x, y| { + Image::try_generate(src.width(), src.height(), src.kind(), &limits_for(src), |x, y| { let mut acc = [0.0f32; 4]; for (i, kv) in k.iter().enumerate() { let o = i as i64 - r; @@ -46,6 +56,7 @@ fn convolve_1d(src: &Image, k: &[f32], r: i64, horizontal: bool, tile: bool) -> } if c == 1 { [acc[0], 0.0, 0.0, 0.0] } else { acc } }) + .unwrap_or_else(|_| src.clone()) } /// One running-sum box pass of radius `r`. @@ -88,7 +99,7 @@ fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { } } // `data` has the size and kind of `src`, which is a valid image. - Image::from_data(src.width(), src.height(), src.kind(), data, &Limits::default()).unwrap_or_else(|_| src.clone()) + Image::from_data(src.width(), src.height(), src.kind(), data, &limits_for(src)).unwrap_or_else(|_| src.clone()) } /// Squared Euclidean distance (pixels) from every pixel to the nearest pixel where `inside` is @@ -381,6 +392,22 @@ mod tests { } } + #[test] + fn blur_keeps_the_size_and_result_of_an_image_over_the_default_limits() { + let w = craft_texture::MAX_SIDE + 1; + let mut limits = Limits::default(); + limits.max_side = w; + let values: Vec = (0..w).map(|x| if (x / 8) % 2 == 0 { 1.0 } else { 0.0 }).collect(); + let Ok(img) = Image::from_data(w, 1, Kind::Gray, values, &limits) else { + panic!("a {w}x1 image fits the raised limits"); + }; + for sigma in [1.0, 5.0] { + let blurred = gaussian(&img, sigma, false); + assert_eq!((blurred.width(), blurred.height()), (w, 1), "sigma {sigma}"); + assert_ne!(blurred.data(), img.data(), "sigma {sigma} left the pixels unchanged"); + } + } + #[test] fn gray_from_rejects_an_empty_size_and_a_wrong_value_count() { assert!(gray_from(0, 4, Vec::new()).is_err()); From 4b5c27188c5a399b0ba91df5224d6816f6fddafd Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 17 Nov 2026 03:28:21 +0000 Subject: [PATCH 3/3] Auto: Fix HDR mipmaps and reuse image processing buffers Prevent overflow in nearest-filter mipmaps and retain regression coverage. Reuse pattern, precision, channel and blur buffers. Wait for asynchronous parameter cooks in snapshot tests. Complete scoped cleanup and remove confirmed unused dependencies. Validated affected release suites, Clippy, layering, wasm, hostile-input checks and all 43 offscreen snapshots. --- Cargo.lock | 2 - Cargo.toml | 3 +- crates/automation/Cargo.toml | 2 - crates/automation/src/headless.rs | 12 +- crates/engine/src/graph_cmds.rs | 21 +-- crates/engine/src/library_preview.rs | 4 +- crates/engine/src/material_cmds.rs | 68 ++++---- crates/engine/src/session.rs | 22 +-- crates/engine/src/session.test.rs | 3 + crates/engine/tests/it/atomics.rs | 9 ++ crates/engine/tests/it/export_names.rs | 3 + crates/engine/tests/it/parameter_functions.rs | 6 + crates/engine/tests/it/subgraph_seed.rs | 10 +- crates/engine/tests/session.rs | 14 +- crates/eval/src/graph_execution.rs | 1 + crates/eval/src/graph_instance.rs | 79 +++++----- crates/eval/src/output_precision.rs | 6 +- crates/eval/src/tests.rs | 28 +++- crates/formats/src/image.rs | 81 +++++----- crates/formats/src/svg.rs | 1 + crates/formats/src/tests.rs | 3 + crates/nodes/src/atomic/blend.rs | 14 +- crates/nodes/src/atomic/box_filter.rs | 63 ++++---- crates/nodes/src/atomic/curve.rs | 24 +-- crates/nodes/src/atomic/directional_warp.rs | 11 +- crates/nodes/src/atomic/distance.rs | 37 +++-- crates/nodes/src/atomic/normal.rs | 2 +- crates/nodes/src/atomic/transformation.rs | 6 +- crates/nodes/src/atomic/warp.rs | 12 +- crates/nodes/src/function/tests.rs | 19 +++ crates/nodes/src/ops.rs | 133 +++++++++------- crates/nodes/src/pattern/raster.rs | 19 ++- crates/nodes/src/pattern/tests.rs | 5 + crates/nodes/src/tests.rs | 40 ++++- crates/nodes/tests/distance.rs | 3 + crates/nodes/tests/parity_unconnected.rs | 1 + crates/render/src/preview.rs | 59 +++---- crates/ui-egui/src/export/export_tests.rs | 3 + crates/ui-egui/src/graph/canvas.rs | 58 +++---- crates/ui-egui/src/levels_editor.rs | 22 +-- crates/ui-egui/src/view2d.rs | 145 ++++++++++-------- crates/ui-egui/tests/it/preview_resolution.rs | 6 + crates/ui-egui/tests/it/resolution.rs | 9 +- crates/ui-egui/tests/snapshot.rs | 5 + .../tests/snapshot/parameter_functions.rs | 15 ++ xtask/src/layers.rs | 1 + 46 files changed, 670 insertions(+), 420 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5c1d95c..cf56723 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2826,9 +2826,7 @@ dependencies = [ "getrandom 0.3.4", "image", "materialcraft-engine", - "materialcraft-formats", "materialcraft-render", - "rayon", "rmcp", "rustix 1.1.6", "schemars", diff --git a/Cargo.toml b/Cargo.toml index da4ec39..3274bd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,6 @@ dds = { version = "0.2", default-features = false } half = "2" eframe = { version = "0.37", default-features = false } egui = "0.37" -wgpu = "30" rfd = "0.17" rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] } zip = { version = "2", default-features = false, features = ["deflate"] } @@ -87,7 +86,7 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"] cap-std = "4" getrandom = "0.3" # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, -# MIT OR Apache-2.0, every craft-libs crate pinned to one rev. +# MIT OR Apache-2.0, with each dependency pinned to its reviewed revision egui_kittest = "0.37" craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["serde"] } diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index d56a4fb..b938cb4 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -11,12 +11,10 @@ workspace = true [dependencies] materialcraft-engine = { workspace = true } materialcraft-render = { workspace = true } -materialcraft-formats = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } image = { workspace = true } -rayon = { workspace = true } rmcp = { workspace = true } tokio = { workspace = true } schemars = { workspace = true } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 4c34f3c..0ddafa9 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -264,15 +264,15 @@ impl Headless { Ok(Rendered { width: w, height: h, png }) } - fn render_2d(&mut self, o: &RenderOptions, max: u32) -> Result<(u32, u32, Vec), AutomationError> { - let img = match o.node { - Some(n) => self.session.cooked.image(NodeId(n), o.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?, + fn render_2d(&mut self, options: &RenderOptions, maximum_side: u32) -> Result<(u32, u32, Vec), AutomationError> { + let image = match options.node { + Some(n) => self.session.cooked.image(NodeId(n), options.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?, None => self.session.view2d_image().map(|(_, i)| i).ok_or_else(|| bad("nothing to show: the graph has no outputs; pass `node`"))?, }; - let (w, h) = (o.width.unwrap_or(img.width()).clamp(16, max), o.height.unwrap_or(img.height()).clamp(16, max)); - let img = img.resize(w, h, true); - Ok((w, h, img.to_rgba8_display())) + let (w, h) = (options.width.unwrap_or(image.width()).clamp(16, maximum_side), options.height.unwrap_or(image.height()).clamp(16, maximum_side)); + let image = image.resize(w, h, true); + Ok((w, h, image.to_rgba8_display())) } fn render_3d(&mut self, o: &RenderOptions, max: u32) -> (u32, u32, Vec) { diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index a05ee94..373d151 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -149,26 +149,27 @@ fn format(s: &mut Session, p: &J) -> Result { }) } -fn cook(s: &mut Session, p: &J) -> Result { - let index = match p.get("graph").filter(|graph| !graph.is_null()) { - None => s.graph, +fn cook(session: &mut Session, parameters: &J) -> Result { + let index = match parameters.get("graph").filter(|graph| !graph.is_null()) { + None => session.graph, Some(graph) => { let index = graph.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph.cook", "`graph` is a graph index"))?; - let graph = s.pkg.graph(index)?; + let graph = session.pkg.graph(index)?; if graph.function.is_some() { return Err(bad("graph.cook", "a Function Graph has no outputs to compute")); } + index } }; - let cooked = if index != s.graph || boolp(p, "full") == Some(true) { s.cook_full(index) } else { s.cook().clone() }; - let g = s.pkg.graph(index)?; + let cooked = if index != session.graph || boolp(parameters, "full") == Some(true) { session.cook_full(index) } else { session.cook().clone() }; + let graph = session.pkg.graph(index)?; Ok(json!({ "ms": cooked.ms, - "nodes": cooked.nodes.iter().map(|(id, r)| { - let n = g.node(*id).ok(); - json!({"id": id.0, "def": n.map(|n| n.def.clone()), "ms": r.ms, "cached": r.cached, "error": r.error, - "size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.width(), i.height()])}) + "nodes": cooked.nodes.iter().map(|(id, result)| { + let node = graph.node(*id).ok(); + json!({"id": id.0, "def": node.map(|node| node.def.clone()), "ms": result.ms, "cached": result.cached, "error": result.error, + "size": result.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.width(), image.height()])}) }).collect::>(), })) } diff --git a/crates/engine/src/library_preview.rs b/crates/engine/src/library_preview.rs index a7f2a3a..4ba0a2e 100644 --- a/crates/engine/src/library_preview.rs +++ b/crates/engine/src/library_preview.rs @@ -32,7 +32,7 @@ impl NodeLibrary { let index = source.graphs.iter().position(|candidate| candidate.function.is_none() && candidate.sbs_path() == graph)?; let size = size.clamp(1, COOKED_SIZE); - // A session links the graph's instances and functions to the library, as an opened package gets + // A session resolves library references just as it does for an opened package let mut session = Session::with_library(Package::clone(source), library.clone()); session.limit_preview_caches(); if cancel.load(Ordering::Relaxed) { @@ -43,7 +43,7 @@ impl NodeLibrary { let decode = session.resource_decoder(); let mut options = materialcraft_eval::Options::new(&decode); - // Thin lines and fine grain vanish when cooked at thumbnail size, so the graph cooks larger and is scaled down + // Cook larger before downsampling so fine detail survives in thumbnails let cooked_size = size.max(COOKED_SIZE); options.max_size = Some(cooked_size); options.cancel = Some(cancel); diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index d42f868..1333e35 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -54,64 +54,66 @@ pub(crate) fn specs() -> Vec { pub use crate::MaterialOptions; -/// Cook graph `gi` with `o` and pack it as a portable material (`.mcmat` bytes) -pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result> { - let mut pkg = s.pkg.clone(); - let g = pkg.graph_mut(gi)?; - if let Some(px) = o.size { - let log2 = 31 - px.clamp(16, 8192).leading_zeros(); - g.size = [log2, log2]; +/// Cook `graph_index` with `options` and pack it as a portable material (`.mcmat` bytes) +pub fn material_bytes(session: &Session, graph_index: usize, options: &MaterialOptions) -> Result> { + let mut package = session.pkg.clone(); + let graph = package.graph_mut(graph_index)?; + if let Some(side_pixels) = options.size { + let log2 = 31 - side_pixels.clamp(16, 8192).leading_zeros(); + graph.size = [log2, log2]; } - g.inputs.extend(o.values.clone()); - let g = pkg.graph(gi)?; - let dec = s.resource_decoder(); - let mut opts = materialcraft_eval::Options::new(&dec); - opts.environment = s.environment; - opts.inputs = o.inputs.clone(); - let cooked = materialcraft_eval::cook(&pkg, gi, &opts, &s.cache); + graph.inputs.extend(options.values.clone()); + let graph = package.graph(graph_index)?; + let decode = session.resource_decoder(); + let mut cook_options = materialcraft_eval::Options::new(&decode); + cook_options.environment = session.environment; + cook_options.inputs = options.inputs.clone(); + let cooked = materialcraft_eval::cook(&package, graph_index, &cook_options, &session.cache); let mut maps: Vec<(String, Vec)> = Vec::new(); let mut entries = Vec::new(); let mut size = [0, 0]; - for (_, usage, _, img) in materialcraft_eval::outputs(g, &cooked) { - let Some(img) = img else { continue }; + for (_, usage, _, image) in materialcraft_eval::outputs(graph, &cooked) { + let Some(image) = image else { continue }; if usage == "any" || entries.iter().any(|e: &MapEntry| e.usage == usage) { continue; } + let srgb = srgb_usage(usage); let file = format!("maps/{usage}.png"); - maps.push((file.clone(), encode(img, "png", if srgb { Depth::U8 } else { Depth::U16 }, srgb)?)); + maps.push((file.clone(), encode(image, "png", if srgb { Depth::U8 } else { Depth::U16 }, srgb)?)); entries.push(MapEntry { usage: usage.into(), file, color_space: if srgb { "srgb" } else { "linear" }.into() }); - size = [img.width(), img.height()]; + size = [image.width(), image.height()]; } if entries.is_empty() { return Err(bad( "file.exportMaterial", format!( "graph `{}` has no outputs with a material usage ({})", - g.name, + graph.name, ComponentUsage::ALL.iter().filter(|usage| **usage != ComponentUsage::ANY).map(|usage| usage.id).collect::>().join(", ") ), )); } + let manifest = Manifest { format: FORMAT.into(), version: VERSION, - name: g.name.replace('_', " "), - graph: g.name.clone(), + name: graph.name.replace('_', " "), + graph: graph.name.clone(), size, maps: entries, - parameters: g + parameters: graph .exposed .iter() .filter(|e| portable(&e.default)) - .map(|e| Parameter { param: e.clone(), value: g.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()) }) + .map(|e| Parameter { param: e.clone(), value: graph.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()) }) .collect(), - inputs: image_inputs(g), - presets: g.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(), + inputs: image_inputs(graph), + presets: graph.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(), source: String::new(), }; - let source = materialcraft_formats::sbs::write_sbs(&pkg)?; + let source = materialcraft_formats::sbs::write_sbs(&package)?; Ok(materialcraft_formats::material::write_material(&manifest, &maps, &source)?) } @@ -291,15 +293,22 @@ mod tests { crate::execute(&mut s, "graph.node.add", &json!({"def": "input_grayscale", "params": {"identifier": "curvature"}})).unwrap(); let png = encode(&Image::filled(4, 4, craft_texture::Kind::Gray, [0.7; 4]), "png", Depth::U16, false).unwrap(); let res = crate::file_cmds::add_resource(&mut s, "curv.png", png, None).unwrap(); + assert!(crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "nope", "resource": res})).is_err()); + crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "curvature", "resource": res, "linear": true})).unwrap(); + assert_eq!(s.graph().unwrap().input_images.get("curvature"), Some(&res)); + let bytes = materialcraft_formats::sbs::write_sbs(&s.pkg).unwrap(); let reopened = materialcraft_formats::sbs::read_sbs(&bytes, "input.sbs", &|_| None).unwrap().pkg; + assert_eq!(reopened.graphs[s.graph].input_images.get("curvature"), Some(&res)); assert!(reopened.graphs[s.graph].input_images_linear.contains("curvature")); + let bytes = material_bytes(&s, s.graph, &MaterialOptions { size: Some(16), ..Default::default() }).unwrap(); let (m, _) = read_material(&bytes).unwrap(); + assert!(m.inputs.iter().any(|i| i.identifier == "curvature" && i.kind == "gray")); assert_eq!(crate::execute(&mut s, "graph.input.unbind", &json!({"identifier": "curvature"})).unwrap(), J::Bool(true)); assert!(s.graph().unwrap().input_images.is_empty()); @@ -338,23 +347,26 @@ mod tests { let output_path = dir.join("out.mcmat").to_str().unwrap().to_string(); let result = crate::execute(&mut s, "file.exportMaterial", &json!({"path": output_path, "size": 16, "inputs": {"normal": input_path}})); + assert!(result.is_ok()); let bytes = std::fs::read(&output_path).unwrap(); let _ = std::fs::remove_dir_all(&dir); - // The material archive stores maps uncompressed; pull the normal map - // out of its local file header and decode it as linear data. + // The uncompressed archive exposes the normal map after its local file header let name = b"maps/normal.png"; let pos = bytes.windows(name.len()).position(|w| w == name).unwrap(); let header = pos - 30; + assert_eq!(&bytes[header..header + 4], b"PK\x03\x04"); + let name_len = u16::from_le_bytes([bytes[header + 26], bytes[header + 27]]) as usize; let extra_len = u16::from_le_bytes([bytes[header + 28], bytes[header + 29]]) as usize; let compressed = u32::from_le_bytes([bytes[header + 18], bytes[header + 19], bytes[header + 20], bytes[header + 21]]) as usize; let start = header + 30 + name_len + extra_len; let map = &bytes[start..start + compressed]; let decoded = decode(map, true).unwrap(); + assert!((decoded.get(0, 0, false)[0] - 128.0 / 255.0).abs() < 1e-3, "data inputs must be decoded as linear"); } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 896b21a..4e77b22 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -426,29 +426,29 @@ impl Session { /// A decoder for the package's bitmap resources (memoized, shareable with worker threads). pub fn resource_decoder(&self) -> impl Fn(&str) -> Option + Sync + Send + 'static { - let mut res: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); - res.extend( + let mut resources: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); + resources.extend( self.pkg .dependencies .iter() .flat_map(|(file, package)| package.resources.iter().map(move |resource| (format!("{file}\0{}", resource.name), resource.bytes.clone()))), ); - let memo = self.decoded.clone(); + let decoded = self.decoded.clone(); // Release decoded images of deleted or replaced resources - let hashes = res.iter().map(|(_, bytes)| bytes.content_hash()).collect(); - memo.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes); + let hashes = resources.iter().map(|(_, bytes)| bytes.content_hash()).collect(); + decoded.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes); move |requested: &str| { let (name, linear) = craft_texture::split_resource_key(requested); - let (_, bytes) = res.iter().find(|(n, _)| n == name)?; + let (_, bytes) = resources.iter().find(|(name_candidate, _)| name_candidate == name)?; let key = (bytes.content_hash(), linear); - if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { - return Some(i); + if let Some(image) = decoded.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { + return Some(image); } - let img = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?; - memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone()); - Some(img) + let image = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?; + decoded.lock().unwrap_or_else(PoisonError::into_inner).insert(key, image.clone()); + Some(image) } } diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs index 3e102c5..e854e08 100644 --- a/crates/engine/src/session.test.rs +++ b/crates/engine/src/session.test.rs @@ -193,7 +193,10 @@ fn a_failed_group_recooks_if_it_cooked_a_temporary_document() { s.cook(); Err(crate::EngineError::Other("failed".into())) }); + assert!(result.is_err()); + s.cook_if_dirty(); + assert_eq!(s.cooked.image(id, 0).unwrap().data(), before.as_slice()); } diff --git a/crates/engine/tests/it/atomics.rs b/crates/engine/tests/it/atomics.rs index a12da18..fc13c90 100644 --- a/crates/engine/tests/it/atomics.rs +++ b/crates/engine/tests/it/atomics.rs @@ -59,19 +59,28 @@ fn atomic_sample_round_trips_through_native_fields_and_cooks_identically() { assert!(!text.contains(forbidden)); } let read = read_sbs(&bytes, "atomic_sample.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let mut loaded = Session::new(read.pkg); loaded.preview_size = Some(64); loaded.cook(); + assert_eq!(original.graph().unwrap().connections.len(), loaded.graph().unwrap().connections.len()); + for (before, after) in original.graph().unwrap().nodes.iter().zip(&loaded.graph().unwrap().nodes) { assert_eq!(before.def, after.def); + let result = &loaded.cooked.nodes[&after.id]; + assert!(result.error.is_none(), "{}: {:?}", after.def, result.error); + match (original.cooked.image(before.id, 0), loaded.cooked.image(after.id, 0)) { (Some(before), Some(after)) => { assert_eq!((before.width(), before.height(), before.kind()), (after.width(), after.height(), after.kind())); + let error = before.data().iter().zip(after.data()).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max); + assert!(error < 1e-5, "pixel error {error}"); } (None, None) => assert_eq!(original.cooked.value(before.id, 0), loaded.cooked.value(after.id, 0)), diff --git a/crates/engine/tests/it/export_names.rs b/crates/engine/tests/it/export_names.rs index e1c15ce..5e4b43c 100644 --- a/crates/engine/tests/it/export_names.rs +++ b/crates/engine/tests/it/export_names.rs @@ -101,9 +101,12 @@ fn unique_export_writes_both_maps_with_their_expected_pixels() { let (mut s, _) = session(); let dir = TempDir::new("unique"); let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"})).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 2); + for (name, value) in [("first.png", 0.2), ("second.png", 0.8)] { let image = formats::decode(&std::fs::read(dir.0.join(name)).unwrap(), false).unwrap(); + assert_eq!((image.width(), image.height()), (16, 16)); assert!((image.get(0, 0, false)[0] - value).abs() < 0.001, "{name}"); } diff --git a/crates/engine/tests/it/parameter_functions.rs b/crates/engine/tests/it/parameter_functions.rs index cebd707..aab2fab 100644 --- a/crates/engine/tests/it/parameter_functions.rs +++ b/crates/engine/tests/it/parameter_functions.rs @@ -25,17 +25,21 @@ fn output_size_function_controls_resolution_and_survives_sbs() { let cooked = session.cook(); let image = cooked.image(owner, 0).unwrap(); + assert_eq!((image.width(), image.height()), (128, 32)); assert!(cooked.nodes[&owner].error.is_none()); let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); let loaded = formats::sbs::read_sbs(&bytes, "parameter-functions.sbs", &|_| None).unwrap(); + assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings); + let mut reopened = Session::new(loaded.pkg); reopened.preview_size = None; let owner = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "uniform").unwrap().id; let cooked = reopened.cook(); let image = cooked.image(owner, 0).unwrap(); + assert_eq!((image.width(), image.height()), (128, 32)); } @@ -90,6 +94,7 @@ fn native_dynamic_output_size_is_not_discarded_on_load() { let cooked = session.cook(); let image = cooked.image(owner, 0).unwrap(); + assert_eq!((image.width(), image.height()), (64, 32)); } @@ -394,6 +399,7 @@ fn base_functions_inherit_from_the_primary_input_and_bypasses_keep_input_dimensi let cooked = session.cook(); let image = cooked.image(blend, 0).unwrap(); + assert_eq!((image.width(), image.height()), (16, 16)); assert_eq!(cooked.nodes[&blend].base.size, [32, 32]); assert_eq!(cooked.nodes[&output].base.size, [32, 32]); diff --git a/crates/engine/tests/it/subgraph_seed.rs b/crates/engine/tests/it/subgraph_seed.rs index 569dec9..c125139 100644 --- a/crates/engine/tests/it/subgraph_seed.rs +++ b/crates/engine/tests/it/subgraph_seed.rs @@ -23,23 +23,31 @@ fn grouping_noise_preserves_pixels_seed_and_undo() { let before_graphs = s.pkg.graphs.clone(); let before = s.cook().image(output, 0).unwrap().clone(); run(&mut s, "graph.createFromSelection", json!({"name": "Grouped_noise"})); - // Force an actual cook instead of relying on the pre-grouping cache entry. + + // Force an actual cook instead of relying on the pre-grouping cache entry s.cache.lock().unwrap().clear(); let after = s.cook().image(output, 0).unwrap().clone(); + assert!(before.data() == after.data(), "grouping changed the material at graph seed {seed}"); assert_eq!((after.width(), after.height()), (64, 32)); assert_eq!(s.pkg.graphs[1].seed, seed); + let grouped_graphs = s.pkg.graphs.clone(); run(&mut s, "edit.undo", json!({})); + assert_eq!(s.pkg.graphs, before_graphs); assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data()); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.pkg.graphs, grouped_graphs); assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data()); + let bytes = formats::sbs::write_sbs(&s.pkg).unwrap(); let mut reopened = Session::new(formats::sbs::read_sbs(&bytes, "seed.sbs", &|_| None).unwrap().pkg); reopened.preview_size = None; let reopened_output = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id; + assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data(), before.data()); } } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 636a558..c2c0a7a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -79,15 +79,21 @@ fn package_save_and_open_round_trip() { let before = s.pkg.clone(); run(&mut s, "file.newPackage", json!({})); run(&mut s, "file.open", json!({"path": path.to_str().unwrap()})); + assert_eq!(s.pkg.graphs[0].nodes.len(), before.graphs[0].nodes.len()); + let out = dir.join("tex"); let r = run(&mut s, "file.export", json!({"dir": out.to_str().unwrap(), "format": "png", "depth": 8})); + assert_eq!(r["files"].as_array().unwrap().len(), 1); + let small = dir.join("small"); run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64})); let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path(); let img = materialcraft_formats::decode(&std::fs::read(file).unwrap(), false).unwrap(); + assert_eq!((img.width(), img.height()), (64, 64)); + let _ = std::fs::remove_dir_all(&dir); } @@ -113,11 +119,13 @@ fn export_size_keeps_proportions_and_clamps() { assert_eq!(parsed(&s, json!(0)).unwrap(), None); assert_eq!(parsed(&s, json!(u64::MAX)).unwrap(), Some(ExportSize::LargerSide(u32::MAX))); assert_eq!(parsed(&s, json!([1, u64::MAX])).unwrap(), Some(ExportSize::Exact([1, u32::MAX]))); + for invalid in [json!("large"), json!([64]), json!([64, "wide"]), json!([64, 64, 64])] { assert!(parsed(&s, invalid.clone()).is_err(), "{invalid}"); } s.pkg.graphs[0].size = [u32::MAX, u32::MAX]; + assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32))); assert!(dims(&s, json!([1, u64::MAX])).iter().all(|d| *d == (16, 8192)), "sides clamp to 16..8192"); } @@ -380,13 +388,16 @@ fn reimported_bitmap_shows_new_pixels() { use materialcraft_formats::{Depth, encode}; let bmp = |v: f32| encode(&Image::filled(4, 4, Kind::Color, [v, v, v, 1.0]), "bmp", Depth::U8, true).unwrap(); let (dark, light) = (bmp(0.1), bmp(0.9)); + assert_eq!(dark.len(), light.len(), "same-size files are the case under test"); + let mut s = sample_session(); materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", dark, Some("tex")).unwrap(); let before = s.resource_decoder()("tex").unwrap().data()[0]; s.undo(); materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", light, Some("tex")).unwrap(); let after = s.resource_decoder()("tex").unwrap().data()[0]; + assert!(after - before > 0.5, "{before} -> {after}"); } @@ -422,7 +433,7 @@ fn a_wire_splits_with_a_reroute_dot_and_deletes() { #[test] fn every_template_is_opaque_in_the_3d_view() { - // The 3D view sees through a base color whose alpha is below one: the templates must not + // Template base colors must stay opaque in the 3D view let mut s = sample_session(); s.preview_size = Some(64); for (id, _) in materialcraft_engine::samples::TEMPLATES { @@ -431,6 +442,7 @@ fn every_template_is_opaque_in_the_3d_view() { for (usage, img) in s.material_maps() { if usage == "baseColor" && !img.is_gray() { let min = img.data().chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min); + assert!(min >= 0.999, "{id}: base color alpha goes down to {min}"); } } diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index c3c18c8..1013b2e 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -47,6 +47,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu cooked.cancelled = true; break; } + let Some(node) = prepared.index.node(id) else { continue }; let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, cache); diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index d7f75ba..d11e671 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -37,71 +37,76 @@ pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool } pub(crate) fn cook_instance( - pkg: &Package, - gi: usize, + package: &Package, + graph_index: usize, node: &Node, - in_ports: &[Port], - out_ports: &[Port], + input_ports: &[Port], + output_ports: &[Port], inputs: &[Option<&NodeOutput>], params: &BTreeMap, size: (u32, u32), base: crate::resolved_base_parameters::ResolvedBaseParameters, - opts: &Options, + options: &Options, cache: &Mutex, ) -> Result, String> { - if opts.depth >= MAX_DEPTH { + if options.depth >= MAX_DEPTH { return Err("graph instances nest too deep (does a graph use itself?)".into()); } - let registry = opts.registry.unwrap_or(pkg); - let (source, sub_gi, sub) = resolve(registry, pkg, node).ok_or("the instanced graph does not exist")?; - let identity = std::ptr::from_ref(sub) as usize; - if pkg.graphs.get(gi).is_some_and(|graph| std::ptr::eq(graph, sub)) || opts.graph_stack.contains(&identity) { - return Err(format!("graph `{}` uses itself through a graph instance", sub.name)); + + let registry = options.registry.unwrap_or(package); + let (source, source_graph_index, source_graph) = resolve(registry, package, node).ok_or("the instanced graph does not exist")?; + let identity = std::ptr::from_ref(source_graph) as usize; + if package.graphs.get(graph_index).is_some_and(|graph| std::ptr::eq(graph, source_graph)) || options.graph_stack.contains(&identity) { + return Err(format!("graph `{}` uses itself through a graph instance", source_graph.name)); } - if sub.function.is_some() || !sub.nodes.iter().any(|node| node.def == "output") { + + if source_graph.function.is_some() || !source_graph.nodes.iter().any(|node| node.def == "output") { return Err("the referenced graph must be a main graph with an output".into()); } - let root_resource = opts.resource_root.unwrap_or(opts.resource); + + let root_resource = options.resource_root.unwrap_or(options.resource); let resource = |name: &str| match &node.instance { Some(instance) if !instance.package.is_empty() => { let (name, linear) = craft_texture::split_resource_key(name); root_resource(&craft_texture::resource_key(&format!("{}\0{name}", instance.package), linear)) } - _ => (opts.resource)(name), + _ => (options.resource)(name), }; - let mut o = Options::new(&resource); - o.environment = opts.environment; - o.parent_tiling = Some(base.tiling); - o.parent_pixel_ratio = Some(base.pixel_ratio); - o.parent_base = Some(base); - o.registry = Some(registry); - o.resource_root = Some(root_resource); - o.max_size = opts.max_size; - o.cancel = opts.cancel; - o.depth = opts.depth + 1; - o.graph_stack = opts.graph_stack.clone(); - o.graph_stack.push(identity); - o.only = Some(sub.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect()); - o.inputs = in_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect(); - o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); - o.overrides.extend(in_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone())))); - let cooked = cook(source, sub_gi, &o, cache); + let mut source_options = Options::new(&resource); + source_options.environment = options.environment; + source_options.parent_tiling = Some(base.tiling); + source_options.parent_pixel_ratio = Some(base.pixel_ratio); + source_options.parent_base = Some(base); + source_options.registry = Some(registry); + source_options.resource_root = Some(root_resource); + source_options.max_size = options.max_size; + source_options.cancel = options.cancel; + source_options.depth = options.depth + 1; + source_options.graph_stack = options.graph_stack.clone(); + source_options.graph_stack.push(identity); + source_options.only = Some(source_graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect()); + source_options.inputs = input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect(); + source_options.overrides = params.iter().filter(|(k, _)| source_graph.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); + source_options.overrides.extend(input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone())))); + let cooked = cook(source, source_graph_index, &source_options, cache); if cooked.cancelled { return Err("cancelled".into()); } + if let Some(error) = cooked.nodes.values().find_map(|result| result.error.as_deref()) { - return Err(format!("{}: {error}", sub.name)); + return Err(format!("{}: {error}", source_graph.name)); } - out_ports + + output_ports .iter() - .map(|p| { - let output = sub + .map(|port| { + let output = source_graph .nodes .iter() - .find(|n| n.def == "output" && identifier(n) == p.id) + .find(|candidate| candidate.def == "output" && identifier(candidate) == port.id) .and_then(|node| cooked.nodes.get(&node.id)) .and_then(|result| result.outputs.first()) - .ok_or_else(|| format!("the source output `{}` is missing", p.id))?; + .ok_or_else(|| format!("the source output `{}` is missing", port.id))?; Ok(match output { NodeOutput::Image(image) => NodeOutput::Image(image.resize(size.0, size.1, true)), NodeOutput::Value(value) => NodeOutput::Value(value.clone()), diff --git a/crates/eval/src/output_precision.rs b/crates/eval/src/output_precision.rs index 46ec27a..9b1a240 100644 --- a/crates/eval/src/output_precision.rs +++ b/crates/eval/src/output_precision.rs @@ -49,10 +49,10 @@ fn with_pixels(image: Image, integer_sampling: bool, convert: impl Fn(&mut f32)) limits.max_pixels = u64::MAX; limits.max_bytes = u64::MAX; - let shared = Arc::clone(image.shared_data()); + let mut data = Arc::clone(image.shared_data()); drop(image); - let mut data = Arc::unwrap_or_clone(shared); - data.iter_mut().for_each(convert); + + Arc::make_mut(&mut data).iter_mut().for_each(convert); // `data` keeps the size and kind of a valid image, so `from_data` accepts it Image::from_data(width, height, kind, data, &limits) diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 7eb7aab..2892244 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -121,6 +121,7 @@ fn hostile_param_is_clamped_before_cooking() { p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1e30)); let cache = Mutex::new(Cache::default()); let c = cook(&p, 0, &Options::new(&no_res), &cache); + assert!(c.nodes[&blur].error.is_none(), "{:?}", c.nodes[&blur].error); assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((64, 64))); } @@ -134,6 +135,7 @@ fn preview_cap_and_unknown_nodes() { let mut opts = Options::new(&no_res); opts.max_size = Some(128); let c = cook(&p, 0, &opts, &cache); + assert_eq!(c.image(out, 0).map(|i| i.width()), Some(128)); assert!(c.nodes[&bad].error.is_some()); } @@ -379,20 +381,27 @@ fn cached_input_fingerprint_tracks_copy_on_write_and_shape() { let cache = Mutex::new(Cache::default()); let image = Image::filled(128, 128, Kind::Gray, [0.0; 4]); let first = image_key(&image, &cache); + assert_eq!(image_key(&image, &cache), first); + let mut data = image.data().to_vec(); data[1] = 1.0; let image = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap(); let changed = image_key(&image, &cache); + assert_ne!(changed, first); - // The same buffer read as another shape. + + // The same buffer read as another shape let image = Image::from_data(64, 256, Kind::Gray, Arc::clone(image.shared_data()), &Limits::default()).unwrap(); let reshaped = image_key(&image, &cache); + assert_ne!(reshaped, changed); cache.lock().unwrap().clear(); + assert_eq!(image_key(&image, &cache), reshaped); } + #[test] fn preview_cap_does_not_compound_downscaling() { let (mut p, noise, blur, out) = sample(); @@ -402,10 +411,12 @@ fn preview_cap_does_not_compound_downscaling() { let mut opts = Options::new(&no_res); opts.max_size = Some(512); let c = cook(&p, 0, &opts, &cache); + assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((512, 512))); assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 128))); assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 128))); } + #[test] fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { let (mut p, noise, blur, out) = sample(); @@ -416,10 +427,12 @@ fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { let mut opts = Options::new(&no_res); opts.max_size = Some(128); let c = cook(&p, 0, &opts, &cache); + assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((128, 64))); assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 64))); assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 64))); } + #[test] fn changed_unsampled_input_recooks() { let mut g = Graph::new("g"); @@ -432,15 +445,19 @@ fn changed_unsampled_input_recooks() { opts.inputs.insert("input".into(), image.clone()); let cache = Mutex::new(Cache::default()); let first = cook(&p, 0, &opts, &cache); + assert!(!first.nodes[&input].cached); + let mut data = image.data().to_vec(); data[1] = 1.0; let changed = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap(); opts.inputs.insert("input".into(), changed); let second = cook(&p, 0, &opts, &cache); + assert!(!second.nodes[&input].cached); assert_eq!(second.image(input, 0).unwrap().data()[1], 1.0); } + #[test] fn linear_input_images_and_bitmap_nodes_request_data_reads() { // The decoder returns 0.5 for a linear request and 0.2 for an sRGB one @@ -531,16 +548,25 @@ fn bound_input_image_linear_flag_change_recooks_instance() { let cache = Mutex::new(Cache::default()); let opts = Options::new(&res); let first = cook(&p, 0, &opts, &cache); + assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error); assert!(!first.nodes[&inst].cached); + let first_value = first.image(inst, 0).unwrap().data()[0]; + assert!((first_value - 0.2).abs() < 1e-4, "sRGB bound image should reach the instance, got {first_value}"); + let second = cook(&p, 0, &opts, &cache); + assert!(second.nodes[&inst].cached, "an unchanged instance should be served from the cache"); + p.graphs[1].input_images_linear.insert("in".into()); let third = cook(&p, 0, &opts, &cache); + assert!(!third.nodes[&inst].cached, "toggling input_images_linear must recook the instance"); + let third_value = third.image(inst, 0).unwrap().data()[0]; + assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}"); } diff --git a/crates/formats/src/image.rs b/crates/formats/src/image.rs index 3a8647a..a4db566 100644 --- a/crates/formats/src/image.rs +++ b/crates/formats/src/image.rs @@ -8,7 +8,10 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { return guard(|| crate::dds_image::decode(bytes, linear), || FormatError::Image("DDS decoder failed".into())); } - if std::str::from_utf8(bytes.get(..bytes.len().min(4096)).unwrap_or_default()).is_ok_and(|text| text.contains(" Result { let mut limits = image::Limits::default(); limits.max_image_width = Some(MAX_SIDE); limits.max_image_height = Some(MAX_SIDE); - limits.max_alloc = Some(1 << 30); + limits.max_alloc = Some(MAX_DECODE_BYTES); reader.limits(limits); Ok(reader) }; @@ -35,16 +38,16 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels"))); } - let img = guard(|| open()?.decode().map_err(image_error), failed)?; - let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16); - let float = matches!(img.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F); + let decoded = guard(|| open()?.decode().map_err(image_error), failed)?; + let gray = matches!(decoded.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16); + let float = matches!(decoded.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F); if gray { - let l = img.into_luma16(); - let data: Vec = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); + let luminance = decoded.into_luma16(); + let data: Vec = luminance.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); return Image::from_data(w, h, Kind::Gray, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string())); } - let mut data = img.into_rgba32f().into_raw(); + let mut data = decoded.into_rgba32f().into_raw(); if !(float || linear) { for px in data.as_chunks_mut::<4>().0 { for c in px.iter_mut().take(3) { @@ -56,24 +59,24 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { Image::from_data(w, h, Kind::Color, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string())) } -/// Encode `img` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear -pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result> { +/// Encode `image` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear +pub fn encode(image: &Image, ext: &str, depth: Depth, srgb: bool) -> Result> { let ext = ext.trim_start_matches('.').to_ascii_lowercase(); - let enc = |v: f32| if srgb && img.kind() == Kind::Color { linear_to_srgb(v) } else { v }; - let (w, h) = (img.width(), img.height()); - let color = img.kind() == Kind::Color; - let px = |i: usize| -> [f32; 4] { + let encode_channel = |v: f32| if srgb && image.kind() == Kind::Color { linear_to_srgb(v) } else { v }; + let (w, h) = (image.width(), image.height()); + let color = image.kind() == Kind::Color; + let pixel = |i: usize| -> [f32; 4] { if color { - let s = img.data().get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); - [enc(s[0]), enc(s[1]), enc(s[2]), s[3]] + let s = image.data().get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + [encode_channel(s[0]), encode_channel(s[1]), encode_channel(s[2]), s[3]] } else { - let v = img.data().get(i).copied().unwrap_or(0.0); + let v = image.data().get(i).copied().unwrap_or(0.0); [v, v, v, 1.0] } }; - let n = (w * h) as usize; - let fmt = match ext.as_str() { + let pixel_count = (w * h) as usize; + let format = match ext.as_str() { "png" => image::ImageFormat::Png, "jpg" | "jpeg" => image::ImageFormat::Jpeg, "tga" => image::ImageFormat::Tga, @@ -84,44 +87,44 @@ pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result return Err(FormatError::Image(format!("unsupported export format `{other}`"))), }; - let float_only = matches!(fmt, image::ImageFormat::OpenExr | image::ImageFormat::Hdr); - let sixteen_ok = fmt == image::ImageFormat::Png; - let q8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let q16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; - let dynimg: image::DynamicImage = if float_only { - let data: Vec = (0..n) + let float_only = matches!(format, image::ImageFormat::OpenExr | image::ImageFormat::Hdr); + let sixteen_ok = format == image::ImageFormat::Png; + let quantize_u8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let quantize_u16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; + let dynamic_image: image::DynamicImage = if float_only { + let data: Vec = (0..pixel_count) .flat_map(|i| { - let p = px(i); + let p = pixel(i); [p[0], p[1], p[2]] }) .collect(); - let buf = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?; - buf.into() + let buffer = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?; + buffer.into() } else if depth != Depth::U8 && sixteen_ok { if color { - let data: Vec = (0..n).flat_map(|i| px(i).map(q16)).collect(); + let data: Vec = (0..pixel_count).flat_map(|i| pixel(i).map(quantize_u16)).collect(); image::ImageBuffer::, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() } else { - let data: Vec = (0..n).map(|i| q16(px(i)[0])).collect(); + let data: Vec = (0..pixel_count).map(|i| quantize_u16(pixel(i)[0])).collect(); image::ImageBuffer::, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() } - } else if color && !matches!(fmt, image::ImageFormat::Jpeg) { - let data: Vec = (0..n).flat_map(|i| px(i).map(q8)).collect(); + } else if color && !matches!(format, image::ImageFormat::Jpeg) { + let data: Vec = (0..pixel_count).flat_map(|i| pixel(i).map(quantize_u8)).collect(); image::RgbaImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() } else if color { - let data: Vec = (0..n) + let data: Vec = (0..pixel_count) .flat_map(|i| { - let p = px(i); - [q8(p[0]), q8(p[1]), q8(p[2])] + let p = pixel(i); + [quantize_u8(p[0]), quantize_u8(p[1]), quantize_u8(p[2])] }) .collect(); image::RgbImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() } else { - let data: Vec = (0..n).map(|i| q8(px(i)[0])).collect(); + let data: Vec = (0..pixel_count).map(|i| quantize_u8(pixel(i)[0])).collect(); image::GrayImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() }; - let mut out = Cursor::new(Vec::new()); - dynimg.write_to(&mut out, fmt).map_err(|e| FormatError::Image(e.to_string()))?; - Ok(out.into_inner()) + let mut output = Cursor::new(Vec::new()); + dynamic_image.write_to(&mut output, format).map_err(|e| FormatError::Image(e.to_string()))?; + Ok(output.into_inner()) } diff --git a/crates/formats/src/svg.rs b/crates/formats/src/svg.rs index 46e022e..4ab862f 100644 --- a/crates/formats/src/svg.rs +++ b/crates/formats/src/svg.rs @@ -79,6 +79,7 @@ mod tests { #[test] fn draws_a_shape_in_linear_light() { let image = decode(&svg(r##""##)).unwrap(); + let left = image.get(0, 0, false); assert_eq!((image.width(), image.height()), (4, 2)); diff --git a/crates/formats/src/tests.rs b/crates/formats/src/tests.rs index 972ddc0..ea4173f 100644 --- a/crates/formats/src/tests.rs +++ b/crates/formats/src/tests.rs @@ -11,11 +11,13 @@ fn export_every_format() { for i in [&img, &gray] { let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}")); let back = decode(&b, false).unwrap_or_else(|e| panic!("{ext} decode: {e}")); + assert_eq!((back.width(), back.height()), (8, 8)); } } } let png16 = encode(&gray, "png", Depth::U16, false).unwrap(); + assert!((decode(&png16, false).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3); } @@ -39,6 +41,7 @@ fn tga_still_decodes() { let mut tga = Cursor::new(Vec::new()); ::image::RgbaImage::new(2, 2).write_to(&mut tga, ::image::ImageFormat::Tga).unwrap(); let img = decode(tga.get_ref(), false).unwrap(); + assert_eq!((img.width(), img.height(), img.kind()), (2, 2, Kind::Color)); } diff --git a/crates/nodes/src/atomic/blend.rs b/crates/nodes/src/atomic/blend.rs index 9bf28fa..3437fdb 100644 --- a/crates/nodes/src/atomic/blend.rs +++ b/crates/nodes/src/atomic/blend.rs @@ -21,19 +21,19 @@ pub(super) fn definition() -> NodeDefinition { } fn blend(context: &CookContext) -> CookResult { - let (fg, bg) = (context.sized(0), context.sized(1)); - let kind = if [&fg, &bg].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray }; - let fg = fg.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 0.0])); - let bg = bg.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 1.0])); + let (foreground, background) = (context.sized(0), context.sized(1)); + let kind = if [&foreground, &background].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray }; + let foreground = foreground.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 0.0])); + let background = background.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 1.0])); let mask = context.sized(2).map(|m| m.to_gray()); - let (mode, op) = (context.i("mode"), context.f("opacity")); + let (mode, opacity) = (context.i("mode"), context.f("opacity")); let color_blending = context.i("color_blending"); - let blend_alpha = context.b("alpha") && !fg.is_gray(); + let blend_alpha = context.b("alpha") && !foreground.is_gray(); let clamp = matches!(context.format, materialcraft_core::OutputFormat::U8 | materialcraft_core::OutputFormat::U16 | materialcraft_core::OutputFormat::Inherit); Ok(vec![Image::generate(context.w, context.h, kind, |x, y| { let (x, y) = (x as i64, y as i64); let m = mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false)); - ops::blend_px(mode, bg.get(x, y, false), fg.get(x, y, false), op * m, color_blending, blend_alpha, clamp) + ops::blend_px(mode, background.get(x, y, false), foreground.get(x, y, false), opacity * m, color_blending, blend_alpha, clamp) })]) } diff --git a/crates/nodes/src/atomic/box_filter.rs b/crates/nodes/src/atomic/box_filter.rs index e8841f5..07436ae 100644 --- a/crates/nodes/src/atomic/box_filter.rs +++ b/crates/nodes/src/atomic/box_filter.rs @@ -13,40 +13,45 @@ pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) -> let edge_weight = (0.5 - (extent as f64 - 0.5) * weight).max(0.0); let (length, lines) = if horizontal { (input.width(), input.height()) } else { (input.height(), input.width()) }; 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); - } + let fill_line = |line: u32, output: &mut [f32]| { + let get = |position: i64| { + if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) } + }; + 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); } - output - }) - .collect(); + 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); + } + } + }; let data = if horizontal { - results.into_iter().flatten().collect() + let mut data = vec![0.0; input.width() as usize * input.height() as usize * channels]; + data.par_chunks_mut(length as usize * channels).enumerate().for_each(|(line, output)| fill_line(line as u32, output)); + data } else { + let results: Vec> = (0..lines) + .into_par_iter() + .map(|line| { + let mut output = vec![0.0; length as usize * channels]; + fill_line(line, &mut output); + output + }) + .collect(); let mut data = Vec::with_capacity(input.width() as usize * input.height() as usize * channels); for y in 0..input.height() as usize { for line in &results { diff --git a/crates/nodes/src/atomic/curve.rs b/crates/nodes/src/atomic/curve.rs index 6060202..c3167f4 100644 --- a/crates/nodes/src/atomic/curve.rs +++ b/crates/nodes/src/atomic/curve.rs @@ -7,16 +7,18 @@ pub(super) fn definition() -> NodeDefinition { } fn curve(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); - let c = context.curve("curve"); - // A 1024-entry table: the curve is smooth, so linear lookups are exact enough - let lut: Vec = (0..=1024).map(|i| c.eval(i as f32 / 1024.0)).collect(); - let f = |v: f32| { - let t = v.clamp(0.0, 1.0) * 1024.0; - let i = t as usize; - let a = lut.get(i).copied().unwrap_or(0.0); - let b = lut.get(i + 1).copied().unwrap_or(a); - a + (b - a) * (t - i as f32) + let image = context.any_or(0, Kind::Gray, [0.0; 4]); + let curve = context.curve("curve"); + + // Linear interpolation over 1024 intervals approximates the smooth curve + const TABLE_INTERVALS: usize = 1024; + let table: Vec = (0..=TABLE_INTERVALS).map(|i| curve.eval(i as f32 / TABLE_INTERVALS as f32)).collect(); + let lookup = |value: f32| { + let position = value.clamp(0.0, 1.0) * TABLE_INTERVALS as f32; + let i = position as usize; + let a = table.get(i).copied().unwrap_or(0.0); + let b = table.get(i + 1).copied().unwrap_or(a); + a + (b - a) * (position - i as f32) }; - Ok(vec![img.map(img.kind(), |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) + Ok(vec![image.map(image.kind(), |p| [lookup(p[0]), lookup(p[1]), lookup(p[2]), p[3]])]) } diff --git a/crates/nodes/src/atomic/directional_warp.rs b/crates/nodes/src/atomic/directional_warp.rs index e7a4722..a7be3e0 100644 --- a/crates/nodes/src/atomic/directional_warp.rs +++ b/crates/nodes/src/atomic/directional_warp.rs @@ -15,12 +15,13 @@ pub(super) fn definition() -> NodeDefinition { } fn directional_warp(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); + let image = context.any_or(0, Kind::Gray, [0.0; 4]); let map = context.gray_or(1, 0.0); let (dx, dy) = direction(context.f("angle")); - let k = context.f("intensity") / 256.0; - Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| { - let m = map.sample_gray(u, v, context.tile) * k; - img.sample(u + dx * m, v + dy * m, context.tile) + const BASE_RESOLUTION: f32 = 256.0; + let intensity_scale = context.f("intensity") / BASE_RESOLUTION; + Ok(vec![Image::generate_uv(context.w, context.h, image.kind(), |u, v| { + let offset = map.sample_gray(u, v, context.tile) * intensity_scale; + image.sample(u + dx * offset, v + dy * offset, context.tile) })]) } diff --git a/crates/nodes/src/atomic/distance.rs b/crates/nodes/src/atomic/distance.rs index 486270e..92cacb9 100644 --- a/crates/nodes/src/atomic/distance.rs +++ b/crates/nodes/src/atomic/distance.rs @@ -17,31 +17,38 @@ pub(super) fn definition() -> NodeDefinition { fn distance(context: &CookContext) -> CookResult { let mask = context.gray_or(0, 0.0); - let maxd = (context.f("distance").max(0.0) * context.w as f32 / 256.0).max(1e-3); + const BASE_RESOLUTION: f32 = 256.0; + const MIN_DISTANCE_PIXELS: f32 = 1e-3; + let maximum_distance = (context.f("distance").max(0.0) * context.w as f32 / BASE_RESOLUTION).max(MIN_DISTANCE_PIXELS); let data = mask.shared_data().clone(); let inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5; - let Some(src) = context.sized(1) else { - let d2 = ops::distance_sq(context.w, context.h, inside, context.tile); - return Ok(vec![ops::gray_from(context.w, context.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())?]); + let Some(source) = context.sized(1) else { + let squared_distances = ops::distance_sq(context.w, context.h, inside, context.tile); + return Ok(vec![ops::gray_from( + context.w, + context.h, + squared_distances.iter().map(|d| (1.0 - d.sqrt() / maximum_distance).clamp(0.0, 1.0)).collect(), + )?]); }; + // Propagate the exact nearest site without gaps from gradient-walk stalls - let (d2, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile); + let (squared_distances, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile); let combine = context.b("combine"); - Ok(vec![Image::generate(context.w, context.h, src.kind(), |x, y| { + Ok(vec![Image::generate(context.w, context.h, source.kind(), |x, y| { let i = y as usize * context.w as usize + x as usize; let site = sites.get(i).copied().unwrap_or(usize::MAX); - let mut c = if site == usize::MAX { - [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }] + let mut pixel = if site == usize::MAX { + [0.0, 0.0, 0.0, if source.is_gray() { 1.0 } else { 0.0 }] } else { - src.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false) + source.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false) }; - let d = d2.get(i).copied().unwrap_or(f32::INFINITY).sqrt(); - if d > maxd { - c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]; + let d = squared_distances.get(i).copied().unwrap_or(f32::INFINITY).sqrt(); + if d > maximum_distance { + pixel = [0.0, 0.0, 0.0, if source.is_gray() { 1.0 } else { 0.0 }]; } else if combine { - let f = (1.0 - d / maxd).clamp(0.0, 1.0); - c = [c[0] * f, c[1] * f, c[2] * f, c[3]]; + let falloff = (1.0 - d / maximum_distance).clamp(0.0, 1.0); + pixel = [pixel[0] * falloff, pixel[1] * falloff, pixel[2] * falloff, pixel[3]]; } - c + pixel })]) } diff --git a/crates/nodes/src/atomic/normal.rs b/crates/nodes/src/atomic/normal.rs index d0836bb..802c9c0 100644 --- a/crates/nodes/src/atomic/normal.rs +++ b/crates/nodes/src/atomic/normal.rs @@ -24,7 +24,7 @@ fn normal(context: &CookContext) -> CookResult { pub fn height_to_normal(height_map: &Image, intensity: f32, directx: bool, tile: bool, alpha_height: bool) -> Image { Image::generate(height_map.width(), height_map.height(), Kind::Color, |x, y| { - // Backward differences place alpha wrapped discontinuity on its owning pixel + // Backward differences place a wrapped discontinuity on its owning pixel let height = height_map.get_gray(x as i64, y as i64, tile); let dx = height - height_map.get_gray(x as i64 - 1, y as i64, tile); let dy = height - height_map.get_gray(x as i64, y as i64 - 1, tile); diff --git a/crates/nodes/src/atomic/transformation.rs b/crates/nodes/src/atomic/transformation.rs index 2404979..3d4eabd 100644 --- a/crates/nodes/src/atomic/transformation.rs +++ b/crates/nodes/src/atomic/transformation.rs @@ -21,8 +21,9 @@ fn transformation(context: &CookContext) -> CookResult { let input = context.input(0).cloned().unwrap_or_else(|| Image::filled(context.w, context.h, Kind::Gray, [0.0; 4])); let offset = context.v2("offset"); let matrix = context.v4("matrix"); + const MIN_DETERMINANT: f32 = 1e-8; let determinant = matrix[0] * matrix[3] - matrix[1] * matrix[2]; - if !determinant.is_finite() || determinant.abs() < 1e-8 { + if !determinant.is_finite() || determinant.abs() < MIN_DETERMINANT { return Err("transform matrix is singular".into()); } @@ -78,7 +79,8 @@ fn nearest_mip(mut input: Image, matrix: [f32; 4], context: &CookContext) -> Ima let sum: u32 = pixels.iter().map(|pixel| (pixel[channel].clamp(0.0, 1.0) * maximum).round() as u32).sum(); ((sum + 2) / 4) as f32 / maximum } else { - pixels.iter().map(|pixel| pixel[channel]).sum::() * 0.25 + // Average in f64 so finite HDR texels cannot overflow the sum + (pixels.iter().map(|pixel| f64::from(pixel[channel])).sum::() * 0.25) as f32 } }) }); diff --git a/crates/nodes/src/atomic/warp.rs b/crates/nodes/src/atomic/warp.rs index f0a5d7f..ba9ae42 100644 --- a/crates/nodes/src/atomic/warp.rs +++ b/crates/nodes/src/atomic/warp.rs @@ -15,12 +15,12 @@ pub(super) fn definition() -> NodeDefinition { } fn warp(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); - let grad = context.gray_or(1, 0.0); - let k = context.f("intensity"); - Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| { + let image = context.any_or(0, Kind::Gray, [0.0; 4]); + let gradient = context.gray_or(1, 0.0); + let intensity = context.f("intensity"); + Ok(vec![Image::generate_uv(context.w, context.h, image.kind(), |u, v| { let (x, y) = ((u * context.w as f32) as i64, (v * context.h as f32) as i64); - let (dx, dy) = ops::slope(&grad, x, y, context.tile); - img.sample(u + dx * k, v + dy * k, context.tile) + let (dx, dy) = ops::slope(&gradient, x, y, context.tile); + image.sample(u + dx * intensity, v + dy * intensity, context.tile) })]) } diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 8380fd5..bfea4f8 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -37,7 +37,9 @@ fn every_native_function_executes_with_its_declared_ports() { let mut covered = BTreeSet::new(); for definition in FUNCTIONS { let name = definition.id; + assert!(covered.insert(name), "duplicate {name}"); + let mut graph = FunctionGraph::default(); let mut variables = BTreeMap::new(); let mut setting = default_value(name); @@ -131,11 +133,13 @@ fn branches_are_lazy_and_sequence_orders_side_effects() { let expected = graph.add_constant(Value::Int(17)); let undefined = graph.add("get_integer1", &[], Some(Value::Text("missing".into()))); graph.output = Some(graph.add("ifelse", &[condition, expected, undefined], None)); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17)); let set = graph.add("set", &[expected], Some(Value::Text("stored".into()))); let get = graph.add("get_integer1", &[], Some(Value::Text("stored".into()))); graph.output = Some(graph.add("sequence", &[set, get], None)); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17)); } @@ -153,18 +157,22 @@ fn time_and_tiling_variables_have_typed_defaults_and_host_overrides() { let expected = variables.get(name).unwrap_or(&default); let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; let program = compile(&graph, 0).unwrap(); + assert_eq!(program.evaluate(&context, &mut EvaluationState::default()).unwrap(), *expected); assert_eq!(program.evaluate_pixel(&context, &mut EvaluationState::default()).unwrap(), *expected); } assert!(evaluate(&graph, &BTreeMap::from([(name.into(), Value::Bool(false))])).unwrap_err().contains("wrong type")); + graph.output = Some(defined); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Bool(true)); } let mut graph = FunctionGraph::default(); graph.output = Some(graph.add("get_integer1", &[], Some(Value::Text("$tiling".into())))); let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: false, variables: &BTreeMap::new() }; + assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Int(0)); } @@ -180,10 +188,12 @@ fn loops_recompute_state_and_have_a_budget() { let add = graph.add("add", &[get, one], None); let body = graph.add("set", &[add], Some(Value::Text("counter".into()))); graph.output = Some(graph.add("while", &[init, condition, body], Some(Value::Int(-1)))); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3)); let condition = graph.add_constant(Value::Bool(false)); graph.output = Some(graph.add("while", &[zero, condition, one], Some(Value::Int(-1)))); + assert!(evaluate(&graph, &BTreeMap::new()).unwrap_err().contains("budget")); } @@ -195,9 +205,12 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() { previous = graph.add("passthrough", &[previous], None); } graph.output = Some(graph.add("abs", &[previous], None)); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1.0)); + graph.nodes[0].op = "passthrough".into(); graph.nodes[0].inputs = vec![Some(previous)]; + assert!(compile(&graph, 0).err().unwrap().contains("cycle")); let mut graph = FunctionGraph::constant(Value::Float(1.0)); @@ -206,6 +219,7 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() { previous = graph.add("add", &[previous, previous], None); } graph.output = Some(previous); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1_073_741_824.0)); } @@ -236,6 +250,7 @@ fn pixel_assignments_are_local_and_match_exported_evaluation() { let read_only = compile(&FunctionGraph::constant(Value::Float(0.5)), 7).unwrap(); let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &BTreeMap::new() }; + assert_eq!(read_only.evaluate_pixel(&context, &mut pixel_state).unwrap(), Value::Float(0.5)); assert!(pixel_state.variables().is_empty()); } @@ -253,6 +268,7 @@ fn pixel_random_seed_and_defined_variables_match_general_evaluation() { for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] { let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; let expected = program.evaluate(&context, &mut EvaluationState::default()).unwrap(); + assert_eq!(program.evaluate_pixel(&context, &mut state).unwrap(), expected); } } @@ -587,6 +603,7 @@ fn unconnected_ifelse_branches_use_the_value_type_not_the_condition() { node.type_code = declared_type; let selected = if condition_value { 1 } else { 2 }; let expected = if selected == missing { zero.clone() } else { value.clone() }; + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), expected); } } @@ -603,6 +620,7 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t let node = graph.nodes.last_mut().unwrap(); node.inputs = vec![None, Some(branch), None]; node.type_code = 0; + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(0.0)); for condition_value in [false, true] { @@ -612,6 +630,7 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t let node = graph.nodes.last_mut().unwrap(); node.inputs = vec![Some(condition), None, None]; node.type_code = 512; + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float2([0.0; 2])); } } diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index 55ece2a..7fbc4f1 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -6,34 +6,40 @@ use rayon::prelude::*; /// Gaussian blur with standard deviation `sigma` (pixels). Small sigmas use a sampled kernel; /// larger ones three box passes (a close Gaussian approximation in O(1) per pixel). -pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { - if sigma.is_nan() || sigma <= 0.05 || !sigma.is_finite() { - return img.clone(); +pub fn gaussian(image: &Image, sigma: f32, tile: bool) -> Image { + const MIN_SIGMA_PIXELS: f32 = 0.05; + const BOX_BLUR_MIN_SIGMA_PIXELS: f32 = 3.0; + const KERNEL_RADIUS_SIGMAS: f32 = 3.0; + + if sigma.is_nan() || sigma <= MIN_SIGMA_PIXELS || !sigma.is_finite() { + return image.clone(); } - let sigma = sigma.min(img.width().max(img.height()) as f32); - if sigma < 3.0 { - let r = (sigma * 3.0).ceil() as i64; - let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); - let s: f32 = k.iter().sum(); - let k: Vec = k.iter().map(|v| v / s).collect(); - let pass = |src: &Image, horizontal: bool| convolve_1d(src, &k, r, horizontal, tile); - return pass(&pass(img, true), false); + let sigma = sigma.min(image.width().max(image.height()) as f32); + if sigma < BOX_BLUR_MIN_SIGMA_PIXELS { + let radius = (sigma * KERNEL_RADIUS_SIGMAS).ceil() as i64; + let kernel: Vec = (-radius..=radius).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); + let kernel_sum: f32 = kernel.iter().sum(); + let kernel: Vec = kernel.iter().map(|v| v / kernel_sum).collect(); + let pass = |src: &Image, horizontal: bool| convolve_1d(src, &kernel, radius, horizontal, tile); + return pass(&pass(image, true), false); } // Box widths for three passes (Kovesi, "Fast almost-Gaussian filtering") - let n = 3.0f32; - let wl = ((12.0 * sigma * sigma / n + 1.0).sqrt()).floor() as i64; - let wl = if wl % 2 == 0 { wl - 1 } else { wl }; - let wu = wl + 2; - let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round() as i64; - let mut out = img.clone(); + let pass_count = 3.0f32; + let lower_width = ((12.0 * sigma * sigma / pass_count + 1.0).sqrt()).floor() as i64; + let lower_width = if lower_width % 2 == 0 { lower_width - 1 } else { lower_width }; + let upper_width = lower_width + 2; + let lower_passes = ((12.0 * sigma * sigma - pass_count * (lower_width * lower_width) as f32 - 4.0 * pass_count * lower_width as f32 - 3.0 * pass_count) + / (-4.0 * lower_width as f32 - 4.0)) + .round() as i64; + let mut output = image.clone(); for i in 0..3 { - let r = (if i < m { wl } else { wu } - 1) / 2; - out = box_1d(&box_1d(&out, r.max(0), true, tile), r.max(0), false, tile); + let radius = (if i < lower_passes { lower_width } else { upper_width } - 1) / 2; + output = box_1d(&box_1d(&output, radius.max(0), true, tile), radius.max(0), false, tile); } - out + output } /// The default limits, raised to admit `src`, so a pass over an image made with raised limits @@ -46,66 +52,73 @@ fn limits_for(src: &Image) -> Limits { limits } -fn convolve_1d(src: &Image, k: &[f32], r: i64, horizontal: bool, tile: bool) -> Image { - let c = src.channels(); +fn convolve_1d(src: &Image, kernel: &[f32], radius: i64, horizontal: bool, tile: bool) -> Image { + let channels = src.channels(); Image::try_generate(src.width(), src.height(), src.kind(), &limits_for(src), |x, y| { - let mut acc = [0.0f32; 4]; - for (i, kv) in k.iter().enumerate() { - let o = i as i64 - r; - let p = if horizontal { src.get(x as i64 + o, y as i64, tile) } else { src.get(x as i64, y as i64 + o, tile) }; - for ch in 0..c.clamp(1, 4) { - acc[ch] += p[ch] * kv; + let mut accumulator = [0.0f32; 4]; + for (i, weight) in kernel.iter().enumerate() { + let offset = i as i64 - radius; + let pixel = if horizontal { src.get(x as i64 + offset, y as i64, tile) } else { src.get(x as i64, y as i64 + offset, tile) }; + for channel in 0..channels.clamp(1, 4) { + accumulator[channel] += pixel[channel] * weight; } } - if c == 1 { [acc[0], 0.0, 0.0, 0.0] } else { acc } + if channels == 1 { [accumulator[0], 0.0, 0.0, 0.0] } else { accumulator } }) .unwrap_or_else(|_| src.clone()) } -/// One running-sum box pass of radius `r`. -fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { - if r <= 0 { +/// One running-sum box pass of radius `radius`. +fn box_1d(src: &Image, radius: i64, horizontal: bool, tile: bool) -> Image { + if radius <= 0 { return src.clone(); } let (w, h) = (src.width() as usize, src.height() as usize); - let c = src.channels(); - let inv = 1.0 / (2 * r + 1) as f64; - let mut data = vec![0.0f32; w * h * c]; + let channels = src.channels(); + let inverse_width = 1.0 / (2 * radius + 1) as f64; + let mut data = vec![0.0f32; w * h * channels]; let line_len = if horizontal { w } else { h }; let lines = if horizontal { h } else { w }; - // The running sum is kept in f64, so a window of finite values near `f32::MAX` does not overflow. - let get = |line: usize, i: i64, ch: usize| -> f64 { + + // f64 keeps finite HDR windows from overflowing the running sum + let get = |line: usize, i: i64, channel: usize| -> f64 { let n = line_len as i64; let i = if tile { i.rem_euclid(n) } else { i.clamp(0, n - 1) } as usize; let (x, y) = if horizontal { (i, line) } else { (line, i) }; - f64::from(src.data().get((y * w + x) * c + ch).copied().unwrap_or(0.0)) + f64::from(src.data().get((y * w + x) * channels + channel).copied().unwrap_or(0.0)) }; - let results: Vec> = (0..lines) - .into_par_iter() - .map(|line| { - let mut out = vec![0.0f32; line_len * c]; - for ch in 0..c { - let mut sum: f64 = (-r..=r).map(|i| get(line, i, ch)).sum(); - for i in 0..line_len { - out[i * c + ch] = (sum * inv) as f32; - sum += get(line, i as i64 + r + 1, ch) - get(line, i as i64 - r, ch); - } + let fill_line = |line: usize, output: &mut [f32]| { + for channel in 0..channels { + let mut sum: f64 = (-radius..=radius).map(|i| get(line, i, channel)).sum(); + for i in 0..line_len { + output[i * channels + channel] = (sum * inverse_width) as f32; + sum += get(line, i as i64 + radius + 1, channel) - get(line, i as i64 - radius, channel); } + } + }; - out - }) - .collect(); - for (line, vals) in results.iter().enumerate() { - for i in 0..line_len { - let (x, y) = if horizontal { (i, line) } else { (line, i) }; - let dst = (y * w + x) * c; - data[dst..dst + c].copy_from_slice(&vals[i * c..i * c + c]); + if horizontal { + data.par_chunks_mut(w * channels).enumerate().for_each(|(line, output)| fill_line(line, output)); + } else { + let results: Vec> = (0..lines) + .into_par_iter() + .map(|line| { + let mut output = vec![0.0f32; line_len * channels]; + fill_line(line, &mut output); + output + }) + .collect(); + for (line, values) in results.into_iter().enumerate() { + for i in 0..line_len { + let destination = (i * w + line) * channels; + data[destination..destination + channels].copy_from_slice(&values[i * channels..i * channels + channels]); + } } } - // `data` has the size and kind of `src`, which is a valid image. + // A valid source has matching dimensions and data length Image::from_data(src.width(), src.height(), src.kind(), data, &limits_for(src)).unwrap_or_else(|_| src.clone()) } @@ -417,9 +430,11 @@ mod tests { let img = Image::gray(32, 32, |x, y| if (x / 4 + y / 4) % 2 == 0 { 1.0 } else { 0.0 }); for s in [1.0, 6.0] { let b = gaussian(&img, s, true); + assert!((b.mean()[0] - img.mean()[0]).abs() < 1e-3, "sigma {s}"); } let flat = gaussian(&Image::filled(8, 8, Kind::Color, [0.2, 0.4, 0.6, 1.0]), 4.0, false); + assert!((flat.get(3, 3, false)[1] - 0.4).abs() < 1e-5); } @@ -427,8 +442,10 @@ mod tests { fn box_blur_of_large_hdr_values_stays_finite() { let value = 0.75 * f32::MAX; let blurred = gaussian(&Image::filled(16, 4, Kind::Gray, [value; 4]), 5.0, true); + for x in 0..16 { let v = blurred.get(x, 1, false)[0]; + assert!(v.is_finite() && (v / value - 1.0).abs() < 1e-5, "pixel {x} is {v}"); } } @@ -442,8 +459,10 @@ mod tests { let Ok(img) = Image::from_data(w, 1, Kind::Gray, values, &limits) else { panic!("a {w}x1 image fits the raised limits"); }; + for sigma in [1.0, 5.0] { let blurred = gaussian(&img, sigma, false); + assert_eq!((blurred.width(), blurred.height()), (w, 1), "sigma {sigma}"); assert_ne!(blurred.data(), img.data(), "sigma {sigma} left the pixels unchanged"); } diff --git a/crates/nodes/src/pattern/raster.rs b/crates/nodes/src/pattern/raster.rs index 8365214..7827c60 100644 --- a/crates/nodes/src/pattern/raster.rs +++ b/crates/nodes/src/pattern/raster.rs @@ -5,13 +5,15 @@ use super::{pattern_stamp::PatternStamp, region::Region, shape}; use crate::CookContext; const MAX_SAMPLES: u64 = 256_000_000; +const MAX_STAMP_COPIES: u64 = 1_048_576; +const MIN_STAMP_SIZE: f32 = 1e-8; pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: u32) -> Result { let (width, height) = craft_texture::clamp_size(context.w, context.h); let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; - let background = + let mut background = context.input(0).map(|image| image.resize(width, height, context.tile)).unwrap_or_else(|| Image::filled(width, height, kind, context.v4("background"))); - let background = if kind == Kind::Gray { background.to_gray() } else { background.to_color() }; + background = if kind == Kind::Gray { background.to_gray() } else { background.to_color() }; if stamps.is_empty() { return Ok(background); } @@ -20,11 +22,12 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: let opacity = context.f("opacity").max(0.0); let weights = depth_weights(context.f("roughness"), max_depth)?; let integer_sampling = background.integer_sampling(); - let data = Arc::clone(background.shared_data()); + let mut data = Arc::clone(background.shared_data()); drop(background); - let mut pixels = Arc::unwrap_or_clone(data); + + let pixels = Arc::make_mut(&mut data); let mut budget = MAX_SAMPLES; - let mut copies_left = 1_048_576_u64; + let mut copies_left = MAX_STAMP_COPIES; let render_region = Region::new(context.v4("render_region"))?; let period = if context.tile { Region::new(context.v4("tiling_region"))?.period() } else { [1.0; 2] }; @@ -33,7 +36,7 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: return Err("pattern parameters must be finite".into()); } - if stamp.size.iter().any(|size| size.abs() < 1e-8) { + if stamp.size.iter().any(|size| size.abs() < MIN_STAMP_SIZE) { continue; } @@ -123,11 +126,11 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: } } - Image::from_data(width, height, kind, pixels, &Limits::default()).map(|image| image.with_integer_sampling(integer_sampling)).map_err(|e| e.to_string()) + Image::from_data(width, height, kind, data, &Limits::default()).map(|image| image.with_integer_sampling(integer_sampling)).map_err(|e| e.to_string()) } fn depth_weights(roughness: f32, max_depth: u32) -> Result, String> { - // Traversal is bounded by the 4096-node acyclic pattern graph. Keep this allocation bounded too + // Match the depth allocation cap to the 4096-node acyclic traversal limit if max_depth >= 4096 || !roughness.is_finite() || roughness < 0.0 { return Err("pattern roughness must be finite and nonnegative, with depth below 4096".into()); } diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index 7c46905..e274174 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -67,12 +67,17 @@ fn iterate_sets_number_and_switch_selects_one_child() { function.output = Some(function.add("get_float1", &[], Some(Value::Text("$number".into())))); graph.nodes[2].parameters.insert("opacity".into(), Value::Function(Box::new(function))); let image = cook(graph.clone()).unwrap().remove(0); + assert!((image.mean()[0] - 3.0).abs() < 1e-6); + let dot = graph.add(PatternNodeKind::Dot).unwrap(); graph.nodes[1].children[0] = Some(dot); graph.nodes[3].children[0] = Some(quadrant); + assert_eq!(cook(graph.clone()).unwrap()[0].data(), image.data()); + graph.nodes[1].parameters.insert("switch".into(), Value::Bool(true)); + assert_eq!(cook(graph).unwrap()[0].mean()[0], 0.0); } diff --git a/crates/nodes/src/tests.rs b/crates/nodes/src/tests.rs index c86f8e5..7cca901 100644 --- a/crates/nodes/src/tests.rs +++ b/crates/nodes/src/tests.rs @@ -69,11 +69,14 @@ fn every_node_cooks() { let result = cook(definition, &inputs, 32); if definition.id == "pixel_processor" { assert_eq!(result.unwrap_err(), "function has no result node"); + continue; } let outputs = result.unwrap_or_else(|error| panic!("{}: {error}", definition.id)); + assert_eq!(outputs.len(), definition.outputs.len().max(1), "{}", definition.id); + for image in &outputs { assert_eq!((image.width(), image.height()), (32, 32), "{}", definition.id); assert!(image.data().iter().all(|value| value.is_finite()), "{} produced a non-finite value", definition.id); @@ -180,6 +183,7 @@ fn dynamic_gradient_preserves_the_gradient_image_type() { let source = Image::filled(4, 4, Kind::Gray, [0.5; 4]); let gradient = Image::filled(4, 4, kind, [0.25, 0.5, 0.75, 1.0]); let result = cook(definition, &[Some(source), Some(gradient.clone())], 16).unwrap(); + assert_eq!(result[0].kind(), kind); assert_eq!(result[0].get(0, 0, false), gradient.get(0, 0, false)); } @@ -199,6 +203,7 @@ fn an_oversized_transformation_covers_the_whole_input() { let ramp = Image::gray(8192, 1, |x, _| x as f32 / 8191.0); let out = cook_sized(find("transformation").unwrap(), &[Some(ramp)], 16384, 1, &|_| None).unwrap(); let last = out[0].get(8191, 0, false)[0]; + assert!(last > 0.99, "the last pixel reads the ramp at {last}"); } @@ -207,20 +212,52 @@ fn an_oversized_transformation_covers_the_whole_input() { fn transformation_resamples_extreme_neighbors_to_finite_values() { let extremes = Image::gray(2, 1, |x, _| if x == 0 { f32::MAX } else { -f32::MAX }); let out = cook_sized(find("transformation").unwrap(), &[Some(extremes)], 4, 1, &|_| None).unwrap(); + for x in 0..4 { let value = out[0].get(x, 0, false)[0]; + assert!(value.is_finite(), "pixel {x} is {value}"); } } +#[test] +fn nearest_transformation_mips_preserve_finite_hdr_constants() { + let definition = find("transformation").unwrap(); + let parameters = resolve_params(definition, &BTreeMap::from([("filtering".into(), Value::Enum(1))])); + let variables = BTreeMap::new(); + let value = 0.75 * f32::MAX; + + for kind in [Kind::Gray, Kind::Color] { + let inputs = [Some(Image::filled(16, 16, kind, [value; 4]))]; + let context = CookContext { + format: materialcraft_core::OutputFormat::F32, + w: 4, + h: 4, + seed: 7, + tile: false, + inputs: &inputs, + params: ¶meters, + resource: &|_| None, + vars: &variables, + }; + + let output = (definition.cook)(&context).unwrap().remove(0); + + assert_eq!((output.width(), output.height(), output.kind()), (4, 4, kind)); + assert!(output.data().iter().all(|pixel| *pixel == value), "{:?}", output.data()); + } +} + /// A repeated input offset far past its edge keeps the offset's phase: an offset near 2^31 lands on /// the same place as an offset of zero, halfway between the last and the first column. #[test] fn directional_warp_repeats_a_far_offset_with_its_phase() { let stripes = Image::gray(3, 3, |x, _| [0.0, 1.0, 4.0][x as usize]); - // Intensity 10 scales the map by 10 / 256, so this map moves every pixel by about 2^31. + + // Intensity 10 scales the map by 10 / 256, moving each pixel by about 2^31 let far = Image::filled(3, 3, Kind::Gray, [2_147_483_648.0 * 25.6; 4]); let out = cook(find("directional_warp").unwrap(), &[Some(stripes), Some(far)], 3).unwrap(); + for x in 0..3 { assert_eq!(out[0].get_gray(x, 1, false), 2.0, "pixel {x}"); } @@ -232,6 +269,7 @@ fn bitmap_shrinks_large_hdr_values_without_overflow() { let hdr = |_: &str| Some(Image::filled(2, 2, Kind::Color, [0.75 * f32::MAX, 0.75 * f32::MAX, 0.75 * f32::MAX, 1.0])); let out = cook_sized(find("bitmap").unwrap(), &[], 1, 1, &hdr).unwrap(); let pixel = out[0].get(0, 0, false); + assert!(pixel.iter().all(|value| value.is_finite()), "{pixel:?}"); assert!((pixel[0] / (0.75 * f32::MAX) - 1.0).abs() < 1e-6, "{pixel:?}"); } diff --git a/crates/nodes/tests/distance.rs b/crates/nodes/tests/distance.rs index 538bb37..642d6f2 100644 --- a/crates/nodes/tests/distance.rs +++ b/crates/nodes/tests/distance.rs @@ -55,11 +55,14 @@ fn distance_handles_empty_full_masks_and_no_source() { let empty = Image::filled(7, 5, Kind::Gray, [0.0; 4]); let full = Image::filled(7, 5, Kind::Gray, [1.0; 4]); let source = Image::generate(7, 5, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 5.0, 0.4, 0.7]); + assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data().iter().all(|&v| v == 0.0)); assert_eq!(cook(full, Some(source), tile, true, 256.0).get(3, 2, false), [3.0 / 7.0, 2.0 / 5.0, 0.4, 0.7]); assert!(cook(empty, None, tile, true, 256.0).data().iter().all(|&v| v == 0.0)); + let mask = Image::gray(7, 5, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 }); let ramp = cook(mask, None, tile, false, 512.0 / 7.0); + assert_eq!(ramp.get_gray(0, 0, false), 1.0); assert_eq!(ramp.get_gray(1, 0, false), 0.5); assert_eq!(ramp.get_gray(3, 0, false), 0.0); diff --git a/crates/nodes/tests/parity_unconnected.rs b/crates/nodes/tests/parity_unconnected.rs index 9be1b93..bb24cb8 100644 --- a/crates/nodes/tests/parity_unconnected.rs +++ b/crates/nodes/tests/parity_unconnected.rs @@ -22,6 +22,7 @@ fn absent_textures_have_zero_pixels_and_expected_kinds() { 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}"); diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index b8a3ae3..25c88ff 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -94,8 +94,9 @@ impl Scene { mesh = mesh.subdivided(); } - // Pre-filtered so detail finer than the mesh (left to the normal map) does not spike the silhouette - let height = height.resize(height.width().min(512), height.height().min(512), true); + // Filter detail finer than the mesh to prevent silhouette spikes + const MAX_HEIGHT_MAP_SIDE: u32 = 512; + let height = height.resize(height.width().min(MAX_HEIGHT_MAP_SIDE), height.height().min(MAX_HEIGHT_MAP_SIDE), true); let level = if displacement.level.is_finite() { displacement.level.clamp(0.0, 1.0) } else { 0.0 }; let depth = if displacement.depth.is_finite() { displacement.depth } else { 0.0 }; let tiling = if displacement.tiling.is_finite() { displacement.tiling.max(0.01) } else { 1.0 }; @@ -495,52 +496,52 @@ pub fn render(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, w: u32 /// [`render`] that gives up once `cancel` is set (rows not yet started are skipped) and then /// returns `None`: a frame the viewer no longer needs (the camera moved, the view was resized) /// stops holding the CPU. -pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, w: u32, h: u32, cancel: &AtomicBool) -> Option> { +pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, settings: &Settings, w: u32, h: u32, cancel: &AtomicBool) -> Option> { let (w, h) = (w.clamp(1, 4096), h.clamp(1, 4096)); - let cam = camera(scene, s); + let camera = camera(scene, settings); let aspect = w as f32 / h as f32; - let ss = s.supersample.clamp(1, 4); - let k = 2f32.powf(s.exposure); - let bg_env = light.specular.get(3).or(light.specular.last()); + let samples_per_axis = settings.supersample.clamp(1, 4); + let exposure_scale = 2f32.powf(settings.exposure); + let background_environment = light.specular.get(3).or(light.specular.last()); // Key light from the camera's upper left, a little in front of the subject - let fwd = cam.ray(Vec2::ZERO, aspect).dir; - let right = fwd.cross(Vec3::Y).normalize_or(Vec3::X); - let key = (right * -0.6 + right.cross(fwd) * 0.75 - fwd * 0.5).normalize_or_zero(); - let mut out = vec![0u8; (w * h * 4) as usize]; - out.par_chunks_mut(w as usize * 4).enumerate().for_each(|(y, row)| { + let forward = camera.ray(Vec2::ZERO, aspect).dir; + let right = forward.cross(Vec3::Y).normalize_or(Vec3::X); + let key = (right * -0.6 + right.cross(forward) * 0.75 - forward * 0.5).normalize_or_zero(); + let mut output = vec![0u8; (w * h * 4) as usize]; + output.par_chunks_mut(w as usize * 4).enumerate().for_each(|(y, row)| { if cancel.load(Ordering::Relaxed) { return; } for x in 0..w as usize { - let mut acc = Vec3::ZERO; - for sy in 0..ss { - for sx in 0..ss { - let px = (x as f32 + (sx as f32 + 0.5) / ss as f32) / w as f32 * 2.0 - 1.0; - let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / ss as f32) / h as f32 * 2.0; - let ray = cam.ray(Vec2::new(px, py), aspect); - let bg = backdrop(Vec2::new(px, py)); - let p = Px { key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) }; - let miss = match (s.show_env, bg_env) { - (true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k, - _ => bg, + let mut accumulated = Vec3::ZERO; + for sy in 0..samples_per_axis { + for sx in 0..samples_per_axis { + let px = (x as f32 + (sx as f32 + 0.5) / samples_per_axis as f32) / w as f32 * 2.0 - 1.0; + let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / samples_per_axis as f32) / h as f32 * 2.0; + let ray = camera.ray(Vec2::new(px, py), aspect); + let background = backdrop(Vec2::new(px, py)); + let p = Px { key, jitter: jitter(x as u32 * samples_per_axis + sx, y as u32 * samples_per_axis + sy) }; + let miss = match (settings.show_env, background_environment) { + (true, Some(e)) => e.sample(rotate_y(ray.dir, -settings.env_rotation)) * exposure_scale, + _ => background, }; - acc += if s.alpha_view { + accumulated += if settings.alpha_view { // Display values: the alpha as is, the background tone mapped - match shade(scene, maps, light, s, ray.origin, ray.dir, &p) { + match shade(scene, maps, light, settings, ray.origin, ray.dir, &p) { Some(h) => h.color, None => miss.map(|v| linear_to_srgb(aces(v))), } } else { - trace(scene, maps, light, s, ray.origin, ray.dir, &p, k, miss) + trace(scene, maps, light, settings, ray.origin, ray.dir, &p, exposure_scale, miss) }; } } - let c = acc / (ss * ss) as f32; + let c = accumulated / (samples_per_axis * samples_per_axis) as f32; let q = |v: f32| { - let d = if s.alpha_view { v } else { linear_to_srgb(aces(v)) }; + let d = if settings.alpha_view { v } else { linear_to_srgb(aces(v)) }; (d.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 }; if let Some(px) = row.get_mut(x * 4..x * 4 + 4) { @@ -548,7 +549,7 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett } } }); - if cancel.load(Ordering::Relaxed) { None } else { Some(out) } + if cancel.load(Ordering::Relaxed) { None } else { Some(output) } } #[cfg(test)] diff --git a/crates/ui-egui/src/export/export_tests.rs b/crates/ui-egui/src/export/export_tests.rs index e18d1f6..9dd5f5b 100644 --- a/crates/ui-egui/src/export/export_tests.rs +++ b/crates/ui-egui/src/export/export_tests.rs @@ -77,8 +77,11 @@ fn batch_writes_every_material_graph_at_the_output_size() { assert!(export(&mut app, &settings)); assert_eq!(files(&directory), ["New_graph_base_color.png", "New_graph_height.png", "Second_mask.png"]); + let image = materialcraft_engine::formats::decode(&std::fs::read(directory.join("Second_mask.png")).unwrap(), true).unwrap(); + assert_eq!((image.width(), image.height()), (64, 32)); + let _ = std::fs::remove_dir_all(directory); } diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 4c533c5..9d607d8 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -50,9 +50,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let theme = Tokens::get(ui.ctx()); - let ctx = ui.ctx().clone(); - let (rect, resp) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Node graph"); + let context = ui.ctx().clone(); + let (rect, response) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Node graph"); app.graph.view = rect; if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) { app.ui.frame_all = false; @@ -69,7 +69,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { camera.zoom_from_input(ui, rect); app.ui.graph_camera = camera.state(); super::grid::paint(&painter, &camera, rect); - let pointer = ctx.input(|input| input.pointer.hover_pos()); + let pointer = context.input(|input| input.pointer.hover_pos()); let show_thumbnails = app.ui.prefs.thumbnails; let Ok(graph) = app.session.graph() else { return }; @@ -82,7 +82,6 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { }; // Layout every node and its ports - let mut layouts: Vec = Vec::with_capacity(graph.nodes.len()); for node in &graph.nodes { let (ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied()); @@ -211,24 +210,29 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { dot_grabs.push(grab); } - let resp = ui.interact(grab, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Button, &node_label(node)); + let response = ui.interact(grab, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Button, &node_label(node)); if node.def == "dot" { node_card::paint_dot(&painter, screen_rect, if selected { theme.accent } else { Color32::from_gray(0xb4) }); } else { node_card::paint(&painter, screen_rect, camera.zoom, &node_label(node), header_color(&node.def)); let header = node_card::header(screen_rect, camera.zoom); let body = node_card::body(screen_rect, camera.zoom); - if let Some(r0) = result - && let Some(img) = r0.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image) + if let Some(node_result) = result + && let Some(image) = node_result.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image) && show_thumbnails && !app.graph.thumbnails_cleared { let side = body.width().min(body.height()) - 6.0 * camera.zoom; - let tr_ = Rect::from_center_size(body.center(), vec2(side, side)); - node_card::paint_well(&painter, tr_.expand(camera.zoom), camera.zoom); - let tex = app.thumbs.node(&ctx, r0.key, 0, img); - painter.image(tex, tr_, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), if node.disabled { Color32::from_gray(90) } else { Color32::WHITE }); + let thumbnail_rect = Rect::from_center_size(body.center(), vec2(side, side)); + node_card::paint_well(&painter, thumbnail_rect.expand(camera.zoom), camera.zoom); + let texture = app.thumbs.node(&context, node_result.key, 0, image); + painter.image( + texture, + thumbnail_rect, + Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), + if node.disabled { Color32::from_gray(90) } else { Color32::WHITE }, + ); } else if let Some(value) = result.and_then(|result| result.outputs.first()).and_then(materialcraft_engine::eval::NodeOutput::as_value) { node_card::paint_well(&painter, body.shrink(4.0 * camera.zoom), camera.zoom); node_card::paint_symbol(&painter, body, camera.zoom, &super::value_text::value_text(value), theme.text_strong); @@ -240,25 +244,25 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // Footer: size and format let footer = Rect::from_min_max(pos2(screen_rect.left(), body.bottom()), screen_rect.max); - if let Some(img) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) { + if let Some(image) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) { let bits = result.map_or(graph.format.bits(), |result| result.base.format.bits()); - let format = format!("{}{bits}", if img.is_gray() { "L" } else { "C" }); - let txt = if let Some(limit) = app.session.preview_size { + let format = format!("{}{bits}", if image.is_gray() { "L" } else { "C" }); + let label_text = if let Some(limit) = app.session.preview_size { let [width, height] = graph.size_px(); - resp.clone().on_hover_text(format!( + response.clone().on_hover_text(format!( "{} x {} ({bits}bpc)\n{}: {width} x {height}\n{}: {limit} px\n{}", - img.width(), - img.height(), + image.width(), + image.height(), tr("Parent size"), tr("Preview limit"), tr("Change Preview size while editing in Edit > Preferences. Exports use each node's configured output size.") )); - format!("{}x{} {}", img.width(), img.height(), tr("Preview")) + format!("{}x{} {}", image.width(), image.height(), tr("Preview")) } else { - format!("{}x{} - {format}", img.width(), img.height()) + format!("{}x{} - {format}", image.width(), image.height()) }; - painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), theme.text_dim); + painter.text(footer.center(), Align2::CENTER_CENTER, label_text, small.clone(), theme.text_dim); } if node.def == "output" { painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::SIGN_OUT, small.clone(), Color32::WHITE); @@ -267,7 +271,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { Stroke::new(2.0, Color32::from_rgb(0xff, 0x30, 0xd0)) } else if selected { Stroke::new(2.0, theme.accent) - } else if resp.hovered() { + } else if response.hovered() { Stroke::new(1.0, Color32::from_gray(0x90)) } else { Stroke::new(1.0, Color32::from_gray(0x10)) @@ -278,11 +282,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { painter.line_segment([screen_rect.left_top(), screen_rect.right_bottom()], Stroke::new(1.5, theme.danger)); } if let Some(e) = error { - resp.clone().on_hover_text(e); + response.clone().on_hover_text(e); } } - node_responses.push((node.id, resp)); + node_responses.push((node.id, response)); } let comment_hits = super::annotation_canvas::comments(app, ui, &graph.comments, &camera); @@ -318,11 +322,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // A wire under a comment is not hit let wire_hover = wire_hover.filter(|_| !pointer.is_some_and(|p| comment_hits.iter().any(|(_, r)| r.contains(p)))); if wire_hover.is_some() { - ctx.set_cursor_icon(egui::CursorIcon::PointingHand); + context.set_cursor_icon(egui::CursorIcon::PointingHand); } app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); - super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, &pin_hits, port_hover, wire_hover); + super::input::handle(app, ui, &response, rect, &camera, &node_responses, &frame_hits, &comment_hits, &pin_hits, port_hover, wire_hover); app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); // GraphDrag previews diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs index bdd4290..707270b 100644 --- a/crates/ui-egui/src/levels_editor.rs +++ b/crates/ui-egui/src/levels_editor.rs @@ -15,20 +15,20 @@ pub const BINS: usize = 256; const MIN_SPAN: f32 = 0.004; /// Histograms of an image's values in 0..1, clamped: one for a gray image, else R, G and B -pub fn histogram(img: &Image) -> Vec<[u32; BINS]> { - let channels = if img.kind() == Kind::Gray { 1 } else { 3 }; - let stride = img.channels(); - let mut h = vec![[0u32; BINS]; channels]; - for px in img.data().chunks(stride) { - for (c, bins) in h.iter_mut().enumerate() { - let v = px.get(c).copied().unwrap_or(0.0); - let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - if let Some(b) = bins.get_mut(((v * (BINS - 1) as f32).round() as usize).min(BINS - 1)) { - *b = b.saturating_add(1); +pub fn histogram(image: &Image) -> Vec<[u32; BINS]> { + let channels = if image.kind() == Kind::Gray { 1 } else { 3 }; + let stride = image.channels(); + let mut histograms = vec![[0u32; BINS]; channels]; + for pixel in image.data().chunks(stride) { + for (channel, bins) in histograms.iter_mut().enumerate() { + let value = pixel.get(channel).copied().unwrap_or(0.0); + let value = if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; + if let Some(bin) = bins.get_mut(((value * (BINS - 1) as f32).round() as usize).min(BINS - 1)) { + *bin = bin.saturating_add(1); } } } - h + histograms } /// The bar height scale: the tallest bin away from pure black and white (masks pile up there and would flatten everything else), at least one diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index ad923de..81e7c90 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -38,27 +38,34 @@ pub fn title(app: &MaterialCraftApp) -> String { format!("{} - {}", name.unwrap_or_default(), tr("2D View")) } -fn rgba8(img: &Image, channel: &str) -> Vec { - let base = img.to_rgba8_display(); - let pick = match channel { +fn rgba8(image: &Image, channel: &str) -> Vec { + let mut pixels = image.to_rgba8_display(); + let selected = match channel { "r" => Some(0), "g" => Some(1), "b" => Some(2), "a" => Some(3), _ => None, }; - match pick { - Some(k) if img.kind() == Kind::Color => base.chunks(4).flat_map(|p| [p[k], p[k], p[k], 255]).collect(), - _ => base, + + if let Some(channel) = selected + && image.kind() == Kind::Color + { + for pixel in pixels.as_chunks_mut::<4>().0 { + let value = pixel[channel]; + pixel.copy_from_slice(&[value, value, value, u8::MAX]); + } } + + pixels } pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let ctx = ui.ctx().clone(); + let theme = Tokens::get(ui.ctx()); + let context = ui.ctx().clone(); // Toolbar - egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { + egui::Frame::NONE.fill(theme.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { ui.horizontal(|ui| { crate::preview_resolution::show(app, ui); for (c, label) in [("rgba", "RGBA"), ("r", "R"), ("g", "G"), ("b", "B"), ("a", "A")] { @@ -87,90 +94,90 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); }); - let Some((id, img)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else { - let (r, resp) = ui.allocate_exact_size(ui.available_size(), Sense::hover()); - crate::widgets::name(&resp, egui::Role::Image, "2D view"); - ui.painter().rect_filled(r, 0.0, tk.viewport); - ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), tk.viewport_text); + let Some((id, image)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else { + let (r, response) = ui.allocate_exact_size(ui.available_size(), Sense::hover()); + crate::widgets::name(&response, egui::Role::Image, "2D view"); + ui.painter().rect_filled(r, 0.0, theme.viewport); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), theme.viewport_text); return; }; - let texture_limit = ctx.input(|i| i.max_texture_side).max(1); + let texture_limit = context.input(|i| i.max_texture_side).max(1); let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key) ^ (texture_limit as u64).rotate_left(32) - ^ (img.width() as u64).rotate_left(16) - ^ img.height() as u64 + ^ (image.width() as u64).rotate_left(16) + ^ image.height() as u64 ^ (app.session.view2d.port as u64).wrapping_mul(0x9e37) ^ (app.session.view2d.channel.len() as u64 * 31) ^ app.session.view2d.channel.bytes().next().unwrap_or(0) as u64; if app.view2d.tex.as_ref().is_none_or(|(k, _)| *k != key) { - let px = rgba8(&img, &app.session.view2d.channel); + let pixels = rgba8(&image, &app.session.view2d.channel); // Keep source pixels for readout/screenshots, but respect the renderer's upload limit - let ci = if img.width().max(img.height()) as usize > texture_limit { - let scale = texture_limit as f64 / f64::from(img.width().max(img.height())); + let color_image = if image.width().max(image.height()) as usize > texture_limit { + let scale = texture_limit as f64 / f64::from(image.width().max(image.height())); let display = - img.resize((f64::from(img.width()) * scale).floor().max(1.0) as u32, (f64::from(img.height()) * scale).floor().max(1.0) as u32, false); + image.resize((f64::from(image.width()) * scale).floor().max(1.0) as u32, (f64::from(image.height()) * scale).floor().max(1.0) as u32, false); ColorImage::from_rgba_unmultiplied([display.width() as usize, display.height() as usize], &rgba8(&display, &app.session.view2d.channel)) } else { - ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], &px) + ColorImage::from_rgba_unmultiplied([image.width() as usize, image.height() as usize], &pixels) }; - app.view2d.tex = Some((key, ctx.load_texture("view2d", ci, TextureOptions::NEAREST))); - app.view2d.shown = Some((img.width(), img.height(), px)); + app.view2d.tex = Some((key, context.load_texture("view2d", color_image, TextureOptions::NEAREST))); + app.view2d.shown = Some((image.width(), image.height(), pixels)); } - let avail = ui.available_size(); - let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 20.0).max(40.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Image, "2D view"); + let available = ui.available_size(); + let (rect, response) = ui.allocate_exact_size(vec2(available.x, (available.y - 20.0).max(40.0)), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Image, "2D view"); let p = ui.painter_at(rect); - p.rect_filled(rect, 0.0, tk.viewport); + p.rect_filled(rect, 0.0, theme.viewport); // Camera: fit, wheel zoom around the pointer, drag to pan app.ui.image_camera = app.ui.image_camera.sanitized(); - let cam = &mut app.ui.image_camera; + let camera = &mut app.ui.image_camera; let tiles = if app.session.view2d.tiled { 3.0 } else { 1.0 }; - let fit_zoom = ((rect.width() - 16.0) / (img.width() as f32 * tiles)).min((rect.height() - 16.0) / (img.height() as f32 * tiles)).max(0.01); - if cam.fit { - cam.zoom = fit_zoom; - cam.offset = [0.0, 0.0]; + let fit_zoom = ((rect.width() - 16.0) / (image.width() as f32 * tiles)).min((rect.height() - 16.0) / (image.height() as f32 * tiles)).max(0.01); + if camera.fit { + camera.zoom = fit_zoom; + camera.offset = [0.0, 0.0]; } - if resp.hovered() { + if response.hovered() { let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll.abs() > 0.0 { - cam.fit = false; - let old = cam.zoom; - cam.zoom = (cam.zoom * (scroll * 0.003).exp()).clamp(0.02, 64.0); - if let Some(ptr) = resp.hover_pos() { - let c = rect.center() + vec2(cam.offset[0], cam.offset[1]); + camera.fit = false; + let old = camera.zoom; + camera.zoom = (camera.zoom * (scroll * 0.003).exp()).clamp(0.02, 64.0); + if let Some(ptr) = response.hover_pos() { + let c = rect.center() + vec2(camera.offset[0], camera.offset[1]); let d = ptr - c; - let k = cam.zoom / old; - cam.offset = [cam.offset[0] - d.x * (k - 1.0), cam.offset[1] - d.y * (k - 1.0)]; + let k = camera.zoom / old; + camera.offset = [camera.offset[0] - d.x * (k - 1.0), camera.offset[1] - d.y * (k - 1.0)]; } } } - if resp.dragged() { - cam.fit = false; - let d = resp.drag_delta(); - cam.offset = [cam.offset[0] + d.x, cam.offset[1] + d.y]; + if response.dragged() { + camera.fit = false; + let d = response.drag_delta(); + camera.offset = [camera.offset[0] + d.x, camera.offset[1] + d.y]; } - let size = vec2(img.width() as f32, img.height() as f32) * cam.zoom; - let center = rect.center() + vec2(cam.offset[0], cam.offset[1]); + let size = vec2(image.width() as f32, image.height() as f32) * camera.zoom; + let center = rect.center() + vec2(camera.offset[0], camera.offset[1]); let full = Rect::from_center_size(center, size * tiles); // A checker behind transparent images - if img.kind() == Kind::Color && app.session.view2d.channel == "rgba" { + if image.kind() == Kind::Color && app.session.view2d.channel == "rgba" { let cell = 8.0; - let vis = full.intersect(rect); - let mut y = vis.top(); + let visible = full.intersect(rect); + let mut y = visible.top(); let mut row = 0; - while y < vis.bottom() { - let mut x = vis.left() + if row % 2 == 0 { 0.0 } else { cell }; - while x < vis.right() { - p.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell, cell)).intersect(vis), 0.0, Color32::from_gray(0x55)); + while y < visible.bottom() { + let mut x = visible.left() + if row % 2 == 0 { 0.0 } else { cell }; + while x < visible.right() { + p.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell, cell)).intersect(visible), 0.0, Color32::from_gray(0x55)); x += cell * 2.0; } y += cell; @@ -189,27 +196,35 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } if app.session.view2d.histogram { - let single = img.is_gray() || app.session.view2d.channel != "rgba"; + let single = image.is_gray() || app.session.view2d.channel != "rgba"; draw_histogram(&mut app.view2d, &p, rect, key, single); } // Info line: size, format, zoom and the pixel under the pointer let info = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 20.0)); let bits = app.session.cooked.nodes.get(&id).map_or("16", |result| result.base.format.bits()); - let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.width(), img.height(), if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0); - if let Some(ptr) = resp.hover_pos() { - let local = (ptr - (center - size * 0.5)) / cam.zoom; + let mut text = + format!("{} x {} ({}, {}bpc) {:.0}%", image.width(), image.height(), if image.is_gray() { "L" } else { "RGBA" }, bits, camera.zoom * 100.0); + if let Some(ptr) = response.hover_pos() { + let local = (ptr - (center - size * 0.5)) / camera.zoom; let (x, y) = (local.x.floor() as i64, local.y.floor() as i64); - let v = img.get(x, y, true); - if img.is_gray() { - text += &format!(" ({}, {}) {:.3}", x.rem_euclid(img.width() as i64), y.rem_euclid(img.height() as i64), v[0]); + let v = image.get(x, y, true); + if image.is_gray() { + text += &format!(" ({}, {}) {:.3}", x.rem_euclid(image.width() as i64), y.rem_euclid(image.height() as i64), v[0]); } else { - text += - &format!(" ({}, {}) {:.3} {:.3} {:.3} {:.3}", x.rem_euclid(img.width() as i64), y.rem_euclid(img.height() as i64), v[0], v[1], v[2], v[3]); + text += &format!( + " ({}, {}) {:.3} {:.3} {:.3} {:.3}", + x.rem_euclid(image.width() as i64), + y.rem_euclid(image.height() as i64), + v[0], + v[1], + v[2], + v[3] + ); } } - ui.painter().rect_filled(info, 0.0, tk.panel); - ui.painter().text(info.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(11.0), tk.text_dim); + ui.painter().rect_filled(info, 0.0, theme.panel); + ui.painter().text(info.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(11.0), theme.text_dim); } /// The histogram card in the view's bottom-right corner, computed once per shown image. diff --git a/crates/ui-egui/tests/it/preview_resolution.rs b/crates/ui-egui/tests/it/preview_resolution.rs index c8e414f..2513aca 100644 --- a/crates/ui-egui/tests/it/preview_resolution.rs +++ b/crates/ui-egui/tests/it/preview_resolution.rs @@ -48,19 +48,24 @@ fn painted(h: &Harness<'static, MaterialCraftApp>) -> Vec { fn node_resolution_explains_the_preview_cap() { let (mut h, id) = harness(512, false); let img = h.state().session.cooked.image(id, 0).unwrap(); + assert_eq!((img.width(), img.height()), (512, 512)); assert_eq!(h.state().session.graph().unwrap().size, [10, 10]); assert!(painted(&h).iter().any(|t| t == "512x512 Preview"), "missing preview label: {:?}", painted(&h)); + let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1; h.event(Event::PointerMoved(rect.center())); h.run_steps(90); let text = painted(&h).join("\n"); + assert!(text.contains("Parent size: 1024 x 1024"), "{text}"); assert!(text.contains("Preview limit: 512 px"), "{text}"); assert!(text.contains("Edit > Preferences"), "{text}"); assert!(text.contains("16bpc"), "format information lost: {text}"); + let full = h.state().session.cook_full(0); let img = full.image(id, 0).unwrap(); + assert_eq!((img.width(), img.height()), (1024, 1024)); } @@ -68,6 +73,7 @@ fn node_resolution_explains_the_preview_cap() { fn full_size_mode_retains_the_resolution_and_format() { let (h, id) = harness(0, false); let img = h.state().session.cooked.image(id, 0).unwrap(); + assert_eq!((img.width(), img.height()), (1024, 1024)); assert!(painted(&h).iter().any(|t| t == "1024x1024 - C16"), "{:?}", painted(&h)); assert!(!painted(&h).iter().any(|t| t == "1024x1024 Preview")); diff --git a/crates/ui-egui/tests/it/resolution.rs b/crates/ui-egui/tests/it/resolution.rs index 40140ae..974f819 100644 --- a/crates/ui-egui/tests/it/resolution.rs +++ b/crates/ui-egui/tests/it/resolution.rs @@ -19,12 +19,15 @@ fn choose_4k(h: &mut Harness<'static, MaterialCraftApp>) { h.run(); h.get_by_label("4096 px").click(); h.run(); + assert_eq!(h.state().session.preview_size, Some(4096)); assert_eq!(h.state().ui.prefs.preview_size, 4096); + h.state_mut().session.cook(); h.step(); let app = h.state(); let (_, image) = app.session.view2d_image().unwrap(); + assert_eq!((image.width(), image.height()), (4096, 4096)); assert!(app.session.material_maps().iter().all(|(_, image)| (image.width(), image.height()) == (4096, 4096))); assert!(!app.session.material_maps().is_empty()); @@ -58,7 +61,8 @@ fn four_k_preview_refreshes_texture_after_size_change() { app(), ); h.input_mut().max_texture_side = Some(4096); - // The cooked key alone does not name the input size, so changing size must still refresh. + + // The cooked key alone does not name the input size, so changing size must still refresh let node = h.state().session.view2d.node.unwrap(); h.state_mut().session.preview_size = Some(4096); h.state_mut().session.cook(); @@ -66,14 +70,17 @@ fn four_k_preview_refreshes_texture_after_size_change() { h.state_mut().ui.prefs.preview_size = 4096; h.step(); let (_, image) = h.state().session.view2d_image().unwrap(); + assert_eq!((image.width(), image.height()), (4096, 4096)); assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); + h.state_mut().session.preview_size = Some(256); h.state_mut().session.cook(); h.state_mut().session.cooked.nodes.get_mut(&node).unwrap().key = 0; h.state_mut().ui.prefs.preview_size = 256; h.step(); let (_, image) = h.state().session.view2d_image().unwrap(); + assert_eq!((image.width(), image.height()), (256, 256)); assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((256, 256))); } diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index daf34b7..aa24a2b 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1299,6 +1299,7 @@ fn named_outputs_select_without_loading_and_open_on_double_click() { let query = By::new().role(egui::accesskit::Role::TreeItem).label("Base Color"); let position = harness.get(query.clone()).rect().center(); click_canvas(&mut harness, position); + assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(source)]); assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(source))); assert!(!harness.state().graph.ports.iter().any(|port| port.node.0 == output && port.output)); @@ -1313,12 +1314,16 @@ fn named_outputs_select_without_loading_and_open_on_double_click() { harness.step(); } settle(&mut harness, 3); + assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(output))); assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]); assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); assert_eq!(serde_json::to_value(&harness.state().session.view3d).unwrap(), view3d); + let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.shared_data().clone())).collect::>(); + assert_eq!(current, material); + save(&mut harness, &directory, "named-output-preview"); } diff --git a/crates/ui-egui/tests/snapshot/parameter_functions.rs b/crates/ui-egui/tests/snapshot/parameter_functions.rs index b5267dd..37bfc14 100644 --- a/crates/ui-egui/tests/snapshot/parameter_functions.rs +++ b/crates/ui-egui/tests/snapshot/parameter_functions.rs @@ -4,6 +4,16 @@ use materialcraft_engine::core::{BaseParameter, NodeId}; use materialcraft_ui_egui::{MaterialCraftApp, UiState}; use serde_json::json; +fn wait_for_cook(harness: &mut egui_kittest::Harness<'static, MaterialCraftApp>) { + // Cook errors can move Properties controls before a queued pointer click + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while (harness.state().cooker.busy() || harness.state().session.dirty) && std::time::Instant::now() < deadline { + settle(harness, 1); + } + + assert!(!harness.state().cooker.busy() && !harness.state().session.dirty, "the parameter preview cook must complete"); +} + #[test] #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] fn parameter_functions_create_edit_reset_and_return_to_the_owner() { @@ -14,6 +24,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() { let owner = NodeId(app.run("graph.node.add", json!({"def": "directional_blur"})).unwrap()["id"].as_u64().unwrap()); let mut harness = harness(app, 1600.0, 1100.0); settle(&mut harness, 8); + wait_for_cook(&mut harness); let button = |label| By::new().role(egui::accesskit::Role::Button).label(label); for parameter in BaseParameter::ALL { let label = format!("Parameter actions: {}", parameter.label()); @@ -34,6 +45,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() { save(&mut harness, &directory, "parameter-function-menu"); harness.get(button("Empty function")).click(); settle(&mut harness, 5); + wait_for_cook(&mut harness); assert!(harness.state().session.graph().unwrap().node(owner).unwrap().base.functions[&BaseParameter::OutputSize].nodes.is_empty()); assert_eq!(harness.state().function_editor.as_ref().unwrap().node, Some(owner)); @@ -68,12 +80,14 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() { settle(&mut harness, 8); harness.get(button("Reset to default")).click(); settle(&mut harness, 8); + wait_for_cook(&mut harness); harness.get(button("Parameter actions: Output size")).click(); settle(&mut harness, 8); save(&mut harness, &directory, "parameter-after-reset-menu"); assert!(harness.query(button("Constant value")).is_some(), "the reset parameter menu must offer a constant"); harness.get(button("Constant value")).click(); settle(&mut harness, 4); + wait_for_cook(&mut harness); let function = &harness.state().session.graph().unwrap().node(owner).unwrap().base.functions[&BaseParameter::OutputSize]; assert_eq!(function.nodes.len(), 1); @@ -93,6 +107,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() { settle(&mut harness, 3); harness.get(button("Constant value")).click(); settle(&mut harness, 4); + wait_for_cook(&mut harness); assert!(harness.query(By::new().label("Expected output: Float")).is_some()); assert!(harness.state().session.graph().unwrap().node(owner).unwrap().functions.contains_key("angle")); save(&mut harness, &directory, "parameter-specific-function"); diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index c551092..4d74850 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -155,6 +155,7 @@ mod tests { c("materialcraft-ui-egui", &[("materialcraft-automation", Normal, true), ("egui", Normal, false), ("wgpu", Normal, false)]), c("materialcraft", &[("eframe", Normal, false), ("materialcraft-ui-egui", Normal, true), ("winresource", Build, false)]), ]; + assert!(check(&g).is_empty(), "{:?}", check(&g)); }