Skip to main content

nsi_intermediate/scene/
mod.rs

1//! Node and attribute tables.
2//!
3//! `IndexMap` throughout: replaying a scene in a different order than it
4//! was recorded would make the `.nsi` stream diff against 3Delight
5//! meaningless.
6
7use crate::{
8    ALL, Edge, EdgeKind, HashMap, HashSet, OwnedArgument, RecordError,
9    classify_on,
10    handle::{self, Handle},
11};
12use core::{cmp::Ordering, mem};
13use indexmap::{IndexMap, IndexSet};
14use std::sync::LazyLock;
15
16/// One node's static attributes, by name.
17pub(crate) type AttributeTable = IndexMap<Handle, OwnedArgument>;
18
19/// Every `set_attribute_at_time` call for one node, per attribute, in
20/// call order.
21pub(crate) type SampleTable = IndexMap<Handle, Vec<(f64, OwnedArgument)>>;
22
23/// One ɴsɪ node.
24#[derive(Debug, Clone, Default)]
25#[non_exhaustive]
26pub struct Node {
27    /// The ɴsɪ node type this handle was created with. Read it with
28    /// [`Node::node_type`].
29    ///
30    /// Stored rather than public so `ustr_handles` can intern it: a
31    /// production scene says `"mesh"` a million times.
32    pub(crate) node_type: Handle,
33    /// Attributes set with `set_attribute`, keyed by name.
34    ///
35    /// Boxed and absent until one is set, for the same reason
36    /// [`Node::samples`] is: a scene is mostly nodes that hold
37    /// connections rather than values -- sets, groups, the transforms
38    /// above an asset -- and an inline `IndexMap` cost every one of
39    /// them a header it never filled.
40    pub(crate) attributes: Option<Box<AttributeTable>>,
41    /// Every `set_attribute_at_time` call, per attribute, **in call
42    /// order**.
43    ///
44    /// A call log rather than a timeline, because that is what ɴsɪ's
45    /// rules are stated over. 3Delight applies the last *call*, and a
46    /// table keyed by time cannot say which call that was: rendered,
47    /// with `visibility` set only at times, `t=1 -> 0` then `t=0 -> 1`
48    /// leaves the object **visible** while `t=1 -> 1` then `t=0 -> 0`
49    /// hides it. The same two times, opposite answers.
50    ///
51    /// The order is equally what decides the reach of an unreadable
52    /// sample: 3Delight rejects the argument at the call, so what
53    /// survives is what was set *after* it, not what sits later on the
54    /// timeline. And a same-time re-set is a call of its own here --
55    /// keeping the superseded value is the difference between `good`
56    /// replacing `good`, which sweeps, and `good` replacing an
57    /// unreadable one, which does not.
58    ///
59    /// Read it through [`Node::effective`] or the resolver rather than
60    /// walking it: they apply that rule. Setting an attribute
61    /// statically clears its entry, as ɴsɪ says it should.
62    ///
63    /// One entry per call, so a caller that re-sets one time in a loop
64    /// grows it. That is the record ɴsɪ's rules need, and for any
65    /// scene an exporter writes -- each time set once -- it is the
66    /// same values a table keyed by time would hold.
67    ///
68    /// Boxed and absent until something is set at a time: most nodes
69    /// in a scene never move, and an inline `IndexMap` cost every one
70    /// of them the header whether or not it held anything.
71    pub(crate) samples: Option<Box<SampleTable>>,
72}
73
74/// An empty table, for a node that has no attributes.
75static NO_ATTRIBUTES: LazyLock<AttributeTable> = LazyLock::new(IndexMap::new);
76
77/// An empty table, for a node that has no samples.
78static NO_SAMPLES: LazyLock<SampleTable> = LazyLock::new(IndexMap::new);
79
80/// Two nodes are equal when they say the same thing, which an absent
81/// table and an emptied one both do -- `delete_attribute` leaves the
82/// second, and a scene compared against a replay of itself must not
83/// hinge on which one it holds.
84impl PartialEq for Node {
85    fn eq(&self, other: &Self) -> bool {
86        self.node_type == other.node_type
87            && self.attribute_table() == other.attribute_table()
88            && self.sample_table() == other.sample_table()
89    }
90}
91
92impl Node {
93    /// This node's static attributes, by name.
94    pub fn attributes(&self) -> impl Iterator<Item = (&str, &OwnedArgument)> {
95        self.attribute_table()
96            .iter()
97            .map(|(name, arg)| (name.as_str(), arg))
98    }
99
100    /// One static attribute by name.
101    ///
102    /// **Use [`Node::effective`] unless you mean the static one
103    /// specifically**: an attribute set with `SetAttributeAtTime` is
104    /// not here, and the renderer honours it.
105    pub fn attribute(&self, name: &str) -> Option<&OwnedArgument> {
106        handle::map_get(self.attribute_table(), name)
107    }
108
109    pub(crate) fn attribute_table(&self) -> &AttributeTable {
110        self.attributes.as_deref().unwrap_or(&NO_ATTRIBUTES)
111    }
112
113    pub(crate) fn attribute_table_mut(&mut self) -> &mut AttributeTable {
114        self.attributes.get_or_insert_with(Box::default)
115    }
116
117    /// This node's sampled attributes, by name, each in call order.
118    pub fn samples(
119        &self,
120    ) -> impl Iterator<Item = (&str, &[(f64, OwnedArgument)])> {
121        self.sample_table()
122            .iter()
123            .map(|(name, calls)| (name.as_str(), calls.as_slice()))
124    }
125
126    /// The calls that set one attribute at a time, in call order.
127    pub fn sample_calls(&self, name: &str) -> Option<&[(f64, OwnedArgument)]> {
128        handle::map_get(self.sample_table(), name).map(Vec::as_slice)
129    }
130
131    pub(crate) fn sample_table(&self) -> &SampleTable {
132        self.samples.as_deref().unwrap_or(&NO_SAMPLES)
133    }
134
135    pub(crate) fn sample_table_mut(&mut self) -> &mut SampleTable {
136        self.samples.get_or_insert_with(Box::default)
137    }
138
139    /// One attribute as a single `f32`.
140    ///
141    /// Reads the **effective** value -- static or the last call at a
142    /// time -- and yields `None` when the attribute is absent or is not
143    /// exactly one `f32`. A backend pulling one number out of a node
144    /// wrote `node.effective(name).and_then(OwnedArgument::as_f32)`
145    /// before this existed; twenty such sites in one backend's flush
146    /// path is what asked for these.
147    pub fn f32(&self, name: &str) -> Option<f32> {
148        self.effective(name)?.as_f32()
149    }
150
151    /// One attribute as a single `f64`, on the same terms.
152    pub fn f64(&self, name: &str) -> Option<f64> {
153        match self.effective(name)?.as_f64s()? {
154            [value] => Some(*value),
155            _ => None,
156        }
157    }
158
159    /// One attribute as a single `i32`, on the same terms.
160    pub fn i32(&self, name: &str) -> Option<i32> {
161        self.effective(name)?.as_i32()
162    }
163
164    /// One attribute as an ɴsɪ integer flag.
165    ///
166    /// ɴsɪ writes booleans as `int` with `0` and `1` -- `withalpha`,
167    /// `dithering`, `clockwisewinding` -- so this is the shape those
168    /// are read in. Anything other than a single integer is `None`,
169    /// which a caller replaces with the attribute's documented
170    /// default rather than with `false`.
171    pub fn flag(&self, name: &str) -> Option<bool> {
172        Some(self.i32(name)? != 0)
173    }
174
175    /// One attribute as a single string.
176    ///
177    /// **`None` for a value that is not UTF-8**, which is not the same
178    /// as absent: an ɴsɪ string is bytes, and a file name on Linux need
179    /// not be UTF-8. Use [`Node::bytes`] where the value may be a path;
180    /// this is for the enumerants -- `"shader"`, `"uint8"`, `"color"`
181    /// -- where UTF-8 is the whole vocabulary.
182    pub fn string(&self, name: &str) -> Option<&str> {
183        core::str::from_utf8(self.bytes(name)?).ok()
184    }
185
186    /// One attribute as a single string's raw bytes.
187    pub fn bytes(&self, name: &str) -> Option<&[u8]> {
188        match self.effective(name)?.as_strings()? {
189            [value] => Some(value),
190            _ => None,
191        }
192    }
193
194    /// The ɴsɪ node type this handle was created with.
195    pub fn node_type(&self) -> &str {
196        &self.node_type
197    }
198
199    /// This node's effective value for an attribute.
200    ///
201    /// **Use this, not [`Node::attributes`].** `SetAttributeAtTime` on an
202    /// attribute
203    /// that is not motion data sets it for the whole shutter, exactly
204    /// as `SetAttribute` would: rendered, an `attributes` node whose
205    /// `visibility` is set only through `SetAttributeAtTime` hides the
206    /// object, identically to the static form. Reading [`Node::attributes`]
207    /// alone answers "not set" for an attribute the renderer honours,
208    /// which is a silent wrong answer -- and was one here until it was
209    /// rendered.
210    ///
211    /// Static first, then the **last call**, which is not the sample
212    /// at the greatest time -- see [`Node::samples`] for the render
213    /// that separates the two. The static value and the samples never
214    /// coexist: `set_attribute` clears that name from the log and
215    /// `set_attribute_at_time` clears the static value, which is ɴsɪ's
216    /// own rule and 3Delight's behaviour.
217    ///
218    /// This is what the resolver reads, so a backend asking a node
219    /// directly gets the same answer the resolver would.
220    pub fn effective(&self, name: &str) -> Option<&OwnedArgument> {
221        if let Some(arg) = handle::map_get(self.attribute_table(), name) {
222            return Some(arg);
223        }
224        handle::map_get(self.sample_table(), name)?
225            .last()
226            .map(|(_, arg)| arg)
227    }
228}
229
230/// The value standing at each time, once a same-time re-set has
231/// replaced what it superseded, ascending by time.
232///
233/// One statement of it, read by [`Scene::attribute_samples`] and by
234/// the resolver's typing rule -- which runs it over the calls that
235/// survived an unreadable one rather than over all of them. Two copies
236/// of a resolution rule have drifted apart in this crate four times.
237pub(crate) fn latest_per_time(
238    calls: &[(f64, OwnedArgument)],
239) -> Vec<(f64, &OwnedArgument)> {
240    // Sorted by time, and by **call order** within one time -- the
241    // call index is part of the key rather than a stability the sort
242    // happens to give. A reviewer switched this to `sort_unstable_by`
243    // and nothing went red; no fixture had enough same-time calls to
244    // make an unstable sort actually reorder, so the guarantee the
245    // rule rested on was one no test could see. With the index in the
246    // key the order is total and any correct sort gives this answer.
247    let mut standing: Vec<(f64, usize, &OwnedArgument)> = calls
248        .iter()
249        .enumerate()
250        .map(|(index, (time, arg))| (*time, index, arg))
251        .collect();
252    standing.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
253    standing.dedup_by(|later, earlier| {
254        // `dedup_by` keeps the *earlier* of a matching pair, and the
255        // later call is the one that stands, so its value moves down
256        // before the earlier one is dropped.
257        if later.0.total_cmp(&earlier.0) == Ordering::Equal {
258            earlier.2 = later.2;
259            true
260        } else {
261            false
262        }
263    });
264
265    standing
266        .into_iter()
267        .map(|(time, _, arg)| (time, arg))
268        .collect()
269}
270
271/// What changed since the last [`Scene::take_changes`].
272///
273/// A **net** record, not a log of calls: re-setting one attribute
274/// forty times is one entry, connecting and reconnecting one edge is
275/// one entry, and a handle created and then deleted in the same
276/// interval appears only in [`Changes::deleted`] -- the create is
277/// undone by the delete, and a consumer that never saw the node has
278/// nothing to undo. A consumer synchronising a live renderer wants the
279/// set of things to look at again, and coalescing a call log into that
280/// set would be its work rather than ours.
281///
282/// It carries **no values**. The scene holds the current one --
283/// [`Node::effective`] answers it -- so an entry names an attribute
284/// rather than copying a vertex buffer per edit.
285///
286/// This is the raw record, and it is deliberately in ɴsɪ's domain: a
287/// `transform` and an `attributes` node have no counterpart in a
288/// renderer's scene, and one geometry under two parents is several
289/// objects there. [`Scene::affected`] turns "this transform moved"
290/// into "these nodes may have moved", which is the question a backend
291/// actually asks.
292#[derive(Debug, Clone, Default, PartialEq)]
293#[non_exhaustive]
294pub struct Changes {
295    /// Handles created during this interval and not since deleted.
296    ///
297    /// Read it with [`Changes::created`]. Stored as handles so that
298    /// `ustr_handles` interns them: a frame that touches ten thousand
299    /// nodes copied ten thousand strings out of the scene otherwise,
300    /// on the one path an interactive host walks every frame.
301    pub(crate) created: IndexSet<Handle>,
302    /// Handles deleted, with the node type they had.
303    ///
304    /// The type is kept because the handle is gone from the scene: a
305    /// consumer that has to undo whatever it built for a node cannot
306    /// ask what kind of node it was any more. Read it with
307    /// [`Changes::deleted`].
308    pub(crate) deleted: IndexMap<Handle, Handle>,
309    /// `(handle, attribute)` pairs set, re-set or deleted. Read it
310    /// with [`Changes::attributes`].
311    pub(crate) attributes: IndexSet<(Handle, Handle)>,
312    /// Connections made.
313    pub edges_added: Vec<Edge>,
314    /// Connections removed, **in full**.
315    ///
316    /// The endpoints and kind are kept because the graph no longer has
317    /// them: working out what a severed `objects` edge orphaned means
318    /// walking down from a node the edge no longer points at. A
319    /// `disconnect` naming `.all` is expanded here into the edges it
320    /// actually removed, since the pattern cannot be re-expanded once
321    /// they are gone.
322    pub edges_removed: Vec<Edge>,
323    /// Connections whose arguments a repeated `connect` replaced in
324    /// place.
325    ///
326    /// No edge appeared or disappeared, so a record keyed on additions
327    /// and removals misses this entirely -- and ɴsɪ's `"priority"`
328    /// rides on these arguments, which decides which of two shaders
329    /// wins. This is the quietest way for a scene to change meaning.
330    pub edges_rearmed: Vec<Edge>,
331}
332
333impl Changes {
334    /// The handles created and not since deleted.
335    pub fn created(&self) -> impl Iterator<Item = &str> {
336        self.created.iter().map(|handle| handle.as_str())
337    }
338
339    /// Whether one handle was created in this interval.
340    pub fn was_created(&self, handle: &str) -> bool {
341        handle::set_contains(&self.created, handle)
342    }
343
344    /// The handles deleted, each with the node type it had.
345    pub fn deleted(&self) -> impl Iterator<Item = (&str, &str)> {
346        self.deleted
347            .iter()
348            .map(|(handle, node_type)| (handle.as_str(), node_type.as_str()))
349    }
350
351    /// The node type a deleted handle had, if it was deleted here.
352    pub fn deleted_type(&self, handle: &str) -> Option<&str> {
353        handle::map_get(&self.deleted, handle)
354            .map(|node_type| node_type.as_str())
355    }
356
357    /// The `(handle, attribute)` pairs set, re-set or deleted.
358    pub fn attributes(&self) -> impl Iterator<Item = (&str, &str)> {
359        self.attributes
360            .iter()
361            .map(|(handle, name)| (handle.as_str(), name.as_str()))
362    }
363
364    /// Nothing changed since the last [`Scene::take_changes`].
365    pub fn is_empty(&self) -> bool {
366        self.created.is_empty()
367            && self.deleted.is_empty()
368            && self.attributes.is_empty()
369            && self.edges_added.is_empty()
370            && self.edges_removed.is_empty()
371            && self.edges_rearmed.is_empty()
372    }
373}
374
375/// What a [`Changes`] batch may have moved.
376///
377/// **Candidates, not a minimal set.** An entry means "resolve this
378/// again", not "this definitely differs": ɴsɪ's precedence rules can
379/// make an edit invisible -- a re-armed `surfaceshader` at a lower
380/// priority than a nearer one changes nothing -- and deciding that
381/// here would mean remembering every previous answer this crate ever
382/// gave, which is the consumer's own record to keep.
383///
384/// Keyed by **handle**, not by placement path. One geometry under two
385/// parents is several objects to a renderer, and editing one parent
386/// moves only one of them; a handle-level answer makes the consumer
387/// re-resolve both. Correct, and coarse for a crowd -- path-precision
388/// is an optimisation to ask for with a measurement.
389/// # Why it borrows
390///
391/// Every handle in here already lives in the [`Scene`] or in the
392/// [`Changes`] it was computed from, so owning them meant a `String`
393/// clone per named node on a path an interactive host walks every
394/// frame. Measured, one transform with *n* children, debug build,
395/// best of ten: 1000 nodes 2.08 ms, 10 000 27.3 ms, 50 000 88.9 ms --
396/// about 2 us a node, four to five allocations of it. Borrowing costs
397/// a lifetime on the type and nothing else.
398#[derive(Debug, Clone, Default, PartialEq, Eq)]
399#[non_exhaustive]
400pub struct Affected<'a> {
401    /// The **roots** of what may have moved: these nodes and
402    /// everything below them on the `objects` chain.
403    ///
404    /// Roots rather than an enumeration, because enumerating is
405    /// O(scene) for the edit that matters least -- moving one
406    /// transform near the top of a production scene names every
407    /// geometry under it, and a set-dressing scene has millions. The
408    /// consumer walks its own objects anyway;
409    /// [`Scene::descendants`] expands a root when it wants the list.
410    pub roots: IndexSet<&'a str>,
411    /// Shader nodes whose own attributes or network changed.
412    ///
413    /// Kept apart because they map one-to-one onto a renderer's
414    /// material parameters and cost no geometry work: only the *root*
415    /// shader's identity reaches geometry, and that is a
416    /// `surfaceshader` edge, which lands in `nodes`.
417    pub shaders: IndexSet<&'a str>,
418    /// Whether the camera/screen/layer/driver chain changed, so the
419    /// outputs need re-reading.
420    pub outputs: bool,
421    /// Whether something global changed -- an attribute on `.root` or
422    /// `.global` -- and the whole scene is a candidate.
423    ///
424    /// When this is set, `nodes` is not filled: the answer is
425    /// everything, and listing it would be a copy of the scene.
426    pub everything: bool,
427}
428
429/// Name a root of the affected set.
430///
431/// A root stands for itself and everything below it, so a handle that
432/// is already named needs no second entry -- and a caller expanding
433/// two overlapping roots gets the union either way.
434fn insert_root<'a>(roots: &mut IndexSet<&'a str>, handle: &'a str) {
435    roots.insert(handle);
436}
437
438/// Record an edge in one of [`Changes`]'s lists, at most once.
439///
440/// Keyed on `(from, to, kind)`, which is an edge's identity to ɴsɪ --
441/// `args` carry the priority and are what a re-arm replaces. Without
442/// this the lists were logs: a host that re-`connect`s the same edge
443/// every frame grew the record by a full `Edge`, arguments included,
444/// on every one of them, and the record is supposed to be net.
445fn record_edge(list: &mut Vec<Edge>, edge: Edge) {
446    match list.iter_mut().find(|recorded| {
447        recorded.from == edge.from
448            && recorded.to == edge.to
449            && recorded.kind == edge.kind
450    }) {
451        Some(recorded) => *recorded = edge,
452        None => list.push(edge),
453    }
454}
455
456/// The recorded scene graph.
457#[derive(Debug, Clone, Default)]
458#[non_exhaustive]
459pub struct Scene {
460    /// Nodes by handle, in creation order.
461    nodes: IndexMap<Handle, Node>,
462    /// Classified connections, in connection order.
463    edges: Vec<Edge>,
464    /// `Evaluate` calls, in call order, each with the node count at the
465    /// time so replay can put them back where they were.
466    ///
467    /// ɴsɪ's `Evaluate` "includes a block of interface calls from an
468    /// external source" -- an archive, a Lua script or a compiled
469    /// procedural. This crate does not execute one, so whatever it
470    /// would have produced is absent from the scene; recording the call
471    /// at least means a stream carrying one is not silently reduced to
472    /// a scene missing its geometry, with no error and no trace.
473    evaluations: Vec<Vec<OwnedArgument>>,
474    /// Edge positions keyed by source handle, and by destination.
475    ///
476    /// Resolution walks the graph per object, so without these every
477    /// hop of every walk scanned every edge -- quadratic in the scene,
478    /// which a production asset feels immediately. Rebuilt on removal
479    /// (rare) and appended to on `connect` (common).
480    by_from: HashMap<Handle, Vec<usize>>,
481    by_to: HashMap<Handle, Vec<usize>>,
482    /// Edge positions keyed by destination *and* destination attribute.
483    ///
484    /// `by_to` alone is not enough: a transform with twenty thousand
485    /// children has twenty thousand incoming `objects` edges, and
486    /// gathering attributes there would scan all of them once per
487    /// child. Keying on the attribute too makes that lookup
488    /// proportional to the matches rather than to the scene.
489    by_to_attr: HashMap<(Handle, Handle), Vec<usize>>,
490    /// What has changed since the last [`Scene::take_changes`].
491    ///
492    /// Private, and not part of [`Scene`]'s equality: two scenes with
493    /// the same nodes and edges are the same scene whether or not one
494    /// of them has been synchronised since.
495    changes: Changes,
496}
497
498/// Two scenes are equal when they describe the same thing.
499///
500/// Written out rather than derived because of what it must *exclude*:
501/// the pending [`Changes`], which say what happened to a scene rather
502/// than what it is -- a scene that has just been synchronised would
503/// otherwise stop being equal to the identical scene that has not --
504/// and the three edge indexes, which are a function of the edges they
505/// index.
506impl PartialEq for Scene {
507    fn eq(&self, other: &Self) -> bool {
508        self.nodes == other.nodes
509            && self.edges == other.edges
510            && self.evaluations == other.evaluations
511    }
512}
513
514impl Scene {
515    /// What has changed since this was last called, clearing the
516    /// record.
517    ///
518    /// ɴsɪ's `NSIRenderControl "synchronize"` is where a host asks a
519    /// renderer to catch up: the specification says "apply all the
520    /// **buffered** calls to scene's state", so the interval between
521    /// two synchronises is exactly one batch of edits. Observed on
522    /// 3Delight: edits made without synchronising change nothing and
523    /// report nothing; the synchronise then reports `Restarted`
524    /// followed by `Synchronized`, once, for the whole batch.
525    ///
526    /// Taking clears, because the alternative is a record that grows
527    /// for the life of an interactive session and a caller that must
528    /// remember where it read up to.
529    ///
530    /// Pass it to [`Scene::affected`] for the nodes to re-resolve.
531    /// This is the half that cannot be reconstructed after the fact --
532    /// a delete takes its edges with it, and a re-armed connection
533    /// leaves the graph looking exactly as it did.
534    pub fn take_changes(&mut self) -> Changes {
535        mem::take(&mut self.changes)
536    }
537
538    /// What has changed, without clearing it.
539    pub fn changes(&self) -> &Changes {
540        &self.changes
541    }
542
543    /// The nodes a [`Changes`] batch may have moved.
544    ///
545    /// Every rule here is the **inverse** of a walk this crate already
546    /// does upward. Resolution asks "what applies to this geometry" by
547    /// climbing `objects` to `.root` and gathering containers on the
548    /// way; a synchronise asks the same question backwards -- "given
549    /// this node changed, whose answers depended on it" -- so the
550    /// indexes that make the climb cheap (`by_to_attr`) make the
551    /// descent cheap too, and no new index is needed.
552    ///
553    /// The rules, and what each inverts:
554    ///
555    /// - a `transform`'s attribute, or an `objects` edge: everything
556    ///   below it, and any instancer drawing a prototype found there.
557    ///   Inverts the chain walk. Cameras and lights hang off `objects`
558    ///   like geometry, so they come along.
559    /// - an `attributes` node's attribute, or a shader edge into one:
560    ///   everything below each node it is bound to. Inverts the
561    ///   container gather. A binding onto a `set` reaches the set's
562    ///   members.
563    /// - a shader's own attribute, or a shader-network edge: the
564    ///   shader alone. Nothing about geometry changed.
565    /// - `.root` or `.global`: everything.
566    ///
567    /// Over-approximate on purpose -- see [`Affected`].
568    pub fn affected<'a>(&'a self, changes: &'a Changes) -> Affected<'a> {
569        let mut affected = Affected::default();
570
571        for (handle, _) in &changes.attributes {
572            if crate::is_reserved(handle) {
573                affected.everything = true;
574                continue;
575            }
576            match handle::map_get(&self.nodes, handle) {
577                Some(node) if node.node_type == "shader" => {
578                    affected.shaders.insert(handle.as_str());
579                }
580                Some(node) if node.node_type == "attributes" => {
581                    self.through_bindings(handle, &mut affected.roots);
582                }
583                // Anything else is a scene node: it may be the thing
584                // that moved, and it may be a transform with a subtree
585                // under it. The descent answers both.
586                _ => insert_root(&mut affected.roots, handle),
587            }
588            if self.is_output_node(handle) {
589                affected.outputs = true;
590            }
591        }
592
593        for handle in &changes.created {
594            insert_root(&mut affected.roots, handle);
595        }
596
597        // A deleted handle is gone from the graph, so there is nothing
598        // left to descend *from*: what it orphaned is reached through
599        // the edges the delete took with it, which is why they are
600        // recorded in full.
601        for handle in changes.deleted.keys() {
602            affected.roots.insert(handle.as_str());
603        }
604
605        for edge in changes
606            .edges_added
607            .iter()
608            .chain(&changes.edges_removed)
609            .chain(&changes.edges_rearmed)
610        {
611            // On `EdgeKind`, with no wildcard. Matching the
612            // *destination attribute string* let a new variant land
613            // silently in whatever arm the `_` was, and a
614            // `ShaderNetwork` whose port happens to be named `objects`
615            // took the child arm -- the resolver already carries a
616            // comment about that hazard, and this had re-learned it.
617            // Exhaustive here means the compiler asks the question.
618            match &edge.kind {
619                // A child, a set member: whatever hung below the
620                // source now hangs somewhere else.
621                EdgeKind::SceneMember | EdgeKind::SetMember => {
622                    insert_root(&mut affected.roots, &edge.from);
623                    if self.is_output_node(&edge.from)
624                        || self.is_output_node(&edge.to)
625                    {
626                        affected.outputs = true;
627                    }
628                }
629                // A prototype joining or leaving an instancer. The
630                // node whose answer moves is the **instancer**, and it
631                // is not below the prototype -- it is the other end of
632                // this edge, which is exactly why a walk that only
633                // descends from `edge.from` missed it: rendered, a
634                // severed `sourcemodels` leaves the instancer drawing
635                // a prototype the scene no longer has.
636                EdgeKind::InstanceSource => {
637                    insert_root(&mut affected.roots, &edge.from);
638                    affected.roots.insert(edge.to.as_str());
639                }
640                // A geometry joining or leaving a weld namespace. Its
641                // own boundaries change, and so do those of every
642                // geometry it was, or now is, welded to: a seam has two
643                // sides.
644                EdgeKind::Weld => {
645                    insert_root(&mut affected.roots, &edge.to);
646                    for partner in self
647                        .edges_from(&edge.from)
648                        .filter(|partner| partner.kind == EdgeKind::Weld)
649                    {
650                        insert_root(&mut affected.roots, &partner.to);
651                    }
652                }
653                // A container bound to something, or unbound from it.
654                EdgeKind::AttributeBinding | EdgeKind::ShaderAttributes => {
655                    insert_root(&mut affected.roots, &edge.to);
656                    self.set_members(&edge.to, &mut affected.roots);
657                }
658                // A shader reaching an `attributes` node -- including a
659                // repeated `connect` that only changed `"priority"`,
660                // which is why re-armed edges are here.
661                EdgeKind::SurfaceShader
662                | EdgeKind::DisplacementShader
663                | EdgeKind::VolumeShader => {
664                    affected.shaders.insert(edge.from.as_str());
665                    self.through_bindings(&edge.to, &mut affected.roots);
666                }
667                // The output chain, and the things hung off it. A
668                // light set and a background layer belong to an
669                // `outputlayer`, and a lens shader to a camera: none
670                // of them is a material parameter, and filing them
671                // under `shaders` told a backend honouring light sets
672                // nothing at all.
673                EdgeKind::Screen
674                | EdgeKind::OutputLayer
675                | EdgeKind::OutputDriver
676                | EdgeKind::LightSet
677                | EdgeKind::BackgroundLayer
678                | EdgeKind::LensShader => {
679                    affected.outputs = true;
680                }
681                // `.global`'s own membership: it applies to the whole
682                // render, so the whole scene is the candidate.
683                EdgeKind::ExclusiveShading => {
684                    affected.everything = true;
685                }
686                // Bounds, subsurface sets and face sets attach to a
687                // geometry or a set and change what it resolves to.
688                EdgeKind::Bounds
689                | EdgeKind::SubsurfaceSet
690                | EdgeKind::FaceSet => {
691                    insert_root(&mut affected.roots, &edge.to);
692                    self.set_members(&edge.to, &mut affected.roots);
693                }
694                // A shader network edge is between shaders, and a
695                // carried connection this crate does not resolve is
696                // not known to reach geometry. Only ends that really
697                // are shader nodes go in `shaders`.
698                EdgeKind::ShaderNetwork { .. } | EdgeKind::Other { .. } => {
699                    for handle in [&edge.from, &edge.to] {
700                        if self.is_shader_node(handle) {
701                            affected.shaders.insert(handle.as_str());
702                        } else {
703                            insert_root(&mut affected.roots, handle);
704                        }
705                    }
706                }
707            }
708        }
709
710        if affected.everything {
711            affected.roots.clear();
712        }
713
714        affected
715    }
716
717    /// Everything at or below `handle` on the `objects` chain, plus any
718    /// instancer that draws a prototype found there.
719    ///
720    /// This is what an [`Affected`] root stands for. Call it when the
721    /// list is actually wanted -- a backend that is walking its own
722    /// objects can compare against the roots instead and never build
723    /// it.
724    ///
725    /// [`Affected::roots`] with the roots an ancestor already covers
726    /// removed.
727    ///
728    /// A root stands for itself and everything below it, so when one
729    /// root sits under another the union is unchanged -- which is why
730    /// [`Scene::affected`] does not do this itself. What it costs is
731    /// the consumer's walk: every redundant root is a subtree walked
732    /// twice.
733    ///
734    /// **Opt in when you walk subtrees, not otherwise.** Measured on a
735    /// 1791-node asset hierarchy, release build:
736    ///
737    /// | edit batch | roots | redundant | walking all | collapsed | this call |
738    /// | --- | --- | --- | --- | --- | --- |
739    /// | a transform and 20 of its descendants | 21 | 20 | 1785 nodes, 200 us | 597 nodes, 56 us | 3.6 us |
740    /// | 21 unrelated leaves | 21 | 0 | 21 nodes, 2.4 us | the same | 11.3 us |
741    ///
742    /// So a clustered batch -- moving an asset and tweaking its parts
743    /// -- returns forty times the check's cost, and a scattered one
744    /// pays eleven microseconds for nothing. A consumer that only
745    /// reads the root names should not call this.
746    ///
747    /// A node with more than one parent is never removed: ɴsɪ's
748    /// lightweight instancing puts it under two paths, and a root
749    /// covering one of them does not cover the other.
750    pub fn collapsed_roots<'a>(
751        &'a self,
752        affected: &Affected<'a>,
753    ) -> IndexSet<&'a str> {
754        affected
755            .roots
756            .iter()
757            .copied()
758            .filter(|root| !self.covered_by_another_root(root, &affected.roots))
759            .collect()
760    }
761
762    /// Whether an ancestor of `handle` is itself a root.
763    fn covered_by_another_root(
764        &self,
765        handle: &str,
766        roots: &IndexSet<&str>,
767    ) -> bool {
768        let mut current = handle.to_string();
769        // The scene's node count bounds the walk, so a cycle -- which
770        // `chain` would reject outright -- terminates here instead.
771        for _ in 0..self.nodes.len() {
772            let mut parents = self
773                .edges_from(&current)
774                .filter(|edge| edge.kind == EdgeKind::SceneMember);
775            let Some(parent) = parents.next() else {
776                return false;
777            };
778            if parents.next().is_some() {
779                return false;
780            }
781            let parent = parent.to().to_string();
782            if roots.contains(parent.as_str()) {
783                return true;
784            }
785            current = parent;
786        }
787        false
788    }
789
790    /// Iterative with an explicit stack: an ɴsɪ scene's depth is the
791    /// caller's, not ours, and a recursive walk here would overflow on
792    /// a deep chain. The `insert` doubles as the visited set, so a
793    /// cycle terminates.
794    pub fn descendants<'a>(&'a self, handle: &'a str) -> IndexSet<&'a str> {
795        let mut out = IndexSet::new();
796        self.descend(handle, &mut out);
797        out
798    }
799
800    fn descend<'a>(&'a self, handle: &'a str, out: &mut IndexSet<&'a str>) {
801        let mut stack = vec![handle];
802        while let Some(node) = stack.pop() {
803            if !out.insert(node) {
804                continue;
805            }
806            for edge in self.edges_to_attribute(node, "objects") {
807                stack.push(&edge.from);
808            }
809            // A prototype's mover moves every instancer drawing it, and
810            // the instancer is not below the transform that moved --
811            // it is reached the other way, through `sourcemodels`.
812            for edge in self.edges_from(node) {
813                if edge.kind.to_attribute() == "sourcemodels" {
814                    stack.push(&edge.to);
815                }
816            }
817        }
818    }
819
820    /// Everything an `attributes` node is bound to, and below that.
821    fn through_bindings<'a>(
822        &'a self,
823        handle: &str,
824        out: &mut IndexSet<&'a str>,
825    ) {
826        for edge in self.edges_from(handle) {
827            if matches!(
828                edge.kind.to_attribute(),
829                "geometryattributes" | "shaderattributes"
830            ) {
831                insert_root(out, &edge.to);
832                self.set_members(&edge.to, out);
833            }
834        }
835    }
836
837    /// If `handle` is a `set`, everything its members carry.
838    ///
839    /// One hop, not a recursion: a `set` inside a `set` contributes
840    /// nothing to what a geometry inherits -- rendered, and pinned by
841    /// `a_nested_sets_attributes_are_not_inherited` -- so descending
842    /// through nested sets would name nodes the renderer never reaches.
843    fn set_members<'a>(&'a self, handle: &str, out: &mut IndexSet<&'a str>) {
844        for edge in self.edges_to_attribute(handle, "members") {
845            insert_root(out, &edge.from);
846        }
847    }
848
849    /// Whether this handle is a shader node.
850    ///
851    /// Asked before filing anything under [`Affected::shaders`], whose
852    /// documented meaning is "maps one-to-one onto a renderer's
853    /// material parameters". A `set` reached through a `lightset` edge
854    /// is not that, and neither is a camera reached through a lens
855    /// shader.
856    fn is_shader_node(&self, handle: &str) -> bool {
857        handle::map_get(&self.nodes, handle)
858            .is_some_and(|node| node.node_type() == "shader")
859    }
860
861    /// Whether this handle is part of the camera/screen/layer/driver
862    /// chain, whose answers come from [`Scene::render_outputs`] rather
863    /// than from a geometry walk.
864    fn is_output_node(&self, handle: &str) -> bool {
865        handle::map_get(&self.nodes, handle).is_some_and(|node| {
866            node.node_type().ends_with("camera")
867                || matches!(
868                    node.node_type(),
869                    "screen" | "outputlayer" | "outputdriver"
870                )
871        })
872    }
873
874    /// The nodes, by handle, in creation order.
875    pub fn nodes(&self) -> impl Iterator<Item = (&str, &Node)> {
876        self.nodes
877            .iter()
878            .map(|(handle, node)| (handle.as_str(), node))
879    }
880
881    /// The recorded `Evaluate` calls, in call order.
882    ///
883    /// Each is the argument list as given. A backend that wants
884    /// archives or procedurals has to execute them itself: this crate
885    /// records the call and does not define an execution model for it.
886    pub fn evaluations(&self) -> impl Iterator<Item = &[OwnedArgument]> {
887        self.evaluations.iter().map(Vec::as_slice)
888    }
889
890    /// Record an `Evaluate`.
891    ///
892    /// Only the call, not where it fell among the nodes: replay emits
893    /// every `Evaluate` first, nothing reads a position, and a node
894    /// count kept here would be wrong the moment a `delete` shifted
895    /// it.
896    pub(crate) fn evaluate(&mut self, args: Vec<OwnedArgument>) {
897        self.evaluations.push(args);
898    }
899
900    /// One node by handle.
901    pub fn node(&self, handle: &str) -> Option<&Node> {
902        handle::map_get(&self.nodes, handle)
903    }
904
905    /// A node together with the scene's own copy of its handle.
906    ///
907    /// Resolution returns borrowed handles that outlive the `&str` a
908    /// caller passed in, so it needs the stored key, not the argument.
909    pub(crate) fn node_entry(&self, handle: &str) -> Option<(&str, &Node)> {
910        handle::map_entry(&self.nodes, handle)
911    }
912
913    /// The classified connections, in connection order.
914    pub fn edges(&self) -> impl Iterator<Item = &Edge> {
915        self.edges.iter()
916    }
917
918    /// How many nodes the scene holds.
919    pub fn len(&self) -> usize {
920        self.nodes.len()
921    }
922
923    /// Whether the scene holds no nodes.
924    pub fn is_empty(&self) -> bool {
925        self.nodes.is_empty()
926    }
927
928    /// The connections *out of* `handle`, in connection order.
929    ///
930    /// Indexed, so this does not scan the scene.
931    pub fn edges_from<'a>(
932        &'a self,
933        handle: &str,
934    ) -> impl Iterator<Item = &'a Edge> + use<'a> {
935        self.indexed(&self.by_from, handle)
936    }
937
938    /// The connections *into* `handle`, in connection order.
939    ///
940    /// Indexed, so this does not scan the scene.
941    pub fn edges_to<'a>(
942        &'a self,
943        handle: &str,
944    ) -> impl Iterator<Item = &'a Edge> + use<'a> {
945        self.indexed(&self.by_to, handle)
946    }
947
948    /// The connections into `handle` through `to_attribute`, in connection
949    /// order.
950    ///
951    /// Indexed on both, so this is proportional to the matches rather
952    /// than to the scene.
953    pub fn edges_to_attribute<'a>(
954        &'a self,
955        handle: &str,
956        to_attribute: &str,
957    ) -> impl Iterator<Item = &'a Edge> + use<'a> {
958        // Without `ustr_handles` this allocates two `String`s to probe
959        // the map, on what is the hot path's key: a `HashMap<(String,
960        // String), _>` cannot be probed with a pair of `&str`.
961        // Interned, the probe allocates nothing.
962        handle::get_pair(&self.by_to_attr, handle, to_attribute)
963            .into_iter()
964            .flatten()
965            .map(|position| &self.edges[*position])
966    }
967
968    fn indexed<'a>(
969        &'a self,
970        index: &'a HashMap<Handle, Vec<usize>>,
971        handle: &str,
972    ) -> impl Iterator<Item = &'a Edge> + use<'a> {
973        crate::handle::get(index, handle)
974            .into_iter()
975            .flatten()
976            .map(|position| &self.edges[*position])
977    }
978
979    /// Rebuild both edge indexes.
980    ///
981    /// Called after a removal, which shifts every later position.
982    fn reindex(&mut self) {
983        self.by_from.clear();
984        self.by_to.clear();
985        self.by_to_attr.clear();
986        for (position, edge) in self.edges.iter().enumerate() {
987            self.by_from
988                .entry(handle::handle(&edge.from))
989                .or_default()
990                .push(position);
991            self.by_to
992                .entry(handle::handle(&edge.to))
993                .or_default()
994                .push(position);
995            self.by_to_attr
996                .entry((
997                    handle::handle(&edge.to),
998                    handle::handle(edge.kind.to_attribute()),
999                ))
1000                .or_default()
1001                .push(position);
1002        }
1003    }
1004
1005    /// Create a node.
1006    ///
1007    /// # Errors
1008    ///
1009    /// [`RecordError::TypeMismatch`] when the handle exists with a
1010    /// different type. ɴsɪ: "the function does nothing if all other
1011    /// parameters match the call which created that node. Otherwise, it
1012    /// emits an error." Re-creating with the *same* type is a no-op, as
1013    /// ɴsɪ says.
1014    pub fn create(
1015        &mut self,
1016        handle: &str,
1017        node_type: &str,
1018    ) -> Result<(), RecordError> {
1019        // ɴsɪ's reserved handles exist already. 3Delight answers a
1020        // `create` on one with "already exists"; accepting it here kept
1021        // a node that replay then drops, so the scene changed on its
1022        // own first round trip.
1023        if crate::is_reserved(handle) {
1024            return Err(RecordError::Reserved {
1025                handle: handle.to_string(),
1026            });
1027        }
1028
1029        // A scene speaks the naming-convention draft's vocabulary,
1030        // whichever one created it.
1031        let node_type = match crate::names::draft_node_type(node_type) {
1032            Some(draft) => {
1033                crate::names::warn_deprecated(node_type, draft);
1034                draft
1035            }
1036            None => node_type,
1037        };
1038
1039        match handle::map_get(&self.nodes, handle) {
1040            Some(existing) if existing.node_type() != node_type => {
1041                Err(RecordError::TypeMismatch {
1042                    handle: handle.to_string(),
1043                    existing: existing.node_type().to_string(),
1044                    requested: node_type.to_string(),
1045                })
1046            }
1047            Some(_) => Ok(()),
1048            None => {
1049                self.nodes.insert(
1050                    crate::handle::handle(handle),
1051                    Node {
1052                        node_type: crate::handle::handle(node_type),
1053                        ..Node::default()
1054                    },
1055                );
1056                self.changes.created.insert(handle::handle(handle));
1057                Ok(())
1058            }
1059        }
1060    }
1061
1062    /// Delete a node and every edge that touches it.
1063    ///
1064    /// `shift_remove` rather than `swap_remove`: insertion order is the
1065    /// replay order and must survive a delete.
1066    ///
1067    /// # Errors
1068    ///
1069    /// [`RecordError::Reserved`] for `.root` or `.global`. ɴsɪ: "it is
1070    /// not possible to delete the root or the global node." Deleting
1071    /// `.root` here would strip every membership edge in the scene.
1072    pub fn delete(&mut self, handle: &str) -> Result<(), RecordError> {
1073        if crate::is_reserved(handle) {
1074            Err(RecordError::Reserved {
1075                handle: handle.to_string(),
1076            })
1077        } else {
1078            // Recorded *before* the removal: afterwards the type is
1079            // gone and the edges that named this handle cannot be
1080            // found, and a consumer working out what the delete
1081            // orphaned needs both.
1082            if let Some(node) = handle::map_remove(&mut self.nodes, handle) {
1083                handle::set_remove(&mut self.changes.created, handle);
1084                self.changes
1085                    .deleted
1086                    .insert(handle::handle(handle), node.node_type);
1087            }
1088            for edge in self
1089                .edges
1090                .iter()
1091                .filter(|e| e.from == handle || e.to == handle)
1092            {
1093                record_edge(&mut self.changes.edges_removed, edge.clone());
1094            }
1095            self.edges.retain(|e| e.from != handle && e.to != handle);
1096            self.reindex();
1097            Ok(())
1098        }
1099    }
1100
1101    /// Whether `handle` names something a connection may refer to.
1102    ///
1103    /// ɴsɪ's `.root` and `.global` are reserved and "don't need to be
1104    /// created", so they count as known without appearing in `nodes`.
1105    fn is_known(&self, handle: &str) -> bool {
1106        handle == crate::ROOT
1107            || handle == crate::GLOBAL
1108            || handle::map_get(&self.nodes, handle).is_some()
1109    }
1110
1111    /// Delete a node and, recursively, the nodes that only fed it.
1112    ///
1113    /// ɴsɪ: "nodes which connect to the specified node are recursively
1114    /// removed, unless they meet one of the following conditions: they
1115    /// also have connections which do not eventually lead to the
1116    /// specified node; their connection to the deleted node was created
1117    /// with a strength greater than 0." That is what makes deleting a
1118    /// whole shader network one call.
1119    ///
1120    /// # Errors
1121    ///
1122    /// [`RecordError::Reserved`] for `.root` or `.global`.
1123    pub fn delete_recursive(
1124        &mut self,
1125        handle: &str,
1126    ) -> Result<(), RecordError> {
1127        if crate::is_reserved(handle) {
1128            return Err(RecordError::Reserved {
1129                handle: handle.to_string(),
1130            });
1131        }
1132
1133        let mut doomed = HashSet::new();
1134        doomed.insert(handle.to_string());
1135
1136        // Grow the set until it stops growing: a node joins when every
1137        // connection it makes leads into the set, and none of those is
1138        // strong enough to block.
1139        loop {
1140            let candidates = doomed
1141                .iter()
1142                .flat_map(|node| self.edges_to(node))
1143                .filter(|edge| edge.strength() <= 0)
1144                .map(|edge| edge.from().to_string())
1145                .filter(|from| !doomed.contains(from.as_str()))
1146                .collect::<Vec<_>>();
1147
1148            let mut grew = false;
1149            for candidate in candidates {
1150                let leads_elsewhere = self
1151                    .edges_from(&candidate)
1152                    .any(|edge| !doomed.contains(edge.to()));
1153
1154                // The strength rule is about *this* node's connection to
1155                // anything being deleted, not only about how it was
1156                // first reached. Checking it at discovery alone let a
1157                // node be swept in through a second, weak path.
1158                let held = self.edges_from(&candidate).any(|edge| {
1159                    doomed.contains(edge.to()) && edge.strength() > 0
1160                });
1161
1162                if !leads_elsewhere && !held && doomed.insert(candidate) {
1163                    grew = true;
1164                }
1165            }
1166
1167            if !grew {
1168                break;
1169            }
1170        }
1171
1172        for handle in &doomed {
1173            if let Some(node) = handle::map_get(&self.nodes, handle) {
1174                let node_type = handle::copy(&node.node_type);
1175                handle::set_remove(&mut self.changes.created, handle);
1176                self.changes
1177                    .deleted
1178                    .insert(handle::handle(handle), node_type);
1179            }
1180        }
1181        for edge in self.edges.iter().filter(|edge| {
1182            doomed.contains(edge.from()) || doomed.contains(edge.to())
1183        }) {
1184            record_edge(&mut self.changes.edges_removed, edge.clone());
1185        }
1186
1187        self.nodes
1188            .retain(|handle, _| !doomed.contains(handle.as_str()));
1189        self.edges.retain(|edge| {
1190            !doomed.contains(edge.from()) && !doomed.contains(edge.to())
1191        });
1192        self.reindex();
1193
1194        Ok(())
1195    }
1196
1197    /// Set static attributes, overwriting by name.
1198    ///
1199    /// ɴsɪ: "Setting an attribute using this function replaces any value
1200    /// previously set by `NSISetAttribute` or `NSISetAttributeAtTime`."
1201    /// So this also clears every motion sample of the same name --
1202    /// otherwise a node set static after being sampled would still look
1203    /// motion-blurred to the resolver.
1204    ///
1205    /// # Errors
1206    ///
1207    /// [`RecordError::UnknownHandle`] when the node does not exist.
1208    /// 3Delight answers the same call with "unknown node handle". A
1209    /// fabricated node is worse than a rejected one: it joins the scene,
1210    /// satisfies later `connect` calls, and replays as a `Create` the
1211    /// renderer never wrote.
1212    pub fn set_attribute(
1213        &mut self,
1214        handle: &str,
1215        args: Vec<OwnedArgument>,
1216    ) -> Result<(), RecordError> {
1217        // Existence first, so a rejected call records nothing.
1218        self.node_mut(handle)?;
1219        let node_handle = handle::handle(handle);
1220        // `nodes` and `changes` are separate fields, so the node and
1221        // the journal are borrowed at once. Through `node_mut` they
1222        // are not, and carrying the names out of the loop in a `Vec`
1223        // to record them afterwards cost a clone of every one.
1224        // SAFETY: `node_mut` above returned `Ok`, which means it
1225        // either found this handle or created it, and nothing since
1226        // could have removed it.
1227        let node = self
1228            .nodes
1229            .get_mut(&node_handle)
1230            .expect("node_mut found or created it");
1231        let node_type = crate::names::reserved_node_type(handle)
1232            .unwrap_or(node.node_type())
1233            .to_string();
1234        for mut arg in args {
1235            crate::names::to_draft(&node_type, &mut arg);
1236            let name = handle::handle(&arg.name);
1237            // Only when the node has samples: reaching for the table
1238            // through `sample_table_mut` would allocate one for every
1239            // node that has an attribute, which is most of a scene.
1240            if let Some(table) = node.samples.as_mut() {
1241                table.shift_remove(&name);
1242            }
1243            self.changes
1244                .attributes
1245                .insert((handle::copy(&node_handle), handle::copy(&name)));
1246            node.attribute_table_mut().insert(name, arg);
1247        }
1248        Ok(())
1249    }
1250
1251    /// A node to mutate, or [`RecordError::UnknownHandle`].
1252    ///
1253    /// ɴsɪ's reserved handles are created on demand: they "don't need to
1254    /// be created using NSICreate", but they do carry attributes.
1255    fn node_mut(&mut self, handle: &str) -> Result<&mut Node, RecordError> {
1256        if crate::is_reserved(handle) {
1257            Ok(self.nodes.entry(crate::handle::handle(handle)).or_default())
1258        } else {
1259            handle::map_get_mut(&mut self.nodes, handle).ok_or_else(|| {
1260                RecordError::UnknownHandle {
1261                    handle: handle.to_string(),
1262                }
1263            })
1264        }
1265    }
1266
1267    /// Set attributes at one motion sample, keeping samples time-sorted.
1268    ///
1269    /// # Errors
1270    ///
1271    /// [`RecordError::UnknownHandle`] when the node does not exist.
1272    pub fn set_attribute_at_time(
1273        &mut self,
1274        handle: &str,
1275        time: f64,
1276        args: Vec<OwnedArgument>,
1277    ) -> Result<(), RecordError> {
1278        // 3Delight answers a non-finite time with `E6026 invalid time`.
1279        if !time.is_finite() {
1280            return Err(RecordError::InvalidTime {
1281                handle: handle.to_string(),
1282            });
1283        }
1284
1285        // `-0.0` and `0.0` are one sample to the renderer, which reads a
1286        // `-0` time as `+0`. Keeping them apart handed a backend two
1287        // matrices at times that compare equal -- a zero-length motion
1288        // segment.
1289        let time = time + 0.0;
1290
1291        // Existence first, so a rejected call records nothing.
1292        self.node_mut(handle)?;
1293        let node_handle = handle::handle(handle);
1294        // See `set_attribute` for why the node is reached for by
1295        // field rather than through `node_mut`.
1296        // SAFETY: `node_mut` above returned `Ok`, which means it
1297        // either found this handle or created it, and nothing since
1298        // could have removed it.
1299        let node = self
1300            .nodes
1301            .get_mut(&node_handle)
1302            .expect("node_mut found or created it");
1303        let node_type = crate::names::reserved_node_type(handle)
1304            .unwrap_or(node.node_type())
1305            .to_string();
1306        for mut arg in args {
1307            crate::names::to_draft(&node_type, &mut arg);
1308            let name = handle::handle(&arg.name);
1309            // ɴsɪ: setting at a time "replaces any value previously set
1310            // by NSISetAttribute", so the static value goes.
1311            if let Some(table) = node.attributes.as_mut() {
1312                table.shift_remove(&name);
1313            }
1314            self.changes
1315                .attributes
1316                .insert((handle::copy(&node_handle), handle::copy(&name)));
1317
1318            // Appended, never merged: a re-set at a time already
1319            // recorded is another call, and what it superseded is part
1320            // of the record. `Node::samples` says why.
1321            node.sample_table_mut()
1322                .entry(name)
1323                .or_default()
1324                .push((time, arg));
1325        }
1326
1327        Ok(())
1328    }
1329
1330    /// Remove one attribute by name, from static and every time sample.
1331    /// Silent when absent, as ɴsɪ is.
1332    pub fn delete_attribute(&mut self, handle: &str, name: &str) {
1333        // A delete names an attribute, so it takes the shipped
1334        // vocabulary as a set does.
1335        let node_type = crate::names::reserved_node_type(handle)
1336            .or_else(|| {
1337                handle::map_get(&self.nodes, handle)
1338                    .map(|node| node.node_type())
1339            })
1340            .unwrap_or_default()
1341            .to_string();
1342        let name = crate::names::draft_attribute(&node_type, name)
1343            .inspect(|draft| crate::names::warn_deprecated(name, draft))
1344            .unwrap_or(name);
1345        // Recorded whether or not it was set: ɴsɪ is silent about
1346        // deleting an absent attribute, and a consumer asking "what
1347        // should I look at again" is not harmed by one extra name.
1348        self.changes
1349            .attributes
1350            .insert((handle::handle(handle), handle::handle(name)));
1351        if let Some(node) = handle::map_get_mut(&mut self.nodes, handle) {
1352            if let Some(table) = node.attributes.as_mut() {
1353                table.shift_remove(&handle::handle(name));
1354            }
1355            if let Some(table) = node.samples.as_mut() {
1356                table.shift_remove(&handle::handle(name));
1357            }
1358        }
1359    }
1360
1361    /// Classify and record a connection at the default priority.
1362    ///
1363    /// An unmapped destination propagates rather than being recorded as
1364    /// a guess.
1365    pub fn connect(
1366        &mut self,
1367        from: &str,
1368        from_attribute: Option<&str>,
1369        to: &str,
1370        to_attribute: &str,
1371    ) -> Result<(), RecordError> {
1372        self.connect_with_arguments(
1373            from,
1374            from_attribute,
1375            to,
1376            to_attribute,
1377            Vec::new(),
1378        )
1379    }
1380
1381    /// Classify and record a connection carrying its ɴsɪ arguments.
1382    ///
1383    /// ɴsɪ: "It is not an error to create a connection which already
1384    /// exists." A repeat therefore updates the existing edge's arguments
1385    /// rather than adding a second one. Recording both would make the
1386    /// node look like it had two parents, which would fail resolution
1387    /// for it and everything beneath it.
1388    pub fn connect_with_arguments(
1389        &mut self,
1390        from: &str,
1391        from_attribute: Option<&str>,
1392        to: &str,
1393        to_attribute: &str,
1394        args: Vec<OwnedArgument>,
1395    ) -> Result<(), RecordError> {
1396        let kind = classify_on(
1397            self.node(to).map_or("", Node::node_type),
1398            from_attribute,
1399            to_attribute,
1400        );
1401
1402        // ɴsɪ: "the nodes on which the connection is performed must
1403        // exist." `.root` and `.global` are reserved and need no
1404        // `create`.
1405        for handle in [from, to] {
1406            if !self.is_known(handle) {
1407                return Err(RecordError::UnknownHandle {
1408                    handle: handle.to_string(),
1409                });
1410            }
1411        }
1412
1413        // Through the index, not over every edge in the scene. A
1414        // repeated `connect` has to be detected before one is appended,
1415        // and scanning `edges` for it made recording **quadratic**:
1416        // measured, one transform with 1000 children took 67 ms to
1417        // build, 4000 took 749 ms and 16 000 took 17 s. An interactive
1418        // host connects per edit, so it paid that on every one.
1419        let existing = handle::get(&self.by_from, from).and_then(|positions| {
1420            positions.iter().copied().find(|&at| {
1421                let edge = &self.edges[at];
1422                edge.to == to && edge.kind == kind
1423            })
1424        });
1425
1426        let mut rearmed = None;
1427        match existing.map(|at| &mut self.edges[at]) {
1428            Some(existing) => {
1429                // No edge appears or disappears here, and ɴsɪ's
1430                // `"priority"` rides on these arguments -- so a record
1431                // keyed on additions and removals would miss a scene
1432                // changing which shader wins.
1433                existing.args = args;
1434                rearmed = Some(existing.clone());
1435            }
1436            None => {
1437                self.by_from
1438                    .entry(handle::handle(from))
1439                    .or_default()
1440                    .push(self.edges.len());
1441                self.by_to
1442                    .entry(handle::handle(to))
1443                    .or_default()
1444                    .push(self.edges.len());
1445                self.by_to_attr
1446                    .entry((
1447                        handle::handle(to),
1448                        handle::handle(kind.to_attribute()),
1449                    ))
1450                    .or_default()
1451                    .push(self.edges.len());
1452                let edge = Edge {
1453                    from: handle::handle(from),
1454                    to: handle::handle(to),
1455                    kind,
1456                    args,
1457                };
1458                record_edge(&mut self.changes.edges_added, edge.clone());
1459                self.edges.push(edge);
1460            }
1461        }
1462
1463        if let Some(edge) = rearmed {
1464            record_edge(&mut self.changes.edges_rearmed, edge);
1465        }
1466
1467        Ok(())
1468    }
1469
1470    /// Remove a connection. Silent when absent, as ɴsɪ is.
1471    ///
1472    /// ɴsɪ: "the handle for either node, as well as any or all of the
1473    /// attributes, may be the special value `.all`. This will remove all
1474    /// connections which match the other parameters." So each of the
1475    /// four positions matches everything when it is [`ALL`].
1476    ///
1477    /// The connection *arguments* are not part of an edge's identity:
1478    /// ɴsɪ's disconnect names four things and priority is not one.
1479    pub fn disconnect(
1480        &mut self,
1481        from: &str,
1482        from_attribute: Option<&str>,
1483        to: &str,
1484        to_attribute: &str,
1485    ) -> Result<(), RecordError> {
1486        // `.all` matches every class, so there is nothing to classify.
1487        let kind = if to_attribute == ALL {
1488            None
1489        } else {
1490            Some(classify_on(
1491                self.node(to).map_or("", Node::node_type),
1492                from_attribute,
1493                to_attribute,
1494            ))
1495        };
1496
1497        let from_port = from_attribute.unwrap_or_default();
1498        let any_port = from_port == ALL;
1499
1500        let mut removed = Vec::new();
1501        self.edges.retain(|edge| {
1502            let port_matches = any_port
1503                || match &edge.kind {
1504                    EdgeKind::ShaderNetwork {
1505                        from_port: port, ..
1506                    } => port == from_port,
1507                    _ => from_port.is_empty(),
1508                };
1509
1510            let attr_matches = match &kind {
1511                // A named `to_attribute` fixes the class outright, unless the
1512                // source port is `.all` -- then only the destination
1513                // attribute is being matched.
1514                Some(kind) if !any_port => &edge.kind == kind,
1515                Some(kind) => edge.kind.to_attribute() == kind.to_attribute(),
1516                None => true,
1517            };
1518
1519            let matches = (from == ALL || edge.from == from)
1520                && (to == ALL || edge.to == to)
1521                && port_matches
1522                && attr_matches;
1523
1524            if matches {
1525                // Kept in full, because a `.all` pattern cannot be
1526                // re-expanded once the edges it named are gone.
1527                removed.push(edge.clone());
1528            }
1529
1530            !matches
1531        });
1532        for edge in removed {
1533            record_edge(&mut self.changes.edges_removed, edge);
1534        }
1535        self.reindex();
1536
1537        Ok(())
1538    }
1539}
1540
1541#[cfg(test)]
1542mod tests;