diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 631c6cf0..5a0400d8 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -32,7 +32,6 @@ images, materials, sample graphs, presets, environments) may ever be added.
| `docs/images/materialcraft-levels-editor.png` | Docs screenshot: the Levels editor with the input histogram | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 |
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
| `crates/nodes/src/atomic/text.rs` (`GLYPHS`) | Single-stroke vector font of the Text node (A–Z, a–z, 0–9, punctuation) | MaterialCraft contributors | Original, designed as stroke data in code | MIT OR Apache-2.0 |
-| `examples/atomic_sample.sbs` | Atomic sample graph | MaterialCraft contributors | Original graph built by `crates/engine/src/atomic_sample.rs` | MIT OR Apache-2.0 |
## Third-party assets compiled into the binary
@@ -42,13 +41,3 @@ These come from Rust crate dependencies (not files in this repository) and keep
|---|---|---|---|---|
| Phosphor Icons (regular), via the `egui-phosphor` crate (vendored in `vendor/egui-phosphor` for egui 0.37) | Every UI icon (toolbars, panels, node quick-insert buttons) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 |
| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT |
-
-## Procedural content (no asset files)
-
-The node library's primitives (`crates/nodes`), the sample materials and graph templates
-(`crates/engine/src/samples.rs`), the 3D view's environments (`crates/render/src/ibl.rs`, procedural
-HDR skies and soft boxes), the built-in meshes (`crates/geom/src/primitives.rs`), the library's node
-previews (`crates/ui-egui/src/thumbs.rs`, each node cooked on sample waves) and the New graph
-dialog's template spheres (`crates/ui-egui/src/windows.rs`) are generated in code by MaterialCraft
-contributors (MIT OR Apache-2.0). None of them is derived from another product's presets,
-shaders, materials, sample graphs or images.
diff --git a/ROADMAP.md b/ROADMAP.md
index 0e97d7b7..37dcf3eb 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,6 +1,6 @@
# MaterialCraft roadmap
-**Current focus (2026-11-05):** native primitive editing, evaluation and SBS save/load.
+**Current focus (2026-11-08):** native primitive editing, reusable SBS functions and interoperable save/load.
The old Rust procedural library has been removed. The main catalog has 30 entries: 26 native
primitives and four graph input/output items. Functions have 85 operations; pattern graphs have
@@ -13,13 +13,15 @@ rendering parity and arbitrary SBS round trips have not been established.
1. Verify the original atomic sample in the reference application
2. Compare primitive outputs and parameter semantics against reference results
-3. Add SBS graph references with cycle-safe resolution
-4. Build the library from SBS definitions instead of duplicate Rust nodes
+3. Validate the converted standard library in the reference application and establish redistribution rights
+4. Extend the SBS library beyond reusable functions to processing graphs
## Progress log
| Date | What landed |
|---|---|
+| 2026-11-08 | Explorer folder hierarchy and package/folder/graph context menus, native SBS empty folders and resource paths, undoable copy/move/rename/remove, and package reload/save-copy actions |
+| 2026-11-08 | Portable `sbs://` function instances in the Library, preserved package folders and missing references, and a converted library retaining all 171 supplied function bodies (2,334 nodes); external runtime equivalence and redistribution rights remain unverified |
| 2026-11-02 | Cross-app materials: `.mcmat` portable materials, Send to TextureCraft, input-node preview images (mesh maps from TextureCraft), live re-cooks from TextureCraft through the CLI |
| 2026-11-02 | Visual function editor, dynamic parameters, presets and groups, 105 more nodes (flood fill, FX-Map, SVG, Text, 3D noises, weathering, material blending), mesh import, browser file I/O, 2D histogram, CLI `--set`, better samples |
| 2026-11-02 | First day: engine, ~120 nodes, cooking cache, packages, export, the full editor UI, 3D preview, CLI, control channel with synthetic input, MCP server, wasm builds |
diff --git a/assets/sbs/functions.sbs b/assets/sbs/functions.sbs
new file mode 100644
index 00000000..0294f74a
--- /dev/null
+++ b/assets/sbs/functions.sbs
@@ -0,0 +1 @@
+
diff --git a/crates/core/src/attributes.rs b/crates/core/src/attributes.rs
index 1dc3b2bc..e8d20402 100644
--- a/crates/core/src/attributes.rs
+++ b/crates/core/src/attributes.rs
@@ -4,8 +4,12 @@ use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Attributes {
+ pub label: String,
pub category: String,
pub description: String,
pub author: String,
+ pub author_url: String,
pub tags: String,
+ pub group: String,
+ pub user_data: String,
}
diff --git a/crates/core/src/base_parameters.rs b/crates/core/src/base_parameters.rs
index 2eba06c5..ed0f58d9 100644
--- a/crates/core/src/base_parameters.rs
+++ b/crates/core/src/base_parameters.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
-use crate::{OutputFormat, SizeMode};
+use crate::{OutputFormat, ParameterInheritance, SizeMode};
/// Parameters every node has ("Base parameters")
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -14,10 +14,23 @@ pub struct BaseParameters {
pub seed: i32,
/// Whether sampling wraps at the edges (horizontal, vertical)
pub tiling: [bool; 2],
+ pub tiling_mode: ParameterInheritance,
+ /// SBS pixel ratio: zero stretches the image; one keeps pixels square.
+ pub pixel_ratio: i32,
+ pub pixel_ratio_mode: ParameterInheritance,
}
impl Default for BaseParameters {
fn default() -> Self {
- BaseParameters { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, seed: 0, tiling: [true, true] }
+ BaseParameters {
+ size_mode: SizeMode::RelativeToInput,
+ size: [0, 0],
+ format: OutputFormat::Inherit,
+ seed: 0,
+ tiling: [true, true],
+ tiling_mode: ParameterInheritance::default(),
+ pixel_ratio: 0,
+ pixel_ratio_mode: ParameterInheritance::default(),
+ }
}
}
diff --git a/crates/core/src/evaluation_environment.rs b/crates/core/src/evaluation_environment.rs
new file mode 100644
index 00000000..baf5620b
--- /dev/null
+++ b/crates/core/src/evaluation_environment.rs
@@ -0,0 +1,11 @@
+use serde::{Deserialize, Serialize};
+
+/// Host values shared by graph instances for one deterministic evaluation.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct EvaluationEnvironment {
+ pub time_seconds: f32,
+ pub uv_tile: [i32; 2],
+ /// Raw host convention code; the static authoring environment uses zero.
+ pub normal_format: i32,
+}
diff --git a/crates/core/src/function_graph.rs b/crates/core/src/function_graph.rs
index fc663ba9..c3f43bc2 100644
--- a/crates/core/src/function_graph.rs
+++ b/crates/core/src/function_graph.rs
@@ -30,6 +30,8 @@ impl FunctionGraph {
let horizontal_position = self.nodes.len() as f32 * 140.0;
let node = FunctionNode {
id,
+ missing: None,
+ missing_data: String::new(),
instance: None,
source: None,
type_code: 0,
diff --git a/crates/core/src/function_node.rs b/crates/core/src/function_node.rs
index a81e094c..c171802a 100644
--- a/crates/core/src/function_node.rs
+++ b/crates/core/src/function_node.rs
@@ -9,6 +9,12 @@ pub struct FunctionNode {
#[serde(default)]
pub type_code: u32,
pub op: String,
+ /// Connector names for an unavailable operation; its wires remain editable.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub missing: Option>,
+ /// Uninterpreted function data, retained for unavailable operations on save.
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub missing_data: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instance: Option,
/// Resolved call body shared by cooks; SBS stores only the source reference
diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs
index 98c9e848..a277554f 100644
--- a/crates/core/src/graph.rs
+++ b/crates/core/src/graph.rs
@@ -10,8 +10,14 @@ use crate::{Attributes, Comment, Connection, ExposedParameter, Frame, GraphKind,
#[serde(rename_all = "camelCase")]
pub struct Graph {
pub name: String,
+ /// Package folder, retained so external SBS references keep their identity.
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub folder: String,
#[serde(default)]
pub function: Option,
+ /// Declared SBS return type, including functions whose implementation is unavailable.
+ #[serde(default)]
+ pub function_type: u32,
pub nodes: Vec,
pub connections: Vec,
#[serde(default)]
@@ -27,6 +33,16 @@ pub struct Graph {
#[serde(default)]
pub seed: i32,
#[serde(default)]
+ pub pixel_ratio: i32,
+ #[serde(default)]
+ pub pixel_ratio_mode: crate::ParameterInheritance,
+ #[serde(default = "default_tiling")]
+ pub tiling: [bool; 2],
+ #[serde(default)]
+ pub tiling_mode: crate::ParameterInheritance,
+ #[serde(default)]
+ pub physical_size: [f32; 3],
+ #[serde(default)]
pub exposed: Vec,
/// Current values of the exposed inputs (missing = default)
#[serde(default)]
@@ -49,10 +65,17 @@ pub const MIN_SIZE_LOG2: u32 = 4;
pub const MAX_SIZE_LOG2: u32 = 13;
impl Graph {
+ /// Display text never changes the identifier used by SBS references
+ pub fn display_name(&self) -> &str {
+ if self.attributes.label.is_empty() { &self.name } else { &self.attributes.label }
+ }
+
pub fn new(name: &str) -> Graph {
Graph {
name: name.into(),
+ folder: String::new(),
function: None,
+ function_type: 0,
nodes: Vec::new(),
connections: Vec::new(),
frames: Vec::new(),
@@ -61,6 +84,11 @@ impl Graph {
size: [10, 10],
format: OutputFormat::U16,
seed: 0,
+ pixel_ratio: 0,
+ pixel_ratio_mode: crate::ParameterInheritance::default(),
+ tiling: [true, true],
+ tiling_mode: crate::ParameterInheritance::default(),
+ physical_size: [0.0; 3],
exposed: Vec::new(),
inputs: BTreeMap::new(),
presets: Vec::new(),
@@ -71,6 +99,10 @@ impl Graph {
}
}
+ pub fn sbs_path(&self) -> String {
+ if self.folder.is_empty() { self.name.clone() } else { format!("{}/{}", self.folder, self.name) }
+ }
+
/// All editable Function canvases, including processor and parameter functions
pub fn functions(&self) -> impl Iterator- {
self.function.iter().chain(self.nodes.iter().flat_map(|node| node.functions.values().chain(node.params.values().flat_map(value_functions))))
@@ -196,6 +228,10 @@ impl Graph {
}
}
+fn default_tiling() -> [bool; 2] {
+ [true, true]
+}
+
fn value_functions(value: &Value) -> impl Iterator
- {
let (function, pattern) = match value {
Value::Function(function) => (Some(function.as_ref()), None),
diff --git a/crates/core/src/graph_instance.rs b/crates/core/src/graph_instance.rs
index afdabfed..5880054a 100644
--- a/crates/core/src/graph_instance.rs
+++ b/crates/core/src/graph_instance.rs
@@ -4,9 +4,15 @@ use serde::{Deserialize, Serialize};
/// An SBS graph reference and its last known interface, without a copy of its nodes
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphInstance {
+ /// Display label resolved from the source; the SBS reference keeps its identifier
+ #[serde(skip)]
+ pub label: String,
/// Empty for a graph in the same package
pub package: String,
pub graph: String,
pub inputs: Vec,
pub outputs: Vec,
+ /// Resolved function input defaults; the source package remains authoritative
+ #[serde(skip)]
+ pub defaults: std::collections::BTreeMap,
}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 2abda532..18105082 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -10,6 +10,7 @@ mod connection;
mod core_error;
mod curve;
mod curve_point;
+mod evaluation_environment;
mod exposed_parameter;
mod frame;
mod function_graph;
@@ -27,6 +28,7 @@ mod node;
mod node_id;
mod output_format;
mod package;
+mod parameter_inheritance;
mod pattern_graph;
mod pattern_node;
mod pattern_node_kind;
@@ -47,6 +49,7 @@ pub use connection::Connection;
pub use core_error::CoreError;
pub use curve::Curve;
pub use curve_point::CurvePoint;
+pub use evaluation_environment::EvaluationEnvironment;
pub use exposed_parameter::ExposedParameter;
pub use frame::Frame;
pub use function_graph::FunctionGraph;
@@ -64,6 +67,7 @@ pub use node::Node;
pub use node_id::NodeId;
pub use output_format::OutputFormat;
pub use package::{PACKAGE_EXT, Package};
+pub use parameter_inheritance::ParameterInheritance;
pub use pattern_graph::PatternGraph;
pub use pattern_node::PatternNode;
pub use pattern_node_kind::PatternNodeKind;
diff --git a/crates/core/src/package.rs b/crates/core/src/package.rs
index bb42b434..2e4bffc4 100644
--- a/crates/core/src/package.rs
+++ b/crates/core/src/package.rs
@@ -8,6 +8,9 @@ pub const PACKAGE_EXT: &str = "sbs";
pub struct Package {
pub name: String,
pub graphs: Vec,
+ /// Explicit SBS group paths, including folders without graphs
+ #[serde(default)]
+ pub folders: Vec,
#[serde(default)]
pub resources: Vec,
/// Resolved source packages shared by cooks; SBS stores their file references instead
@@ -24,7 +27,25 @@ fn version() -> u32 {
impl Package {
pub fn new(name: &str) -> Package {
- Package { name: name.into(), graphs: Vec::new(), resources: Vec::new(), version: 1, dependencies: Default::default() }
+ Package { name: name.into(), graphs: Vec::new(), folders: Vec::new(), resources: Vec::new(), version: 1, dependencies: Default::default() }
+ }
+
+ pub fn folder_paths(&self) -> std::collections::BTreeSet {
+ let mut folders = std::collections::BTreeSet::new();
+ for path in self
+ .folders
+ .iter()
+ .map(String::as_str)
+ .chain(self.graphs.iter().map(|graph| graph.folder.as_str()))
+ .chain(self.resources.iter().map(|resource| resource.folder.as_str()))
+ {
+ let mut parent = path;
+ while !parent.is_empty() {
+ folders.insert(parent.to_string());
+ parent = parent.rsplit_once('/').map_or("", |(parent, _)| parent);
+ }
+ }
+ folders
}
pub fn graph(&self, i: usize) -> Result<&Graph> {
@@ -36,7 +57,11 @@ impl Package {
}
pub fn graph_by_name(&self, name: &str) -> Option<(usize, &Graph)> {
- self.graphs.iter().enumerate().find(|(_, g)| g.name == name)
+ self.graphs.iter().enumerate().find(|(_, g)| g.sbs_path() == name).or_else(|| {
+ let mut matches = self.graphs.iter().enumerate().filter(|(_, g)| g.name == name);
+ let first = matches.next()?;
+ matches.next().is_none().then_some(first)
+ })
}
pub fn resource(&self, name: &str) -> Option<&Resource> {
@@ -46,10 +71,10 @@ impl Package {
/// A name not used by any graph: `base`, `base_1`, `base_2`…
pub fn unique_graph_name(&self, base: &str) -> String {
let base = if base.trim().is_empty() { "Graph" } else { base.trim() };
- if self.graph_by_name(base).is_none() {
+ if !self.graphs.iter().any(|graph| graph.name == base) {
return base.to_string();
}
- (1..).map(|i| format!("{base}_{i}")).find(|n| self.graph_by_name(n).is_none()).unwrap_or_else(|| base.to_string())
+ (1..).map(|index| format!("{base}_{index}")).find(|name| !self.graphs.iter().any(|graph| graph.name == *name)).unwrap_or_else(|| base.to_string())
}
pub fn instance_package(&self, node: &crate::Node) -> Option<&Package> {
diff --git a/crates/core/src/parameter_inheritance.rs b/crates/core/src/parameter_inheritance.rs
new file mode 100644
index 00000000..b0866e9e
--- /dev/null
+++ b/crates/core/src/parameter_inheritance.rs
@@ -0,0 +1,20 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ParameterInheritance {
+ Absolute,
+ #[default]
+ RelativeToInput,
+ RelativeToParent,
+}
+
+impl ParameterInheritance {
+ pub fn resolve(self, absolute: T, input: Option, parent: T) -> T {
+ match self {
+ Self::Absolute => absolute,
+ Self::RelativeToInput => input.unwrap_or(parent),
+ Self::RelativeToParent => parent,
+ }
+ }
+}
diff --git a/crates/core/src/resource.rs b/crates/core/src/resource.rs
index f7545736..c2e65b8c 100644
--- a/crates/core/src/resource.rs
+++ b/crates/core/src/resource.rs
@@ -6,8 +6,13 @@ use serde::{Deserialize, Serialize};
pub struct Resource {
/// Unique name, referenced by nodes (`resource` parameter)
pub name: String,
+ #[serde(default = "default_folder")]
+ pub folder: String,
/// File name inside the package's `resources/` folder
pub file: String,
+ /// Unavailable external asset retained for repair on a later load
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub source: String,
/// The file's bytes (stored in the zip, not in `package.json`)
#[serde(skip)]
pub bytes: ResourceBytes,
@@ -16,6 +21,14 @@ pub struct Resource {
impl Resource {
/// A resource named `name`, stored as `file` in the package
pub fn new(name: impl Into, file: impl Into, bytes: ResourceBytes) -> Resource {
- Resource { name: name.into(), file: file.into(), bytes }
+ Resource { name: name.into(), folder: default_folder(), file: file.into(), source: String::new(), bytes }
+ }
+
+ pub fn sbs_path(&self) -> String {
+ if self.folder.is_empty() { self.name.clone() } else { format!("{}/{}", self.folder, self.name) }
}
}
+
+fn default_folder() -> String {
+ "Resources".into()
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 3a0a753e..330756a3 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -49,18 +49,25 @@ pub fn command_specs() -> &'static [CommandSpec] {
let mut v = Vec::new();
v.extend(crate::file_cmds::specs());
v.extend(crate::package_commands::specs());
+ v.extend(crate::package_file_commands::specs());
+ v.extend(crate::folder_commands::specs());
+ v.extend(crate::explorer_clipboard_commands::specs());
v.extend(crate::graph_instance_commands::specs());
+ v.extend(crate::function_library_commands::specs());
v.extend(crate::node_info_commands::specs());
v.extend(crate::atomic_sample_commands::specs());
v.extend(crate::material_cmds::specs());
v.extend(crate::edit_cmds::specs());
v.extend(crate::embedded_edit_commands::specs());
v.extend(crate::graph_cmds::specs());
+ v.extend(crate::graph_property_commands::specs());
v.extend(crate::alignment_commands::specs());
v.extend(crate::annotation_commands::specs());
v.extend(crate::frame_commands::specs());
v.extend(crate::function_commands::specs());
v.extend(crate::function_info_commands::specs());
+ v.extend(crate::function_variable_commands::specs());
+ v.extend(crate::evaluation_environment_commands::specs());
v.extend(crate::comment_commands::specs());
v.extend(crate::node_cmds::specs());
v.extend(crate::node_graph_commands::specs());
diff --git a/crates/engine/src/document_path.rs b/crates/engine/src/document_path.rs
index 372797a8..0778f1d2 100644
--- a/crates/engine/src/document_path.rs
+++ b/crates/engine/src/document_path.rs
@@ -1,4 +1,7 @@
pub(crate) fn normalize(path: &str) -> String {
+ if path.contains("://") {
+ return path.to_string();
+ }
#[cfg(not(target_arch = "wasm32"))]
{
use std::path::{Component, PathBuf};
@@ -32,6 +35,12 @@ pub(crate) fn normalize(path: &str) -> String {
}
pub(crate) fn resolve(owner: &str, reference: &str) -> String {
+ if reference.contains("://") {
+ return reference.to_string();
+ }
+ if owner.starts_with("sbs://") {
+ return materialcraft_formats::sbs::library::resolve(owner, reference).unwrap_or_else(|_| format!("sbs://{reference}"));
+ }
let path = std::path::Path::new(reference);
if path.is_absolute() {
return normalize(reference);
@@ -40,6 +49,9 @@ pub(crate) fn resolve(owner: &str, reference: &str) -> String {
}
pub(crate) fn relative(owner: &str, source: &str) -> String {
+ if source.contains("://") {
+ return source.to_string();
+ }
let folder = std::path::Path::new(owner).parent().unwrap_or(std::path::Path::new(""));
let from: Vec<_> = folder.components().collect();
let to: Vec<_> = std::path::Path::new(source).components().collect();
diff --git a/crates/engine/src/evaluation_environment_commands.rs b/crates/engine/src/evaluation_environment_commands.rs
new file mode 100644
index 00000000..f4b846c5
--- /dev/null
+++ b/crates/engine/src/evaluation_environment_commands.rs
@@ -0,0 +1,99 @@
+use crate::{
+ Result, Session, cmd,
+ commands::{CommandSpec, always, bad, has_graph},
+};
+use serde_json::{Value as Json, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![
+ cmd!(
+ "session.environment",
+ "Evaluation environment",
+ [],
+ None,
+ "{timeSeconds?: nonnegative float, uvTile?: [int, int], normalFormat?: int} updates host values; {} reads them; does not modify the package",
+ always,
+ environment
+ ),
+ cmd!(
+ "graph.context",
+ "Graph evaluation context",
+ [],
+ None,
+ "{physicalSize?: [x, y, z], pixelRatio?: 0|1, tiling?: [horizontal, vertical]} updates material-graph metadata used by system variables; {} reads it",
+ has_graph,
+ graph_context
+ ),
+ ]
+}
+
+fn environment(session: &mut Session, parameters: &Json) -> Result {
+ let command = "session.environment";
+ let mut environment = session.environment;
+ let fields = parameters.as_object().ok_or_else(|| bad(command, "expected an object"))?;
+ for (name, value) in fields {
+ match name.as_str() {
+ "timeSeconds" => environment.time_seconds = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?,
+ "uvTile" => environment.uv_tile = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?,
+ "normalFormat" => environment.normal_format = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?,
+ _ => return Err(bad(command, format!("unknown environment field `{name}`"))),
+ }
+ }
+
+ if !environment.time_seconds.is_finite() || environment.time_seconds < 0.0 {
+ return Err(bad(command, "timeSeconds must be finite and nonnegative"));
+ }
+
+ if session.environment != environment {
+ session.environment = environment;
+ session.dirty = true;
+ session.cook_epoch = session.cook_epoch.wrapping_add(1);
+ }
+ Ok(json!(environment))
+}
+
+fn graph_context(session: &mut Session, parameters: &Json) -> Result {
+ let command = "graph.context";
+ let graph = session.graph()?;
+ // Reusable functions receive these values from their caller and do not serialize base parameters
+ if graph.function.is_some() {
+ return Err(bad(command, "function graphs use their caller's evaluation context; edit the material graph"));
+ }
+
+ let (mut physical_size, mut pixel_ratio, mut tiling) = (graph.physical_size, graph.pixel_ratio, graph.tiling);
+ let (mut pixel_ratio_mode, mut tiling_mode) = (graph.pixel_ratio_mode, graph.tiling_mode);
+ let fields = parameters.as_object().ok_or_else(|| bad(command, "expected an object"))?;
+ for (name, value) in fields {
+ match name.as_str() {
+ "physicalSize" => physical_size = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?,
+ "pixelRatio" => {
+ pixel_ratio = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?;
+ pixel_ratio_mode = materialcraft_core::ParameterInheritance::Absolute;
+ }
+ "tiling" => {
+ tiling = serde_json::from_value(value.clone()).map_err(|error| bad(command, error.to_string()))?;
+ tiling_mode = materialcraft_core::ParameterInheritance::Absolute;
+ }
+ _ => return Err(bad(command, format!("unknown graph context field `{name}`"))),
+ }
+ }
+
+ if physical_size.iter().any(|value| !value.is_finite() || *value < 0.0) || !(0..=1).contains(&pixel_ratio) {
+ return Err(bad(command, "physicalSize must be finite and nonnegative; pixelRatio must be 0 or 1"));
+ }
+
+ if (graph.physical_size, graph.pixel_ratio, graph.tiling, graph.pixel_ratio_mode, graph.tiling_mode)
+ != (physical_size, pixel_ratio, tiling, pixel_ratio_mode, tiling_mode)
+ {
+ session.edit("Graph evaluation context", |session| {
+ let graph = session.graph_mut()?;
+ graph.physical_size = physical_size;
+ graph.pixel_ratio = pixel_ratio;
+ graph.tiling = tiling;
+ graph.pixel_ratio_mode = pixel_ratio_mode;
+ graph.tiling_mode = tiling_mode;
+ Ok(())
+ })?;
+ }
+ Ok(json!({"physicalSize": physical_size, "pixelRatio": pixel_ratio, "tiling": tiling}))
+}
diff --git a/crates/engine/src/explorer_clipboard.rs b/crates/engine/src/explorer_clipboard.rs
new file mode 100644
index 00000000..6b8e30c6
--- /dev/null
+++ b/crates/engine/src/explorer_clipboard.rs
@@ -0,0 +1,10 @@
+use materialcraft_core::Package;
+
+#[derive(Clone, Debug)]
+pub struct ExplorerClipboard {
+ pub(crate) source: Package,
+ pub(crate) document: u64,
+ pub(crate) path: Option,
+ pub(crate) graph: Option,
+ pub(crate) folder: Option,
+}
diff --git a/crates/engine/src/explorer_clipboard_commands.rs b/crates/engine/src/explorer_clipboard_commands.rs
new file mode 100644
index 00000000..158b2ac3
--- /dev/null
+++ b/crates/engine/src/explorer_clipboard_commands.rs
@@ -0,0 +1,206 @@
+use crate::{
+ ExplorerClipboard, Result, Session, cmd,
+ commands::{CommandSpec, always, bad, strp},
+ folder_path,
+};
+use materialcraft_core::{Package, Value as GraphValue};
+use serde_json::{Value, json};
+use std::collections::{BTreeMap, BTreeSet};
+
+pub(crate) fn specs() -> Vec {
+ vec![
+ cmd!("explorer.copy", "Copy Explorer item", [], None, "{graph? index, folder?} copies a graph, folder subtree, or package contents", always, copy),
+ cmd!(
+ "explorer.paste",
+ "Paste Explorer item",
+ [],
+ None,
+ "{folder?} pastes into a folder or the package root, with unique names",
+ |session| { if session.explorer_clipboard.is_some() { Ok(()) } else { Err("the Explorer clipboard is empty".into()) } },
+ paste
+ ),
+ ]
+}
+
+fn copy(session: &mut Session, parameters: &Value) -> Result {
+ let graph = parameters
+ .get("graph")
+ .map(|value| value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("explorer.copy", "graph must be an index")))
+ .transpose()?;
+ let folder = strp(parameters, "folder").map(str::to_string);
+ if graph.is_some() && folder.is_some() {
+ return Err(bad("explorer.copy", "select one graph or folder"));
+ }
+ if let Some(index) = graph {
+ session.pkg.graph(index)?;
+ }
+ if let Some(folder) = &folder {
+ folder_path::require(&session.pkg, folder)?;
+ }
+
+ session.explorer_clipboard =
+ Some(ExplorerClipboard { source: session.pkg.clone(), document: session.document_id, path: session.path.clone(), graph, folder });
+ Ok(Value::Null)
+}
+
+fn paste(session: &mut Session, parameters: &Value) -> Result {
+ let parent = strp(parameters, "folder").unwrap_or("");
+ folder_path::require(&session.pkg, parent)?;
+ let clipboard = session.explorer_clipboard.as_ref().ok_or_else(|| bad("explorer.paste", "the Explorer clipboard is empty"))?;
+ let mut incoming = clipboard.source.clone();
+ incoming.graphs = clipboard
+ .source
+ .graphs
+ .iter()
+ .enumerate()
+ .filter(|(index, graph)| {
+ clipboard.graph.is_none_or(|selected| selected == *index)
+ && clipboard.folder.as_ref().is_none_or(|folder| folder.is_empty() || folder_path::contains(folder, &graph.folder))
+ })
+ .map(|(_, graph)| graph.clone())
+ .collect();
+ let folders: BTreeSet<_> = if clipboard.graph.is_some() {
+ BTreeSet::new()
+ } else {
+ clipboard
+ .source
+ .folder_paths()
+ .into_iter()
+ .filter(|path| clipboard.folder.as_ref().is_none_or(|folder| folder.is_empty() || folder_path::contains(folder, path)))
+ .collect()
+ };
+ if session.pkg.graphs.len().saturating_add(incoming.graphs.len()) > 4096 || session.pkg.folder_paths().len().saturating_add(folders.len()) > 16384 {
+ return Err(bad("explorer.paste", "a package supports at most 4096 graphs and 16384 folders"));
+ }
+
+ let mut destination = session.pkg.clone();
+ let mut folder_names = BTreeMap::new();
+ for folder in &folders {
+ let (source_parent, leaf) = folder.rsplit_once('/').unwrap_or(("", folder));
+ let target_parent = folder_names.get(source_parent).map(String::as_str).unwrap_or(parent);
+ let new = folder_path::join(target_parent, &folder_path::unique(&destination, target_parent, leaf));
+ folder_path::validate(&new)?;
+ destination.folders.push(new.clone());
+ folder_names.insert(folder.clone(), new);
+ }
+ incoming.folders = folder_names.values().cloned().collect();
+ let mut paths = BTreeMap::new();
+ for graph in &mut incoming.graphs {
+ let old = graph.sbs_path();
+ graph.folder = folder_names.get(&graph.folder).cloned().unwrap_or_else(|| parent.to_string());
+ graph.name = folder_path::unique(&destination, &graph.folder, &graph.name);
+ paths.insert(old, graph.sbs_path());
+ destination.graphs.push(graph.clone());
+ }
+ let names = crate::graph_references::with_leaf_names(&clipboard.source, &paths);
+ for graph in &mut incoming.graphs {
+ for instance in graph.instances_mut() {
+ if !instance.package.is_empty() {
+ continue;
+ }
+ if let Some(new) = names.get(&instance.graph) {
+ instance.graph = new.clone();
+ } else if clipboard.document != session.document_id {
+ instance.package =
+ clipboard.path.clone().ok_or_else(|| bad("explorer.paste", "save the source package or copy the referenced graphs together"))?;
+ if let Some((_, source)) = clipboard.source.graph_by_name(&instance.graph) {
+ instance.graph = source.sbs_path();
+ }
+ }
+ }
+ for node in graph.nodes.iter_mut().filter(|node| node.def == "graph_instance" && node.instance.is_none()) {
+ if let Some(GraphValue::Text(name)) = node.params.get_mut("graph") {
+ if let Some(new) = names.get(name) {
+ *name = new.clone();
+ } else if clipboard.document != session.document_id {
+ let package =
+ clipboard.path.clone().ok_or_else(|| bad("explorer.paste", "save the source package or copy the referenced graphs together"))?;
+ node.instance = Some(materialcraft_core::GraphInstance {
+ label: String::new(),
+ package,
+ graph: name.clone(),
+ inputs: Vec::new(),
+ outputs: Vec::new(),
+ defaults: Default::default(),
+ });
+ }
+ }
+ }
+ }
+ for resource in &mut incoming.resources {
+ if let Some(folder) = folder_names.get(&resource.folder) {
+ resource.folder = folder.clone();
+ } else if clipboard.graph.is_none() && resource.folder.is_empty() {
+ resource.folder = parent.into();
+ }
+ }
+ transfer_resources(
+ &mut incoming,
+ &destination,
+ clipboard.graph.is_none() && clipboard.folder.is_none(),
+ clipboard.folder.as_deref().and_then(|path| folder_names.get(path)).map(String::as_str),
+ );
+ let dependencies = incoming.dependencies.clone();
+ let result = session.edit("Paste Explorer item", |session| {
+ let first = session.pkg.graphs.len();
+ let count = incoming.graphs.len();
+ session.pkg.graphs.extend(incoming.graphs);
+ session.pkg.folders.extend(incoming.folders);
+ session.pkg.resources.extend(incoming.resources);
+ if count > 0 {
+ session.graph = first;
+ session.open_material_preview();
+ session.selection.clear();
+ session.annotation_selection = None;
+ }
+ Ok(json!({"graph": (count > 0).then_some(first), "graphs": count}))
+ })?;
+ session.linked_sources.extend(dependencies);
+ session.refresh_links();
+ Ok(result)
+}
+
+fn transfer_resources(incoming: &mut Package, destination: &Package, all: bool, folder: Option<&str>) {
+ let used: BTreeSet<_> = incoming
+ .graphs
+ .iter()
+ .flat_map(|graph| {
+ graph.input_images.values().cloned().chain(graph.nodes.iter().filter_map(|node| match node.params.get("resource") {
+ Some(GraphValue::Text(name)) => Some(name.clone()),
+ _ => None,
+ }))
+ })
+ .collect();
+ incoming.resources.retain(|resource| all || used.contains(&resource.name) || folder.is_some_and(|folder| folder_path::contains(folder, &resource.folder)));
+ let mut occupied: BTreeSet<_> = destination.resources.iter().map(|resource| resource.name.clone()).collect();
+ let occupied_paths: BTreeSet<_> = destination.folder_paths().into_iter().chain(destination.graphs.iter().map(|graph| graph.sbs_path())).collect();
+ let mut names = BTreeMap::new();
+ incoming.resources.retain_mut(|resource| {
+ if destination.resources.iter().any(|existing| existing == resource) {
+ return false;
+ }
+
+ let original = resource.name.clone();
+ let free = |name: &str| !occupied.contains(name) && !occupied_paths.contains(&folder_path::join(&resource.folder, name));
+ if !free(&original) {
+ resource.name = (1..).map(|index| format!("{original}_{index}")).find(|name| free(name)).unwrap_or_else(|| original.clone());
+ names.insert(original, resource.name.clone());
+ }
+ occupied.insert(resource.name.clone());
+ true
+ });
+ for graph in &mut incoming.graphs {
+ for resource in graph.input_images.values_mut() {
+ if let Some(new) = names.get(resource) {
+ *resource = new.clone();
+ }
+ }
+ for node in &mut graph.nodes {
+ if let Some(GraphValue::Text(name)) = node.params.get_mut("resource")
+ && let Some(new) = names.get(name)
+ {
+ *name = new.clone();
+ }
+ }
+ }
+}
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 0898ed4b..99480ae6 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -1,4 +1,5 @@
pub use crate::Exported;
+pub use crate::linked_resource::reader as linked_files;
use serde_json::{Value as J, json};
@@ -16,7 +17,7 @@ pub(crate) fn specs() -> Vec {
"Graph...",
["File", "New"],
Some("Ctrl+N"),
- "{name?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it",
+ "{name?, folder?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it",
always,
new_graph
),
@@ -71,16 +72,20 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result {
let size = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192);
let log2 = 63 - size.leading_zeros();
let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_"));
+ let folder = strp(parameters, "folder").unwrap_or("");
+ crate::folder_path::require(&session.pkg, folder)?;
+ let base = crate::folder_path::name(&base)?;
session.edit("New graph", |session| {
- let name = session.pkg.unique_graph_name(&base);
- let graph = if kind == materialcraft_core::GraphKind::Function {
+ let name = crate::folder_path::unique(&session.pkg, folder, base);
+ let mut graph = if kind == materialcraft_core::GraphKind::Function {
let mut graph = materialcraft_core::Graph::new(&name);
graph.function = Some(materialcraft_core::FunctionGraph::default());
graph
} else {
template(template_id, &name, log2)?
};
+ graph.folder = folder.into();
session.pkg.graphs.push(graph);
session.graph = session.pkg.graphs.len() - 1;
session.open_material_preview();
@@ -149,10 +154,8 @@ pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option Result> {
save_bytes_at(session, session.path.as_deref())
}
-fn save_bytes_at(session: &Session, path: Option<&str>) -> Result> {
+pub(crate) fn save_bytes_at(session: &Session, path: Option<&str>) -> Result> {
let mut package = session.pkg.clone();
if let Some(path) = path {
+ for resource in &mut package.resources {
+ if !resource.source.is_empty() {
+ resource.source = crate::document_path::relative(path, &resource.source);
+ }
+ }
+
for instance in package.graphs.iter_mut().flat_map(|graph| graph.instances_mut()) {
if !instance.package.is_empty() {
instance.package = crate::document_path::relative(path, &instance.package);
@@ -178,36 +187,14 @@ fn save_bytes_at(session: &Session, path: Option<&str>) -> Result> {
Ok(materialcraft_formats::sbs::write_sbs(&package)?)
}
-/// Largest file an SBS package may link to
-#[cfg(not(target_arch = "wasm32"))]
-const MAX_LINKED_FILE_BYTES: u64 = 256 << 20;
-
-/// Reads files an SBS package at `path` links to: plain relative paths that resolve inside its folder
-#[cfg(not(target_arch = "wasm32"))]
-pub fn linked_files(path: &str) -> impl Fn(&str) -> Option> + use<> {
- let parent = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));
- let folder = std::fs::canonicalize(parent).ok();
-
- move |relative: &str| {
- let relative = relative.trim().replace('\\', "/");
- let plain = !relative.is_empty() && !relative.contains(':') && !relative.starts_with('/');
- if !plain || std::path::Path::new(&relative).components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
- return None;
- }
-
- let folder = folder.as_ref()?;
- let file = std::fs::canonicalize(folder.join(&relative)).ok()?;
- let metadata = std::fs::metadata(&file).ok()?;
- if !file.starts_with(folder) || !metadata.is_file() || metadata.len() > MAX_LINKED_FILE_BYTES {
- return None;
- }
- std::fs::read(file).ok()
- }
-}
-
/// Open the package file at `path` (native), with the bitmaps an SBS package keeps next to it
#[cfg(not(target_arch = "wasm32"))]
pub fn open_file(s: &mut Session, path: &str) -> Result<()> {
+ if path.starts_with("sbs://") {
+ let bytes = materialcraft_formats::sbs::library::read(path).map_err(|error| bad("file.open", error))?;
+ return open_bytes_linked(s, &bytes, Some(path.into()), &linked_files(path));
+ }
+
let bytes = std::fs::read(path).map_err(|e| bad("file.open", format!("{path}: {e}")))?;
open_bytes_linked(s, &bytes, Some(path.to_string()), &linked_files(path))
}
@@ -221,8 +208,14 @@ fn open(s: &mut Session, p: &J) -> Result {
}
#[cfg(target_arch = "wasm32")]
-fn open(_: &mut Session, _: &J) -> Result {
- Err(bad("file.open", "the browser opens files with the file picker"))
+fn open(session: &mut Session, parameters: &J) -> Result {
+ let path = strp(parameters, "path")
+ .filter(|path| path.starts_with("sbs://"))
+ .ok_or_else(|| bad("file.open", "the browser opens local files with the file picker"))?;
+ let bytes = materialcraft_formats::sbs::library::read(path).map_err(|error| bad("file.open", error))?;
+ open_bytes_linked(session, &bytes, Some(path.into()), &linked_files(path))?;
+
+ Ok(json!({"name": session.pkg.name, "graphs": session.pkg.graphs.len(), "path": session.path, "warnings": session.load_warnings}))
}
#[cfg(not(target_arch = "wasm32"))]
@@ -233,6 +226,10 @@ fn save(s: &mut Session, p: &J) -> Result {
};
let path = crate::document_path::normalize(&path);
+ if path.contains("://") {
+ return Err(bad("file.save", "library aliases cannot be overwritten; save to a local .sbs path"));
+ }
+
if s.open_packages().into_iter().any(|entry| entry.0 != s.document_id && entry.2 == Some(path.as_str())) {
return Err(bad("file.save", "another open package already uses this file"));
}
@@ -263,7 +260,9 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O
}
let g = pkg.graph(gi)?;
let dec = s.resource_decoder();
- let cooked = materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &s.cache);
+ let mut options = materialcraft_eval::Options::new(&dec);
+ options.environment = s.environment;
+ let cooked = materialcraft_eval::cook(&pkg, gi, &options, &s.cache);
let mut out = Vec::new();
let mut names = std::collections::HashSet::new();
for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) {
diff --git a/crates/engine/src/folder_commands.rs b/crates/engine/src/folder_commands.rs
new file mode 100644
index 00000000..0377cad6
--- /dev/null
+++ b/crates/engine/src/folder_commands.rs
@@ -0,0 +1,137 @@
+use crate::{
+ Result, Session, cmd,
+ commands::{CommandSpec, always, bad, strp},
+ folder_path,
+};
+use serde_json::{Value, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![
+ cmd!("folder.create", "New folder", [], None, "{parent?, name?} creates an empty folder", always, create),
+ cmd!("folder.rename", "Rename folder", [], None, "{folder, name} renames a folder and updates local graph references", always, rename),
+ cmd!("folder.remove", "Remove folder", [], None, "{folder} removes a folder and its contents, with undo", always, remove),
+ cmd!("explorer.move", "Move Explorer item", [], None, "{graph? index, folder?, parent?} moves a graph or folder within its package", always, move_item),
+ ]
+}
+
+fn create(session: &mut Session, parameters: &Value) -> Result {
+ let parent = strp(parameters, "parent").unwrap_or("");
+ folder_path::require(&session.pkg, parent)?;
+ let name = folder_path::name(strp(parameters, "name").unwrap_or("Untitled_Folder"))?;
+ let path = folder_path::join(parent, &folder_path::unique(&session.pkg, parent, name));
+ folder_path::validate(&path)?;
+ session.edit("New folder", |session| {
+ session.pkg.folders.push(path.clone());
+ Ok(json!({"folder": path}))
+ })
+}
+
+fn source<'a>(session: &Session, parameters: &'a Value) -> Result<&'a str> {
+ let path = strp(parameters, "folder").filter(|path| !path.is_empty()).ok_or_else(|| bad("folder", "folder is required"))?;
+ folder_path::require(&session.pkg, path)?;
+ Ok(path)
+}
+
+fn rename(session: &mut Session, parameters: &Value) -> Result {
+ let old = source(session, parameters)?;
+ let name = folder_path::name(strp(parameters, "name").ok_or_else(|| bad("folder.rename", "name is required"))?)?;
+ let parent = old.rsplit_once('/').map_or("", |(parent, _)| parent);
+ relocate_folder(session, old, &folder_path::join(parent, name))
+}
+
+fn relocate_folder(session: &mut Session, old: &str, new: &str) -> Result {
+ folder_path::validate(new)?;
+ if old == new {
+ return Ok(json!({"folder": new}));
+ }
+ if folder_path::contains(old, new)
+ || session.pkg.folder_paths().contains(new)
+ || session.pkg.graphs.iter().any(|graph| graph.sbs_path() == new)
+ || session.pkg.resources.iter().any(|resource| resource.sbs_path() == new)
+ {
+ return Err(bad("folder", "the destination already exists or is inside the source folder"));
+ }
+
+ let replace = |path: &str| format!("{new}{}", path.strip_prefix(old).unwrap_or(""));
+ let folders = session.pkg.folder_paths().into_iter().map(|path| if folder_path::contains(old, &path) { replace(&path) } else { path }).collect::>();
+ for folder in &folders {
+ folder_path::validate(folder)?;
+ }
+ let paths = session
+ .pkg
+ .graphs
+ .iter()
+ .filter(|graph| folder_path::contains(old, &graph.folder))
+ .map(|graph| (graph.sbs_path(), folder_path::join(&replace(&graph.folder), &graph.name)))
+ .collect();
+ let names = crate::graph_references::with_leaf_names(&session.pkg, &paths);
+ session.edit("Move or rename folder", |session| {
+ for graph in &mut session.pkg.graphs {
+ if folder_path::contains(old, &graph.folder) {
+ graph.folder = replace(&graph.folder);
+ }
+ }
+ session.pkg.folders = folders;
+ for resource in &mut session.pkg.resources {
+ if folder_path::contains(old, &resource.folder) {
+ resource.folder = replace(&resource.folder);
+ }
+ }
+ crate::graph_references::remap(&mut session.pkg, &names);
+ Ok(json!({"folder": new}))
+ })
+}
+
+fn remove(session: &mut Session, parameters: &Value) -> Result {
+ let folder = source(session, parameters)?;
+ session.edit("Remove folder", |session| {
+ session.pkg.folders = session.pkg.folder_paths().into_iter().filter(|path| !folder_path::contains(folder, path)).collect();
+ let indices: Vec<_> =
+ session.pkg.graphs.iter().enumerate().filter(|(_, graph)| folder_path::contains(folder, &graph.folder)).map(|(index, _)| index).collect();
+ for index in indices.into_iter().rev() {
+ session.pkg.graphs.remove(index);
+ session.material_preview.remove_graph(index);
+ if index < session.graph {
+ session.graph -= 1;
+ }
+ }
+ session.pkg.resources.retain(|resource| !folder_path::contains(folder, &resource.folder));
+ session.graph = session.graph.min(session.pkg.graphs.len().saturating_sub(1));
+ session.selection.clear();
+ session.annotation_selection = None;
+ session.view2d.node = None;
+ session.clear_preview_results();
+ Ok(Value::Null)
+ })
+}
+
+fn move_item(session: &mut Session, parameters: &Value) -> Result {
+ let parent = strp(parameters, "parent").unwrap_or("");
+ folder_path::require(&session.pkg, parent)?;
+ if let Some(index) = parameters.get("graph").and_then(Value::as_u64).and_then(|index| usize::try_from(index).ok()) {
+ let graph = session.pkg.graph(index)?;
+ let new = folder_path::join(parent, &graph.name);
+ if graph.folder == parent {
+ return Ok(json!({"graph": index}));
+ }
+ if session.pkg.graphs.iter().any(|graph| graph.sbs_path() == new)
+ || session.pkg.folder_paths().contains(&new)
+ || session.pkg.resources.iter().any(|resource| resource.sbs_path() == new)
+ {
+ return Err(bad("explorer.move", "the destination already contains an item with this name"));
+ }
+
+ let paths = [(graph.sbs_path(), new)].into();
+ let names = crate::graph_references::with_leaf_names(&session.pkg, &paths);
+ return session.edit("Move graph", |session| {
+ session.pkg.folders = session.pkg.folder_paths().into_iter().collect();
+ session.pkg.graph_mut(index)?.folder = parent.into();
+ crate::graph_references::remap(&mut session.pkg, &names);
+ Ok(json!({"graph": index}))
+ });
+ }
+
+ let old = source(session, parameters)?;
+ let name = old.rsplit('/').next().unwrap_or(old);
+ relocate_folder(session, old, &folder_path::join(parent, name))
+}
diff --git a/crates/engine/src/folder_path.rs b/crates/engine/src/folder_path.rs
new file mode 100644
index 00000000..673c71ba
--- /dev/null
+++ b/crates/engine/src/folder_path.rs
@@ -0,0 +1,63 @@
+use crate::{Result, commands::bad};
+use materialcraft_core::Package;
+
+pub(crate) fn name(value: &str) -> Result<&str> {
+ let value = value.trim();
+ if value.is_empty() || value.len() > 256 || matches!(value, "." | "..") || value.contains(['/', '\\']) || value.chars().any(char::is_control) {
+ return Err(bad("explorer", "names must be nonempty, at most 256 bytes, and contain no path separators or control characters"));
+ }
+ Ok(value)
+}
+
+pub(crate) fn validate(path: &str) -> Result<()> {
+ if path.len() > 4096 || path.split('/').count() > 64 {
+ return Err(bad("explorer", "folder paths must be at most 4096 bytes and 64 levels deep"));
+ }
+ if !path.is_empty() {
+ for component in path.split('/') {
+ if name(component)? != component {
+ return Err(bad("explorer", "folder names cannot start or end with whitespace"));
+ }
+ }
+ }
+ Ok(())
+}
+
+pub(crate) fn require(package: &Package, path: &str) -> Result<()> {
+ validate(path)?;
+ if !path.is_empty() && !package.folder_paths().contains(path) {
+ return Err(bad("explorer", format!("no folder `{path}`")));
+ }
+ Ok(())
+}
+
+pub(crate) fn join(parent: &str, name: &str) -> String {
+ if parent.is_empty() { name.into() } else { format!("{parent}/{name}") }
+}
+
+pub(crate) fn contains(parent: &str, path: &str) -> bool {
+ path == parent || path.strip_prefix(parent).is_some_and(|suffix| suffix.starts_with('/'))
+}
+
+pub(crate) fn unique(package: &Package, parent: &str, base: &str) -> String {
+ let occupied = package.folder_paths();
+ let free = |name: &str| {
+ !occupied.contains(&join(parent, name))
+ && !package.graphs.iter().any(|graph| graph.folder == parent && graph.name == name)
+ && !package.resources.iter().any(|resource| resource.folder == parent && resource.name == name)
+ };
+ if free(base) {
+ return base.to_string();
+ }
+
+ let numbered = base.rsplit_once('_').and_then(|(stem, number)| number.parse::().ok().map(|number| (stem, number)));
+ // One more candidate than occupied items guarantees a free name without an unbounded search
+ let attempts = occupied.len().saturating_add(package.graphs.len()).saturating_add(package.resources.len()).saturating_add(1);
+ (1..=attempts)
+ .map(|index| match numbered.and_then(|(stem, number)| number.checked_add(index as u64).map(|next| (stem, next))) {
+ Some((stem, next)) => format!("{stem}_{next}"),
+ None => format!("{base}_{index}"),
+ })
+ .find(|candidate| free(candidate))
+ .unwrap_or_else(|| base.to_string())
+}
diff --git a/crates/engine/src/function_edit.rs b/crates/engine/src/function_edit.rs
index e1716e78..abd03406 100644
--- a/crates/engine/src/function_edit.rs
+++ b/crates/engine/src/function_edit.rs
@@ -42,6 +42,8 @@ impl FunctionEdit {
let definition = materialcraft_nodes::function::definition(operation).ok_or("unknown function operation")?;
let id = graph.next_id();
graph.nodes.push(FunctionNode {
+ missing: None,
+ missing_data: String::new(),
instance: None,
source: None,
id,
@@ -84,7 +86,7 @@ impl FunctionEdit {
}
Self::Value { id, value } => {
let node = graph.nodes.iter_mut().find(|node| node.id == *id).ok_or("missing function node")?;
- if node.value.is_none() {
+ if node.value.is_none() || node.missing.is_some() {
return Err("the operation has no editable value".into());
}
diff --git a/crates/engine/src/function_graph_target.rs b/crates/engine/src/function_graph_target.rs
index 883355ad..5e7f8c1f 100644
--- a/crates/engine/src/function_graph_target.rs
+++ b/crates/engine/src/function_graph_target.rs
@@ -23,6 +23,10 @@ pub enum FunctionGraphTarget {
}
impl FunctionGraphTarget {
+ pub fn variables(&self, session: &Session, id: u32) -> Result> {
+ crate::function_variables::suggestions(self, session, id)
+ }
+
pub fn available_operations(&self, session: &Session) -> impl Iterator
- + use<> {
let value_processor = matches!(self, Self::Parameter { node, parameter }
if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "value_processor"));
diff --git a/crates/engine/src/function_library.rs b/crates/engine/src/function_library.rs
new file mode 100644
index 00000000..ad55a8b1
--- /dev/null
+++ b/crates/engine/src/function_library.rs
@@ -0,0 +1,21 @@
+use materialcraft_core::Package;
+use std::{collections::BTreeMap, sync::Arc};
+
+pub(crate) const STANDARD_PACKAGE: &str = "sbs://functions.sbs";
+
+pub(crate) struct FunctionLibrary {
+ pub packages: BTreeMap>,
+ pub warnings: Vec,
+}
+
+pub(crate) fn load() -> Result {
+ let bytes = materialcraft_formats::sbs::library::read(STANDARD_PACKAGE)?;
+ let mut read =
+ materialcraft_formats::sbs::read_sbs(&bytes, STANDARD_PACKAGE, &crate::file_cmds::linked_files(STANDARD_PACKAGE)).map_err(|error| error.to_string())?;
+ crate::linked_files::normalize_references(&mut read.pkg, STANDARD_PACKAGE);
+ read.warnings.extend(crate::linked_files::load(&mut read.pkg));
+
+ let mut packages = std::mem::take(&mut read.pkg.dependencies);
+ packages.insert(STANDARD_PACKAGE.into(), Arc::new(read.pkg));
+ Ok(FunctionLibrary { packages, warnings: read.warnings })
+}
diff --git a/crates/engine/src/function_library_commands.rs b/crates/engine/src/function_library_commands.rs
new file mode 100644
index 00000000..785db1e9
--- /dev/null
+++ b/crates/engine/src/function_library_commands.rs
@@ -0,0 +1,62 @@
+use crate::{
+ Result, Session, cmd,
+ commands::{CommandSpec, always, strp},
+};
+use serde_json::{Value, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![
+ cmd!("library.functions", "List library functions", [], None, "{filter?} lists reusable SBS functions with source paths and interfaces", always, list),
+ cmd!(
+ "library.function.add",
+ "Add library function",
+ [],
+ None,
+ "{graph, package? (sbs://functions.sbs), function?: FunctionGraphTarget, at?, snapToGrid?} adds a function instance to the active Function or processor canvas",
+ crate::commands::has_graph,
+ add
+ ),
+ ]
+}
+
+fn list(session: &mut Session, parameters: &Value) -> Result {
+ let filter = strp(parameters, "filter").unwrap_or("").to_lowercase();
+ let mut entries = Vec::new();
+ for (path, package) in &session.pkg.dependencies {
+ if !path.starts_with("sbs://") {
+ continue;
+ }
+
+ for graph in &package.graphs {
+ let Some(function) = &graph.function else { continue };
+ let identifier = graph.sbs_path();
+ if !filter.is_empty() && !identifier.to_lowercase().contains(&filter) && !graph.display_name().to_lowercase().contains(&filter) {
+ continue;
+ }
+
+ let ports = materialcraft_nodes::function::graph_ports(graph);
+ let error = ports.as_ref().err().cloned();
+ let (inputs, outputs) = ports.unwrap_or_default();
+ let category = if graph.attributes.category.is_empty() { &graph.folder } else { &graph.attributes.category };
+ entries.push(json!({"package": path, "graph": identifier, "label": graph.display_name(),
+ "category": category, "description": graph.attributes.description,
+ "inputs": inputs, "outputs": outputs, "error": error,
+ "missing": function.output.is_none() || function.nodes.iter().any(|node| node.missing.is_some())}));
+ }
+ }
+ Ok(json!(entries))
+}
+
+fn add(session: &mut Session, parameters: &Value) -> Result {
+ let mut parameters = parameters.clone();
+ let object = parameters.as_object_mut().ok_or_else(|| crate::commands::bad("library.function.add", "expected an object"))?;
+ object.entry("package").or_insert_with(|| json!(crate::function_library::STANDARD_PACKAGE));
+
+ let package = strp(¶meters, "package").and_then(|path| session.pkg.dependencies.get(path));
+ let graph = strp(¶meters, "graph").and_then(|name| package?.graph_by_name(name));
+ if graph.is_none_or(|(_, graph)| graph.function.is_none()) {
+ return Err(crate::commands::bad("library.function.add", "the library function is unavailable"));
+ }
+
+ crate::graph_instance_commands::add(session, ¶meters)
+}
diff --git a/crates/engine/src/function_variable.rs b/crates/engine/src/function_variable.rs
new file mode 100644
index 00000000..4d508991
--- /dev/null
+++ b/crates/engine/src/function_variable.rs
@@ -0,0 +1,10 @@
+use materialcraft_core::ValueType;
+use serde::Serialize;
+
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FunctionVariable {
+ pub name: String,
+ pub value_type: ValueType,
+ pub system: bool,
+}
diff --git a/crates/engine/src/function_variable_commands.rs b/crates/engine/src/function_variable_commands.rs
new file mode 100644
index 00000000..4c007536
--- /dev/null
+++ b/crates/engine/src/function_variable_commands.rs
@@ -0,0 +1,25 @@
+use crate::{
+ FunctionGraphTarget, Result, Session, cmd,
+ commands::{CommandSpec, bad, has_graph},
+};
+use serde_json::{Value as Json, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![cmd!(
+ "graph.function.variables",
+ "List function variables",
+ [],
+ None,
+ "{id, target?: FunctionGraphTarget} lists variable suggestions matching the selected Get node's type and caller context",
+ has_graph,
+ variables
+ )]
+}
+
+fn variables(session: &mut Session, parameters: &Json) -> Result {
+ let command = "graph.function.variables";
+ let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"})))
+ .map_err(|error| bad(command, error.to_string()))?;
+ let id = parameters.get("id").and_then(Json::as_u64).and_then(|id| u32::try_from(id).ok()).ok_or_else(|| bad(command, "id must be a function node id"))?;
+ Ok(json!({"variables": target.variables(session, id)?}))
+}
diff --git a/crates/engine/src/function_variables.rs b/crates/engine/src/function_variables.rs
new file mode 100644
index 00000000..676f607b
--- /dev/null
+++ b/crates/engine/src/function_variables.rs
@@ -0,0 +1,72 @@
+use std::collections::BTreeMap;
+
+use materialcraft_core::{Value, ValueType};
+use materialcraft_nodes::function::{FunctionScope, SystemVariable, node_types};
+
+use crate::{FunctionGraphTarget, FunctionVariable, Result, Session, commands::bad};
+
+fn variable_scope(target: &FunctionGraphTarget, session: &Session) -> FunctionScope {
+ match target {
+ FunctionGraphTarget::Pattern { .. } => FunctionScope::FxMap,
+ FunctionGraphTarget::Parameter { node, parameter }
+ if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "pixel_processor") =>
+ {
+ FunctionScope::PixelProcessor
+ }
+ _ => FunctionScope::Node,
+ }
+}
+
+/// Suggestions preserve typed names, even while a graph is being assembled.
+pub(crate) fn suggestions(target: &FunctionGraphTarget, session: &Session, id: u32) -> Result> {
+ let command = "graph.function.variables";
+ let function = target.current(session)?;
+ let node = function.node(id).ok_or_else(|| bad(command, "missing function node"))?;
+ if !node.op.starts_with("get_") && node.op != "isdefined" {
+ return Err(bad(command, "select a Get or Is Defined node"));
+ }
+
+ let types = node_types(function).map_err(|error| bad(command, error))?;
+ let expected = (node.op != "isdefined").then(|| types.get(&id).and_then(|code| ValueType::from_code(*code))).flatten();
+ let scope = variable_scope(target, session);
+ let mut variables: Vec<_> = SystemVariable::ALL
+ .into_iter()
+ .filter(|variable| variable.available_in(scope) && expected.is_none_or(|expected| expected == variable.value_type()))
+ .map(|variable| FunctionVariable { name: variable.name().into(), value_type: variable.value_type(), system: true })
+ .collect();
+
+ let document = session.graph()?;
+ let mut custom = BTreeMap::new();
+ for input in &document.exposed {
+ if let Some(value_type) = ValueType::of(&input.default) {
+ custom.insert(input.id.clone(), value_type);
+ }
+ }
+
+ let owner = match target {
+ FunctionGraphTarget::Parameter { node, .. } | FunctionGraphTarget::Dynamic { node, .. } => Some(*node),
+ FunctionGraphTarget::Pattern { owner, .. } => Some(*owner),
+ FunctionGraphTarget::Graph => None,
+ };
+ if let Some(owner) = owner {
+ custom.extend(document.node(owner)?.input_values.iter().map(|(name, value_type)| (name.clone(), *value_type)));
+ }
+
+ for candidate in &function.nodes {
+ if (candidate.op.starts_with("get_") || candidate.op == "set")
+ && let Some(Value::Text(name)) = &candidate.value
+ && let Some(value_type) = types.get(&candidate.id).and_then(|code| ValueType::from_code(*code))
+ && expected.is_none_or(|expected| expected == value_type)
+ {
+ custom.entry(name.clone()).or_insert(value_type);
+ }
+ }
+
+ variables.extend(
+ custom
+ .into_iter()
+ .filter(|(name, value_type)| !name.is_empty() && SystemVariable::named(name).is_none() && expected.is_none_or(|expected| expected == *value_type))
+ .map(|(name, value_type)| FunctionVariable { name, value_type, system: false }),
+ );
+ Ok(variables)
+}
diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs
index 975bdae8..f6dcdd42 100644
--- a/crates/engine/src/graph_cmds.rs
+++ b/crates/engine/src/graph_cmds.rs
@@ -10,20 +10,26 @@ use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec {
vec![
cmd!("graph.open", "Open graph", [], None, "{graph: index or name}", always, open),
- cmd!("graph.rename", "Rename graph", [], None, "{name, graph?}", has_graph, rename),
cmd!("graph.delete", "Delete graph", [], None, "{graph?}", has_graph, delete),
cmd!("graph.duplicate", "Duplicate graph", [], None, "{graph?}", has_graph, duplicate),
- cmd!("graph.size", "Graph size", [], None, "{width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", has_graph, size),
- cmd!("graph.seed", "Random seed", [], None, "{seed}", has_graph, |s, p| {
+ cmd!("graph.size", "Graph size", [], None, "{graph?, document?, width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", always, size),
+ cmd!("graph.seed", "Random seed", [], None, "{seed, graph?, document?}", always, |s, p| {
let seed = i64p(p, "seed").ok_or_else(|| bad("graph.seed", "`seed` is required"))?.clamp(0, i32::MAX as i64) as i32;
- s.edit_merged("graph.seed", "Random seed", |s| {
- s.graph_mut()?.seed = seed;
+ let target = crate::GraphTarget::resolve(s, p)?;
+ if target.document != s.document_id {
+ return target.edit(s, "Random seed", |package| {
+ package.graph_mut(target.graph)?.seed = seed;
+ Ok(J::Null)
+ });
+ }
+
+ s.edit_merged(&format!("graph.seed:{}:{}", target.document, target.graph), "Random seed", |s| {
+ s.pkg.graph_mut(target.graph)?.seed = seed;
Ok(J::Null)
})
}),
- cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32}", has_graph, format),
+ cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32, graph?, document?}", always, format),
cmd!("graph.cook", "Compute graph", [], None, "{full?: bool} cooks now; returns per-node timings and errors", has_graph, cook),
- cmd!("graph.attributes", "Graph attributes", [], None, "{category?, description?, author?, tags?}", has_graph, attributes),
cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, at? [x, y]}", has_graph, pin_add),
cmd!("graph.pin.delete", "Delete pin", [], None, "{id}", has_graph, pin_delete),
cmd!(
@@ -86,34 +92,10 @@ fn open(s: &mut Session, p: &J) -> Result {
Ok(json!({"graph": i, "name": s.pkg.graphs.get(i).map(|g| g.name.clone())}))
}
-fn rename(s: &mut Session, p: &J) -> Result {
- let i = graph_index(s, p)?;
- let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("graph.rename", "`name` is required"))?.to_string();
- if s.pkg.graphs.iter().enumerate().any(|(j, g)| j != i && g.name == name) {
- return Err(bad("graph.rename", format!("a graph is already called `{name}`")));
- }
- s.edit("Rename graph", |s| {
- let old = std::mem::replace(&mut s.pkg.graph_mut(i)?.name, name.clone());
- // Instances follow the rename
- for g in &mut s.pkg.graphs {
- for instance in g.instances_mut() {
- if instance.package.is_empty() && instance.graph == old {
- instance.graph = name.clone();
- }
- }
- for n in g.nodes.iter_mut().filter(|n| n.def == "graph_instance") {
- if n.params.get("graph") == Some(&Value::Text(old.clone())) {
- n.params.insert("graph".into(), Value::Text(name.clone()));
- }
- }
- }
- Ok(json!({"name": name}))
- })
-}
-
fn delete(s: &mut Session, p: &J) -> Result {
let i = graph_index(s, p)?;
s.edit("Delete graph", |s| {
+ s.pkg.folders = s.pkg.folder_paths().into_iter().collect();
s.pkg.graphs.remove(i);
if i < s.graph {
s.graph -= 1;
@@ -145,6 +127,7 @@ fn duplicate(s: &mut Session, p: &J) -> Result {
}
fn size(s: &mut Session, p: &J) -> Result {
+ let target = crate::GraphTarget::resolve(s, p)?;
let log = |px: u64| 63 - px.clamp(1, 1 << 20).leading_zeros();
let (w, h) = if let Some(a) = p.get("log2").and_then(J::as_array) {
(a.first().and_then(J::as_u64).unwrap_or(10) as u32, a.get(1).and_then(J::as_u64).unwrap_or(10) as u32)
@@ -154,13 +137,14 @@ fn size(s: &mut Session, p: &J) -> Result {
};
let (w, h) = (w.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2), h.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2));
- s.edit("Graph size", |s| {
- s.graph_mut()?.size = [w, h];
+ target.edit(s, "Graph size", |package| {
+ package.graph_mut(target.graph)?.size = [w, h];
Ok(json!({"width": 1u32 << w, "height": 1u32 << h}))
})
}
fn format(s: &mut Session, p: &J) -> Result {
+ let target = crate::GraphTarget::resolve(s, p)?;
let f = match strp(p, "format") {
Some("u8" | "8") => OutputFormat::U8,
Some("u16" | "16") => OutputFormat::U16,
@@ -169,8 +153,8 @@ fn format(s: &mut Session, p: &J) -> Result {
_ => return Err(bad("graph.format", "`format` is u8, u16, f16 or f32")),
};
- s.edit("Output format", |s| {
- s.graph_mut()?.format = f;
+ target.edit(s, "Output format", |package| {
+ package.graph_mut(target.graph)?.format = f;
Ok(J::Null)
})
}
@@ -188,18 +172,6 @@ fn cook(s: &mut Session, p: &J) -> Result {
}))
}
-fn attributes(s: &mut Session, p: &J) -> Result {
- s.edit("Graph attributes", |s| {
- let a = &mut s.graph_mut()?.attributes;
- for (k, slot) in [("category", &mut a.category), ("description", &mut a.description), ("author", &mut a.author), ("tags", &mut a.tags)] {
- if let Some(v) = strp(p, k) {
- *slot = v.into();
- }
- }
- Ok(J::Null)
- })
-}
-
/// Graph-space bounding rect of nodes `ids` (node cards are about 96×110)
pub fn nodes_rect(s: &Session, ids: &[NodeId]) -> Option<[f32; 4]> {
let g = s.graph().ok()?;
diff --git a/crates/engine/src/graph_instance_commands.rs b/crates/engine/src/graph_instance_commands.rs
index 20a3f54f..5614fb8c 100644
--- a/crates/engine/src/graph_instance_commands.rs
+++ b/crates/engine/src/graph_instance_commands.rs
@@ -65,7 +65,7 @@ fn reaches(
false
}
-fn add(session: &mut Session, parameters: &Value) -> Result {
+pub(crate) fn add(session: &mut Session, parameters: &Value) -> Result {
if parameters.get("pattern").is_some() {
return Err(bad(COMMAND, "FX-Map graphs do not accept graph instances"));
}
@@ -79,10 +79,20 @@ fn add(session: &mut Session, parameters: &Value) -> Result {
if let Some(target) = &target {
target.current(session)?;
}
- let document = u64p(parameters, "document").ok_or_else(|| bad(COMMAND, "document is required"))?;
let name = strp(parameters, "graph").ok_or_else(|| bad(COMMAND, "graph is required"))?;
let packages = session.open_packages();
- let (_, source, path, _) = packages.iter().find(|entry| entry.0 == document).copied().ok_or_else(|| bad(COMMAND, "the source package is not open"))?;
+ let document = u64p(parameters, "document");
+ let (source, path) = if let Some(path) = strp(parameters, "package") {
+ if !path.starts_with("sbs://") {
+ return Err(bad(COMMAND, "library instances require an sbs:// package"));
+ }
+
+ (session.pkg.dependencies.get(path).map(AsRef::as_ref).ok_or_else(|| bad(COMMAND, "the library package is missing"))?, Some(path))
+ } else {
+ let document = document.ok_or_else(|| bad(COMMAND, "document is required"))?;
+ let (_, source, path, _) = packages.iter().find(|entry| entry.0 == document).copied().ok_or_else(|| bad(COMMAND, "the source package is not open"))?;
+ (source, path)
+ };
let (_, graph) = source.graph_by_name(name).ok_or_else(|| bad(COMMAND, "the source graph no longer exists"))?;
if graph.function.is_some() != target.is_some() {
return Err(bad(COMMAND, "Function instances require a Function canvas; main instances require a main graph"));
@@ -100,17 +110,18 @@ fn add(session: &mut Session, parameters: &Value) -> Result {
return Err(bad(COMMAND, "source connector identifiers must be unique"));
}
}
- let file = if document == session.document_id {
+ let file = if document == Some(session.document_id) && parameters.get("package").is_none() {
""
} else {
path.ok_or_else(|| bad(COMMAND, "save the source SBS file before instancing its graph in another package"))?
};
- let source_file = path.map(str::to_string).unwrap_or_else(|| format!("unsaved:{document}"));
+ let source_file = path.map(str::to_string).unwrap_or_else(|| format!("unsaved:{}", document.unwrap_or(session.document_id)));
let target_file = session.path.clone().unwrap_or_else(|| format!("unsaved:{}", session.document_id));
- if reaches(source, &source_file, name, &target_file, &session.graph()?.name, &session.pkg.dependencies) {
+ if reaches(source, &source_file, &graph.sbs_path(), &target_file, &session.graph()?.sbs_path(), &session.pkg.dependencies) {
return Err(bad(COMMAND, "the instance would create a graph dependency cycle"));
}
- let instance = GraphInstance { package: file.into(), graph: name.into(), inputs, outputs };
+ let instance =
+ GraphInstance { label: graph.display_name().into(), defaults: Default::default(), package: file.into(), graph: graph.sbs_path(), inputs, outputs };
let at =
crate::graph_grid::snap_position(point(parameters, "at").unwrap_or([0.0; 2]), parameters.get("snapToGrid").and_then(Value::as_bool).unwrap_or(false));
session.edit("Add graph instance", |session| {
@@ -122,6 +133,8 @@ fn add(session: &mut Session, parameters: &Value) -> Result {
let id = function.next_id();
function.nodes.push(materialcraft_core::FunctionNode {
id,
+ missing: None,
+ missing_data: String::new(),
op: "instance".into(),
type_code: instance.outputs.first().map_or(0, |port| port.type_code),
inputs: vec![None; instance.inputs.len()],
diff --git a/crates/engine/src/graph_property_commands.rs b/crates/engine/src/graph_property_commands.rs
new file mode 100644
index 00000000..018d417d
--- /dev/null
+++ b/crates/engine/src/graph_property_commands.rs
@@ -0,0 +1,72 @@
+use crate::{
+ GraphTarget, Result, Session, cmd,
+ commands::{CommandSpec, always, bad, strp},
+};
+use serde_json::{Value, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![
+ cmd!("graph.rename", "Rename graph", [], None, "{name, graph?, document?}", always, rename),
+ cmd!("graph.properties", "Inspect graph properties", [], None, "{graph?, document?}", always, |session, parameters| {
+ let target = GraphTarget::resolve(session, parameters)?;
+ let graph = target.get(session)?;
+ Ok(json!({"document": target.document, "graph": target.graph, "identifier": graph.name, "attributes": graph.attributes}))
+ }),
+ cmd!(
+ "graph.attributes",
+ "Graph attributes",
+ [],
+ None,
+ "{graph?, document?, label?, category?, description?, author?, authorUrl?, tags?, group?, userData?}",
+ always,
+ attributes
+ ),
+ ]
+}
+
+fn attributes(session: &mut Session, parameters: &Value) -> Result {
+ let target = GraphTarget::resolve(session, parameters)?;
+ target.edit(session, "Graph attributes", |package| {
+ let attributes = &mut package.graph_mut(target.graph)?.attributes;
+ for (key, slot) in [
+ ("label", &mut attributes.label),
+ ("category", &mut attributes.category),
+ ("description", &mut attributes.description),
+ ("author", &mut attributes.author),
+ ("authorUrl", &mut attributes.author_url),
+ ("tags", &mut attributes.tags),
+ ("group", &mut attributes.group),
+ ("userData", &mut attributes.user_data),
+ ] {
+ if let Some(value) = parameters.get(key) {
+ *slot = value.as_str().ok_or_else(|| bad("graph.attributes", format!("`{key}` must be text")))?.into();
+ }
+ }
+ Ok(Value::Null)
+ })
+}
+
+fn rename(session: &mut Session, parameters: &Value) -> Result {
+ let target = GraphTarget::resolve(session, parameters)?;
+ let index = target.graph;
+ let package = target.package(session)?;
+ let name = strp(parameters, "name").map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| bad("graph.rename", "`name` is required"))?.to_string();
+ let source = package.graph(index)?;
+ if package.graphs.iter().enumerate().any(|(other, graph)| other != index && graph.folder == source.folder && graph.name == name) {
+ return Err(bad("graph.rename", format!("a graph is already called `{name}`")));
+ }
+
+ crate::folder_path::name(&name)?;
+ let new_path = crate::folder_path::join(&source.folder, &name);
+ if package.folder_paths().contains(&new_path) || package.resources.iter().any(|resource| resource.sbs_path() == new_path) {
+ return Err(bad("graph.rename", "a folder or resource already has that name"));
+ }
+
+ let paths = [(source.sbs_path(), new_path)].into();
+ let names = crate::graph_references::with_leaf_names(package, &paths);
+ target.edit(session, "Rename graph", |package| {
+ package.graph_mut(index)?.name = name.clone();
+ crate::graph_references::remap(package, &names);
+ Ok(json!({"name": name}))
+ })
+}
diff --git a/crates/engine/src/graph_references.rs b/crates/engine/src/graph_references.rs
new file mode 100644
index 00000000..f95cea2a
--- /dev/null
+++ b/crates/engine/src/graph_references.rs
@@ -0,0 +1,34 @@
+use materialcraft_core::{Package, Value};
+use std::collections::BTreeMap;
+
+pub(crate) fn with_leaf_names(package: &Package, paths: &BTreeMap) -> BTreeMap {
+ let mut names = paths.clone();
+ for (old, new) in paths {
+ let leaf = old.rsplit('/').next().unwrap_or(old);
+ if package.graph_by_name(leaf).is_some_and(|(_, graph)| graph.sbs_path() == *old) {
+ names.entry(leaf.into()).or_insert_with(|| new.clone());
+ }
+ }
+ names
+}
+
+pub(crate) fn remap(package: &mut Package, names: &BTreeMap) {
+ for graph in &mut package.graphs {
+ for instance in graph.instances_mut() {
+ if instance.package.is_empty()
+ && let Some(new) = names.get(&instance.graph)
+ {
+ instance.graph = new.clone();
+ }
+ }
+ for node in
+ graph.nodes.iter_mut().filter(|node| node.def == "graph_instance" && node.instance.as_ref().is_none_or(|instance| instance.package.is_empty()))
+ {
+ if let Some(Value::Text(old)) = node.params.get_mut("graph")
+ && let Some(new) = names.get(old)
+ {
+ *old = new.clone();
+ }
+ }
+ }
+}
diff --git a/crates/engine/src/graph_target.rs b/crates/engine/src/graph_target.rs
new file mode 100644
index 00000000..ef47fab4
--- /dev/null
+++ b/crates/engine/src/graph_target.rs
@@ -0,0 +1,56 @@
+use crate::{Result, Session, commands::bad};
+use materialcraft_core::{Graph, Package};
+use serde_json::Value;
+
+/// A graph being inspected, independent of the active canvas
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct GraphTarget {
+ pub document: u64,
+ pub graph: usize,
+}
+
+impl GraphTarget {
+ pub fn active(session: &Session) -> Self {
+ Self { document: session.document_id, graph: session.graph }
+ }
+
+ pub(crate) fn resolve(session: &Session, parameters: &Value) -> Result {
+ let document = match parameters.get("document") {
+ None | Some(Value::Null) => session.document_id,
+ Some(value) => value.as_u64().ok_or_else(|| bad("graph", "`document` must be an open document id"))?,
+ };
+ let mut target = Self { document, graph: session.graph };
+ let package = target.package(session)?;
+ target.graph = match parameters.get("graph") {
+ None | Some(Value::Null) if document == session.document_id => session.graph,
+ None | Some(Value::Null) => session.documents.get(&document).map_or(0, |document| document.graph),
+ Some(Value::String(name)) => package.graph_by_name(name).map(|(index, _)| index).ok_or_else(|| bad("graph", format!("no graph `{name}`")))?,
+ Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph", "`graph` must be an index or name"))?,
+ };
+ target.get(session)?;
+ Ok(target)
+ }
+
+ pub fn package(self, session: &Session) -> Result<&Package> {
+ if self.document == session.document_id {
+ return Ok(&session.pkg);
+ }
+
+ session.documents.get(&self.document).map(|document| &document.pkg).ok_or_else(|| bad("graph", "the inspected package is no longer open"))
+ }
+
+ pub fn get(self, session: &Session) -> Result<&Graph> {
+ Ok(self.package(session)?.graph(self.graph)?)
+ }
+
+ pub(crate) fn edit(self, session: &mut Session, label: &str, edit: impl FnOnce(&mut Package) -> Result) -> Result {
+ if self.document == session.document_id {
+ return session.edit(label, |session| edit(&mut session.pkg));
+ }
+
+ let document = session.documents.get_mut(&self.document).ok_or_else(|| bad("graph", "the inspected package is no longer open"))?;
+ let result = document.edit(label, edit)?;
+ session.refresh_links();
+ Ok(result)
+ }
+}
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs
index 4e489f01..9f4d272b 100644
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@ -9,9 +9,10 @@ pub fn session(s: &Session, graph: Option) -> J {
let g = s.pkg.graphs.get(gi);
let cooked = (gi == s.graph).then_some(&s.cooked);
let graph_json = g.map(|g| {
- json!({
+ let mut result = json!({
"index": gi,
"name": g.name,
+ "path": g.sbs_path(),
"kind": g.kind(),
"function": g.function,
"functionWarnings": crate::function_inspection::warnings(g).into_iter().map(|(target, messages)| json!({"target": target, "messages": messages})).collect::>(),
@@ -54,12 +55,18 @@ pub fn session(s: &Session, graph: Option) -> J {
"frames": g.frames,
"comments": g.comments,
"pins": g.pins,
- })
+ });
+ result["physicalSize"] = json!(g.physical_size);
+ result["pixelRatio"] = json!(g.pixel_ratio);
+ result["pixelRatioMode"] = json!(g.pixel_ratio_mode);
+ result["tiling"] = json!(g.tiling);
+ result["tilingMode"] = json!(g.tiling_mode);
+ result
});
json!({
"documents": s.inspect_documents(),
- "package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "warnings": s.load_warnings, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "bytes": r.bytes.len()})).collect::>()},
- "graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "nodes": g.nodes.len(), "kind": g.kind()})).collect::>(),
+ "package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "folders": s.pkg.folder_paths(), "warnings": s.load_warnings, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "bytes": r.bytes.len()})).collect::>()},
+ "graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "path": g.sbs_path(), "nodes": g.nodes.len(), "kind": g.kind()})).collect::>(),
"openGraph": s.graph,
"graph": graph_json,
"annotationSelection": s.annotation_selection,
@@ -75,6 +82,7 @@ pub fn session(s: &Session, graph: Option) -> J {
},
"previewSize": s.preview_size,
"camera": s.camera,
+ "environment": s.environment,
"cookMs": s.cooked.ms,
"dirty": s.dirty,
"history": s.history(),
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 8b591f14..dfd2831c 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -2,15 +2,30 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod document_path;
+mod evaluation_environment_commands;
+mod explorer_clipboard;
+mod explorer_clipboard_commands;
+mod folder_commands;
+mod folder_path;
+pub use explorer_clipboard::ExplorerClipboard;
+mod function_library;
+mod function_library_commands;
+mod function_variable;
+mod function_variable_commands;
+mod function_variables;
+pub use function_variable::FunctionVariable;
mod graph_instance_commands;
+mod graph_references;
mod linked_files;
mod linked_packages;
+mod linked_resource;
mod material_preview;
mod material_preview_commands;
mod material_source;
mod node_info_commands;
mod open_document;
mod package_commands;
+mod package_file_commands;
mod preview_cook;
pub use material_preview::MaterialPreview;
pub use material_source::MaterialSource;
@@ -28,6 +43,9 @@ pub mod commands;
pub mod edit_cmds;
pub mod file_cmds;
pub mod graph_cmds;
+mod graph_property_commands;
+mod graph_target;
+pub use graph_target::GraphTarget;
pub mod graph_edit;
pub mod graph_grid;
pub mod inspect;
diff --git a/crates/engine/src/linked_files.rs b/crates/engine/src/linked_files.rs
index 4de4a65d..4c4417a4 100644
--- a/crates/engine/src/linked_files.rs
+++ b/crates/engine/src/linked_files.rs
@@ -2,6 +2,12 @@ use crate::document_path;
use materialcraft_core::Package;
pub(crate) fn normalize_references(package: &mut Package, path: &str) {
+ for resource in &mut package.resources {
+ if !resource.source.is_empty() {
+ resource.source = document_path::resolve(path, &resource.source);
+ }
+ }
+
for instance in package.graphs.iter_mut().flat_map(|graph| graph.instances_mut()) {
if !instance.package.is_empty() {
instance.package = document_path::resolve(path, &instance.package);
@@ -31,7 +37,6 @@ impl crate::Session {
}
}
-#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn load(package: &mut Package) -> Vec {
use std::{collections::BTreeSet, sync::Arc};
let references = |package: &Package| {
@@ -60,23 +65,40 @@ pub(crate) fn load(package: &mut Package) -> Vec {
continue;
}
let mut read = || -> std::result::Result {
- let size = std::fs::metadata(&path).map_err(|error| error.to_string())?.len();
- if size > remaining {
- return Err("linked package exceeds the remaining file budget".into());
+ if path.starts_with("sbs://") {
+ let bytes = materialcraft_formats::sbs::library::read(&path)?;
+ if bytes.len() as u64 > remaining {
+ return Err("linked package exceeds the remaining file budget".into());
+ }
+ remaining -= bytes.len() as u64;
+ let read = materialcraft_formats::sbs::read_sbs(&bytes, &path, &crate::file_cmds::linked_files(&path)).map_err(|error| error.to_string())?;
+ warnings.extend(read.warnings);
+ return Ok(read.pkg);
}
- // Bound the read even if the file grows after the metadata check
- use std::io::Read;
- let mut bytes = Vec::new();
- std::fs::File::open(&path).map_err(|error| error.to_string())?.take(remaining + 1).read_to_end(&mut bytes).map_err(|error| error.to_string())?;
- if bytes.len() as u64 > remaining {
- return Err("linked package exceeds the remaining file budget".into());
+ #[cfg(target_arch = "wasm32")]
+ return Err("external file is unavailable in the browser".into());
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let size = std::fs::metadata(&path).map_err(|error| error.to_string())?.len();
+ if size > remaining {
+ return Err("linked package exceeds the remaining file budget".into());
+ }
+ // Bound the read even if the file grows after the metadata check
+ use std::io::Read;
+ let mut bytes = Vec::new();
+ std::fs::File::open(&path)
+ .map_err(|error| error.to_string())?
+ .take(remaining + 1)
+ .read_to_end(&mut bytes)
+ .map_err(|error| error.to_string())?;
+ if bytes.len() as u64 > remaining {
+ return Err("linked package exceeds the remaining file budget".into());
+ }
+ remaining -= bytes.len() as u64;
+ let read = materialcraft_formats::sbs::read_sbs(&bytes, &path, &crate::file_cmds::linked_files(&path)).map_err(|error| error.to_string())?;
+ warnings.extend(read.warnings);
+ Ok(read.pkg)
}
- remaining -= bytes.len() as u64;
- let read = materialcraft_formats::sbs::read_sbs(&bytes, &path, &crate::file_cmds::linked_files(&path)).map_err(|error| error.to_string())?;
- if !read.warnings.is_empty() {
- return Err(read.warnings.join("; "));
- }
- Ok(read.pkg)
};
match read() {
Ok(mut source) => {
diff --git a/crates/engine/src/linked_packages.rs b/crates/engine/src/linked_packages.rs
index 23e676fe..01fad15e 100644
--- a/crates/engine/src/linked_packages.rs
+++ b/crates/engine/src/linked_packages.rs
@@ -38,7 +38,14 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) -
return None;
}
let materialcraft_core::Value::Text(name) = node.params.get("graph")? else { return None };
- Some(GraphInstance { package: String::new(), graph: name.clone(), inputs: Vec::new(), outputs: Vec::new() })
+ Some(GraphInstance {
+ label: String::new(),
+ defaults: Default::default(),
+ package: String::new(),
+ graph: name.clone(),
+ inputs: Vec::new(),
+ outputs: Vec::new(),
+ })
})?;
let source = if instance.package.is_empty() { &*package } else { sources.get(&instance.package)?.as_ref() };
let (_, graph) = source.graph_by_name(&instance.graph)?;
@@ -63,6 +70,7 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) -
}
instance.inputs = inputs;
instance.outputs = outputs;
+ instance.label = graph.display_name().into();
(node.instance.as_ref() != Some(&instance)).then_some((graph_index, node_index, instance))
})
.collect();
diff --git a/crates/engine/src/linked_resource.rs b/crates/engine/src/linked_resource.rs
new file mode 100644
index 00000000..5d0361a2
--- /dev/null
+++ b/crates/engine/src/linked_resource.rs
@@ -0,0 +1,45 @@
+/// Read resource paths relative to an SBS package, including portable library aliases.
+pub fn reader(path: &str) -> impl Fn(&str) -> Option> + use<> {
+ let owner = path.to_string();
+ #[cfg(not(target_arch = "wasm32"))]
+ let folder = {
+ let parent = std::path::Path::new(path).parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));
+ std::fs::canonicalize(parent).ok()
+ };
+
+ move |reference: &str| {
+ if reference.starts_with("sbs://") {
+ return materialcraft_formats::sbs::library::read(reference).ok();
+ }
+
+ if owner.starts_with("sbs://") {
+ let uri = materialcraft_formats::sbs::library::resolve(&owner, reference).ok()?;
+ return materialcraft_formats::sbs::library::read(&uri).ok();
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use std::io::Read;
+ const MAX_LINKED_FILE_BYTES: u64 = 256 << 20;
+ let relative = reference.trim().replace('\\', "/");
+ let plain = !relative.is_empty() && !relative.contains(':') && !relative.starts_with('/');
+ if !plain || std::path::Path::new(&relative).components().any(|part| !matches!(part, std::path::Component::Normal(_))) {
+ return None;
+ }
+
+ let folder = folder.as_ref()?;
+ let file = std::fs::canonicalize(folder.join(&relative)).ok()?;
+ let metadata = std::fs::metadata(&file).ok()?;
+ if !file.starts_with(folder) || !metadata.is_file() || metadata.len() > MAX_LINKED_FILE_BYTES {
+ return None;
+ }
+
+ // Bound the read even if a linked file grows after the metadata check
+ let mut bytes = Vec::new();
+ std::fs::File::open(file).ok()?.take(MAX_LINKED_FILE_BYTES + 1).read_to_end(&mut bytes).ok()?;
+ (bytes.len() as u64 <= MAX_LINKED_FILE_BYTES).then_some(bytes)
+ }
+ #[cfg(target_arch = "wasm32")]
+ None
+ }
+}
diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs
index e4fb3f70..d262c674 100644
--- a/crates/engine/src/material_cmds.rs
+++ b/crates/engine/src/material_cmds.rs
@@ -66,6 +66,7 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result)> = Vec::new();
diff --git a/crates/engine/src/node_cmds.rs b/crates/engine/src/node_cmds.rs
index fbc2af9e..66a590f1 100644
--- a/crates/engine/src/node_cmds.rs
+++ b/crates/engine/src/node_cmds.rs
@@ -2,7 +2,7 @@
use serde_json::{Value as J, json};
-use materialcraft_core::{FunctionGraph, NodeId, OutputFormat, SizeMode, Value, ValueType};
+use materialcraft_core::{NodeId, OutputFormat, SizeMode, Value, ValueType};
use crate::connection_commands::connection_input;
use crate::graph_grid::snap_position;
@@ -39,7 +39,7 @@ pub(crate) fn specs() -> Vec {
"Set base parameters",
[],
None,
- "{id?, sizeMode? (relativeToInput|relativeToParent|absolute), size? [w, h] (log2 offset, or log2 size when absolute), format? (inherit|u8|u16|f16|f32), seed?, tiling? bool}",
+ "{id?, sizeMode? (relativeToInput|relativeToParent|absolute), size? [w, h] (log2 offset, or log2 size when absolute), format? (inherit|u8|u16|f16|f32), seed?, tiling?: bool|[bool,bool], pixelRatio?: 0|1, tilingMode?, pixelRatioMode? (relativeToInput|relativeToParent|absolute)}",
has_selection,
base
),
@@ -56,68 +56,69 @@ pub(crate) fn specs() -> Vec {
]
}
-fn add(s: &mut Session, p: &J) -> Result {
- if s.graph()?.function.is_some() {
+fn add(session: &mut Session, parameters: &J) -> Result {
+ if session.graph()?.function.is_some() {
return Err(bad("graph.node.add", "use function operations in a Function Graph"));
}
- let def = strp(p, "def").ok_or_else(|| bad("graph.node.add", "`def` is required (see library.list)"))?.to_string();
- let catalog = materialcraft_nodes::find(&def);
- if catalog.is_none() {
- return Err(bad("graph.node.add", format!("unknown node `{def}`")));
- }
+ let definition = strp(parameters, "def").ok_or_else(|| bad("graph.node.add", "`def` is required (see library.list)"))?.to_string();
+ let catalog = materialcraft_nodes::find(&definition).ok_or_else(|| bad("graph.node.add", format!("unknown node `{definition}`")))?;
+
// Typed parameter values, checked against the catalog
- let mut params = Vec::new();
- if let Some(obj) = p.get("params").and_then(J::as_object) {
- for (k, v) in obj {
- let v = if def == "graph_instance" && k == "graph" {
- Value::Text(v.as_str().ok_or_else(|| bad("graph.node.add", "`graph` is a graph name"))?.into())
- } else if def == "input_value" && k == "default" {
- serde_json::from_value::(v.clone())
+ let mut parameter_values = Vec::new();
+ if let Some(values) = parameters.get("params").and_then(J::as_object) {
+ for (identifier, value) in values {
+ let value = if definition == "graph_instance" && identifier == "graph" {
+ Value::Text(value.as_str().ok_or_else(|| bad("graph.node.add", "`graph` is a graph name"))?.into())
+ } else if definition == "input_value" && identifier == "default" {
+ serde_json::from_value::(value.clone())
.ok()
- .or_else(|| Value::Float(0.0).coerce_json(v))
- .filter(|value| materialcraft_core::ValueType::of(value).is_some())
+ .or_else(|| Value::Float(0.0).coerce_json(value))
+ .filter(|value| ValueType::of(value).is_some())
.ok_or_else(|| bad("graph.node.add", "default must be a scalar or vector value"))?
} else {
- let pd = catalog.and_then(|d| d.param(k)).ok_or_else(|| bad("graph.node.add", format!("`{def}` has no parameter `{k}`")))?;
- pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.add", format!("`{k}` takes a {}", pd.default.type_name())))?
+ let parameter = catalog.param(identifier).ok_or_else(|| bad("graph.node.add", format!("`{definition}` has no parameter `{identifier}`")))?;
+ parameter
+ .default
+ .coerce_json(value)
+ .ok_or_else(|| bad("graph.node.add", format!("`{identifier}` takes a {}", parameter.default.type_name())))?
};
- crate::graph_validation::value(&v).map_err(|error| bad("graph.node.add", error))?;
- params.push((k.clone(), v));
+ crate::graph_validation::value(&value).map_err(|error| bad("graph.node.add", error))?;
+ parameter_values.push((identifier.clone(), value));
}
}
- let from = p.get("connectFrom").and_then(|c| Some((NodeId(c.get("node")?.as_u64()?), c.get("port").and_then(J::as_str).unwrap_or("output").to_string())));
- let at = point(p, "at").unwrap_or_else(|| {
- let g = s.graph().ok();
- let src = from.as_ref().and_then(|(n, _)| g.and_then(|g| g.node(*n).ok()));
- src.map_or([0.0, 0.0], |n| [n.pos[0] + 150.0, n.pos[1]])
+
+ let source = parameters
+ .get("connectFrom")
+ .and_then(|connection| Some((NodeId(connection.get("node")?.as_u64()?), connection.get("port").and_then(J::as_str).unwrap_or("output").to_string())));
+ let position = point(parameters, "at").unwrap_or_else(|| {
+ let graph = session.graph().ok();
+ let source = source.as_ref().and_then(|(node, _)| graph.and_then(|graph| graph.node(*node).ok()));
+ source.map_or([0.0, 0.0], |node| [node.pos[0] + 150.0, node.pos[1]])
});
- let at = snap_position(at, boolp(p, "snapToGrid").unwrap_or(false));
- let label = strp(p, "label").unwrap_or("").to_string();
- s.edit("Add node", |s| {
- let g = s.graph_mut()?;
- let id = g.add_node(&def, at);
- let n = g.node_mut(id)?;
- n.label = label;
- if let Some(parameter) = catalog.and_then(|definition| definition.param("pattern")) {
- n.params.insert("pattern".into(), parameter.default.clone());
+ let position = snap_position(position, boolp(parameters, "snapToGrid").unwrap_or(false));
+ let label = strp(parameters, "label").unwrap_or("").to_string();
+
+ session.edit("Add node", |session| {
+ let graph = session.graph_mut()?;
+ let id = graph.add_node(&definition, position);
+ let node = graph.node_mut(id)?;
+ node.label = label;
+ if let Some(parameter) = catalog.param("pattern") {
+ node.params.insert("pattern".into(), parameter.default.clone());
}
- if def == "value_processor" {
- n.input_values.insert("value1".into(), ValueType::Float);
- let mut function = FunctionGraph::default();
- function.output = Some(function.add("get_float1", &[], Some(Value::Text("value1".into()))));
- n.params.insert("function".into(), Value::Function(Box::new(function)));
+ if definition == "value_processor" {
+ node.input_values.insert("value1".into(), ValueType::Float);
}
+ node.params.extend(parameter_values);
- n.params.extend(params);
-
- if let Some((src, port)) = from {
- let first = connection_input(s, src, &port, id)?;
- s.graph_mut()?.connect(src, &port, id, &first)?;
+ if let Some((source, port)) = source {
+ let input = connection_input(session, source, &port, id)?;
+ session.graph_mut()?.connect(source, &port, id, &input)?;
}
- s.selection = vec![id];
+ session.selection = vec![id];
Ok(json!({"id": id.0}))
})
}
@@ -228,49 +229,82 @@ fn reset(s: &mut Session, p: &J) -> Result {
})
}
-fn base(s: &mut Session, p: &J) -> Result {
- let id = node_param(s, "graph.node.base", p, "id")?;
- let mode = match strp(p, "sizeMode") {
+fn base(session: &mut Session, parameters: &J) -> Result {
+ let id = node_param(session, "graph.node.base", parameters, "id")?;
+ let mode = match strp(parameters, "sizeMode") {
None => None,
Some("relativeToInput") => Some(SizeMode::RelativeToInput),
Some("relativeToParent") => Some(SizeMode::RelativeToParent),
Some("absolute") => Some(SizeMode::Absolute),
- Some(o) => return Err(bad("graph.node.base", format!("unknown sizeMode `{o}`"))),
+ Some(unknown) => return Err(bad("graph.node.base", format!("unknown sizeMode `{unknown}`"))),
};
- let format = match strp(p, "format") {
+ let format = match strp(parameters, "format") {
None => None,
Some("inherit") => Some(OutputFormat::Inherit),
Some("u8") => Some(OutputFormat::U8),
Some("u16") => Some(OutputFormat::U16),
Some("f16") => Some(OutputFormat::F16),
Some("f32") => Some(OutputFormat::F32),
- Some(o) => return Err(bad("graph.node.base", format!("unknown format `{o}`"))),
+ Some(unknown) => return Err(bad("graph.node.base", format!("unknown format `{unknown}`"))),
};
- let size = p
- .get("size")
- .and_then(J::as_array)
- .map(|a| [a.first().and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32, a.get(1).and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32]);
- let seed = i64p(p, "seed").map(|v| v.clamp(0, i32::MAX as i64) as i32);
- let tiling = boolp(p, "tiling");
- s.edit_merged(&format!("base:{}", id.0), "Set base parameters", |s| {
- let b = &mut s.graph_mut()?.node_mut(id)?.base;
- if let Some(m) = mode {
- b.size_mode = m;
+ let size = parameters.get("size").and_then(J::as_array).map(|components| {
+ [components.first().and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32, components.get(1).and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32]
+ });
+ let seed = i64p(parameters, "seed").map(|value| value.clamp(0, i32::MAX as i64) as i32);
+ let tiling = parameters
+ .get("tiling")
+ .map(|value| match value.as_bool() {
+ Some(value) => Ok([value, value]),
+ None => serde_json::from_value::<[bool; 2]>(value.clone()).map_err(|error| bad("graph.node.base", error.to_string())),
+ })
+ .transpose()?;
+ let tiling_mode = parameters
+ .get("tilingMode")
+ .map(|value| serde_json::from_value(value.clone()).map_err(|error| bad("graph.node.base", error.to_string())))
+ .transpose()?;
+ let pixel_ratio_mode = parameters
+ .get("pixelRatioMode")
+ .map(|value| serde_json::from_value(value.clone()).map_err(|error| bad("graph.node.base", error.to_string())))
+ .transpose()?;
+ let pixel_ratio = parameters
+ .get("pixelRatio")
+ .map(|value| serde_json::from_value::(value.clone()).map_err(|error| bad("graph.node.base", error.to_string())))
+ .transpose()?;
+ if pixel_ratio.is_some_and(|value| !(0..=1).contains(&value)) {
+ return Err(bad("graph.node.base", "pixelRatio must be 0 or 1"));
+ }
+
+ session.edit_merged(&format!("base:{}", id.0), "Set base parameters", |session| {
+ let base = &mut session.graph_mut()?.node_mut(id)?.base;
+ if let Some(size_mode) = mode {
+ base.size_mode = size_mode;
}
- if let Some(sz) = size {
- b.size = sz;
+ if let Some(size) = size {
+ base.size = size;
}
- if let Some(f) = format {
- b.format = f;
+ if let Some(format) = format {
+ base.format = format;
}
- if let Some(sd) = seed {
- b.seed = sd;
+ if let Some(seed) = seed {
+ base.seed = seed;
}
- if let Some(t) = tiling {
- b.tiling = [t, t];
+ if let Some(tiling) = tiling {
+ base.tiling = tiling;
+ base.tiling_mode = materialcraft_core::ParameterInheritance::Absolute;
}
+ if let Some(mode) = tiling_mode {
+ base.tiling_mode = mode;
+ }
+ if let Some(value) = pixel_ratio {
+ base.pixel_ratio = value;
+ base.pixel_ratio_mode = materialcraft_core::ParameterInheritance::Absolute;
+ }
+ if let Some(mode) = pixel_ratio_mode {
+ base.pixel_ratio_mode = mode;
+ }
+
Ok(J::Null)
})
}
diff --git a/crates/engine/src/open_document.rs b/crates/engine/src/open_document.rs
index 3ee514ad..7cc12062 100644
--- a/crates/engine/src/open_document.rs
+++ b/crates/engine/src/open_document.rs
@@ -21,6 +21,30 @@ pub struct OpenDocument {
}
impl OpenDocument {
+ pub(crate) fn edit(&mut self, label: &str, edit: impl FnOnce(&mut Package) -> crate::Result) -> crate::Result {
+ let mut package = self.pkg.clone();
+ let result = edit(&mut package)?;
+ let snapshot = Snapshot {
+ pkg: std::mem::replace(&mut self.pkg, package),
+ graph: self.graph,
+ selection: self.selection.clone(),
+ annotation_selection: self.annotation_selection,
+ material_preview: self.material_preview.clone(),
+ label: label.into(),
+ modified: self.modified,
+ // The active document's cook cache cannot be reused after activation
+ dirty: true,
+ cook_epoch: 0,
+ };
+ self.undo.push(snapshot);
+ if self.undo.len() > crate::session::MAX_UNDO {
+ self.undo.remove(0);
+ }
+ self.redo.clear();
+ self.modified = true;
+ Ok(result)
+ }
+
pub(crate) fn new(id: u64, pkg: Package, path: Option) -> Self {
Self {
id,
diff --git a/crates/engine/src/package_commands.rs b/crates/engine/src/package_commands.rs
index bf2681e1..e8ac1855 100644
--- a/crates/engine/src/package_commands.rs
+++ b/crates/engine/src/package_commands.rs
@@ -116,7 +116,8 @@ impl Session {
json!(self.open_packages().into_iter().map(|(id, package, path, modified)| json!({
"id": id, "name": package.name, "path": path, "modified": modified,
"active": id == self.document_id,
- "graphs": package.graphs.iter().enumerate().map(|(index, graph)| json!({"index": index, "name": graph.name, "kind": graph.kind()})).collect::>()
+ "folders": package.folder_paths(),
+ "graphs": package.graphs.iter().enumerate().map(|(index, graph)| json!({"index": index, "name": graph.name, "path": graph.sbs_path(), "kind": graph.kind()})).collect::>()
})).collect::>())
}
}
diff --git a/crates/engine/src/package_file_commands.rs b/crates/engine/src/package_file_commands.rs
new file mode 100644
index 00000000..a70ed82f
--- /dev/null
+++ b/crates/engine/src/package_file_commands.rs
@@ -0,0 +1,77 @@
+use crate::{
+ Result, Session, cmd,
+ commands::{CommandSpec, always, bad},
+};
+use serde_json::{Value, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![
+ cmd!(
+ "file.reload",
+ "Reload package",
+ [],
+ None,
+ "{discard?: bool} reloads the current package; unsaved changes require explicit discard",
+ |session| { session.path.as_ref().map(|_| ()).ok_or_else(|| "the package has no file to reload".into()) },
+ reload
+ ),
+ cmd!("file.saveCopyAs", "Save a copy as...", [], None, "{path} writes an SBS copy without changing the current path or saved state", always, save_copy),
+ ]
+}
+
+fn reload(session: &mut Session, parameters: &Value) -> Result {
+ if session.modified && parameters.get("discard").and_then(Value::as_bool) != Some(true) {
+ return Err(bad("file.reload", "save the package or explicitly discard its edits"));
+ }
+ let path = session.path.clone().ok_or_else(|| bad("file.reload", "the package has no file to reload"))?;
+ let bytes = read_package(&path)?;
+ let linked = crate::file_cmds::linked_files(&path);
+ let mut read = materialcraft_formats::sbs::read_sbs(&bytes, &path, &linked)?;
+ crate::linked_files::normalize_references(&mut read.pkg, &path);
+ read.pkg.dependencies = session.pkg.dependencies.clone();
+ let safe_path = read.warnings.is_empty().then_some(path.clone());
+ read.warnings.extend(crate::linked_files::load(&mut read.pkg));
+
+ crate::file_cmds::replace_package(session, read.pkg, safe_path);
+ session.load_warnings = read.warnings;
+ session.refresh_links();
+ session.modified = false;
+ Ok(json!({"path": session.path, "warnings": session.load_warnings}))
+}
+
+fn read_package(path: &str) -> Result> {
+ if path.starts_with("sbs://") {
+ return materialcraft_formats::sbs::library::read(path).map_err(|error| bad("file.reload", error));
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use std::io::Read;
+ let mut bytes = Vec::new();
+ std::fs::File::open(path).and_then(|file| file.take((256 << 20) + 1).read_to_end(&mut bytes)).map_err(|error| bad("file.reload", error.to_string()))?;
+ if bytes.len() > 256 << 20 {
+ return Err(bad("file.reload", "the package exceeds 256 MiB"));
+ }
+ Ok(bytes)
+ }
+ #[cfg(target_arch = "wasm32")]
+ Err(bad("file.reload", "reopen local browser files with the file picker"))
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn save_copy(session: &mut Session, parameters: &Value) -> Result {
+ let path = crate::commands::strp(parameters, "path")
+ .filter(|path| !path.trim().is_empty())
+ .ok_or_else(|| bad("file.saveCopyAs", "a nonempty path is required"))?;
+ let path = crate::document_path::normalize(&crate::file_cmds::package_path(path));
+ if path.contains("://") || session.open_packages().iter().any(|entry| entry.2 == Some(path.as_str())) {
+ return Err(bad("file.saveCopyAs", "choose a local file that is not already open"));
+ }
+ let bytes = crate::file_cmds::save_bytes_at(session, Some(&path))?;
+ materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?;
+ Ok(json!({"path": path, "bytes": bytes.len()}))
+}
+
+#[cfg(target_arch = "wasm32")]
+fn save_copy(_: &mut Session, _: &Value) -> Result {
+ Err(bad("file.saveCopyAs", "the browser saves copies with a download"))
+}
diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs
index b6db6e09..c99a0323 100644
--- a/crates/engine/src/session.rs
+++ b/crates/engine/src/session.rs
@@ -13,7 +13,7 @@ use crate::snapshot::Snapshot;
use crate::{AnnotationSelection, Clip, EngineError, Result};
/// Undo keeps this many steps.
-const MAX_UNDO: usize = 200;
+pub(crate) const MAX_UNDO: usize = 200;
/// The 3D view's scene and look.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -119,6 +119,7 @@ pub struct View2d {
pub const WARNING_PREFIX: &str = "Warning: ";
pub struct Session {
+ pub environment: materialcraft_core::EvaluationEnvironment,
pub document_id: u64,
pub(crate) next_document_id: u64,
pub(crate) documents: std::collections::BTreeMap,
@@ -145,6 +146,7 @@ pub struct Session {
pub load_warnings: Vec,
pub clipboard: Option,
pub embedded_clipboard: Option,
+ pub explorer_clipboard: Option,
/// The last cook of the open graph.
pub cooked: Cooked,
/// Set when the graph changed and needs cooking.
@@ -164,8 +166,15 @@ pub struct Session {
}
impl Session {
- pub fn new(pkg: Package) -> Session {
+ pub fn new(mut pkg: Package) -> Session {
+ let library = crate::function_library::load();
+ if let Ok(library) = &library {
+ for (path, package) in &library.packages {
+ pkg.dependencies.entry(path.clone()).or_insert_with(|| package.clone());
+ }
+ }
let mut session = Session {
+ environment: Default::default(),
document_id: 0,
next_document_id: 1,
documents: std::collections::BTreeMap::new(),
@@ -187,6 +196,7 @@ impl Session {
load_warnings: Vec::new(),
clipboard: None,
embedded_clipboard: None,
+ explorer_clipboard: None,
cooked: Cooked::default(),
dirty: true,
cook_epoch: 0,
@@ -199,6 +209,14 @@ impl Session {
decoded: Arc::new(Mutex::new(HashMap::new())),
};
session.refresh_links();
+ match library {
+ Ok(library) => {
+ for warning in library.warnings {
+ session.warn(warning);
+ }
+ }
+ Err(error) => session.warn(format!("Missing function library: {error}")),
+ }
session
}
@@ -432,6 +450,7 @@ impl Session {
pub fn cook(&mut self) -> &Cooked {
let dec = self.resource_decoder();
let mut opts = Options::new(&dec);
+ opts.environment = self.environment;
opts.max_size = self.preview_size;
let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache);
self.accept_preview(cooked);
@@ -453,7 +472,8 @@ impl Session {
/// Cook graph `gi` at full size, without touching the preview results.
pub fn cook_full(&self, gi: usize) -> Cooked {
let dec = self.resource_decoder();
- let opts = Options::new(&dec);
+ let mut opts = Options::new(&dec);
+ opts.environment = self.environment;
materialcraft_eval::cook(&self.pkg, gi, &opts, &self.cache)
}
diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs
index d254c555..9b64c363 100644
--- a/crates/engine/src/session.test.rs
+++ b/crates/engine/src/session.test.rs
@@ -7,7 +7,7 @@ use crate::session::Session;
fn normal_map_session() -> Session {
let mut pkg = Package::new("T");
let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.5, 1.0, 1.0]), "png", Depth::U8, false).unwrap();
- pkg.resources.push(Resource { name: "n".into(), file: "n.png".into(), bytes: materialcraft_core::ResourceBytes::new(png) });
+ pkg.resources.push(Resource::new("n", "n.png", materialcraft_core::ResourceBytes::new(png)));
Session::new(pkg)
}
diff --git a/crates/engine/tests/atomics.rs b/crates/engine/tests/atomics.rs
index 7a5db0c4..968fab93 100644
--- a/crates/engine/tests/atomics.rs
+++ b/crates/engine/tests/atomics.rs
@@ -6,6 +6,42 @@ use materialcraft_engine::{
};
use serde_json::json;
+#[test]
+fn new_processors_start_with_empty_functions_and_preserve_them_in_sbs() {
+ use materialcraft_engine::{FunctionGraphTarget, core::NodeId};
+
+ for definition in ["pixel_processor", "value_processor"] {
+ let mut session = materialcraft_engine::new_session();
+ let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap());
+ let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() };
+
+ assert_eq!(target.current(&session).unwrap(), &FunctionGraph::default(), "{definition}");
+ session.preview_size = Some(16);
+ session.cook();
+ assert_eq!(session.cooked.nodes[&node].error.as_deref(), Some("function has no result node"), "{definition}");
+
+ let loaded = read_sbs(&write_sbs(&session.pkg).unwrap(), "empty_processors.sbs", &|_| None).unwrap();
+ assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
+ let session = Session::new(loaded.pkg);
+ let node = session.graph().unwrap().nodes[0].id;
+ let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() };
+ assert_eq!(target.current(&session).unwrap(), &FunctionGraph::default(), "{definition}");
+ }
+}
+
+#[test]
+fn new_fx_map_starts_with_a_quadrant_output() {
+ use materialcraft_engine::core::{NodeId, PatternGraph, PatternNodeKind};
+
+ let mut session = materialcraft_engine::new_session();
+ let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap());
+
+ assert_eq!(
+ session.graph().unwrap().node(node).unwrap().params.get("pattern"),
+ Some(&Value::PatternGraph(Box::new(PatternGraph::with_root(PatternNodeKind::Quadrant))))
+ );
+}
+
#[test]
fn atomic_sample_round_trips_through_native_fields_and_cooks_identically() {
let mut original = Session::new(atomic_sample().unwrap());
@@ -55,7 +91,7 @@ fn every_catalog_entry_has_a_native_sbs_representation() {
let bytes = write_sbs(&package).unwrap();
let loaded = read_sbs(&bytes, "primitives.sbs", &|_| None).unwrap();
assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
- assert_eq!(loaded.pkg.graphs[0].nodes.len(), 30);
+ assert_eq!(loaded.pkg.graphs[0].nodes.len(), 29);
for (before, after) in package.graphs[0].nodes.iter().zip(&loaded.pkg.graphs[0].nodes) {
assert_eq!(before.def, after.def);
}
diff --git a/crates/engine/tests/embedded_edit.rs b/crates/engine/tests/embedded_edit.rs
index 6af8baa4..32bf8adc 100644
--- a/crates/engine/tests/embedded_edit.rs
+++ b/crates/engine/tests/embedded_edit.rs
@@ -27,13 +27,16 @@ fn function_session(kind: &str) -> (Session, FunctionGraphTarget) {
.unwrap(),
);
if kind == "dynamic" {
- session.graph_mut().unwrap().node_mut(node).unwrap().functions.insert("test".into(), FunctionGraph::default());
+ let owner = session.graph_mut().unwrap().node_mut(node).unwrap();
+ owner.params.insert("function".into(), Value::Function(Box::new(FunctionGraph::constant(Value::Float4([0.5; 4])))));
+ owner.functions.insert("test".into(), FunctionGraph::default());
FunctionGraphTarget::Dynamic { node, parameter: "test".into() }
} else {
FunctionGraphTarget::Parameter { node, parameter: "function".into() }
}
}
};
+
execute(&mut session, "graph.function.set", &json!({"target": target, "function": FunctionGraph::default()})).unwrap();
session.reset_history();
(session, target)
diff --git a/crates/engine/tests/explorer.rs b/crates/engine/tests/explorer.rs
new file mode 100644
index 00000000..ae059284
--- /dev/null
+++ b/crates/engine/tests/explorer.rs
@@ -0,0 +1,234 @@
+use materialcraft_engine::{Session, core::Package, execute};
+use serde_json::{Value, json};
+
+fn run(session: &mut Session, command: &str, parameters: Value) -> Value {
+ execute(session, command, ¶meters).unwrap()
+}
+
+#[test]
+fn folders_contain_both_graph_kinds_and_removal_is_undoable() {
+ let mut session = Session::new(Package::new("Explorer"));
+ run(&mut session, "folder.create", json!({"name": "Tools"}));
+ run(&mut session, "folder.create", json!({"parent": "Tools", "name": "Math"}));
+ run(&mut session, "file.new", json!({"folder": "Tools", "name": "Surface", "template": "empty"}));
+ run(&mut session, "file.new", json!({"folder": "Tools/Math", "name": "Helper", "kind": "function"}));
+
+ assert!(session.pkg.graph_by_name("Tools/Surface").is_some());
+ assert!(session.pkg.graph_by_name("Tools/Math/Helper").is_some());
+ let before = session.pkg.clone();
+ run(&mut session, "folder.remove", json!({"folder": "Tools"}));
+ assert!(session.pkg.graphs.is_empty());
+
+ run(&mut session, "edit.undo", json!({}));
+ assert_eq!(session.pkg, before);
+}
+
+#[test]
+fn numbered_explorer_names_increment_across_conflicts() {
+ let mut session = Session::new(Package::new("Names"));
+ run(&mut session, "folder.create", json!({"name": "Tools"}));
+ run(&mut session, "folder.create", json!({"parent": "Tools", "name": "Untitled_Graph_2"}));
+
+ for (kind, prefix) in [("material", "Untitled_Graph"), ("function", "Untitled_Function_Graph")] {
+ for expected in if kind == "material" { [1, 3] } else { [1, 2] } {
+ let result = run(&mut session, "file.new", json!({"folder": "Tools", "name": format!("{prefix}_1"), "kind": kind, "template": "empty"}));
+ assert_eq!(result["name"], format!("{prefix}_{expected}"));
+ }
+ }
+ for expected in [1, 2] {
+ let result = run(&mut session, "folder.create", json!({"parent": "Tools", "name": "Untitled_Folder_1"}));
+ assert_eq!(result["folder"], format!("Tools/Untitled_Folder_{expected}"));
+ }
+ let result = run(&mut session, "folder.create", json!({"name": "Untitled_Folder_1"}));
+ assert_eq!(result["folder"], "Untitled_Folder_1");
+}
+
+#[test]
+fn explorer_moves_and_renames_cannot_collide_with_resources() {
+ use materialcraft_engine::core::{Resource, ResourceBytes};
+ let mut session = Session::new(Package::new("Names"));
+ run(&mut session, "folder.create", json!({"name": "Folder"}));
+ run(&mut session, "file.new", json!({"name": "Graph", "template": "empty"}));
+ for (folder, name) in [("", "Taken"), ("Folder", "Graph")] {
+ let mut resource = Resource::new(name, "tile.png", ResourceBytes::new(vec![1]));
+ resource.folder = folder.into();
+ session.pkg.resources.push(resource);
+ }
+ let before = materialcraft_engine::file_cmds::save_bytes(&session).unwrap();
+
+ assert!(execute(&mut session, "folder.rename", &json!({"folder": "Folder", "name": "Taken"})).is_err());
+ assert!(execute(&mut session, "graph.rename", &json!({"graph": 0, "name": "Taken"})).is_err());
+ assert!(execute(&mut session, "explorer.move", &json!({"graph": 0, "parent": "Folder"})).is_err());
+ assert_eq!(materialcraft_engine::file_cmds::save_bytes(&session).unwrap(), before);
+}
+
+#[test]
+fn package_paste_places_root_resources_in_the_destination_folder() {
+ use materialcraft_engine::core::{Resource, ResourceBytes};
+ let mut session = Session::new(Package::new("Copy"));
+ let mut resource = Resource::new("Tile", "tile.png", ResourceBytes::new(vec![1]));
+ resource.folder = String::new();
+ session.pkg.resources.push(resource);
+ run(&mut session, "explorer.copy", json!({}));
+ run(&mut session, "file.newPackage", json!({}));
+ run(&mut session, "folder.create", json!({"name": "Destination"}));
+ run(&mut session, "file.new", json!({"folder": "Destination", "name": "Tile", "template": "empty"}));
+
+ run(&mut session, "explorer.paste", json!({"folder": "Destination"}));
+
+ assert_eq!(session.pkg.resources[0].sbs_path(), "Destination/Tile_1");
+}
+
+fn linked_functions() -> Session {
+ use materialcraft_engine::core::{FunctionGraph, Graph, Value as GraphValue};
+ let mut package = Package::new("Linked functions");
+ let mut source = Graph::new("Source");
+ source.folder = "Tools/Math".into();
+ source.function = Some(FunctionGraph::constant(GraphValue::Float(0.5)));
+ package.graphs.push(source);
+ let mut session = Session::new(package);
+ run(&mut session, "file.new", json!({"kind": "function", "name": "Caller", "folder": "Tools"}));
+ run(&mut session, "graph.instance.add", json!({"document": 0, "graph": "Tools/Math/Source"}));
+ session
+}
+
+#[test]
+fn renamed_and_moved_folders_rewrite_nested_function_references() {
+ let mut session = linked_functions();
+ run(&mut session, "folder.rename", json!({"folder": "Tools", "name": "Helpers"}));
+ let caller = &session.pkg.graphs[1].function.as_ref().unwrap().nodes[0];
+ assert_eq!(caller.instance.as_ref().unwrap().graph, "Helpers/Math/Source");
+ assert!(matches!(caller.source, Some(Ok(_))));
+
+ run(&mut session, "explorer.move", json!({"folder": "Helpers/Math", "parent": ""}));
+ assert_eq!(session.pkg.graphs[0].folder, "Math");
+ let caller = &session.pkg.graphs[1].function.as_ref().unwrap().nodes[0];
+ assert_eq!(caller.instance.as_ref().unwrap().graph, "Math/Source");
+ assert!(matches!(caller.source, Some(Ok(_))));
+ assert!(session.pkg.folder_paths().contains("Helpers"));
+
+ let before = session.pkg.clone();
+ assert!(execute(&mut session, "explorer.move", &json!({"folder": "Math", "parent": "Math"})).is_err());
+ assert_eq!(session.pkg, before);
+}
+
+#[test]
+fn folder_copy_keeps_empty_descendants_and_retargets_its_internal_instances() {
+ let mut session = linked_functions();
+ run(&mut session, "folder.create", json!({"parent": "Tools", "name": "Empty"}));
+ run(&mut session, "explorer.copy", json!({"folder": "Tools"}));
+ let before = session.pkg.clone();
+
+ run(&mut session, "explorer.paste", json!({}));
+
+ assert!(session.pkg.folder_paths().contains("Tools_1/Empty"));
+ let (_, caller) = session.pkg.graph_by_name("Tools_1/Caller").unwrap();
+ let node = &caller.function.as_ref().unwrap().nodes[0];
+ assert_eq!(node.instance.as_ref().unwrap().graph, "Tools_1/Math/Source");
+ assert!(matches!(node.source, Some(Ok(_))));
+ run(&mut session, "edit.undo", json!({}));
+ assert_eq!(session.pkg, before);
+}
+
+#[test]
+fn explorer_clipboard_survives_document_switch_and_checks_external_references() {
+ let mut session = linked_functions();
+ run(&mut session, "explorer.copy", json!({"graph": 1}));
+ run(&mut session, "file.newPackage", json!({"name": "Destination"}));
+ let destination = session.document_id;
+ let before = session.pkg.clone();
+
+ assert!(execute(&mut session, "explorer.paste", &json!({})).is_err());
+ assert_eq!(session.pkg, before);
+ run(&mut session, "package.activate", json!({"document": 0}));
+ run(&mut session, "explorer.copy", json!({"folder": "Tools"}));
+ run(&mut session, "package.activate", json!({"document": destination}));
+ run(&mut session, "explorer.paste", json!({}));
+
+ let (_, caller) = session.pkg.graph_by_name("Tools/Caller").unwrap();
+ assert!(matches!(caller.function.as_ref().unwrap().nodes[0].source, Some(Ok(_))));
+}
+
+#[test]
+fn folder_removal_does_not_remove_similarly_named_siblings() {
+ let mut session = Session::new(Package::new("Siblings"));
+ for folder in ["A", "AB"] {
+ run(&mut session, "folder.create", json!({"name": folder}));
+ run(&mut session, "file.new", json!({"folder": folder, "name": "Graph", "template": "empty"}));
+ }
+ run(&mut session, "folder.remove", json!({"folder": "A"}));
+
+ assert_eq!(session.pkg.graphs.len(), 1);
+ assert_eq!(session.pkg.graphs[0].sbs_path(), "AB/Graph");
+ assert!(session.pkg.folder_paths().contains("AB"));
+}
+
+#[test]
+fn save_copy_keeps_document_identity_and_reload_is_atomic() {
+ let directory = std::env::temp_dir().join(format!("materialcraft-explorer-{}", std::process::id()));
+ std::fs::create_dir_all(&directory).unwrap();
+ let original = directory.join("original.sbs");
+ let copy = directory.join("copy.sbs");
+ let mut session = linked_functions();
+ for path in ["", " "] {
+ assert!(execute(&mut session, "file.saveCopyAs", &json!({"path": path})).is_err());
+ }
+
+ run(&mut session, "file.save", json!({"path": original}));
+ let document = session.document_id;
+ let path = session.path.clone();
+ run(&mut session, "folder.create", json!({"name": "Unsaved"}));
+ let history = session.history().len();
+
+ run(&mut session, "file.saveCopyAs", json!({"path": copy}));
+ assert_eq!(session.path, path);
+ assert!(session.modified);
+ assert_eq!(session.history().len(), history);
+ let copied = materialcraft_engine::formats::sbs::read_sbs(&std::fs::read(©).unwrap(), "copy.sbs", &|_| None).unwrap();
+ assert!(copied.pkg.folder_paths().contains("Unsaved"));
+ assert!(execute(&mut session, "file.reload", &json!({})).is_err());
+
+ run(&mut session, "file.reload", json!({"discard": true}));
+ assert_eq!(session.document_id, document);
+ assert!(!session.modified);
+ assert!(!session.pkg.folder_paths().contains("Unsaved"));
+ let before = session.pkg.clone();
+ std::fs::write(&original, "broken package").unwrap();
+ assert!(execute(&mut session, "file.reload", &json!({})).is_err());
+ assert_eq!(session.pkg, before);
+ std::fs::remove_dir_all(directory).unwrap();
+}
+
+#[test]
+fn folder_names_and_depth_are_bounded() {
+ let mut session = Session::new(Package::new("Validation"));
+ run(&mut session, "file.new", json!({"name": " Surface ", "template": "empty"}));
+ assert_eq!(session.graph().unwrap().name, "Surface");
+
+ for name in ["", "../escape", "A/B", "A\\B", ".", "\0"] {
+ assert!(execute(&mut session, "folder.create", &json!({"name": name})).is_err(), "{name:?}");
+ }
+ let path = std::iter::repeat_n("A", 64).collect::>().join("/");
+ session.pkg.folders.push(path.clone());
+ assert!(execute(&mut session, "folder.create", &json!({"parent": path})).is_err());
+}
+
+#[test]
+fn copied_folders_keep_unreferenced_resources_in_the_copied_subtree() {
+ use materialcraft_engine::core::{Resource, ResourceBytes};
+ let mut package = Package::new("Resources");
+ let mut resource = Resource::new("Mask", "mask.png", ResourceBytes::new(vec![1, 2, 3]));
+ resource.folder = "Tools/Images".into();
+ package.resources.push(resource);
+ let mut session = Session::new(package);
+ run(&mut session, "explorer.copy", json!({"folder": "Tools"}));
+
+ run(&mut session, "explorer.paste", json!({}));
+ assert_eq!(session.pkg.resources.len(), 2);
+ assert_eq!(session.pkg.resources[1].folder, "Tools_1/Images");
+ assert_eq!(session.pkg.resources[1].bytes.as_slice(), &[1, 2, 3]);
+ run(&mut session, "folder.rename", json!({"folder": "Tools_1", "name": "Copy"}));
+ assert_eq!(session.pkg.resources[1].folder, "Copy/Images");
+ run(&mut session, "folder.remove", json!({"folder": "Copy"}));
+ assert_eq!(session.pkg.resources.len(), 1);
+}
diff --git a/crates/engine/tests/function_graph.rs b/crates/engine/tests/function_graph.rs
index dac11466..f1deb9fd 100644
--- a/crates/engine/tests/function_graph.rs
+++ b/crates/engine/tests/function_graph.rs
@@ -62,6 +62,6 @@ fn standalone_function_creation_wiring_frame_movement_and_native_round_trip() {
let function = graph.function.as_ref().unwrap();
assert_eq!(function.nodes[0].pos, [32.0, 64.0]);
let variables = Default::default();
- let context = EvaluationContext { position: [0.0; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
+ let context = EvaluationContext { scope: Default::default(), position: [0.0; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
assert_eq!(compile(function, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Float(6.0));
}
diff --git a/crates/engine/tests/function_instances.rs b/crates/engine/tests/function_instances.rs
index ee944e06..2c95e065 100644
--- a/crates/engine/tests/function_instances.rs
+++ b/crates/engine/tests/function_instances.rs
@@ -43,12 +43,59 @@ fn evaluate(graph: &FunctionGraph) -> Value {
function::compile(graph, 0)
.unwrap()
.evaluate(
- &EvaluationContext { position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &BTreeMap::new() },
+ &EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &BTreeMap::new() },
&mut EvaluationState::default(),
)
.unwrap()
}
+#[test]
+fn redundant_legacy_function_connectors_preserve_wires_without_repeating_evaluation() {
+ let mut package = source();
+ let mut graph = Graph::new("Caller");
+ let mut body = FunctionGraph::default();
+ let maximum = body.add_constant(Value::Float(1.0));
+ let random = body.add("rand", &[maximum], None);
+ let instance = body.add("instance", &[random], None);
+ let call = body.nodes.iter_mut().find(|node| node.id == instance).unwrap();
+ call.instance = Some(GraphInstance {
+ label: String::new(),
+ package: String::new(),
+ graph: "Twice".into(),
+ inputs: vec![GraphPort { identifier: "amount".into(), type_code: 256 }],
+ outputs: vec![GraphPort { identifier: "output".into(), type_code: 256 }],
+ defaults: BTreeMap::new(),
+ });
+ let next_random = body.add("rand", &[maximum], None);
+ body.output = Some(body.add("add", &[instance, next_random], None));
+ graph.function = Some(body);
+ package.graphs.push(graph);
+ let canonical = Session::new(package.clone());
+ let expected = evaluate(canonical.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap());
+ let caller = package.graphs.last_mut().unwrap().function.as_mut().unwrap();
+ let call = caller.nodes.iter_mut().find(|node| node.id == instance).unwrap();
+ call.instance.as_mut().unwrap().inputs.push(GraphPort { identifier: "old_amount".into(), type_code: 0 });
+ call.inputs.push(Some(random));
+
+ let session = Session::new(package.clone());
+ let function = session.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap();
+ assert_eq!(evaluate(function), expected);
+ assert!(function::warnings(function).is_empty());
+ let saved = formats::sbs::write_sbs(&session.pkg).unwrap();
+ let reopened = Session::new(formats::sbs::read_sbs(&saved, "caller.sbs", &|_| None).unwrap().pkg);
+ let function = reopened.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap();
+ let call = function.nodes.iter().find(|node| node.instance.is_some()).unwrap();
+ assert_eq!(call.instance.as_ref().unwrap().inputs.iter().map(|port| port.identifier.as_str()).collect::>(), ["amount", "old_amount"]);
+ assert_eq!(call.inputs[0], call.inputs[1]);
+ assert_eq!(evaluate(function), expected);
+
+ let caller = package.graphs.last_mut().unwrap().function.as_mut().unwrap();
+ *caller.nodes.iter_mut().find(|node| node.id == instance).unwrap().inputs.last_mut().unwrap() = Some(maximum);
+ let conflicting = Session::new(package);
+ let function = conflicting.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap();
+ assert!(function::compile(function, 0).err().unwrap().contains("connected input no longer exists"));
+}
+
#[test]
fn functions_link_across_documents_and_keep_independent_undo() {
let mut session = Session::new(source());
@@ -64,7 +111,7 @@ fn functions_link_across_documents_and_keep_independent_undo() {
let constant = edit(&mut session, &target, json!({"action": "add", "operation": "const_float1", "at": [0,0]}))["id"].as_u64().unwrap();
edit(&mut session, &target, json!({"action": "value", "id": constant, "value": Value::Float(0.25)}));
edit(&mut session, &target, json!({"action": "output", "id": instance}));
- assert!(function::warnings(session.graph().unwrap().function.as_ref().unwrap())[0].contains("missing input"));
+ assert!(function::warnings(session.graph().unwrap().function.as_ref().unwrap()).is_empty());
edit(&mut session, &target, json!({"action": "connect", "from": constant, "to": instance, "input": 0}));
assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.5));
let history = session.history();
@@ -76,7 +123,7 @@ fn functions_link_across_documents_and_keep_independent_undo() {
assert_eq!(session.history(), history);
assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.75));
execute(&mut session, "edit.undo", &json!({})).unwrap();
- assert!(function::compile(session.graph().unwrap().function.as_ref().unwrap(), 0).is_err());
+ assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(1.5));
execute(&mut session, "edit.redo", &json!({})).unwrap();
assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.75));
}
@@ -173,6 +220,8 @@ fn calls_isolate_variables_and_evaluate_arguments_once() {
let argument = caller.add("set", &[next], Some(Value::Text("private".into())));
let call = caller.add("instance", &[argument], None);
caller.nodes.last_mut().unwrap().instance = Some(GraphInstance {
+ label: String::new(),
+ defaults: Default::default(),
package: String::new(),
graph: "Twice".into(),
inputs: vec![GraphPort { identifier: "amount".into(), type_code: 256 }],
@@ -184,6 +233,19 @@ fn calls_isolate_variables_and_evaluate_arguments_once() {
assert_eq!(evaluate(&caller), Value::Float(6.0));
}
+#[test]
+fn unconnected_instance_inputs_use_the_source_defaults() {
+ let mut session = Session::new(source());
+ execute(&mut session, "file.new", &json!({"name": "Caller", "kind": "function"})).unwrap();
+ let target = json!({"kind": "graph"});
+ let instance = call(&mut session, 0, "Twice", &target);
+ edit(&mut session, &target, json!({"action": "output", "id": instance}));
+
+ let graph = session.graph().unwrap().function.as_ref().unwrap();
+ assert_eq!(evaluate(graph), Value::Float(1.0));
+ assert!(function::warnings(graph).is_empty());
+}
+
#[test]
fn connected_inputs_survive_source_interface_changes_and_missing_sources() {
let mut session = Session::new(source());
@@ -312,6 +374,8 @@ fn cyclic_references_loaded_from_sbs_report_errors_without_recursing_forever() {
let mut function = FunctionGraph::default();
let id = function.add("instance", &[], None);
function.nodes[0].instance = Some(GraphInstance {
+ label: String::new(),
+ defaults: Default::default(),
package: String::new(),
graph: graph.name.clone(),
inputs: Vec::new(),
diff --git a/crates/engine/tests/function_library.rs b/crates/engine/tests/function_library.rs
new file mode 100644
index 00000000..dd57176b
--- /dev/null
+++ b/crates/engine/tests/function_library.rs
@@ -0,0 +1,281 @@
+use materialcraft_engine::{
+ FunctionGraphTarget, Session,
+ core::{FunctionGraph, Graph, NodeId, Package, Value},
+ execute, file_cmds,
+ nodes::function::{self, EvaluationContext, EvaluationState},
+};
+use serde_json::json;
+use std::collections::BTreeMap;
+
+fn session() -> Session {
+ let mut package = Package::new("Library integration");
+ let mut graph = Graph::new("Caller");
+ graph.function = Some(FunctionGraph::default());
+ package.graphs.push(graph);
+ Session::new(package)
+}
+
+fn value(function: &FunctionGraph) -> Value {
+ let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &BTreeMap::new() };
+ function::compile(function, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap()
+}
+
+#[test]
+fn library_instances_are_discoverable_undoable_and_portable() {
+ let mut session = session();
+ let entries = execute(&mut session, "library.functions", &json!({})).unwrap();
+ assert_eq!(entries.as_array().unwrap().len(), 171);
+ let pi = entries.as_array().unwrap().iter().find(|entry| entry["graph"] == "Functions/Math/Pi").unwrap();
+ assert_eq!(pi["outputs"][0]["type_code"], 256);
+
+ let node = execute(&mut session, "library.function.add", &json!({"graph": "Functions/Math/Pi", "at": [64.0, 128.0]})).unwrap()["id"].as_u64().unwrap();
+ execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "output", "id": node}})).unwrap();
+ assert_eq!(value(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(std::f32::consts::PI));
+ execute(&mut session, "edit.undo", &json!({})).unwrap();
+ execute(&mut session, "edit.undo", &json!({})).unwrap();
+ assert!(session.graph().unwrap().function.as_ref().unwrap().nodes.is_empty());
+ execute(&mut session, "edit.redo", &json!({})).unwrap();
+ execute(&mut session, "edit.redo", &json!({})).unwrap();
+
+ let bytes = file_cmds::save_bytes(&session).unwrap();
+ let xml = std::str::from_utf8(&bytes).unwrap();
+ assert!(xml.contains("sbs://functions.sbs"));
+ assert!(!xml.contains("assets/sbs"));
+ assert!(!xml.contains(" = entries.iter().filter(|entry| entry["missing"] != false).map(|entry| &entry["graph"]).collect();
+
+ assert_eq!(entries.len(), 171);
+ assert!(missing.is_empty(), "missing bundled functions: {missing:?}");
+ for entry in entries {
+ let mut caller = self::session();
+ let identifier = execute(&mut caller, "library.function.add", &json!({"graph": entry["graph"]})).unwrap()["id"].as_u64().unwrap();
+ execute(&mut caller, "graph.function.edit", &json!({"edit": {"action": "output", "id": identifier}})).unwrap();
+ let function = caller.graph().unwrap().function.as_ref().unwrap();
+
+ assert!(matches!(function.nodes[0].source, Some(Ok(_))), "{}", entry["graph"]);
+ function::compile(function, 0).unwrap_or_else(|error| panic!("{}: {error}", entry["graph"]));
+ }
+}
+
+#[test]
+fn parity_library_instances_evaluate_connected_inputs_after_reopen() {
+ for (name, expected, default) in [
+ ("EvenCount", Value::Float(3.0), Value::Float(0.0)),
+ ("OddCount", Value::Float(2.0), Value::Float(0.0)),
+ ("ParityTest", Value::Bool(true), Value::Bool(true)),
+ ] {
+ let mut session = session();
+ let entries = execute(&mut session, "library.functions", &json!({"filter": name})).unwrap();
+ assert_eq!(entries[0]["missing"], false, "{name} must be usable from the Library");
+
+ let instance =
+ execute(&mut session, "library.function.add", &json!({"graph": format!("Functions/Math/Parity/{name}")})).unwrap()["id"].as_u64().unwrap();
+ execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "output", "id": instance}})).unwrap();
+ assert_eq!(value(session.graph().unwrap().function.as_ref().unwrap()), default);
+ let constant = execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "add", "operation": "const_float1", "at": [-200.0, 0.0]}}))
+ .unwrap()["id"]
+ .as_u64()
+ .unwrap();
+ execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "value", "id": constant, "value": Value::Float(5.75)}})).unwrap();
+ execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "connect", "from": constant, "to": instance, "input": 0}})).unwrap();
+ let bytes = file_cmds::save_bytes(&session).unwrap();
+ let mut reopened = self::session();
+ file_cmds::open_bytes(&mut reopened, &bytes, Some("parity-caller.sbs".into())).unwrap();
+
+ assert_eq!(value(session.graph().unwrap().function.as_ref().unwrap()), expected, "{name}");
+ assert_eq!(value(reopened.graph().unwrap().function.as_ref().unwrap()), expected, "reopened {name}");
+ }
+}
+
+#[test]
+fn missing_library_implementations_remain_instances_with_typed_ports() {
+ let mut session = session();
+ let mut missing = session.pkg.dependencies["sbs://functions.sbs"].graph_by_name("Functions/Random/GlobalRandom").unwrap().1.clone();
+ missing.name = "MissingFunction".into();
+ missing.folder = "Functions/Test".into();
+ missing.function = Some(FunctionGraph::default());
+ let mut package = Package::new("Missing library");
+ package.graphs.push(missing);
+ session.pkg.dependencies.insert("sbs://missing-functions.sbs".into(), std::sync::Arc::new(package));
+
+ let entries = execute(&mut session, "library.functions", &json!({"filter": "MissingFunction"})).unwrap();
+ assert_eq!(entries[0]["missing"], true);
+ assert_eq!(entries[0]["inputs"].as_array().unwrap().len(), 2);
+
+ let id = execute(&mut session, "library.function.add", &json!({"package": "sbs://missing-functions.sbs", "graph": "Functions/Test/MissingFunction"}))
+ .unwrap()["id"]
+ .as_u64()
+ .unwrap();
+ let node = session.graph().unwrap().function.as_ref().unwrap().node(id as u32).unwrap();
+ assert!(matches!(node.source, Some(Err(_))));
+ assert_eq!(node.instance.as_ref().unwrap().inputs.len(), 2);
+ let saved = file_cmds::save_bytes(&session).unwrap();
+ let mut reopened = self::session();
+ file_cmds::open_bytes(&mut reopened, &saved, None).unwrap();
+ assert!(matches!(reopened.graph().unwrap().function.as_ref().unwrap().nodes[0].source, Some(Err(_))));
+}
+
+#[test]
+fn function_library_accepts_processor_canvases_and_rejects_material_canvases() {
+ let mut package = Package::new("Processors");
+ package.graphs.push(Graph::new("Material"));
+ let mut session = Session::new(package);
+ assert!(execute(&mut session, "library.function.add", &json!({"graph": "Functions/Math/Pi"})).is_err());
+
+ for kind in ["pixel_processor", "value_processor"] {
+ let owner = execute(&mut session, "graph.node.add", &json!({"def": kind})).unwrap()["id"].as_u64().unwrap();
+ if kind == "pixel_processor" {
+ execute(&mut session, "graph.node.param", &json!({"id": owner, "param": "color_mode", "value": false})).unwrap();
+ }
+
+ let target = FunctionGraphTarget::Parameter { node: NodeId(owner), parameter: "function".into() };
+ let node = execute(&mut session, "library.function.add", &json!({"graph": "Functions/Math/Pi", "function": target})).unwrap()["id"].as_u64().unwrap();
+ execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": node}})).unwrap();
+
+ assert_eq!(value(target.current(&session).unwrap()), Value::Float(std::f32::consts::PI));
+ }
+}
+
+#[test]
+fn library_aliases_open_as_references_and_require_a_local_save_path() {
+ let mut session = session();
+ file_cmds::open_file(&mut session, "sbs://functions.sbs").unwrap();
+
+ assert_eq!(session.pkg.graphs.len(), 171);
+ let error = execute(&mut session, "file.save", &json!({})).unwrap_err().to_string();
+ assert!(error.contains("local .sbs"), "{error}");
+}
+
+#[test]
+fn renaming_a_nested_source_updates_its_local_reference() {
+ let mut session = session();
+ session.pkg.graphs[0].folder = "Functions/Local".into();
+ session.pkg.graphs[0].function = Some(FunctionGraph::constant(Value::Float(0.75)));
+ execute(&mut session, "file.new", &json!({"kind": "function", "name": "Consumer"})).unwrap();
+ execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Functions/Local/Caller"})).unwrap();
+
+ execute(&mut session, "graph.rename", &json!({"graph": 0, "name": "Renamed"})).unwrap();
+
+ let node = &session.graph().unwrap().function.as_ref().unwrap().nodes[0];
+ assert_eq!(node.instance.as_ref().unwrap().graph, "Functions/Local/Renamed");
+ assert!(matches!(node.source, Some(Ok(_))));
+}
+
+#[test]
+#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"]
+fn supplied_library_instances_resolve_all_function_paths() {
+ let path = std::env::var("MC_FUNCTIONS_SBS").unwrap();
+ let bytes = std::fs::read(&path).unwrap();
+ let read = materialcraft_engine::formats::sbs::read_sbs(&bytes, &path, &|_| None).unwrap();
+ let session = Session::new(read.pkg);
+ let mut references = 0;
+ let mut unresolved = 0;
+ let mut compiled = 0;
+
+ for graph in &session.pkg.graphs {
+ let function = graph.function.as_ref().unwrap();
+ for node in function.nodes.iter().filter(|node| node.instance.is_some()) {
+ let source = node.source.as_ref().expect("every instance must be resolved or diagnosed");
+ if let Err(error) = source {
+ unresolved += 1;
+ eprintln!("Unresolved instance in {}: {error}", graph.sbs_path());
+ }
+ references += 1;
+ }
+ match function::compile(function, 0) {
+ Ok(_) => compiled += 1,
+ Err(error) => eprintln!("Could not compile {}: {error}", graph.sbs_path()),
+ }
+ }
+
+ eprintln!("Resolved {} of {references} instances and compiled {compiled} functions", references - unresolved);
+ assert_eq!(unresolved, 0, "every supplied instance must resolve");
+ assert_eq!(compiled, session.pkg.graphs.len(), "every supplied function must compile");
+}
+
+#[test]
+#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"]
+fn supplied_functions_evaluate_before_and_after_save() {
+ let path = std::env::var("MC_FUNCTIONS_SBS").unwrap();
+ let read = materialcraft_engine::formats::sbs::read_sbs(&std::fs::read(&path).unwrap(), &path, &|_| None).unwrap();
+ let before = Session::new(read.pkg);
+ let bytes = materialcraft_engine::formats::sbs::write_sbs(&before.pkg).unwrap();
+ let after = Session::new(materialcraft_engine::formats::sbs::read_sbs(&bytes, "saved.sbs", &|_| None).unwrap().pkg);
+ let bundled = Session::new(
+ materialcraft_engine::formats::sbs::read_sbs(include_bytes!("../../../assets/sbs/functions.sbs"), "functions.sbs", &|_| None).unwrap().pkg,
+ );
+ let mut failures = Vec::new();
+ let mut defaults = 0;
+
+ for graph in &before.pkg.graphs {
+ let source = function::compile(graph.function.as_ref().unwrap(), 0).unwrap();
+ let saved = after.pkg.graph_by_name(&graph.sbs_path()).unwrap().1;
+ let saved = function::compile(saved.function.as_ref().unwrap(), 0).unwrap();
+ let converted = bundled.pkg.graph_by_name(&graph.sbs_path()).unwrap().1;
+ let converted = function::compile(converted.function.as_ref().unwrap(), 0).unwrap();
+ let mut errors = Vec::new();
+ for profile in 0..4 {
+ let mut variables: BTreeMap<_, _> = graph
+ .exposed
+ .iter()
+ .enumerate()
+ .map(|(index, parameter)| {
+ let scalar = (profile as f32 + index as f32) * 0.25;
+ let value = if profile == 0 {
+ parameter.default.clone()
+ } else {
+ match parameter.default {
+ Value::Float(_) => Value::Float(scalar),
+ Value::Float2(_) => Value::Float2([scalar, scalar * 2.0]),
+ Value::Float3(_) => Value::Float3([scalar, scalar * 2.0, scalar * 3.0]),
+ Value::Float4(_) => Value::Float4([scalar, scalar * 2.0, scalar * 3.0, scalar * 4.0]),
+ Value::Int(_) => Value::Int(profile),
+ Value::Int2(_) => Value::Int2([profile, profile + 1]),
+ Value::Int3(_) => Value::Int3([profile, profile + 1, profile + 2]),
+ Value::Int4(_) => Value::Int4([profile, profile + 1, profile + 2, profile + 3]),
+ Value::Bool(_) => Value::Bool(profile % 2 != 0),
+ _ => parameter.default.clone(),
+ }
+ };
+ (parameter.id.clone(), value)
+ })
+ .collect();
+ // This hidden helper requires a render region supplied by its caller
+ if graph.name == "compute_total_number" {
+ variables.insert("render_region".into(), Value::Float4([-0.5, 0.5, -0.5, 0.5]));
+ }
+ let context =
+ EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [256.0, 128.0], images: &[], tile: true, variables: &variables };
+ match source.evaluate(&context, &mut EvaluationState::default()) {
+ Ok(expected) => {
+ assert_eq!(saved.evaluate(&context, &mut EvaluationState::default()).unwrap(), expected, "{}", graph.sbs_path());
+ assert_eq!(converted.evaluate(&context, &mut EvaluationState::default()).unwrap(), expected, "converted {}", graph.sbs_path());
+ defaults += usize::from(profile == 0);
+ errors.clear();
+ break;
+ }
+ Err(error) => errors.push(error),
+ }
+ }
+ if !errors.is_empty() {
+ failures.push(format!("{}: {}", graph.sbs_path(), errors.join("; ")));
+ }
+ }
+
+ eprintln!(
+ "Evaluated {} of {} supplied functions before/after save and in the converted library; {defaults} used their declared defaults",
+ before.pkg.graphs.len() - failures.len(),
+ before.pkg.graphs.len()
+ );
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
diff --git a/crates/engine/tests/graph_edit.rs b/crates/engine/tests/graph_edit.rs
index d7630985..deaa5635 100644
--- a/crates/engine/tests/graph_edit.rs
+++ b/crates/engine/tests/graph_edit.rs
@@ -97,6 +97,8 @@ fn connected_selection_performance() {
let mut graph = FunctionGraph::default();
for id in 1..=4096 {
graph.nodes.push(materialcraft_engine::core::FunctionNode {
+ missing: None,
+ missing_data: String::new(),
instance: None,
source: None,
id,
diff --git a/crates/engine/tests/graph_interaction.rs b/crates/engine/tests/graph_interaction.rs
index 69061cca..2bf5dfb8 100644
--- a/crates/engine/tests/graph_interaction.rs
+++ b/crates/engine/tests/graph_interaction.rs
@@ -1,6 +1,6 @@
use materialcraft_engine::{
- Session,
- core::{NodeId, Value},
+ FunctionGraphTarget, Session,
+ core::{FunctionGraph, NodeId, Value},
execute,
formats::sbs::{read_sbs, write_sbs},
new_session,
@@ -12,7 +12,7 @@ fn add(session: &mut Session, definition: &str) -> NodeId {
}
#[test]
-fn fresh_value_processors_accept_one_source_and_round_trip() {
+fn value_inputs_feed_authored_processors_and_round_trip() {
let mut session = new_session();
let input = add(&mut session, "input_value");
execute(&mut session, "graph.node.param", &json!({"id": input.0, "param": "default", "value": 0.35})).unwrap();
@@ -20,12 +20,22 @@ fn fresh_value_processors_accept_one_source_and_round_trip() {
NodeId(execute(&mut session, "graph.node.add", &json!({"def": "value_processor", "connectFrom": {"node": input.0}})).unwrap()["id"].as_u64().unwrap());
let second = add(&mut session, "value_processor");
execute(&mut session, "graph.connect", &json!({"from": input.0, "to": second.0, "toPort": "value1"})).unwrap();
+
assert_eq!(session.graph().unwrap().connections.len(), 2);
assert!(session.undo().is_some());
assert_eq!(session.graph().unwrap().connections.len(), 1);
assert_eq!(session.graph().unwrap().connections[0].to, first);
assert!(session.redo().is_some());
+
+ for node in [first, second] {
+ let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() };
+ assert_eq!(target.current(&session).unwrap(), &FunctionGraph::default());
+ let mut function = FunctionGraph::default();
+ function.output = Some(function.add("get_float1", &[], Some(Value::Text("value1".into()))));
+ execute(&mut session, "graph.function.set", &json!({"target": target, "function": function})).unwrap();
+ }
+
session.cook();
for node in [first, second] {
assert_eq!(session.cooked.value(node, 0), Some(&Value::Float(0.35)));
diff --git a/crates/engine/tests/graph_properties.rs b/crates/engine/tests/graph_properties.rs
new file mode 100644
index 00000000..9fbb5b7d
--- /dev/null
+++ b/crates/engine/tests/graph_properties.rs
@@ -0,0 +1,119 @@
+use materialcraft_engine::{
+ Session,
+ core::{Graph, Package},
+ execute,
+};
+use serde_json::json;
+
+#[test]
+fn attributes_target_an_unopened_graph_without_changing_the_canvas() {
+ let mut package = Package::new("Source");
+ package.graphs = vec![Graph::new("Canvas"), Graph::new("Inspected")];
+ let mut session = Session::new(package);
+
+ execute(&mut session, "graph.attributes", &json!({"graph": "Inspected", "description": "Edited elsewhere", "label": "Readable name"})).unwrap();
+
+ assert_eq!(session.graph, 0);
+ assert!(session.pkg.graphs[0].attributes.description.is_empty());
+ assert_eq!(session.pkg.graphs[1].attributes.description, "Edited elsewhere");
+ assert_eq!(serde_json::to_value(&session.pkg.graphs[1].attributes).unwrap()["label"], "Readable name");
+}
+
+#[test]
+fn another_documents_properties_have_their_own_undo_history() {
+ let mut package = Package::new("Source");
+ package.graphs.push(Graph::new("Inspected"));
+ let mut session = Session::new(package);
+ let source = session.document_id;
+ execute(&mut session, "file.newPackage", &json!({"name": "Canvas"})).unwrap();
+ execute(&mut session, "file.new", &json!({"template": "empty"})).unwrap();
+ let active = session.document_id;
+ let history = session.history();
+ let selection = session.selection.clone();
+
+ execute(&mut session, "graph.attributes", &json!({"document": source, "graph": 0, "description": "Saved on source"})).unwrap();
+
+ assert_eq!(session.document_id, active);
+ assert_eq!(session.history(), history);
+ assert_eq!(session.selection, selection);
+ assert!(session.graph().unwrap().attributes.description.is_empty());
+ execute(&mut session, "package.activate", &json!({"document": source})).unwrap();
+ assert_eq!(session.graph().unwrap().attributes.description, "Saved on source");
+ assert!(session.modified);
+ execute(&mut session, "edit.undo", &json!({})).unwrap();
+ assert!(session.graph().unwrap().attributes.description.is_empty());
+ assert!(!session.modified);
+ execute(&mut session, "edit.redo", &json!({})).unwrap();
+ assert_eq!(session.graph().unwrap().attributes.description, "Saved on source");
+}
+
+#[test]
+fn invalid_attribute_updates_are_atomic_in_inactive_documents() {
+ let mut package = Package::new("Source");
+ package.graphs.push(Graph::new("Inspected"));
+ let mut session = Session::new(package);
+ let source = session.document_id;
+ execute(&mut session, "file.newPackage", &json!({"name": "Canvas"})).unwrap();
+ let original = materialcraft_engine::GraphTarget { document: source, graph: 0 }.package(&session).unwrap().clone();
+
+ assert!(execute(&mut session, "graph.attributes", &json!({"document": source, "graph": 0, "label": "Partial edit", "description": 42})).is_err());
+
+ assert_eq!(*materialcraft_engine::GraphTarget { document: source, graph: 0 }.package(&session).unwrap(), original);
+ assert!(!session.open_packages().iter().find(|(id, _, _, _)| *id == source).unwrap().3);
+ assert!(execute(&mut session, "graph.properties", &json!({"document": u64::MAX})).is_err());
+ assert!(execute(&mut session, "graph.properties", &json!({"document": source, "graph": u64::MAX})).is_err());
+}
+
+#[test]
+fn inactive_material_base_parameters_and_identifier_target_the_inspected_graph() {
+ let mut package = Package::new("Source");
+ package.graphs = vec![Graph::new("Canvas"), Graph::new("Inspected")];
+ let mut session = Session::new(package);
+ let source = session.document_id;
+ execute(&mut session, "file.newPackage", &json!({"name": "Other"})).unwrap();
+
+ for (command, mut parameters) in [
+ ("graph.size", json!({"log2": [8, 9]})),
+ ("graph.seed", json!({"seed": 12})),
+ ("graph.format", json!({"format": "f32"})),
+ ("graph.rename", json!({"name": "Renamed"})),
+ ] {
+ parameters["document"] = json!(source);
+ parameters["graph"] = json!(1);
+ execute(&mut session, command, ¶meters).unwrap();
+ }
+
+ let graph = materialcraft_engine::GraphTarget { document: source, graph: 1 }.get(&session).unwrap();
+ assert_eq!(graph.name, "Renamed");
+ assert_eq!(graph.size, [8, 9]);
+ assert_eq!(graph.seed, 12);
+ assert_eq!(graph.format, materialcraft_engine::core::OutputFormat::F32);
+ assert_eq!(execute(&mut session, "graph.properties", &json!({"document": source, "graph": "Renamed"})).unwrap()["identifier"], "Renamed");
+ assert_ne!(session.document_id, source);
+}
+
+#[test]
+fn a_function_label_updates_instances_without_renaming_references() {
+ use materialcraft_engine::core::{FunctionGraph, Value};
+ let mut source = Graph::new("Stable_identifier");
+ source.function = Some(FunctionGraph::constant(Value::Float(1.0)));
+ let mut caller = Graph::new("Caller");
+ caller.function = Some(FunctionGraph::default());
+ let mut package = Package::new("Labels");
+ package.graphs = vec![source, caller];
+ let mut session = Session::new(package);
+ execute(&mut session, "graph.open", &json!({"graph": "Caller"})).unwrap();
+ execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Stable_identifier"})).unwrap();
+
+ execute(&mut session, "graph.attributes", &json!({"graph": "Stable_identifier", "label": "Readable label"})).unwrap();
+
+ let function = session.graph().unwrap().function.as_ref().unwrap();
+ let node = &function.nodes[0];
+ assert_eq!(materialcraft_engine::nodes::function::node_label(node), "Readable label");
+ assert_eq!(node.instance.as_ref().unwrap().graph, "Stable_identifier");
+ let bytes = materialcraft_engine::file_cmds::save_bytes(&session).unwrap();
+ let reopened = Session::new(materialcraft_engine::formats::sbs::read_sbs(&bytes, "labels.sbs", &|_| None).unwrap().pkg);
+ let node = &reopened.pkg.graphs[1].function.as_ref().unwrap().nodes[0];
+ assert_eq!(materialcraft_engine::nodes::function::node_label(node), "Readable label");
+ assert_eq!(node.instance.as_ref().unwrap().graph, "Stable_identifier");
+}
diff --git a/crates/engine/tests/linked_resources.rs b/crates/engine/tests/linked_resources.rs
new file mode 100644
index 00000000..d16468c2
--- /dev/null
+++ b/crates/engine/tests/linked_resources.rs
@@ -0,0 +1,94 @@
+use materialcraft_engine::{
+ Session,
+ core::{FunctionGraph, Graph, Package, Resource, ResourceBytes, Value},
+ execute, file_cmds,
+ formats::sbs,
+};
+use serde_json::json;
+
+const TILE: &[u8] = br#""#;
+
+fn resource_package(source: &str) -> Package {
+ let mut package = Package::new("Resource resolution");
+ let mut graph = Graph::new("Constant");
+ graph.function = Some(FunctionGraph::constant(Value::Float(0.5)));
+ package.graphs.push(graph);
+ let mut resource = Resource::new("Tile", "tile.svg", ResourceBytes::new(Vec::new()));
+ resource.source = source.into();
+ package.resources.push(resource);
+ package
+}
+
+#[test]
+fn library_resources_resolve_next_to_their_package() {
+ const CHILD_ROOT: &str = "MC_LINKED_RESOURCES_TEST_ROOT";
+ if let Ok(root) = std::env::var(CHILD_ROOT) {
+ verify_library_resources(std::path::Path::new(&root));
+ return;
+ }
+
+ // A child process isolates the library root without mutating the test runner's environment
+ let root = std::env::temp_dir().join(format!("materialcraft-linked-resources-{}", std::process::id()));
+ std::fs::create_dir_all(root.join("assets/sbs/resources")).unwrap();
+ std::fs::create_dir_all(root.join("assets/sbs/nested/resources")).unwrap();
+ std::fs::write(root.join("assets/sbs/resources/tile.svg"), TILE).unwrap();
+ std::fs::write(root.join("assets/sbs/nested/resources/tile.svg"), TILE).unwrap();
+ let package = sbs::write_sbs(&resource_package("resources/tile.svg")).unwrap();
+ std::fs::write(root.join("assets/sbs/functions.sbs"), &package).unwrap();
+ std::fs::write(root.join("assets/sbs/nested/source.sbs"), &package).unwrap();
+
+ let status = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "library_resources_resolve_next_to_their_package", "--nocapture"])
+ .env(CHILD_ROOT, &root)
+ .env("MATERIALCRAFT_SBS_DIR", root.join("assets/sbs"))
+ .status()
+ .unwrap();
+ std::fs::remove_dir_all(root).unwrap();
+
+ assert!(status.success());
+}
+
+fn verify_library_resources(root: &std::path::Path) {
+ let mut session = Session::new(Package::new("Caller"));
+ let library = session.pkg.dependencies.get("sbs://functions.sbs").unwrap();
+ assert_eq!(library.resources[0].bytes.as_slice(), TILE);
+
+ file_cmds::open_file(&mut session, "sbs://nested/source.sbs").unwrap();
+ assert!(session.load_warnings.is_empty(), "{:?}", session.load_warnings);
+ assert_eq!(session.pkg.resources[0].bytes.as_slice(), TILE);
+ execute(&mut session, "file.reload", &json!({})).unwrap();
+ assert_eq!(session.pkg.resources[0].bytes.as_slice(), TILE);
+
+ let read = file_cmds::linked_files("sbs://nested/source.sbs");
+ assert_eq!(read("resources/tile.svg").unwrap(), TILE);
+ assert_eq!(read("sbs://resources/tile.svg").unwrap(), TILE);
+ assert_eq!(read("../resources/tile.svg").unwrap(), TILE);
+ assert!(read("../../private.svg").is_none());
+ assert!(read("resources/absent.svg").is_none());
+
+ // Saving embeds loaded resources so a relocated package remains self-contained
+ let saved = file_cmds::save_bytes(&session).unwrap();
+ let reopened = sbs::read_sbs(&saved, "elsewhere/copy.sbs", &|_| None).unwrap();
+ assert!(reopened.warnings.is_empty(), "{:?}", reopened.warnings);
+ assert_eq!(reopened.pkg.resources[0].bytes.as_slice(), TILE);
+
+ let source_document = session.document_id;
+ execute(&mut session, "file.newPackage", &json!({})).unwrap();
+ execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap();
+ execute(&mut session, "graph.instance.add", &json!({"document": source_document, "graph": "Constant"})).unwrap();
+ let caller = file_cmds::save_bytes(&session).unwrap();
+ let mut dependent = Session::new(Package::new("Dependent"));
+ file_cmds::open_bytes(&mut dependent, &caller, Some(root.join("dependent.sbs").to_string_lossy().into_owned())).unwrap();
+ assert_eq!(dependent.pkg.dependencies["sbs://nested/source.sbs"].resources[0].bytes.as_slice(), TILE);
+
+ let missing = sbs::write_sbs(&resource_package("resources/absent.svg")).unwrap();
+ file_cmds::open_bytes_linked(&mut session, &missing, Some("sbs://nested/missing.sbs".into()), &read).unwrap();
+ assert!(session.pkg.resources[0].bytes.is_empty());
+ assert_eq!(session.pkg.resources[0].source, "sbs://nested/resources/absent.svg");
+ assert!(!session.load_warnings.is_empty());
+
+ let local = root.join("caller.sbs");
+ std::fs::write(&local, sbs::write_sbs(&resource_package("sbs://resources/tile.svg")).unwrap()).unwrap();
+ file_cmds::open_file(&mut session, local.to_str().unwrap()).unwrap();
+ assert_eq!(session.pkg.resources[0].bytes.as_slice(), TILE);
+}
diff --git a/crates/engine/tests/open_documents.rs b/crates/engine/tests/open_documents.rs
index 49c7ee90..83366cc5 100644
--- a/crates/engine/tests/open_documents.rs
+++ b/crates/engine/tests/open_documents.rs
@@ -8,15 +8,19 @@ fn opening_another_package_preserves_edits_selection_and_undo() {
let added = execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap();
let history = session.history();
let selection = session.selection.clone();
- let original = session.pkg.clone();
+ let original = file_cmds::save_bytes(&session).unwrap();
let bytes = formats::sbs::write_sbs(&Package::new("Second")).unwrap();
+
file_cmds::open_bytes(&mut session, &bytes, Some("second.sbs".into())).unwrap();
+
assert_eq!(inspect::session(&session, None)["documents"].as_array().unwrap().len(), 2);
execute(&mut session, "package.activate", &json!({"document": 0})).unwrap();
- assert_eq!(session.pkg, original);
+ // Other open packages extend the runtime dependency registry without editing this document
+ assert_eq!(file_cmds::save_bytes(&session).unwrap(), original);
assert_eq!(session.selection, selection);
assert_eq!(session.history(), history);
assert!(session.modified);
+
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert!(session.graph().unwrap().nodes.iter().all(|node| node.id.0 != added["id"].as_u64().unwrap()));
}
diff --git a/crates/engine/tests/system_variables.rs b/crates/engine/tests/system_variables.rs
new file mode 100644
index 00000000..5ccebbfc
--- /dev/null
+++ b/crates/engine/tests/system_variables.rs
@@ -0,0 +1,270 @@
+use materialcraft_engine::{
+ FunctionGraphTarget, Session,
+ core::{FunctionGraph, Graph, NodeId, Package, ParameterInheritance, Value},
+ execute,
+ formats::sbs::{read_sbs, write_sbs},
+ new_session,
+};
+use serde_json::json;
+
+fn getter(operation: &str, name: &str) -> FunctionGraph {
+ let mut function = FunctionGraph::default();
+ function.output = Some(function.add(operation, &[], Some(Value::Text(name.into()))));
+ function
+}
+
+fn processor(graph: &mut Graph, operation: &str, name: &str) -> NodeId {
+ let id = graph.add_node("value_processor", [0.0; 2]);
+ graph.node_mut(id).unwrap().params.insert("function".into(), Value::Function(Box::new(getter(operation, name))));
+ id
+}
+
+#[test]
+fn standalone_get_suggestions_match_each_type_and_order() {
+ let mut session = new_session();
+ execute(&mut session, "file.new", &json!({"kind": "function", "name": "Variables"})).unwrap();
+ for (operation, expected) in [
+ ("get_string", vec![]),
+ ("get_bool", vec![]),
+ ("get_integer4", vec![]),
+ ("get_integer3", vec![]),
+ ("get_integer2", vec!["$uvtile"]),
+ ("get_integer1", vec!["$normalformat", "$tiling", "$pixelratio"]),
+ ("get_float4", vec![]),
+ ("get_float3", vec!["$physicalsize"]),
+ ("get_float2", vec!["$size", "$sizelog2"]),
+ ("get_float1", vec!["$time"]),
+ ] {
+ let function = getter(operation, "ITypedThis");
+ let id = function.output.unwrap();
+ execute(&mut session, "graph.function.set", &json!({"function": function})).unwrap();
+ let before = session.pkg.clone();
+
+ let result = execute(&mut session, "graph.function.variables", &json!({"id": id})).unwrap();
+ let variables = result["variables"].as_array().unwrap();
+ let actual: Vec<_> = variables.iter().filter(|variable| variable["system"] == true).map(|variable| variable["name"].as_str().unwrap()).collect();
+
+ assert_eq!(actual, expected, "{operation}");
+ assert_eq!(variables.last().unwrap()["name"], "ITypedThis");
+ assert_eq!(session.pkg, before);
+ }
+}
+
+#[test]
+fn pixel_processor_suggestions_add_position_without_fx_variables() {
+ let mut graph = Graph::new("Pixels");
+ let owner = graph.add_node("pixel_processor", [0.0; 2]);
+ graph.node_mut(owner).unwrap().params.insert("function".into(), Value::Function(Box::new(getter("get_float2", ""))));
+ let mut package = Package::new("Pixels");
+ package.graphs.push(graph);
+ let session = Session::new(package);
+ let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() };
+
+ let variables = target.variables(&session, 1).unwrap();
+
+ assert_eq!(variables.iter().map(|variable| variable.name.as_str()).collect::>(), ["$size", "$sizelog2", "$pos"]);
+}
+
+#[test]
+fn graph_metadata_and_host_values_cook_and_round_trip_as_native_get_nodes() {
+ let mut graph = Graph::new("Context");
+ graph.size = [5, 4];
+ let cases = [
+ ("get_float1", "$time", Value::Float(2.5)),
+ ("get_integer2", "$uvtile", Value::Int2([7, 11])),
+ ("get_integer1", "$normalformat", Value::Int(1)),
+ ("get_integer1", "$tiling", Value::Int(2)),
+ ("get_integer1", "$pixelratio", Value::Int(1)),
+ ("get_float3", "$physicalsize", Value::Float3([20.0, 10.0, 0.5])),
+ ("get_float2", "$size", Value::Float2([32.0, 16.0])),
+ ("get_float2", "$sizelog2", Value::Float2([5.0, 4.0])),
+ ];
+ let ids: Vec<_> = cases.iter().map(|(operation, name, _)| processor(&mut graph, operation, name)).collect();
+ let mut package = Package::new("Context");
+ package.graphs.push(graph);
+ let mut session = Session::new(package);
+ execute(&mut session, "graph.context", &json!({"physicalSize": [20, 10, 0.5], "pixelRatio": 1, "tiling": [false, true]})).unwrap();
+ let environment = json!({"timeSeconds": 2.5, "uvTile": [7, 11], "normalFormat": 1});
+ execute(&mut session, "session.environment", &environment).unwrap();
+ let bytes = write_sbs(&session.pkg).unwrap();
+ let read = read_sbs(&bytes, "context.sbs", &|_| None).unwrap();
+ assert!(read.warnings.is_empty(), "{:?}", read.warnings);
+ let mut reopened = Session::new(read.pkg);
+ execute(&mut reopened, "session.environment", &environment).unwrap();
+
+ for session in [&mut session, &mut reopened] {
+ let cooked = session.cook();
+ for ((_, name, expected), id) in cases.iter().zip(&ids) {
+ let result = &cooked.nodes[id];
+ assert_eq!(result.error, None, "{name}");
+ assert_eq!(result.outputs[0].as_value(), Some(expected), "{name}");
+ }
+ assert!(session.cook().nodes.values().all(|result| result.cached));
+ let original = session.pkg.clone();
+ execute(session, "session.environment", &json!({"timeSeconds": 4.0})).unwrap();
+ let cooked = session.cook();
+ assert_eq!(cooked.nodes[&ids[0]].outputs[0].as_value(), Some(&Value::Float(4.0)));
+ assert!(!cooked.nodes[&ids[0]].cached);
+ assert!(cooked.nodes[&ids[1]].cached, "unrelated host variables keep their cache entries");
+ assert_eq!(session.pkg, original, "host values are not authored into the package");
+ }
+}
+
+#[test]
+fn pixel_ratio_and_tiling_inherit_and_preserve_native_relative_modes() {
+ let mut graph = Graph::new("Inheritance");
+ graph.size = [4, 4];
+ graph.tiling = [true, true];
+ let source = graph.add_node("uniform", [0.0; 2]);
+ let input = graph.node_mut(source).unwrap();
+ input.base.pixel_ratio = 1;
+ input.base.pixel_ratio_mode = ParameterInheritance::Absolute;
+ input.base.tiling = [true, false];
+ input.base.tiling_mode = ParameterInheritance::Absolute;
+ let pixel = graph.add_node("pixel_processor", [200.0, 0.0]);
+ let mut function = getter("get_integer1", "$pixelratio");
+ let ratio = function.output.unwrap();
+ let tiling = function.add("get_integer1", &[], Some(Value::Text("$tiling".into())));
+ let value = function.add("add", &[ratio, tiling], None);
+ function.output = Some(function.add("tofloat", &[value], None));
+ graph.node_mut(pixel).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
+ graph.connect(source, "output", pixel, "input0").unwrap();
+ let mut package = Package::new("Inheritance");
+ package.graphs.push(graph);
+ let mut session = Session::new(package);
+ session.selection = vec![pixel];
+
+ for (mode, expected) in [("relativeToInput", 2.0), ("relativeToParent", 3.0), ("absolute", 0.0)] {
+ execute(&mut session, "graph.node.base", &json!({"pixelRatio": 0, "tiling": false, "pixelRatioMode": mode, "tilingMode": mode})).unwrap();
+ let bytes = write_sbs(&session.pkg).unwrap();
+ let read = read_sbs(&bytes, "inheritance.sbs", &|_| None).unwrap();
+ assert!(read.warnings.is_empty(), "{:?}", read.warnings);
+ assert_eq!(read.pkg.graphs[0].node(pixel).unwrap().base, session.pkg.graphs[0].node(pixel).unwrap().base);
+ let mut reopened = Session::new(read.pkg);
+
+ for session in [&mut session, &mut reopened] {
+ let cooked = session.cook();
+ assert_eq!(cooked.nodes[&pixel].error, None);
+ assert!((cooked.image(pixel, 0).unwrap().mean()[0] - expected).abs() < 1e-6, "{mode}");
+ }
+ }
+}
+
+#[test]
+fn nested_graph_instances_inherit_host_values_and_invalidate_their_cache() {
+ let mut source = Graph::new("Source");
+ source.size = [4, 4];
+ let value = processor(&mut source, "get_float1", "$time");
+ let output = source.add_node("output", [200.0, 0.0]);
+ source.connect(value, "output", output, "input").unwrap();
+ let mut package = Package::new("Nested");
+ package.graphs.push(source);
+ for (name, reference) in [("Middle", "Source"), ("Outer", "Middle")] {
+ let mut graph = Graph::new(name);
+ graph.size = [4, 4];
+ let instance = graph.add_node("graph_instance", [0.0; 2]);
+ graph.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text(reference.into()));
+ let output = graph.add_node("output", [200.0, 0.0]);
+ graph.connect(instance, "output", output, "input").unwrap();
+ package.graphs.push(graph);
+ }
+ let mut session = Session::new(package);
+ session.graph = 2;
+ for seconds in [1.25, 8.5] {
+ execute(&mut session, "session.environment", &json!({"timeSeconds": seconds})).unwrap();
+
+ let cooked = session.cook();
+
+ for result in cooked.nodes.values() {
+ assert_eq!(result.error, None);
+ assert_eq!(result.outputs[0].as_value(), Some(&Value::Float(seconds)));
+ assert!(!result.cached);
+ }
+ assert!(session.cook().nodes.values().all(|result| result.cached));
+ }
+}
+
+fn function_instance(name: &str, type_code: u32) -> FunctionGraph {
+ let mut function = FunctionGraph::default();
+ let id = function.add("instance", &[], None);
+ function.nodes[0].instance = Some(materialcraft_engine::core::GraphInstance {
+ label: String::new(),
+ package: String::new(),
+ graph: name.into(),
+ inputs: Vec::new(),
+ outputs: vec![materialcraft_engine::core::GraphPort { identifier: "output".into(), type_code }],
+ defaults: Default::default(),
+ });
+ function.output = Some(id);
+ function
+}
+
+#[test]
+fn nested_function_instances_use_the_processing_callers_variable_scope() {
+ let mut package = Package::new("Caller scope");
+ let mut source = Graph::new("Position");
+ source.function = Some(getter("get_float2", "$pos"));
+ package.graphs.push(source);
+ let mut wrapper = Graph::new("NestedPosition");
+ wrapper.function = Some(function_instance("Position", 512));
+ package.graphs.push(wrapper);
+ let mut graph = Graph::new("Material");
+ graph.size = [4, 4];
+ let pixel = graph.add_node("pixel_processor", [0.0; 2]);
+ let value = graph.add_node("value_processor", [200.0, 0.0]);
+ for id in [pixel, value] {
+ graph.node_mut(id).unwrap().params.insert("function".into(), Value::Function(Box::new(function_instance("NestedPosition", 512))));
+ }
+ package.graphs.push(graph);
+ let mut session = Session::new(package);
+ let bytes = write_sbs(&session.pkg).unwrap();
+ let mut reopened = Session::new(read_sbs(&bytes, "scope.sbs", &|_| None).unwrap().pkg);
+
+ for session in [&mut session, &mut reopened] {
+ session.graph = 2;
+ let cooked = session.cook();
+
+ assert_eq!(cooked.nodes[&pixel].error, None);
+ assert!(cooked.nodes[&value].error.as_deref().unwrap().contains("undefined variable `$pos`"));
+ let image = cooked.image(pixel, 0).unwrap();
+ assert_eq!(&image.get(0, 0, false)[..2], &[0.03125; 2]);
+ assert_eq!(&image.get(15, 15, false)[..2], &[0.96875; 2]);
+ }
+}
+
+#[test]
+fn environment_errors_are_atomic_and_graph_context_is_undoable() {
+ let mut session = new_session();
+ let original_environment = session.environment;
+ let original_package = session.pkg.clone();
+ for parameters in [json!({"timeSeconds": -1}), json!({"timeSeconds": 1e100}), json!({"timeSeconds": 2, "uvTile": [1]}), json!({"normalFormat": "invalid"})]
+ {
+ assert!(execute(&mut session, "session.environment", ¶meters).is_err());
+ assert_eq!(session.environment, original_environment);
+ assert_eq!(session.pkg, original_package);
+ }
+ for parameters in [json!({"physicalSize": [1, 2]}), json!({"physicalSize": [-1, 2, 3]}), json!({"pixelRatio": 3}), json!({"tiling": [true]})] {
+ assert!(execute(&mut session, "graph.context", ¶meters).is_err());
+ assert_eq!(session.pkg, original_package);
+ }
+
+ execute(&mut session, "graph.context", &json!({"physicalSize": [2, 3, 4], "pixelRatio": 0})).unwrap();
+ assert_eq!(session.graph().unwrap().physical_size, [2.0, 3.0, 4.0]);
+ assert_eq!(session.graph().unwrap().pixel_ratio_mode, ParameterInheritance::Absolute);
+ session.undo().unwrap();
+ assert_eq!(session.pkg, original_package);
+ session.redo().unwrap();
+ assert_eq!(session.graph().unwrap().physical_size, [2.0, 3.0, 4.0]);
+}
+
+#[test]
+fn reusable_functions_cannot_author_context_that_belongs_to_their_caller() {
+ let mut session = new_session();
+ execute(&mut session, "file.new", &json!({"kind": "function", "name": "Caller context"})).unwrap();
+ let original = session.pkg.clone();
+
+ let error = execute(&mut session, "graph.context", &json!({"physicalSize": [1, 2, 3]})).unwrap_err();
+
+ assert!(error.to_string().contains("caller's evaluation context"));
+ assert_eq!(session.pkg, original);
+}
diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs
index a9c48c19..7a84fa08 100644
--- a/crates/eval/src/graph_execution.rs
+++ b/crates/eval/src/graph_execution.rs
@@ -29,7 +29,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
options
};
- let prepared = PreparedGraph::new(package, graph, options.only.as_deref());
+ let prepared = PreparedGraph::new(package, graph, options);
// Exposed parameter values: the graph's own, then the caller's overrides
let mut variables: BTreeMap =
@@ -37,6 +37,11 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
for (name, value) in &options.overrides {
variables.insert(name.clone(), value.clone());
}
+ variables.insert("$time".into(), Value::Float(options.environment.time_seconds));
+ variables.insert("$uvtile".into(), Value::Int2(options.environment.uv_tile));
+ variables.insert("$normalformat".into(), Value::Int(options.environment.normal_format));
+ variables.insert("$physicalsize".into(), Value::Float3(graph.physical_size));
+
for &id in &prepared.order {
if options.cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
cooked.cancelled = true;
diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs
index 4ed35dce..d5928db7 100644
--- a/crates/eval/src/graph_instance.rs
+++ b/crates/eval/src/graph_instance.rs
@@ -45,6 +45,7 @@ pub(crate) fn cook_instance(
inputs: &[Option<&NodeOutput>],
params: &BTreeMap,
size: (u32, u32),
+ base: crate::resolved_base_parameters::ResolvedBaseParameters,
opts: &Options,
cache: &Mutex,
) -> Result, String> {
@@ -69,6 +70,9 @@ pub(crate) fn cook_instance(
_ => (opts.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.registry = Some(registry);
o.resource_root = Some(root_resource);
o.max_size = opts.max_size;
diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs
index 3fea0cce..aee73603 100644
--- a/crates/eval/src/lib.rs
+++ b/crates/eval/src/lib.rs
@@ -17,6 +17,7 @@ mod parameter;
mod port;
mod ports;
mod prepared_graph;
+mod resolved_base_parameters;
mod resource_decoder;
mod time;
mod value_execution;
diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs
index dbe98ee4..de70ee85 100644
--- a/crates/eval/src/node_execution.rs
+++ b/crates/eval/src/node_execution.rs
@@ -80,6 +80,13 @@ pub(crate) fn cook_node(
incoming.push(output);
}
+ let base = prepared.base_parameters(node);
+ if !node.functions.is_empty() || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map") {
+ let tiling = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1);
+ variables.to_mut().insert("$tiling".into(), Value::Int(tiling));
+ variables.to_mut().insert("$pixelratio".into(), Value::Int(base.pixel_ratio));
+ }
+
let vars = &variables;
let first = prepared.first_input_size(node.id);
let (w, h) = node_size(graph, def, node, first, opts.max_size);
@@ -101,7 +108,7 @@ pub(crate) fn cook_node(
Err(error) => return fail(error, 0),
};
- let tile = node.base.tiling[0] && node.base.tiling[1];
+ let tile = base.tiling[0] && base.tiling[1];
// Input nodes read the caller's image for their identifier
let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten();
let res_hash = match params.get("resource") {
@@ -119,10 +126,12 @@ pub(crate) fn cook_node(
let key = hash_of(&(
&node.def,
serde_json::to_string(¶ms).unwrap_or_default(),
- (w, h, seed, tile, node.disabled),
+ (w, h, seed, tile, node.disabled, base.tiling, base.pixel_ratio),
&input_keys,
res_hash,
sub_hash,
+ // A cached graph instance includes results evaluated with its host environment
+ (node.def == "graph_instance").then(|| serde_json::to_string(&opts.environment).unwrap_or_default()),
input_img.map(|image| image_key(image, cache)),
variable_key(node, ¶ms, vars),
));
@@ -150,7 +159,7 @@ pub(crate) fn cook_node(
Err(format!("unsupported node `{name}`"))
} else if node.def == "graph_instance" {
- cook_instance(pkg, gi, node, in_ports, out_ports, &incoming, ¶ms, (w, h), opts, cache)
+ cook_instance(pkg, gi, node, in_ports, out_ports, &incoming, ¶ms, (w, h), base, opts, cache)
} else if let Some(definition) = def {
let context = CookContext { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars };
(definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect())
diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs
index a28716c3..91d0bd56 100644
--- a/crates/eval/src/options.rs
+++ b/crates/eval/src/options.rs
@@ -5,6 +5,9 @@ use std::sync::atomic::AtomicBool;
/// What to cook and how
pub struct Options<'a> {
+ pub environment: materialcraft_core::EvaluationEnvironment,
+ pub parent_tiling: Option<[bool; 2]>,
+ pub parent_pixel_ratio: Option,
/// Cap on the larger side of every node's output (previews); `None` = full size
pub max_size: Option,
/// Cook only these nodes and what they depend on (`None` = the whole graph)
@@ -28,6 +31,9 @@ pub struct Options<'a> {
impl<'a> Options<'a> {
pub fn new(resource: &'a crate::ResourceDecoder<'a>) -> Options<'a> {
Options {
+ environment: Default::default(),
+ parent_tiling: None,
+ parent_pixel_ratio: None,
max_size: None,
only: None,
inputs: BTreeMap::new(),
diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs
index 5d2a7b57..4005a931 100644
--- a/crates/eval/src/parameter.rs
+++ b/crates/eval/src/parameter.rs
@@ -29,6 +29,7 @@ pub(crate) fn resolve_parameters(
match materialcraft_nodes::function::compile(f, seed) {
Ok(prog) => {
let context = materialcraft_nodes::function::EvaluationContext {
+ scope: Default::default(),
position: [0.5; 2],
size: size.map(|side| side as f32),
images: &[],
diff --git a/crates/eval/src/prepared_graph.rs b/crates/eval/src/prepared_graph.rs
index d34d0c6e..615b69c9 100644
--- a/crates/eval/src/prepared_graph.rs
+++ b/crates/eval/src/prepared_graph.rs
@@ -7,13 +7,15 @@ pub(crate) struct PreparedGraph<'a> {
pub index: GraphIndex<'a>,
pub order: Vec,
nominal_sizes: BTreeMap,
+ base_parameters: BTreeMap,
+ parent_base: crate::resolved_base_parameters::ResolvedBaseParameters,
ports: BTreeMap, Vec)>,
}
impl<'a> PreparedGraph<'a> {
- pub fn new(package: &Package, graph: &'a Graph, roots: Option<&[NodeId]>) -> Self {
+ pub fn new(package: &Package, graph: &'a Graph, options: &crate::Options<'_>) -> Self {
let index = GraphIndex::new(graph);
- let needed = roots.map(|roots| index.required_nodes(roots));
+ let needed = options.only.as_deref().map(|roots| index.required_nodes(roots));
let order: Vec<_> = index.topo_order().into_iter().filter(|id| needed.as_ref().is_none_or(|needed| needed.contains(id))).collect();
let ports = order
.iter()
@@ -23,7 +25,8 @@ impl<'a> PreparedGraph<'a> {
})
.collect();
- let mut prepared = Self { index, order, ports, nominal_sizes: BTreeMap::new() };
+ let parent_base = crate::resolved_base_parameters::ResolvedBaseParameters::graph(graph, options);
+ let mut prepared = Self { index, order, ports, nominal_sizes: BTreeMap::new(), base_parameters: BTreeMap::new(), parent_base };
for &id in &prepared.order {
let Some(node) = prepared.index.node(id) else { continue };
@@ -34,6 +37,12 @@ impl<'a> PreparedGraph<'a> {
crate::node_size(graph, materialcraft_nodes::find(&node.def), node, input, None)
};
prepared.nominal_sizes.insert(id, nominal);
+ let input_base = prepared.ports(id).0.iter().filter(|port| port.kind != materialcraft_nodes::PortKind::Value).find_map(|port| {
+ let connection = prepared.index.input_of(id, &port.id)?;
+ prepared.base_parameters.get(&connection.from).copied()
+ });
+ let base = crate::resolved_base_parameters::ResolvedBaseParameters::resolve(&node.base, input_base, parent_base);
+ prepared.base_parameters.insert(id, base);
}
prepared
}
@@ -48,4 +57,11 @@ impl<'a> PreparedGraph<'a> {
pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) {
self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice()))
}
+
+ pub fn base_parameters(&self, node: &materialcraft_core::Node) -> crate::resolved_base_parameters::ResolvedBaseParameters {
+ self.base_parameters
+ .get(&node.id)
+ .copied()
+ .unwrap_or_else(|| crate::resolved_base_parameters::ResolvedBaseParameters::resolve(&node.base, None, self.parent_base))
+ }
}
diff --git a/crates/eval/src/resolved_base_parameters.rs b/crates/eval/src/resolved_base_parameters.rs
new file mode 100644
index 00000000..94baaa28
--- /dev/null
+++ b/crates/eval/src/resolved_base_parameters.rs
@@ -0,0 +1,23 @@
+use materialcraft_core::{BaseParameters, Graph};
+
+#[derive(Clone, Copy)]
+pub(crate) struct ResolvedBaseParameters {
+ pub tiling: [bool; 2],
+ pub pixel_ratio: i32,
+}
+
+impl ResolvedBaseParameters {
+ pub fn graph(graph: &Graph, options: &crate::Options<'_>) -> Self {
+ Self {
+ tiling: graph.tiling_mode.resolve(graph.tiling, options.parent_tiling, options.parent_tiling.unwrap_or(graph.tiling)),
+ pixel_ratio: graph.pixel_ratio_mode.resolve(graph.pixel_ratio, options.parent_pixel_ratio, options.parent_pixel_ratio.unwrap_or(graph.pixel_ratio)),
+ }
+ }
+
+ pub fn resolve(base: &BaseParameters, input: Option, parent: Self) -> Self {
+ Self {
+ tiling: base.tiling_mode.resolve(base.tiling, input.map(|input| input.tiling), parent.tiling),
+ pixel_ratio: base.pixel_ratio_mode.resolve(base.pixel_ratio, input.map(|input| input.pixel_ratio), parent.pixel_ratio),
+ }
+ }
+}
diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs
index f1271949..ee5991bb 100644
--- a/crates/eval/src/tests.rs
+++ b/crates/eval/src/tests.rs
@@ -42,6 +42,31 @@ fn cooks_and_caches() {
assert_eq!(outputs(&p.graphs[0], &c).len(), 1);
}
+#[test]
+fn processor_tiling_variable_tracks_both_axes_and_invalidates_cached_values() {
+ let mut function = materialcraft_core::FunctionGraph::default();
+ function.output = Some(function.add("get_integer1", &[], Some(Value::Text("$tiling".into()))));
+ let mut graph = Graph::new("Tiling");
+ let processor = graph.add_node("value_processor", [0.0; 2]);
+ graph.node_mut(processor).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
+ let mut package = Package::new("Tiling");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+
+ for (tiling, expected) in [([false, false], 0), ([true, false], 1), ([false, true], 2), ([true, true], 3)] {
+ package.graphs[0].node_mut(processor).unwrap().base.tiling = tiling;
+ package.graphs[0].node_mut(processor).unwrap().base.tiling_mode = materialcraft_core::ParameterInheritance::Absolute;
+ let result = cook(&package, 0, &Options::new(&no_res), &cache);
+
+ assert_eq!(result.nodes[&processor].error, None);
+ assert_eq!(result.nodes[&processor].outputs[0].as_value(), Some(&Value::Int(expected)));
+ assert!(!result.nodes[&processor].cached);
+ let cached = cook(&package, 0, &Options::new(&no_res), &cache);
+ assert!(cached.nodes[&processor].cached);
+ assert_eq!(cached.nodes[&processor].outputs[0].as_value(), Some(&Value::Int(expected)));
+ }
+}
+
#[test]
fn hostile_param_is_clamped_before_cooking() {
let (mut p, noise, _, _) = sample();
@@ -229,6 +254,8 @@ fn input_change_recooks_only_readers() {
let (mut p, noise, blur, out) = sample();
let reader = p.graphs[0].add_node("pixel_processor", [0.0, 100.0]);
let get_a = FunctionNode {
+ missing: None,
+ missing_data: String::new(),
instance: None,
source: None,
id: 1,
diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs
index ee72c631..6ed651cf 100644
--- a/crates/eval/src/value_execution.rs
+++ b/crates/eval/src/value_execution.rs
@@ -17,7 +17,7 @@ pub(crate) fn evaluate_value(
};
let program = compile(graph, seed)?;
- let context = EvaluationContext { position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables };
+ let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables };
program.evaluate(&context, &mut EvaluationState::default())
}
diff --git a/crates/formats/examples/standard_function_library/convert.rs b/crates/formats/examples/standard_function_library/convert.rs
new file mode 100644
index 00000000..6c88540c
--- /dev/null
+++ b/crates/formats/examples/standard_function_library/convert.rs
@@ -0,0 +1,46 @@
+use materialcraft_core::{Package, ValueType};
+use materialcraft_nodes::function;
+
+pub(super) fn package(bytes: &[u8], source: &str) -> Result> {
+ let imported = materialcraft_formats::sbs::read_sbs(bytes, source, &|_| None)?;
+ if !imported.warnings.is_empty() {
+ return Err(imported.warnings.join("\n").into());
+ }
+
+ if !imported.pkg.resources.is_empty() {
+ return Err("function library conversion does not copy resource assets".into());
+ }
+
+ let mut package = imported.pkg.clone();
+ for graph in &mut package.graphs {
+ let path = graph.sbs_path();
+ let body = graph.function.as_mut().ok_or_else(|| format!("{path}: expected a Function Graph"))?;
+ if body.nodes.iter().any(|node| node.missing.is_some()) {
+ return Err(format!("{path}: contains unsupported operations").into());
+ }
+
+ // Resolve a temporary body so validation cannot rewrite the source connector contract
+ let mut resolved = body.clone();
+ function::resolve_instances(&mut resolved, &imported.pkg, &imported.pkg.dependencies);
+ function::compile(&resolved, 0).map_err(|error| format!("{path}: {error}"))?;
+ crate::layout::reposition(body).map_err(|error| format!("{path}: {error}"))?;
+
+ let result = ValueType::from_code(graph.function_type).ok_or_else(|| format!("{path}: unknown result type"))?;
+ let inputs = if graph.exposed.is_empty() {
+ "none".to_string()
+ } else {
+ graph.exposed.iter().map(|parameter| parameter.id.as_str()).collect::>().join(", ")
+ };
+ graph.attributes.description = format!("Evaluates the {} function graph. Result type: {}. Inputs: {inputs}.", graph.name, result.label());
+ graph.attributes.category = graph.folder.clone();
+ graph.attributes.author.clear();
+ graph.attributes.author_url.clear();
+ graph.attributes.user_data.clear();
+ graph.attributes.tags.clear();
+ graph.frames.clear();
+ graph.comments.clear();
+ graph.pins.clear();
+ }
+
+ Ok(package)
+}
diff --git a/crates/formats/examples/standard_function_library/layout.rs b/crates/formats/examples/standard_function_library/layout.rs
new file mode 100644
index 00000000..d3b62298
--- /dev/null
+++ b/crates/formats/examples/standard_function_library/layout.rs
@@ -0,0 +1,56 @@
+use materialcraft_core::FunctionGraph;
+use std::collections::{BTreeMap, VecDeque};
+
+pub(super) fn reposition(function: &mut FunctionGraph) -> Result<(), String> {
+ if function.nodes.len() > 4096 {
+ return Err("function exceeds the 4096-node limit".into());
+ }
+
+ let mut pending = BTreeMap::new();
+ let mut successors = BTreeMap::>::new();
+ let mut columns = BTreeMap::::new();
+ let mut ready = VecDeque::new();
+ for node in &function.nodes {
+ if pending.insert(node.id, node.inputs.iter().flatten().count()).is_some() {
+ return Err("duplicate node identifier".into());
+ }
+
+ if node.inputs.iter().all(Option::is_none) {
+ ready.push_back(node.id);
+ }
+ for input in node.inputs.iter().flatten() {
+ successors.entry(*input).or_default().push(node.id);
+ }
+ }
+ if successors.keys().any(|identifier| !pending.contains_key(identifier)) {
+ return Err("connection references a missing node".into());
+ }
+
+ let mut visited = 0;
+ while let Some(identifier) = ready.pop_front() {
+ visited += 1;
+ let next_column = columns.get(&identifier).copied().unwrap_or(0) + 1;
+ for successor in successors.get(&identifier).into_iter().flatten() {
+ let column = columns.entry(*successor).or_default();
+ *column = (*column).max(next_column);
+ let remaining = pending.get_mut(successor).ok_or("missing successor")?;
+ *remaining = remaining.checked_sub(1).ok_or("inconsistent connection count")?;
+ if *remaining == 0 {
+ ready.push_back(*successor);
+ }
+ }
+ }
+ if visited != function.nodes.len() {
+ return Err("function contains a connection cycle".into());
+ }
+
+ let mut heights = BTreeMap::::new();
+ for node in &mut function.nodes {
+ let column = columns.get(&node.id).copied().unwrap_or(0);
+ let height = heights.entry(column).or_default();
+ node.pos = [64.0 + column as f32 * 280.0, 64.0 + *height];
+ *height += (80.0 + node.inputs.len() as f32 * 28.0).max(160.0);
+ }
+
+ Ok(())
+}
diff --git a/crates/formats/examples/standard_function_library/main.rs b/crates/formats/examples/standard_function_library/main.rs
new file mode 100644
index 00000000..ef77427c
--- /dev/null
+++ b/crates/formats/examples/standard_function_library/main.rs
@@ -0,0 +1,37 @@
+#![forbid(unsafe_code)]
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+
+mod convert;
+mod layout;
+
+#[cfg(test)]
+#[allow(clippy::unwrap_used, clippy::expect_used)]
+mod tests;
+
+use std::{io::Read, path::Path};
+
+fn main() -> Result<(), Box> {
+ let mut arguments = std::env::args().skip(1);
+ let source = arguments.next().ok_or("usage: standard_function_library [destination.sbs]")?;
+ let destination = arguments.next().unwrap_or_else(|| "assets/sbs/functions.sbs".into());
+ if arguments.next().is_some() {
+ return Err("usage: standard_function_library [destination.sbs]".into());
+ }
+
+ // Bound allocation before parsing potentially untrusted XML
+ const MAX_BYTES: u64 = 256 << 20;
+ let mut bytes = Vec::new();
+ std::fs::File::open(&source)?.take(MAX_BYTES + 1).read_to_end(&mut bytes)?;
+ if bytes.len() as u64 > MAX_BYTES {
+ return Err("source package exceeds 256 MiB".into());
+ }
+
+ let package = convert::package(&bytes, &source)?;
+ let nodes: usize = package.graphs.iter().flat_map(|graph| graph.functions()).map(|function| function.nodes.len()).sum();
+ let saved = materialcraft_formats::sbs::write_sbs(&package)?;
+ materialcraft_formats::write_atomic(Path::new(&destination), &saved)?;
+
+ eprintln!("Saved {} function graphs and {nodes} nodes to {destination}", package.graphs.len());
+ eprintln!("Descriptions and layout were rewritten; source graph rights are unchanged.");
+ Ok(())
+}
diff --git a/crates/formats/examples/standard_function_library/tests.rs b/crates/formats/examples/standard_function_library/tests.rs
new file mode 100644
index 00000000..45bcdff8
--- /dev/null
+++ b/crates/formats/examples/standard_function_library/tests.rs
@@ -0,0 +1,66 @@
+use materialcraft_core::{FunctionGraph, Graph, Package, Value};
+use materialcraft_formats::sbs::{read_sbs, write_sbs};
+
+#[test]
+fn conversion_preserves_function_bodies_and_replaces_presentation_metadata() {
+ let mut package = Package::new("Functions");
+ let mut graph = Graph::new("AddOne");
+ graph.folder = "Functions/Math".into();
+ graph.attributes.description = "Source description".into();
+ graph.attributes.author = "Source author".into();
+ graph.attributes.author_url = "https://example.org/source".into();
+ graph.attributes.user_data = "Source notes".into();
+ graph.attributes.tags = "Source tags".into();
+ graph.function_type = 256;
+ let mut body = FunctionGraph::default();
+ let left = body.add_constant(Value::Float(1.0));
+ let right = body.add_constant(Value::Float(2.0));
+ body.output = Some(body.add("add", &[left, right], None));
+ graph.function = Some(body);
+ package.graphs.push(graph);
+ let bytes = write_sbs(&package).unwrap();
+ let imported = read_sbs(&bytes, "source.sbs", &|_| None).unwrap().pkg;
+
+ let converted = super::convert::package(&bytes, "source.sbs").unwrap();
+ let exported = write_sbs(&converted).unwrap();
+ let reopened = read_sbs(&exported, "converted.sbs", &|_| None).unwrap().pkg;
+
+ assert_eq!(converted.graphs[0].sbs_path(), "Functions/Math/AddOne");
+ assert_ne!(converted.graphs[0].attributes.description, imported.graphs[0].attributes.description);
+ assert!(converted.graphs[0].attributes.author.is_empty());
+ assert!(converted.graphs[0].attributes.author_url.is_empty());
+ assert!(converted.graphs[0].attributes.user_data.is_empty());
+ assert!(converted.graphs[0].attributes.tags.is_empty());
+ assert_eq!(converted.graphs[0].function, reopened.graphs[0].function);
+ let mut restored = converted.graphs[0].function.clone().unwrap();
+ let original = imported.graphs[0].function.as_ref().unwrap();
+ for (node, source) in restored.nodes.iter_mut().zip(&original.nodes) {
+ assert_ne!(node.pos, source.pos);
+ node.pos = source.pos;
+ }
+ assert_eq!(&restored, original);
+ assert_eq!(exported, write_sbs(&super::convert::package(&bytes, "source.sbs").unwrap()).unwrap());
+}
+
+#[test]
+fn layout_separates_nodes_and_rejects_invalid_connections_without_partial_edits() {
+ let mut function = FunctionGraph::default();
+ let constant = function.add_constant(Value::Float(1.0));
+ function.output = Some(function.add("add", &[constant, constant], None));
+ let disconnected = function.add_constant(Value::Float(2.0));
+ function.nodes.reverse();
+
+ super::layout::reposition(&mut function).unwrap();
+
+ let source = function.node(constant).unwrap();
+ let result = function.node(function.output.unwrap()).unwrap();
+ assert!(result.pos[0] > source.pos[0]);
+ assert_ne!(source.pos, function.node(disconnected).unwrap().pos);
+ function.nodes[0].inputs = vec![function.output];
+ function.nodes[1].inputs = vec![Some(disconnected)];
+ let cyclic = function.clone();
+ assert!(super::layout::reposition(&mut function).unwrap_err().contains("cycle"));
+ assert_eq!(function, cyclic);
+ function.nodes[0].inputs = vec![Some(9999)];
+ assert!(super::layout::reposition(&mut function).unwrap_err().contains("missing node"));
+}
diff --git a/crates/formats/src/sbs/base_parameters.rs b/crates/formats/src/sbs/base_parameters.rs
index 812bffb1..93a2e295 100644
--- a/crates/formats/src/sbs/base_parameters.rs
+++ b/crates/formats/src/sbs/base_parameters.rs
@@ -1,6 +1,6 @@
use super::sbs_value::sbs_constant;
use super::xml::{child_element, child_value, children_named};
-use materialcraft_core::{BaseParameters, MAX_SIZE_LOG2, OutputFormat, SizeMode};
+use materialcraft_core::{BaseParameters, MAX_SIZE_LOG2, OutputFormat, ParameterInheritance, SizeMode};
use roxmltree::Node as XmlNode;
use std::fmt::Write as _;
@@ -8,6 +8,17 @@ pub(super) fn read_base_params(params: Option) -> BaseParameters {
let mut base = BaseParameters::default();
for param in params.into_iter().flat_map(|p| children_named(p, "parameter")) {
let relative_to = child_value(param, "relativeTo").and_then(|r| r.trim().parse::().ok()).unwrap_or(1);
+ let inheritance = match relative_to {
+ 0 => ParameterInheritance::Absolute,
+ 2 => ParameterInheritance::RelativeToParent,
+ _ => ParameterInheritance::RelativeToInput,
+ };
+ match child_value(param, "name") {
+ Some("tiling") => base.tiling_mode = inheritance,
+ Some("pixelratio") => base.pixel_ratio_mode = inheritance,
+ _ => {}
+ }
+
let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) else { continue };
match child_value(param, "name") {
@@ -31,7 +42,8 @@ pub(super) fn read_base_params(params: Option) -> BaseParameters {
}
}
Some("randomseed") if relative_to == 0 => base.seed = value.int(0),
- Some("tiling") if relative_to == 0 => base.tiling = [value.int(0) & 1 != 0, value.int(0) & 2 != 0],
+ Some("tiling") => base.tiling = [value.int(0) & 1 != 0, value.int(0) & 2 != 0],
+ Some("pixelratio") => base.pixel_ratio = value.int(0).clamp(0, 1),
_ => {}
}
}
@@ -74,9 +86,21 @@ pub(super) fn base_params_xml(base: &BaseParameters) -> String {
base.seed
);
}
- if base.tiling != [true, true] {
- let code = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1);
- out.push_str(&super::node_parameter::param_xml("tiling", &materialcraft_core::Value::Int(code)).unwrap_or_default());
+ let tiling = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1);
+ for (name, value, inheritance, default) in [("tiling", tiling, base.tiling_mode, 3), ("pixelratio", base.pixel_ratio, base.pixel_ratio_mode, 0)] {
+ if inheritance == ParameterInheritance::RelativeToInput && value == default {
+ continue;
+ }
+
+ let relative_to = match inheritance {
+ ParameterInheritance::Absolute => 0,
+ ParameterInheritance::RelativeToInput => 1,
+ ParameterInheritance::RelativeToParent => 2,
+ };
+ let _ = write!(
+ out,
+ ""
+ );
}
out
}
diff --git a/crates/formats/src/sbs/filter_map.rs b/crates/formats/src/sbs/filter_map.rs
index 9ddeed34..62f783b8 100644
--- a/crates/formats/src/sbs/filter_map.rs
+++ b/crates/formats/src/sbs/filter_map.rs
@@ -6,7 +6,6 @@ pub(super) struct FilterMap {
}
pub(super) const FILTERS: &[FilterMap] = &[
- FilterMap { sbs: "motionblur", def: "motion_blur", inputs: &[("input1", "input")], params: &[("intensity", "intensity"), ("shiftangle", "shiftangle")] },
FilterMap { sbs: "uniform", def: "uniform", inputs: &[], params: &[("outputcolor", "color"), ("colorswitch", "color_mode")] },
FilterMap {
sbs: "blend",
diff --git a/crates/formats/src/sbs/function_graph.rs b/crates/formats/src/sbs/function_graph.rs
index 8f180312..f07c4ea7 100644
--- a/crates/formats/src/sbs/function_graph.rs
+++ b/crates/formats/src/sbs/function_graph.rs
@@ -27,26 +27,30 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result {
.map(|value| to_natural_value(&value));
let type_code = child_value(element, "type").and_then(|value| value.parse().ok()).unwrap_or(0);
let mut instance = if op == "instance" { Some(super::function_instance::read(element, value.as_ref(), type_code)?) } else { None };
+ let mut missing = instance.is_none() && function::definition(op).is_none();
let mut names: Vec = if let Some(instance) = &instance {
instance.inputs.iter().map(|port| port.identifier.clone()).collect()
} else {
- function::definition(op).ok_or_else(|| format!("unsupported function `{op}`"))?.inputs.iter().map(|name| (*name).into()).collect()
+ function::definition(op).into_iter().flat_map(|definition| definition.inputs.iter().map(|name| (*name).into())).collect()
};
let mut inputs = vec![None; names.len()];
for connection in child_element(element, "connections").into_iter().flat_map(|connections| children_named(connections, "connection")) {
let port = child_value(connection, "identifier").unwrap_or("");
let index = if let Some(index) = names.iter().position(|name| name == port) {
index
- } else if let Some(instance) = &mut instance {
+ } else {
if names.len() >= 4096 {
return Err("Function instance exceeds the 4096-input limit".into());
}
- instance.inputs.push(materialcraft_core::GraphPort { identifier: port.into(), type_code: 0 });
+ if let Some(instance) = &mut instance {
+ instance.inputs.push(materialcraft_core::GraphPort { identifier: port.into(), type_code: 0 });
+ } else {
+ // A newer connector contract must remain editable without running the older operation
+ missing = true;
+ }
names.push(port.into());
inputs.push(None);
names.len() - 1
- } else {
- return Err(format!("{op}: unknown input `{port}`"));
};
let source = child_value(connection, "connRef").and_then(|value| value.parse().ok()).ok_or("invalid function connection")?;
let input = inputs.get_mut(index).ok_or("invalid input index")?;
@@ -56,6 +60,12 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result {
}
let position = child_element(element, "GUILayout").and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default();
graph.nodes.push(FunctionNode {
+ missing: missing.then_some(names),
+ missing_data: if missing {
+ child_element(element, "funcDatas").map(|data| element.document().input_text()[data.range()].to_string()).unwrap_or_default()
+ } else {
+ String::new()
+ },
instance,
source: None,
id,
@@ -74,7 +84,7 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result {
return Err("function connection references a missing node".into());
}
// Earlier files may designate a Dot; keep the graph editable without promoting another node
- if graph.output.and_then(|id| graph.node(id)).is_some_and(|node| !function::can_be_output(&node.op)) {
+ if graph.output.and_then(|id| graph.node(id)).is_some_and(|node| node.missing.is_none() && !function::can_be_output(&node.op)) {
graph.output = None;
}
Ok(graph)
@@ -120,7 +130,21 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result");
- if let Some(instance) = &node.instance {
+ if node.missing.is_some() && !node.missing_data.is_empty() {
+ // Only a bounded data element may be emitted; command input must not inject package XML
+ let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 100_000 };
+ if node.missing_data.len() > (1 << 20) {
+ return Err("invalid preserved function data".into());
+ }
+
+ let document = roxmltree::Document::parse_with_options(&node.missing_data, options).map_err(|_| "invalid preserved function data")?;
+ let root = document.root_element();
+ if !root.has_tag_name("funcDatas") {
+ return Err("invalid preserved function data".into());
+ }
+
+ output.push_str(node.missing_data.get(root.range()).ok_or("invalid preserved function data")?);
+ } else if let Some(instance) = &node.instance {
output.push_str(&super::function_instance::write(instance, writer));
} else if let Some(value) = &node.value {
let constant = constant_xml(value).ok_or("function data must be a scalar or vector constant")?;
diff --git a/crates/formats/src/sbs/function_instance.rs b/crates/formats/src/sbs/function_instance.rs
index 5bd446c6..0b7543db 100644
--- a/crates/formats/src/sbs/function_instance.rs
+++ b/crates/formats/src/sbs/function_instance.rs
@@ -9,22 +9,8 @@ use std::fmt::Write;
pub(super) fn read(element: XmlNode<'_, '_>, value: Option<&Value>, type_code: u32) -> Result {
let Some(Value::Text(reference)) = value else { return Err("function instance has no source reference".into()) };
- let reference = reference.strip_prefix("pkg:///").ok_or("invalid function source reference")?;
- let (graph, query) = reference.split_once('?').unwrap_or((reference, ""));
- let dependency = query.split('&').find_map(|part| part.strip_prefix("dependency="));
- let package = if let Some(uid) = dependency {
- child_element(element.document().root_element(), "dependencies")
- .into_iter()
- .flat_map(|dependencies| children_named(dependencies, "dependency"))
- .find(|dependency| child_value(*dependency, "uid") == Some(uid))
- .and_then(|dependency| child_value(dependency, "filename"))
- .ok_or("function source dependency is missing")?
- } else {
- SELF_DEPENDENCY
- };
- if package != SELF_DEPENDENCY && (package.contains("://") || !package.to_ascii_lowercase().ends_with(".sbs")) {
- return Err("function sources must be SBS files".into());
- }
+ let (package, graph) = source_reference(element, reference)?;
+
let inputs: Vec<_> = child_element(element, "materialcraftInterface")
.into_iter()
.flat_map(|interface| children_named(interface, "input"))
@@ -42,13 +28,41 @@ pub(super) fn read(element: XmlNode<'_, '_>, value: Option<&Value>, type_code: u
return Err("Duplicate Function input identifiers".into());
}
Ok(GraphInstance {
- package: if package == SELF_DEPENDENCY { String::new() } else { package.into() },
- graph: graph.into(),
+ label: String::new(),
+ defaults: Default::default(),
+ package,
+ graph,
inputs,
outputs: vec![GraphPort { identifier: "output".into(), type_code }],
})
}
+fn source_reference(element: XmlNode<'_, '_>, reference: &str) -> Result<(String, String), String> {
+ if let Some(reference) = reference.strip_prefix("pkg:///") {
+ let (graph, query) = reference.split_once('?').unwrap_or((reference, ""));
+ let dependency = query.split('&').find_map(|part| part.strip_prefix("dependency="));
+ let package = dependency
+ .map(|uid| {
+ child_element(element.document().root_element(), "dependencies")
+ .into_iter()
+ .flat_map(|dependencies| children_named(dependencies, "dependency"))
+ .find(|dependency| child_value(*dependency, "uid") == Some(uid))
+ .and_then(|dependency| child_value(dependency, "filename"))
+ .map(str::to_string)
+ .unwrap_or_else(|| format!("missing://dependency/{uid}"))
+ })
+ .unwrap_or_default();
+
+ return Ok((if package == SELF_DEPENDENCY { String::new() } else { package }, graph.into()));
+ }
+
+ if let Some((package, graph)) = reference.split_once(".sbs/") {
+ return Ok((format!("{package}.sbs"), graph.into()));
+ }
+
+ Err("invalid function source reference".into())
+}
+
pub(super) fn write(instance: &GraphInstance, writer: &mut SbsWriter) -> String {
let reference = if instance.package.is_empty() {
format!("pkg:///{}", instance.graph)
diff --git a/crates/formats/src/sbs/graph_attributes.rs b/crates/formats/src/sbs/graph_attributes.rs
new file mode 100644
index 00000000..a345d8f7
--- /dev/null
+++ b/crates/formats/src/sbs/graph_attributes.rs
@@ -0,0 +1,42 @@
+use super::xml::{child_value, xml_escape};
+use materialcraft_core::{Attributes, Graph};
+use roxmltree::Node;
+use std::fmt::Write;
+
+pub(super) fn read(element: Node<'_, '_>) -> Attributes {
+ let text = |tag| child_value(element, tag).unwrap_or_default().to_string();
+ Attributes {
+ label: text("label"),
+ category: text("category"),
+ description: text("description"),
+ author: text("author"),
+ author_url: text("authorURL"),
+ tags: text("tags"),
+ group: text("group"),
+ user_data: text("userdata"),
+ }
+}
+
+pub(super) fn write(output: &mut String, graph: &Graph) {
+ let attributes = &graph.attributes;
+ output.push_str("");
+ for (tag, value) in [
+ ("category", &attributes.category),
+ ("description", &attributes.description),
+ ("author", &attributes.author),
+ ("tags", &attributes.tags),
+ ("label", &attributes.label),
+ ("authorURL", &attributes.author_url),
+ ("group", &attributes.group),
+ ("userdata", &attributes.user_data),
+ ] {
+ if !value.is_empty() {
+ let _ = write!(output, "<{tag} v=\"{}\"/>", xml_escape(value));
+ }
+ }
+ if graph.function.is_none() && graph.physical_size != [0.0; 3] {
+ let [x, y, z] = graph.physical_size;
+ let _ = write!(output, "");
+ }
+ output.push_str("");
+}
diff --git a/crates/formats/src/sbs/group_layout.rs b/crates/formats/src/sbs/group_layout.rs
new file mode 100644
index 00000000..542f16e5
--- /dev/null
+++ b/crates/formats/src/sbs/group_layout.rs
@@ -0,0 +1,58 @@
+use super::{sbs_writer::SbsWriter, xml::xml_escape};
+use crate::{FormatError, Result};
+use materialcraft_core::Package;
+use std::{collections::BTreeSet, fmt::Write};
+
+pub(super) fn write(out: &mut String, package: &Package, writer: &mut SbsWriter, self_uid: u64) -> Result<()> {
+ let folders = package.folder_paths();
+ // Bound recursion for hostile package folders supplied through commands or imported XML
+ if folders.iter().any(|path| path.split('/').count() > 64 || path.split('/').any(str::is_empty)) {
+ return Err(FormatError::BadPackage("SBS folders must be nonempty and at most 64 levels deep".into()));
+ }
+
+ write_level(out, package, writer, self_uid, &folders, "")
+}
+
+fn write_level(out: &mut String, package: &Package, writer: &mut SbsWriter, self_uid: u64, folders: &BTreeSet, parent: &str) -> Result<()> {
+ let prefix = if parent.is_empty() { String::new() } else { format!("{parent}/") };
+ let mut written = BTreeSet::new();
+ for graph in &package.graphs {
+ if graph.folder == parent {
+ if graph.function.is_some() {
+ super::standalone_function::write(out, graph, writer)?;
+ } else {
+ writer.write_graph(out, package, graph, self_uid)?;
+ }
+ } else if let Some(child) = graph.folder.strip_prefix(&prefix).and_then(|path| path.split('/').next())
+ && written.insert(child.to_string())
+ {
+ write_folder(out, package, writer, self_uid, folders, &prefix, child)?;
+ }
+ }
+ for resource in package.resources.iter().filter(|resource| resource.folder == parent) {
+ super::resource::write(out, resource, writer)?;
+ }
+ for path in folders {
+ if let Some(child) = path.strip_prefix(&prefix).filter(|path| !path.contains('/'))
+ && written.insert(child.to_string())
+ {
+ write_folder(out, package, writer, self_uid, folders, &prefix, child)?;
+ }
+ }
+ Ok(())
+}
+
+fn write_folder(
+ out: &mut String,
+ package: &Package,
+ writer: &mut SbsWriter,
+ self_uid: u64,
+ folders: &BTreeSet,
+ prefix: &str,
+ name: &str,
+) -> Result<()> {
+ let _ = write!(out, "", xml_escape(name), writer.next_uid());
+ write_level(out, package, writer, self_uid, folders, &format!("{prefix}{name}"))?;
+ out.push_str("");
+ Ok(())
+}
diff --git a/crates/formats/src/sbs/library.rs b/crates/formats/src/sbs/library.rs
new file mode 100644
index 00000000..61dece3e
--- /dev/null
+++ b/crates/formats/src/sbs/library.rs
@@ -0,0 +1,88 @@
+//! Resolve the portable SBS library alias against the application's asset directory.
+
+/// Validate alias paths before joining a filesystem root. No package may escape the library.
+pub fn relative_path(uri: &str) -> Result<&str, String> {
+ let path = uri.strip_prefix("sbs://").ok_or("not an SBS library alias")?;
+ if path.is_empty()
+ || path.len() > 4096
+ || path.contains(['\\', ':', '?', '#', '%', '\0'])
+ || path.split('/').any(|part| part.is_empty() || matches!(part, "." | ".."))
+ {
+ return Err("invalid SBS library path".into());
+ }
+ Ok(path)
+}
+
+/// Resolve a package-relative resource or dependency without leaving the library root.
+pub fn resolve(owner: &str, reference: &str) -> Result {
+ let owner = relative_path(owner)?;
+ if reference.starts_with("sbs://") {
+ relative_path(reference)?;
+ return Ok(reference.into());
+ }
+
+ let reference = reference.trim().replace('\\', "/");
+ if reference.is_empty() || reference.len() > 4096 || reference.starts_with('/') || reference.contains([':', '?', '#', '%', '\0']) {
+ return Err("invalid relative SBS library path".into());
+ }
+
+ let mut parts: Vec<_> = owner.split('/').collect();
+ parts.pop();
+ for part in reference.split('/') {
+ match part {
+ "" | "." => {}
+ ".." => {
+ if parts.pop().is_none() {
+ return Err("SBS reference escapes its library directory".into());
+ }
+ }
+ part => parts.push(part),
+ }
+ }
+
+ let uri = format!("sbs://{}", parts.join("/"));
+ relative_path(&uri)?;
+ Ok(uri)
+}
+
+/// The native asset root may be configured for installations with a separate data directory.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn root() -> std::path::PathBuf {
+ if let Some(root) = std::env::var_os("MATERIALCRAFT_SBS_DIR") {
+ return root.into();
+ }
+ if let Ok(executable) = std::env::current_exe()
+ && let Some(parent) = executable.parent()
+ && parent.join("assets/sbs").is_dir()
+ {
+ return parent.join("assets/sbs");
+ }
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs")
+}
+
+pub fn read(uri: &str) -> Result, String> {
+ let relative = relative_path(uri)?;
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use std::io::Read;
+ let root = root();
+ if root.exists() || std::env::var_os("MATERIALCRAFT_SBS_DIR").is_some() {
+ let root = root.canonicalize().map_err(|error| error.to_string())?;
+ let file = root.join(relative).canonicalize().map_err(|error| format!("Missing library asset {uri}: {error}"))?;
+ if !file.starts_with(&root) {
+ return Err("SBS library symlink escapes its asset directory".into());
+ }
+ let mut bytes = Vec::new();
+ std::fs::File::open(file).map_err(|error| error.to_string())?.take((256 << 20) + 1).read_to_end(&mut bytes).map_err(|error| error.to_string())?;
+ if bytes.len() > 256 << 20 {
+ return Err("SBS library asset exceeds 256 MiB".into());
+ }
+ return Ok(bytes);
+ }
+ }
+ // Installed and browser builds use the same bundled asset when no disk asset root exists
+ match relative {
+ "functions.sbs" => Ok(include_bytes!("../../../../assets/sbs/functions.sbs").to_vec()),
+ _ => Err(format!("Missing library asset {uri}")),
+ }
+}
diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs
index 17e53552..b86db61b 100644
--- a/crates/formats/src/sbs/mod.rs
+++ b/crates/formats/src/sbs/mod.rs
@@ -7,8 +7,11 @@ mod embedded;
mod filter_map;
mod function_graph;
mod function_instance;
+mod graph_attributes;
+mod group_layout;
mod image_input;
mod input_bridge;
+pub mod library;
mod node_identifiers;
mod node_parameter;
mod output;
@@ -37,3 +40,5 @@ mod read;
mod write;
mod preview_binding;
+
+mod resource;
diff --git a/crates/formats/src/sbs/node_parameter.rs b/crates/formats/src/sbs/node_parameter.rs
index 9137a455..0702c027 100644
--- a/crates/formats/src/sbs/node_parameter.rs
+++ b/crates/formats/src/sbs/node_parameter.rs
@@ -11,12 +11,20 @@ pub(super) fn text_param(node: &Node, key: &str, default: &str) -> String {
pub(super) fn param_xml(name: &str, value: &Value) -> Option {
Some(format!("{}", xml_escape(name), constant_xml(value)?))
}
-pub(super) fn special_filter_params_xml<'a>(filter: &str, value_of: &dyn Fn(&str) -> Option<&'a Value>, self_uid: u64) -> String {
+pub(super) fn special_filter_params_xml<'a>(
+ filter: &str,
+ value_of: &dyn Fn(&str) -> Option<&'a Value>,
+ self_uid: u64,
+ package: &materialcraft_core::Package,
+) -> String {
match filter {
"bitmap" | "svg" => match value_of("resource") {
Some(Value::Text(name)) if !name.is_empty() => param_xml(
if filter == "svg" { "vectorresourcepath" } else { "bitmapresourcepath" },
- &Value::Text(format!("pkg:///Resources/{name}?dependency={self_uid}")),
+ &Value::Text(format!(
+ "pkg:///{}?dependency={self_uid}",
+ package.resource(name).map_or_else(|| format!("Resources/{name}"), |resource| resource.sbs_path())
+ )),
)
.unwrap_or_default(),
_ => String::new(),
diff --git a/crates/formats/src/sbs/read.rs b/crates/formats/src/sbs/read.rs
index 003272b5..94aa466f 100644
--- a/crates/formats/src/sbs/read.rs
+++ b/crates/formats/src/sbs/read.rs
@@ -2,12 +2,12 @@ use super::{
constant::{MAX_GRAPHS, MAX_SBS_BYTES, MAX_XML_NODES, SNIFF_BYTES},
placeholder::report_placeholders,
sbs_read::SbsRead,
- sbs_reader::{SbsReader, unique_name},
+ sbs_reader::SbsReader,
warnings::Warnings,
xml::{child_element, child_value, children_named},
};
use crate::{FormatError, Result};
-use materialcraft_core::{Graph, Package};
+use materialcraft_core::Package;
use roxmltree::Node as XmlNode;
use std::collections::HashMap;
@@ -61,22 +61,19 @@ pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option = Vec::new();
for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) {
let identifier = child_value(*graph, "identifier").unwrap_or("").trim();
- let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier });
- reader.graph_names.insert(path.clone(), unique.clone());
- names.push(unique);
+ let name = if identifier.is_empty() { "Graph" } else { identifier }.to_string();
+ reader.graph_names.insert(path.clone(), path.clone());
+ names.push(name);
}
if graph_elements.len() > MAX_GRAPHS {
reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read"));
}
- for ((_, graph), name) in graph_elements.iter().zip(names) {
- let graph = reader.read_graph(*graph, name);
+ for ((path, graph), name) in graph_elements.iter().zip(names) {
+ let mut graph = reader.read_graph(*graph, name);
+ graph.folder = path.rsplit_once('/').map_or("", |(folder, _)| folder).into();
pkg.graphs.push(graph);
}
- if pkg.graphs.is_empty() {
- reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added");
- pkg.graphs.push(Graph::new("Graph"));
- }
report_placeholders(&pkg, reader.warnings);
Ok(SbsRead { pkg, warnings: warnings.finish() })
diff --git a/crates/formats/src/sbs/resource.rs b/crates/formats/src/sbs/resource.rs
new file mode 100644
index 00000000..29803d15
--- /dev/null
+++ b/crates/formats/src/sbs/resource.rs
@@ -0,0 +1,24 @@
+use super::{embedded::encode_embedded, sbs_writer::SbsWriter, xml::xml_escape};
+use crate::Result;
+use materialcraft_core::Resource;
+use std::fmt::Write;
+
+pub(super) fn write(content: &mut String, resource: &Resource, writer: &mut SbsWriter) -> Result<()> {
+ let svg = resource.file.to_ascii_lowercase().ends_with(".svg");
+ let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e);
+ let source = if !resource.source.is_empty() && resource.bytes.is_empty() {
+ format!("", xml_escape(&resource.source))
+ } else {
+ format!("", resource.bytes.len(), encode_embedded(resource.bytes.as_slice())?)
+ };
+ let _ = write!(
+ content,
+ "{source}",
+ xml_escape(&resource.name),
+ writer.next_uid(),
+ if svg { "svg" } else { "bitmap" },
+ xml_escape(ext)
+ );
+
+ Ok(())
+}
diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs
index 2933ae12..2d8ab5c1 100644
--- a/crates/formats/src/sbs/sbs_reader.rs
+++ b/crates/formats/src/sbs/sbs_reader.rs
@@ -48,6 +48,20 @@ impl<'text> SbsReader<'text, '_> {
match item.tag_name().name() {
"graph" | "function" => graphs.push((path, item)),
"group" => {
+ if identifier.is_empty() || identifier.contains('/') {
+ self.warnings.add(format!("invalid folder `{path}` was flattened"));
+ if let Some(group_content) = child_element(item, "content") {
+ pending.push((folder.clone(), group_content));
+ }
+ continue;
+ }
+
+ if path.split('/').count() > 64 {
+ self.warnings.add(format!("excessively nested folder `{path}` was skipped"));
+ continue;
+ }
+
+ pkg.folders.push(path.clone());
if let Some(group_content) = child_element(item, "content") {
pending.push((path, group_content));
}
@@ -66,6 +80,11 @@ impl<'text> SbsReader<'text, '_> {
let kind = child_value(item, "type").unwrap_or("bitmap");
let format = child_value(item, "format").unwrap_or("png").trim().to_ascii_lowercase();
let source = child_element(item, "source");
+ let external = source
+ .and_then(|source| child_element(source, "externalcopy"))
+ .and_then(|copy| child_value(copy, "filename"))
+ .filter(|path| !path.is_empty())
+ .or_else(|| child_value(item, "filepath"));
let mut bytes: Option> = None;
let mut why_missing = String::new();
@@ -79,7 +98,7 @@ impl<'text> SbsReader<'text, '_> {
if bytes.is_none() {
let external_copy = source.and_then(|s| child_element(s, "externalcopy")).and_then(|e| child_value(e, "filename"));
for file in [external_copy, child_value(item, "filepath")].into_iter().flatten().filter(|p| !p.trim().is_empty()) {
- if file.contains("://") {
+ if file.contains("://") && !file.starts_with("sbs://") {
why_missing = format!("it links to `{file}`, which is not available");
continue;
}
@@ -102,11 +121,17 @@ impl<'text> SbsReader<'text, '_> {
self.resource_bytes += data.len();
let ext = if kind == "svg" { "svg".to_string() } else { format };
- pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data)));
+ let mut resource = Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data));
+ resource.folder = path.rsplit_once('/').map_or("", |(folder, _)| folder).into();
+ pkg.resources.push(resource);
}
None => {
let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing };
-
+ let extension = if kind == "svg" { "svg" } else { &format };
+ let mut resource = Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{extension}")), ResourceBytes::new(Vec::new()));
+ resource.source = external.unwrap_or("").into();
+ resource.folder = path.rsplit_once('/').map_or("", |(folder, _)| folder).into();
+ pkg.resources.push(resource);
self.warnings.add(format!("resource `{path}` could not be loaded: {why}"));
}
}
@@ -121,7 +146,12 @@ impl<'text> SbsReader<'text, '_> {
pub(super) fn read_graph(&mut self, element: XmlNode<'_, 'text>, name: String) -> Graph {
let mut graph = Graph::new(&name);
- graph.seed = read_base_params(child_element(element, "baseParameters")).seed;
+ let base = read_base_params(child_element(element, "baseParameters"));
+ graph.seed = base.seed;
+ graph.pixel_ratio = base.pixel_ratio;
+ graph.pixel_ratio_mode = base.pixel_ratio_mode;
+ graph.tiling = base.tiling;
+ graph.tiling_mode = base.tiling_mode;
// The default parent size option ("11x11", log2 sizes)
for option in child_element(element, "options").into_iter().flat_map(|o| children_named(o, "option")) {
@@ -135,14 +165,21 @@ impl<'text> SbsReader<'text, '_> {
}
if let Some(attributes) = child_element(element, "attributes") {
- let text = |tag: &str| child_value(attributes, tag).unwrap_or("").to_string();
- graph.attributes.category = text("category");
- graph.attributes.description = text("description");
- graph.attributes.author = text("author");
- graph.attributes.tags = text("tags");
+ graph.attributes = super::graph_attributes::read(attributes);
+ if let Some(size) = child_value(attributes, "physicalSize") {
+ let mut components = size.split_whitespace().map(str::parse::);
+ if let (Some(Ok(x)), Some(Ok(y)), Some(Ok(z)), None) = (components.next(), components.next(), components.next(), components.next())
+ && [x, y, z].iter().all(|component| component.is_finite() && *component >= 0.0)
+ {
+ graph.physical_size = [x, y, z];
+ } else {
+ self.warnings.add(format!("graph `{name}` has an invalid physical size"));
+ }
+ }
}
if element.has_tag_name("function") {
+ graph.function_type = child_value(element, "type").and_then(|code| code.parse().ok()).unwrap_or(0);
self.read_graph_inputs(element, &mut graph);
let dynamic = child_element(element, "paramValue").and_then(|value| child_element(value, "dynamicValue"));
let function = dynamic.ok_or_else(|| "missing function body".to_string()).and_then(super::function_graph::read);
@@ -397,6 +434,7 @@ impl<'text> SbsReader<'text, '_> {
}
}
pub(super) fn read_instance(&mut self, graph: &mut Graph, implementation: XmlNode<'_, 'text>, pos: [f32; 2], output_uids: &[(String, bool)]) -> ReadNode {
+ let graph_name = graph.name.clone();
let (path, dependency) = self.resolve_reference(child_value(implementation, "path").unwrap_or(""));
let params = child_element(implementation, "parameters");
let bridgings: Vec<(String, String)> = child_element(implementation, "outputBridgings")
@@ -408,7 +446,7 @@ impl<'text> SbsReader<'text, '_> {
|| params.into_iter().flat_map(|p| children_named(p, "parameter")).filter(|p| !BASE_PARAMS.contains(&child_value(*p, "name").unwrap_or("")));
let own_graph = dependency.as_deref().is_none_or(|d| d == SELF_DEPENDENCY).then(|| self.graph_names.get(&path).cloned()).flatten();
- let external = dependency.as_deref().filter(|file| *file != SELF_DEPENDENCY && !file.contains("://") && file.to_ascii_lowercase().ends_with(".sbs"));
+ let external = dependency.as_deref().filter(|file| *file != SELF_DEPENDENCY && file.to_ascii_lowercase().ends_with(".sbs"));
if own_graph.is_some() || external.is_some() {
let (id, index, node) = push_node(graph, "graph_instance", pos);
if let Some(node) = node {
@@ -425,6 +463,8 @@ impl<'text> SbsReader<'text, '_> {
})
.collect();
node.instance = Some(materialcraft_core::GraphInstance {
+ label: String::new(),
+ defaults: Default::default(),
package: external.unwrap_or("").into(),
graph: path.clone(),
inputs: Vec::new(),
@@ -440,6 +480,8 @@ impl<'text> SbsReader<'text, '_> {
for param in instance_params() {
if let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) {
node.params.insert(child_value(param, "name").unwrap_or("").to_string(), to_natural_value(&value));
+ } else {
+ self.set_param(node, child_value(param, "name").unwrap_or(""), &Value::Float(0.0), 0, param, &graph_name);
}
}
node.base = read_base_params(params);
diff --git a/crates/formats/src/sbs/sbs_writer.rs b/crates/formats/src/sbs/sbs_writer.rs
index 60afeac3..2e9304ba 100644
--- a/crates/formats/src/sbs/sbs_writer.rs
+++ b/crates/formats/src/sbs/sbs_writer.rs
@@ -65,17 +65,7 @@ impl SbsWriter {
pub(super) fn write_graph(&mut self, out: &mut String, pkg: &Package, graph: &Graph, self_uid: u64) -> Result<()> {
let _ = write!(out, "", xml_escape(&graph.name), self.next_uid());
- let attributes = &graph.attributes;
- if !(attributes.category.is_empty() && attributes.description.is_empty() && attributes.author.is_empty() && attributes.tags.is_empty()) {
- let _ = write!(
- out,
- "",
- xml_escape(&attributes.category),
- xml_escape(&attributes.description),
- xml_escape(&attributes.author),
- xml_escape(&attributes.tags)
- );
- }
+ super::graph_attributes::write(out, graph);
let mut node_uids: HashMap = HashMap::new();
let mut node_outputs: HashMap = HashMap::new();
@@ -148,11 +138,19 @@ impl SbsWriter {
out.push_str("");
let ids = NodeIdentifiers { input_entry: input_entries.get(&node.id).copied(), graph_output: output_uids.get(&node.id).copied(), self_uid };
- self.write_implementation(out, node, outputs, ids)?;
+ self.write_implementation(out, node, outputs, ids, pkg)?;
out.push_str("");
}
out.push_str("");
out.push_str(¶m_xml("randomseed", &Value::Int(graph.seed)).unwrap_or_default());
+ let base = materialcraft_core::BaseParameters {
+ pixel_ratio: graph.pixel_ratio,
+ pixel_ratio_mode: graph.pixel_ratio_mode,
+ tiling: graph.tiling,
+ tiling_mode: graph.tiling_mode,
+ ..Default::default()
+ };
+ out.push_str(&super::base_parameters::base_params_xml(&base));
out.push_str("");
write_canvas_items(out, graph, self);
@@ -236,7 +234,14 @@ impl SbsWriter {
out.push_str("");
output_uids
}
- pub(super) fn write_implementation(&mut self, out: &mut String, node: &Node, outputs: &[(String, u32, u64)], ids: NodeIdentifiers) -> Result<()> {
+ pub(super) fn write_implementation(
+ &mut self,
+ out: &mut String,
+ node: &Node,
+ outputs: &[(String, u32, u64)],
+ ids: NodeIdentifiers,
+ package: &Package,
+ ) -> Result<()> {
let base = base_params_xml(&node.base);
match node.def.as_str() {
@@ -253,7 +258,17 @@ impl SbsWriter {
.as_ref()
.filter(|instance| !instance.package.is_empty())
.map_or(ids.self_uid, |instance| self.external_package_uid(&instance.package));
- let params: String = node.params.iter().filter(|(k, _)| *k != "graph").filter_map(|(k, v)| param_xml(k, v)).collect();
+ let mut params: String = node
+ .params
+ .iter()
+ .filter(|(name, _)| *name != "graph" && !node.functions.contains_key(*name))
+ .filter_map(|(name, value)| param_xml(name, value))
+ .collect();
+ for (name, function) in &node.functions {
+ let body = function_graph::write(function, self).map_err(FormatError::Io)?;
+ let _ = write!(params, "{body}", xml_escape(name));
+ }
+
let _ = write!(
out,
"{base}{params}",
@@ -309,7 +324,7 @@ impl SbsWriter {
}
out.push_str(¶m_xml(sbs_name, value).unwrap_or_default());
}
- out.push_str(&special_filter_params_xml(filter.sbs, &value_of, ids.self_uid));
+ out.push_str(&special_filter_params_xml(filter.sbs, &value_of, ids.self_uid, package));
out.push_str("");
for parameter in ["curve", "gradient"] {
if let Some(value) = value_of(parameter) {
diff --git a/crates/formats/src/sbs/standalone_function.rs b/crates/formats/src/sbs/standalone_function.rs
index 585253a8..7c802b30 100644
--- a/crates/formats/src/sbs/standalone_function.rs
+++ b/crates/formats/src/sbs/standalone_function.rs
@@ -1,27 +1,26 @@
use super::{canvas::write_canvas_items, function_graph, sbs_writer::SbsWriter, xml::xml_escape};
use crate::{FormatError, Result};
-use materialcraft_core::Graph;
+use materialcraft_core::{Graph, ValueType};
use std::fmt::Write;
pub(super) fn write(output: &mut String, graph: &Graph, writer: &mut SbsWriter) -> Result<()> {
let function = graph.function.as_ref().ok_or_else(|| FormatError::Io("missing function graph".into()))?;
let types = materialcraft_nodes::function::node_types(function).map_err(FormatError::Io)?;
- let result_type = function.output.and_then(|id| types.get(&id)).copied().unwrap_or(256);
+
+ // An unresolved instance may carry a type mask rather than the graph's concrete result type
+ let result_type = function
+ .output
+ .and_then(|identifier| types.get(&identifier))
+ .copied()
+ .filter(|code| ValueType::from_code(*code).is_some())
+ .unwrap_or(if graph.function_type == 0 { 256 } else { graph.function_type });
let mut body = function_graph::write(function, writer).map_err(FormatError::Io)?;
body.truncate(body.len().saturating_sub("".len()));
write_canvas_items(&mut body, graph, writer);
body.push_str("");
let _ = write!(output, "", xml_escape(&graph.name), writer.next_uid());
- let attributes = &graph.attributes;
- let _ = write!(
- output,
- "",
- xml_escape(&attributes.category),
- xml_escape(&attributes.description),
- xml_escape(&attributes.author),
- xml_escape(&attributes.tags)
- );
+ super::graph_attributes::write(output, graph);
writer.write_graph_inputs(output, graph);
let _ = write!(output, "{body}");
Ok(())
diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs
index d706f832..7d69010b 100644
--- a/crates/formats/src/sbs/tests.rs
+++ b/crates/formats/src/sbs/tests.rs
@@ -2,7 +2,7 @@ use super::embedded::{base64_engine, decode_embedded, encode_embedded};
use super::read::{is_sbs, read_sbs};
use super::write::write_sbs;
use base64::Engine as _;
-use materialcraft_core::{Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Package, Resource, ResourceBytes, SizeMode, Value, missing_ports};
+use materialcraft_core::{Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, Package, Resource, ResourceBytes, SizeMode, Value, missing_ports};
fn no_linked_files(_: &str) -> Option> {
None
@@ -135,11 +135,11 @@ fn native_data_is_the_saved_document() {
}
#[test]
-fn missing_nodes_are_placeholders_that_survive_saving() {
+fn external_references_and_unknown_filters_survive_saving() {
let xml = r#"
-
+
@@ -154,25 +154,32 @@ fn missing_nodes_are_placeholders_that_survive_saving() {
assert_eq!(graph.connections.len(), 2);
let fancy = &graph.nodes[0];
- assert_eq!(fancy.def, MISSING_NODE);
- assert_eq!(fancy.label, "fancy_noise");
- assert_eq!(missing_ports(fancy).1, vec![("noise".to_string(), true)]);
+ assert_eq!(fancy.def, "graph_instance");
+ let instance = fancy.instance.as_ref().unwrap();
+ assert_eq!(instance.package, "sbs://noise_fancy.sbs");
+ assert_eq!(instance.graph, "fancy_noise");
+ assert_eq!(instance.outputs[0].identifier, "noise");
+ assert_eq!(instance.outputs[0].type_code, 2);
+ assert_eq!(fancy.params.get("scale"), Some(&Value::Float(3.0)));
assert_eq!(graph.nodes[1].params.get("intensity"), Some(&Value::Float(6.0)));
assert_eq!(graph.input_of(graph.nodes[1].id, "input").map(|c| c.from_port.as_str()), Some("noise"));
assert_eq!(missing_ports(&graph.nodes[2]).0, vec!["weird_in".to_string()]);
- for expected in ["missing node `fancy_noise`", "missing node `futurefilter`", "bogus"] {
+ for expected in ["missing node `futurefilter`", "bogus"] {
assert!(read.warnings.iter().any(|w| w.contains(expected)), "{expected}: {:?}", read.warnings);
}
- // Saved and read back from the SBS data alone, the placeholders are written as they came
+ // References and unavailable operations survive without embedding their implementations
let text = String::from_utf8(write_sbs(&read.pkg).unwrap()).unwrap();
assert!(text.contains("sbs://noise_fancy.sbs"));
assert!(text.contains("pkg:///fancy_noise?dependency="));
assert!(text.contains(""));
let back = read_sbs(text.as_bytes(), "p.sbs", &no_linked_files).unwrap();
let back_graph = &back.pkg.graphs[0];
- assert_eq!(back_graph.nodes[0].def, MISSING_NODE);
- assert_eq!(back_graph.nodes[0].params.get("sbs_parameters"), fancy.params.get("sbs_parameters"));
+ assert_eq!(back_graph.nodes[0].def, "graph_instance");
+ assert_eq!(back_graph.nodes[0].instance, fancy.instance);
+ assert_eq!(back_graph.nodes[0].params, fancy.params);
+ assert_eq!(back_graph.nodes[0].functions["detail"].nodes.len(), 1);
+ assert_eq!(back_graph.nodes[0].functions["detail"].nodes[0].value, fancy.functions["detail"].nodes[0].value);
assert_eq!(back_graph.connections.len(), 2);
}
@@ -220,7 +227,7 @@ fn hostile_input_is_an_error_or_a_warning_never_a_panic() {
];
for case in cases {
if let Ok(read) = read_sbs(case.as_bytes(), "x.sbs", &no_linked_files) {
- assert!(!read.pkg.graphs.is_empty(), "{case}");
+ assert!(write_sbs(&read.pkg).is_ok(), "{case}");
}
}
assert!(read_sbs(b"\xff\xfe", "x.sbs", &no_linked_files).is_err());
@@ -242,7 +249,8 @@ fn linked_resources_load_through_the_callback() {
assert_eq!(found.pkg.resources[0].bytes.as_slice(), &[1, 2, 3]);
let not_found = read_sbs(xml.as_bytes(), "p.sbs", &no_linked_files).unwrap();
- assert!(not_found.pkg.resources.is_empty());
+ assert!(not_found.pkg.resources[0].bytes.is_empty());
+ assert_eq!(not_found.pkg.resources[0].source, "p.resources/img.png");
assert!(not_found.warnings.iter().any(|w| w.contains("img")), "{:?}", not_found.warnings);
}
diff --git a/crates/formats/src/sbs/write.rs b/crates/formats/src/sbs/write.rs
index f98e2352..18895d6f 100644
--- a/crates/formats/src/sbs/write.rs
+++ b/crates/formats/src/sbs/write.rs
@@ -1,6 +1,5 @@
use super::{
constant::{FIRST_UID, FORMAT_VERSION, SELF_DEPENDENCY, UPDATER_VERSION},
- embedded::encode_embedded,
sbs_writer::SbsWriter,
xml::xml_escape,
};
@@ -13,31 +12,7 @@ pub fn write_sbs(pkg: &Package) -> Result> {
let self_uid = writer.next_uid();
let mut content = String::from("");
- for graph in &pkg.graphs {
- if graph.function.is_some() {
- super::standalone_function::write(&mut content, graph, &mut writer)?;
- } else {
- writer.write_graph(&mut content, pkg, graph, self_uid)?;
- }
- }
- if !pkg.resources.is_empty() {
- let _ = write!(content, "", writer.next_uid());
- for resource in &pkg.resources {
- let svg = resource.file.to_ascii_lowercase().ends_with(".svg");
- let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e);
- let _ = write!(
- content,
- "",
- xml_escape(&resource.name),
- writer.next_uid(),
- if svg { "svg" } else { "bitmap" },
- xml_escape(ext),
- resource.bytes.len(),
- encode_embedded(resource.bytes.as_slice())?
- );
- }
- content.push_str("");
- }
+ super::group_layout::write(&mut content, pkg, &mut writer, self_uid)?;
content.push_str("");
let mut out = String::with_capacity(content.len() + 4096);
diff --git a/crates/formats/tests/explorer_folders.rs b/crates/formats/tests/explorer_folders.rs
new file mode 100644
index 00000000..393398f2
--- /dev/null
+++ b/crates/formats/tests/explorer_folders.rs
@@ -0,0 +1,119 @@
+use materialcraft_formats::sbs::{read_sbs, write_sbs};
+
+#[test]
+fn empty_nested_folders_survive_sbs_round_trip() {
+ let xml = br#""#;
+ let imported = read_sbs(xml, "folders.sbs", &|_| None).unwrap();
+
+ let saved = write_sbs(&imported.pkg).unwrap();
+ let document = roxmltree::Document::parse(std::str::from_utf8(&saved).unwrap()).unwrap();
+ let groups: Vec<_> = document.descendants().filter(|node| node.has_tag_name("group")).collect();
+
+ assert_eq!(groups.len(), 2);
+ assert!(groups[1].ancestors().any(|node| node == groups[0]));
+ assert!(imported.pkg.graphs.is_empty());
+ assert!(imported.warnings.is_empty());
+}
+
+#[test]
+fn nested_resource_paths_are_preserved_without_duplicate_groups() {
+ use materialcraft_core::{Graph, Package, Resource, ResourceBytes, Value};
+ let mut package = Package::new("Resources");
+ let mut resource = Resource::new("Mask", "mask.png", ResourceBytes::new(vec![1, 2, 3]));
+ resource.folder = "Tools/Images".into();
+ package.resources.push(resource);
+ package.folders.push("Tools/Images".into());
+ let mut graph = Graph::new("Surface");
+ graph.folder = "Tools".into();
+ let bitmap = graph.add_node("bitmap", [0.0; 2]);
+ graph.node_mut(bitmap).unwrap().params.insert("resource".into(), Value::Text("Mask".into()));
+ package.graphs.push(graph);
+
+ let bytes = write_sbs(&package).unwrap();
+ let xml = std::str::from_utf8(&bytes).unwrap();
+ assert!(xml.contains("pkg:///Tools/Images/Mask?dependency="));
+ let read = read_sbs(&bytes, "resources.sbs", &|_| None).unwrap();
+ assert_eq!(read.pkg.resources[0].folder, "Tools/Images");
+ assert_eq!(read.pkg.graphs[0].nodes[0].params["resource"], Value::Text("Mask".into()));
+ let bytes = write_sbs(&read.pkg).unwrap();
+ let document = roxmltree::Document::parse(std::str::from_utf8(&bytes).unwrap()).unwrap();
+ assert_eq!(document.descendants().filter(|node| node.has_tag_name("group")).count(), 2);
+}
+
+#[test]
+#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"]
+fn supplied_package_folder_paths_round_trip() {
+ let path = std::env::var("MC_FUNCTIONS_SBS").unwrap();
+ let bytes = std::fs::read(&path).unwrap();
+ let document = roxmltree::Document::parse(std::str::from_utf8(&bytes).unwrap()).unwrap();
+ let native_paths: std::collections::BTreeSet<_> = document
+ .descendants()
+ .filter(|node| node.has_tag_name("group"))
+ .map(|node| {
+ let mut parts: Vec<_> = node
+ .ancestors()
+ .filter(|node| node.has_tag_name("group"))
+ .map(|node| node.children().find(|node| node.has_tag_name("identifier")).unwrap().attribute("v").unwrap())
+ .collect();
+ parts.reverse();
+ parts.join("/")
+ })
+ .collect();
+
+ let imported = read_sbs(&bytes, &path, &|_| None).unwrap();
+ assert_eq!(imported.pkg.folder_paths(), native_paths);
+ let saved = write_sbs(&imported.pkg).unwrap();
+ let reopened = read_sbs(&saved, "roundtrip.sbs", &|_| None).unwrap();
+ assert_eq!(reopened.pkg.folder_paths(), native_paths);
+ for graph in &imported.pkg.graphs {
+ assert!(reopened.pkg.graph_by_name(&graph.sbs_path()).is_some());
+ }
+}
+
+#[test]
+fn empty_packages_round_trip_without_invented_graphs() {
+ let package = materialcraft_core::Package::new("Empty");
+ let read = read_sbs(&write_sbs(&package).unwrap(), "empty.sbs", &|_| None).unwrap();
+ assert!(read.pkg.graphs.is_empty());
+ assert!(read.warnings.is_empty());
+}
+
+#[test]
+#[ignore = "local interoperability inputs; set MC_SBS_PACKAGES to a package directory"]
+fn supplied_packages_keep_native_folder_hierarchies() {
+ let mut pending = vec![std::path::PathBuf::from(std::env::var_os("MC_SBS_PACKAGES").unwrap())];
+ let mut checked = 0;
+ while let Some(path) = pending.pop() {
+ if path.is_dir() {
+ pending.extend(std::fs::read_dir(path).unwrap().map(|entry| entry.unwrap().path()));
+ continue;
+ }
+ if path.extension().is_none_or(|extension| extension != "sbs") {
+ continue;
+ }
+ let bytes = std::fs::read(&path).unwrap();
+ let document = roxmltree::Document::parse(std::str::from_utf8(&bytes).unwrap().trim_start_matches('\u{feff}')).unwrap();
+ let is_folder = |node: &roxmltree::Node<'_, '_>| node.has_tag_name("group") && node.children().any(|child| child.has_tag_name("content"));
+ let paths: std::collections::BTreeSet<_> = document
+ .descendants()
+ .filter(is_folder)
+ .map(|node| {
+ let mut parts: Vec<_> = node
+ .ancestors()
+ .filter(is_folder)
+ .map(|node| node.children().find(|node| node.has_tag_name("identifier")).unwrap().attribute("v").unwrap())
+ .collect();
+ parts.reverse();
+ parts.join("/")
+ })
+ .collect();
+ let imported = read_sbs(&bytes, &path.to_string_lossy(), &|_| None).unwrap();
+ assert_eq!(imported.pkg.folder_paths(), paths, "{}: import", path.display());
+ let saved = write_sbs(&imported.pkg).unwrap();
+ let reopened = read_sbs(&saved, "roundtrip.sbs", &|_| None).unwrap();
+ assert_eq!(reopened.pkg.folder_paths(), paths, "{}: export", path.display());
+ checked += 1;
+ }
+ assert!(checked > 0);
+ println!("Verified native folder hierarchies in {checked} supplied SBS packages");
+}
diff --git a/crates/formats/tests/function_library.rs b/crates/formats/tests/function_library.rs
new file mode 100644
index 00000000..6e495380
--- /dev/null
+++ b/crates/formats/tests/function_library.rs
@@ -0,0 +1,254 @@
+use materialcraft_formats::sbs::{read_sbs, write_sbs};
+
+const LIBRARY: &str = r#"
+
+
+
+
+
+
+
+"#;
+
+#[test]
+fn unresolved_polymorphic_output_preserves_the_declared_function_type() {
+ let xml = LIBRARY.replace("", "");
+ let source = read_sbs(xml.as_bytes(), "source.sbs", &|_| None).unwrap().pkg;
+
+ let saved = read_sbs(&write_sbs(&source).unwrap(), "saved.sbs", &|_| None).unwrap().pkg;
+
+ assert_eq!(saved.graph_by_name("Caller").unwrap().1.function_type, 256);
+ assert_eq!(saved.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap().nodes[0].type_code, 118772);
+}
+
+#[test]
+fn nested_function_paths_and_library_aliases_survive_save() {
+ let read = read_sbs(LIBRARY.as_bytes(), "test.sbs", &|_| None).unwrap();
+ assert!(read.warnings.is_empty(), "{:?}", read.warnings);
+ let (_, pi) = read.pkg.graph_by_name("Functions/Math/Pi").expect("package path must remain addressable");
+ assert_eq!(pi.name, "Pi");
+ let call = read.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap();
+ assert_eq!(call.nodes[0].instance.as_ref().unwrap().package, "sbs://functions.sbs");
+ let bytes = write_sbs(&read.pkg).unwrap();
+ let saved = read_sbs(&bytes, "saved.sbs", &|_| None).unwrap();
+ assert!(saved.warnings.is_empty(), "{:?}", saved.warnings);
+ assert!(saved.pkg.graph_by_name("Functions/Math/Pi").is_some());
+ assert!(String::from_utf8(bytes).unwrap().contains(&format!("".into();
+
+ let bytes = write_sbs(&package).unwrap();
+ assert!(read_sbs(&bytes, "saved.sbs", &|_| None).is_ok());
+ package.graphs[index].function.as_mut().unwrap().nodes[0].missing_data = "".into();
+ assert!(write_sbs(&package).is_err());
+}
+
+#[test]
+fn absent_dependency_records_do_not_erase_function_nodes() {
+ let xml = LIBRARY.replace("dependency=9", "dependency=404");
+ let read = read_sbs(xml.as_bytes(), "missing.sbs", &|_| None).unwrap();
+
+ let function = read.pkg.graph_by_name("Caller").unwrap().1.function.as_ref().unwrap();
+ assert_eq!(function.nodes.len(), 1);
+ assert_eq!(function.output, Some(2));
+ assert!(function.nodes[0].instance.is_some());
+}
+
+#[test]
+fn missing_resource_links_survive_save_and_can_be_repaired() {
+ let xml = r#""#;
+ let read = read_sbs(xml.as_bytes(), "missing.sbs", &|_| None).unwrap();
+
+ let bytes = write_sbs(&read.pkg).unwrap();
+ let repaired = read_sbs(&bytes, "saved.sbs", &|path| (path == "sbs://missing.png").then(|| vec![1, 2, 3])).unwrap();
+
+ assert_eq!(repaired.pkg.resources.len(), 1);
+ assert_eq!(repaired.pkg.resources[0].bytes.as_slice(), &[1, 2, 3]);
+}
+
+#[test]
+#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"]
+fn supplied_function_package_round_trip() {
+ let path = std::env::var("MC_FUNCTIONS_SBS").unwrap();
+ let bytes = std::fs::read(&path).unwrap();
+ let read = read_sbs(&bytes, &path, &|_| None).unwrap();
+ assert!(read.warnings.is_empty(), "{:?}", read.warnings);
+ assert!(read.pkg.graphs.iter().all(|graph| graph.function.as_ref().is_some_and(|function| !function.nodes.is_empty())));
+ let saved = read_sbs(&write_sbs(&read.pkg).unwrap(), "saved.sbs", &|_| None).unwrap();
+ let bundled = read_sbs(include_bytes!("../../../assets/sbs/functions.sbs"), "functions.sbs", &|_| None).unwrap();
+ assert!(saved.warnings.is_empty(), "{:?}", saved.warnings);
+ assert!(bundled.warnings.is_empty(), "{:?}", bundled.warnings);
+ assert_eq!(read.pkg.graphs.len(), 171);
+ assert_eq!(read.pkg.graphs.len(), bundled.pkg.graphs.len());
+ assert_eq!(read.pkg.folder_paths(), bundled.pkg.folder_paths());
+ for graph in &read.pkg.graphs {
+ let other = saved.pkg.graph_by_name(&graph.sbs_path()).unwrap().1;
+ let replacement = bundled.pkg.graph_by_name(&graph.sbs_path()).unwrap().1;
+ assert_eq!(graph.function_type, replacement.function_type, "{}", graph.sbs_path());
+ assert_eq!(graph.function_type, other.function_type, "{}", graph.sbs_path());
+ let interface =
+ |graph: &materialcraft_core::Graph| graph.exposed.iter().map(|parameter| (parameter.id.clone(), parameter.default.clone())).collect::>();
+ assert_eq!(interface(graph), interface(replacement), "{}", graph.sbs_path());
+ assert_eq!(graph.exposed, replacement.exposed, "{}", graph.sbs_path());
+ assert_ne!(graph.attributes.description, replacement.attributes.description, "{}", graph.sbs_path());
+ assert!(replacement.attributes.author.is_empty());
+ assert!(replacement.attributes.tags.is_empty());
+ assert!(replacement.frames.is_empty() && replacement.comments.is_empty() && replacement.pins.is_empty());
+ assert_same_body(graph, replacement);
+ assert_eq!(graph.name, other.name);
+ assert_eq!(graph.exposed, other.exposed);
+ assert_eq!(graph.function.as_ref().unwrap().nodes.len(), other.function.as_ref().unwrap().nodes.len());
+ let before = graph.function.as_ref().unwrap();
+ let after = other.function.as_ref().unwrap();
+ let ids: std::collections::BTreeMap<_, _> = before.nodes.iter().zip(&after.nodes).map(|(left, right)| (left.id, right.id)).collect();
+ assert_eq!(before.output.map(|id| ids[&id]), after.output);
+ for (left, right) in before.nodes.iter().zip(&after.nodes) {
+ assert_eq!(left.op, right.op, "{}", graph.sbs_path());
+ assert_eq!(left.value, right.value, "{}", graph.sbs_path());
+ assert_eq!(left.type_code, right.type_code);
+ assert_eq!(left.pos, right.pos);
+ assert_eq!(left.instance, right.instance);
+ assert_eq!(left.inputs.iter().map(|id| id.map(|id| ids[&id])).collect::>(), right.inputs);
+ }
+ }
+ eprintln!("Round-tripped and compared all {} converted function bodies against the supplied package", read.pkg.graphs.len());
+}
+
+fn assert_same_body(source: &materialcraft_core::Graph, converted: &materialcraft_core::Graph) {
+ let before = source.function.as_ref().unwrap();
+ let after = converted.function.as_ref().unwrap();
+ assert_eq!(before.nodes.len(), after.nodes.len(), "{}", source.sbs_path());
+ let identifiers: std::collections::BTreeMap<_, _> = before.nodes.iter().zip(&after.nodes).map(|(left, right)| (left.id, right.id)).collect();
+
+ assert_eq!(before.output.map(|identifier| identifiers[&identifier]), after.output);
+ for (left, right) in before.nodes.iter().zip(&after.nodes) {
+ assert_eq!(left.op, right.op, "{}", source.sbs_path());
+ assert_eq!(left.value, right.value, "{}", source.sbs_path());
+ assert_eq!(left.type_code, right.type_code);
+ assert_eq!(left.instance, right.instance);
+ assert_eq!(left.inputs.iter().map(|identifier| identifier.map(|identifier| identifiers[&identifier])).collect::>(), right.inputs);
+ assert_ne!(left.pos, right.pos, "layout was not replaced in {}", source.sbs_path());
+ }
+}
+
+#[test]
+fn bundled_library_has_complete_bodies_and_current_export_metadata() {
+ let bytes = include_bytes!("../../../assets/sbs/functions.sbs");
+ let read = read_sbs(bytes, "functions.sbs", &|_| None).unwrap();
+ let xml = roxmltree::Document::parse(std::str::from_utf8(bytes).unwrap()).unwrap();
+ let version = xml.descendants().find(|element| element.has_tag_name("updaterVersion")).unwrap().attribute("v").unwrap();
+
+ assert_eq!(version, env!("CARGO_PKG_VERSION"));
+ assert!(read.warnings.is_empty(), "{:?}", read.warnings);
+ assert_eq!(read.pkg.graphs.len(), 171);
+ assert_eq!(read.pkg.graphs.iter().flat_map(|graph| graph.functions()).map(|function| function.nodes.len()).sum::(), 2334);
+ for graph in &read.pkg.graphs {
+ let function = graph.function.as_ref().unwrap();
+ assert!(function.output.is_some(), "{}", graph.sbs_path());
+ assert!(function.nodes.iter().all(|node| node.missing.is_none()), "{}", graph.sbs_path());
+ assert!(!graph.attributes.description.is_empty());
+ assert!(graph.attributes.author.is_empty() && graph.attributes.tags.is_empty());
+ assert!(graph.frames.is_empty() && graph.comments.is_empty() && graph.pins.is_empty());
+ }
+ assert!(!xml.descendants().any(|element| element.has_tag_name("icon")));
+}
+
+#[test]
+#[ignore = "local interoperability input; set MC_FUNCTIONS_SBS to an external package"]
+fn supplied_parity_functions_match_bundled_graphs() {
+ use materialcraft_core::Value;
+ use materialcraft_nodes::function::{self, EvaluationContext, EvaluationState};
+ use std::collections::BTreeMap;
+
+ let path = std::env::var("MC_FUNCTIONS_SBS").unwrap();
+ let supplied = read_sbs(&std::fs::read(&path).unwrap(), &path, &|_| None).unwrap().pkg;
+ let bundled = read_sbs(include_bytes!("../../../assets/sbs/functions.sbs"), "functions.sbs", &|_| None).unwrap().pkg;
+ let mut inputs: Vec = (-2048..=2048).map(|index| index as f32 / 8.0).collect();
+ for boundary in [-16_777_216.0_f32, -2.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 16_777_216.0] {
+ inputs.extend([boundary.next_down(), boundary, boundary.next_up()]);
+ }
+
+ for name in ["EvenCount", "OddCount", "ParityTest"] {
+ let compile = |package: &materialcraft_core::Package| {
+ let graph = package.graph_by_name(&format!("Functions/Math/Parity/{name}")).unwrap().1;
+ function::compile(graph.function.as_ref().unwrap(), 0).unwrap()
+ };
+ let expected = compile(&supplied);
+ let actual = compile(&bundled);
+ for &input in &inputs {
+ let variables = BTreeMap::from([("Input".into(), Value::Float(input))]);
+ let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &variables };
+ let evaluate = |program: &function::Program| program.evaluate(&context, &mut EvaluationState::default()).unwrap();
+
+ assert_eq!(evaluate(&actual), evaluate(&expected), "{name}({input})");
+ }
+ }
+
+ eprintln!("Compared three parity functions against the supplied graphs at {} inputs each", inputs.len());
+}
+
+#[test]
+fn library_aliases_reject_paths_outside_the_asset_root() {
+ use materialcraft_formats::sbs::library::relative_path;
+
+ assert_eq!(relative_path("sbs://folder/file.sbs").unwrap(), "folder/file.sbs");
+ for invalid in ["sbs://../private", "sbs:///etc/passwd", "sbs://folder/../../private", "sbs://%2e%2e/private", "sbs://C:/private", "sbs://folder\\private"]
+ {
+ assert!(relative_path(invalid).is_err(), "{invalid}");
+ }
+}
+
+#[test]
+fn library_relative_resources_stay_with_the_owning_package() {
+ use materialcraft_formats::sbs::library::resolve;
+
+ assert_eq!(resolve("sbs://functions.sbs", "resources/tile.png").unwrap(), "sbs://resources/tile.png");
+ assert_eq!(resolve("sbs://nested/functions.sbs", "resources/tile.png").unwrap(), "sbs://nested/resources/tile.png");
+ assert_eq!(resolve("sbs://nested/functions.sbs", "../resources/tile.png").unwrap(), "sbs://resources/tile.png");
+ assert_eq!(resolve("sbs://functions.sbs", ".\\resources\\tile.png").unwrap(), "sbs://resources/tile.png");
+ assert_eq!(resolve("sbs://nested/functions.sbs", "sbs://resources/tile.png").unwrap(), "sbs://resources/tile.png");
+ for invalid in ["../private", "../../private", "/etc/passwd", "C:\\private", "https://example.com/image.png", "%2e%2e/private", ""] {
+ assert!(resolve("sbs://functions.sbs", invalid).is_err(), "{invalid}");
+ }
+}
+
+#[test]
+fn duplicate_leaf_names_require_their_package_folder() {
+ let mut package = materialcraft_core::Package::new("Folders");
+ for folder in ["A", "B"] {
+ let mut graph = materialcraft_core::Graph::new("Same");
+ graph.folder = folder.into();
+ graph.function = Some(materialcraft_core::FunctionGraph::constant(materialcraft_core::Value::Float(1.0)));
+ package.graphs.push(graph);
+ }
+
+ let read = read_sbs(&write_sbs(&package).unwrap(), "folders.sbs", &|_| None).unwrap();
+
+ assert!(read.pkg.graph_by_name("Same").is_none());
+ assert_eq!(read.pkg.unique_graph_name("Same"), "Same_1");
+ assert_eq!(read.pkg.graph_by_name("A/Same").unwrap().1.folder, "A");
+ assert_eq!(read.pkg.graph_by_name("B/Same").unwrap().1.folder, "B");
+}
diff --git a/crates/formats/tests/graph_attributes.rs b/crates/formats/tests/graph_attributes.rs
new file mode 100644
index 00000000..e52702c3
--- /dev/null
+++ b/crates/formats/tests/graph_attributes.rs
@@ -0,0 +1,30 @@
+use materialcraft_formats::sbs::{read_sbs, write_sbs};
+use serde_json::json;
+
+#[test]
+fn native_graph_attributes_load_and_survive_sbs_save() {
+ for kind in ["graph", "function"] {
+ let body = if kind == "function" { "" } else { "" };
+ let xml = format!(
+ r#"<{kind}>
+
+
+
+ {body}{kind}>"#
+ );
+ let imported = read_sbs(xml.as_bytes(), "attributes.sbs", &|_| None).unwrap().pkg;
+ let expected = json!({"label": "Readable & non-unique label", "description": "First line\n
Second line
",
+ "category": "Tools/Math", "author": "Example author", "authorUrl": "https://example.org/?a=1&b=2",
+ "tags": "math utility", "group": "Utilities", "userData": "pipeline=example"});
+
+ assert_eq!(serde_json::to_value(&imported.graphs[0].attributes).unwrap(), expected, "{kind} import");
+ let bytes = write_sbs(&imported).unwrap();
+ let saved = read_sbs(&bytes, "saved.sbs", &|_| None).unwrap().pkg;
+
+ assert_eq!(saved.graphs[0].name, "Stable_identifier");
+ assert_eq!(serde_json::to_value(&saved.graphs[0].attributes).unwrap(), expected, "{kind} save");
+ let xml = String::from_utf8(bytes).unwrap();
+ assert!(xml.contains(" NodeDefinition {
- node("directional_blur", "Directional Blur", ATOMIC)
+ node("directional_blur", "Directional blur", ATOMIC)
.desc("Blurs along one direction.")
.atomic()
.any_in("input", "Input")
diff --git a/crates/nodes/src/atomic/directional_warp.rs b/crates/nodes/src/atomic/directional_warp.rs
index 821c481d..9489b617 100644
--- a/crates/nodes/src/atomic/directional_warp.rs
+++ b/crates/nodes/src/atomic/directional_warp.rs
@@ -3,7 +3,7 @@ use crate::{CookContext, CookResult, NodeDefinition, node};
use materialcraft_image::{Image, Kind};
pub(super) fn definition() -> NodeDefinition {
- node("directional_warp", "Directional Warp", ATOMIC)
+ node("directional_warp", "Directional warp", ATOMIC)
.desc("Offsets the input along a direction, by an intensity map.")
.atomic()
.any_in("input", "Input")
diff --git a/crates/nodes/src/atomic/gradient_map.rs b/crates/nodes/src/atomic/gradient_map.rs
index 033b3054..38677f5d 100644
--- a/crates/nodes/src/atomic/gradient_map.rs
+++ b/crates/nodes/src/atomic/gradient_map.rs
@@ -4,7 +4,7 @@ use materialcraft_core::Gradient;
use materialcraft_image::{Kind, luminance};
pub(super) fn definition() -> NodeDefinition {
- node("gradient_map", "Gradient Map", ATOMIC)
+ node("gradient_map", "Gradient map", ATOMIC)
.desc("Maps grayscale values to colors along a gradient.")
.atomic()
.gray_in("input", "Input")
diff --git a/crates/nodes/src/atomic/grayscale_conversion.rs b/crates/nodes/src/atomic/grayscale_conversion.rs
index 8f14943c..f4b9fa1b 100644
--- a/crates/nodes/src/atomic/grayscale_conversion.rs
+++ b/crates/nodes/src/atomic/grayscale_conversion.rs
@@ -3,7 +3,7 @@ use crate::{CookContext, CookResult, NodeDefinition, node};
use materialcraft_image::Kind;
pub(super) fn definition() -> NodeDefinition {
- node("grayscale_conversion", "Grayscale Conversion", ATOMIC)
+ node("grayscale_conversion", "Grayscale conversion", ATOMIC)
.desc("Weighted sum of the RGBA channels.")
.atomic()
.color_in("input", "Input")
diff --git a/crates/nodes/src/atomic/input_color.rs b/crates/nodes/src/atomic/input_color.rs
index fa94be9b..b3dc487b 100644
--- a/crates/nodes/src/atomic/input_color.rs
+++ b/crates/nodes/src/atomic/input_color.rs
@@ -4,7 +4,7 @@ use materialcraft_core::ComponentUsage;
use materialcraft_image::{Image, Kind};
pub(super) fn definition() -> NodeDefinition {
- node("input_color", "Input Color", GRAPH_ITEMS)
+ node("input_color", "Input color", GRAPH_ITEMS)
.desc("A color image input of the graph.")
.atomic()
.generator()
diff --git a/crates/nodes/src/atomic/input_grayscale.rs b/crates/nodes/src/atomic/input_grayscale.rs
index 80900df7..202263a6 100644
--- a/crates/nodes/src/atomic/input_grayscale.rs
+++ b/crates/nodes/src/atomic/input_grayscale.rs
@@ -4,7 +4,7 @@ use materialcraft_core::ComponentUsage;
use materialcraft_image::{Image, Kind};
pub(super) fn definition() -> NodeDefinition {
- node("input_grayscale", "Input Grayscale", GRAPH_ITEMS)
+ node("input_grayscale", "Input grayscale", GRAPH_ITEMS)
.desc("A grayscale image input of the graph.")
.atomic()
.generator()
diff --git a/crates/nodes/src/atomic/input_value.rs b/crates/nodes/src/atomic/input_value.rs
index 4178e2ce..5aaa5440 100644
--- a/crates/nodes/src/atomic/input_value.rs
+++ b/crates/nodes/src/atomic/input_value.rs
@@ -3,7 +3,7 @@ use crate::{NodeDefinition, PortKind, node};
use materialcraft_core::ComponentUsage;
pub(super) fn definition() -> NodeDefinition {
- node("input_value", "Input Value", GRAPH_ITEMS)
+ node("input_value", "Input value", GRAPH_ITEMS)
.desc("A typed value input of the graph.")
.atomic()
.text("identifier", "Identifier", "value")
diff --git a/crates/nodes/src/atomic/mod.rs b/crates/nodes/src/atomic/mod.rs
index 33a2a17b..aeb31097 100644
--- a/crates/nodes/src/atomic/mod.rs
+++ b/crates/nodes/src/atomic/mod.rs
@@ -16,7 +16,6 @@ mod input_color;
mod input_grayscale;
mod input_value;
mod levels;
-mod motion_blur;
mod normal;
mod output;
mod pattern_map;
diff --git a/crates/nodes/src/atomic/motion_blur.rs b/crates/nodes/src/atomic/motion_blur.rs
deleted file mode 100644
index 69da3bd0..00000000
--- a/crates/nodes/src/atomic/motion_blur.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-use super::{ATOMIC, directional_blur};
-use crate::{CookContext, CookResult, NodeDefinition, node};
-
-pub(super) fn definition() -> NodeDefinition {
- node("motion_blur", "Motion Blur", ATOMIC)
- .desc("Blurs the input along a motion direction.")
- .atomic()
- .any_in("input", "Input")
- .float("intensity", "Intensity", 10.0, 0.0, 64.0)
- .angle("shiftangle", "Angle", 0.0)
- .any_out()
- .cook(cook)
-}
-
-fn cook(context: &CookContext) -> CookResult {
- directional_blur::blur(context, context.f("shiftangle"))
-}
diff --git a/crates/nodes/src/atomic/pixel_processor.rs b/crates/nodes/src/atomic/pixel_processor.rs
index 07ba8a0a..a0a34d43 100644
--- a/crates/nodes/src/atomic/pixel_processor.rs
+++ b/crates/nodes/src/atomic/pixel_processor.rs
@@ -2,11 +2,11 @@ use super::ATOMIC;
use crate::{NodeDefinition, node};
pub(super) fn definition() -> NodeDefinition {
- node("pixel_processor", "Pixel Processor", ATOMIC)
+ node("pixel_processor", "Pixel processor", ATOMIC)
.desc("Computes every pixel with a function graph ($pos, $size; sample the inputs).")
.atomic()
.any_in("input0", "Input image 0")
- .function("function", "Per pixel function", crate::function::default_pixel_function())
+ .function("function", "Per pixel function", materialcraft_core::FunctionGraph::default())
.boolean("color_mode", "Color output", true)
.any_out()
.cook(crate::function::pixel_processor)
diff --git a/crates/nodes/src/atomic/uniform.rs b/crates/nodes/src/atomic/uniform.rs
index 36f230e0..fedde70a 100644
--- a/crates/nodes/src/atomic/uniform.rs
+++ b/crates/nodes/src/atomic/uniform.rs
@@ -3,7 +3,7 @@ use crate::{CookContext, CookResult, NodeDefinition, node};
use materialcraft_image::{Image, Kind, luminance};
pub(super) fn definition() -> NodeDefinition {
- node("uniform", "Uniform Color", ATOMIC)
+ node("uniform", "Uniform color", ATOMIC)
.desc("A single color or gray value.")
.atomic()
.generator()
diff --git a/crates/nodes/src/atomic/value_processor.rs b/crates/nodes/src/atomic/value_processor.rs
index 554a5bc0..583c51ac 100644
--- a/crates/nodes/src/atomic/value_processor.rs
+++ b/crates/nodes/src/atomic/value_processor.rs
@@ -2,11 +2,11 @@ use super::ATOMIC;
use crate::{NodeDefinition, node};
pub(super) fn definition() -> NodeDefinition {
- node("value_processor", "Value Processor", ATOMIC)
+ node("value_processor", "Value processor", ATOMIC)
.desc("Computes a typed value with a function graph.")
.atomic()
.any_in("input0", "Input image 0")
- .function("function", "Function", materialcraft_core::FunctionGraph::constant(materialcraft_core::Value::Float(0.5)))
+ .function("function", "Function", materialcraft_core::FunctionGraph::default())
.output("output", "Value", crate::PortKind::Value)
.cook(crate::node_definition_builder::no_cook)
}
diff --git a/crates/nodes/src/function/catalog.rs b/crates/nodes/src/function/catalog.rs
index d8f0dacf..a798180d 100644
--- a/crates/nodes/src/function/catalog.rs
+++ b/crates/nodes/src/function/catalog.rs
@@ -2,33 +2,59 @@ use super::FunctionDefinition;
use materialcraft_core::Value;
pub const FUNCTIONS: &[FunctionDefinition] = &[
- FunctionDefinition { id: "const_bool", label: "Boolean", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_bool", label: "Get Boolean", inputs: &[], category: "Variables" },
FunctionDefinition { id: "const_float1", label: "Float", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_float1", label: "Get Float", inputs: &[], category: "Variables" },
FunctionDefinition { id: "const_float2", label: "Float2", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_float2", label: "Get Float2", inputs: &[], category: "Variables" },
FunctionDefinition { id: "const_float3", label: "Float3", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_float3", label: "Get Float3", inputs: &[], category: "Variables" },
FunctionDefinition { id: "const_float4", label: "Float4", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_float4", label: "Get Float4", inputs: &[], category: "Variables" },
FunctionDefinition { id: "const_int1", label: "Integer", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_integer1", label: "Get Integer", inputs: &[], category: "Variables" },
FunctionDefinition { id: "const_int2", label: "Integer2", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_integer2", label: "Get Integer2", inputs: &[], category: "Variables" },
FunctionDefinition { id: "const_int3", label: "Integer3", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_integer3", label: "Get Integer3", inputs: &[], category: "Variables" },
FunctionDefinition { id: "const_int4", label: "Integer4", inputs: &[], category: "Constant" },
- FunctionDefinition { id: "get_integer4", label: "Get Integer4", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "const_bool", label: "Boolean", inputs: &[], category: "Constant" },
FunctionDefinition { id: "const_string", label: "String", inputs: &[], category: "Constant" },
+ FunctionDefinition { id: "vector2", label: "Vector Float2", inputs: &["componentsin", "componentslast"], category: "Vector" },
+ FunctionDefinition { id: "vector3", label: "Vector Float3", inputs: &["componentsin", "componentslast"], category: "Vector" },
+ FunctionDefinition { id: "vector4", label: "Vector Float4", inputs: &["componentsin", "componentslast"], category: "Vector" },
+ FunctionDefinition { id: "swizzle1", label: "Swizzle Float1", inputs: &["vector"], category: "Vector" },
+ FunctionDefinition { id: "swizzle2", label: "Swizzle Float2", inputs: &["vector"], category: "Vector" },
+ FunctionDefinition { id: "swizzle3", label: "Swizzle Float3", inputs: &["vector"], category: "Vector" },
+ FunctionDefinition { id: "swizzle4", label: "Swizzle Float4", inputs: &["vector"], category: "Vector" },
+ FunctionDefinition { id: "ivector2", label: "Vector Integer2", inputs: &["componentsin", "componentslast"], category: "Vector" },
+ FunctionDefinition { id: "ivector3", label: "Vector Integer3", inputs: &["componentsin", "componentslast"], category: "Vector" },
+ FunctionDefinition { id: "ivector4", label: "Vector Integer4", inputs: &["componentsin", "componentslast"], category: "Vector" },
+ FunctionDefinition { id: "iswizzle1", label: "Swizzle Integer1", inputs: &["vector"], category: "Vector" },
+ FunctionDefinition { id: "iswizzle2", label: "Swizzle Integer2", inputs: &["vector"], category: "Vector" },
+ FunctionDefinition { id: "iswizzle3", label: "Swizzle Integer3", inputs: &["vector"], category: "Vector" },
+ FunctionDefinition { id: "iswizzle4", label: "Swizzle Integer4", inputs: &["vector"], category: "Vector" },
+ FunctionDefinition { id: "set", label: "Set", inputs: &["value"], category: "Variables" },
+ FunctionDefinition { id: "get_float1", label: "Get Float", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "get_float2", label: "Get Float2", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "get_float3", label: "Get Float3", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "get_float4", label: "Get Float4", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "get_integer1", label: "Get Integer", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "get_integer2", label: "Get Integer2", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "get_integer3", label: "Get Integer3", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "get_integer4", label: "Get Integer4", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "get_bool", label: "Get Boolean", inputs: &[], category: "Variables" },
FunctionDefinition { id: "get_string", label: "Get String", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "isdefined", label: "Is defined", inputs: &[], category: "Variables" },
+ FunctionDefinition { id: "samplelum", label: "Sample gray", inputs: &["pos"], category: "Samplers" },
+ FunctionDefinition { id: "samplecol", label: "Sample color", inputs: &["pos"], category: "Samplers" },
+ FunctionDefinition { id: "tofloat", label: "To Float", inputs: &["value"], category: "Cast" },
+ FunctionDefinition { id: "tofloat2", label: "To Float2", inputs: &["value"], category: "Cast" },
+ FunctionDefinition { id: "tofloat3", label: "To Float3", inputs: &["value"], category: "Cast" },
+ FunctionDefinition { id: "tofloat4", label: "To Float4", inputs: &["value"], category: "Cast" },
+ FunctionDefinition { id: "toint1", label: "To Integer", inputs: &["value"], category: "Cast" },
+ FunctionDefinition { id: "toint2", label: "To Integer2", inputs: &["value"], category: "Cast" },
+ FunctionDefinition { id: "toint3", label: "To Integer3", inputs: &["value"], category: "Cast" },
+ FunctionDefinition { id: "toint4", label: "To Integer4", inputs: &["value"], category: "Cast" },
FunctionDefinition { id: "add", label: "Add", inputs: &["a", "b"], category: "Operator" },
- FunctionDefinition { id: "sub", label: "Subtract", inputs: &["a", "b"], category: "Operator" },
- FunctionDefinition { id: "mul", label: "Multiply", inputs: &["a", "b"], category: "Operator" },
- FunctionDefinition { id: "div", label: "Divide", inputs: &["a", "b"], category: "Operator" },
+ FunctionDefinition { id: "sub", label: "Subtraction", inputs: &["a", "b"], category: "Operator" },
+ FunctionDefinition { id: "mul", label: "Multiplication", inputs: &["a", "b"], category: "Operator" },
+ FunctionDefinition { id: "mulscalar", label: "Scalar multiplication", inputs: &["a", "scalar"], category: "Operator" },
+ FunctionDefinition { id: "div", label: "Division", inputs: &["a", "b"], category: "Operator" },
+ FunctionDefinition { id: "neg", label: "Negation", inputs: &["a"], category: "Operator" },
FunctionDefinition { id: "mod", label: "Modulo", inputs: &["a", "b"], category: "Operator" },
- FunctionDefinition { id: "neg", label: "Negate", inputs: &["a"], category: "Operator" },
- FunctionDefinition { id: "mulscalar", label: "Multiply by scalar", inputs: &["a", "scalar"], category: "Operator" },
FunctionDefinition { id: "dot", label: "Dot product", inputs: &["a", "b"], category: "Operator" },
FunctionDefinition { id: "and", label: "And", inputs: &["a", "b"], category: "Logical" },
FunctionDefinition { id: "or", label: "Or", inputs: &["a", "b"], category: "Logical" },
@@ -37,54 +63,28 @@ pub const FUNCTIONS: &[FunctionDefinition] = &[
FunctionDefinition { id: "noteq", label: "Not equal", inputs: &["a", "b"], category: "Comparison" },
FunctionDefinition { id: "gt", label: "Greater", inputs: &["a", "b"], category: "Comparison" },
FunctionDefinition { id: "gteq", label: "Greater or equal", inputs: &["a", "b"], category: "Comparison" },
- FunctionDefinition { id: "lr", label: "Less", inputs: &["a", "b"], category: "Comparison" },
- FunctionDefinition { id: "lreq", label: "Less or equal", inputs: &["a", "b"], category: "Comparison" },
+ FunctionDefinition { id: "lr", label: "Lower", inputs: &["a", "b"], category: "Comparison" },
+ FunctionDefinition { id: "lreq", label: "Lower or equal", inputs: &["a", "b"], category: "Comparison" },
FunctionDefinition { id: "abs", label: "Absolute", inputs: &["a"], category: "Function" },
FunctionDefinition { id: "floor", label: "Floor", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "ceil", label: "Ceiling", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "sqrt", label: "Square root", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "exp", label: "Exponential", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "log", label: "Natural logarithm", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "log2", label: "Logarithm base 2", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "pow2", label: "Power of 2", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "sin", label: "Sine", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "ceil", label: "Ceil", inputs: &["a"], category: "Function" },
FunctionDefinition { id: "cos", label: "Cosine", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "sin", label: "Sine", inputs: &["a"], category: "Function" },
FunctionDefinition { id: "tan", label: "Tangent", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "atan2", label: "Arc tangent", inputs: &["a"], category: "Function" },
- FunctionDefinition { id: "rand", label: "Random", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "atan2", label: "Arc tangent 2", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "cartesian", label: "Cartesian", inputs: &["rho", "theta"], category: "Function" },
+ FunctionDefinition { id: "sqrt", label: "Square root", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "log", label: "Logarithm", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "exp", label: "Exponential", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "log2", label: "Logarithm base 2", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "pow2", label: "2Pow", inputs: &["a"], category: "Function" },
+ FunctionDefinition { id: "pow", label: "Pow", inputs: &["a", "b"], category: "Function" },
+ FunctionDefinition { id: "lerp", label: "Linear interpolation", inputs: &["a", "b", "x"], category: "Function" },
FunctionDefinition { id: "min", label: "Minimum", inputs: &["a", "b"], category: "Function" },
FunctionDefinition { id: "max", label: "Maximum", inputs: &["a", "b"], category: "Function" },
- FunctionDefinition { id: "pow", label: "Power", inputs: &["a", "b"], category: "Function" },
- FunctionDefinition { id: "lerp", label: "Linear interpolation", inputs: &["a", "b", "x"], category: "Function" },
- FunctionDefinition { id: "cartesian", label: "Cartesian", inputs: &["rho", "theta"], category: "Function" },
- FunctionDefinition { id: "vector2", label: "Float vector 2", inputs: &["componentsin", "componentslast"], category: "Vector" },
- FunctionDefinition { id: "vector3", label: "Float vector 3", inputs: &["componentsin", "componentslast"], category: "Vector" },
- FunctionDefinition { id: "vector4", label: "Float vector 4", inputs: &["componentsin", "componentslast"], category: "Vector" },
- FunctionDefinition { id: "swizzle1", label: "Float swizzle 1", inputs: &["vector"], category: "Vector" },
- FunctionDefinition { id: "swizzle2", label: "Float swizzle 2", inputs: &["vector"], category: "Vector" },
- FunctionDefinition { id: "swizzle3", label: "Float swizzle 3", inputs: &["vector"], category: "Vector" },
- FunctionDefinition { id: "swizzle4", label: "Float swizzle 4", inputs: &["vector"], category: "Vector" },
- FunctionDefinition { id: "ivector2", label: "Integer vector 2", inputs: &["componentsin", "componentslast"], category: "Vector" },
- FunctionDefinition { id: "ivector3", label: "Integer vector 3", inputs: &["componentsin", "componentslast"], category: "Vector" },
- FunctionDefinition { id: "ivector4", label: "Integer vector 4", inputs: &["componentsin", "componentslast"], category: "Vector" },
- FunctionDefinition { id: "iswizzle1", label: "Integer swizzle 1", inputs: &["vector"], category: "Vector" },
- FunctionDefinition { id: "iswizzle2", label: "Integer swizzle 2", inputs: &["vector"], category: "Vector" },
- FunctionDefinition { id: "iswizzle3", label: "Integer swizzle 3", inputs: &["vector"], category: "Vector" },
- FunctionDefinition { id: "iswizzle4", label: "Integer swizzle 4", inputs: &["vector"], category: "Vector" },
- FunctionDefinition { id: "tofloat", label: "To Float1", inputs: &["value"], category: "Cast" },
- FunctionDefinition { id: "toint1", label: "To Integer1", inputs: &["value"], category: "Cast" },
- FunctionDefinition { id: "tofloat2", label: "To Float2", inputs: &["value"], category: "Cast" },
- FunctionDefinition { id: "toint2", label: "To Integer2", inputs: &["value"], category: "Cast" },
- FunctionDefinition { id: "tofloat3", label: "To Float3", inputs: &["value"], category: "Cast" },
- FunctionDefinition { id: "toint3", label: "To Integer3", inputs: &["value"], category: "Cast" },
- FunctionDefinition { id: "tofloat4", label: "To Float4", inputs: &["value"], category: "Cast" },
- FunctionDefinition { id: "toint4", label: "To Integer4", inputs: &["value"], category: "Cast" },
- FunctionDefinition { id: "samplecol", label: "Sample color", inputs: &["pos"], category: "Samplers" },
- FunctionDefinition { id: "samplelum", label: "Sample grayscale", inputs: &["pos"], category: "Samplers" },
- FunctionDefinition { id: "set", label: "Set variable", inputs: &["value"], category: "Variables" },
- FunctionDefinition { id: "isdefined", label: "Is defined", inputs: &[], category: "Variables" },
- FunctionDefinition { id: "ifelse", label: "If…Else", inputs: &["condition", "ifpath", "elsepath"], category: "Control" },
+ FunctionDefinition { id: "rand", label: "Random", inputs: &["a"], category: "Function" },
FunctionDefinition { id: "sequence", label: "Sequence", inputs: &["seqin", "seqlast"], category: "Control" },
+ FunctionDefinition { id: "ifelse", label: "If...Else", inputs: &["condition", "ifpath", "elsepath"], category: "Control" },
FunctionDefinition { id: "while", label: "While loop", inputs: &["init", "cond", "loop"], category: "Control" },
FunctionDefinition { id: "passthrough", label: "Dot", inputs: &["input"], category: "Control" },
];
diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs
index 58028516..aa7ac5a6 100644
--- a/crates/nodes/src/function/compile.rs
+++ b/crates/nodes/src/function/compile.rs
@@ -29,38 +29,60 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
}
let node = nodes.get(&id).ok_or_else(|| format!("missing function node {id}"))?;
+ if node.missing.is_some() {
+ return Err(format!("Missing function operation `{}`", node.op));
+ }
let definition = if node.instance.is_some() {
&super::function_call::DEFINITION
} else {
catalog::definition(&node.op).ok_or_else(|| format!("unknown function `{}`", node.op))?
};
let names: Vec<_> = super::input_identifiers(node).collect();
- if node.inputs.len() != names.len() || node.inputs.iter().any(Option::is_none) {
+ let missing_input = names
+ .iter()
+ .zip(&node.inputs)
+ .any(|(name, input)| input.is_none() && !node.instance.as_ref().is_some_and(|instance| instance.defaults.contains_key(*name)));
+ if node.inputs.len() != names.len() || missing_input {
return Err(format!("{} ({id}) requires connected inputs: {}", super::node_label(node), names.join(", ")));
}
+ // Preserved legacy connectors must not evaluate a duplicate random or stateful input twice
+ let ports: Vec<_> = names
+ .into_iter()
+ .zip(&node.inputs)
+ .filter(|(name, _)| node.instance.as_ref().is_none_or(|instance| instance.defaults.contains_key(*name)))
+ .collect();
+ let sources: Vec<_> = ports.iter().filter_map(|(_, input)| **input).collect();
if !visited {
if !active.insert(id) {
return Err(format!("function cycle at node {id}"));
}
pending.push((id, true));
- pending.extend(node.inputs.iter().rev().flatten().map(|input| (*input, false)));
+ pending.extend(sources.iter().rev().map(|input| (*input, false)));
continue;
}
active.remove(&id);
let inputs: Vec =
- node.inputs.iter().flatten().map(|input| indices.get(input).copied().ok_or("unresolved function input".to_string())).collect::>()?;
+ sources.iter().map(|input| indices.get(input).copied().ok_or("unresolved function input".to_string())).collect::>()?;
let call = if let Some(instance) = &node.instance {
let source = node.source.as_ref().ok_or_else(|| format!("unresolved Function Graph `{}`", instance.graph))?.as_ref().map_err(Clone::clone)?;
let program = compile_nested(source, seed, depth + 1, remaining)?;
- for (port, index) in instance.inputs.iter().zip(&inputs) {
+ for (port, index) in instance
+ .inputs
+ .iter()
+ .zip(&node.inputs)
+ .filter(|(port, input)| input.is_some() && instance.defaults.contains_key(&port.identifier))
+ .map(|(port, _)| port)
+ .zip(&inputs)
+ {
if instructions.get(*index).is_some_and(|instruction| instruction.type_code != port.type_code) {
return Err(format!("{}: input `{}` has the wrong type", instance.graph, port.identifier));
}
}
- Some(super::function_call::FunctionCall { program, inputs: names.iter().map(|name| (*name).to_string()).collect() })
+ let inputs = ports.iter().filter(|(_, input)| input.is_some()).map(|(name, _)| (*name).to_string()).collect();
+ Some(super::function_call::FunctionCall { program, inputs, defaults: instance.defaults.clone() })
} else {
None
};
diff --git a/crates/nodes/src/function/evaluation_context.rs b/crates/nodes/src/function/evaluation_context.rs
index 94a2c5c1..449b685e 100644
--- a/crates/nodes/src/function/evaluation_context.rs
+++ b/crates/nodes/src/function/evaluation_context.rs
@@ -4,9 +4,21 @@ use std::collections::BTreeMap;
/// Inputs shared by one function evaluation
pub struct EvaluationContext<'a> {
+ pub scope: super::FunctionScope,
pub position: [f32; 2],
pub size: [f32; 2],
pub images: &'a [Option],
pub tile: bool,
pub variables: &'a BTreeMap,
}
+
+impl EvaluationContext<'_> {
+ pub(super) fn variable(&self, name: &str, local: &BTreeMap) -> Result