Unify graph editors and optimize material workflows

This commit is contained in:
chasse20 committed 2026-11-06 00:13:10 -05:00
1 parent d318484b41
commit fe88ee5c4d
163 files changed
+8130 -4038

No files matched your search

Generated
+1
View File
@@ -2463,6 +2463,7 @@ dependencies = [
name = "materialcraft-render"
version = "0.1.2"
dependencies = [
"materialcraft-core",
"materialcraft-geom",
"materialcraft-image",
"rayon",
+81
View File
@@ -0,0 +1,81 @@
/// Input/output semantics shared by node properties, SBS and texture exports
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ComponentUsage {
pub id: &'static str,
pub label: &'static str,
}
impl ComponentUsage {
pub const ANY: Self = Self { id: "any", label: "Any" };
pub const ANY_INDEX: u32 = 9;
// Existing indices are saved in documents; append new entries without reordering
pub const ALL: &'static [Self] = &[
Self { id: "baseColor", label: "Base color" },
Self { id: "normal", label: "Normal" },
Self { id: "roughness", label: "Roughness" },
Self { id: "metallic", label: "Metallic" },
Self { id: "height", label: "Height" },
Self { id: "ambientOcclusion", label: "Ambient occlusion" },
Self { id: "emissive", label: "Emissive" },
Self { id: "opacity", label: "Opacity" },
Self { id: "specular", label: "Specular" },
Self::ANY,
Self { id: "diffuse", label: "Diffuse" },
Self { id: "glossiness", label: "Glossiness" },
Self { id: "specularLevel", label: "Specular level" },
Self { id: "specularEdgeColor", label: "Specular edge color" },
Self { id: "anisotropyLevel", label: "Anisotropy level" },
Self { id: "anisotropyAngle", label: "Anisotropy angle" },
Self { id: "IOR", label: "Index of refraction" },
Self { id: "scattering", label: "Scattering" },
Self { id: "scatteringColor", label: "Scattering color" },
Self { id: "scatteringDistance", label: "Scattering distance" },
Self { id: "scatteringDistanceScale", label: "Scattering distance scale" },
Self { id: "transmissive", label: "Transmissive" },
Self { id: "translucency", label: "Translucency" },
Self { id: "absorptionColor", label: "Absorption color" },
Self { id: "absorptionDistance", label: "Absorption distance" },
Self { id: "coatOpacity", label: "Coat opacity" },
Self { id: "coatColor", label: "Coat color" },
Self { id: "coatRoughness", label: "Coat roughness" },
Self { id: "coatSpecularLevel", label: "Coat specular level" },
Self { id: "coatNormal", label: "Coat normal" },
Self { id: "coatIOR", label: "Coat index of refraction" },
Self { id: "sheenOpacity", label: "Sheen opacity" },
Self { id: "sheenColor", label: "Sheen color" },
Self { id: "sheenRoughness", label: "Sheen roughness" },
Self { id: "reflection", label: "Reflection" },
Self { id: "displacement", label: "Displacement" },
Self { id: "ambient", label: "Ambient" },
Self { id: "mask", label: "Mask" },
Self { id: "blendingmask", label: "Blending mask" },
Self { id: "bump", label: "Bump" },
Self { id: "user0", label: "User 0" },
Self { id: "user1", label: "User 1" },
Self { id: "user2", label: "User 2" },
Self { id: "user3", label: "User 3" },
Self { id: "user4", label: "User 4" },
Self { id: "user5", label: "User 5" },
Self { id: "user6", label: "User 6" },
Self { id: "user7", label: "User 7" },
];
pub const LABELS: &'static [&'static str] = &{
let mut labels = [""; Self::ALL.len()];
let mut index = 0;
while index < labels.len() {
labels[index] = Self::ALL[index].label;
index += 1;
}
labels
};
pub fn from_index(index: u32) -> Self {
Self::ALL.get(index as usize).copied().unwrap_or(Self::ANY)
}
pub fn index(id: &str) -> u32 {
Self::ALL.iter().position(|usage| usage.id.eq_ignore_ascii_case(id.trim())).map_or(Self::ANY_INDEX, |index| index as u32)
}
}
+3 -44
View File
@@ -138,58 +138,17 @@ impl Graph {
}
pub fn topo_order(&self) -> Vec<NodeId> {
let mut indeg: BTreeMap<NodeId, usize> = self.nodes.iter().map(|n| (n.id, 0)).collect();
for c in &self.connections {
if let Some(d) = indeg.get_mut(&c.to)
&& self.nodes.iter().any(|n| n.id == c.from)
{
*d += 1;
}
}
let mut ready: Vec<NodeId> = indeg.iter().filter(|(_, d)| **d == 0).map(|(id, _)| *id).collect();
let mut out = Vec::with_capacity(self.nodes.len());
while let Some(n) = ready.pop() {
out.push(n);
for c in self.connections.iter().filter(|c| c.from == n) {
if let Some(d) = indeg.get_mut(&c.to) {
*d = d.saturating_sub(1);
if *d == 0 {
ready.push(c.to);
}
}
}
}
out
crate::GraphIndex::new(self).topo_order()
}
/// Every node upstream of `id` (not including it)
pub fn upstream(&self, id: NodeId) -> Vec<NodeId> {
let mut out = Vec::new();
let mut stack = vec![id];
while let Some(n) = stack.pop() {
for c in self.connections.iter().filter(|c| c.to == n) {
if !out.contains(&c.from) {
out.push(c.from);
stack.push(c.from);
}
}
}
out
crate::GraphIndex::new(self).upstream(id)
}
/// Every node downstream of `id` (not including it)
pub fn downstream(&self, id: NodeId) -> Vec<NodeId> {
let mut out = Vec::new();
let mut stack = vec![id];
while let Some(n) = stack.pop() {
for c in self.connections.iter().filter(|c| c.from == n) {
if !out.contains(&c.to) {
out.push(c.to);
stack.push(c.to);
}
}
}
out
crate::GraphIndex::new(self).downstream(id)
}
/// The value of exposed input `id` (its default when unset)
+133
View File
@@ -0,0 +1,133 @@
use std::collections::{BTreeMap, BTreeSet};
use crate::{Connection, Graph, Node, NodeId};
/// Borrowed lookups for one graph operation, rebuilt when the graph changes
pub struct GraphIndex<'a> {
nodes: BTreeMap<NodeId, &'a Node>,
incoming: BTreeMap<NodeId, Vec<&'a Connection>>,
outgoing: BTreeMap<NodeId, Vec<&'a Connection>>,
}
impl<'a> GraphIndex<'a> {
pub fn new(graph: &'a Graph) -> Self {
let mut nodes = BTreeMap::new();
for node in &graph.nodes {
nodes.entry(node.id).or_insert(node);
}
let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new();
let mut outgoing: BTreeMap<_, Vec<_>> = BTreeMap::new();
for connection in &graph.connections {
incoming.entry(connection.to).or_default().push(connection);
outgoing.entry(connection.from).or_default().push(connection);
}
Self { nodes, incoming, outgoing }
}
pub fn node(&self, id: NodeId) -> Option<&'a Node> {
self.nodes.get(&id).copied()
}
pub fn incoming(&self, id: NodeId) -> &[&'a Connection] {
self.incoming.get(&id).map_or(&[], Vec::as_slice)
}
pub fn input_of(&self, id: NodeId, port: &str) -> Option<&'a Connection> {
self.incoming(id).iter().copied().find(|connection| connection.to_port == port)
}
pub fn topo_order(&self) -> Vec<NodeId> {
let mut degrees: BTreeMap<_, _> = self.nodes.keys().map(|id| (*id, 0usize)).collect();
for (id, connections) in &self.incoming {
if let Some(degree) = degrees.get_mut(id) {
*degree = connections.iter().filter(|connection| self.nodes.contains_key(&connection.from)).count();
}
}
let mut ready: Vec<_> = degrees.iter().filter(|(_, degree)| **degree == 0).map(|(id, _)| *id).collect();
let mut ordered = Vec::with_capacity(self.nodes.len());
while let Some(id) = ready.pop() {
ordered.push(id);
for connection in self.outgoing.get(&id).into_iter().flatten() {
if let Some(degree) = degrees.get_mut(&connection.to) {
*degree = degree.saturating_sub(1);
if *degree == 0 {
ready.push(connection.to);
}
}
}
}
ordered
}
pub fn upstream(&self, id: NodeId) -> Vec<NodeId> {
self.connected(id, true)
}
pub fn downstream(&self, id: NodeId) -> Vec<NodeId> {
self.connected(id, false)
}
pub fn required_nodes(&self, roots: &[NodeId]) -> BTreeSet<NodeId> {
let mut required: BTreeSet<_> = roots.iter().copied().collect();
let mut pending = roots.to_vec();
while let Some(id) = pending.pop() {
for connection in self.incoming(id) {
if required.insert(connection.from) {
pending.push(connection.from);
}
}
}
required
}
fn connected(&self, root: NodeId, upstream: bool) -> Vec<NodeId> {
let adjacency = if upstream { &self.incoming } else { &self.outgoing };
let mut visited = BTreeSet::new();
let mut connected = Vec::new();
let mut pending = vec![root];
while let Some(id) = pending.pop() {
for connection in adjacency.get(&id).into_iter().flatten() {
let next = if upstream { connection.from } else { connection.to };
if visited.insert(next) {
connected.push(next);
pending.push(next);
}
}
}
connected
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn traversal_preserves_document_order_and_dangling_edge_behavior() {
let mut graph = Graph::new("Traversal");
let first = graph.add_node("uniform", [0.0; 2]);
let second = graph.add_node("dot", [0.0; 2]);
let third = graph.add_node("blend", [0.0; 2]);
let fourth = graph.add_node("dot", [0.0; 2]);
for (from, to, port) in [(first, second, "input"), (first, third, "foreground"), (second, third, "background"), (NodeId(99), fourth, "input")] {
graph.connections.push(Connection { from, from_port: "output".into(), to, to_port: port.into() });
}
let index = GraphIndex::new(&graph);
assert_eq!(index.topo_order(), [fourth, first, second, third]);
assert_eq!(index.upstream(third), [first, second]);
assert_eq!(index.downstream(first), [second, third]);
assert_eq!(index.required_nodes(&[third, fourth]), BTreeSet::from([first, second, third, fourth, NodeId(99)]));
assert_eq!(index.input_of(third, "background").unwrap().from, second);
graph.connections.push(Connection { from: third, from_port: "output".into(), to: first, to_port: "input".into() });
assert_eq!(GraphIndex::new(&graph).topo_order(), [fourth]);
}
}
+6
View File
@@ -5,6 +5,7 @@ mod attributes;
mod base_parameters;
mod color;
mod comment;
mod component_usage;
mod connection;
mod core_error;
mod curve;
@@ -16,7 +17,9 @@ mod function_node;
mod gradient;
mod gradient_key;
mod graph;
mod graph_index;
mod graph_kind;
mod material_channel;
mod missing_node;
mod node;
mod node_id;
@@ -37,6 +40,7 @@ pub use attributes::Attributes;
pub use base_parameters::BaseParameters;
pub use color::{linear_to_srgb, parse_color, srgb_to_linear};
pub use comment::Comment;
pub use component_usage::ComponentUsage;
pub use connection::Connection;
pub use core_error::CoreError;
pub use curve::Curve;
@@ -48,7 +52,9 @@ pub use function_node::FunctionNode;
pub use gradient::Gradient;
pub use gradient_key::GradientKey;
pub use graph::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2};
pub use graph_index::GraphIndex;
pub use graph_kind::GraphKind;
pub use material_channel::MaterialChannel;
pub use missing_node::{MISSING_NODE, missing_ports};
pub use node::Node;
pub use node_id::NodeId;
+50
View File
@@ -0,0 +1,50 @@
use serde::{Deserialize, Serialize};
/// Texture channels supported by the material preview
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MaterialChannel {
BaseColor,
Normal,
Roughness,
Metallic,
Height,
AmbientOcclusion,
Emissive,
Opacity,
}
impl MaterialChannel {
pub const ALL: [Self; 8] =
[Self::BaseColor, Self::Normal, Self::Roughness, Self::Metallic, Self::Height, Self::AmbientOcclusion, Self::Emissive, Self::Opacity];
pub fn id(self) -> &'static str {
match self {
Self::BaseColor => "baseColor",
Self::Normal => "normal",
Self::Roughness => "roughness",
Self::Metallic => "metallic",
Self::Height => "height",
Self::AmbientOcclusion => "ambientOcclusion",
Self::Emissive => "emissive",
Self::Opacity => "opacity",
}
}
pub fn label(self) -> &'static str {
match self {
Self::BaseColor => "Base color",
Self::Normal => "Normal",
Self::Roughness => "Roughness",
Self::Metallic => "Metallic",
Self::Height => "Height",
Self::AmbientOcclusion => "Ambient occlusion",
Self::Emissive => "Emissive",
Self::Opacity => "Opacity",
}
}
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|channel| channel.id().eq_ignore_ascii_case(id)).or_else(|| id.eq_ignore_ascii_case("diffuse").then_some(Self::BaseColor))
}
}
+31 -1
View File
@@ -22,7 +22,15 @@ impl PatternGraph {
return Err("pattern graph exceeds the 4096-node limit".into());
}
let id = (1..=4097).find(|id| self.nodes.iter().all(|node| node.id != *id)).ok_or("no available pattern node id")?;
let mut occupied = [false; 4097];
for node in &self.nodes {
if let Some(slot) = occupied.get_mut(node.id.saturating_sub(1) as usize)
&& node.id != 0
{
*slot = true;
}
}
let id = occupied.iter().position(|occupied| !occupied).ok_or("no available pattern node id")? as u32 + 1;
self.nodes.push(PatternNode {
id,
kind,
@@ -76,3 +84,25 @@ impl PatternGraph {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allocation_reuses_the_lowest_hole_and_ignores_out_of_range_ids() {
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
let template = graph.nodes[0].clone();
graph.nodes = [0, 2, 4097, u32::MAX].map(|id| PatternNode { id, ..template.clone() }).to_vec();
assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 1);
assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 3);
graph.nodes.retain(|node| node.id != 2);
assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 2);
assert_eq!(graph.root, Some(1));
graph.nodes.resize(4096, template);
let before = graph.clone();
assert!(graph.add(PatternNodeKind::Dot).is_err());
assert_eq!(graph, before);
}
}
+95
View File
@@ -0,0 +1,95 @@
use crate::commands::{CommandSpec, bad, has_graph, strp};
use crate::selection_target::SelectionTarget;
use crate::{Result, Session, cmd};
use materialcraft_core::Value;
use serde_json::Value as Json;
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"graph.align",
"Align nodes",
[],
None,
"{mode: left|right|top|bottom|hcenter|vcenter|hdistribute|vdistribute, ids?: required for Function/FX-Map, pattern?: owner node id, function?: FunctionGraphTarget, graph?: owning graph index}",
has_graph,
align
)]
}
fn align(session: &mut Session, parameters: &Json) -> Result<Json> {
let mode = strp(parameters, "mode").unwrap_or("left");
let ids: Vec<u64> = parameters
.get("ids")
.and_then(Json::as_array)
.map(|ids| ids.iter().filter_map(Json::as_u64).collect())
.unwrap_or_else(|| session.selection.iter().map(|id| id.0).collect());
let target = SelectionTarget::resolve(session, parameters)?;
if target.is_some() && parameters.get("ids").and_then(Json::as_array).is_none() {
return Err(bad("graph.align", "ids are required for a Function Graph or FX-Map"));
}
match target {
Some(SelectionTarget::Function(target)) => {
let mut graph = target.current(session)?.clone();
align_selected(graph.nodes.iter_mut().map(|node| (u64::from(node.id), &mut node.pos)).collect(), &ids, mode)?;
crate::graph_validation::function(&graph).map_err(|error| bad("graph.align", error))?;
session.edit("Align nodes", |session| target.replace(session, graph))?;
}
Some(SelectionTarget::Pattern(owner)) => {
let mut graph = SelectionTarget::pattern(session, owner)?.clone();
align_selected(graph.nodes.iter_mut().map(|node| (u64::from(node.id), &mut node.position)).collect(), &ids, mode)?;
crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.align", error))?;
session.edit("Align nodes", |session| {
session.graph_mut()?.node_mut(owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
Ok(())
})?;
}
None => {
session.edit("Align nodes", |session| {
align_selected(session.graph_mut()?.nodes.iter_mut().map(|node| (node.id.0, &mut node.pos)).collect(), &ids, mode)
})?;
}
}
Ok(Json::Null)
}
fn align_selected(mut positions: Vec<(u64, &mut [f32; 2])>, ids: &[u64], mode: &str) -> Result<()> {
let present: std::collections::BTreeSet<_> = positions.iter().map(|(id, _)| *id).collect();
if let Some(id) = ids.iter().find(|id| !present.contains(id)) {
return Err(bad("graph.align", format!("no node {id}")));
}
let selected: std::collections::BTreeSet<_> = ids.iter().copied().collect();
positions.retain(|(id, _)| selected.contains(id));
align_positions(positions.into_iter().map(|(_, position)| position).collect(), mode)
}
fn align_positions(mut positions: Vec<&mut [f32; 2]>, mode: &str) -> Result<()> {
let axis = match mode {
"left" | "right" | "hcenter" | "hdistribute" => 0,
"top" | "bottom" | "vcenter" | "vdistribute" => 1,
other => return Err(bad("graph.align", format!("unknown mode `{other}`"))),
};
if positions.len() < 2 {
return Ok(());
}
let minimum = positions.iter().map(|position| position[axis]).fold(f32::MAX, f32::min);
let maximum = positions.iter().map(|position| position[axis]).fold(f32::MIN, f32::max);
if mode.ends_with("distribute") {
positions.sort_by(|left, right| left[axis].total_cmp(&right[axis]));
let step = (maximum - minimum) / (positions.len() - 1) as f32;
for (index, position) in positions.iter_mut().enumerate() {
position[axis] = minimum + step * index as f32;
}
} else {
let value = match mode {
"left" | "top" => minimum,
"right" | "bottom" => maximum,
_ => (minimum + maximum) * 0.5,
};
for position in positions {
position[axis] = value;
}
}
Ok(())
}
+9 -1
View File
@@ -51,7 +51,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
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::alignment_commands::specs());
v.extend(crate::annotation_commands::specs());
v.extend(crate::frame_commands::specs());
v.extend(crate::function_commands::specs());
@@ -62,6 +64,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::connection_commands::specs());
v.extend(crate::value_input_commands::specs());
v.extend(crate::view_cmds::specs());
v.extend(crate::material_preview_commands::specs());
v.extend(crate::wire_cmds::specs());
v
})
@@ -74,6 +77,9 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
/// Run a command by id with JSON params (empty params = defaults, never a dialog)
pub fn execute(s: &mut Session, id: &str, params: &J) -> Result<J> {
let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
if let Some(result) = crate::selection_commands::execute(s, id, params) {
return result;
}
(spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
let result = (spec.run)(s, params)?;
if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.graph().is_ok_and(|graph| selection.exists(graph))) {
@@ -90,7 +96,9 @@ pub fn list(s: &Session, filter: Option<&str>) -> J {
command_specs()
.iter()
.filter(|c| f.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f)))
.map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params, "enabled": (c.enabled)(s).is_ok()}))
.map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": if crate::selection_commands::supports(c.id) {
format!("{}; optional function: FunctionGraphTarget or pattern: owner node id, graph: owning graph index; embedded targets use explicit ids; copy returns clip", c.params)
} else { c.params.to_string() }, "enabled": crate::selection_commands::enabled(s, c.id, &J::Null).unwrap_or_else(|| (c.enabled)(s).is_ok())}))
.collect(),
)
}
+1 -1
View File
@@ -126,7 +126,7 @@ fn insert_clip(s: &mut Session, clip: &Clip, at: Option<[f32; 2]>, offset: [f32;
map.insert(n.id, id);
let mut c = n.clone();
c.id = id;
c.pos = crate::graph_grid::snap_position([n.pos[0] + shift[0], n.pos[1] + shift[1]], snap);
c.pos = crate::graph_grid::translate(n.pos, shift, snap);
g.nodes.push(c);
}
for c in &clip.connections {
+9
View File
@@ -0,0 +1,9 @@
use materialcraft_core::{FunctionNode, PatternNode};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum EmbeddedClipboard {
Function { source: String, nodes: Vec<FunctionNode> },
Pattern { source: String, nodes: Vec<PatternNode> },
}
@@ -0,0 +1,88 @@
use crate::{
FunctionEdit, FunctionGraphTarget, PatternEdit, Result, Session, cmd,
commands::{CommandSpec, bad, has_graph},
};
use materialcraft_core::{NodeId, Value};
use serde_json::{Value as Json, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"graph.function.edit",
"Edit function node",
[],
None,
"{target?: {kind: graph|parameter|dynamic|pattern, node?, owner?, parameter?}, edit: {action: add|move|connect|value|output, ...}, merge?: false}",
has_graph,
function
),
cmd!(
"graph.pattern.edit",
"Edit FX-Map node",
[],
None,
"{id: owner, edit: {action: add|move|connect|disconnect|root|value, ...}, merge?: false}",
has_graph,
pattern
),
cmd!("edit.finish", "Finish edit gesture", [], None, "{} ends the current undo group", crate::commands::always, |session, _| {
session.finish_edit();
Ok(Json::Null)
}),
]
}
fn commit(session: &mut Session, label: &str, key: Option<String>, run: impl FnOnce(&mut Session) -> Result<Json>) -> Result<Json> {
match key {
Some(key) => session.edit_merged(&key, label, run),
None => session.edit(label, run),
}
}
fn function(session: &mut Session, parameters: &Json) -> Result<Json> {
let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"})))
.map_err(|error| bad("graph.function.edit", error.to_string()))?;
let edit: FunctionEdit =
serde_json::from_value(parameters.get("edit").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.function.edit", error.to_string()))?;
let current = target.current(session)?;
if let FunctionEdit::Add { operation, .. } = &edit
&& !target.available_operations(session).any(|definition| definition.id == operation)
{
return Err(bad("graph.function.edit", "this operation is not available in the target function graph"));
}
let mut graph = current.clone();
let result = edit.apply(&mut graph).map_err(|error| bad("graph.function.edit", error))?;
crate::graph_validation::function(&graph).map_err(|error| bad("graph.function.edit", error))?;
let key = (parameters.get("merge").and_then(Json::as_bool) == Some(true))
.then(|| edit.merge_key())
.flatten()
.map(|key| format!("function:{}:{target:?}:{key}", session.graph));
commit(session, "Edit Function Graph", key, |session| {
target.replace(session, graph)?;
Ok(result)
})
}
fn pattern(session: &mut Session, parameters: &Json) -> Result<Json> {
let id = NodeId(parameters.get("id").and_then(Json::as_u64).ok_or_else(|| bad("graph.pattern.edit", "id is required"))?);
let node = session.graph()?.node(id)?;
if node.def != "fx_map" {
return Err(bad("graph.pattern.edit", "the node is not an FX-Map"));
}
let value = node.params.get("pattern").or_else(|| materialcraft_nodes::find(&node.def)?.param("pattern").map(|parameter| &parameter.default));
let Some(Value::PatternGraph(graph)) = value else { return Err(bad("graph.pattern.edit", "missing FX-Map graph")) };
let mut graph = (**graph).clone();
let edit: PatternEdit =
serde_json::from_value(parameters.get("edit").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.pattern.edit", error.to_string()))?;
let result = edit.apply(&mut graph).map_err(|error| bad("graph.pattern.edit", error))?;
crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.pattern.edit", error))?;
let key = (parameters.get("merge").and_then(Json::as_bool) == Some(true))
.then(|| edit.merge_key())
.flatten()
.map(|key| format!("pattern:{}:{}:{key}", session.graph, id.0));
commit(session, "Edit FX-Map graph", key, |session| {
session.graph_mut()?.node_mut(id)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
Ok(result)
})
}
+5
View File
@@ -83,6 +83,7 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
};
session.pkg.graphs.push(graph);
session.graph = session.pkg.graphs.len() - 1;
session.open_material_preview();
session.selection.clear();
session.annotation_selection = None;
session.view2d.node = None;
@@ -101,9 +102,12 @@ fn new_package(s: &mut Session, p: &J) -> Result<J> {
pub fn replace_package(s: &mut Session, pkg: Package, path: Option<String>) {
s.pkg = pkg;
s.clipboard = None;
s.embedded_clipboard = None;
s.clear_decoded();
s.path = path;
s.graph = 0;
s.material_preview = crate::MaterialPreview::for_graph(&s.pkg, 0);
s.clear_preview_results();
s.selection.clear();
s.annotation_selection = None;
s.view2d.node = None;
@@ -130,6 +134,7 @@ pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option<Strin
let (manifest, source) = materialcraft_formats::material::read_material(bytes)?;
replace_package(session, materialcraft_formats::sbs::read_sbs(&source, "source.sbs", &|_| None)?.pkg, None);
session.graph = session.pkg.graph_by_name(&manifest.graph).map_or(0, |(index, _)| index);
session.open_material_preview();
return Ok(());
}
+15 -7
View File
@@ -1,23 +1,31 @@
use crate::commands::{CommandSpec, bad, has_graph};
use crate::{Result, Session, cmd};
use crate::{FunctionGraphTarget, Result, Session, cmd};
use materialcraft_core::FunctionGraph;
use serde_json::{Value as Json, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!("graph.function.set", "Edit Function Graph", [], None, "{function} replaces the current function graph", has_graph, set)]
vec![cmd!(
"graph.function.set",
"Edit Function Graph",
[],
None,
"{function, target?: {kind: graph|parameter|dynamic|pattern, node?, owner?, parameter?}} replaces a function graph",
has_graph,
set
)]
}
fn set(session: &mut Session, parameters: &Json) -> Result<Json> {
if session.graph()?.function.is_none() {
return Err(bad("graph.function.set", "the current graph is not a Function Graph"));
}
let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"})))
.map_err(|error| bad("graph.function.set", error.to_string()))?;
target.current(session)?;
let graph: FunctionGraph =
serde_json::from_value(parameters.get("function").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.function.set", error.to_string()))?;
materialcraft_nodes::function::node_types(&graph).map_err(|error| bad("graph.function.set", error))?;
crate::graph_validation::function(&graph).map_err(|error| bad("graph.function.set", error))?;
session.edit("Edit Function Graph", |session| {
session.graph_mut()?.function = Some(graph);
target.replace(session, graph)?;
Ok(json!({}))
})
}
+105
View File
@@ -0,0 +1,105 @@
use materialcraft_core::{FunctionGraph, FunctionNode, Value};
use serde::{Deserialize, Serialize};
use serde_json::{Value as Json, json};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "camelCase")]
pub enum FunctionEdit {
Add {
operation: String,
at: [f32; 2],
#[serde(default)]
snap: bool,
},
Move {
ids: Vec<u32>,
by: [f32; 2],
#[serde(default)]
snap: bool,
},
Connect {
from: u32,
to: u32,
input: usize,
},
Value {
id: u32,
value: Value,
},
Output {
id: u32,
},
}
impl FunctionEdit {
pub(crate) fn apply(&self, graph: &mut FunctionGraph) -> Result<Json, String> {
match self {
Self::Add { operation, at, snap } => {
if graph.nodes.len() >= 4096 {
return Err("the function exceeds the 4096-node limit".into());
}
let definition = materialcraft_nodes::function::definition(operation).ok_or("unknown function operation")?;
let id = graph.next_id();
graph.nodes.push(FunctionNode {
id,
type_code: 0,
op: operation.clone(),
inputs: vec![None; definition.inputs.len()],
value: materialcraft_nodes::function::default_value(operation),
pos: crate::graph_grid::snap_position(*at, *snap),
});
if graph.output.is_none() {
graph.output = Some(id);
}
return Ok(json!({"id": id}));
}
Self::Move { ids, by, snap } => {
for id in ids {
if graph.node(*id).is_none() {
return Err(format!("no function node {id}"));
}
}
for node in &mut graph.nodes {
if ids.contains(&node.id) {
node.pos = crate::graph_grid::translate(node.pos, *by, *snap);
}
}
}
Self::Connect { from, to, input } => {
if from == to || graph.node(*from).is_none() {
return Err("invalid function source".into());
}
let node = graph.nodes.iter_mut().find(|node| node.id == *to).ok_or("missing function destination")?;
let count = materialcraft_nodes::function::definition(&node.op).map_or(0, |definition| definition.inputs.len());
if *input >= count {
return Err("invalid function input".into());
}
node.inputs.resize(count, None);
if let Some(slot) = node.inputs.get_mut(*input) {
*slot = Some(*from);
}
}
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() {
return Err("the operation has no editable value".into());
}
node.value = Some(value.clone());
}
Self::Output { id } => {
if graph.node(*id).is_none() {
return Err("missing output node".into());
}
graph.output = Some(*id);
}
}
Ok(Json::Null)
}
pub(crate) fn merge_key(&self) -> Option<String> {
match self {
Self::Value { id, .. } => Some(format!("value:{id}")),
_ => None,
}
}
}
@@ -0,0 +1,80 @@
use crate::{Result, Session, commands::bad};
use materialcraft_core::{FunctionGraph, NodeId, Value};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum FunctionGraphTarget {
#[default]
Graph,
Parameter {
node: NodeId,
parameter: String,
},
Dynamic {
node: NodeId,
parameter: String,
},
Pattern {
owner: NodeId,
node: u32,
parameter: String,
},
}
impl FunctionGraphTarget {
pub fn available_operations(&self, session: &Session) -> impl Iterator<Item = &'static materialcraft_nodes::function::FunctionDefinition> + 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"));
materialcraft_nodes::function::FUNCTIONS.iter().filter(move |operation| !value_processor || !matches!(operation.id, "samplelum" | "samplecol"))
}
pub fn current<'a>(&self, session: &'a Session) -> Result<&'a FunctionGraph> {
let document = session.graph()?;
let value = match self {
Self::Graph => return document.function.as_ref().ok_or_else(|| bad("graph.function.edit", "no Function Graph is open")),
Self::Dynamic { node, parameter } => {
return document.node(*node)?.functions.get(parameter).ok_or_else(|| bad("graph.function.edit", "missing parameter function"));
}
Self::Parameter { node, parameter } => {
let node = document.node(*node)?;
node.params.get(parameter).or_else(|| materialcraft_nodes::find(&node.def)?.param(parameter).map(|parameter| &parameter.default))
}
Self::Pattern { owner, node, parameter } => {
let Some(Value::PatternGraph(graph)) = document.node(*owner)?.params.get("pattern") else {
return Err(bad("graph.function.edit", "missing FX-Map graph"));
};
graph.nodes.iter().find(|candidate| candidate.id == *node).and_then(|node| node.parameters.get(parameter))
}
};
match value {
Some(Value::Function(graph)) => Ok(graph),
_ => Err(bad("graph.function.edit", "missing function")),
}
}
pub(crate) fn replace(&self, session: &mut Session, function: FunctionGraph) -> Result<()> {
self.current(session)?;
let document = session.graph_mut()?;
match self {
Self::Graph => document.function = Some(function),
Self::Dynamic { node, parameter } => {
document.node_mut(*node)?.functions.insert(parameter.clone(), function);
}
Self::Parameter { node, parameter } => {
document.node_mut(*node)?.params.insert(parameter.clone(), Value::Function(Box::new(function)));
}
Self::Pattern { owner, node, parameter } => {
let Some(Value::PatternGraph(graph)) = document.node_mut(*owner)?.params.get_mut("pattern") else {
return Err(bad("graph.function.edit", "missing FX-Map graph"));
};
let node = graph.nodes.iter_mut().find(|candidate| candidate.id == *node).ok_or_else(|| bad("graph.function.edit", "missing FX-Map node"))?;
node.parameters.insert(parameter.clone(), Value::Function(Box::new(function)));
}
}
Ok(())
}
}
+6 -37
View File
@@ -51,7 +51,6 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
cmd!("graph.select", "Select nodes", [], None, "{ids, add?: bool}", has_graph, select),
cmd!("graph.selectUpstream", "Select upstream nodes", [], None, "{ids?}", has_selection, |s, p| select_stream(s, p, true)),
cmd!("graph.selectDownstream", "Select downstream nodes", [], None, "{ids?}", has_selection, |s, p| select_stream(s, p, false)),
cmd!("graph.align", "Align nodes", [], None, "{mode: left|right|top|bottom|hcenter|vcenter|hdistribute|vdistribute, ids?}", has_selection, align),
cmd!(
"graph.createFromSelection",
"Create graph from selection",
@@ -79,6 +78,7 @@ fn graph_index(s: &Session, p: &J) -> Result<usize> {
fn open(s: &mut Session, p: &J) -> Result<J> {
let i = graph_index(s, p)?;
s.graph = i;
s.open_material_preview();
s.selection.clear();
s.annotation_selection = None;
s.view2d.node = None;
@@ -110,7 +110,10 @@ fn delete(s: &mut Session, p: &J) -> Result<J> {
let i = graph_index(s, p)?;
s.edit("Delete graph", |s| {
s.pkg.graphs.remove(i);
s.material_preview.remove_graph(i);
s.clear_preview_results();
s.clipboard = None;
s.embedded_clipboard = None;
s.graph = s.graph.min(s.pkg.graphs.len().saturating_sub(1));
s.selection.clear();
s.annotation_selection = None;
@@ -126,6 +129,7 @@ fn duplicate(s: &mut Session, p: &J) -> Result<J> {
g.name = s.pkg.unique_graph_name(&g.name);
s.pkg.graphs.push(g);
s.graph = s.pkg.graphs.len() - 1;
s.open_material_preview();
s.selection.clear();
s.annotation_selection = None;
Ok(json!({"graph": s.graph}))
@@ -350,41 +354,6 @@ fn select_stream(s: &mut Session, p: &J, up: bool) -> Result<J> {
Ok(json!({"selected": s.selection.len()}))
}
fn align(s: &mut Session, p: &J) -> Result<J> {
let ids = ids_param(s, "graph.align", p)?;
let mode = strp(p, "mode").unwrap_or("left").to_string();
s.edit("Align nodes", |s| {
let g = s.graph_mut()?;
let mut nodes: Vec<&mut materialcraft_core::Node> = g.nodes.iter_mut().filter(|n| ids.contains(&n.id)).collect();
if nodes.len() < 2 {
return Ok(J::Null);
}
let xs: Vec<f32> = nodes.iter().map(|n| n.pos[0]).collect();
let ys: Vec<f32> = nodes.iter().map(|n| n.pos[1]).collect();
let (minx, maxx) = (xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max));
let (miny, maxy) = (ys.iter().copied().fold(f32::MAX, f32::min), ys.iter().copied().fold(f32::MIN, f32::max));
match mode.as_str() {
"left" => nodes.iter_mut().for_each(|n| n.pos[0] = minx),
"right" => nodes.iter_mut().for_each(|n| n.pos[0] = maxx),
"top" => nodes.iter_mut().for_each(|n| n.pos[1] = miny),
"bottom" => nodes.iter_mut().for_each(|n| n.pos[1] = maxy),
"hcenter" => nodes.iter_mut().for_each(|n| n.pos[0] = (minx + maxx) * 0.5),
"vcenter" => nodes.iter_mut().for_each(|n| n.pos[1] = (miny + maxy) * 0.5),
"hdistribute" | "vdistribute" => {
let k = usize::from(mode == "vdistribute");
nodes.sort_by(|a, b| a.pos[k].total_cmp(&b.pos[k]));
let (lo, hi) = if k == 0 { (minx, maxx) } else { (miny, maxy) };
let step = (hi - lo) / (nodes.len() - 1) as f32;
for (i, n) in nodes.iter_mut().enumerate() {
n.pos[k] = lo + step * i as f32;
}
}
other => return Err(bad("graph.align", format!("unknown mode `{other}`"))),
}
Ok(J::Null)
})
}
fn from_selection(s: &mut Session, p: &J) -> Result<J> {
let ids = ids_param(s, "graph.createFromSelection", p)?;
let base = strp(p, "name").unwrap_or("Sub_graph").to_string();
@@ -415,7 +384,7 @@ fn from_selection(s: &mut Session, p: &J) -> Result<J> {
}
let ident = format!("output_{}", outputs.len() + 1);
let id = sub.add_node("output", [rect[0] + rect[2] + 80.0, rect[1] + outputs.len() as f32 * 120.0]);
let usage = materialcraft_nodes::atomic::USAGE_IDS.len() as u32 - 1;
let usage = materialcraft_core::ComponentUsage::ANY_INDEX;
sub.node_mut(id)?.params.extend([("identifier".to_string(), Value::Text(ident.clone())), ("usage".to_string(), Value::Enum(usage))]);
sub.connect(c.from, &c.from_port, id, "input")?;
outputs.push((c.from, c.from_port.clone(), ident));
@@ -0,0 +1,17 @@
/// The data access needed by shared function and pattern editing operations
pub trait EditableGraph {
type Node: Clone;
const LINKS_ARE_INPUTS: bool;
const RELINK: bool;
fn nodes(&self) -> &[Self::Node];
fn nodes_mut(&mut self) -> &mut Vec<Self::Node>;
fn id(node: &Self::Node) -> u32;
fn position(node: &mut Self::Node) -> &mut [f32; 2];
fn links(node: &Self::Node) -> &[Option<u32>];
fn links_mut(node: &mut Self::Node) -> &mut [Option<u32>];
fn result(&mut self) -> &mut Option<u32>;
fn check_capacity(&self, additional: usize) -> Result<(), String>;
fn insert(&mut self, node: Self::Node) -> Result<u32, String>;
}
@@ -0,0 +1,45 @@
use super::EditableGraph;
use materialcraft_core::{FunctionGraph, FunctionNode};
impl EditableGraph for FunctionGraph {
type Node = FunctionNode;
const LINKS_ARE_INPUTS: bool = true;
const RELINK: bool = true;
fn nodes(&self) -> &[FunctionNode] {
&self.nodes
}
fn nodes_mut(&mut self) -> &mut Vec<FunctionNode> {
&mut self.nodes
}
fn id(node: &FunctionNode) -> u32 {
node.id
}
fn position(node: &mut FunctionNode) -> &mut [f32; 2] {
&mut node.pos
}
fn links(node: &FunctionNode) -> &[Option<u32>] {
&node.inputs
}
fn links_mut(node: &mut FunctionNode) -> &mut [Option<u32>] {
&mut node.inputs
}
fn result(&mut self) -> &mut Option<u32> {
&mut self.output
}
fn check_capacity(&self, additional: usize) -> Result<(), String> {
if self.nodes.len().saturating_add(additional) > 4096 {
return Err("function exceeds the 4096-node limit".into());
}
Ok(())
}
fn insert(&mut self, mut node: FunctionNode) -> Result<u32, String> {
let id = self.next_id();
node.id = id;
self.nodes.push(node);
Ok(id)
}
}
+9
View File
@@ -0,0 +1,9 @@
//! Editing rules shared by Function Graphs and FX-Map graphs
mod editable_graph;
mod function_graph;
mod pattern_graph;
mod selection;
pub use editable_graph::EditableGraph;
pub use selection::{enabled, read, remove, run};
@@ -0,0 +1,47 @@
use super::EditableGraph;
use materialcraft_core::{PatternGraph, PatternNode};
impl EditableGraph for PatternGraph {
type Node = PatternNode;
const LINKS_ARE_INPUTS: bool = false;
const RELINK: bool = false;
fn nodes(&self) -> &[PatternNode] {
&self.nodes
}
fn nodes_mut(&mut self) -> &mut Vec<PatternNode> {
&mut self.nodes
}
fn id(node: &PatternNode) -> u32 {
node.id
}
fn position(node: &mut PatternNode) -> &mut [f32; 2] {
&mut node.position
}
fn links(node: &PatternNode) -> &[Option<u32>] {
&node.children
}
fn links_mut(node: &mut PatternNode) -> &mut [Option<u32>] {
&mut node.children
}
fn result(&mut self) -> &mut Option<u32> {
&mut self.root
}
fn check_capacity(&self, additional: usize) -> Result<(), String> {
if self.nodes.len().saturating_add(additional) > 4096 {
return Err("pattern graph exceeds the 4096-node limit".into());
}
Ok(())
}
fn insert(&mut self, mut node: PatternNode) -> Result<u32, String> {
let id = self.add(node.kind)?;
node.id = id;
if let Some(destination) = self.nodes.last_mut() {
*destination = node;
}
Ok(id)
}
}
+127
View File
@@ -0,0 +1,127 @@
use super::EditableGraph;
use std::collections::{BTreeMap, BTreeSet};
pub fn enabled<G: EditableGraph>(selection: &[u32], clipboard: &[G::Node], command: &str) -> Option<bool> {
Some(match command {
"graph.select" | "edit.selectAll" | "edit.selectNone" => true,
"edit.paste" | "edit.pasteWithoutLinks" => !clipboard.is_empty(),
"edit.copy" | "edit.cut" | "edit.delete" | "edit.duplicate" | "edit.duplicateWithoutLinks" | "graph.selectUpstream" | "graph.selectDownstream" => {
!selection.is_empty()
}
"edit.deleteRelink" => G::RELINK && !selection.is_empty(),
"graph.node.disable" => false,
_ => return None,
})
}
pub fn run<G: EditableGraph>(
graph: &mut G,
selection: &mut Vec<u32>,
clipboard: &mut Vec<G::Node>,
command: &str,
at: [f32; 2],
snap: bool,
) -> Result<bool, String> {
if read(graph, selection, clipboard, command) {
return Ok(false);
}
match command {
"edit.cut" => {
*clipboard = selected::<G>(graph, selection);
return Ok(remove(graph, selection, false));
}
"edit.delete" | "edit.deleteRelink" => return Ok(remove(graph, selection, G::RELINK && command == "edit.deleteRelink")),
"edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => {
let duplicate = command.starts_with("edit.duplicate");
let mut nodes = if duplicate { selected::<G>(graph, selection) } else { clipboard.clone() };
graph.check_capacity(nodes.len())?;
let anchor = nodes.first_mut().map_or([0.0; 2], |node| *G::position(node));
let offset = if duplicate { [32.0; 2] } else { [at[0] - anchor[0], at[1] - anchor[1]] };
let present: BTreeSet<_> = graph.nodes().iter().map(G::id).collect();
let mut ids = BTreeMap::new();
for mut node in nodes {
let original = G::id(&node);
let position = G::position(&mut node);
*position = crate::graph_grid::translate(*position, offset, snap);
ids.insert(original, graph.insert(node)?);
}
let inserted: BTreeSet<_> = ids.values().copied().collect();
for node in graph.nodes_mut().iter_mut().filter(|node| inserted.contains(&G::id(node))) {
for link in G::links_mut(node) {
*link = link.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks") && present.contains(&id)).then_some(id)));
}
}
*selection = ids.values().copied().collect();
return Ok(!ids.is_empty());
}
_ => {}
}
Ok(false)
}
fn selected<G: EditableGraph>(graph: &G, selection: &[u32]) -> Vec<G::Node> {
let selection: BTreeSet<_> = selection.iter().copied().collect();
graph.nodes().iter().filter(|node| selection.contains(&G::id(node))).cloned().collect()
}
pub fn remove<G: EditableGraph>(graph: &mut G, selection: &mut Vec<u32>, relink: bool) -> bool {
let selection_set: BTreeSet<_> = selection.iter().copied().collect();
let replacements: BTreeMap<_, _> = graph
.nodes()
.iter()
.filter(|node| selection_set.contains(&G::id(node)))
.map(|node| (G::id(node), if relink { G::links(node).first().copied().flatten() } else { None }))
.collect();
graph.nodes_mut().retain(|node| !selection_set.contains(&G::id(node)));
for node in graph.nodes_mut() {
for link in G::links_mut(node) {
let mut seen = BTreeSet::new();
while let Some(id) = *link {
let Some(replacement) = replacements.get(&id) else { break };
if !seen.insert(id) {
*link = None;
break;
}
*link = *replacement;
}
}
}
if graph.result().is_some_and(|id| selection_set.contains(&id)) {
*graph.result() = None;
}
selection.clear();
!replacements.is_empty()
}
/// Apply selection and copy actions without cloning or mutating the graph
pub fn read<G: EditableGraph>(graph: &G, selection: &mut Vec<u32>, clipboard: &mut Vec<G::Node>, command: &str) -> bool {
match command {
"edit.selectAll" => *selection = graph.nodes().iter().map(G::id).collect(),
"edit.selectNone" => selection.clear(),
"graph.select" => {}
"edit.copy" => *clipboard = selected::<G>(graph, selection),
"graph.selectUpstream" | "graph.selectDownstream" => {
let follow_links = (command == "graph.selectUpstream") == G::LINKS_ARE_INPUTS;
let mut neighbors: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
for node in graph.nodes() {
for link in G::links(node).iter().flatten() {
let (from, to) = if follow_links { (G::id(node), *link) } else { (*link, G::id(node)) };
neighbors.entry(from).or_default().push(to);
}
}
let mut visited = BTreeSet::new();
let mut pending = selection.clone();
while let Some(id) = pending.pop() {
if visited.insert(id)
&& let Some(next) = neighbors.get(&id)
{
pending.extend(next);
}
}
*selection = visited.into_iter().collect();
}
_ => return false,
}
true
}
+5
View File
@@ -6,3 +6,8 @@ pub fn snap_position(position: [f32; 2], enabled: bool) -> [f32; 2] {
if enabled { (coordinate / GRID_SPACING).round() * GRID_SPACING } else { coordinate }
})
}
/// Apply the same movement and snapping rule during a drag preview and its commit
pub fn translate(position: [f32; 2], offset: [f32; 2], snap: bool) -> [f32; 2] {
snap_position([position[0] + offset[0], position[1] + offset[1]], snap)
}
+50
View File
@@ -0,0 +1,50 @@
use materialcraft_core::{FunctionGraph, PatternGraph, Value};
fn function_structure(graph: &FunctionGraph) -> Result<(), String> {
materialcraft_nodes::function::node_types(graph)?;
if graph.nodes.iter().any(|node| node.pos.iter().any(|coordinate| !coordinate.is_finite())) {
return Err("function node positions must be finite".into());
}
Ok(())
}
pub(crate) fn pattern(graph: &PatternGraph) -> Result<(), String> {
pattern_structure(graph)?;
values(graph.nodes.iter().flat_map(|node| node.parameters.values()))
}
pub(crate) fn function(graph: &FunctionGraph) -> Result<(), String> {
function_structure(graph)?;
values(graph.nodes.iter().filter_map(|node| node.value.as_ref()))
}
pub(crate) fn value(value: &Value) -> Result<(), String> {
values(std::iter::once(value))
}
fn values<'a>(values: impl Iterator<Item = &'a Value>) -> Result<(), String> {
// Nested graph values are checked without recursive traversal
let mut pending: Vec<_> = values.collect();
while let Some(value) = pending.pop() {
match value {
Value::Function(graph) => {
function_structure(graph)?;
pending.extend(graph.nodes.iter().filter_map(|node| node.value.as_ref()));
}
Value::PatternGraph(graph) => {
pattern_structure(graph)?;
pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values()));
}
_ => {}
}
}
Ok(())
}
fn pattern_structure(graph: &PatternGraph) -> Result<(), String> {
graph.validate()?;
if graph.nodes.iter().any(|node| node.position.iter().any(|coordinate| !coordinate.is_finite())) {
return Err("pattern node positions must be finite".into());
}
Ok(())
}
+7
View File
@@ -61,6 +61,13 @@ pub fn session(s: &Session, graph: Option<usize>) -> J {
"selection": s.selection.iter().map(|i| i.0).collect::<Vec<_>>(),
"view2d": s.view2d,
"view3d": s.view3d,
"material3d": {
"assignments": s.material_preview,
"channels": s.material_preview.sources(&s.pkg).into_iter().map(|(channel, source)| {
let image = s.material_image(&source);
json!({"channel": channel, "source": source, "size": image.map(|image| [image.w, image.h]), "mean": image.map(|image| image.mean())})
}).collect::<Vec<_>>(),
},
"previewSize": s.preview_size,
"camera": s.camera,
"cookMs": s.cooked.ms,
+24
View File
@@ -1,10 +1,26 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod material_preview;
mod material_preview_commands;
mod material_source;
mod preview_cook;
pub use material_preview::MaterialPreview;
pub use material_source::MaterialSource;
pub use preview_cook::PreviewCook;
mod alignment_commands;
mod embedded_clipboard;
mod graph_validation;
pub mod selection_commands;
mod selection_target;
pub use embedded_clipboard::EmbeddedClipboard;
pub use selection_target::SelectionTarget;
pub mod commands;
pub mod edit_cmds;
pub mod file_cmds;
pub mod graph_cmds;
pub mod graph_edit;
pub mod graph_grid;
pub mod inspect;
pub mod material_cmds;
@@ -59,3 +75,11 @@ mod pattern_graph_commands;
mod snapshot;
pub use annotation_selection::AnnotationSelection;
pub use frame_contents::FrameContents;
mod embedded_edit_commands;
mod function_edit;
mod function_graph_target;
mod pattern_edit;
pub use function_edit::FunctionEdit;
pub use function_graph_target::FunctionGraphTarget;
pub use pattern_edit::PatternEdit;
+9 -2
View File
@@ -3,6 +3,7 @@ use std::collections::BTreeMap;
use serde_json::{Value as J, json};
use materialcraft_core::ComponentUsage;
use materialcraft_core::Graph;
#[cfg(any(test, not(target_arch = "wasm32")))]
use materialcraft_core::Value;
@@ -10,7 +11,6 @@ use materialcraft_formats::material::{FORMAT, ImageInput, Manifest, MapEntry, Pa
use materialcraft_formats::{Depth, encode};
#[cfg(test)]
use materialcraft_image::Image;
use materialcraft_nodes::atomic::USAGE_IDS;
#[cfg(not(target_arch = "wasm32"))]
use crate::commands::u64p;
@@ -83,7 +83,14 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result<Vec
size = [img.w, img.h];
}
if entries.is_empty() {
return Err(bad("file.exportMaterial", format!("graph `{}` has no outputs with a material usage ({})", g.name, USAGE_IDS.join(", "))));
return Err(bad(
"file.exportMaterial",
format!(
"graph `{}` has no outputs with a material usage ({})",
g.name,
ComponentUsage::ALL.iter().filter(|usage| **usage != ComponentUsage::ANY).map(|usage| usage.id).collect::<Vec<_>>().join(", ")
),
));
}
let manifest = Manifest {
format: FORMAT.into(),
+93
View File
@@ -0,0 +1,93 @@
use std::collections::{BTreeMap, BTreeSet};
use std::hash::{Hash, Hasher};
use materialcraft_core::{MaterialChannel, Package};
use materialcraft_image::Image;
use serde::{Deserialize, Serialize};
use crate::{MaterialSource, Session};
/// Automatic graph outputs with explicit channel overrides
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MaterialPreview {
pub graph: Option<usize>,
pub channels: BTreeMap<MaterialChannel, MaterialSource>,
}
impl MaterialPreview {
pub fn for_graph(package: &Package, graph: usize) -> Self {
Self { graph: package.graphs.get(graph).filter(|graph| graph.function.is_none()).map(|_| graph), channels: BTreeMap::new() }
}
pub fn sources(&self, package: &Package) -> BTreeMap<MaterialChannel, MaterialSource> {
let mut sources = BTreeMap::new();
if let Some(index) = self.graph
&& let Some(graph) = package.graphs.get(index)
{
for node in graph.nodes.iter().filter(|node| node.def == "output") {
let source = MaterialSource { graph: index, node: node.id, port: "output".into() };
if let Some(channel) = MaterialChannel::from_id(materialcraft_eval::output_usage(node))
&& source.is_image(package)
{
sources.entry(channel).or_insert(source);
}
}
}
sources.extend(self.channels.clone());
sources
}
pub fn graphs(&self) -> BTreeSet<usize> {
self.graph.into_iter().chain(self.channels.values().map(|source| source.graph)).collect()
}
pub(crate) fn remove_graph(&mut self, graph: usize) {
self.graph = self.graph.filter(|index| *index != graph).map(|index| if index > graph { index - 1 } else { index });
self.channels.retain(|_, source| source.graph != graph);
for source in self.channels.values_mut() {
if source.graph > graph {
source.graph -= 1;
}
}
}
}
impl Session {
/// Show a material graph on open, retaining the material while editing functions
pub(crate) fn open_material_preview(&mut self) {
if self.graph().is_ok_and(|graph| graph.function.is_none()) {
self.material_preview = MaterialPreview::for_graph(&self.pkg, self.graph);
}
}
pub(crate) fn clear_preview_results(&mut self) {
self.cooked_graph = None;
self.material_cooked.clear();
}
pub fn material_image(&self, source: &MaterialSource) -> Option<&Image> {
let port = source.port_index(&self.pkg)?;
let cooked = self.preview_cooked(source.graph)?;
cooked.image(source.node, port)
}
fn preview_cooked(&self, graph: usize) -> Option<&materialcraft_eval::Cooked> {
if self.cooked_graph == Some(graph) { Some(&self.cooked) } else { self.material_cooked.get(&graph) }
}
/// Assigned image channels, including sources outside the open graph
pub fn material_maps(&self) -> Vec<(&'static str, &Image)> {
self.material_preview.sources(&self.pkg).into_iter().filter_map(|(channel, source)| Some((channel.id(), self.material_image(&source)?))).collect()
}
/// Assignment and cooked content both invalidate the rendered preview
pub fn material_key(&self) -> u64 {
let mut hash = std::collections::hash_map::DefaultHasher::new();
for (channel, source) in self.material_preview.sources(&self.pkg) {
let result = self.preview_cooked(source.graph).and_then(|cooked| cooked.nodes.get(&source.node));
let port = source.port_index(&self.pkg);
(channel, &source, port, result.map(|result| result.key)).hash(&mut hash);
}
hash.finish()
}
}
@@ -0,0 +1,100 @@
use materialcraft_core::{MaterialChannel, NodeId};
use serde_json::{Value, json};
use crate::commands::{CommandSpec, always, bad, boolp, has_graph, u64p};
use crate::{MaterialPreview, MaterialSource, Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"view.3d.outputs",
"View outputs in 3D view",
["Tools"],
None,
"{graph?: index or name, reset?: bool} assigns image outputs by usage; reset clears other assignments without moving the camera",
has_graph,
outputs
),
cmd!(
"view.3d.assign",
"View output in 3D view",
[],
None,
"{graph?: index or name, node?: selected node, port?: index or identifier, channel: baseColor|normal|roughness|metallic|height|ambientOcclusion|emissive|opacity, reset?: bool}",
has_graph,
assign
),
cmd!("view.3d.clear", "Clear material assignments", [], None, "{} clears the material without resetting the scene or camera", always, |session, _| {
session.material_preview = MaterialPreview::default();
session.dirty = true;
Ok(Value::Null)
}),
]
}
fn graph_index(session: &Session, parameters: &Value, command: &str) -> Result<usize> {
let graph = match parameters.get("graph") {
None => session.graph,
Some(Value::String(name)) => session.pkg.graph_by_name(name).map(|(index, _)| index).ok_or_else(|| bad(command, format!("no graph `{name}`")))?,
Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad(command, "graph must be an index or name"))?,
};
if session.pkg.graph(graph)?.function.is_some() {
return Err(bad(command, "a Function Graph has no material image outputs"));
}
Ok(graph)
}
fn outputs(session: &mut Session, parameters: &Value) -> Result<Value> {
let graph = graph_index(session, parameters, "view.3d.outputs")?;
let material = MaterialPreview::for_graph(&session.pkg, graph);
let sources = material.sources(&session.pkg);
if sources.is_empty() {
return Err(bad("view.3d.outputs", "no image outputs have supported material usages; assign an image to a channel with View in 3D view"));
}
if boolp(parameters, "reset") == Some(true) {
session.material_preview = material;
} else {
session.material_preview.channels.extend(sources);
}
session.dirty = true;
Ok(json!(session.material_preview))
}
fn assign(session: &mut Session, parameters: &Value) -> Result<Value> {
const COMMAND: &str = "view.3d.assign";
let graph = graph_index(session, parameters, COMMAND)?;
let channel = parameters
.get("channel")
.and_then(Value::as_str)
.and_then(MaterialChannel::from_id)
.ok_or_else(|| bad(COMMAND, "choose a supported material channel"))?;
let node = match parameters.get("node") {
Some(_) => NodeId(u64p(parameters, "node").ok_or_else(|| bad(COMMAND, "node must be an ID"))?),
None if graph == session.graph => *session.selection.last().ok_or_else(|| bad(COMMAND, "select a node or supply its ID"))?,
None => return Err(bad(COMMAND, "node is required for another graph")),
};
let source_graph = session.pkg.graph(graph)?;
let source_node = source_graph.node(node)?;
let ports = if source_node.def == "output" {
vec!["output".to_string()]
} else {
materialcraft_eval::ports(&session.pkg, source_graph, source_node).1.into_iter().map(|port| port.id).collect()
};
let port = match parameters.get("port") {
None => ports.first(),
Some(Value::String(name)) => ports.iter().find(|port| *port == name),
Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).and_then(|index| ports.get(index)),
}
.cloned()
.ok_or_else(|| bad(COMMAND, "no such image output port"))?;
let source = MaterialSource { graph, node, port };
if !source.is_image(&session.pkg) {
return Err(bad(COMMAND, "the 3D view needs an image, not a scalar, vector or unresolved output"));
}
if boolp(parameters, "reset") == Some(true) {
session.material_preview = MaterialPreview::default();
}
session.material_preview.channels.insert(channel, source);
session.dirty = true;
Ok(json!(session.material_preview))
}
+62
View File
@@ -0,0 +1,62 @@
use materialcraft_core::{NodeId, Package};
use serde::{Deserialize, Serialize};
/// An image assigned to a material channel, independent of editor selection
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MaterialSource {
pub graph: usize,
pub node: NodeId,
pub port: String,
}
impl MaterialSource {
pub fn is_image(&self, package: &Package) -> bool {
let mut graph_index = self.graph;
let mut node_id = self.node;
let mut port = self.port.clone();
let mut visited = std::collections::BTreeSet::new();
loop {
if !visited.insert((graph_index, node_id, port.clone())) {
return false;
}
let Some(graph) = package.graphs.get(graph_index) else { return false };
let Ok(node) = graph.node(node_id) else { return false };
match node.def.as_str() {
"output" | "dot" => {
let Some(connection) = graph.input_of(node_id, "input") else { return true };
node_id = connection.from;
port = connection.from_port.clone();
}
"graph_instance" => {
let Some((index, graph)) = materialcraft_eval::instance_graph(package, node) else { return false };
let Some(output) = graph.nodes.iter().find(|node| node.def == "output" && materialcraft_eval::identifier(node) == port) else {
return false;
};
graph_index = index;
node_id = output.id;
port = "output".into();
}
_ => {
return materialcraft_eval::ports(package, graph, node)
.1
.iter()
.any(|output| output.id == port && output.kind != materialcraft_nodes::PortKind::Value)
&& materialcraft_nodes::output_value_type(graph, node_id).is_ok_and(|value| value.is_none());
}
}
}
}
pub fn port_index(&self, package: &Package) -> Option<usize> {
let graph = package.graphs.get(self.graph)?;
let node = graph.node(self.node).ok()?;
if node.def == "output" {
return (self.port == "output").then_some(0);
}
materialcraft_eval::ports(package, graph, node).1.iter().position(|port| port.id == self.port)
}
}
+4 -7
View File
@@ -83,6 +83,7 @@ fn add(s: &mut Session, p: &J) -> Result<J> {
pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.add", format!("`{k}` takes a {}", pd.default.type_name())))?
};
crate::graph_validation::value(&v).map_err(|error| bad("graph.node.add", error))?;
params.push((k.clone(), v));
}
}
@@ -136,7 +137,7 @@ fn move_nodes(s: &mut Session, p: &J) -> Result<J> {
if let Some(t) = to {
n.pos = snap_position(t, snap);
} else if let Some(d) = by {
n.pos = snap_position([n.pos[0] + d[0], n.pos[1] + d[1]], snap);
n.pos = crate::graph_grid::translate(n.pos, d, snap);
}
}
Ok(J::Null)
@@ -198,9 +199,7 @@ fn set_param(s: &mut Session, p: &J) -> Result<J> {
v
};
if let Value::PatternGraph(graph) = &value {
graph.validate().map_err(|error| bad("graph.node.param", error))?;
}
crate::graph_validation::value(&value).map_err(|error| bad("graph.node.param", error))?;
s.edit_merged(&format!("param:{}:{param}", id.0), "Set parameter", |s| {
s.graph_mut()?.node_mut(id)?.params.insert(param.clone(), value);
@@ -315,9 +314,7 @@ fn set_function(s: &mut Session, p: &J) -> Result<J> {
},
};
if f.nodes.len() > 4096 {
return Err(bad("graph.node.function", "the function is too large"));
}
crate::graph_validation::function(&f).map_err(|error| bad("graph.node.function", error))?;
s.edit_merged(&format!("fn:{}:{param}", id.0), "Set parameter function", |s| {
s.graph_mut()?.node_mut(id)?.functions.insert(param.clone(), f);
Ok(J::Null)
+18 -22
View File
@@ -1,8 +1,7 @@
use materialcraft_core::NodeId;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, bad};
use crate::{Result, Session, cmd};
use crate::{FunctionGraphTarget, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
@@ -10,32 +9,29 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"Edit node graph",
["Edit"],
Some("Ctrl+E"),
"{} resolves the selected FX-Map graph to {node, parameter}; UI invocation opens its editor",
enabled,
edit
"{} resolves the selected FX-Map, processor or local graph instance to {kind, node, parameter?, graph?}; UI invocation opens it in the graph panel",
|session| resolve(session).map(|_| ()),
|session, _| resolve(session).map_err(|error| bad("graph.node.edit", error))
)]
}
fn selected_node(session: &Session) -> std::result::Result<NodeId, String> {
fn resolve(session: &Session) -> std::result::Result<Value, String> {
if session.annotation_selection.is_some() {
return Err("select an FX-Map node".into());
return Err("select a node with an editable graph".into());
}
let id = session.selection.last().copied().ok_or("select an FX-Map node")?;
let id = session.selection.last().copied().ok_or("select a node with an editable graph")?;
let graph = session.graph().map_err(|error| error.to_string())?;
let node = graph.node(id).map_err(|error| error.to_string())?;
if node.def != "fx_map" {
return Err("the selected node has no editable FX-Map graph".into());
match node.def.as_str() {
"fx_map" => Ok(json!({"kind": "pattern", "node": id, "parameter": "pattern"})),
"pixel_processor" | "value_processor" => {
FunctionGraphTarget::Parameter { node: id, parameter: "function".into() }.current(session).map_err(|error| error.to_string())?;
Ok(json!({"kind": "function", "node": id, "parameter": "function"}))
}
"graph_instance" => {
let (index, _) = materialcraft_eval::instance_graph(&session.pkg, node).ok_or("the referenced graph is missing")?;
Ok(json!({"kind": "graph", "node": id, "graph": index}))
}
_ => Err("the selected node has no editable graph".into()),
}
Ok(id)
}
fn enabled(session: &Session) -> std::result::Result<(), String> {
selected_node(session).map(|_| ())
}
fn edit(session: &mut Session, _: &Value) -> Result<Value> {
let node = selected_node(session).map_err(|error| bad("graph.node.edit", error))?;
Ok(json!({"node": node.0, "parameter": "pattern"}))
}
+114
View File
@@ -0,0 +1,114 @@
use materialcraft_core::{PatternGraph, PatternNodeKind, Value};
use serde::{Deserialize, Serialize};
use serde_json::{Value as Json, json};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "camelCase")]
pub enum PatternEdit {
Add {
kind: PatternNodeKind,
at: [f32; 2],
#[serde(default)]
snap: bool,
},
Move {
ids: Vec<u32>,
by: [f32; 2],
#[serde(default)]
snap: bool,
},
Connect {
parent: u32,
slot: usize,
child: u32,
},
Disconnect {
node: u32,
slot: Option<usize>,
},
Root {
id: u32,
},
Value {
id: u32,
parameter: String,
value: Option<Value>,
},
}
impl PatternEdit {
pub(crate) fn apply(&self, graph: &mut PatternGraph) -> Result<Json, String> {
match self {
Self::Add { kind, at, snap } => {
let id = graph.add(*kind)?;
if let Some(node) = graph.nodes.last_mut() {
node.position = crate::graph_grid::snap_position(*at, *snap);
}
return Ok(json!({"id": id}));
}
Self::Move { ids, by, snap } => {
for id in ids {
if !graph.nodes.iter().any(|node| node.id == *id) {
return Err(format!("no FX-Map node {id}"));
}
}
for node in &mut graph.nodes {
if ids.contains(&node.id) {
node.position = crate::graph_grid::translate(node.position, *by, *snap);
}
}
}
Self::Connect { parent, slot, child } => {
if !graph.nodes.iter().any(|node| node.id == *child) {
return Err("missing child node".into());
}
let destination =
graph.nodes.iter_mut().find(|node| node.id == *parent).and_then(|node| node.children.get_mut(*slot)).ok_or("invalid child slot")?;
*destination = Some(*child);
}
Self::Disconnect { node, slot } => {
if let Some(slot) = slot {
let destination = graph
.nodes
.iter_mut()
.find(|candidate| candidate.id == *node)
.and_then(|node| node.children.get_mut(*slot))
.ok_or("invalid child slot")?;
*destination = None;
} else {
for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) {
if *child == Some(*node) {
*child = None;
}
}
}
}
Self::Root { id } => {
if !graph.nodes.iter().any(|node| node.id == *id) {
return Err("missing root node".into());
}
graph.root = Some(*id);
}
Self::Value { id, parameter, value } => {
let node = graph.nodes.iter_mut().find(|node| node.id == *id).ok_or("missing FX-Map node")?;
let definition = materialcraft_nodes::pattern::definition(node.kind).ok_or("unknown FX-Map node")?;
if !definition.params.iter().any(|candidate| candidate.id == parameter) {
return Err("unknown FX-Map parameter".into());
}
if let Some(value) = value {
node.parameters.insert(parameter.clone(), value.clone());
} else {
node.parameters.remove(parameter);
}
}
}
Ok(Json::Null)
}
pub(crate) fn merge_key(&self) -> Option<String> {
match self {
Self::Value { id, parameter, .. } => Some(format!("value:{id}:{parameter}")),
_ => None,
}
}
}
+1 -4
View File
@@ -16,10 +16,7 @@ fn set(session: &mut Session, parameters: &Json) -> Result<Json> {
let graph: PatternGraph =
serde_json::from_value(parameters.get("pattern").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.pattern.set", error.to_string()))?;
graph.validate().map_err(|error| bad("graph.pattern.set", error))?;
if graph.nodes.iter().any(|node| node.position.iter().any(|coordinate| !coordinate.is_finite())) {
return Err(bad("graph.pattern.set", "node positions must be finite"));
}
crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.pattern.set", error))?;
session.edit("Edit FX-Map graph", |session| {
session.graph_mut()?.node_mut(id)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
+32
View File
@@ -0,0 +1,32 @@
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex};
use materialcraft_core::Package;
use materialcraft_eval::{Cache, Cooked, Options};
/// One background result for the editor and the assigned material sources
#[derive(Default)]
pub struct PreviewCook {
pub graph: usize,
pub cooked: Cooked,
pub materials: BTreeMap<usize, Cooked>,
}
impl PreviewCook {
pub fn run(package: &Package, graph: usize, materials: &BTreeSet<usize>, options: &Options<'_>, cache: &Arc<Mutex<Cache>>) -> Self {
let mut result = Self { graph, cooked: materialcraft_eval::cook(package, graph, options, cache), materials: BTreeMap::new() };
for &index in materials {
if result.cancelled() {
break;
}
if index != graph && package.graphs.get(index).is_some() {
result.materials.insert(index, materialcraft_eval::cook(package, index, options, cache));
}
}
result
}
pub fn cancelled(&self) -> bool {
self.cooked.cancelled || self.materials.values().any(|cooked| cooked.cancelled)
}
}
+191
View File
@@ -0,0 +1,191 @@
//! Targeted selection and clipboard commands for standalone and embedded graphs
use crate::{EmbeddedClipboard, Result, Session, commands::bad, graph_edit, selection_target::SelectionTarget};
use materialcraft_core::{FunctionGraph, NodeId, PatternGraph, Value};
use serde_json::{Value as Json, json};
pub fn supports(command: &str) -> bool {
matches!(
command,
"graph.select"
| "edit.selectAll"
| "edit.selectNone"
| "edit.copy"
| "edit.cut"
| "edit.paste"
| "edit.pasteWithoutLinks"
| "edit.delete"
| "edit.deleteRelink"
| "edit.duplicate"
| "edit.duplicateWithoutLinks"
| "graph.selectUpstream"
| "graph.selectDownstream"
)
}
fn selected(session: &Session, target: &SelectionTarget, parameters: &Json) -> Result<Vec<u32>> {
if let Some(ids) = parameters.get("ids") {
return serde_json::from_value(ids.clone()).map_err(|error| bad("graph selection", error.to_string()));
}
if target.standalone() {
return session.selection.iter().map(|id| u32::try_from(id.0).map_err(|_| bad("graph selection", "invalid function node id"))).collect();
}
Ok(Vec::new())
}
pub fn enabled(session: &Session, command: &str, parameters: &Json) -> Option<bool> {
if !handles(session, command, parameters) {
return None;
}
let target = match SelectionTarget::resolve(session, parameters) {
Ok(Some(target)) => target,
Ok(None) => return None,
Err(_) => return Some(false),
};
let selection = match selected(session, &target, parameters) {
Ok(selection) => selection,
Err(_) => return Some(false),
};
enabled_for(session, &target, &selection, command)
}
pub fn enabled_for(session: &Session, target: &SelectionTarget, selection: &[u32], command: &str) -> Option<bool> {
if !supports(command) {
return None;
}
match target {
SelectionTarget::Function(target) => {
if target.current(session).is_err() {
return Some(false);
}
let nodes = match &session.embedded_clipboard {
Some(EmbeddedClipboard::Function { nodes, .. }) => nodes.as_slice(),
_ => &[],
};
graph_edit::enabled::<FunctionGraph>(selection, nodes, command)
}
SelectionTarget::Pattern(owner) => {
if SelectionTarget::pattern(session, *owner).is_err() {
return Some(false);
}
let nodes = match &session.embedded_clipboard {
Some(EmbeddedClipboard::Pattern { nodes, .. }) => nodes.as_slice(),
_ => &[],
};
graph_edit::enabled::<PatternGraph>(selection, nodes, command)
}
}
}
fn handles(session: &Session, command: &str, parameters: &Json) -> bool {
supports(command)
&& !(parameters.get("function").is_none()
&& parameters.get("pattern").is_none()
&& session.annotation_selection.is_some()
&& matches!(command, "edit.delete" | "edit.deleteRelink"))
}
pub(crate) fn execute(session: &mut Session, command: &str, parameters: &Json) -> Option<Result<Json>> {
if !handles(session, command, parameters) {
return None;
}
match SelectionTarget::resolve(session, parameters) {
Ok(Some(target)) => Some(run(session, command, parameters, target)),
Ok(None) => None,
Err(error) => Some(Err(error)),
}
}
fn run(session: &mut Session, command: &str, parameters: &Json, target: SelectionTarget) -> Result<Json> {
let source = target.source(session)?;
let mut selection = selected(session, &target, parameters)?;
if command == "graph.select" && target.standalone() && parameters.get("add").and_then(Json::as_bool) == Some(true) {
for id in session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()) {
if !selection.contains(&id) {
selection.push(id);
}
}
}
let copied_count = selection.len();
let at = crate::commands::point(parameters, "at").unwrap_or([0.0; 2]);
let snap = parameters.get("snapToGrid").and_then(Json::as_bool).unwrap_or(false);
let supplied: Option<EmbeddedClipboard> =
parameters.get("clip").cloned().map(serde_json::from_value).transpose().map_err(|error| bad(command, error.to_string()))?;
let clipboard = supplied.as_ref().or(session.embedded_clipboard.as_ref());
let copying = matches!(command, "edit.copy" | "edit.cut");
let updated_clipboard = match &target {
SelectionTarget::Function(function) => {
let (nodes, origin) = match clipboard {
Some(EmbeddedClipboard::Function { nodes, source }) => (nodes.as_slice(), source.as_str()),
_ => (&[][..], ""),
};
let (graph, copied) = apply(function.current(session)?, &mut selection, nodes, paste_command(command, origin == source), at, snap)?;
if let Some(graph) = graph {
crate::graph_validation::function(&graph).map_err(|error| bad(command, error))?;
session.edit("Edit Function Graph", |session| function.replace(session, graph))?;
}
copying.then_some(EmbeddedClipboard::Function { source, nodes: copied })
}
SelectionTarget::Pattern(owner) => {
let (nodes, origin) = match clipboard {
Some(EmbeddedClipboard::Pattern { nodes, source }) => (nodes.as_slice(), source.as_str()),
_ => (&[][..], ""),
};
let (graph, copied) = apply(SelectionTarget::pattern(session, *owner)?, &mut selection, nodes, paste_command(command, origin == source), at, snap)?;
if let Some(graph) = graph {
crate::graph_validation::pattern(&graph).map_err(|error| bad(command, error))?;
session.edit("Edit FX-Map graph", |session| {
session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
Ok(())
})?;
}
copying.then_some(EmbeddedClipboard::Pattern { source, nodes: copied })
}
};
if target.standalone() {
session.selection = selection.iter().map(|id| NodeId(u64::from(*id))).collect();
session.annotation_selection = None;
}
let mut result = json!({"ids": selection, "selected": selection.len()});
if copying {
result["clip"] = json!(updated_clipboard);
result["copied"] = json!(copied_count);
}
if let Some(clipboard) = updated_clipboard {
session.embedded_clipboard = Some(clipboard);
}
Ok(result)
}
fn paste_command(command: &str, same_source: bool) -> &str {
if command == "edit.paste" && !same_source { "edit.pasteWithoutLinks" } else { command }
}
fn apply<G: graph_edit::EditableGraph + Clone>(
graph: &G,
selection: &mut Vec<u32>,
clipboard: &[G::Node],
command: &str,
at: [f32; 2],
snap: bool,
) -> Result<(Option<G>, Vec<G::Node>)> {
if !matches!(command, "edit.selectAll" | "edit.selectNone") {
let present: std::collections::BTreeSet<_> = graph.nodes().iter().map(G::id).collect();
if selection.iter().any(|id| !present.contains(id)) {
return Err(bad(command, "selection contains a missing node"));
}
}
if graph_edit::enabled::<G>(selection, clipboard, command) != Some(true) {
return Err(bad(command, "the selection or clipboard does not support this action"));
}
let mut copied = Vec::new();
if graph_edit::read(graph, selection, &mut copied, command) {
return Ok((None, copied));
}
if command.starts_with("edit.paste") {
copied = clipboard.to_vec();
}
let mut edited = graph.clone();
let changed = graph_edit::run(&mut edited, selection, &mut copied, command, at, snap).map_err(|error| bad(command, error))?;
Ok((changed.then_some(edited), copied))
}
+51
View File
@@ -0,0 +1,51 @@
use crate::{FunctionGraphTarget, Result, Session, commands::bad};
use materialcraft_core::{NodeId, PatternGraph, Value};
use serde_json::Value as Json;
#[derive(Clone, Debug)]
pub enum SelectionTarget {
Function(FunctionGraphTarget),
Pattern(NodeId),
}
impl SelectionTarget {
pub(crate) fn resolve(session: &Session, parameters: &Json) -> Result<Option<Self>> {
if parameters.get("function").is_some() && parameters.get("pattern").is_some() {
return Err(bad("graph selection", "specify function or pattern, not both"));
}
if let Some(graph) = parameters.get("graph")
&& graph.as_u64() != Some(session.graph as u64)
{
return Err(bad("graph selection", "the owning graph is no longer active"));
}
if let Some(target) = parameters.get("function") {
let target = serde_json::from_value(target.clone()).map_err(|error| bad("graph selection", error.to_string()))?;
return Ok(Some(Self::Function(target)));
}
if let Some(owner) = parameters.get("pattern") {
let owner = owner.as_u64().ok_or_else(|| bad("graph selection", "pattern must be an owner node id"))?;
return Ok(Some(Self::Pattern(NodeId(owner))));
}
Ok(session.graph()?.function.as_ref().map(|_| Self::Function(FunctionGraphTarget::Graph)))
}
pub(crate) fn standalone(&self) -> bool {
matches!(self, Self::Function(FunctionGraphTarget::Graph))
}
pub(crate) fn source(&self, session: &Session) -> Result<String> {
Ok(format!("{}:{self:?}", session.graph()?.name))
}
pub(crate) fn pattern(session: &Session, owner: NodeId) -> Result<&PatternGraph> {
let node = session.graph()?.node(owner)?;
if node.def != "fx_map" {
return Err(bad("graph selection", "the node is not an FX-Map"));
}
let value = node.params.get("pattern").or_else(|| materialcraft_nodes::find(&node.def)?.param("pattern").map(|parameter| &parameter.default));
match value {
Some(Value::PatternGraph(graph)) => Ok(graph),
_ => Err(bad("graph selection", "missing FX-Map graph")),
}
}
}
+28 -7
View File
@@ -124,6 +124,9 @@ pub struct Session {
pub annotation_selection: Option<AnnotationSelection>,
pub view2d: View2d,
pub view3d: View3d,
pub material_preview: crate::MaterialPreview,
pub(crate) cooked_graph: Option<usize>,
pub(crate) material_cooked: std::collections::BTreeMap<usize, Cooked>,
/// Cap on node output size while editing (`None` = full size).
pub preview_size: Option<u32>,
/// 3D view camera preferences (set with [`Session::set_camera_prefs`]).
@@ -133,6 +136,7 @@ pub struct Session {
/// What the last opened SBS package held that MaterialCraft couldn't read; empty after a clean open.
pub load_warnings: Vec<String>,
pub clipboard: Option<Clip>,
pub embedded_clipboard: Option<crate::EmbeddedClipboard>,
/// The last cook of the open graph.
pub cooked: Cooked,
/// Set when the graph changed and needs cooking.
@@ -151,6 +155,9 @@ pub struct Session {
impl Session {
pub fn new(pkg: Package) -> Session {
Session {
material_preview: crate::MaterialPreview::for_graph(&pkg, 0),
cooked_graph: None,
material_cooked: std::collections::BTreeMap::new(),
pkg,
path: None,
graph: 0,
@@ -164,6 +171,7 @@ impl Session {
log: Vec::new(),
load_warnings: Vec::new(),
clipboard: None,
embedded_clipboard: None,
cooked: Cooked::default(),
dirty: true,
cache: Arc::new(Mutex::new(Cache::default())),
@@ -190,6 +198,7 @@ impl Session {
graph: self.graph,
selection: self.selection.clone(),
annotation_selection: self.annotation_selection,
material_preview: self.material_preview.clone(),
label: label.into(),
}
}
@@ -217,6 +226,11 @@ impl Session {
r
}
/// End the current gesture without adding an undo step
pub fn finish_edit(&mut self) {
self.merge_key = None;
}
fn edit_inner<T>(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
let snap = self.snapshot(label);
match f(self) {
@@ -241,6 +255,8 @@ impl Session {
self.graph = s.graph.min(self.pkg.graphs.len().saturating_sub(1));
self.selection = s.selection;
self.annotation_selection = s.annotation_selection;
self.material_preview = s.material_preview;
self.clear_preview_results();
}
/// Mark the document modified and in need of a cook.
@@ -319,11 +335,22 @@ impl Session {
let dec = self.resource_decoder();
let mut opts = Options::new(&dec);
opts.max_size = self.preview_size;
self.cooked = materialcraft_eval::cook(&self.pkg, self.graph, &opts, &self.cache);
let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache);
self.accept_preview(cooked);
self.dirty = false;
&self.cooked
}
/// Publish a completed editor and material cook together
pub fn accept_preview(&mut self, result: crate::PreviewCook) {
if result.graph != self.graph || result.cancelled() {
return;
}
self.cooked_graph = Some(result.graph);
self.cooked = result.cooked;
self.material_cooked = result.materials;
}
/// Cook graph `gi` at full size, without touching the preview results.
pub fn cook_full(&self, gi: usize) -> Cooked {
let dec = self.resource_decoder();
@@ -358,12 +385,6 @@ impl Session {
self.view3d.target = self.camera.clamp_target(self.view3d.target);
}
/// The open graph's material channels for the 3D view: usage id → image.
pub fn material_maps(&self) -> Vec<(&'static str, &Image)> {
let Ok(g) = self.graph() else { return Vec::new() };
materialcraft_eval::outputs(g, &self.cooked).into_iter().filter_map(|(_, usage, _, img)| Some((usage, img?))).collect()
}
/// Show a mesh file in the 3D view (OBJ, glTF, GLB).
pub fn load_mesh_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<()> {
let mesh = materialcraft_formats::mesh::load_mesh(name, bytes)?;
+1
View File
@@ -7,5 +7,6 @@ pub(crate) struct Snapshot {
pub(crate) graph: usize,
pub(crate) selection: Vec<NodeId>,
pub(crate) annotation_selection: Option<AnnotationSelection>,
pub(crate) material_preview: crate::MaterialPreview,
pub(crate) label: String,
}
+22 -9
View File
@@ -171,17 +171,30 @@ fn levels_preserve_independent_rgba_parameters_in_sbs() {
}
#[test]
fn selected_pattern_graph_is_resolved_without_changing_the_document() {
fn selected_node_graph_is_resolved_without_changing_the_document() {
let mut session = materialcraft_engine::new_session();
assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err());
let node = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap();
let original = session.pkg.clone();
let history = session.history();
assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"node": node, "parameter": "pattern"}));
assert_eq!(session.pkg, original);
assert_eq!(session.history(), history);
for (definition, kind, parameter) in
[("fx_map", "pattern", "pattern"), ("pixel_processor", "function", "function"), ("value_processor", "function", "function")]
{
let node = execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap();
let original = session.pkg.clone();
let history = session.history();
assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"kind": kind, "node": node, "parameter": parameter}));
assert_eq!(session.pkg, original);
assert_eq!(session.history(), history);
}
execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap();
assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err());
let node = session.graph_mut().unwrap().add_node("graph_instance", [0.0; 2]);
session.graph_mut().unwrap().node_mut(node).unwrap().params.insert("graph".into(), Value::Text("Child".into()));
session.selection = vec![node];
assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err());
session.pkg.graphs.push(materialcraft_engine::core::Graph::new("Child"));
let original = session.pkg.clone();
let history = session.history();
assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"kind": "graph", "node": node, "graph": 1}));
assert_eq!(session.pkg, original);
assert_eq!(session.history(), history);
}
+319
View File
@@ -0,0 +1,319 @@
use materialcraft_engine::{
FunctionGraphTarget, Session,
core::{FunctionGraph, NodeId, PatternGraph, PatternNodeKind, Value},
execute, new_session,
};
use serde_json::json;
fn function_session(kind: &str) -> (Session, FunctionGraphTarget) {
let mut session = new_session();
let target = match kind {
"graph" => {
execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap();
FunctionGraphTarget::Graph
}
"pattern" => {
let owner = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap());
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
let node = graph.nodes[0].id;
graph.nodes[0].parameters.insert("patternrotation".into(), Value::Function(Box::default()));
execute(&mut session, "graph.pattern.set", &json!({"id": owner.0, "pattern": graph})).unwrap();
FunctionGraphTarget::Pattern { owner, node, parameter: "patternrotation".into() }
}
_ => {
let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap());
if kind == "dynamic" {
session.graph_mut().unwrap().node_mut(node).unwrap().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)
}
#[test]
fn creation_and_connections_use_the_same_rules_for_every_function_target() {
for kind in ["graph", "parameter", "dynamic", "pattern"] {
let (mut session, target) = function_session(kind);
let mut ids = Vec::new();
for operation in ["const_float1", "mul"] {
let result = execute(
&mut session,
"graph.function.edit",
&json!({"target": target, "edit": {"action": "add", "operation": operation, "at": [19, -19], "snap": true}}),
)
.unwrap();
ids.push(result["id"].as_u64().unwrap() as u32);
}
let graph = target.current(&session).unwrap();
assert_eq!(graph.node(ids[1]).unwrap().inputs, vec![None, None]);
assert_eq!(graph.node(ids[1]).unwrap().pos, [32.0, -32.0]);
assert_eq!(graph.output, Some(ids[0]));
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "connect", "from": ids[0], "to": ids[1], "input": 0}}))
.unwrap();
assert_eq!(target.current(&session).unwrap().node(ids[1]).unwrap().inputs[0], Some(ids[0]));
let before = session.pkg.clone();
for edit in [
json!({"action": "connect", "from": ids[1], "to": ids[1], "input": 0}),
json!({"action": "connect", "from": ids[0], "to": ids[1], "input": 1000000}),
json!({"action": "add", "operation": "unknown", "at": [0, 0]}),
] {
assert!(execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": edit})).is_err());
assert_eq!(session.pkg, before);
}
}
}
#[test]
fn value_gestures_merge_but_separate_edits_undo_independently() {
for kind in ["graph", "parameter", "dynamic", "pattern"] {
let (mut session, target) = function_session(kind);
let added =
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}}))
.unwrap();
let id = added["id"].as_u64().unwrap();
let initial = target.current(&session).unwrap().node(id as u32).unwrap().value.clone();
session.reset_history();
for value in [1.0, 2.0, 3.0] {
execute(
&mut session,
"graph.function.edit",
&json!({"target": target, "merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(value)}}),
)
.unwrap();
}
assert_eq!(session.history().len(), 1, "{kind}");
execute(&mut session, "edit.finish", &json!({})).unwrap();
for value in [4.0, 5.0] {
execute(
&mut session,
"graph.function.edit",
&json!({"target": target, "merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(value)}}),
)
.unwrap();
}
assert_eq!(session.history().len(), 2, "{kind}");
session.undo();
assert_eq!(target.current(&session).unwrap().node(id as u32).unwrap().value, Some(Value::Float(3.0)));
session.undo();
assert_eq!(target.current(&session).unwrap().node(id as u32).unwrap().value, initial);
for _ in 0..2 {
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "mul", "at": [0, 0]}})).unwrap();
}
session.undo();
assert_eq!(target.current(&session).unwrap().nodes.len(), 2);
}
}
#[test]
fn pattern_value_gestures_and_invalid_connections_are_atomic() {
let mut session = new_session();
let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap();
let result = execute(&mut session, "graph.pattern.edit", &json!({"id": owner, "edit": {"action": "add", "kind": "paramset", "at": [0, 0]}})).unwrap();
let id = result["id"].as_u64().unwrap();
session.reset_history();
for value in [1.0, 2.0, 3.0] {
execute(
&mut session,
"graph.pattern.edit",
&json!({"id": owner, "merge": true, "edit": {"action": "value", "id": id, "parameter": "patternrotation", "value": Value::Float(value)}}),
)
.unwrap();
}
assert_eq!(session.history().len(), 1);
execute(&mut session, "edit.finish", &json!({})).unwrap();
execute(
&mut session,
"graph.pattern.edit",
&json!({"id": owner, "merge": true, "edit": {"action": "value", "id": id, "parameter": "patternrotation", "value": Value::Float(4.0)}}),
)
.unwrap();
assert_eq!(session.history().len(), 2);
let before = session.pkg.clone();
assert!(execute(&mut session, "graph.pattern.edit", &json!({"id": owner, "edit": {"action": "connect", "parent": id, "slot": 0, "child": id}})).is_err());
assert_eq!(session.pkg, before);
assert!(execute(&mut session, "graph.function.edit", &json!({"target": {"kind": "pattern", "owner": owner, "node": id, "parameter": "absent"}, "edit": {"action": "add", "operation": "mul", "at": [0, 0]}})).is_err());
assert_eq!(session.pkg, before);
}
#[test]
fn selection_commands_work_without_a_ui_for_every_function_target() {
for kind in ["graph", "parameter", "dynamic", "pattern"] {
let (mut session, target) = function_session(kind);
for operation in ["const_float1", "passthrough"] {
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": operation, "at": [0, 0]}})).unwrap();
}
let target_parameters = if kind == "graph" { json!({}) } else { json!({"function": target}) };
let parent_selection = session.selection.clone();
session.reset_history();
let selected = execute(&mut session, "edit.selectAll", &target_parameters).unwrap();
assert_eq!(selected["selected"], 2, "{kind}");
let mut parameters = target_parameters.clone();
parameters["ids"] = selected["ids"].clone();
let copied = execute(&mut session, "edit.copy", &parameters).unwrap();
assert_eq!(copied["copied"], 2);
assert!(session.history().is_empty());
let duplicated = execute(&mut session, "edit.duplicate", &parameters).unwrap();
assert_eq!(target.current(&session).unwrap().nodes.len(), 4);
parameters["ids"] = duplicated["ids"].clone();
execute(&mut session, "edit.delete", &parameters).unwrap();
assert_eq!(target.current(&session).unwrap().nodes.len(), 2);
parameters["ids"] = json!([]);
parameters["clip"] = copied["clip"].clone();
execute(&mut session, "edit.paste", &parameters).unwrap();
assert_eq!(target.current(&session).unwrap().nodes.len(), 4);
if kind != "graph" {
assert_eq!(session.selection, parent_selection, "embedded commands changed the parent selection");
}
}
}
#[test]
fn rejected_function_duplicate_preserves_document_selection_clipboard_and_history() {
let (mut session, target) = function_session("graph");
let mut graph = FunctionGraph::default();
for _ in 0..2049 {
graph.add("passthrough", &[], None);
}
execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap();
execute(&mut session, "edit.selectAll", &json!({})).unwrap();
execute(&mut session, "edit.copy", &json!({})).unwrap();
let before = session.pkg.clone();
let selection = session.selection.clone();
let clipboard = serde_json::to_value(&session.embedded_clipboard).unwrap();
let history = session.history();
assert!(execute(&mut session, "edit.duplicate", &json!({})).is_err());
assert_eq!(session.pkg, before);
assert_eq!(session.selection, selection);
assert_eq!(serde_json::to_value(&session.embedded_clipboard).unwrap(), clipboard);
assert_eq!(session.history(), history);
assert_eq!(target.current(&session).unwrap().nodes.len(), 2049);
}
#[test]
fn graph_validation_is_shared_by_creation_legacy_setters_and_targeted_edits() {
let mut cyclic = FunctionGraph::default();
let id = cyclic.add("passthrough", &[], None);
cyclic.nodes[0].inputs = vec![Some(id)];
cyclic.output = Some(id);
let mut session = new_session();
let owner = execute(&mut session, "graph.node.add", &json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap();
let before = session.pkg.clone();
for (command, parameters) in [
("graph.node.add", json!({"def": "pixel_processor", "params": {"function": Value::Function(Box::new(cyclic.clone()))}})),
("graph.node.param", json!({"id": owner, "param": "function", "value": Value::Function(Box::new(cyclic.clone()))})),
("graph.node.function", json!({"id": owner, "param": "color_mode", "function": cyclic})),
("graph.function.set", json!({"target": {"kind": "parameter", "node": owner, "parameter": "function"}, "function": cyclic})),
] {
let error = execute(&mut session, command, &parameters).unwrap_err().to_string();
assert!(error.contains("cycle"), "{command}: {error}");
assert_eq!(session.pkg, before);
}
let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap();
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
graph.nodes[0].parameters.insert("patternrotation".into(), Value::Function(Box::new(cyclic.clone())));
let before = session.pkg.clone();
for (command, parameters) in [
("graph.pattern.set", json!({"id": owner, "pattern": graph})),
("graph.node.param", json!({"id": owner, "param": "pattern", "value": Value::PatternGraph(Box::new(graph))})),
(
"graph.pattern.edit",
json!({"id": owner, "edit": {"action": "value", "id": 1, "parameter": "patternrotation", "value": Value::Function(Box::new(cyclic))}}),
),
] {
assert!(execute(&mut session, command, &parameters).unwrap_err().to_string().contains("cycle"), "{command}");
assert_eq!(session.pkg, before);
}
}
#[test]
fn pattern_selection_commands_and_cross_graph_clipboards_keep_ownership() {
let mut session = new_session();
let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap();
let selected = execute(&mut session, "edit.selectAll", &json!({"pattern": owner})).unwrap();
let parameters = json!({"pattern": owner, "ids": selected["ids"]});
execute(&mut session, "edit.copy", &parameters).unwrap();
let before = session.pkg.clone();
assert!(execute(&mut session, "edit.deleteRelink", &parameters).is_err());
assert!(execute(&mut session, "edit.delete", &json!({"pattern": owner, "ids": [1], "graph": 99})).is_err());
assert_eq!(session.pkg, before);
execute(&mut session, "edit.duplicate", &parameters).unwrap();
assert_eq!(session.selection, vec![NodeId(owner)]);
let (mut session, _) = function_session("graph");
let mut graph = FunctionGraph::default();
let source = graph.add_constant(Value::Float(1.0));
let child = graph.add("passthrough", &[source], None);
execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap();
let copied = execute(&mut session, "edit.copy", &json!({"ids": [child]})).unwrap();
execute(&mut session, "graph.duplicate", &json!({})).unwrap();
let pasted = execute(&mut session, "edit.paste", &json!({"clip": copied["clip"]})).unwrap();
let id = pasted["ids"][0].as_u64().unwrap() as u32;
assert_eq!(session.graph().unwrap().function.as_ref().unwrap().node(id).unwrap().inputs, vec![None]);
}
#[test]
fn alignment_targets_embedded_functions_and_undo_restores_them() {
for kind in ["parameter", "dynamic", "pattern"] {
let (mut session, target) = function_session(kind);
for at in [[10, 30], [50, 90]] {
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "const_float1", "at": at}})).unwrap();
}
let before = session.pkg.clone();
execute(&mut session, "graph.align", &json!({"function": target, "ids": [1, 2], "mode": "left"})).unwrap();
let positions: Vec<_> = target.current(&session).unwrap().nodes.iter().map(|node| node.pos).collect();
assert_eq!(positions, vec![[10.0, 30.0], [10.0, 90.0]]);
session.undo().unwrap();
assert_eq!(session.pkg, before);
}
}
#[test]
fn replacing_a_package_discards_embedded_clipboard_provenance() {
let (mut session, _) = function_session("graph");
execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})).unwrap();
execute(&mut session, "edit.selectAll", &json!({})).unwrap();
execute(&mut session, "edit.copy", &json!({})).unwrap();
assert!(session.embedded_clipboard.is_some());
let package = session.pkg.clone();
materialcraft_engine::file_cmds::replace_package(&mut session, package, None);
assert!(session.embedded_clipboard.is_none());
}
#[test]
fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs() {
for definition in ["pixel_processor", "value_processor"] {
let mut session = 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() };
let operations: Vec<_> = target.available_operations(&session).map(|operation| operation.id).collect();
let full_catalog = materialcraft_engine::nodes::function::FUNCTIONS;
let sampling = definition == "pixel_processor";
assert_eq!(operations.len(), full_catalog.len() - if sampling { 0 } else { 2 });
assert!(operations.contains(&"add"));
for sampler in ["samplelum", "samplecol"] {
assert_eq!(operations.contains(&sampler), sampling);
let original = session.pkg.clone();
let history = session.history();
let result =
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": sampler, "at": [0, 0]}}));
assert_eq!(result.is_ok(), sampling);
if !sampling {
assert_eq!(session.pkg, original);
assert_eq!(session.history(), history);
}
}
let mut existing = FunctionGraph::default();
existing.add("samplelum", &[], Some(Value::Int2([0, 1])));
execute(&mut session, "graph.function.set", &json!({"target": target, "function": existing})).unwrap();
assert_eq!(target.current(&session).unwrap().nodes[0].op, "samplelum");
}
for kind in ["graph", "pattern", "dynamic"] {
let (session, target) = function_session(kind);
assert_eq!(target.available_operations(&session).count(), materialcraft_engine::nodes::function::FUNCTIONS.len());
}
}
+93
View File
@@ -0,0 +1,93 @@
use materialcraft_engine::{
Session,
core::{FunctionGraph, PatternGraph, PatternNodeKind, Value},
execute, new_session,
};
use serde_json::json;
fn positions(session: &Session, kind: &str, owner: u64) -> Vec<[f32; 2]> {
let graph = session.graph().unwrap();
match kind {
"function" => graph.function.as_ref().unwrap().nodes.iter().map(|node| node.pos).collect(),
"pattern" => {
let Value::PatternGraph(pattern) = &graph.node(materialcraft_engine::core::NodeId(owner)).unwrap().params["pattern"] else {
panic!("missing pattern")
};
pattern.nodes.iter().map(|node| node.position).collect()
}
_ => graph.nodes.iter().map(|node| node.pos).collect(),
}
}
#[test]
fn alignment_and_undo_target_only_the_active_graph_kind() {
for kind in ["material", "function", "pattern"] {
let mut session = new_session();
let coordinates = [[0.0, 0.0], [32.0, 96.0], [256.0, 192.0]];
let mut owner = 0;
let ids: Vec<u64> = match kind {
"function" => {
execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap();
let mut graph = FunctionGraph::default();
for position in coordinates {
graph.add_constant(Value::Float(1.0));
graph.nodes.last_mut().unwrap().pos = position;
}
let ids = graph.nodes.iter().map(|node| u64::from(node.id)).collect();
execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap();
ids
}
"pattern" => {
owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map", "at": [700, 800]})).unwrap()["id"].as_u64().unwrap();
let mut graph = PatternGraph::default();
for position in coordinates {
graph.add(PatternNodeKind::Quadrant).unwrap();
graph.nodes.last_mut().unwrap().position = position;
}
let ids = graph.nodes.iter().map(|node| u64::from(node.id)).collect();
execute(&mut session, "graph.pattern.set", &json!({"id": owner, "pattern": graph})).unwrap();
ids
}
_ => coordinates
.into_iter()
.map(|position| execute(&mut session, "graph.node.add", &json!({"def": "uniform", "at": position})).unwrap()["id"].as_u64().unwrap())
.collect(),
};
let original = session.pkg.clone();
for (mode, expected) in [("left", vec![[0.0, 0.0], [0.0, 96.0], [0.0, 192.0]]), ("hdistribute", vec![[0.0, 0.0], [128.0, 96.0], [256.0, 192.0]])] {
let mut parameters = json!({"ids": ids, "mode": mode});
if kind == "pattern" {
parameters["pattern"] = json!(owner);
}
execute(&mut session, "graph.align", &parameters).unwrap();
assert_eq!(positions(&session, kind, owner), expected, "{kind}: {mode}");
if kind == "pattern" {
assert_eq!(session.graph().unwrap().nodes[0].pos, [700.0, 800.0]);
assert_eq!(session.graph().unwrap().nodes.len(), 1);
}
session.undo().unwrap();
assert_eq!(session.pkg, original);
parameters["ids"] = json!([u64::MAX]);
assert!(execute(&mut session, "graph.align", &parameters).is_err());
assert_eq!(session.pkg, original);
parameters["ids"] = json!(ids);
parameters["mode"] = json!("invalid");
assert!(execute(&mut session, "graph.align", &parameters).is_err());
assert_eq!(session.pkg, original);
}
}
}
#[test]
fn malformed_embedded_targets_never_fall_back_to_parent_selection() {
let mut session = new_session();
for position in [[0, 0], [200, 100]] {
execute(&mut session, "graph.node.add", &json!({"def": "fx_map", "at": position})).unwrap();
}
execute(&mut session, "edit.selectAll", &json!({})).unwrap();
let original = session.pkg.clone();
for parameters in [json!({"pattern": "invalid", "mode": "left"}), json!({"pattern": 1, "mode": "left"})] {
assert!(execute(&mut session, "graph.align", &parameters).is_err());
assert_eq!(session.pkg, original);
}
}
+130
View File
@@ -0,0 +1,130 @@
use materialcraft_engine::{
core::{FunctionGraph, PatternGraph, PatternNodeKind, Value},
graph_edit::{self, EditableGraph},
};
fn exercise_clipboard<G: EditableGraph>(mut graph: G, chain: [u32; 3]) {
let mut selection = vec![chain[1], chain[2]];
let mut clipboard = Vec::new();
let before = graph.nodes().len();
graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.copy", [0.0; 2], true).unwrap();
for command in ["edit.paste", "edit.pasteWithoutLinks"] {
graph_edit::run(&mut graph, &mut selection, &mut clipboard, command, [19.0, 19.0], true).unwrap();
assert_eq!(selection.len(), 2);
let first = graph.nodes().iter().find(|node| G::id(node) == selection[0]).unwrap();
let second = graph.nodes().iter().find(|node| G::id(node) == selection[1]).unwrap();
assert_eq!(G::links(second)[0], Some(selection[0]));
assert_eq!(G::links(first)[0], if command == "edit.paste" { Some(chain[0]) } else { None });
assert!(graph_edit::remove(&mut graph, &mut selection, false));
assert_eq!(graph.nodes().len(), before);
}
for command in ["graph.selectUpstream", "graph.selectDownstream"] {
selection = vec![chain[1]];
graph_edit::run(&mut graph, &mut selection, &mut clipboard, command, [0.0; 2], false).unwrap();
let follow_links = (command == "graph.selectUpstream") == G::LINKS_ARE_INPUTS;
let mut expected = if follow_links { vec![chain[0], chain[1]] } else { vec![chain[1], chain[2]] };
expected.sort();
assert_eq!(selection, expected);
}
}
#[test]
fn function_and_pattern_clipboards_keep_internal_links_and_respect_direction() {
let mut function = FunctionGraph::default();
let a = function.add_constant(Value::Float(1.0));
let b = function.add("passthrough", &[a], None);
let c = function.add("passthrough", &[b], None);
exercise_clipboard(function, [a, b, c]);
let mut pattern = PatternGraph::default();
let a = pattern.add(PatternNodeKind::Dot).unwrap();
let b = pattern.add(PatternNodeKind::Dot).unwrap();
let c = pattern.add(PatternNodeKind::Dot).unwrap();
pattern.nodes[1].children[0] = Some(a);
pattern.nodes[2].children[0] = Some(b);
exercise_clipboard(pattern, [a, b, c]);
}
#[test]
fn pattern_paste_capacity_failure_is_atomic_and_root_is_preserved() {
let mut graph = PatternGraph::with_root(PatternNodeKind::Dot);
let node = graph.nodes[0].clone();
graph.nodes = (1..4096).map(|id| materialcraft_engine::core::PatternNode { id, ..node.clone() }).collect();
let before = graph.clone();
let mut clipboard = vec![node.clone(), node];
let mut selection = vec![1];
assert!(graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.paste", [0.0; 2], true).is_err());
assert_eq!(graph, before);
assert_eq!(selection, vec![1]);
}
#[test]
fn function_delete_relinks_chains_and_clears_a_deleted_output() {
let mut graph = FunctionGraph::default();
let a = graph.add_constant(Value::Float(1.0));
let b = graph.add("passthrough", &[a], None);
let c = graph.add("passthrough", &[b], None);
let d = graph.add("passthrough", &[c], None);
graph.output = Some(d);
assert!(graph_edit::remove(&mut graph, &mut vec![b, c], true));
assert_eq!(graph.node(d).unwrap().inputs, vec![Some(a)]);
assert_eq!(graph.output, Some(d));
assert!(graph_edit::remove(&mut graph, &mut vec![d], false));
assert_eq!(graph.output, None);
}
#[test]
fn pattern_clipboard_preserves_selection_order_when_ids_have_holes() {
let mut graph = PatternGraph::default();
for _ in 0..3 {
graph.add(PatternNodeKind::Quadrant).unwrap();
}
graph.nodes.remove(1);
let id = graph.add(PatternNodeKind::Quadrant).unwrap();
assert_eq!(id, 2);
let mut selection = vec![2, 3];
let mut clipboard = Vec::new();
graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.duplicate", [0.0; 2], false).unwrap();
assert_eq!(selection, vec![5, 4]);
}
#[test]
#[ignore = "release timing probe; run explicitly with --ignored --nocapture"]
fn connected_selection_performance() {
use std::{collections::BTreeSet, time::Instant};
let mut graph = FunctionGraph::default();
for id in 1..=4096 {
graph.nodes.push(materialcraft_engine::core::FunctionNode {
id,
op: "passthrough".into(),
type_code: 0,
inputs: if id == 1 { vec![] } else { vec![Some(id - 1)] },
value: None,
pos: [0.0; 2],
});
}
let mut before = Vec::new();
let mut after = Vec::new();
for _ in 0..3 {
let start = Instant::now();
let mut visited = BTreeSet::new();
let mut pending = vec![1];
while let Some(id) = pending.pop() {
if visited.insert(id) {
pending.extend(graph.nodes.iter().filter(|node| node.inputs.contains(&Some(id))).map(|node| node.id));
}
}
let expected: Vec<_> = visited.into_iter().collect();
before.push(start.elapsed().as_secs_f64() * 1000.0);
let mut selection = vec![1];
let start = Instant::now();
graph_edit::run(std::hint::black_box(&mut graph), &mut selection, &mut Vec::new(), "graph.selectDownstream", [0.0; 2], false).unwrap();
after.push(start.elapsed().as_secs_f64() * 1000.0);
assert_eq!(selection, expected);
}
before.sort_by(f64::total_cmp);
after.sort_by(f64::total_cmp);
println!("4096-node downstream selection, median of three: scan {:.3} ms; shared index {:.3} ms", before[1], after[1]);
}
+263
View File
@@ -0,0 +1,263 @@
use materialcraft_engine::{
MaterialPreview, MaterialSource, Session,
core::{Graph, MaterialChannel, NodeId, Package, Value},
execute, new_session,
};
use serde_json::json;
fn add(session: &mut Session, definition: &str, params: serde_json::Value) -> NodeId {
NodeId(execute(session, "graph.node.add", &json!({"def": definition, "params": params})).unwrap()["id"].as_u64().unwrap())
}
fn source(session: &mut Session, color: [f32; 4]) -> NodeId {
add(session, "uniform", json!({"color_mode": true, "color": color}))
}
fn output(session: &mut Session, source: NodeId, usage: u32) -> NodeId {
let output = add(session, "output", json!({"usage": usage}));
execute(session, "graph.connect", &json!({"from": source, "to": output})).unwrap();
output
}
fn instance(session: &mut Session, graph: &str) -> NodeId {
let node = session.graph_mut().unwrap().add_node("graph_instance", [0.0; 2]);
session.graph_mut().unwrap().node_mut(node).unwrap().params.insert("graph".into(), Value::Text(graph.into()));
node
}
fn color(session: &mut Session, channel: &str) -> [f32; 4] {
session.cook();
session.material_maps().into_iter().find(|(usage, _)| *usage == channel).unwrap().1.get(0, 0, false)
}
#[test]
fn explicit_assignment_shows_unclassified_output_and_tracks_edits() {
let mut session = new_session();
session.preview_size = Some(16);
let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
let output = output(&mut session, red, 9);
session.cook();
assert!(session.material_maps().is_empty());
let history = session.history();
let package = session.pkg.clone();
execute(&mut session, "view.3d.assign", &json!({"node": output, "channel": "baseColor"})).unwrap();
assert_eq!(session.history(), history);
assert_eq!(session.pkg, package);
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
let key = session.material_key();
execute(&mut session, "graph.node.param", &json!({"id": red, "param": "color", "value": [0.1, 0.8, 0.2, 1.0]})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.1, 0.8, 0.2, 1.0]);
assert_ne!(session.material_key(), key);
let inspection = execute(&mut session, "session.inspect", &json!({})).unwrap();
assert_eq!(inspection["material3d"]["channels"][0]["size"], json!([16, 16]));
}
#[test]
fn automatic_outputs_follow_usage_and_do_not_follow_selection() {
let mut session = new_session();
session.preview_size = Some(16);
let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]);
let output = output(&mut session, red, 0);
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "graph.select", &json!({"ids": [blue]})).unwrap();
execute(&mut session, "view.2d", &json!({"node": blue})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "graph.node.param", &json!({"id": output, "param": "usage", "value": 4})).unwrap();
assert_eq!(color(&mut session, "height"), [0.8, 0.1, 0.1, 1.0]);
assert!(session.material_maps().iter().all(|(channel, _)| *channel != "baseColor"));
}
#[test]
fn graph_application_and_material_reset_preserve_camera_and_scene() {
let mut session = new_session();
session.preview_size = Some(16);
let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
output(&mut session, red, 0);
let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]);
execute(&mut session, "view.3d.assign", &json!({"node": blue, "channel": "baseColor"})).unwrap();
execute(&mut session, "view.3d.assign", &json!({"node": blue, "channel": "roughness"})).unwrap();
execute(&mut session, "view.3d", &json!({"scene": "sphere", "yaw": 70, "distance": 4, "environment": "sunset"})).unwrap();
let view = session.view3d.clone();
execute(&mut session, "view.3d.outputs", &json!({})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
assert!(session.material_maps().iter().any(|(channel, _)| *channel == "roughness"));
execute(&mut session, "view.3d.outputs", &json!({"reset": true})).unwrap();
session.cook();
assert_eq!(session.material_maps().len(), 1);
assert_eq!(session.view3d, view);
execute(&mut session, "view.3d.clear", &json!({})).unwrap();
assert!(session.material_maps().is_empty());
assert_eq!(session.view3d, view);
}
#[test]
fn assignments_survive_function_editing_and_undo_without_retargeting_node_ids() {
let mut session = new_session();
session.preview_size = Some(16);
let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "view.3d.assign", &json!({"node": red, "channel": "baseColor"})).unwrap();
session.cook();
execute(&mut session, "file.new", &json!({"kind": "function", "name": "Function"})).unwrap();
assert_eq!(session.material_maps()[0].1.get(0, 0, false), [0.8, 0.1, 0.1, 1.0], "keep the previous material while the worker cooks");
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "file.new", &json!({"template": "empty", "name": "Blue"})).unwrap();
let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]);
assert_eq!(red, blue);
execute(&mut session, "view.3d.assign", &json!({"graph": 0, "node": red, "channel": "baseColor"})).unwrap();
execute(&mut session, "graph.node.param", &json!({"id": blue, "param": "color", "value": [0.2, 0.2, 0.9, 1.0]})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "graph.rename", &json!({"graph": 0, "name": "Renamed"})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "graph.delete", &json!({"graph": 0})).unwrap();
session.cook();
assert!(session.material_maps().is_empty());
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "file.newPackage", &json!({})).unwrap();
assert!(session.material_preview.channels.is_empty());
}
#[test]
fn opening_material_graph_automatically_applies_its_outputs() {
let mut session = new_session();
session.preview_size = Some(16);
let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
output(&mut session, red, 0);
execute(&mut session, "file.new", &json!({"template": "empty", "name": "Blue"})).unwrap();
let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]);
output(&mut session, blue, 0);
assert_eq!(color(&mut session, "baseColor"), [0.1, 0.1, 0.8, 1.0]);
execute(&mut session, "graph.open", &json!({"graph": 0})).unwrap();
assert!(session.material_maps().is_empty(), "stale results must not cross graph IDs");
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
}
#[test]
fn invalid_assignments_are_atomic_including_scalar_instance_outputs() {
let mut session = new_session();
session.preview_size = Some(16);
let image = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "view.3d.assign", &json!({"node": image, "channel": "baseColor"})).unwrap();
let value = add(&mut session, "input_value", json!({}));
let value_output = output(&mut session, value, 0);
let mut graph = Graph::new("Values");
let input = graph.add_node("input_value", [0.0; 2]);
let out = graph.add_node("output", [100.0, 0.0]);
graph.node_mut(out).unwrap().params.insert("identifier".into(), Value::Text("value".into()));
graph.connect(input, "output", out, "input").unwrap();
session.pkg.graphs.push(graph);
let instance = instance(&mut session, "Values");
let before = session.material_preview.clone();
let history = session.history();
let package = session.pkg.clone();
for parameters in [
json!({"node": image, "channel": "unknown", "reset": true}),
json!({"node": image, "channel": "baseColor", "port": 999, "reset": true}),
json!({"node": image, "channel": "baseColor", "graph": 999, "reset": true}),
json!({"node": value, "channel": "baseColor", "reset": true}),
json!({"node": value_output, "channel": "baseColor", "reset": true}),
json!({"node": instance, "port": "value", "channel": "baseColor", "reset": true}),
] {
assert!(execute(&mut session, "view.3d.assign", &parameters).is_err(), "{parameters}");
assert_eq!(session.material_preview, before);
assert_eq!(session.history(), history);
assert_eq!(session.pkg, package);
}
assert!(execute(&mut session, "view.3d.outputs", &json!({"graph": "Values", "reset": true})).is_err());
assert_eq!(session.material_preview, before);
}
#[test]
fn multiple_graph_channels_and_multi_output_instances_use_the_correct_ports() {
let mut package = Package::new("Test");
let mut graph = Graph::new("Colors");
graph.size = [4, 4];
for (name, color) in [("red", [0.8, 0.1, 0.1, 1.0]), ("blue", [0.1, 0.1, 0.8, 1.0])] {
let image = graph.add_node("uniform", [0.0; 2]);
graph.node_mut(image).unwrap().params.insert("color".into(), Value::Color(color));
let output = graph.add_node("output", [100.0, 0.0]);
graph.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text(name.into()));
graph.connect(image, "output", output, "input").unwrap();
}
package.graphs.push(graph);
package.graphs.push(Graph::new("Instances"));
let mut session = Session::new(package);
execute(&mut session, "graph.open", &json!({"graph": 1})).unwrap();
let instance = instance(&mut session, "Colors");
execute(&mut session, "view.3d.assign", &json!({"node": instance, "port": "blue", "channel": "baseColor"})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.1, 0.1, 0.8, 1.0]);
let key = session.material_key();
execute(&mut session, "view.3d.assign", &json!({"node": instance, "port": 0, "channel": "baseColor"})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
assert_ne!(session.material_key(), key);
execute(&mut session, "view.3d.assign", &json!({"graph": "Colors", "node": 1, "channel": "emissive"})).unwrap();
assert_eq!(color(&mut session, "emissive"), [0.8, 0.1, 0.1, 1.0]);
assert_eq!(session.graph, 1);
}
#[test]
fn removing_an_earlier_graph_adjusts_sources_and_undo_restores_them() {
let mut session = new_session();
execute(&mut session, "file.new", &json!({"template": "empty"})).unwrap();
let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "view.3d.assign", &json!({"node": red, "channel": "baseColor"})).unwrap();
execute(&mut session, "graph.delete", &json!({"graph": 0})).unwrap();
assert_eq!(session.material_preview.channels[&MaterialChannel::BaseColor].graph, 0);
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(session.material_preview.channels[&MaterialChannel::BaseColor].graph, 1);
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
let before = session.material_key();
execute(&mut session, "graph.select", &json!({"ids": [red]})).unwrap();
execute(&mut session, "edit.delete", &json!({})).unwrap();
session.cook();
assert!(session.material_maps().is_empty());
assert_ne!(session.material_key(), before);
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
}
#[test]
fn source_cycles_are_rejected_without_recursion() {
let mut package = Package::new("Cycle");
let mut graph = Graph::new("Cycle");
let instance = graph.add_node("graph_instance", [0.0; 2]);
graph.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text("Cycle".into()));
let output = graph.add_node("output", [100.0, 0.0]);
graph.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text("loop".into()));
graph.connect(instance, "loop", output, "input").unwrap();
package.graphs.push(graph);
let source = MaterialSource { graph: 0, node: instance, port: "loop".into() };
assert!(!source.is_image(&package));
assert!(MaterialPreview::for_graph(&package, 0).sources(&package).is_empty());
}
#[test]
fn diffuse_usage_previews_as_base_color_and_unknown_usages_stay_unassigned() {
use materialcraft_engine::core::ComponentUsage;
let mut session = new_session();
session.preview_size = Some(16);
let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
let output = output(&mut session, red, ComponentUsage::index("diffuse"));
assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]);
for usage in [ComponentUsage::ANY_INDEX, u32::MAX, ComponentUsage::index("coatRoughness")] {
session.graph_mut().unwrap().node_mut(output).unwrap().params.insert("usage".into(), Value::Enum(usage));
assert!(session.material_maps().is_empty(), "usage {usage} must not become a different channel");
}
}
#[test]
fn extracted_graph_outputs_remain_unclassified() {
let mut session = new_session();
let uniform = source(&mut session, [0.8, 0.1, 0.1, 1.0]);
output(&mut session, uniform, 0);
execute(&mut session, "graph.select", &json!({"ids": [uniform]})).unwrap();
execute(&mut session, "graph.createFromSelection", &json!({"name": "Extracted"})).unwrap();
let (_, graph) = session.pkg.graph_by_name("Extracted").unwrap();
let output = graph.nodes.iter().find(|node| node.def == "output").unwrap();
assert_eq!(materialcraft_engine::eval::output_usage(output), "any");
}
+84
View File
@@ -0,0 +1,84 @@
//! Focused optimization benchmarks: release, ignored, serial, with --nocapture
use std::{collections::BTreeMap, hint::black_box, sync::Mutex, time::Instant};
use materialcraft_core::{Connection, FunctionGraph, Graph, Package, PatternGraph, PatternNodeKind, Value};
use materialcraft_eval::{Cache, Options, cook};
use materialcraft_nodes::{CookContext, find, resolve_params};
fn median_ms(mut run: impl FnMut()) -> f64 {
let mut samples = [0.0; 3];
for sample in &mut samples {
let start = Instant::now();
run();
*sample = start.elapsed().as_secs_f64() * 1000.0;
}
samples.sort_by(f64::total_cmp);
samples[1]
}
#[test]
#[ignore = "optimization benchmark"]
fn optimization_baseline() {
for count in [128, 1024, 4096] {
let ms = median_ms(|| {
let mut graph = PatternGraph::default();
for _ in 0..count {
graph.add(PatternNodeKind::Quadrant).unwrap();
}
black_box(graph);
});
println!("pattern_add,{count},{ms:.3}");
}
let mut function = FunctionGraph::default();
let position = function.add("get_float2", &[], Some(Value::Text("$pos".into())));
let horizontal = function.add("swizzle1", &[position], Some(Value::Int(0)));
let factor = function.add_constant(Value::Float(0.5));
function.output = Some(function.add("mul", &[horizontal, factor], None));
let definition = find("pixel_processor").unwrap();
let mut parameters = resolve_params(definition, &BTreeMap::new());
parameters.insert("function".into(), Value::Function(Box::new(function)));
parameters.insert("color_mode".into(), Value::Bool(false));
for size in [512, 2048] {
for count in [0, 16] {
let variables = (0..count).map(|index| (format!("input_{index}"), Value::Float(index as f32))).collect();
let context = CookContext { w: size, h: size, seed: 7, tile: true, inputs: &[], params: &parameters, resource: &|_| None, vars: &variables };
let ms = median_ms(|| {
black_box((definition.cook)(&context).unwrap());
});
println!("pixel_processor,{size},{count},{ms:.3}");
}
}
for count in [128, 1024, 4096] {
for branching in [false, true] {
let mut graph = Graph::new("Benchmark");
graph.size = [4, 4];
let source = graph.add_node("uniform", [0.0; 2]);
let mut previous = source;
for _ in 1..count {
let node = graph.add_node("dot", [0.0; 2]);
graph.connections.push(Connection {
from: if branching { source } else { previous },
from_port: "output".into(),
to: node,
to_port: "input".into(),
});
previous = node;
}
let mut package = Package::new("Benchmark");
package.graphs.push(graph);
let options = Options::new(&|_| None);
let cache = Mutex::new(Cache::default());
let initial = cook(&package, 0, &options, &cache);
assert_eq!(initial.nodes.len(), count);
assert!(initial.nodes.values().all(|result| result.error.is_none()));
let ms = median_ms(|| {
let cooked = cook(&package, 0, &options, &cache);
assert!(cooked.nodes.values().all(|result| result.cached));
black_box(cooked);
});
println!("warm_cook,{count},{branching},{ms:.3}");
}
}
}
+63
View File
@@ -1,4 +1,7 @@
use crate::{identifier, instance_graph};
use materialcraft_core::{Node, Package, Value};
use materialcraft_image::Image;
use std::collections::{BTreeMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
pub(crate) fn image_key(i: &Image) -> u64 {
@@ -11,3 +14,63 @@ pub(crate) fn hash_of(v: &impl Hash) -> u64 {
v.hash(&mut h);
h.finish()
}
pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 {
let mut h = DefaultHasher::new();
let mut pending = vec![gi];
let mut seen = HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
let Some(graph) = pkg.graphs.get(index) else { continue };
index.hash(&mut h);
serde_json::to_string(graph).unwrap_or_default().hash(&mut h);
for n in &graph.nodes {
if let Some(Value::Text(name)) = n.params.get("resource") {
pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h);
}
if n.def == "graph_instance"
&& let Some((si, _)) = instance_graph(pkg, n)
{
pending.push(si);
}
}
}
h.finish()
}
pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap<String, Value>, variables: &BTreeMap<String, Value>) -> u64 {
let mut names = std::collections::BTreeSet::new();
let mut pending: Vec<&Value> = parameters.values().collect();
while let Some(value) = pending.pop() {
match value {
Value::Function(graph) => {
for function in &graph.nodes {
if (function.op.starts_with("get_") || function.op == "isdefined")
&& let Some(Value::Text(name)) = &function.value
{
names.insert(name.as_str());
}
}
}
Value::PatternGraph(graph) => {
pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values()));
}
_ => {}
}
}
let input_identifier = identifier(node);
if node.def == "input_value" {
names.insert(&input_identifier);
}
let mut hasher = DefaultHasher::new();
for name in names {
name.hash(&mut hasher);
variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher);
}
hasher.finish()
}
+33 -386
View File
@@ -1,400 +1,47 @@
use std::collections::{BTreeMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};
use crate::{Cache, Cooked, Options, now_ms};
use crate::{node_execution::cook_node, prepared_graph::PreparedGraph};
use materialcraft_core::{Package, Value};
use materialcraft_image::Image;
use std::{
collections::BTreeMap,
sync::{Mutex, atomic::Ordering},
};
use materialcraft_core::{Graph, Node, NodeId, Package, Value};
use materialcraft_image::{Image, Kind};
use materialcraft_nodes::{CookContext, clamp_params, find, resolve_params};
pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mutex<Cache>) -> Cooked {
let started_ms = now_ms();
let mut cooked = Cooked::default();
let Some(graph) = package.graphs.get(graph_index) else { return cooked };
use crate::cache_key::{hash_of, image_key};
use crate::{Cache, Cooked, MAX_DEPTH, NodeOutput, NodeResult, Options, Port, identifier, instance_graph, node_size, ports};
/// The magenta image a failed node shows
pub fn error_image(w: u32, h: u32) -> Image {
Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0])
}
/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written)
fn lock(cache: &Mutex<Cache>) -> std::sync::MutexGuard<'_, Cache> {
cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &Mutex<Cache>) -> Cooked {
let t0 = now_ms();
let mut out = Cooked::default();
let Some(graph) = pkg.graphs.get(gi) else { return out };
// The top-level graph's input nodes show their preview images; the caller's images win
let bound;
let opts = if opts.depth == 0 && !graph.input_images.is_empty() {
let mut inputs: BTreeMap<String, Image> = graph.input_images.iter().filter_map(|(id, res)| Some((id.clone(), (opts.resource)(res)?))).collect();
inputs.extend(opts.inputs.iter().map(|(k, v)| (k.clone(), v.clone())));
bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), graph_stack: opts.graph_stack.clone(), ..*opts };
let options = if options.depth == 0 && !graph.input_images.is_empty() {
let mut inputs: BTreeMap<String, Image> =
graph.input_images.iter().filter_map(|(id, resource)| Some((id.clone(), (options.resource)(resource)?))).collect();
inputs.extend(options.inputs.iter().map(|(name, value)| (name.clone(), value.clone())));
bound = Options { only: options.only.clone(), inputs, overrides: options.overrides.clone(), graph_stack: options.graph_stack.clone(), ..*options };
&bound
} else {
opts
options
};
let order = graph.topo_order();
let needed: Option<std::collections::BTreeSet<NodeId>> = opts.only.as_ref().map(|ids| {
let mut s: std::collections::BTreeSet<NodeId> = ids.iter().copied().collect();
for id in ids {
s.extend(graph.upstream(*id));
}
s
});
let prepared = PreparedGraph::new(package, graph, options.only.as_deref());
// Exposed parameter values: the graph's own, then the caller's overrides
let mut vars: BTreeMap<String, Value> = graph.exposed.iter().filter_map(|e| graph.input_value(&e.id).map(|v| (e.id.clone(), v.clone()))).collect();
for (k, v) in &opts.overrides {
vars.insert(k.clone(), v.clone());
let mut variables: BTreeMap<String, Value> =
graph.exposed.iter().filter_map(|exposed| graph.input_value(&exposed.id).map(|value| (exposed.id.clone(), value.clone()))).collect();
for (name, value) in &options.overrides {
variables.insert(name.clone(), value.clone());
}
for id in order {
if needed.as_ref().is_some_and(|s| !s.contains(&id)) {
continue;
}
if opts.cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
out.cancelled = true;
for &id in &prepared.order {
if options.cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
cooked.cancelled = true;
break;
}
let Ok(node) = graph.node(id) else { continue };
let r = cook_node(pkg, gi, graph, node, &out, &vars, opts, cache);
out.nodes.insert(id, r);
let Some(node) = prepared.index.node(id) else { continue };
let result = cook_node(package, graph_index, graph, &prepared, node, &cooked, &variables, options, cache);
cooked.nodes.insert(id, result);
}
out.ms = (now_ms() - t0) as f32;
out
}
pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 {
let mut h = DefaultHasher::new();
let mut pending = vec![gi];
let mut seen = HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
let Some(graph) = pkg.graphs.get(index) else { continue };
index.hash(&mut h);
serde_json::to_string(graph).unwrap_or_default().hash(&mut h);
for n in &graph.nodes {
if let Some(Value::Text(name)) = n.params.get("resource") {
pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h);
}
if n.def == "graph_instance"
&& let Some((si, _)) = instance_graph(pkg, n)
{
pending.push(si);
}
}
}
h.finish()
}
fn cook_node(
pkg: &Package,
gi: usize,
graph: &Graph,
node: &Node,
done: &Cooked,
vars: &BTreeMap<String, Value>,
opts: &Options,
cache: &Mutex<Cache>,
) -> NodeResult {
let (in_ports, out_ports) = ports(pkg, graph, node);
let def = find(&node.def);
// Gather inputs by port order, with their keys
let mut inputs = Vec::new();
let mut incoming = Vec::new();
let mut input_keys = Vec::new();
let mut variables = vars.clone();
let mut input_error = None;
for port in &in_ports {
let source = graph.input_of(node.id, &port.id).and_then(|connection| {
let result = done.nodes.get(&connection.from)?;
let source_node = graph.node(connection.from).ok()?;
let index = ports(pkg, graph, source_node).1.iter().position(|output| output.id == connection.from_port)?;
Some((result.outputs.get(index)?.clone(), result.key ^ hash_of(&index)))
});
input_keys.push(source.as_ref().map_or(0, |source| source.1));
let output = source.map(|source| source.0);
if let Some(expected) = node.input_values.get(&port.id) {
let value = match output.as_ref() {
Some(NodeOutput::Value(value)) if materialcraft_core::ValueType::of(value) == Some(*expected) => value.clone(),
Some(_) => {
input_error = Some(format!("input `{}` requires {}", port.id, expected.label()));
expected.default_value()
}
None => expected.default_value(),
};
variables.insert(port.id.clone(), value);
} else {
if output.as_ref().is_some_and(|output| output.as_value().is_some()) && !matches!(node.def.as_str(), "output" | "dot") {
input_error = Some(format!("input `{}` requires an image", port.id));
}
inputs.push(output.as_ref().and_then(NodeOutput::as_image).cloned());
}
incoming.push(output);
}
let vars = &variables;
let first = inputs.iter().flatten().next().map(|i| (i.w, i.h));
let (w, h) = node_size(graph, def, node, first, opts.max_size);
let fail = |msg: String, key: u64| NodeResult {
outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); out_ports.len().max(1)]),
error: Some(msg),
ms: 0.0,
key,
cached: false,
};
if let Some(error) = input_error {
return fail(error, 0);
}
// Parameters: defaults, overrides, then bindings to exposed inputs
let mut params = match def {
Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params),
_ => node.params.clone(),
};
for (param, exposed) in &node.bindings {
if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param))
&& let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default())
{
params.insert(param.clone(), c);
}
}
let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32);
// Dynamic parameters: functions of the graph's inputs, evaluated once per cook
for (param, f) in &node.functions {
let Some(cur) = params.get(param) else { continue };
match materialcraft_nodes::function::compile(f, seed) {
Ok(prog) => {
let context = materialcraft_nodes::function::EvaluationContext {
position: [0.5; 2],
size: [w as f32, h as f32],
images: &[],
tile: true,
variables: vars,
};
let value = match prog.evaluate(&context, &mut materialcraft_nodes::function::EvaluationState::default()) {
Ok(value) => value,
Err(error) => return fail(format!("function of `{param}`: {error}"), 0),
};
if let Some(c) = cur.coerce_json(&serde_json::to_value(value).unwrap_or_default()) {
params.insert(param.clone(), c);
}
}
Err(e) => return fail(format!("function of `{param}`: {e}"), 0),
}
}
// Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook)
if let Some(d) = def
&& node.def != "graph_instance"
{
clamp_params(d, &mut params);
}
let tile = node.base.tiling[0] && node.base.tiling[1];
// Input nodes read the caller's image for their identifier
let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten();
let res_hash = match params.get("resource") {
Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()),
_ => 0,
};
let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 };
let key = hash_of(&(
&node.def,
serde_json::to_string(&params).unwrap_or_default(),
(w, h, seed, tile, node.disabled),
&input_keys,
res_hash,
sub_hash,
input_img.map(image_key),
variable_key(node, &params, vars),
));
if let Some(v) = lock(cache).get(key) {
return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true };
}
let t0 = now_ms();
let result: Result<Vec<NodeOutput>, String> = if node.disabled {
let output = incoming.iter().flatten().next().cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4])));
Ok(vec![output; out_ports.len().max(1)])
} else if node.def == "input_value" {
let value = vars.get(&identifier(node)).or_else(|| params.get("default")).cloned().unwrap_or(Value::Float(0.0));
Ok(vec![NodeOutput::Value(value)])
} else if node.def == "value_processor" {
evaluate_value(&params, vars, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)])
} else if matches!(node.def.as_str(), "output" | "dot") && incoming.first().and_then(Option::as_ref).is_some_and(|output| output.as_value().is_some()) {
incoming.first().and_then(Clone::clone).map(|output| vec![output]).ok_or("missing value input".into())
} else if let Some(image) = input_img {
let image = image.resize(w, h, tile);
let image = if node.def == "input_grayscale" { image.to_gray() } else { image };
Ok(vec![NodeOutput::Image(image)])
} else if node.def == materialcraft_core::MISSING_NODE {
let name = if node.label.is_empty() { "this node" } else { node.label.as_str() };
Err(format!("unsupported node `{name}`"))
} else if node.def == "graph_instance" {
cook_instance(pkg, gi, node, &in_ports, &out_ports, &inputs, &params, (w, h), opts, cache)
.map(|images| images.into_iter().map(NodeOutput::Image).collect())
} else if let Some(definition) = def {
let context = CookContext { w, h, seed, tile, inputs: &inputs, params: &params, resource: opts.resource, vars };
(definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect())
} else {
Err(format!("unknown node `{}`", node.def))
};
match result {
Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => {
let v = Arc::new(imgs);
lock(cache).put(key, v.clone());
NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false }
}
Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key),
Err(e) => fail(e, key),
}
}
/// Whether graph `from` reaches `target`, without recursive stack growth
pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool {
let mut pending = vec![from];
let mut seen = HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
let Some(graph) = pkg.graphs.get(index) else { continue };
for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) {
if si == target {
return true;
}
pending.push(si);
}
}
false
}
fn cook_instance(
pkg: &Package,
gi: usize,
node: &Node,
in_ports: &[Port],
out_ports: &[Port],
inputs: &[Option<Image>],
params: &BTreeMap<String, Value>,
size: (u32, u32),
opts: &Options,
cache: &Mutex<Cache>,
) -> Result<Vec<Image>, String> {
if opts.depth >= MAX_DEPTH {
return Err("graph instances nest too deep (does a graph use itself?)".into());
}
let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?;
if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) {
return Err(format!("graph `{}` uses itself through a graph instance", sub.name));
}
let mut o = Options::new(opts.resource);
o.max_size = opts.max_size;
o.cancel = opts.cancel;
o.depth = opts.depth + 1;
o.graph_stack = opts.graph_stack.clone();
o.graph_stack.push(gi);
o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect();
o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect();
let cooked = cook(pkg, sub_gi, &o, cache);
if cooked.cancelled {
return Err("cancelled".into());
}
Ok(out_ports
.iter()
.map(|p| {
sub.nodes
.iter()
.find(|n| n.def == "output" && identifier(n) == p.id)
.and_then(|n| cooked.image(n.id, 0))
.map(|i| i.resize(size.0, size.1, true))
.unwrap_or_else(|| Image::filled(size.0, size.1, Kind::Gray, [0.0; 4]))
})
.collect())
}
/// The graph's output nodes with their usage id and image, in node order
pub fn outputs<'c>(graph: &Graph, cooked: &'c Cooked) -> Vec<(NodeId, &'static str, String, Option<&'c Image>)> {
graph
.nodes
.iter()
.filter(|n| n.def == "output")
.map(|n| {
let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0).clamp(0, materialcraft_nodes::atomic::USAGE_IDS.len() as i32 - 1) as usize;
(n.id, materialcraft_nodes::atomic::USAGE_IDS.get(usage).copied().unwrap_or("any"), identifier(n), cooked.image(n.id, 0))
})
.collect()
}
/// Milliseconds since the first call (0 on the web, where `std::time::Instant` is unavailable)
pub fn now_ms() -> f64 {
#[cfg(not(target_arch = "wasm32"))]
{
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0
}
#[cfg(target_arch = "wasm32")]
0.0
}
fn evaluate_value(
parameters: &BTreeMap<String, Value>,
variables: &BTreeMap<String, Value>,
seed: u32,
size: [u32; 2],
images: &[Option<Image>],
tile: bool,
) -> Result<Value, String> {
use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile};
let Some(Value::Function(graph)) = parameters.get("function") else {
return Err("missing value function".into());
};
let program = compile(graph, seed)?;
let context = EvaluationContext { position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables };
program.evaluate(&context, &mut EvaluationState::default())
}
fn variable_key(node: &Node, parameters: &BTreeMap<String, Value>, variables: &BTreeMap<String, Value>) -> u64 {
let mut names = std::collections::BTreeSet::new();
let mut pending: Vec<&Value> = parameters.values().collect();
while let Some(value) = pending.pop() {
match value {
Value::Function(graph) => {
for function in &graph.nodes {
if (function.op.starts_with("get_") || function.op == "isdefined")
&& let Some(Value::Text(name)) = &function.value
{
names.insert(name.as_str());
}
}
}
Value::PatternGraph(graph) => {
pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values()));
}
_ => {}
}
}
let input_identifier = identifier(node);
if node.def == "input_value" {
names.insert(&input_identifier);
}
let mut hasher = DefaultHasher::new();
for name in names {
name.hash(&mut hasher);
variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher);
}
hasher.finish()
cooked.ms = (now_ms() - started_ms) as f32;
cooked
}
+71
View File
@@ -0,0 +1,71 @@
use crate::{Cache, MAX_DEPTH, Options, Port, cook, identifier, instance_graph};
use materialcraft_core::{Node, Package, Value};
use materialcraft_image::{Image, Kind};
use std::{
collections::{BTreeMap, HashSet},
sync::Mutex,
};
/// Whether graph `from` reaches `target`, without recursive stack growth
pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool {
let mut pending = vec![from];
let mut seen = HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
let Some(graph) = pkg.graphs.get(index) else { continue };
for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) {
if si == target {
return true;
}
pending.push(si);
}
}
false
}
pub(crate) fn cook_instance(
pkg: &Package,
gi: usize,
node: &Node,
in_ports: &[Port],
out_ports: &[Port],
inputs: &[Option<Image>],
params: &BTreeMap<String, Value>,
size: (u32, u32),
opts: &Options,
cache: &Mutex<Cache>,
) -> Result<Vec<Image>, String> {
if opts.depth >= MAX_DEPTH {
return Err("graph instances nest too deep (does a graph use itself?)".into());
}
let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?;
if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) {
return Err(format!("graph `{}` uses itself through a graph instance", sub.name));
}
let mut o = Options::new(opts.resource);
o.max_size = opts.max_size;
o.cancel = opts.cancel;
o.depth = opts.depth + 1;
o.graph_stack = opts.graph_stack.clone();
o.graph_stack.push(gi);
o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect();
o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect();
let cooked = cook(pkg, sub_gi, &o, cache);
if cooked.cancelled {
return Err("cancelled".into());
}
Ok(out_ports
.iter()
.map(|p| {
sub.nodes
.iter()
.find(|n| n.def == "output" && identifier(n) == p.id)
.and_then(|n| cooked.image(n.id, 0))
.map(|i| i.resize(size.0, size.1, true))
.unwrap_or_else(|| Image::filled(size.0, size.1, Kind::Gray, [0.0; 4]))
})
.collect())
}
+17
View File
@@ -0,0 +1,17 @@
use crate::{Cooked, identifier};
use materialcraft_core::{ComponentUsage, Graph, Node, NodeId, Value};
pub fn output_usage(node: &Node) -> &'static str {
let index = match node.params.get("usage") {
None => 0,
Some(Value::Enum(index)) => *index,
Some(value) => value.as_i32().map_or(ComponentUsage::ANY_INDEX, |index| index.max(0) as u32),
};
ComponentUsage::from_index(index).id
}
use materialcraft_image::Image;
/// The graph's output nodes with their usage id and image, in node order
pub fn outputs<'c>(graph: &Graph, cooked: &'c Cooked) -> Vec<(NodeId, &'static str, String, Option<&'c Image>)> {
graph.nodes.iter().filter(|n| n.def == "output").map(|n| (n.id, output_usage(n), identifier(n), cooked.image(n.id, 0))).collect()
}
+14 -2
View File
@@ -5,21 +5,33 @@ mod cache;
mod cache_key;
mod cooked;
mod graph_execution;
mod graph_instance;
mod graph_output;
mod node_execution;
mod node_output;
mod node_result;
mod node_size;
mod options;
mod parameter;
mod port;
mod ports;
mod prepared_graph;
mod time;
mod value_execution;
mod value_input_label;
pub use cache::Cache;
pub use cooked::Cooked;
pub use graph_execution::{cook, error_image, now_ms, outputs};
pub use graph_execution::cook;
pub use graph_output::{output_usage, outputs};
pub use node_execution::error_image;
pub use node_output::NodeOutput;
pub use node_result::NodeResult;
pub use node_size::node_size;
pub use options::Options;
pub use port::{Port, identifier, instance_graph, ports};
pub use port::Port;
pub use ports::{identifier, instance_graph, ports, ports_with_connections};
pub use time::now_ms;
pub use value_input_label::value_input_label;
pub const MAX_DEPTH: u32 = 8;
+158
View File
@@ -0,0 +1,158 @@
use crate::{Cache, Cooked, NodeOutput, NodeResult, Options, identifier, instance_graph, node_size, now_ms};
use crate::{
cache_key::{graph_tree_hash, hash_of, image_key, variable_key},
graph_instance::cook_instance,
parameter::resolve_parameters,
prepared_graph::PreparedGraph,
value_execution::evaluate_value,
};
use materialcraft_core::{Graph, Node, Package, Value};
use materialcraft_image::{Image, Kind};
use materialcraft_nodes::{CookContext, find};
use std::{
collections::BTreeMap,
sync::{Arc, Mutex},
};
/// The magenta image a failed node shows
pub fn error_image(w: u32, h: u32) -> Image {
Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0])
}
/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written)
fn lock(cache: &Mutex<Cache>) -> std::sync::MutexGuard<'_, Cache> {
cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn cook_node(
pkg: &Package,
gi: usize,
graph: &Graph,
prepared: &PreparedGraph<'_>,
node: &Node,
done: &Cooked,
vars: &BTreeMap<String, Value>,
opts: &Options,
cache: &Mutex<Cache>,
) -> NodeResult {
let (in_ports, out_ports) = prepared.ports(node.id);
let def = find(&node.def);
// Gather inputs by port order, with their keys
let mut inputs = Vec::new();
let mut incoming = Vec::new();
let mut input_keys = Vec::new();
let mut variables = std::borrow::Cow::Borrowed(vars);
let mut input_error = None;
for port in in_ports {
let source = prepared.index.input_of(node.id, &port.id).and_then(|connection| {
let result = done.nodes.get(&connection.from)?;
let index = prepared.ports(connection.from).1.iter().position(|output| output.id == connection.from_port)?;
Some((result.outputs.get(index)?, result.key ^ hash_of(&index)))
});
input_keys.push(source.as_ref().map_or(0, |source| source.1));
let output = source.map(|source| source.0);
if let Some(expected) = node.input_values.get(&port.id) {
let value = match output.as_ref() {
Some(NodeOutput::Value(value)) if materialcraft_core::ValueType::of(value) == Some(*expected) => value.clone(),
Some(_) => {
input_error = Some(format!("input `{}` requires {}", port.id, expected.label()));
expected.default_value()
}
None => expected.default_value(),
};
variables.to_mut().insert(port.id.clone(), value);
} else {
if output.as_ref().is_some_and(|output| output.as_value().is_some()) && !matches!(node.def.as_str(), "output" | "dot") {
input_error = Some(format!("input `{}` requires an image", port.id));
}
inputs.push(output.and_then(NodeOutput::as_image).cloned());
}
incoming.push(output);
}
let vars = &variables;
let first = inputs.iter().flatten().next().map(|i| (i.w, i.h));
let (w, h) = node_size(graph, def, node, first, opts.max_size);
let fail = |msg: String, key: u64| NodeResult {
outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); out_ports.len().max(1)]),
error: Some(msg),
ms: 0.0,
key,
cached: false,
};
if let Some(error) = input_error {
return fail(error, 0);
}
let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32);
let params = match resolve_parameters(node, def, vars, seed, [w, h]) {
Ok(parameters) => parameters,
Err(error) => return fail(error, 0),
};
let tile = node.base.tiling[0] && node.base.tiling[1];
// Input nodes read the caller's image for their identifier
let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten();
let res_hash = match params.get("resource") {
Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()),
_ => 0,
};
let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 };
let key = hash_of(&(
&node.def,
serde_json::to_string(&params).unwrap_or_default(),
(w, h, seed, tile, node.disabled),
&input_keys,
res_hash,
sub_hash,
input_img.map(image_key),
variable_key(node, &params, vars),
));
if let Some(v) = lock(cache).get(key) {
return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true };
}
let t0 = now_ms();
let result: Result<Vec<NodeOutput>, String> = if node.disabled {
let output = incoming.iter().find_map(|output| *output).cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4])));
Ok(vec![output; out_ports.len().max(1)])
} else if node.def == "input_value" {
let value = vars.get(&identifier(node)).or_else(|| params.get("default")).cloned().unwrap_or(Value::Float(0.0));
Ok(vec![NodeOutput::Value(value)])
} else if node.def == "value_processor" {
evaluate_value(&params, vars, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)])
} else if matches!(node.def.as_str(), "output" | "dot") && incoming.first().and_then(Option::as_ref).is_some_and(|output| output.as_value().is_some()) {
incoming.first().copied().flatten().cloned().map(|output| vec![output]).ok_or("missing value input".into())
} else if let Some(image) = input_img {
let image = image.resize(w, h, tile);
let image = if node.def == "input_grayscale" { image.to_gray() } else { image };
Ok(vec![NodeOutput::Image(image)])
} else if node.def == materialcraft_core::MISSING_NODE {
let name = if node.label.is_empty() { "this node" } else { node.label.as_str() };
Err(format!("unsupported node `{name}`"))
} else if node.def == "graph_instance" {
cook_instance(pkg, gi, node, in_ports, out_ports, &inputs, &params, (w, h), opts, cache)
.map(|images| images.into_iter().map(NodeOutput::Image).collect())
} else if let Some(definition) = def {
let context = CookContext { w, h, seed, tile, inputs: &inputs, params: &params, resource: opts.resource, vars };
(definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect())
} else {
Err(format!("unknown node `{}`", node.def))
};
match result {
Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => {
let v = Arc::new(imgs);
lock(cache).put(key, v.clone());
NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false }
}
Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key),
Err(e) => fail(e, key),
}
}
+58
View File
@@ -0,0 +1,58 @@
use materialcraft_core::{Node, Value};
use materialcraft_nodes::{NodeDefinition, clamp_params, resolve_params};
use std::collections::BTreeMap;
pub(crate) fn resolve_parameters(
node: &Node,
def: Option<&NodeDefinition>,
vars: &BTreeMap<String, Value>,
seed: u32,
size: [u32; 2],
) -> Result<BTreeMap<String, Value>, String> {
// Parameters: defaults, overrides, then bindings to exposed inputs
let mut params = match def {
Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params),
_ => node.params.clone(),
};
for (param, exposed) in &node.bindings {
if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param))
&& let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default())
{
params.insert(param.clone(), c);
}
}
// Dynamic parameters: functions of the graph's inputs, evaluated once per cook
for (param, f) in &node.functions {
let Some(cur) = params.get(param) else { continue };
match materialcraft_nodes::function::compile(f, seed) {
Ok(prog) => {
let context = materialcraft_nodes::function::EvaluationContext {
position: [0.5; 2],
size: size.map(|side| side as f32),
images: &[],
tile: true,
variables: vars,
};
let value = match prog.evaluate(&context, &mut materialcraft_nodes::function::EvaluationState::default()) {
Ok(value) => value,
Err(error) => return Err(format!("function of `{param}`: {error}")),
};
if let Some(c) = cur.coerce_json(&serde_json::to_value(value).unwrap_or_default()) {
params.insert(param.clone(), c);
}
}
Err(e) => return Err(format!("function of `{param}`: {e}")),
}
}
// Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook)
if let Some(d) = def
&& node.def != "graph_instance"
{
clamp_params(d, &mut params);
}
Ok(params)
}
+1 -87
View File
@@ -1,5 +1,4 @@
use materialcraft_core::{Graph, Node, Package, Value};
use materialcraft_nodes::{PortKind, find};
use materialcraft_nodes::PortKind;
#[derive(Clone, Debug, PartialEq)]
pub struct Port {
@@ -7,88 +6,3 @@ pub struct Port {
pub label: String,
pub kind: PortKind,
}
/// The input and output ports of a node in its package
pub fn ports(package: &Package, graph: &Graph, node: &Node) -> (Vec<Port>, Vec<Port>) {
if node.def == "graph_instance" {
let Some((_, graph)) = instance_graph(package, node) else {
return (Vec::new(), Vec::new());
};
let graph_ports = |definition: &str| -> Vec<Port> {
graph
.nodes
.iter()
.filter(|node| node.def == definition || (definition == "input" && node.def.starts_with("input_")))
.map(|node| {
let id = identifier(node);
let kind = match node.def.as_str() {
"input_grayscale" => PortKind::Gray,
"input_color" => PortKind::Color,
_ => PortKind::Any,
};
Port { label: id.clone(), id, kind }
})
.collect()
};
return (graph_ports("input"), graph_ports("output"));
}
if node.def == materialcraft_core::MISSING_NODE {
let (inputs, outputs) = materialcraft_core::missing_ports(node);
let inputs = inputs.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect();
let outputs =
outputs.into_iter().map(|(id, grayscale)| Port { label: id.clone(), id, kind: if grayscale { PortKind::Gray } else { PortKind::Color } }).collect();
return (inputs, outputs);
}
let Some(definition) = find(&node.def) else {
return (Vec::new(), Vec::new());
};
let catalog_port = |port: &materialcraft_nodes::PortDefinition| Port { id: port.id.into(), label: port.label.into(), kind: port.kind };
let mut inputs: Vec<Port> = node
.input_values
.iter()
.map(|(identifier, value_type)| Port {
id: identifier.clone(),
label: format!("{} ({})", crate::value_input_label(identifier), value_type.label()),
kind: PortKind::Value,
})
.collect();
inputs.extend(definition.inputs.iter().map(catalog_port));
if let Some(prefix) = materialcraft_nodes::image_input_prefix(&node.def) {
let count = graph
.connections
.iter()
.filter(|connection| connection.to == node.id)
.filter_map(|connection| connection.to_port.strip_prefix(prefix)?.parse::<usize>().ok())
.filter(|index| *index < materialcraft_nodes::MAX_IMAGE_INPUTS)
.map(|index| index + 2)
.max()
.unwrap_or(1)
.min(materialcraft_nodes::MAX_IMAGE_INPUTS);
inputs.extend((1..count).map(|index| Port { id: format!("{prefix}{index}"), label: format!("Input image {index}"), kind: PortKind::Any }));
}
(inputs, definition.outputs.iter().map(catalog_port).collect())
}
/// The graph a graph-instance node refers to
pub fn instance_graph<'a>(pkg: &'a Package, node: &Node) -> Option<(usize, &'a Graph)> {
match node.params.get("graph") {
Some(Value::Text(name)) => pkg.graph_by_name(name),
_ => None,
}
}
/// An input or output node's identifier (its `identifier` parameter, default "input"/"output")
pub fn identifier(n: &Node) -> String {
match n.params.get("identifier") {
Some(Value::Text(s)) if !s.is_empty() => s.clone(),
_ => if n.def == "output" { "output" } else { "input" }.into(),
}
}
+95
View File
@@ -0,0 +1,95 @@
use crate::Port;
use materialcraft_core::{Graph, Node, Package, Value};
use materialcraft_nodes::{PortKind, find};
/// The input and output ports of a node in its package
pub fn ports(package: &Package, graph: &Graph, node: &Node) -> (Vec<Port>, Vec<Port>) {
ports_with_connections(package, node, graph.connections.iter().filter(|connection| connection.to == node.id))
}
/// Resolve ports using the node's incoming connections in document order
pub fn ports_with_connections<'a>(
package: &Package,
node: &Node,
incoming: impl IntoIterator<Item = &'a materialcraft_core::Connection>,
) -> (Vec<Port>, Vec<Port>) {
if node.def == "graph_instance" {
let Some((_, graph)) = instance_graph(package, node) else {
return (Vec::new(), Vec::new());
};
let graph_ports = |definition: &str| -> Vec<Port> {
graph
.nodes
.iter()
.filter(|node| node.def == definition || (definition == "input" && node.def.starts_with("input_")))
.map(|node| {
let id = identifier(node);
let kind = match node.def.as_str() {
"input_grayscale" => PortKind::Gray,
"input_color" => PortKind::Color,
_ => PortKind::Any,
};
Port { label: id.clone(), id, kind }
})
.collect()
};
return (graph_ports("input"), graph_ports("output"));
}
if node.def == materialcraft_core::MISSING_NODE {
let (inputs, outputs) = materialcraft_core::missing_ports(node);
let inputs = inputs.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect();
let outputs =
outputs.into_iter().map(|(id, grayscale)| Port { label: id.clone(), id, kind: if grayscale { PortKind::Gray } else { PortKind::Color } }).collect();
return (inputs, outputs);
}
let Some(definition) = find(&node.def) else {
return (Vec::new(), Vec::new());
};
let catalog_port = |port: &materialcraft_nodes::PortDefinition| Port { id: port.id.into(), label: port.label.into(), kind: port.kind };
let mut inputs: Vec<Port> = node
.input_values
.iter()
.map(|(identifier, value_type)| Port {
id: identifier.clone(),
label: format!("{} ({})", crate::value_input_label(identifier), value_type.label()),
kind: PortKind::Value,
})
.collect();
inputs.extend(definition.inputs.iter().map(catalog_port));
if let Some(prefix) = materialcraft_nodes::image_input_prefix(&node.def) {
let count = incoming
.into_iter()
.filter_map(|connection| connection.to_port.strip_prefix(prefix)?.parse::<usize>().ok())
.filter(|index| *index < materialcraft_nodes::MAX_IMAGE_INPUTS)
.map(|index| index + 2)
.max()
.unwrap_or(1)
.min(materialcraft_nodes::MAX_IMAGE_INPUTS);
inputs.extend((1..count).map(|index| Port { id: format!("{prefix}{index}"), label: format!("Input image {index}"), kind: PortKind::Any }));
}
(inputs, definition.outputs.iter().map(catalog_port).collect())
}
/// The graph a graph-instance node refers to
pub fn instance_graph<'a>(pkg: &'a Package, node: &Node) -> Option<(usize, &'a Graph)> {
match node.params.get("graph") {
Some(Value::Text(name)) => pkg.graph_by_name(name),
_ => None,
}
}
/// An input or output node's identifier (its `identifier` parameter, default "input"/"output")
pub fn identifier(n: &Node) -> String {
match n.params.get("identifier") {
Some(Value::Text(s)) if !s.is_empty() => s.clone(),
_ => if n.def == "output" { "output" } else { "input" }.into(),
}
}
+31
View File
@@ -0,0 +1,31 @@
use crate::{Port, ports_with_connections};
use materialcraft_core::{Graph, GraphIndex, NodeId, Package};
use std::collections::BTreeMap;
/// Port definitions resolved once for a cook, alongside borrowed graph lookups
pub(crate) struct PreparedGraph<'a> {
pub index: GraphIndex<'a>,
pub order: Vec<NodeId>,
ports: BTreeMap<NodeId, (Vec<Port>, Vec<Port>)>,
}
impl<'a> PreparedGraph<'a> {
pub fn new(package: &Package, graph: &'a Graph, roots: Option<&[NodeId]>) -> Self {
let index = GraphIndex::new(graph);
let needed = roots.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()
.filter_map(|id| {
let node = index.node(*id)?;
Some((*id, ports_with_connections(package, node, index.incoming(*id).iter().copied())))
})
.collect();
Self { index, order, ports }
}
pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) {
self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice()))
}
}
+30 -1
View File
@@ -1,4 +1,4 @@
use crate::graph_execution::{graph_tree_hash, instances_reach};
use crate::{cache_key::graph_tree_hash, graph_instance::instances_reach};
use materialcraft_core::{NodeId, Package, Value};
use materialcraft_image::{Image, Kind};
use std::sync::Mutex;
@@ -242,3 +242,32 @@ fn input_change_recooks_only_readers() {
}
assert!(!second.nodes[&reader].cached, "the reader must re-cook");
}
#[test]
fn partial_cooks_keep_shared_dependencies_and_first_duplicate_node() {
let mut graph = Graph::new("Partial cook");
graph.size = [4, 4];
let source = graph.add_node("uniform", [0.0; 2]);
let first = graph.add_node("dot", [0.0; 2]);
let second = graph.add_node("dot", [0.0; 2]);
let unrelated = graph.add_node("uniform", [0.0; 2]);
graph.connect(source, "output", first, "input").unwrap();
graph.connect(source, "output", second, "input").unwrap();
let mut duplicate = graph.node(source).unwrap().clone();
duplicate.def = "input_value".into();
graph.nodes.push(duplicate);
let mut package = Package::new("Partial cook");
package.graphs.push(graph);
let cache = Mutex::new(Cache::default());
let mut options = Options::new(&no_res);
options.only = Some(vec![first, second]);
let cooked = cook(&package, 0, &options, &cache);
assert_eq!(cooked.nodes.len(), 3);
assert!(!cooked.nodes.contains_key(&unrelated));
for id in [source, first, second] {
assert!(cooked.nodes[&id].error.is_none());
assert!(cooked.image(id, 0).is_some());
}
}
+10
View File
@@ -0,0 +1,10 @@
/// Milliseconds since the first call (0 on the web, where `std::time::Instant` is unavailable)
pub fn now_ms() -> f64 {
#[cfg(not(target_arch = "wasm32"))]
{
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0
}
#[cfg(target_arch = "wasm32")]
0.0
}
+23
View File
@@ -0,0 +1,23 @@
use materialcraft_core::Value;
use materialcraft_image::Image;
use std::collections::BTreeMap;
pub(crate) fn evaluate_value(
parameters: &BTreeMap<String, Value>,
variables: &BTreeMap<String, Value>,
seed: u32,
size: [u32; 2],
images: &[Option<Image>],
tile: bool,
) -> Result<Value, String> {
use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile};
let Some(Value::Function(graph)) = parameters.get("function") else {
return Err("missing value function".into());
};
let program = compile(graph, seed)?;
let context = EvaluationContext { position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables };
program.evaluate(&context, &mut EvaluationState::default())
}
+14 -1
View File
@@ -16,7 +16,20 @@ const SOURCE: &str = "source.sbs";
/// Whether maps of `usage` hold colors (stored sRGB-encoded) rather than data (linear)
pub fn srgb_usage(usage: &str) -> bool {
matches!(usage, "baseColor" | "emissive" | "specular")
matches!(
usage,
"baseColor"
| "diffuse"
| "emissive"
| "specular"
| "specularEdgeColor"
| "scatteringColor"
| "absorptionColor"
| "coatColor"
| "sheenColor"
| "reflection"
| "ambient"
)
}
/// Whether other apps can set a value of this type from the manifest
+42
View File
@@ -1,6 +1,10 @@
use super::sbs_writer::SbsWriter;
use super::warnings::Warnings;
use super::xml::{child_element, child_value, children_named, parse_floats};
use super::xml::{format_float, xml_escape};
use materialcraft_core::{Comment, Frame, Pin, srgb_to_linear};
use materialcraft_core::{Graph, linear_to_srgb};
use roxmltree::Node as XmlNode;
use std::fmt::Write as _;
pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mut SbsWriter) {
@@ -43,3 +47,41 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu
output.push_str("</GUIObjects>");
}
pub(super) fn read_canvas_items(element: XmlNode, graph: &mut Graph, warnings: &mut Warnings) {
for item in child_element(element, "GUIObjects").into_iter().flat_map(|objects| children_named(objects, "GUIObject")) {
let layout = child_element(item, "GUILayout");
let position = layout.and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default();
let size = layout.and_then(|layout| child_value(layout, "size")).map(parse_floats).unwrap_or_default();
let x = position.first().copied().unwrap_or(0.0);
let y = position.get(1).copied().unwrap_or(0.0);
let width = size.first().copied().unwrap_or(180.0).max(8.0);
let height = size.get(1).copied().unwrap_or(70.0).max(8.0);
let text = child_value(item, "GUIName").unwrap_or("").to_string();
match child_value(item, "type") {
Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => {
let channels = child_value(item, "frameColor").map(parse_floats).unwrap_or_default();
let color = match channels.as_slice() {
&[red, green, blue, alpha, ..] => [srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha],
_ => [0.2, 0.4, 0.8, 0.25],
};
let title = child_value(item, "title").unwrap_or("").to_string();
let title_visible = child_value(item, "isTitleVisible") != Some("0");
let id = graph.alloc_id();
graph.frames.push(Frame { id, title, title_visible, description: text, rect: [x, y, width, height], color });
}
Some("COMMENT") => {
let id = graph.alloc_id();
graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] });
}
Some("PIN") => {
let id = graph.alloc_id();
graph.pins.push(Pin { id, name: text, pos: [x, y] });
}
Some(other) => warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)),
None => {}
}
}
}
+22
View File
@@ -0,0 +1,22 @@
use materialcraft_core::{ComponentUsage, Node, Value};
use roxmltree::Node as XmlNode;
use std::fmt::Write as _;
use super::xml::{child_element, child_value};
pub(super) fn read(element: XmlNode) -> u32 {
child_element(element, "usages")
.and_then(|usages| child_element(usages, "usage"))
.and_then(|usage| child_value(usage, "name"))
.map_or(ComponentUsage::ANY_INDEX, ComponentUsage::index)
}
pub(super) fn write(out: &mut String, node: &Node, default: u32) {
let index = match node.params.get("usage") {
None => default,
Some(Value::Enum(index)) => *index,
Some(value) => value.as_i32().map_or(ComponentUsage::ANY_INDEX, |index| index.max(0) as u32),
};
let id = ComponentUsage::from_index(index).id;
let _ = write!(out, "<usages><usage><components v=\"RGBA\"/><name v=\"{id}\"/></usage></usages>");
}
+1
View File
@@ -3,5 +3,6 @@ use materialcraft_core::Value;
pub(super) struct InputBridge {
pub identifier: String,
pub type_code: u32,
pub usage: u32,
pub default: Value,
}
+6 -2
View File
@@ -1,5 +1,6 @@
mod base_parameters;
mod canvas;
mod component_usage;
mod connection;
mod constant;
mod embedded;
@@ -24,9 +25,12 @@ mod warnings;
mod xml;
pub use constant::SBS_EXT;
pub use read::{is_sbs, read_sbs};
pub use sbs_read::SbsRead;
pub use sbs_reader::{is_sbs, read_sbs};
pub use sbs_writer::write_sbs;
pub use write::write_sbs;
#[cfg(test)]
mod tests;
mod read;
mod write;
-10
View File
@@ -1,15 +1,5 @@
use materialcraft_nodes::PortKind;
pub(super) fn usage_index(name: &str) -> u32 {
let ids = materialcraft_nodes::atomic::USAGE_IDS;
let name = name.trim();
let index = ids.iter().position(|u| u.eq_ignore_ascii_case(name)).or_else(|| name.eq_ignore_ascii_case("diffuse").then_some(0));
index.unwrap_or(ids.len().saturating_sub(1)) as u32
}
pub(super) fn usage_name(index: u32) -> &'static str {
materialcraft_nodes::atomic::USAGE_IDS.get(index as usize).copied().unwrap_or("any")
}
pub(super) fn output_type(graph: &materialcraft_core::Graph, id: materialcraft_core::NodeId, port: &str) -> u32 {
if let Ok(Some(kind)) = materialcraft_nodes::output_value_type(graph, id) {
return kind as u32;
+99
View File
@@ -0,0 +1,99 @@
use super::{
constant::{MAX_GRAPHS, MAX_SBS_BYTES, MAX_XML_NODES, SNIFF_BYTES},
placeholder::report_placeholders,
sbs_read::SbsRead,
sbs_reader::{SbsReader, unique_name},
warnings::Warnings,
xml::{child_element, child_value, children_named},
};
use crate::{FormatError, Result};
use materialcraft_core::{Graph, Package};
use roxmltree::Node as XmlNode;
use std::collections::HashMap;
pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<SbsRead> {
if bytes.len() > MAX_SBS_BYTES {
return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20)));
}
let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?;
let text = text.trim_start_matches('\u{feff}');
let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES };
let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?;
let root = doc.root_element();
if root.tag_name().name() != "package" {
return Err(FormatError::BadPackage("not an SBS package (the root element is not <package>)".into()));
}
let mut warnings = Warnings::default();
let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name);
let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim();
let package_name = match child_value(root, "identifier").map(str::trim) {
Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(),
_ if !file_stem.is_empty() => file_stem.to_string(),
_ => "Untitled package".to_string(),
};
let mut reader =
SbsReader { text, warnings: &mut warnings, dependencies: HashMap::new(), graph_names: HashMap::new(), resource_names: HashMap::new(), node_count: 0 };
for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) {
if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) {
reader.dependencies.insert(uid.to_string(), file.to_string());
}
}
// Load resources before resolving graph references
let content = child_element(root, "content");
let mut pkg = Package::new(&package_name);
let mut graph_elements: Vec<(String, XmlNode)> = Vec::new();
if let Some(content) = content {
reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked);
}
// Name every graph first so instances can refer to graphs defined later in the file
let mut names: Vec<String> = 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);
}
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);
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() })
}
pub fn is_sbs(bytes: &[u8]) -> bool {
let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]);
let mut rest = head.trim_start_matches('\u{feff}');
// Skip the XML declaration and comments before the root element
loop {
rest = rest.trim_start();
let (skip_open, skip_close) = if rest.starts_with("<?") {
("<?", "?>")
} else if rest.starts_with("<!--") {
("<!--", "-->")
} else {
break;
};
match rest[skip_open.len()..].find(skip_close) {
Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..],
None => return false,
}
}
rest.strip_prefix("<package").is_some_and(|after| after.starts_with(|c: char| c == '>' || c == '/' || c.is_whitespace()))
}
+23 -142
View File
@@ -1,23 +1,20 @@
use super::base_parameters::read_base_params;
use super::component_usage;
use super::connection::connect_all;
use super::constant::{MAX_GRAPHS, MAX_NODES, MAX_RESOURCES, MAX_SBS_BYTES, MAX_XML_NODES};
use super::constant::{NODE_HALF_SIZE, SELF_DEPENDENCY, SNIFF_BYTES};
use super::constant::{MAX_NODES, MAX_RESOURCES};
use super::constant::{NODE_HALF_SIZE, SELF_DEPENDENCY};
use super::embedded::decode_embedded;
use super::filter_map::{BASE_PARAMS, FilterMap, HANDLED_PARAMS, filter_by_sbs_name};
use super::function_graph;
use super::input_bridge::InputBridge;
use super::output::usage_index;
use super::placeholder::{add_placeholder_input, fill_placeholder, placeholder_outputs, report_placeholders};
use super::placeholder::{add_placeholder_input, fill_placeholder, placeholder_outputs};
use super::read_node::ReadNode;
use super::sbs_read::SbsRead;
use super::sbs_value::{SbsValue, exposed_default, sbs_constant, to_natural_value, to_param_value};
use super::type_code;
use super::warnings::Warnings;
use super::xml::{child_element, child_value, children_named, parse_floats};
use crate::{FormatError, Result};
use materialcraft_core::{
Comment, Connection, ExposedParameter, Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Pin, Resource, ResourceBytes,
Value, srgb_to_linear,
ComponentUsage, Connection, ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Resource, ResourceBytes, Value,
};
use materialcraft_nodes::find;
use roxmltree::Node as XmlNode;
@@ -100,10 +97,12 @@ impl<'text> SbsReader<'text, '_> {
match bytes {
Some(data) => {
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)));
}
None => {
let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing };
self.warnings.add(format!("resource `{path}` could not be loaded: {why}"));
}
}
@@ -150,7 +149,7 @@ impl<'text> SbsReader<'text, '_> {
}
});
if let Some(dynamic) = dynamic {
self.read_canvas_items(dynamic, &mut graph);
super::canvas::read_canvas_items(dynamic, &mut graph, self.warnings);
}
return graph;
}
@@ -167,6 +166,7 @@ impl<'text> SbsReader<'text, '_> {
}
let Some(uid) = child_value(*comp_node, "uid").map(str::to_string) else { continue };
if read_nodes.contains_key(&uid) {
self.warnings.add(format!("graph `{name}`: duplicate node uid {uid} skipped"));
continue;
@@ -189,7 +189,7 @@ impl<'text> SbsReader<'text, '_> {
let wires = self.read_wires(&mut graph, &comp_nodes, &read_nodes);
connect_all(&mut graph, wires, self.warnings);
self.read_canvas_items(element, &mut graph);
super::canvas::read_canvas_items(element, &mut graph, self.warnings);
graph
}
pub(super) fn read_graph_inputs(&mut self, element: XmlNode, graph: &mut Graph) -> HashMap<String, InputBridge> {
@@ -202,7 +202,10 @@ impl<'text> SbsReader<'text, '_> {
.and_then(sbs_constant)
.and_then(|value| to_param_value(&Value::Color([0.5, 0.5, 0.5, 1.0]), &value, 0))
.unwrap_or(Value::Color([0.5, 0.5, 0.5, 1.0]));
image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), InputBridge { identifier: id, type_code: code as u32, default });
image_inputs.insert(
child_value(input, "uid").unwrap_or("").to_string(),
InputBridge { identifier: id, type_code: code as u32, usage: component_usage::read(input), default },
);
continue;
}
if graph.exposed.iter().any(|e| e.id == id) {
@@ -211,7 +214,10 @@ impl<'text> SbsReader<'text, '_> {
let default = exposed_default(code, child_element(input, "defaultValue").and_then(sbs_constant).as_ref());
if child_value(input, "isConnectable") == Some("1") {
image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), InputBridge { identifier: id, type_code: code as u32, default });
image_inputs.insert(
child_value(input, "uid").unwrap_or("").to_string(),
InputBridge { identifier: id, type_code: code as u32, usage: component_usage::read(input), default },
);
continue;
}
let label = child_element(input, "attributes").and_then(|a| child_value(a, "label")).filter(|l| !l.is_empty()).unwrap_or(&id).to_string();
@@ -238,6 +244,7 @@ impl<'text> SbsReader<'text, '_> {
for comp_node in comp_nodes {
let Some(to) = child_value(*comp_node, "uid").and_then(|u| read_nodes.get(u)) else { continue };
for connection in child_element(*comp_node, "connections").into_iter().flat_map(|c| children_named(c, "connection")) {
let sbs_input = child_value(connection, "identifier").unwrap_or("");
let Some(from) = child_value(connection, "connRef").and_then(|u| read_nodes.get(u)) else {
@@ -275,44 +282,6 @@ impl<'text> SbsReader<'text, '_> {
wires
}
pub(super) fn read_canvas_items(&mut self, element: XmlNode, graph: &mut Graph) {
for item in child_element(element, "GUIObjects").into_iter().flat_map(|objects| children_named(objects, "GUIObject")) {
let layout = child_element(item, "GUILayout");
let position = layout.and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default();
let size = layout.and_then(|layout| child_value(layout, "size")).map(parse_floats).unwrap_or_default();
let x = position.first().copied().unwrap_or(0.0);
let y = position.get(1).copied().unwrap_or(0.0);
let width = size.first().copied().unwrap_or(180.0).max(8.0);
let height = size.get(1).copied().unwrap_or(70.0).max(8.0);
let text = child_value(item, "GUIName").unwrap_or("").to_string();
match child_value(item, "type") {
Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => {
let channels = child_value(item, "frameColor").map(parse_floats).unwrap_or_default();
let color = match channels.as_slice() {
&[red, green, blue, alpha, ..] => [srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha],
_ => [0.2, 0.4, 0.8, 0.25],
};
let title = child_value(item, "title").unwrap_or("").to_string();
let title_visible = child_value(item, "isTitleVisible") != Some("0");
let id = graph.alloc_id();
graph.frames.push(Frame { id, title, title_visible, description: text, rect: [x, y, width, height], color });
}
Some("COMMENT") => {
let id = graph.alloc_id();
graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] });
}
Some("PIN") => {
let id = graph.alloc_id();
graph.pins.push(Pin { id, name: text, pos: [x, y] });
}
Some(other) => self.warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)),
None => {}
}
}
}
pub(super) fn read_node(
&mut self,
graph: &mut Graph,
@@ -354,6 +323,7 @@ impl<'text> SbsReader<'text, '_> {
if let Some(node) = node {
let identifier = input.map_or("input", |input| input.identifier.as_str());
node.params.insert("identifier".into(), Value::Text(identifier.to_string()));
node.params.insert("usage".into(), Value::Enum(input.map_or(ComponentUsage::ANY_INDEX, |input| input.usage)));
if let Some(input) = input {
node.params.insert("default".into(), input.default.clone());
}
@@ -363,7 +333,7 @@ impl<'text> SbsReader<'text, '_> {
}
"compOutputBridge" => {
let output = child_value(implementation, "output").unwrap_or("");
let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), usage_index("any")));
let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), ComponentUsage::ANY_INDEX));
let (id, index, node) = push_node(graph, "output", pos);
if let Some(node) = node {
node.params.insert("identifier".into(), Value::Text(identifier));
@@ -465,6 +435,7 @@ impl<'text> SbsReader<'text, '_> {
}
let Some(dynamic) = child_element(param_value, "dynamicValue") else { return };
match function_graph::read(dynamic) {
Ok(graph) if matches!(like, Value::Function(_)) => {
node.params.insert(id.to_string(), Value::Function(Box::new(graph)));
@@ -513,93 +484,6 @@ impl<'text> SbsReader<'text, '_> {
}
}
}
pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<SbsRead> {
if bytes.len() > MAX_SBS_BYTES {
return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20)));
}
let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?;
let text = text.trim_start_matches('\u{feff}');
let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES };
let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?;
let root = doc.root_element();
if root.tag_name().name() != "package" {
return Err(FormatError::BadPackage("not an SBS package (the root element is not <package>)".into()));
}
let mut warnings = Warnings::default();
let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name);
let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim();
let package_name = match child_value(root, "identifier").map(str::trim) {
Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(),
_ if !file_stem.is_empty() => file_stem.to_string(),
_ => "Untitled package".to_string(),
};
let mut reader =
SbsReader { text, warnings: &mut warnings, dependencies: HashMap::new(), graph_names: HashMap::new(), resource_names: HashMap::new(), node_count: 0 };
for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) {
if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) {
reader.dependencies.insert(uid.to_string(), file.to_string());
}
}
// Load resources before resolving graph references
let content = child_element(root, "content");
let mut pkg = Package::new(&package_name);
let mut graph_elements: Vec<(String, XmlNode)> = Vec::new();
if let Some(content) = content {
reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked);
}
// Name every graph first so instances can refer to graphs defined later in the file
let mut names: Vec<String> = 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);
}
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);
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() })
}
pub fn is_sbs(bytes: &[u8]) -> bool {
let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]);
let mut rest = head.trim_start_matches('\u{feff}');
// Skip the XML declaration and comments before the root element
loop {
rest = rest.trim_start();
let (skip_open, skip_close) = if rest.starts_with("<?") {
("<?", "?>")
} else if rest.starts_with("<!--") {
("<!--", "-->")
} else {
break;
};
match rest[skip_open.len()..].find(skip_close) {
Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..],
None => return false,
}
}
rest.strip_prefix("<package").is_some_and(|after| after.starts_with(|c: char| c == '>' || c == '/' || c.is_whitespace()))
}
pub(super) fn unique_name(taken: &[String], base: &str) -> String {
let free = |name: &str| !taken.iter().any(|t| t == name);
if free(base) {
@@ -616,10 +500,7 @@ pub(super) fn read_graph_outputs(element: XmlNode) -> HashMap<String, (String, u
let mut outputs = HashMap::new();
for output in child_element(element, "graphOutputs").into_iter().flat_map(|o| children_named(o, "graphoutput")) {
let identifier = child_value(output, "identifier").unwrap_or("output").to_string();
let usage = child_element(output, "usages")
.and_then(|u| child_element(u, "usage"))
.and_then(|u| child_value(u, "name"))
.map_or(usage_index("any"), usage_index);
let usage = component_usage::read(output);
outputs.insert(child_value(output, "uid").unwrap_or("").to_string(), (identifier, usage));
}
outputs
+3 -14
View File
@@ -73,6 +73,7 @@ pub(super) fn to_param_value(like: &Value, value: &SbsValue, options: usize) ->
// SBS colors are stored as displayed (sRGB); MaterialCraft's are linear
Value::Color(_) if value.component_count() >= 3 => {
let alpha = if value.component_count() >= 4 { f(3) } else { 1.0 };
Value::Color([srgb_to_linear(f(0)), srgb_to_linear(f(1)), srgb_to_linear(f(2)), alpha])
}
Value::Color(_) => {
@@ -137,21 +138,9 @@ pub(super) fn exposed_default(code: i64, value: Option<&SbsValue>) -> Value {
}
pub(super) fn exposed_type_code(value: &Value) -> i64 {
use type_code::*;
match value {
Value::Bool(_) => BOOL,
Value::Int(_) | Value::Enum(_) => INT1,
Value::Int2(_) => INT2,
Value::Int3(_) => INT3,
Value::Int4(_) => INT4,
Value::Float(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => FLOAT1,
Value::Float2(_) => FLOAT2,
Value::Float3(_) => FLOAT3,
Value::Float4(_) | Value::Color(_) => FLOAT4,
Value::Text(_) => STRING,
}
materialcraft_core::ValueType::of(value).map_or(type_code::FLOAT1, |kind| i64::from(kind as u32))
}
pub(super) fn constant_xml(value: &Value) -> Option<String> {
let join = |xs: &[f32]| xs.iter().map(|x| format_float(*x)).collect::<Vec<_>>().join(" ");
let (tag, text) = match value {
+16 -66
View File
@@ -1,18 +1,17 @@
use super::base_parameters::base_params_xml;
use super::canvas::write_canvas_items;
use super::constant::FORMAT_VERSION;
use super::constant::{FIRST_UID, NODE_HALF_SIZE, SELF_DEPENDENCY};
use super::embedded::encode_embedded;
use super::component_usage;
use super::constant::NODE_HALF_SIZE;
use super::filter_map::filter_by_def;
use super::function_graph;
use super::node_identifiers::NodeIdentifiers;
use super::node_parameter::{param_xml, special_filter_params_xml, text_param};
use super::output::{output_type, usage_name};
use super::output::output_type;
use super::sbs_value::{constant_xml, exposed_type_code};
use super::type_code;
use super::xml::{format_float, is_parameters_element, xml_escape};
use crate::{FormatError, Result};
use materialcraft_core::{Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports};
use materialcraft_core::{ComponentUsage, Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports};
use materialcraft_nodes::find;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;
@@ -120,6 +119,7 @@ impl SbsWriter {
out.push_str("<connections>");
for wire in wires {
let Some(from_uid) = node_uids.get(&wire.from) else { continue };
let Some((_, _, output_uid)) = node_outputs.get(&wire.from).and_then(|o| o.iter().find(|(port, _, _)| *port == wire.from_port)) else {
continue;
};
@@ -169,6 +169,7 @@ impl SbsWriter {
let uid = self.next_uid();
entries.insert(node.id, uid);
let fallback = if node.def == "input_value" { Value::Float(0.0) } else { Value::Color([0.5, 0.5, 0.5, 1.0]) };
let value = node.params.get("default").unwrap_or(&fallback);
let default = constant_xml(value).unwrap_or_default();
let code = match node.def.as_str() {
@@ -179,14 +180,17 @@ impl SbsWriter {
let _ = write!(
out,
"<paraminput><identifier v=\"{}\"/><uid v=\"{uid}\"/><isConnectable v=\"1\"/><type v=\"{code}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"\"/><options/></defaultWidget></paraminput>",
"<paraminput><identifier v=\"{}\"/><uid v=\"{uid}\"/><isConnectable v=\"1\"/><type v=\"{code}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"\"/><options/></defaultWidget>",
xml_escape(&text_param(node, "identifier", "input"))
);
component_usage::write(out, node, ComponentUsage::ANY_INDEX);
out.push_str("</paraminput>");
}
for exposed in &graph.exposed {
let default = constant_xml(graph.inputs.get(&exposed.id).unwrap_or(&exposed.default)).unwrap_or_else(|| "<constantValueFloat1 v=\"0\"/>".into());
let group = if exposed.group.is_empty() { String::new() } else { format!("<group v=\"{}\"/>", xml_escape(&exposed.group)) };
let _ = write!(
out,
"<paraminput><identifier v=\"{}\"/><uid v=\"{}\"/><attributes><label v=\"{}\"/></attributes><type v=\"{}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"slider\"/><options><option><name v=\"min\"/><value v=\"{}\"/></option><option><name v=\"max\"/><value v=\"{}\"/></option></options></defaultWidget>{group}</paraminput>",
@@ -209,18 +213,19 @@ impl SbsWriter {
for node in graph.nodes.iter().filter(|n| n.def == "output") {
let uid = self.next_uid();
output_uids.insert(node.id, uid);
let usage = node.params.get("usage").and_then(Value::as_i32).unwrap_or(0).max(0) as u32;
let code = output_type(graph, node.id, "output");
let channels = format!("<channels v=\"{code}\"/>");
let identifier = text_param(node, "identifier", "output");
let label = if node.label.is_empty() { identifier.clone() } else { node.label.clone() };
let _ = write!(
out,
"<graphoutput><identifier v=\"{}\"/><uid v=\"{uid}\"/><attributes><label v=\"{}\"/></attributes><usages><usage><components v=\"RGBA\"/><name v=\"{}\"/></usage></usages><group v=\"Material\"/>{channels}</graphoutput>",
"<graphoutput><identifier v=\"{}\"/><uid v=\"{uid}\"/><attributes><label v=\"{}\"/></attributes>",
xml_escape(&identifier),
xml_escape(&label),
usage_name(usage)
xml_escape(&label)
);
component_usage::write(out, node, 0);
let _ = write!(out, "<group v=\"Material\"/>{channels}</graphoutput>");
}
out.push_str("</graphOutputs>");
@@ -276,6 +281,7 @@ impl SbsWriter {
let value_of = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default));
for (sbs_name, mc_name) in filter.params {
let Some(value) = value_of(mc_name) else { continue };
let binding =
node.bindings.get(*mc_name).map(|identifier| function_graph::binding(identifier, value)).transpose().map_err(FormatError::Io)?;
let function = node.functions.get(*mc_name).or(binding.as_ref()).or_else(|| match value {
@@ -311,62 +317,6 @@ impl SbsWriter {
Ok(())
}
}
pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> {
let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() };
let self_uid = writer.next_uid();
let mut content = String::from("<content>");
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, "<group><uid v=\"{}\"/><identifier v=\"Resources\"/><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,
"<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>",
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("</content></group>");
}
content.push_str("</content>");
let mut out = String::with_capacity(content.len() + 4096);
let _ = write!(
out,
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><package><identifier v=\"{}\"/><formatVersion v=\"{FORMAT_VERSION}\"/><updaterVersion v=\"{FORMAT_VERSION}\"/><fileUID v=\"0\"/><versionUID v=\"0\"/><dependencies>",
xml_escape(&pkg.name)
);
let write_dependency = |out: &mut String, file: &str, uid: u64| {
let _ = write!(
out,
"<dependency><filename v=\"{}\"/><uid v=\"{uid}\"/><type v=\"package\"/><fileUID v=\"0\"/><versionUID v=\"0\"/></dependency>",
xml_escape(file)
);
};
write_dependency(&mut out, SELF_DEPENDENCY, self_uid);
for (file, uid) in &writer.external_packages {
write_dependency(&mut out, file, *uid);
}
out.push_str("</dependencies>");
out.push_str(&content);
out.push_str("</package>\n");
Ok(out.into_bytes())
}
pub(super) type WrittenOutputs = Vec<(String, u32, u64)>;
pub(super) fn write_bridgings(out: &mut String, outputs: &[(String, u32, u64)]) {
+62 -2
View File
@@ -1,6 +1,6 @@
use super::embedded::{base64_engine, decode_embedded, encode_embedded};
use super::sbs_reader::{is_sbs, read_sbs};
use super::sbs_writer::write_sbs;
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};
@@ -81,6 +81,7 @@ fn structural_round_trip() {
assert_eq!(back.nodes[1].params.get("intensity"), Some(&Value::Float(4.5)));
let Some(Value::Color(color)) = back.nodes[2].params.get("color") else { panic!("uniform color") };
assert!((color[0] - 0.25).abs() < 1e-3 && (color[2] - 0.75).abs() < 1e-3);
assert_eq!(back.nodes[3].params.get("mode"), Some(&Value::Enum(3)));
assert_eq!(back.nodes[4].params.get("usage"), Some(&Value::Enum(4)));
@@ -242,6 +243,7 @@ fn native_function_fixture_retains_operation_types_and_ports() {
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
let back = read_sbs(&write_sbs(&read.pkg).unwrap(), "values.sbs", &no_linked_files).unwrap();
let Value::Function(function) = &back.pkg.graphs[0].nodes[0].params["function"] else { panic!("missing function") };
assert_eq!(function.nodes[0].value, Some(Value::Int(16_777_217)));
assert_eq!(function.nodes[2].op, "add");
assert_eq!(function.nodes[2].type_code, 16);
@@ -301,3 +303,61 @@ fn navigation_pins_round_trip_in_graphs_and_functions() {
assert_eq!(reopened.pkg.graphs[0].pins, *pins);
}
}
#[test]
fn component_usages_round_trip_without_reassigning_existing_indices() {
use materialcraft_core::ComponentUsage;
let original = ["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"];
for (index, id) in original.iter().enumerate() {
assert_eq!(ComponentUsage::from_index(index as u32).id, *id);
}
assert_eq!(ComponentUsage::from_index(u32::MAX), ComponentUsage::ANY);
assert_eq!(ComponentUsage::index("futureUsage"), ComponentUsage::ANY_INDEX);
assert_eq!(ComponentUsage::index(" DIFFUSE "), ComponentUsage::index("diffuse"));
let mut package = Package::new("Usage round trip");
let mut graph = Graph::new("Usages");
for definition in ["output", "input_color", "input_grayscale", "input_value"] {
for (index, usage) in ComponentUsage::ALL.iter().enumerate() {
let id = graph.add_node(definition, [index as f32 * 160.0, 0.0]);
graph
.node_mut(id)
.unwrap()
.params
.extend([("identifier".into(), Value::Text(format!("{definition}_{}", usage.id))), ("usage".into(), Value::Enum(index as u32))]);
}
}
package.graphs.push(graph);
let xml = write_sbs(&package).unwrap();
let restored = read_sbs(&xml, "usages.sbs", &no_linked_files).unwrap();
assert!(restored.warnings.is_empty(), "{:?}", restored.warnings);
assert_eq!(restored.pkg.graphs[0].nodes.len(), package.graphs[0].nodes.len());
for (original, node) in package.graphs[0].nodes.iter().zip(&restored.pkg.graphs[0].nodes) {
assert_eq!(node.def, original.def);
assert_eq!(node.params.get("usage"), original.params.get("usage"));
assert_eq!(node.params.get("identifier"), original.params.get("identifier"));
}
}
#[test]
fn input_usage_defaults_and_unknown_metadata_stay_unclassified() {
use materialcraft_core::ComponentUsage;
let mut package = Package::new("Input usages");
let mut graph = Graph::new("Inputs");
for definition in ["input_color", "input_grayscale", "input_value"] {
graph.add_node(definition, [0.0; 2]);
}
package.graphs.push(graph);
let saved = String::from_utf8(write_sbs(&package).unwrap()).unwrap();
let usage = "<usages><usage><components v=\"RGBA\"/><name v=\"any\"/></usage></usages>";
assert_eq!(saved.matches(usage).count(), 3);
for xml in [saved.clone(), saved.replace(usage, ""), saved.replace("<name v=\"any\"/>", "<name v=\"futureUsage\"/>")] {
let restored = read_sbs(xml.as_bytes(), "inputs.sbs", &no_linked_files).unwrap();
assert_eq!(restored.pkg.graphs[0].nodes.len(), 3);
for node in &restored.pkg.graphs[0].nodes {
assert_eq!(node.params.get("usage"), Some(&Value::Enum(ComponentUsage::ANY_INDEX)));
}
}
}
+12 -10
View File
@@ -1,12 +1,14 @@
use materialcraft_core::ValueType;
pub const COLOR_IMAGE: i64 = 1;
pub const GRAY_IMAGE: i64 = 2;
pub const BOOL: i64 = 4;
pub const INT1: i64 = 16;
pub const INT2: i64 = 32;
pub const INT3: i64 = 64;
pub const INT4: i64 = 128;
pub const FLOAT1: i64 = 256;
pub const FLOAT2: i64 = 512;
pub const FLOAT3: i64 = 1024;
pub const FLOAT4: i64 = 2048;
pub const STRING: i64 = 16384;
pub const BOOL: i64 = ValueType::Boolean as i64;
pub const INT1: i64 = ValueType::Integer as i64;
pub const INT2: i64 = ValueType::Integer2 as i64;
pub const INT3: i64 = ValueType::Integer3 as i64;
pub const INT4: i64 = ValueType::Integer4 as i64;
pub const FLOAT1: i64 = ValueType::Float as i64;
pub const FLOAT2: i64 = ValueType::Float2 as i64;
pub const FLOAT3: i64 = ValueType::Float3 as i64;
pub const FLOAT4: i64 = ValueType::Float4 as i64;
pub const STRING: i64 = ValueType::String as i64;
+66
View File
@@ -0,0 +1,66 @@
use super::{
constant::{FIRST_UID, FORMAT_VERSION, SELF_DEPENDENCY},
embedded::encode_embedded,
sbs_writer::SbsWriter,
xml::xml_escape,
};
use crate::Result;
use materialcraft_core::Package;
use std::{collections::BTreeMap, fmt::Write as _};
pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> {
let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() };
let self_uid = writer.next_uid();
let mut content = String::from("<content>");
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, "<group><uid v=\"{}\"/><identifier v=\"Resources\"/><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,
"<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>",
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("</content></group>");
}
content.push_str("</content>");
let mut out = String::with_capacity(content.len() + 4096);
let _ = write!(
out,
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><package><identifier v=\"{}\"/><formatVersion v=\"{FORMAT_VERSION}\"/><updaterVersion v=\"{FORMAT_VERSION}\"/><fileUID v=\"0\"/><versionUID v=\"0\"/><dependencies>",
xml_escape(&pkg.name)
);
let write_dependency = |out: &mut String, file: &str, uid: u64| {
let _ = write!(
out,
"<dependency><filename v=\"{}\"/><uid v=\"{uid}\"/><type v=\"package\"/><fileUID v=\"0\"/><versionUID v=\"0\"/></dependency>",
xml_escape(file)
);
};
write_dependency(&mut out, SELF_DEPENDENCY, self_uid);
for (file, uid) in &writer.external_packages {
write_dependency(&mut out, file, *uid);
}
out.push_str("</dependencies>");
out.push_str(&content);
out.push_str("</package>\n");
Ok(out.into_bytes())
}
+2
View File
@@ -1,5 +1,6 @@
use super::GRAPH_ITEMS;
use crate::{CookContext, CookResult, NodeDefinition, node};
use materialcraft_core::ComponentUsage;
use materialcraft_image::{Image, Kind};
pub(super) fn definition() -> NodeDefinition {
@@ -8,6 +9,7 @@ pub(super) fn definition() -> NodeDefinition {
.atomic()
.generator()
.text("identifier", "Identifier", "input")
.component_usage(ComponentUsage::ANY_INDEX)
.color("default", "Default color", [0.5, 0.5, 0.5, 1.0])
.color_out()
.cook(input_color_default)
@@ -1,5 +1,6 @@
use super::GRAPH_ITEMS;
use crate::{CookContext, CookResult, NodeDefinition, node};
use materialcraft_core::ComponentUsage;
use materialcraft_image::{Image, Kind};
pub(super) fn definition() -> NodeDefinition {
@@ -8,6 +9,7 @@ pub(super) fn definition() -> NodeDefinition {
.atomic()
.generator()
.text("identifier", "Identifier", "input")
.component_usage(ComponentUsage::ANY_INDEX)
.color("default", "Default value", [0.5, 0.5, 0.5, 1.0])
.gray_out()
.cook(input_gray_default)
+2
View File
@@ -1,11 +1,13 @@
use super::GRAPH_ITEMS;
use crate::{NodeDefinition, PortKind, node};
use materialcraft_core::ComponentUsage;
pub(super) fn definition() -> NodeDefinition {
node("input_value", "Input Value", GRAPH_ITEMS)
.desc("A typed value input of the graph.")
.atomic()
.text("identifier", "Identifier", "value")
.component_usage(ComponentUsage::ANY_INDEX)
.float("default", "Default", 0.0, 0.0, 0.0)
.output("output", "Value", PortKind::Value)
.cook(crate::node_definition_builder::no_cook)
-2
View File
@@ -37,8 +37,6 @@ use direction::direction;
pub const ATOMIC: &str = "Atomic nodes";
pub const GRAPH_ITEMS: &str = "Graph items";
pub const USAGES: &[&str] = &["Base color", "Normal", "Roughness", "Metallic", "Height", "Ambient occlusion", "Emissive", "Opacity", "Specular", "Any"];
pub const USAGE_IDS: &[&str] = &["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"];
pub use levels::levels_fn;
pub use normal::height_to_normal;
+2 -2
View File
@@ -1,5 +1,5 @@
use super::GRAPH_ITEMS;
use super::dot::passthrough;
use super::{GRAPH_ITEMS, USAGES};
use crate::{NodeDefinition, PortKind, node};
use materialcraft_image::{Image, Kind};
@@ -9,7 +9,7 @@ pub(super) fn definition() -> NodeDefinition {
.atomic()
.any_in("input", "Input")
.text("identifier", "Identifier", "output")
.choice("usage", "Usage", USAGES, 0)
.component_usage(0)
.cook(passthrough)
}
+12 -4
View File
@@ -14,8 +14,8 @@ pub(crate) fn evaluate(
context: &EvaluationContext<'_>,
) -> Result<Value, String> {
let op = instruction.definition.id;
let first = || arguments.first().ok_or("missing first operand".to_string());
let second = || arguments.get(1).ok_or("missing second operand".to_string());
let first = || arguments.first().ok_or("missing first operand");
let second = || arguments.get(1).ok_or("missing second operand");
let name = || match &instruction.value {
Some(Value::Text(name)) => Ok(name.as_str()),
_ => Err("variable name must be a string".to_string()),
@@ -26,22 +26,26 @@ pub(crate) fn evaluate(
if value_type::type_code(&value) != instruction.type_code {
return Err("constant has the wrong type".into());
}
return Ok(value);
}
if op.starts_with("get_") {
let name = name()?;
let value = match name {
"$pos" => Value::Float2(context.position),
"$size" => Value::Float2(context.size),
"$sizelog2" => Value::Float2(context.size.map(f32::log2)),
_ => variables.get(name).cloned().ok_or_else(|| format!("undefined variable `{name}`"))?,
_ => variables.get(name).or_else(|| context.variables.get(name)).cloned().ok_or_else(|| format!("undefined variable `{name}`"))?,
};
if value_type::type_code(&value) != instruction.type_code {
return Err(format!("variable `{name}` has the wrong type for {op}"));
}
return Ok(value);
}
if op.starts_with("to") || op.contains("vector") || op.contains("swizzle") {
return super::vector::evaluate(op, arguments, instruction.value.as_ref());
}
@@ -53,11 +57,15 @@ pub(crate) fn evaluate(
if name.is_empty() || name.starts_with('$') {
return Err("use a nonempty user variable name".into());
}
let value = first()?.clone();
variables.insert(name.to_string(), value.clone());
value
}
"isdefined" => Value::Bool(variables.contains_key(name()?) || matches!(name()?, "$pos" | "$size" | "$sizelog2")),
"isdefined" => {
let name = name()?;
Value::Bool(variables.contains_key(name) || context.variables.contains_key(name) || matches!(name, "$pos" | "$size" | "$sizelog2"))
}
"and" => Value::Bool(boolean(first()?)? && boolean(second()?)?),
"or" => Value::Bool(boolean(first()?)? || boolean(second()?)?),
"not" => Value::Bool(!boolean(first()?)?),
+2 -1
View File
@@ -31,6 +31,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult {
let program = compile(graph, context.seed)?;
let gray = !context.b("color_mode");
let kind = if gray { Kind::Gray } else { Kind::Color };
let (width, height) = materialcraft_image::clamp_size(context.w, context.h);
let channels = kind.channels();
let mut data = vec![0.0; width as usize * height as usize * channels];
@@ -44,7 +45,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult {
variables: context.vars,
};
let result = pixel(program.evaluate(&evaluation, state)?, gray)?;
let result = pixel(program.evaluate_pixel(&evaluation, state)?, gray)?;
target.copy_from_slice(result.get(..channels).ok_or("invalid output channels")?);
}
Ok(())
+19 -3
View File
@@ -20,23 +20,35 @@ impl Program {
}
fn instruction(&self, index: usize) -> Result<&Instruction, String> {
self.instructions.get(index).ok_or("invalid function instruction".into())
self.instructions.get(index).ok_or_else(|| "invalid function instruction".into())
}
fn input(&self, index: usize, slot: usize) -> Result<usize, String> {
self.instruction(index)?.inputs.get(slot).copied().ok_or("missing function input".into())
self.instruction(index)?.inputs.get(slot).copied().ok_or_else(|| "missing function input".into())
}
pub fn evaluate(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result<Value, String> {
state.variables.clone_from(context.variables);
self.run(context, state)
}
// Pixel assignments are local; only the general evaluator exports the complete environment
pub(super) fn evaluate_pixel(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result<Value, String> {
state.variables.clear();
self.run(context, state)
}
fn run(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result<Value, String> {
use EvaluationStep::*;
state.steps.clear();
state.values.clear();
state.registers.clear();
state.registers.resize(self.instructions.len(), None);
state.variables.clone_from(context.variables);
state.random = context.variables.get("$randomseed").and_then(Value::as_i32).map_or(self.seed, |seed| seed as u32);
state.steps.push(Enter(self.output));
let mut remaining_steps = MAX_EVALUATION_STEPS;
while let Some(step) = state.steps.pop() {
remaining_steps = remaining_steps.checked_sub(1).ok_or("function exceeded its execution budget; check loop termination")?;
match step {
@@ -71,17 +83,20 @@ impl Program {
let arguments = state.values.get(base..).ok_or("invalid function operands")?;
let result = operation::evaluate(instruction, arguments, &mut state.variables, &mut state.random, context)
.map_err(|error| format!("{} ({}): {error}", instruction.definition.label, instruction.id))?;
state.values.truncate(base);
if instruction.pure
&& let Some(register) = state.registers.get_mut(index)
{
*register = Some(result.clone());
}
state.values.push(result);
}
Branch(index) => {
let condition = state.values.pop().ok_or("missing branch condition")?;
let slot = if value_type::boolean(&condition)? { 1 } else { 2 };
state.steps.push(Enter(self.input(index, slot)?));
}
Sequence(index) => {
@@ -116,6 +131,7 @@ impl Program {
if value_type::type_code(&result) != expected {
return Err(format!("function returned {}, expected native type {expected}", result.type_name()));
}
Ok(result)
}
}
+48
View File
@@ -162,3 +162,51 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() {
graph.output = Some(previous);
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1_073_741_824.0));
}
#[test]
fn pixel_assignments_are_local_and_match_exported_evaluation() {
let mut graph = FunctionGraph::default();
let current = graph.add("get_float1", &[], Some(Value::Text("counter".into())));
let one = graph.add_constant(Value::Float(1.0));
let next = graph.add("add", &[current, one], None);
let assign = graph.add("set", &[next], Some(Value::Text("counter".into())));
let get = graph.add("get_float1", &[], Some(Value::Text("counter".into())));
graph.output = Some(graph.add("sequence", &[assign, get], None));
let program = compile(&graph, 7).unwrap();
let mut pixel_state = EvaluationState::default();
for initial in [3.0, 10.0, -2.0] {
let variables = BTreeMap::from([("counter".into(), Value::Float(initial)), ("untouched".into(), Value::Text("keep".into()))]);
let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
let mut exported = EvaluationState::default();
let expected = program.evaluate(&context, &mut exported).unwrap();
for _ in 0..2 {
assert_eq!(program.evaluate_pixel(&context, &mut pixel_state).unwrap(), expected);
}
assert_eq!(expected, Value::Float(initial + 1.0));
assert_eq!(variables["counter"], Value::Float(initial));
assert_eq!(exported.variables()["counter"], expected);
assert_eq!(exported.variables()["untouched"], variables["untouched"]);
}
let read_only = compile(&FunctionGraph::constant(Value::Float(0.5)), 7).unwrap();
let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &BTreeMap::new() };
assert_eq!(read_only.evaluate_pixel(&context, &mut pixel_state).unwrap(), Value::Float(0.5));
assert!(pixel_state.variables().is_empty());
}
#[test]
fn pixel_random_seed_and_defined_variables_match_general_evaluation() {
let mut graph = FunctionGraph::default();
let maximum = graph.add_constant(Value::Float(1.0));
let random = graph.add("rand", &[maximum], None);
let defined = graph.add("isdefined", &[], Some(Value::Text("known".into())));
let zero = graph.add_constant(Value::Float(0.0));
graph.output = Some(graph.add("ifelse", &[defined, random, zero], None));
let program = compile(&graph, 7).unwrap();
let mut state = EvaluationState::default();
for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] {
let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
let expected = program.evaluate(&context, &mut EvaluationState::default()).unwrap();
assert_eq!(program.evaluate_pixel(&context, &mut state).unwrap(), expected);
}
}
+5 -1
View File
@@ -1,5 +1,5 @@
use crate::{Cook, CookContext, CookResult, NodeDefinition, ParameterDefinition, PortDefinition, PortKind};
use materialcraft_core::{Curve, FunctionGraph, Gradient, PatternGraph, Value};
use materialcraft_core::{ComponentUsage, Curve, FunctionGraph, Gradient, PatternGraph, Value};
pub(crate) fn no_cook(_: &CookContext) -> CookResult {
Err("this node is cooked by the graph evaluator".into())
@@ -120,6 +120,10 @@ impl NodeDefinitionBuilder {
self
}
pub fn component_usage(self, default: u32) -> NodeDefinitionBuilder {
self.choice("usage", "Component Usage", ComponentUsage::LABELS, default)
}
pub fn text(self, id: &'static str, label: &'static str, d: &str) -> NodeDefinitionBuilder {
self.push(id, label, Value::Text(d.into()), 0.0, 0.0)
}
+1
View File
@@ -9,6 +9,7 @@ license.workspace = true
workspace = true
[dependencies]
materialcraft-core = { workspace = true }
materialcraft-geom = { workspace = true }
materialcraft-image = { workspace = true }
rayon = { workspace = true }
+12 -10
View File
@@ -32,16 +32,18 @@ impl Maps {
pub fn from_usages<'a>(items: impl IntoIterator<Item = (&'a str, &'a Image)>) -> Maps {
let mut m = Maps::default();
for (usage, img) in items {
let slot = match usage {
"baseColor" => &mut m.base_color,
"normal" => &mut m.normal,
"roughness" => &mut m.roughness,
"metallic" => &mut m.metallic,
"height" => &mut m.height,
"ambientOcclusion" => &mut m.ao,
"emissive" => &mut m.emissive,
"opacity" => &mut m.opacity,
_ => continue,
use materialcraft_core::MaterialChannel;
let Some(channel) = MaterialChannel::from_id(usage) else { continue };
let slot = match channel {
MaterialChannel::BaseColor => &mut m.base_color,
MaterialChannel::Normal => &mut m.normal,
MaterialChannel::Roughness => &mut m.roughness,
MaterialChannel::Metallic => &mut m.metallic,
MaterialChannel::Height => &mut m.height,
MaterialChannel::AmbientOcclusion => &mut m.ao,
MaterialChannel::Emissive => &mut m.emissive,
MaterialChannel::Opacity => &mut m.opacity,
};
if slot.is_none() {
*slot = Some(img.clone());
+12 -7
View File
@@ -240,20 +240,25 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p:
}
"ui.inspect" => {
let rect = |r: egui::Rect| json!([r.min.x, r.min.y, r.width(), r.height()]);
let target = crate::graph::editor_target::EditorTarget::resolve(app);
let (view, nodes, ports) = (app.graph.view, &app.graph.rects, &app.graph.ports);
ok(json!({
"state": app.ui,
"graphView": rect(app.graph.view),
"graphView": rect(view),
"selection": app.session.selection,
"inspectedNode": app.graph.inspected_node,
"subgraph": app.pattern_editor.as_ref().filter(|_| crate::pattern::active(app))
.map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "inspectedNode": editor.inspected_node}))
.or_else(|| app.function_editor.as_ref().filter(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph(_)))
.map(|editor| json!({"kind": "function", "graph": app.session.graph, "selection": editor.selection, "inspectedNode": editor.inspected_node}))),
"subgraph": match target {
crate::graph::editor_target::EditorTarget::Function => app.function_editor.as_ref()
.map(|editor| json!({"kind": "function", "graph": app.session.graph, "node": editor.node, "target": editor.command_target(), "selection": editor.selection, "inspectedNode": editor.inspected_node})),
crate::graph::editor_target::EditorTarget::Pattern => app.pattern_editor.as_ref()
.map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "inspectedNode": editor.inspected_node})),
crate::graph::editor_target::EditorTarget::Material => None,
},
"annotationSelection": app.session.annotation_selection,
"frames": app.graph.frames.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(),
"comments": app.graph.comments.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(),
"nodes": app.graph.rects.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::<Vec<_>>(),
"ports": app.graph.ports.iter().map(|port| json!({
"nodes": nodes.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::<Vec<_>>(),
"ports": ports.iter().map(|port| json!({
"node": port.node.0,
"port": port.port,
"label": port.label,
+6 -5
View File
@@ -3,13 +3,13 @@
use std::sync::mpsc::{Receiver, TryRecvError};
use materialcraft_engine::eval::Cooked;
use materialcraft_engine::PreviewCook;
use crate::MaterialCraftApp;
#[derive(Default)]
pub struct Cooker {
rx: Option<Receiver<Cooked>>,
rx: Option<Receiver<PreviewCook>>,
/// Stops the running cook between nodes once its result is stale.
#[cfg(not(target_arch = "wasm32"))]
cancel: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
@@ -28,11 +28,11 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if let Some(rx) = &app.cooker.rx {
match rx.try_recv() {
Ok(c) => {
if c.cancelled {
if c.cancelled() {
// A stopped cook is partial: keep the previous results and cook again.
app.session.dirty = true;
} else if !app.session.dirty {
app.session.cooked = c;
app.session.accept_preview(c);
}
app.cooker.rx = None;
app.cooker.started = None;
@@ -78,6 +78,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) {
s.dirty = false;
let pkg = s.pkg.clone();
let (gi, max) = (s.graph, s.preview_size);
let materials = s.material_preview.graphs();
let cache = s.cache.clone();
let dec = s.resource_decoder();
let (tx, rx) = std::sync::mpsc::channel();
@@ -88,7 +89,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) {
let mut opts = Options::new(&dec);
opts.max_size = max;
opts.cancel = Some(&thread_flag);
let cooked = materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache);
let cooked = PreviewCook::run(&pkg, gi, &materials, &opts, &cache);
let _ = tx.send(cooked);
});
match spawned {
+4 -3
View File
@@ -1,11 +1,12 @@
use super::*;
use materialcraft_engine::eval::Cooked;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc,
};
fn waiting() -> (MaterialCraftApp, mpsc::Sender<Cooked>, Arc<AtomicBool>) {
fn waiting() -> (MaterialCraftApp, mpsc::Sender<PreviewCook>, Arc<AtomicBool>) {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default());
app.session.cook();
app.session.cooked.ms = 123.0;
@@ -26,7 +27,7 @@ fn rapid_edits_wait_for_the_cancelled_worker() {
assert!(flag.load(Ordering::Relaxed));
assert!(Arc::ptr_eq(app.cooker.cancel.as_ref().unwrap(), &flag));
}
tx.send(Cooked { cancelled: true, ..Default::default() }).unwrap();
tx.send(PreviewCook { cooked: Cooked { cancelled: true, ..Default::default() }, ..Default::default() }).unwrap();
drive(&mut app, &egui::Context::default());
assert!(!app.session.dirty, "latest snapshot should start once the worker ends");
assert_eq!(app.session.cooked.ms, 123.0, "partial results replaced the display");
@@ -35,7 +36,7 @@ fn rapid_edits_wait_for_the_cancelled_worker() {
#[test]
fn ready_results_are_discarded_when_an_edit_is_pending() {
let (mut app, tx, _) = waiting();
tx.send(Cooked { ms: 7.0, ..Default::default() }).unwrap();
tx.send(PreviewCook { cooked: Cooked { ms: 7.0, ..Default::default() }, ..Default::default() }).unwrap();
app.session.dirty = true;
drive(&mut app, &egui::Context::default());
assert_eq!(app.session.cooked.ms, 123.0);
+32 -8
View File
@@ -1,4 +1,4 @@
//! The package tree, its graphs, named outputs and resources
//! The package tree, its graphs, inputs, outputs and resources
use egui::{RichText, Ui};
@@ -36,17 +36,29 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
ui.label(RichText::new(format!("{} {name}", icon::PACKAGE)).strong().color(tk.text_strong));
let mut open: Option<usize> = None;
let mut action: Option<(&str, usize)> = None;
let mut output = None;
let mut selected_node = None;
let mut assignment = None;
for (index, graph) in app.session.pkg.graphs.iter().enumerate() {
let active = index == app.session.graph;
let function = graph.function.is_some();
let mut header = |ui: &mut Ui| {
let symbol = if function { icon::FUNCTION } else { icon::TREE_STRUCTURE };
let response = tree_row::show(ui, &graph.name, symbol, active);
if !function {
response.interact(egui::Sense::drag()).dnd_set_drag_payload(crate::graph_drag_payload::GraphDragPayload { name: graph.name.clone() });
}
if response.clicked() {
open = Some(index);
}
response.context_menu(|ui| {
if !function {
for (label, command) in [("View outputs in 3D view", "view3d"), ("Reset and view outputs in 3D view", "reset3d")] {
if ui.button(tr(label)).clicked() {
action = Some((command, index));
ui.close();
}
}
}
for (label, command) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] {
if ui.button(tr(label)).clicked() {
action = Some((command, index));
@@ -66,15 +78,21 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let id = ui.make_persistent_id(("graph", index, &graph.name));
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true).show_header(ui, header).body(|ui| {
ui.indent("outputs", |ui| {
for node in graph.nodes.iter().filter(|node| node.def == "output") {
ui.indent("graph-ports", |ui| {
for node in graph.nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "input_color" | "input_grayscale" | "input_value")) {
ui.push_id(node.id, |ui| {
let name = materialcraft_engine::eval::identifier(node);
let name = crate::graph::node_label(node);
let selected = active && app.session.selection.contains(&node.id);
let response = tree_row::show(ui, &name, icon::IMAGE, selected);
let symbol = if node.def == "input_value" { icon::FUNCTION } else { icon::IMAGE };
let response = tree_row::show(ui, &name, symbol, selected);
response.context_menu(|ui| {
if let Some(parameters) = crate::material_preview_menu::show(ui, &app.session, index, node.id) {
assignment = Some(parameters);
}
});
if response.clicked() || response.double_clicked() {
output = Some((index, node.id, response.double_clicked()));
selected_node = Some((index, node.id, response.double_clicked()));
}
});
}
@@ -84,7 +102,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
if let Some(i) = open {
app.run("graph.open", json!({"graph": i}));
}
if let Some((index, node, preview)) = output {
if let Some((index, node, preview)) = selected_node {
if index != app.session.graph && app.run("graph.open", json!({"graph": index})).is_none() {
return;
}
@@ -101,7 +119,13 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
}
}
if let Some(parameters) = assignment {
app.run("view.3d.assign", parameters);
}
match action {
Some((command @ ("view3d" | "reset3d"), graph)) => {
app.run("view.3d.outputs", json!({"graph": graph, "reset": command == "reset3d"}));
}
Some(("open", i)) => {
app.run("graph.open", json!({"graph": i}));
}
+49
View File
@@ -0,0 +1,49 @@
use super::{FunctionEditor, FunctionTarget};
use crate::MaterialCraftApp;
pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, command: &str) -> Option<bool> {
let standalone = matches!(editor.target, FunctionTarget::Graph);
if standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") {
return None;
}
if let Some(target) = editor.command_target()
&& let Some(enabled) = materialcraft_engine::selection_commands::enabled_for(
&app.session,
&materialcraft_engine::SelectionTarget::Function(target),
&editor.selection,
command,
)
{
return Some(enabled && editor.current(app).is_some());
}
match command {
"edit.undo" | "edit.redo" | "edit.finish" | "graph.cook" | "ui.graph.snapToGrid" => None,
"ui.graph.previousPin" | "ui.graph.nextPin" | "graph.comment.add" | "graph.frame.add" | "graph.pin.add" if standalone => None,
command if command.starts_with("graph.") || command.starts_with("ui.graph.") || command.starts_with("edit.") => Some(false),
_ => None,
}
}
pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> {
app.function_editor.as_ref().and_then(|editor| editor_enabled(app, editor, command))
}
pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, command: &str) -> bool {
let Some(allowed) = editor_enabled(app, editor, command) else { return false };
if !allowed {
return true;
}
let parameters = editor.selection_parameters(command);
crate::graph::selection_commands::invoke(app, &mut editor.selection, command, parameters);
true
}
pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool {
let Some(mut editor) = app.function_editor.take() else { return false };
let handled = invoke_editor(app, &mut editor, command);
app.function_editor = Some(editor);
handled
}
+37 -551
View File
@@ -1,572 +1,58 @@
//! Function canvas edits are committed through engine commands
use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::core::Value;
use materialcraft_engine::core::{FunctionGraph, FunctionNode};
use materialcraft_engine::nodes::function::FUNCTIONS;
use super::{FunctionEditor, FunctionTarget};
use crate::{MaterialCraftApp, graph::GraphCamera, i18n::tr};
use egui::Ui;
use materialcraft_engine::FunctionEdit;
use serde_json::json;
use crate::MaterialCraftApp;
use crate::graph::node_card;
use crate::i18n::tr;
use crate::theme::Tokens;
pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) {
let Some(frame) = super::render::paint(app, editor, ui) else { return };
use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label};
fn arity(op: &str) -> usize {
FUNCTIONS.iter().find(|o| o.id == op).map_or(0, |o| o.inputs.len())
}
fn label(op: &str) -> &'static str {
FUNCTIONS.iter().find(|o| o.id == op).map_or("?", |o| o.label)
}
fn category_color(op: &str) -> Color32 {
match FUNCTIONS.iter().find(|o| o.id == op).map_or("", |o| o.category) {
"Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e),
"Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5),
"Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34),
"Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0),
"Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c),
"Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c),
_ => Color32::from_rgb(0x1e, 0x8a, 0xa0),
}
}
fn visible_inputs(node: &FunctionNode) -> usize {
let count = arity(&node.op);
crate::graph::input_visibility::count((0..count).map(|index| node.inputs.get(index).is_some_and(Option::is_some)), 1)
}
fn node_rect(node: &FunctionNode, previews: bool) -> Rect {
node_card::bounds(node.pos, visible_inputs(node), 1, previews, node.op == "passthrough")
}
fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 {
node_card::port(bounds, index, visible_inputs(node), false, node.op == "passthrough")
}
fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 {
node_card::port(bounds, 0, 1, true, node.op == "passthrough")
}
pub(super) fn current(app: &MaterialCraftApp, editor: &FunctionEditor) -> Option<FunctionGraph> {
if let FunctionTarget::Graph(index) = editor.target {
return app.session.pkg.graphs.get(index)?.function.clone();
}
let node = app.session.graph().ok()?.node(editor.node?).ok()?;
let value = match &editor.target {
FunctionTarget::Graph(_) => return None,
FunctionTarget::Dynamic(parameter) => return node.functions.get(parameter).cloned(),
FunctionTarget::Parameter(parameter) => {
node.params.get(parameter).or_else(|| materialcraft_engine::nodes::find(&node.def)?.param(parameter).map(|parameter| &parameter.default))?
}
FunctionTarget::Pattern { node: id, parameter } => {
let Value::PatternGraph(graph) = node.params.get("pattern")? else { return None };
graph.nodes.iter().find(|node| node.id == *id)?.parameters.get(parameter)?
}
};
match value {
Value::Function(function) => Some((**function).clone()),
_ => None,
}
}
pub(super) fn commit(app: &mut MaterialCraftApp, editor: &FunctionEditor, graph: &FunctionGraph) {
match &editor.target {
FunctionTarget::Graph(_) => {
app.run("graph.function.set", json!({"function": graph}));
}
FunctionTarget::Dynamic(parameter) => {
app.run("graph.node.function", json!({"id": editor.node.map(|node| node.0), "param": parameter, "function": graph}));
}
FunctionTarget::Parameter(parameter) => {
let value = Value::Function(Box::new(graph.clone()));
app.run("graph.node.param", json!({"id": editor.node.map(|node| node.0), "param": parameter, "value": value}));
}
FunctionTarget::Pattern { node: id, parameter } => {
let Some(mut pattern) =
app.session.graph().ok().and_then(|graph| graph.node(editor.node?).ok()).and_then(|node| node.params.get("pattern")).cloned()
else {
return;
};
if let Value::PatternGraph(pattern) = &mut pattern
&& let Some(node) = pattern.nodes.iter_mut().find(|node| node.id == *id)
{
node.parameters.insert(parameter.clone(), Value::Function(Box::new(graph.clone())));
}
app.run("graph.node.param", json!({"id": editor.node.map(|node| node.0), "param": "pattern", "value": pattern}));
}
}
}
/// Draw the editor window when one is open
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, FunctionTarget::Graph(_))) {
return;
}
let Some(mut e) = app.function_editor.take() else { return };
let Some(mut g) = current(app, &e) else { return };
let title = app.session.graph().ok().and_then(|gr| gr.node(e.node?).ok()).map(crate::graph::node_label).unwrap_or_default();
let mut open = true;
let mut changed = false;
let what = if e.target.parameter() == "function" { tr("Function").to_string() } else { format!("{} {}", tr("Function"), e.target.parameter()) };
egui::Window::new(format!("{title} - {what}"))
.id(egui::Id::unique(("fn-editor", e.node, &e.target)))
.open(&mut open)
.default_size(vec2(760.0, 460.0))
.resizable(true)
.show(ctx, |ui| {
let tk = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(
egui::RichText::new(tr("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result."))
.size(11.0)
.color(tk.text_dim),
);
});
changed = canvas(app, &mut e, &mut g, ui);
});
if changed {
commit(app, &e, &g);
}
if open {
app.function_editor = Some(e);
}
}
pub(crate) fn show_graph(app: &mut MaterialCraftApp, ui: &mut Ui) {
let index = app.session.graph;
let mut editor =
app.function_editor.take().filter(|editor| editor.target == FunctionTarget::Graph(index)).unwrap_or_else(|| FunctionEditor::standalone(index));
let Some(mut graph) = current(app, &editor) else { return };
ui.horizontal(|ui| {
if ui.button(tr("Frame all")).clicked() {
editor.framed = false;
}
ui.checkbox(&mut app.ui.prefs.snap_to_grid, tr("Snap to grid"));
if graph.output.is_none() {
ui.label(tr("Set a node as the output"));
}
});
if canvas(app, &mut editor, &mut graph, ui) {
commit(app, &editor, &graph);
}
app.function_editor = Some(editor);
}
fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool) -> Rect {
let mut bounds = node_rect(node, app.ui.prefs.thumbnails);
if let Some(FunctionDrag::Node(d, delta)) = &editor.drag
&& (*d == node.id || editor.selection.contains(&node.id))
{
let position = materialcraft_engine::graph_grid::snap_position([node.pos[0] + delta.x, node.pos[1] + delta.y], snap);
bounds = bounds.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1]));
}
if matches!(editor.target, FunctionTarget::Graph(_)) {
bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id)));
}
bounds
}
fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, graph: &mut FunctionGraph, ui: &mut Ui) -> bool {
editor.selection.retain(|id| graph.node(*id).is_some());
editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node);
let snap = app.ui.prefs.snap_to_grid;
let standalone = matches!(editor.target, FunctionTarget::Graph(_));
let tokens = Tokens::get(ui.ctx());
let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag());
crate::widgets::name(&response, egui::Role::Canvas, "Function Graph");
let painter = ui.painter_at(canvas_bounds);
painter.rect_filled(canvas_bounds, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c));
let standalone = matches!(editor.target, FunctionTarget::Graph);
app.ui.frame_all = false;
if standalone {
app.graph.view = canvas_bounds;
app.graph.rects.clear();
app.graph.ports.clear();
app.graph.wires.clear();
app.ui.graph_camera = frame.camera.state();
app.graph.frames = frame.frames.iter().map(|frame| (frame.id, frame.rect)).collect();
app.graph.comments = frame.comments.clone();
}
if !editor.framed || (standalone && app.ui.frame_all) {
if standalone {
app.ui.frame_all = false;
}
editor.framed = true;
let mut destination =
graph.nodes.iter().map(|node| node_rect(node, app.ui.prefs.thumbnails)).fold(Rect::NOTHING, |combined, bounds| combined.union(bounds));
if standalone && let Ok(document) = app.session.graph() {
for frame in &document.frames {
destination = destination.union(Rect::from_min_size(pos2(frame.rect[0], frame.rect[1] - 32.0), vec2(frame.rect[2], frame.rect[3] + 32.0)));
}
}
if destination.is_finite() && destination.width() > 0.0 {
let destination = destination.expand(30.0);
editor.zoom = (canvas_bounds.width() / destination.width()).min(canvas_bounds.height() / destination.height()).clamp(0.3, 1.2);
editor.pan = destination.center().to_vec2() - canvas_bounds.size() * 0.5 / editor.zoom;
}
if frame.clear_annotation {
app.run("graph.annotation.select", json!({}));
}
let to_screen = |position: Pos2, editor: &FunctionEditor| canvas_bounds.min + (position.to_vec2() - editor.pan) * editor.zoom;
let to_graph = |source: Pos2, editor: &FunctionEditor| ((source - canvas_bounds.min) / editor.zoom + editor.pan).to_pos2();
let mut changed = false;
let pointer = ui.input(|input| input.pointer.hover_pos());
// Zoom and pan
if response.hovered() {
let scroll = ui.input(|input| input.smooth_scroll_delta.y);
if scroll.abs() > 0.0
&& let Some(pointer_position) = pointer
for (id, value) in frame.values {
editor.edit(app, FunctionEdit::Value { id, value }, true);
}
for (id, response) in &frame.nodes {
if response.secondary_clicked()
&& let Some(pointer) = response.interact_pointer_pos()
{
let before = to_graph(pointer_position, editor);
editor.zoom = (editor.zoom * (scroll * 0.0025).exp()).clamp(0.3, 2.5);
editor.pan = before.to_vec2() - (pointer_position - canvas_bounds.min) / editor.zoom;
editor.menu_at = frame.camera.to_graph(pointer);
}
}
let camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom };
let document = standalone.then(|| app.session.graph().ok().cloned()).flatten();
let frame_hits = document.as_ref().map(|graph| crate::graph::annotation_canvas::frames(app, ui, graph, &camera)).unwrap_or_default();
if standalone {
app.graph.frames = frame_hits.iter().map(|frame| (frame.id, frame.rect)).collect();
}
crate::graph::canvas::grid(&painter, &camera, canvas_bounds);
// Wires
for node in &graph.nodes {
let bounds = preview_rect(app, editor, node, snap);
for (input_index, source_id) in node.inputs.iter().enumerate() {
if let Some(source) = source_id.and_then(|source| graph.node(source)) {
let source_position = to_screen(out_port(source, preview_rect(app, editor, source, snap)), editor);
let destination = to_screen(in_port(node, bounds, input_index), editor);
let control_offset = ((destination.x - source_position.x).abs() * 0.5).max(24.0);
painter.add(egui::epaint::CubicBezierShape::from_points_stroke(
[source_position, source_position + vec2(control_offset, 0.0), destination - vec2(control_offset, 0.0), destination],
false,
Color32::TRANSPARENT,
Stroke::new(2.0, Color32::from_gray(0xb4)),
));
}
}
}
// Nodes
let font = FontId::proportional((11.0 * editor.zoom).min(16.0));
let mut remove: Option<u32> = None;
let mut set_output: Option<u32> = None;
let mut ports: Vec<(u32, Option<usize>, Pos2)> = Vec::new();
let ids: Vec<u32> = graph.nodes.iter().map(|node| node.id).collect();
for id in ids {
let Some(node_index) = graph.nodes.iter().position(|node| node.id == id) else { continue };
let node = &graph.nodes[node_index];
let bounds = preview_rect(app, editor, node, snap);
let screen_rect = Rect::from_min_max(to_screen(bounds.min, editor), to_screen(bounds.max, editor));
if standalone {
app.graph.rects.push((materialcraft_engine::core::NodeId(u64::from(id)), screen_rect));
}
let dot = node.op == "passthrough";
let show_labels = crate::graph::port_label::visible(ui, screen_rect);
let is_output = graph.output == Some(id);
let selected = editor.selection.contains(&id);
let outline = if selected {
tokens.accent
} else if dot {
Color32::from_gray(0xb4)
} else {
Color32::from_gray(0x10)
};
if dot {
node_card::paint_dot(&painter, screen_rect, outline);
} else {
node_card::paint(&painter, screen_rect, editor.zoom, label(&node.op), category_color(&node.op));
node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline));
let body = node_card::body(screen_rect, editor.zoom);
if node.value.is_none() {
painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim);
}
if is_output {
let header = node_card::header(screen_rect, editor.zoom);
painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::STAR, font.clone(), Color32::GOLD);
}
}
let port_radius = (4.5 * editor.zoom).clamp(2.5, 7.0);
let port_color = crate::graph::port_color(materialcraft_engine::nodes::PortKind::Value);
if let Some(definition) = materialcraft_engine::nodes::function::definition(&node.op) {
for (input_index, identifier) in definition.inputs.iter().take(visible_inputs(node)).enumerate() {
let position = to_screen(in_port(node, bounds, input_index), editor);
painter.circle(position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18)));
if show_labels {
crate::graph::port_label::paint(
&painter,
position - vec2(10.0, 0.0),
Align2::RIGHT_CENTER,
port_label(identifier),
editor.zoom,
tokens.text_strong,
);
}
ports.push((id, Some(input_index), position));
}
}
let output_position = to_screen(out_port(node, bounds), editor);
painter.circle(output_position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18)));
if show_labels {
crate::graph::port_label::paint(
&painter,
output_position + vec2(10.0, 0.0),
Align2::LEFT_CENTER,
port_label("output"),
editor.zoom,
tokens.text_strong,
);
}
ports.push((id, None, output_position));
let body = ui.interact(screen_rect, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag());
crate::widgets::name(&body, egui::Role::Button, label(&graph.nodes[node_index].op));
if !dot && node.value.is_some() {
let content = node_card::body(screen_rect, editor.zoom).shrink(6.0 * editor.zoom);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content));
child.set_clip_rect(content.intersect(canvas_bounds));
if let Some(value) = graph.nodes[node_index].value.as_mut() {
changed |= crate::value_editor::show(&mut child, value);
}
}
if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed())) || body.secondary_clicked() {
let modifiers = if body.secondary_clicked() { egui::Modifiers::NONE } else { ui.input(|input| input.modifiers) };
crate::graph::node_selection::select(&mut editor.selection, Some(id), modifiers);
if standalone && app.session.annotation_selection.is_some() {
app.run("graph.annotation.select", json!({}));
}
}
if body.drag_started() && editor.selection.contains(&id) && editor.drag.is_none() && !app.graph.is_dragging() {
editor.drag = Some(FunctionDrag::Node(id, Vec2::ZERO));
}
body.context_menu(|ui| {
changed |= super::context_menu::show(app, editor, graph, ui);
response.context_menu(|ui| {
super::context_menu::show(app, editor, ui);
ui.separator();
if ui.button(format!("{} {}", icon::STAR, tr("Set as output node"))).clicked() {
set_output = Some(id);
ui.close();
}
if ui.button(format!("{} {}", icon::X, tr("Delete"))).clicked() {
remove = Some(id);
if ui.button(format!("{} {}", egui_phosphor::regular::STAR, tr("Set as output node"))).clicked() {
editor.edit(app, FunctionEdit::Output { id: *id }, false);
ui.close();
}
});
}
if let Some(id) = set_output {
graph.output = Some(id);
changed = true;
}
if let Some(id) = remove {
graph.nodes.retain(|node| node.id != id);
for node in &mut graph.nodes {
for source in &mut node.inputs {
if *source == Some(id) {
*source = None;
}
}
}
if graph.output == Some(id) {
graph.output = None;
}
changed = true;
}
let on_annotation = ui
.input(|input| input.pointer.hover_pos())
.is_some_and(|pointer| frame.frames.iter().any(|frame| frame.contains(pointer)) || frame.comments.iter().any(|(_, rect)| rect.contains(pointer)));
super::input::handle(app, editor, ui, &frame.response, &frame.ports, &frame.geometry.rects, on_annotation);
frame.geometry.publish(&mut app.graph, frame.response.rect);
if standalone {
app.graph.ports = ports
.iter()
.map(|(id, input, position)| {
let identifier = input
.and_then(|slot| {
let node = graph.node(*id)?;
materialcraft_engine::nodes::function::definition(&node.op)?.inputs.get(slot).copied()
})
.unwrap_or(if input.is_some() { "input" } else { "output" });
crate::graph::PortHit {
node: materialcraft_engine::core::NodeId(u64::from(*id)),
port: input.map_or_else(|| "output".into(), |slot| slot.to_string()),
label: port_label(identifier).into(),
output: input.is_none(),
kind: materialcraft_engine::nodes::PortKind::Value,
pos: *position,
}
})
.collect();
app.ui.graph_camera.pan = [editor.pan.x, editor.pan.y];
app.ui.graph_camera.zoom = editor.zoom;
}
// Gestures: wires from output dots, panning
let near = |pointer_position: Pos2| {
ports
.iter()
.filter(|(id, _, position)| {
let dot = graph.node(*id).is_some_and(|node| node.op == "passthrough");
let radius = if dot { (3.5 * editor.zoom).max(2.0) } else { 9.0 };
position.distance(pointer_position) < radius
})
.min_by(|first, second| first.2.distance(pointer_position).total_cmp(&second.2.distance(pointer_position)))
.cloned()
};
if response.drag_started_by(egui::PointerButton::Middle) || (response.drag_started() && ui.input(|input| input.modifiers.alt)) {
editor.drag = Some(FunctionDrag::Pan);
} else if ui.input(|input| input.pointer.primary_pressed())
&& editor.drag.is_none()
&& !app.graph.is_dragging()
&& let Some(pointer_position) = pointer
&& canvas_bounds.contains(pointer_position)
&& let Some((id, None, _)) = near(pointer_position)
{
editor.drag = Some(FunctionDrag::Wire(id));
}
let delta = ui.input(|input| input.pointer.delta());
match &mut editor.drag {
Some(FunctionDrag::Node(_, offset)) => *offset += delta / editor.zoom,
Some(FunctionDrag::Pan) => editor.pan -= delta / editor.zoom,
Some(FunctionDrag::Wire(id)) => {
if let (Some(pointer_position), Some(source_id)) = (pointer, ports.iter().find(|(node, source, _)| node == id && source.is_none())) {
painter.line_segment([source_id.2, pointer_position], Stroke::new(2.0, tokens.accent));
}
}
None => {}
}
if ui.input(|input| input.pointer.any_released()) {
match editor.drag.take() {
Some(FunctionDrag::Node(id, offset)) => {
if offset.length() > 0.5 {
for node in graph.nodes.iter_mut().filter(|node| node.id == id || editor.selection.contains(&node.id)) {
node.pos = materialcraft_engine::graph_grid::snap_position([node.pos[0] + offset.x, node.pos[1] + offset.y], snap);
}
changed = true;
}
}
Some(FunctionDrag::Wire(source_id)) => {
if let Some(pointer_position) = pointer
&& let Some((destination_id, Some(slot), _)) = near(pointer_position)
&& destination_id != source_id
&& !reaches(graph, destination_id, source_id)
&& let Some(node) = graph.nodes.iter_mut().find(|node| node.id == destination_id)
{
if node.inputs.len() <= slot {
node.inputs.resize(slot + 1, None);
}
node.inputs[slot] = Some(source_id);
changed = true;
}
}
_ => {}
}
}
if response.clicked() {
crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers));
}
// Adding operations
if response.secondary_clicked()
&& let Some(pointer_position) = pointer
{
editor.menu_at = to_graph(pointer_position, editor);
}
if response.hovered()
&& ui.input(|input| input.key_pressed(egui::Key::Space))
&& let Some(pointer_position) = pointer
{
editor.menu_at = to_graph(pointer_position, editor);
egui::Popup::open_id(ui.ctx(), response.id.with("menu"));
}
response.context_menu(|ui| {
changed |= super::context_menu::show(app, editor, graph, ui);
});
if let Some(document) = &document {
let comments = crate::graph::annotation_canvas::comments(app, ui, document, &camera);
app.graph.comments = comments.clone();
crate::graph::annotation_canvas::pins(app, ui, document, &camera);
if editor.drag.is_none() {
crate::graph::annotation_input::handle(app, ui, &camera, &frame_hits, &comments);
let camera = GraphCamera { origin: frame.response.rect.min, pan: editor.pan, zoom: editor.zoom };
crate::graph::annotation_input::handle(app, ui, &camera, &frame.frames, &frame.comments);
if app.session.annotation_selection.is_some() {
editor.selection.clear();
}
}
app.ui.graph_camera = crate::state::GraphCamera { pan: editor.pan.into(), zoom: editor.zoom };
app.session.selection = editor.selection.iter().map(|id| materialcraft_engine::core::NodeId(u64::from(*id))).collect();
} else {
app.graph.frames.clear();
app.graph.comments.clear();
}
editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node).filter(|id| graph.node(*id).is_some());
changed
}
// Wiring b into a is invalid when a already feeds b
fn reaches(g: &FunctionGraph, a: u32, b: u32) -> bool {
let mut stack = vec![b];
let mut seen = std::collections::BTreeSet::new();
while let Some(n) = stack.pop() {
if n == a {
return true;
}
if !seen.insert(n) {
continue;
}
if let Some(node) = g.node(n) {
stack.extend(node.inputs.iter().flatten());
}
}
false
}
pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> {
if app.session.annotation_selection.is_some() || !app.session.graph().is_ok_and(|graph| graph.function.is_some()) {
return None;
}
super::selection::enabled(app.function_editor.as_ref()?, command)
}
pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool {
if enabled(app, command).is_none() {
return false;
}
let Some(mut editor) = app.function_editor.take() else { return false };
if let Some(mut graph) = current(app, &editor)
&& super::selection::run(&mut editor, &mut graph, command, app.ui.prefs.snap_to_grid)
{
commit(app, &editor, &graph);
}
app.function_editor = Some(editor);
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cycles_are_detected() {
let mut g = FunctionGraph::default();
let a = g.add("get_float2", &[], Some(Value::Text("$pos".into())));
let b = g.add("swizzle1", &[a], Some(Value::Int(0)));
// a feeds b: wiring b into a would loop
assert!(reaches(&g, a, b));
assert!(!reaches(&g, b, a));
assert_eq!(arity("add"), 2);
assert!(materialcraft_engine::nodes::function::default_value("const_float1").is_some());
}
editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node);
}
+25 -66
View File
@@ -1,32 +1,31 @@
use super::{FunctionEditor, FunctionTarget, selection};
use crate::{MaterialCraftApp, i18n::tr, menus};
use super::{FunctionEditor, FunctionTarget};
use crate::{MaterialCraftApp, graph::edit_menu, i18n::tr, menus};
use egui::Ui;
use materialcraft_engine::{
core::{FunctionGraph, FunctionNode},
nodes::function::{FUNCTIONS, default_value},
};
use materialcraft_engine::FunctionEdit;
use serde_json::json;
pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, graph: &mut FunctionGraph, ui: &mut Ui) -> bool {
let mut changed = false;
pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) {
let Some(target) = editor.command_target() else { return };
let mut add = None;
let standalone = matches!(editor.target, FunctionTarget::Graph(_));
let standalone = matches!(editor.target, FunctionTarget::Graph);
ui.set_min_width(290.0);
ui.menu_button(tr("Add node"), |ui| {
let entries = FUNCTIONS.iter().filter(|operation| operation.id != "passthrough").map(|operation| (operation.id, operation.label, operation.category));
let entries = target
.available_operations(&app.session)
.filter(|operation| operation.id != "passthrough")
.map(|operation| (operation.id, operation.label, operation.category));
add = crate::graph::add_node_menu::show(ui, entries);
});
if standalone {
for (label, command, parameters) in [
("Add Comment", "graph.comment.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})),
("Add Frame", "graph.frame.add", json!({"rect": [editor.menu_at.x, editor.menu_at.y, 400, 260]})),
("Add Navigation pin", "graph.pin.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})),
] {
if ui.button(tr(label)).clicked() {
if edit_menu::button(ui, label, command, true) {
app.run(command, parameters);
editor.selection.clear();
ui.close();
}
}
}
@@ -35,64 +34,24 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, grap
ui.close();
}
ui.separator();
if ui.add(egui::Button::new(tr("Save package")).shortcut_text("Ctrl+S")).clicked() {
if edit_menu::button(ui, "Save package", "file.save", menus::enabled(app, "file.save")) {
menus::invoke(app, ui.ctx(), "file.save");
ui.close();
}
for (label, command) in [
("Paste", "edit.paste"),
("Paste without link", "edit.pasteWithoutLinks"),
("Select all", "edit.selectAll"),
("Previous pin", "ui.graph.previousPin"),
("Next pin", "ui.graph.nextPin"),
("Copy selection", "edit.copy"),
("Delete selection", "edit.delete"),
("Delete and relink", "edit.deleteRelink"),
("Duplicate selection", "edit.duplicate"),
("Duplicate selection without link", "edit.duplicateWithoutLinks"),
("Select upstream nodes", "graph.selectUpstream"),
("Select downstream nodes", "graph.selectDownstream"),
("Disable selection", "graph.node.disable"),
] {
if command == "edit.copy" {
ui.separator();
}
let annotation = standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink");
let enabled = if annotation { true } else { selection::enabled(editor, command).unwrap_or_else(|| standalone && menus::enabled(app, command)) };
let mut button = egui::Button::new(tr(label));
if let Some(shortcut) = menus::shortcut_of(command) {
button = button.shortcut_text(shortcut);
}
if ui.add_enabled(enabled, button).clicked() {
if annotation {
app.run(command, json!({}));
} else if command.starts_with("ui.") {
menus::invoke(app, ui.ctx(), command);
editor.pan = app.ui.graph_camera.pan.into();
} else {
changed |= selection::run(editor, graph, command, app.ui.prefs.snap_to_grid);
if let Some(command) =
edit_menu::selection(ui, |command| super::actions::editor_enabled(app, editor, command).unwrap_or_else(|| menus::enabled(app, command)))
&& !super::actions::invoke_editor(app, editor, command)
{
app.run(command, json!({}));
}
if standalone {
for (label, command) in [("Previous pin", "ui.graph.previousPin"), ("Next pin", "ui.graph.nextPin")] {
if edit_menu::button(ui, label, command, menus::enabled(app, command)) {
crate::graph::actions::invoke(app, command);
editor.set_camera(app.ui.graph_camera);
}
ui.close();
}
}
if let Some(operation) = add {
let id = graph.next_id();
let inputs = FUNCTIONS.iter().find(|definition| definition.id == operation).map_or(0, |definition| definition.inputs.len());
graph.nodes.push(FunctionNode {
id,
type_code: 0,
op: operation.into(),
inputs: vec![None; inputs],
value: default_value(operation),
pos: materialcraft_engine::graph_grid::snap_position([editor.menu_at.x, editor.menu_at.y], app.ui.prefs.snap_to_grid),
});
editor.selection = vec![id];
if graph.output.is_none() {
graph.output = Some(id);
}
changed = true;
editor.edit(app, FunctionEdit::Add { operation: operation.into(), at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false);
}
changed
}
@@ -0,0 +1,16 @@
use super::function_port::FunctionPort;
use crate::graph::{GraphCamera, canvas_geometry::CanvasGeometry, frame_hit::FrameHit};
use egui::{Rect, Response};
use materialcraft_engine::core::Value;
pub(super) struct FunctionCanvas {
pub response: Response,
pub camera: GraphCamera,
pub geometry: CanvasGeometry,
pub ports: Vec<FunctionPort>,
pub nodes: Vec<(u32, Response)>,
pub values: Vec<(u32, Value)>,
pub frames: Vec<FrameHit>,
pub comments: Vec<(u64, Rect)>,
pub clear_annotation: bool,
}
+2 -1
View File
@@ -3,5 +3,6 @@ use egui::Vec2;
pub(super) enum FunctionDrag {
Node(u32, Vec2),
Wire(u32),
Pan,
Box { start: egui::Pos2 },
Pan(egui::PointerButton),
}
+58 -17
View File
@@ -1,29 +1,45 @@
use crate::MaterialCraftApp;
use egui::{Pos2, Vec2, vec2};
use materialcraft_engine::core::FunctionGraph;
use materialcraft_engine::core::NodeId;
use serde_json::json;
use super::{FunctionDrag, FunctionTarget};
pub struct FunctionEditor {
pub node: Option<NodeId>,
pub graph: usize,
pub(crate) selection: Vec<u32>,
pub(crate) inspected_node: Option<u32>,
pub(super) clipboard: Vec<materialcraft_engine::core::FunctionNode>,
pub target: FunctionTarget,
pub(super) pan: Vec2,
pub(super) zoom: f32,
pub(super) drag: Option<FunctionDrag>,
pub(super) menu_at: Pos2,
pub(super) framed: bool,
pub(crate) framed: bool,
}
impl FunctionEditor {
pub fn standalone(graph: usize) -> Self {
Self::with_target(graph, None, FunctionTarget::Graph)
}
pub(crate) fn set_camera(&mut self, camera: crate::state::GraphCamera) {
self.pan = camera.pan.into();
self.zoom = camera.zoom;
}
pub fn new(graph: usize, node: NodeId, target: FunctionTarget) -> Self {
Self::with_target(graph, Some(node), target)
}
fn with_target(graph: usize, node: Option<NodeId>, target: FunctionTarget) -> Self {
Self {
node: None,
target: FunctionTarget::Graph(graph),
graph,
node,
target,
selection: Vec::new(),
inspected_node: None,
clipboard: Vec::new(),
pan: vec2(-40.0, -40.0),
zoom: 1.0,
drag: None,
@@ -32,18 +48,43 @@ impl FunctionEditor {
}
}
pub fn new(node: NodeId, target: FunctionTarget) -> FunctionEditor {
FunctionEditor {
node: Some(node),
selection: Vec::new(),
inspected_node: None,
clipboard: Vec::new(),
target,
pan: vec2(-40.0, -40.0),
zoom: 1.0,
drag: None,
menu_at: Pos2::ZERO,
framed: false,
pub(crate) fn current<'a>(&self, app: &'a MaterialCraftApp) -> Option<&'a FunctionGraph> {
if self.graph != app.session.graph {
return None;
}
self.command_target()?.current(&app.session).ok()
}
pub(crate) fn command_target(&self) -> Option<materialcraft_engine::FunctionGraphTarget> {
use materialcraft_engine::FunctionGraphTarget;
Some(match &self.target {
FunctionTarget::Graph => FunctionGraphTarget::Graph,
FunctionTarget::Parameter(parameter) => FunctionGraphTarget::Parameter { node: self.node?, parameter: parameter.clone() },
FunctionTarget::Dynamic(parameter) => FunctionGraphTarget::Dynamic { node: self.node?, parameter: parameter.clone() },
FunctionTarget::Pattern { node, parameter } => FunctionGraphTarget::Pattern { owner: self.node?, node: *node, parameter: parameter.clone() },
})
}
pub(crate) fn edit(&mut self, app: &mut MaterialCraftApp, edit: materialcraft_engine::FunctionEdit, merge: bool) {
if self.current(app).is_none() {
return;
}
let Some(target) = self.command_target() else { return };
if let Some(result) = app.run("graph.function.edit", json!({"target": target, "edit": edit, "merge": merge}))
&& let Some(id) = result.get("id").and_then(serde_json::Value::as_u64).and_then(|id| u32::try_from(id).ok())
{
self.selection = vec![id];
if self.target == FunctionTarget::Graph {
app.session.selection = vec![NodeId(u64::from(id))];
app.session.annotation_selection = None;
}
}
}
pub(crate) fn selection_parameters(&self, command: &str) -> serde_json::Value {
let selection = if matches!(command, "edit.selectAll" | "edit.selectNone") { &[][..] } else { self.selection.as_slice() };
json!({"graph": self.graph, "function": self.command_target(), "ids": selection, "at": [self.menu_at.x, self.menu_at.y]})
}
}
@@ -0,0 +1,9 @@
use egui::Pos2;
pub(super) struct FunctionPort {
pub node: u32,
pub slot: Option<usize>,
pub position: Pos2,
pub radius: f32,
pub label: &'static str,
}
@@ -1,6 +1,6 @@
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum FunctionTarget {
Graph(usize),
Graph,
Parameter(String),
Dynamic(String),
Pattern { node: u32, parameter: String },
@@ -9,7 +9,7 @@ pub enum FunctionTarget {
impl FunctionTarget {
pub fn parameter(&self) -> &str {
match self {
Self::Graph(_) => "",
Self::Graph => "",
Self::Parameter(parameter) | Self::Dynamic(parameter) | Self::Pattern { parameter, .. } => parameter,
}
}
+51
View File
@@ -0,0 +1,51 @@
use super::{FunctionDrag, FunctionEditor, FunctionTarget};
use crate::{MaterialCraftApp, graph::node_card};
use egui::{Color32, Pos2, Rect, vec2};
use materialcraft_engine::core::FunctionNode;
pub(super) fn arity(op: &str) -> usize {
materialcraft_engine::nodes::function::definition(op).map_or(0, |o| o.inputs.len())
}
pub(super) fn category_color(category: &str) -> Color32 {
match category {
"Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e),
"Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5),
"Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34),
"Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0),
"Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c),
"Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c),
_ => Color32::from_rgb(0x1e, 0x8a, 0xa0),
}
}
pub(super) fn visible_inputs(node: &FunctionNode) -> usize {
let count = arity(&node.op);
crate::graph::input_visibility::count((0..count).map(|index| node.inputs.get(index).is_some_and(Option::is_some)), 1)
}
pub(super) fn node_rect(node: &FunctionNode, previews: bool) -> Rect {
node_card::bounds(node.pos, visible_inputs(node), 1, previews, node.op == "passthrough")
}
pub(super) fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 {
node_card::port(bounds, index, visible_inputs(node), false, node.op == "passthrough")
}
pub(super) fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 {
node_card::port(bounds, 0, 1, true, node.op == "passthrough")
}
pub(super) fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool, selected: bool) -> Rect {
let mut bounds = node_rect(node, app.ui.prefs.thumbnails);
if let Some(FunctionDrag::Node(d, delta)) = &editor.drag
&& (*d == node.id || selected)
{
let position = materialcraft_engine::graph_grid::translate(node.pos, (*delta).into(), snap);
bounds = bounds.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1]));
}
if matches!(editor.target, FunctionTarget::Graph) {
bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id)));
}
bounds
}
+125
View File
@@ -0,0 +1,125 @@
use super::function_port::FunctionPort;
use super::{FunctionDrag, FunctionEditor};
use crate::{MaterialCraftApp, graph::GraphCamera, theme::Tokens};
use egui::{Pos2, Rect, Stroke, Ui};
use materialcraft_engine::{FunctionEdit, core::NodeId};
pub(super) fn handle(
app: &mut MaterialCraftApp,
editor: &mut FunctionEditor,
ui: &mut Ui,
response: &egui::Response,
ports: &[FunctionPort],
rectangles: &[(NodeId, Rect)],
on_annotation: bool,
) {
let canvas_bounds = response.rect;
let pointer = ui.input(|input| input.pointer.hover_pos());
let painter = ui.painter_at(canvas_bounds);
let tokens = Tokens::get(ui.ctx());
let snap = app.ui.prefs.snap_to_grid;
if crate::graph::gesture::cancelled(ui) {
editor.drag = None;
return;
}
// Gestures: wires from output dots, panning
let near = |pointer: Pos2| crate::graph::port_hit::nearest_by(ports, pointer, |port| (port.position, port.radius)).map(|port| (port.node, port.slot));
if editor.drag.is_none() && GraphCamera::pan_started(ui, canvas_bounds) {
editor.drag = Some(FunctionDrag::Pan(crate::graph::gesture::pan_button(ui)));
} else if ui.input(|input| input.pointer.primary_pressed())
&& editor.drag.is_none()
&& !app.graph.is_dragging()
&& let Some(pointer_position) = pointer
&& ui.rect_contains_pointer(canvas_bounds)
&& let Some((id, None)) = near(pointer_position)
{
editor.drag = Some(FunctionDrag::Wire(id));
}
if editor.drag.is_none()
&& !app.graph.is_dragging()
&& response.hovered()
&& ui.input(|input| input.pointer.primary_pressed())
&& let Some(start) = pointer
&& !on_annotation
{
if matches!(editor.target, super::FunctionTarget::Graph) && app.session.annotation_selection.is_some() {
app.run("graph.annotation.select", serde_json::json!({}));
}
editor.drag = Some(FunctionDrag::Box { start });
}
let delta = ui.input(|input| input.pointer.delta());
match &mut editor.drag {
Some(FunctionDrag::Node(_, offset)) => *offset += delta / editor.zoom,
Some(FunctionDrag::Pan(_)) => editor.pan -= delta / editor.zoom,
Some(FunctionDrag::Wire(id)) => {
if let (Some(pointer_position), Some(source_id)) = (pointer, ports.iter().find(|port| port.node == *id && port.slot.is_none())) {
crate::graph::wire_geometry::bezier(&painter, source_id.position, pointer_position, Stroke::new(2.0, tokens.accent));
}
}
Some(FunctionDrag::Box { start }) => {
if let Some(pointer) = pointer {
crate::graph::node_selection::paint_box(&painter, *start, pointer, tokens.accent);
}
}
None => {}
}
let owner = match editor.drag {
Some(FunctionDrag::Pan(button)) => button,
_ => egui::PointerButton::Primary,
};
if crate::graph::gesture::finished(ui, owner) {
match editor.drag.take() {
Some(FunctionDrag::Node(id, offset)) => {
if offset.length() > 0.5 {
let mut ids = editor.selection.clone();
if !ids.contains(&id) {
ids.push(id);
}
editor.edit(app, FunctionEdit::Move { ids, by: offset.into(), snap }, false);
}
}
Some(FunctionDrag::Box { start }) => {
if let Some(pointer) = pointer {
let nodes = rectangles.iter().map(|(id, bounds)| (id.0 as u32, *bounds));
crate::graph::node_selection::select_box(&mut editor.selection, nodes, start, pointer, ui.input(|input| input.modifiers));
}
}
Some(FunctionDrag::Wire(from)) => {
if let Some(pointer) = pointer
&& let Some((to, Some(input))) = near(pointer)
&& from != to
{
editor.edit(app, FunctionEdit::Connect { from, to, input }, false);
}
}
_ => {}
}
}
if response.clicked() && !ui.input(|input| input.modifiers.alt) {
crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers));
}
let camera = GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom };
// Adding operations
if response.secondary_clicked()
&& let Some(pointer_position) = pointer
{
editor.menu_at = camera.to_graph(pointer_position);
}
if response.hovered()
&& !ui.ctx().egui_wants_keyboard_input()
&& ui.input(|input| input.key_pressed(egui::Key::Space))
&& let Some(pointer_position) = pointer
{
editor.menu_at = camera.to_graph(pointer_position);
egui::Popup::open_id(ui.ctx(), response.id.with("menu"));
}
response.context_menu(|ui| {
super::context_menu::show(app, editor, ui);
});
}
+9 -12
View File
@@ -1,24 +1,21 @@
use crate::{MaterialCraftApp, i18n::tr};
use egui::Ui;
use materialcraft_engine::nodes::function::{FUNCTIONS, default_value};
use serde_json::json;
use materialcraft_engine::FunctionEdit;
pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let Some(target) = app.function_editor.as_ref().and_then(|editor| editor.command_target()) else { return };
let operations = target.available_operations(&app.session);
ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions")));
let search = app.ui.library_search.to_ascii_lowercase();
egui::ScrollArea::vertical().show(ui, |ui| {
for definition in FUNCTIONS.iter().filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) {
for definition in operations.filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) {
if ui.selectable_label(false, tr(definition.label)).double_clicked()
&& let Some(mut graph) = app.session.graph().ok().and_then(|graph| graph.function.clone())
&& let Some(mut editor) = app.function_editor.take()
{
let id = graph.add(definition.id, &[], default_value(definition.id));
if graph.output.is_none() {
graph.output = Some(id);
}
if let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) {
node.pos = materialcraft_engine::graph_grid::snap_position(node.pos, app.ui.prefs.snap_to_grid);
}
app.run("graph.function.set", json!({"function": graph}));
let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]);
editor.edit(app, FunctionEdit::Add { operation: definition.id.into(), at, snap: app.ui.prefs.snap_to_grid }, false);
app.function_editor = Some(editor);
}
}
});
+11 -2
View File
@@ -6,9 +6,18 @@ mod function_target;
pub(crate) mod library;
mod port_label;
pub(crate) mod properties;
mod selection;
pub(crate) use canvas::{enabled, invoke, show, show_graph};
pub(crate) use actions::{enabled, invoke};
use function_drag::FunctionDrag;
pub use function_editor::FunctionEditor;
pub use function_target::FunctionTarget;
pub(crate) use panel::show_graph;
mod actions;
mod geometry;
mod input;
mod panel;
mod function_canvas;
mod function_port;
mod render;
+13
View File
@@ -0,0 +1,13 @@
use super::{FunctionEditor, FunctionTarget, canvas::canvas};
use crate::MaterialCraftApp;
use egui::Ui;
pub(crate) fn show_graph(app: &mut MaterialCraftApp, ui: &mut Ui) {
let index = app.session.graph;
let mut editor = app.function_editor.take().filter(|editor| editor.graph == index).unwrap_or_else(|| FunctionEditor::standalone(index));
if editor.target == FunctionTarget::Graph {
editor.selection = app.session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()).collect();
}
canvas(app, &mut editor, ui);
app.function_editor = Some(editor);
}
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more