use crate::{
ALL, Edge, EdgeKind, HashMap, HashSet, OwnedArgument, RecordError,
classify,
handle::{self, Handle},
};
use core::{cmp::Ordering, mem};
use indexmap::{IndexMap, IndexSet};
use std::sync::LazyLock;
pub(crate) type AttributeTable = IndexMap<Handle, OwnedArgument>;
pub(crate) type SampleTable = IndexMap<Handle, Vec<(f64, OwnedArgument)>>;
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Node {
pub(crate) node_type: Handle,
pub(crate) attributes: Option<Box<AttributeTable>>,
pub(crate) samples: Option<Box<SampleTable>>,
}
static NO_ATTRIBUTES: LazyLock<AttributeTable> = LazyLock::new(IndexMap::new);
static NO_SAMPLES: LazyLock<SampleTable> = LazyLock::new(IndexMap::new);
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.node_type == other.node_type
&& self.attribute_table() == other.attribute_table()
&& self.sample_table() == other.sample_table()
}
}
impl Node {
pub fn attributes(&self) -> impl Iterator<Item = (&str, &OwnedArgument)> {
self.attribute_table()
.iter()
.map(|(name, arg)| (name.as_str(), arg))
}
pub fn attribute(&self, name: &str) -> Option<&OwnedArgument> {
handle::map_get(self.attribute_table(), name)
}
pub(crate) fn attribute_table(&self) -> &AttributeTable {
self.attributes.as_deref().unwrap_or(&NO_ATTRIBUTES)
}
pub(crate) fn attribute_table_mut(&mut self) -> &mut AttributeTable {
self.attributes.get_or_insert_with(Box::default)
}
pub fn samples(
&self,
) -> impl Iterator<Item = (&str, &[(f64, OwnedArgument)])> {
self.sample_table()
.iter()
.map(|(name, calls)| (name.as_str(), calls.as_slice()))
}
pub fn sample_calls(&self, name: &str) -> Option<&[(f64, OwnedArgument)]> {
handle::map_get(self.sample_table(), name).map(Vec::as_slice)
}
pub(crate) fn sample_table(&self) -> &SampleTable {
self.samples.as_deref().unwrap_or(&NO_SAMPLES)
}
pub(crate) fn sample_table_mut(&mut self) -> &mut SampleTable {
self.samples.get_or_insert_with(Box::default)
}
pub fn f32(&self, name: &str) -> Option<f32> {
self.effective(name)?.as_f32()
}
pub fn f64(&self, name: &str) -> Option<f64> {
match self.effective(name)?.as_f64s()? {
[value] => Some(*value),
_ => None,
}
}
pub fn i32(&self, name: &str) -> Option<i32> {
self.effective(name)?.as_i32()
}
pub fn flag(&self, name: &str) -> Option<bool> {
Some(self.i32(name)? != 0)
}
pub fn string(&self, name: &str) -> Option<&str> {
core::str::from_utf8(self.bytes(name)?).ok()
}
pub fn bytes(&self, name: &str) -> Option<&[u8]> {
match self.effective(name)?.as_strings()? {
[value] => Some(value),
_ => None,
}
}
pub fn node_type(&self) -> &str {
&self.node_type
}
pub fn effective(&self, name: &str) -> Option<&OwnedArgument> {
if let Some(arg) = handle::map_get(self.attribute_table(), name) {
return Some(arg);
}
handle::map_get(self.sample_table(), name)?
.last()
.map(|(_, arg)| arg)
}
}
pub(crate) fn latest_per_time(
calls: &[(f64, OwnedArgument)],
) -> Vec<(f64, &OwnedArgument)> {
let mut standing: Vec<(f64, usize, &OwnedArgument)> = calls
.iter()
.enumerate()
.map(|(index, (time, arg))| (*time, index, arg))
.collect();
standing.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
standing.dedup_by(|later, earlier| {
if later.0.total_cmp(&earlier.0) == Ordering::Equal {
earlier.2 = later.2;
true
} else {
false
}
});
standing
.into_iter()
.map(|(time, _, arg)| (time, arg))
.collect()
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct Changes {
pub(crate) created: IndexSet<Handle>,
pub(crate) deleted: IndexMap<Handle, Handle>,
pub(crate) attributes: IndexSet<(Handle, Handle)>,
pub edges_added: Vec<Edge>,
pub edges_removed: Vec<Edge>,
pub edges_rearmed: Vec<Edge>,
}
impl Changes {
pub fn created(&self) -> impl Iterator<Item = &str> {
self.created.iter().map(|handle| handle.as_str())
}
pub fn was_created(&self, handle: &str) -> bool {
handle::set_contains(&self.created, handle)
}
pub fn deleted(&self) -> impl Iterator<Item = (&str, &str)> {
self.deleted
.iter()
.map(|(handle, node_type)| (handle.as_str(), node_type.as_str()))
}
pub fn deleted_type(&self, handle: &str) -> Option<&str> {
handle::map_get(&self.deleted, handle)
.map(|node_type| node_type.as_str())
}
pub fn attributes(&self) -> impl Iterator<Item = (&str, &str)> {
self.attributes
.iter()
.map(|(handle, name)| (handle.as_str(), name.as_str()))
}
pub fn is_empty(&self) -> bool {
self.created.is_empty()
&& self.deleted.is_empty()
&& self.attributes.is_empty()
&& self.edges_added.is_empty()
&& self.edges_removed.is_empty()
&& self.edges_rearmed.is_empty()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Affected<'a> {
pub roots: IndexSet<&'a str>,
pub shaders: IndexSet<&'a str>,
pub outputs: bool,
pub everything: bool,
}
fn insert_root<'a>(roots: &mut IndexSet<&'a str>, handle: &'a str) {
roots.insert(handle);
}
fn record_edge(list: &mut Vec<Edge>, edge: Edge) {
match list.iter_mut().find(|recorded| {
recorded.from == edge.from
&& recorded.to == edge.to
&& recorded.kind == edge.kind
}) {
Some(recorded) => *recorded = edge,
None => list.push(edge),
}
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Scene {
nodes: IndexMap<Handle, Node>,
edges: Vec<Edge>,
evaluations: Vec<Vec<OwnedArgument>>,
by_from: HashMap<Handle, Vec<usize>>,
by_to: HashMap<Handle, Vec<usize>>,
by_to_attr: HashMap<(Handle, Handle), Vec<usize>>,
changes: Changes,
}
impl PartialEq for Scene {
fn eq(&self, other: &Self) -> bool {
self.nodes == other.nodes
&& self.edges == other.edges
&& self.evaluations == other.evaluations
}
}
impl Scene {
pub fn take_changes(&mut self) -> Changes {
mem::take(&mut self.changes)
}
pub fn changes(&self) -> &Changes {
&self.changes
}
pub fn affected<'a>(&'a self, changes: &'a Changes) -> Affected<'a> {
let mut affected = Affected::default();
for (handle, _) in &changes.attributes {
if crate::is_reserved(handle) {
affected.everything = true;
continue;
}
match handle::map_get(&self.nodes, handle) {
Some(node) if node.node_type == "shader" => {
affected.shaders.insert(handle.as_str());
}
Some(node) if node.node_type == "attributes" => {
self.through_bindings(handle, &mut affected.roots);
}
_ => insert_root(&mut affected.roots, handle),
}
if self.is_output_node(handle) {
affected.outputs = true;
}
}
for handle in &changes.created {
insert_root(&mut affected.roots, handle);
}
for handle in changes.deleted.keys() {
affected.roots.insert(handle.as_str());
}
for edge in changes
.edges_added
.iter()
.chain(&changes.edges_removed)
.chain(&changes.edges_rearmed)
{
match &edge.kind {
EdgeKind::SceneMember | EdgeKind::SetMember => {
insert_root(&mut affected.roots, &edge.from);
if self.is_output_node(&edge.from)
|| self.is_output_node(&edge.to)
{
affected.outputs = true;
}
}
EdgeKind::InstanceSource => {
insert_root(&mut affected.roots, &edge.from);
affected.roots.insert(edge.to.as_str());
}
EdgeKind::AttributeBinding | EdgeKind::ShaderAttributes => {
insert_root(&mut affected.roots, &edge.to);
self.set_members(&edge.to, &mut affected.roots);
}
EdgeKind::SurfaceShader
| EdgeKind::DisplacementShader
| EdgeKind::VolumeShader => {
affected.shaders.insert(edge.from.as_str());
self.through_bindings(&edge.to, &mut affected.roots);
}
EdgeKind::Screen
| EdgeKind::OutputLayer
| EdgeKind::OutputDriver
| EdgeKind::LightSet
| EdgeKind::BackgroundLayer
| EdgeKind::LensShader => {
affected.outputs = true;
}
EdgeKind::ExclusiveShading => {
affected.everything = true;
}
EdgeKind::Bounds
| EdgeKind::SubsurfaceSet
| EdgeKind::FaceSet => {
insert_root(&mut affected.roots, &edge.to);
self.set_members(&edge.to, &mut affected.roots);
}
EdgeKind::ShaderNetwork { .. } | EdgeKind::Other { .. } => {
for handle in [&edge.from, &edge.to] {
if self.is_shader_node(handle) {
affected.shaders.insert(handle.as_str());
} else {
insert_root(&mut affected.roots, handle);
}
}
}
}
}
if affected.everything {
affected.roots.clear();
}
affected
}
pub fn descendants<'a>(&'a self, handle: &'a str) -> IndexSet<&'a str> {
let mut out = IndexSet::new();
self.descend(handle, &mut out);
out
}
fn descend<'a>(&'a self, handle: &'a str, out: &mut IndexSet<&'a str>) {
let mut stack = vec![handle];
while let Some(node) = stack.pop() {
if !out.insert(node) {
continue;
}
for edge in self.edges_to_attribute(node, "objects") {
stack.push(&edge.from);
}
for edge in self.edges_from(node) {
if edge.kind.to_attribute() == "sourcemodels" {
stack.push(&edge.to);
}
}
}
}
fn through_bindings<'a>(
&'a self,
handle: &str,
out: &mut IndexSet<&'a str>,
) {
for edge in self.edges_from(handle) {
if matches!(
edge.kind.to_attribute(),
"geometryattributes" | "shaderattributes"
) {
insert_root(out, &edge.to);
self.set_members(&edge.to, out);
}
}
}
fn set_members<'a>(&'a self, handle: &str, out: &mut IndexSet<&'a str>) {
for edge in self.edges_to_attribute(handle, "members") {
insert_root(out, &edge.from);
}
}
fn is_shader_node(&self, handle: &str) -> bool {
handle::map_get(&self.nodes, handle)
.is_some_and(|node| node.node_type() == "shader")
}
fn is_output_node(&self, handle: &str) -> bool {
handle::map_get(&self.nodes, handle).is_some_and(|node| {
node.node_type().ends_with("camera")
|| matches!(
node.node_type(),
"screen" | "outputlayer" | "outputdriver"
)
})
}
pub fn nodes(&self) -> impl Iterator<Item = (&str, &Node)> {
self.nodes
.iter()
.map(|(handle, node)| (handle.as_str(), node))
}
pub fn evaluations(&self) -> impl Iterator<Item = &[OwnedArgument]> {
self.evaluations.iter().map(Vec::as_slice)
}
pub(crate) fn evaluate(&mut self, args: Vec<OwnedArgument>) {
self.evaluations.push(args);
}
pub fn node(&self, handle: &str) -> Option<&Node> {
handle::map_get(&self.nodes, handle)
}
pub(crate) fn node_entry(&self, handle: &str) -> Option<(&str, &Node)> {
handle::map_entry(&self.nodes, handle)
}
pub fn edges(&self) -> impl Iterator<Item = &Edge> {
self.edges.iter()
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub fn edges_from<'a>(
&'a self,
handle: &str,
) -> impl Iterator<Item = &'a Edge> + use<'a> {
self.indexed(&self.by_from, handle)
}
pub fn edges_to<'a>(
&'a self,
handle: &str,
) -> impl Iterator<Item = &'a Edge> + use<'a> {
self.indexed(&self.by_to, handle)
}
pub fn edges_to_attribute<'a>(
&'a self,
handle: &str,
to_attribute: &str,
) -> impl Iterator<Item = &'a Edge> + use<'a> {
handle::get_pair(&self.by_to_attr, handle, to_attribute)
.into_iter()
.flatten()
.map(|position| &self.edges[*position])
}
fn indexed<'a>(
&'a self,
index: &'a HashMap<Handle, Vec<usize>>,
handle: &str,
) -> impl Iterator<Item = &'a Edge> + use<'a> {
crate::handle::get(index, handle)
.into_iter()
.flatten()
.map(|position| &self.edges[*position])
}
fn reindex(&mut self) {
self.by_from.clear();
self.by_to.clear();
self.by_to_attr.clear();
for (position, edge) in self.edges.iter().enumerate() {
self.by_from
.entry(handle::handle(&edge.from))
.or_default()
.push(position);
self.by_to
.entry(handle::handle(&edge.to))
.or_default()
.push(position);
self.by_to_attr
.entry((
handle::handle(&edge.to),
handle::handle(edge.kind.to_attribute()),
))
.or_default()
.push(position);
}
}
pub fn create(
&mut self,
handle: &str,
node_type: &str,
) -> Result<(), RecordError> {
if crate::is_reserved(handle) {
return Err(RecordError::Reserved {
handle: handle.to_string(),
});
}
match handle::map_get(&self.nodes, handle) {
Some(existing) if existing.node_type() != node_type => {
Err(RecordError::TypeMismatch {
handle: handle.to_string(),
existing: existing.node_type().to_string(),
requested: node_type.to_string(),
})
}
Some(_) => Ok(()),
None => {
self.nodes.insert(
crate::handle::handle(handle),
Node {
node_type: crate::handle::handle(node_type),
..Node::default()
},
);
self.changes.created.insert(handle::handle(handle));
Ok(())
}
}
}
pub fn delete(&mut self, handle: &str) -> Result<(), RecordError> {
if crate::is_reserved(handle) {
Err(RecordError::Reserved {
handle: handle.to_string(),
})
} else {
if let Some(node) = handle::map_remove(&mut self.nodes, handle) {
handle::set_remove(&mut self.changes.created, handle);
self.changes
.deleted
.insert(handle::handle(handle), node.node_type);
}
for edge in self
.edges
.iter()
.filter(|e| e.from == handle || e.to == handle)
{
record_edge(&mut self.changes.edges_removed, edge.clone());
}
self.edges.retain(|e| e.from != handle && e.to != handle);
self.reindex();
Ok(())
}
}
fn is_known(&self, handle: &str) -> bool {
handle == crate::ROOT
|| handle == crate::GLOBAL
|| handle::map_get(&self.nodes, handle).is_some()
}
pub fn delete_recursive(
&mut self,
handle: &str,
) -> Result<(), RecordError> {
if crate::is_reserved(handle) {
return Err(RecordError::Reserved {
handle: handle.to_string(),
});
}
let mut doomed = HashSet::new();
doomed.insert(handle.to_string());
loop {
let candidates = doomed
.iter()
.flat_map(|node| self.edges_to(node))
.filter(|edge| edge.strength() <= 0)
.map(|edge| edge.from().to_string())
.filter(|from| !doomed.contains(from.as_str()))
.collect::<Vec<_>>();
let mut grew = false;
for candidate in candidates {
let leads_elsewhere = self
.edges_from(&candidate)
.any(|edge| !doomed.contains(edge.to()));
let held = self.edges_from(&candidate).any(|edge| {
doomed.contains(edge.to()) && edge.strength() > 0
});
if !leads_elsewhere && !held && doomed.insert(candidate) {
grew = true;
}
}
if !grew {
break;
}
}
for handle in &doomed {
if let Some(node) = handle::map_get(&self.nodes, handle) {
let node_type = handle::copy(&node.node_type);
handle::set_remove(&mut self.changes.created, handle);
self.changes
.deleted
.insert(handle::handle(handle), node_type);
}
}
for edge in self.edges.iter().filter(|edge| {
doomed.contains(edge.from()) || doomed.contains(edge.to())
}) {
record_edge(&mut self.changes.edges_removed, edge.clone());
}
self.nodes
.retain(|handle, _| !doomed.contains(handle.as_str()));
self.edges.retain(|edge| {
!doomed.contains(edge.from()) && !doomed.contains(edge.to())
});
self.reindex();
Ok(())
}
pub fn set_attribute(
&mut self,
handle: &str,
args: Vec<OwnedArgument>,
) -> Result<(), RecordError> {
self.node_mut(handle)?;
let node_handle = handle::handle(handle);
let node = self
.nodes
.get_mut(&node_handle)
.expect("node_mut found or created it");
for arg in args {
let name = handle::handle(&arg.name);
if let Some(table) = node.samples.as_mut() {
table.shift_remove(&name);
}
self.changes
.attributes
.insert((handle::copy(&node_handle), handle::copy(&name)));
node.attribute_table_mut().insert(name, arg);
}
Ok(())
}
fn node_mut(&mut self, handle: &str) -> Result<&mut Node, RecordError> {
if crate::is_reserved(handle) {
Ok(self.nodes.entry(crate::handle::handle(handle)).or_default())
} else {
handle::map_get_mut(&mut self.nodes, handle).ok_or_else(|| {
RecordError::UnknownHandle {
handle: handle.to_string(),
}
})
}
}
pub fn set_attribute_at_time(
&mut self,
handle: &str,
time: f64,
args: Vec<OwnedArgument>,
) -> Result<(), RecordError> {
if !time.is_finite() {
return Err(RecordError::InvalidTime {
handle: handle.to_string(),
});
}
let time = time + 0.0;
self.node_mut(handle)?;
let node_handle = handle::handle(handle);
let node = self
.nodes
.get_mut(&node_handle)
.expect("node_mut found or created it");
for arg in args {
let name = handle::handle(&arg.name);
if let Some(table) = node.attributes.as_mut() {
table.shift_remove(&name);
}
self.changes
.attributes
.insert((handle::copy(&node_handle), handle::copy(&name)));
node.sample_table_mut()
.entry(name)
.or_default()
.push((time, arg));
}
Ok(())
}
pub fn delete_attribute(&mut self, handle: &str, name: &str) {
self.changes
.attributes
.insert((handle::handle(handle), handle::handle(name)));
if let Some(node) = handle::map_get_mut(&mut self.nodes, handle) {
if let Some(table) = node.attributes.as_mut() {
table.shift_remove(&handle::handle(name));
}
if let Some(table) = node.samples.as_mut() {
table.shift_remove(&handle::handle(name));
}
}
}
pub fn connect(
&mut self,
from: &str,
from_attribute: Option<&str>,
to: &str,
to_attribute: &str,
) -> Result<(), RecordError> {
self.connect_with_arguments(
from,
from_attribute,
to,
to_attribute,
Vec::new(),
)
}
pub fn connect_with_arguments(
&mut self,
from: &str,
from_attribute: Option<&str>,
to: &str,
to_attribute: &str,
args: Vec<OwnedArgument>,
) -> Result<(), RecordError> {
let kind = classify(from_attribute, to_attribute);
for handle in [from, to] {
if !self.is_known(handle) {
return Err(RecordError::UnknownHandle {
handle: handle.to_string(),
});
}
}
let existing = handle::get(&self.by_from, from).and_then(|positions| {
positions.iter().copied().find(|&at| {
let edge = &self.edges[at];
edge.to == to && edge.kind == kind
})
});
let mut rearmed = None;
match existing.map(|at| &mut self.edges[at]) {
Some(existing) => {
existing.args = args;
rearmed = Some(existing.clone());
}
None => {
self.by_from
.entry(handle::handle(from))
.or_default()
.push(self.edges.len());
self.by_to
.entry(handle::handle(to))
.or_default()
.push(self.edges.len());
self.by_to_attr
.entry((
handle::handle(to),
handle::handle(kind.to_attribute()),
))
.or_default()
.push(self.edges.len());
let edge = Edge {
from: handle::handle(from),
to: handle::handle(to),
kind,
args,
};
record_edge(&mut self.changes.edges_added, edge.clone());
self.edges.push(edge);
}
}
if let Some(edge) = rearmed {
record_edge(&mut self.changes.edges_rearmed, edge);
}
Ok(())
}
pub fn disconnect(
&mut self,
from: &str,
from_attribute: Option<&str>,
to: &str,
to_attribute: &str,
) -> Result<(), RecordError> {
let kind = if to_attribute == ALL {
None
} else {
Some(classify(from_attribute, to_attribute))
};
let from_port = from_attribute.unwrap_or_default();
let any_port = from_port == ALL;
let mut removed = Vec::new();
self.edges.retain(|edge| {
let port_matches = any_port
|| match &edge.kind {
EdgeKind::ShaderNetwork {
from_port: port, ..
} => port == from_port,
_ => from_port.is_empty(),
};
let attr_matches = match &kind {
Some(kind) if !any_port => &edge.kind == kind,
Some(kind) => edge.kind.to_attribute() == kind.to_attribute(),
None => true,
};
let matches = (from == ALL || edge.from == from)
&& (to == ALL || edge.to == to)
&& port_matches
&& attr_matches;
if matches {
removed.push(edge.clone());
}
!matches
});
for edge in removed {
record_edge(&mut self.changes.edges_removed, edge);
}
self.reindex();
Ok(())
}
}
#[cfg(test)]
mod tests;