nsi_intermediate/resolve/instances.rs
1//! ɴsɪ's `instances` node: the matrices it draws its prototypes
2//! with, and the per-instance attributes that select them.
3
4use super::{
5 motion::{Located, locate_sample, matrices_of, sampled_attr},
6 *,
7};
8use crate::{HashMap, HashSet};
9
10impl Scene {
11 /// The effective value of an integer instancer attribute that was
12 /// set with `SetAttributeAtTime`.
13 ///
14 /// `None` when it was not.
15 ///
16 /// # Time is not part of the answer
17 ///
18 /// `modelindices` names a prototype and `disabledinstances` names
19 /// instances to skip. 3Delight does not sample either: the last one
20 /// **defined** applies for the whole shutter, exactly as an
21 /// overwriting `SetAttribute` would. Rendered -- two instances,
22 /// `disabledinstances [1]` at `t=0` then `[0]` at `t=1` -- it draws
23 /// instance **1**, which is the `t=1` value applying throughout, and
24 /// mirroring the values mirrors the result. Moving the shutter to
25 /// `[0, 0.25]`, `[2, 3]` or `[-3, -2]` changes nothing.
26 ///
27 /// An earlier version held the *earlier* sample of the bracketing
28 /// pair -- a step -- and documented that as a choice, because the
29 /// probe behind it used the same values at both times and could not
30 /// tell a step from a blend. It was the wrong choice, and it
31 /// returned the discarded sample in every case that discriminates.
32 ///
33 /// The last **defined**, which is not the last by time for a
34 /// stream that sets `t=1` before `t=0`. That was a divergence for
35 /// as long as the record was a table keyed by time;
36 /// [`Node::samples`] is a call log, and this reads the last of
37 /// them.
38 pub(super) fn instance_ints(
39 &self,
40 node: &Node,
41 name: &str,
42 ) -> Option<Vec<i32>> {
43 // The shared typing rule, not a sixth hand-rolled copy of it:
44 // the last sample that *names* the attribute wins, and a type
45 // that cannot be read unsets it. Rendered, a good `int` at
46 // `t=0` followed by an `int64` draws *both* instances.
47 match sampled_attr(node, name, |arg| {
48 matches!(arg.data, OwnedData::I32(_))
49 }) {
50 Sampled::No => None,
51 Sampled::Unset => Some(Vec::new()),
52 // The last *defined*, which 3Delight applies for the whole
53 // shutter as an overwriting `SetAttribute` would. Taking
54 // the last by time answered a different sample for any
55 // scene whose samples did not arrive in time order.
56 Sampled::Yes { last_defined, .. } => {
57 Some(match &last_defined.data {
58 OwnedData::I32(values) => values.to_vec(),
59 _ => Vec::new(),
60 })
61 }
62 }
63 }
64
65 /// The instancer's matrices at `time`, when they are sampled.
66 ///
67 /// `None` when the node has no sampled matrices, in which case the
68 /// static ones apply.
69 pub(super) fn instance_matrices_at(
70 &self,
71 node: &Node,
72 instances: &str,
73 time: Option<f64>,
74 ) -> Result<Option<Vec<f64>>, ResolveError> {
75 // The same typing rule: a wrong-typed last sample unsets the
76 // matrices, and 3Delight then draws **nothing** rather than the
77 // discarded earlier set.
78 let mut samples: Vec<(f64, &[f64])> = match sampled_attr(
79 node,
80 MATRICES,
81 |arg| matrices_of(arg).is_some(),
82 ) {
83 // `No` means "use the static value"; `Unset` means
84 // "there is none". Indistinguishable today, because
85 // `set_attribute` clears the samples of that name and
86 // `set_attribute_at_time` clears the static one, so a
87 // node never holds both -- swapping these two leaves
88 // the suite green, and no reachable scene separates
89 // them. Kept apart because they say different things,
90 // and the arm that would go wrong if that rule changed
91 // is the one that draws instances that should not be
92 // there.
93 Sampled::No => return Ok(None),
94 Sampled::Unset => return Ok(Some(Vec::new())),
95 found @ Sampled::Yes { .. } => found
96 .samples()
97 .filter_map(|(t, arg)| Some((t, matrices_of(arg)?)))
98 .collect(),
99 };
100
101 // A sample that changes the instance *count* describes a
102 // different set, not a moved one, and 3Delight refuses the
103 // change rather than the instancer: `E6023 ... incompatible
104 // with its definition at previously defined time steps and will
105 // be ignored`, after which it renders the first sample's set,
106 // static. Rendered with 2 matrices at t=0 and 3 at t=1: two
107 // sharp bands at the t=0 positions, no third instance and no
108 // blur. Dropping the mismatched samples here reproduces that.
109 let width = samples[0].1.len();
110 samples.retain(|(_, values)| values.len() == width);
111
112 let Some(time) = time else {
113 return Err(ResolveError::MotionSampledTransform {
114 handle: instances.to_string(),
115 });
116 };
117
118 match locate_sample(&samples, time) {
119 Some(Located::At(values)) => Ok(Some(values.to_vec())),
120 Some(Located::Between(from, to, alpha)) => {
121 // Samples of a differing length were dropped above, so
122 // the two here agree by construction.
123 Ok(Some(
124 from.iter()
125 .zip(*to)
126 .map(|(a, b)| a * (1.0 - alpha) + b * alpha)
127 .collect(),
128 ))
129 }
130 None => Err(ResolveError::MissingSampleAtTime {
131 handle: instances.to_string(),
132 time,
133 available: samples.iter().map(|(t, _)| *t).collect(),
134 }),
135 }
136 }
137
138 /// The prototypes an `instances` node draws from, in connection
139 /// order.
140 ///
141 /// Mitsuba turns these into a `shapegroup` referenced by `instance`
142 /// shapes; MoonRay into a `GeometrySet`. Both start from this list.
143 /// ɴsɪ: connections "must have an integer index attribute if there
144 /// are several, so the models effectively form an ordered list", and
145 /// an `instances` node's `modelindices` "is matched to the index
146 /// attribute of the model connection". So the list is ordered by
147 /// that index, not by connection order -- a backend indexes into it.
148 /// Connections without one share index `0` and keep their relative
149 /// connection order.
150 pub fn instance_sources(&self, instances: &str) -> Vec<String> {
151 self.sorted_instance_sources(instances)
152 .into_iter()
153 .map(|(_, from)| from)
154 .collect()
155 }
156
157 /// Compose the transform chain from `handle` up to, but excluding,
158 /// `ancestor`.
159 ///
160 /// The transform an instancing prototype needs: its subtree cannot
161 /// be resolved to world space, because the `instances` node placing
162 /// it holds one matrix per instance, but it *can* be resolved
163 /// relative to the prototype root that the instance transform is
164 /// then applied to.
165 ///
166 /// `relative_transform(h, ROOT)` is [`Scene::world_transform`].
167 ///
168 /// # Errors
169 ///
170 /// [`ResolveError::NotAnAncestor`] when `ancestor` is not on
171 /// `handle`'s chain, plus the usual walk errors.
172 pub fn relative_transform(
173 &self,
174 handle: &str,
175 ancestor: &str,
176 ) -> Result<[f64; 16], ResolveError> {
177 let chain = self.linked_chain(handle, true)?;
178
179 let depth = chain
180 .iter()
181 .position(|link| link.handle == ancestor)
182 .ok_or_else(|| ResolveError::NotAnAncestor {
183 handle: handle.to_string(),
184 ancestor: ancestor.to_string(),
185 })?;
186
187 // Composing across an `instances` node would fold in the
188 // instancer's own matrix and leave out the per-instance one --
189 // a plausible wrong answer, which is the thing this crate is
190 // for refusing. Stopping *at* the instancer is the supported
191 // case and is what a backend asks for.
192 // Only a *crossing* is wrong. Stopping at the instancer means
193 // its matrix is never composed, which is exactly the query a
194 // backend makes to place a prototype's subtree.
195 if let Some(crossed) = chain[..depth]
196 .iter()
197 .enumerate()
198 .position(|(hop, link)| link.via_instancer && hop + 1 < depth)
199 {
200 return Err(ResolveError::Instanced {
201 instancer: chain[crossed + 1].handle.clone(),
202 });
203 }
204
205 chain[..depth].iter().try_fold(IDENTITY, |matrix, link| {
206 let node = &link.handle;
207 if self.has_motion_transform(node) {
208 Err(ResolveError::MotionSampledTransform {
209 handle: node.clone(),
210 })
211 } else {
212 Ok(match self.local_transform(node) {
213 Some(local) => mul(matrix, local),
214 None => matrix,
215 })
216 }
217 })
218 }
219
220 /// The instancer's instances, **without copying the matrices**.
221 ///
222 /// The streaming twin of [`Scene::instance_transforms`], with the
223 /// same rules: `modelindices` matched against each connection's
224 /// index attribute rather than connection order,
225 /// `disabledinstances` applied, and a sampled instancer refused
226 /// rather than reported empty -- ask
227 /// [`Scene::instance_transforms_at`] for that one.
228 ///
229 /// This is the shape a renderer's own instancer wants: create one
230 /// object per [`Scene::instance_sources`] entry, then feed it
231 /// `(source, transform)` pairs. Measured on a million instances,
232 /// the copying form spends 110 ms and returns 136 MB against the
233 /// 128 MB the scene already holds; this borrows.
234 ///
235 /// Both per-instance lookups are hashed rather than scanned. The
236 /// copying form scans the source list and the disabled list for
237 /// every instance, which is fine for the ten-prototype scene it
238 /// was written against and quadratic for a set-dressing instancer
239 /// with thousands.
240 ///
241 /// # Errors
242 ///
243 /// As [`Scene::instance_transforms`].
244 pub fn instances(
245 &self,
246 instances: &str,
247 ) -> Result<Instances<'_>, ResolveError> {
248 let Some(node) = self.node(instances) else {
249 return Ok(Instances::empty());
250 };
251
252 // Refuses a sampled instancer exactly as the copying form
253 // does, and for the same reason: an interpolated matrix is
254 // computed, so there is nothing to borrow.
255 self.instance_matrices_at(node, instances, None)?;
256
257 let matrices = node
258 .attribute(MATRICES)
259 .and_then(matrices_of)
260 .unwrap_or(&[]);
261 if !matrices.len().is_multiple_of(16) {
262 return Err(ResolveError::MalformedInstanceMatrices {
263 instances: instances.to_string(),
264 values: matrices.len(),
265 });
266 }
267
268 let model_indices = match node.attribute(MODEL_INDICES) {
269 Some(arg) => arg.as_i32s().unwrap_or(&[]),
270 None => &[],
271 };
272 let disabled: HashSet<i32> = match node.attribute(DISABLED) {
273 Some(arg) => arg.as_i32s().unwrap_or(&[]).iter().copied().collect(),
274 None => HashSet::new(),
275 };
276
277 let sources = self.sorted_instance_sources(instances);
278 let by_model: HashMap<i32, usize> = sources
279 .iter()
280 .enumerate()
281 .map(|(position, (index, _))| (*index, position))
282 .collect();
283
284 // Every model index is checked once, here, so iterating is
285 // infallible: a stream that yields a `Result` per instance
286 // makes every consumer handle an error that is a property of
287 // the scene, not of the instance.
288 for model in model_indices.iter().copied().filter(|model| *model >= 0) {
289 if !by_model.contains_key(&model) {
290 return Err(ResolveError::UnknownModelIndex {
291 instances: instances.to_string(),
292 model,
293 });
294 }
295 }
296
297 Ok(Instances {
298 matrices: matrices.as_chunks::<16>().0,
299 model_indices,
300 by_model,
301 disabled,
302 at: 0,
303 })
304 }
305
306 /// The instances an `instances` node places.
307 ///
308 /// Reads ɴsɪ's `transformationmatrices` for the per-instance
309 /// transforms, `modelindices` for which prototype each draws, and
310 /// `disabledinstances` for the ones to skip. An instance whose model
311 /// index is negative is omitted too: ɴsɪ says "a negative value will
312 /// cause an instance to not be rendered".
313 ///
314 /// Empty when the node carries no `transformationmatrices` at all.
315 ///
316 /// # Errors
317 ///
318 /// [`ResolveError::MalformedInstanceMatrices`] when the matrix
319 /// buffer is not a whole number of 4x4s, and
320 /// [`ResolveError::UnknownModelIndex`] when a `modelindices` entry
321 /// matches no prototype connection. Both were silent drops, which is
322 /// the failure mode this crate exists to refuse.
323 ///
324 /// [`ResolveError::MotionSampledTransform`] when the matrices are
325 /// *sampled* rather than static: this read only the static
326 /// attributes, so a moving instancer -- which 3Delight renders --
327 /// came back as an empty list, indistinguishable from "no
328 /// instances". Ask [`Scene::instance_transforms_at`] for those.
329 pub fn instance_transforms(
330 &self,
331 instances: &str,
332 ) -> Result<Vec<Instance>, ResolveError> {
333 self.instances_with(instances, None)
334 }
335
336 /// The same, with the instance matrices interpolated at `time`.
337 ///
338 /// ɴsɪ animates a whole instancer by sampling
339 /// `transformationmatrices`, which is how a crowd or a particle
340 /// system moves. Interpolated element-wise between the bracketing
341 /// samples and held outside them, exactly as
342 /// [`Scene::world_transform_interpolated_at`] describes.
343 ///
344 /// # Errors
345 ///
346 /// As [`Scene::instance_transforms`], less
347 /// [`ResolveError::MotionSampledTransform`]; plus
348 /// [`ResolveError::MissingSampleAtTime`] for a time that names no
349 /// sample, such as a NaN.
350 pub fn instance_transforms_at(
351 &self,
352 instances: &str,
353 time: f64,
354 ) -> Result<Vec<Instance>, ResolveError> {
355 self.instances_with(instances, Some(time))
356 }
357
358 /// The shared body: `time` is `None` for the static reading.
359 pub(super) fn instances_with(
360 &self,
361 instances: &str,
362 time: Option<f64>,
363 ) -> Result<Vec<Instance>, ResolveError> {
364 let Some(node) = self.node(instances) else {
365 return Ok(Vec::new());
366 };
367
368 let sampled = self.instance_matrices_at(node, instances, time)?;
369 let matrices: &[f64] = match (&sampled, node.attribute(MATRICES)) {
370 (Some(values), _) => values,
371 (None, Some(arg)) => matrices_of(arg).unwrap_or(&[]),
372 (None, None) => &[],
373 };
374
375 // `modelindices` and `disabledinstances` can be sampled too,
376 // and 3Delight honours them: an instancer whose
377 // `disabledinstances` is set only through `SetAttributeAtTime`
378 // renders the same one instance as the static form, and a
379 // sampled `modelindices` selects the same prototype. Reading
380 // only `attributes` reported every instance as enabled and drawn from
381 // source 0 -- the same silent-empty class as the matrices, one
382 // level down.
383 let sampled_models = self.instance_ints(node, MODEL_INDICES);
384 let model_indices: &[i32] =
385 match (&sampled_models, node.attribute(MODEL_INDICES)) {
386 (Some(values), _) => values,
387 (None, Some(arg)) => match &arg.data {
388 OwnedData::I32(values) => values.as_slice(),
389 _ => &[],
390 },
391 (None, None) => &[],
392 };
393
394 let sampled_disabled = self.instance_ints(node, DISABLED);
395 let disabled: &[i32] =
396 match (&sampled_disabled, node.attribute(DISABLED)) {
397 (Some(values), _) => values,
398 (None, Some(arg)) => match &arg.data {
399 OwnedData::I32(values) => values.as_slice(),
400 _ => &[],
401 },
402 (None, None) => &[],
403 };
404
405 // `modelindices` names the connection's `index` attribute, so
406 // the value has to be looked up rather than used as a position.
407 if !matrices.len().is_multiple_of(16) {
408 return Err(ResolveError::MalformedInstanceMatrices {
409 instances: instances.to_string(),
410 values: matrices.len(),
411 });
412 }
413
414 let sources = self.sorted_instance_sources(instances);
415
416 if let Some(pair) = sources
417 .windows(2)
418 .find(|pair| pair[0].0 == pair[1].0 && sources.len() > 1)
419 {
420 return Err(ResolveError::DuplicateModelIndex {
421 instances: instances.to_string(),
422 index: pair[0].0,
423 });
424 }
425
426 matrices
427 .as_chunks::<16>()
428 .0
429 .iter()
430 .enumerate()
431 .filter(|(instance, _)| {
432 !disabled.contains(&(i32::try_from(*instance).unwrap_or(-1)))
433 })
434 .filter_map(|(instance, values)| {
435 let model =
436 model_indices.get(instance).copied().unwrap_or_default();
437 // ɴsɪ: "a negative value will cause an instance to not
438 // be rendered".
439 if model < 0 {
440 return None;
441 }
442
443 Some(
444 sources
445 .iter()
446 .position(|(index, _)| *index == model)
447 .ok_or_else(|| ResolveError::UnknownModelIndex {
448 instances: instances.to_string(),
449 model,
450 })
451 .map(|source| Instance {
452 source,
453 transform: *values,
454 }),
455 )
456 })
457 .collect()
458 }
459
460 /// The prototypes of an `instances` node with their `index`
461 /// arguments, ordered as [`Scene::instance_sources`] returns them.
462 pub(super) fn sorted_instance_sources(
463 &self,
464 instances: &str,
465 ) -> Vec<(i32, String)> {
466 let mut sources = self
467 .edges_to_attribute(
468 instances,
469 EdgeKind::InstanceSource.to_attribute(),
470 )
471 .filter(|edge| edge.kind == EdgeKind::InstanceSource)
472 .enumerate()
473 .map(|(order, edge)| (edge.index(), order, edge.from().to_string()))
474 .collect::<Vec<_>>();
475 sources.sort_by_key(|(index, order, _)| (*index, *order));
476 sources
477 .into_iter()
478 .map(|(index, _, from)| (index, from))
479 .collect()
480 }
481}
482
483/// The instances of one `instances` node, borrowed.
484///
485/// Returned by [`Scene::instances`]. Yields in instance order, with
486/// the disabled ones and those whose `modelindices` entry is negative
487/// left out -- ɴsɪ says a negative index draws nothing.
488pub struct Instances<'a> {
489 matrices: &'a [[f64; 16]],
490 model_indices: &'a [i32],
491 by_model: HashMap<i32, usize>,
492 disabled: HashSet<i32>,
493 at: usize,
494}
495
496impl Instances<'_> {
497 fn empty() -> Self {
498 Self {
499 matrices: &[],
500 model_indices: &[],
501 by_model: HashMap::new(),
502 disabled: HashSet::new(),
503 at: 0,
504 }
505 }
506}
507
508impl<'a> Iterator for Instances<'a> {
509 type Item = InstanceRef<'a>;
510
511 fn next(&mut self) -> Option<Self::Item> {
512 while self.at < self.matrices.len() {
513 let at = self.at;
514 self.at += 1;
515
516 if self.disabled.contains(&i32::try_from(at).unwrap_or(-1)) {
517 continue;
518 }
519 let model = self.model_indices.get(at).copied().unwrap_or_default();
520 if model < 0 {
521 continue;
522 }
523 // Checked in `Scene::instances`, so this cannot miss.
524 let Some(source) = self.by_model.get(&model).copied() else {
525 continue;
526 };
527
528 return Some(InstanceRef {
529 source,
530 transform: &self.matrices[at],
531 });
532 }
533 None
534 }
535
536 fn size_hint(&self) -> (usize, Option<usize>) {
537 (0, Some(self.matrices.len() - self.at))
538 }
539}