nsi_intermediate/resolve/motion.rs
1//! Time: which samples stand, and what the transform is between
2//! them.
3//!
4//! ɴsɪ's rules here are stated over *calls*, so the typing rule
5//! ([`sampled_attr`]) and the hold-the-ends rule ([`locate_sample`])
6//! are each written once and read by every accessor that needs them.
7
8use super::*;
9
10/// What ɴsɪ's typing rule makes of one attribute's samples.
11///
12/// Returned by [`Scene::sampled_attribute`], and what the resolver
13/// itself reads for `transformationmatrix` and the instancer's
14/// attributes.
15#[derive(Debug, Clone, PartialEq)]
16#[non_exhaustive]
17pub enum Sampled<'a> {
18 /// Not sampled. The static value applies and [`Node::effective`]
19 /// gives it -- **run the same predicate over that too**: the rule
20 /// is about the call, not about `SetAttributeAtTime`. Rendered, a
21 /// static `"nvertices" "int64" 1` is `E6007`, then `E6020`, and
22 /// the mesh does not draw.
23 No,
24 /// Sampled, but the last call cannot be read as the attribute's
25 /// type -- so the attribute is unset, at every time.
26 ///
27 /// This is not "no samples": 3Delight rejects the argument at the
28 /// call and the attribute has no value at all afterwards.
29 /// Rendered on a mesh's `P` -- good at `t=0`, a `float` at `t=1` --
30 /// it logs `E6007` and then `E6020`, and **draws nothing**. A
31 /// backend that fell back to the earlier sample here would draw a
32 /// mesh the renderer does not.
33 Unset,
34 /// The surviving samples.
35 ///
36 /// Never empty: `keep_from` is one past the last *unreadable*
37 /// definition and equals the count only in the `Unset` case, so at
38 /// least one survivor is always left. Three call sites carried an
39 /// `is_empty` branch for a case that cannot arise; they are gone.
40 ///
41 /// The name is resolved here rather than at every consumer, which
42 /// is what lets the survivors be an arbitrary subset of the
43 /// timeline.
44 Yes {
45 /// In **time** order, which is what interpolation needs.
46 samples: Vec<(f64, &'a OwnedArgument)>,
47 /// The survivor defined **last**, which is what an attribute
48 /// that is not motion data takes for the whole shutter -- and
49 /// is not the sample at the greatest time for a scene whose
50 /// samples did not arrive in time order.
51 last_defined: &'a OwnedArgument,
52 },
53}
54
55impl<'a> Sampled<'a> {
56 /// The surviving samples, in time order.
57 pub(super) fn samples(
58 self,
59 ) -> impl Iterator<Item = (f64, &'a OwnedArgument)> {
60 match self {
61 Self::Yes { samples, .. } => samples.into_iter(),
62 Self::No | Self::Unset => Vec::new().into_iter(),
63 }
64 }
65}
66
67/// Apply ɴsɪ's typing rule to a node's samples of `name`.
68///
69/// An unreadable sample **discards every sample before it**. 3Delight
70/// warns `E6007` and unsets the attribute at that call; only samples
71/// set afterwards rebuild it. So if the last sample naming the
72/// attribute is unreadable it is unset entirely, and otherwise the
73/// answer is the run of samples following the last unreadable one.
74///
75/// Rendered, and this is the case that settles it: a good
76/// `doublematrix` at `t=0`, a `float` at `t=1`, a good one at `t=2`
77/// draws a **static** object at the `t=2` matrix -- one lit band. The
78/// control without the `float` sweeps across four. Dropping the
79/// unreadable sample and keeping the two good ones, which this rule
80/// first said, produces that sweep: a motion blur the renderer does not
81/// draw.
82///
83/// Stated once because it was stated six times and only one was right.
84/// The correction matters more than the sharing: deduplicating a rule
85/// makes every site agree, and they agreed on the wrong answer until
86/// this scene was rendered.
87pub(super) fn sampled_attr<'a>(
88 node: &'a Node,
89 name: &str,
90 readable: impl Fn(&OwnedArgument) -> bool,
91) -> Sampled<'a> {
92 // In **call** order, not time order: 3Delight rejects an unreadable
93 // argument at the call, so what survives is what was set after it.
94 // `Node::samples` is a call log for exactly this reason; a table
95 // keyed by time answers by position on the timeline, which is a
96 // different set of survivors for any scene whose samples did not
97 // arrive in time order.
98 let Some(calls) = node.sample_calls(name) else {
99 return Sampled::No;
100 };
101
102 let mut keep_from = 0;
103 for (index, (_, arg)) in calls.iter().enumerate() {
104 if !readable(arg) {
105 keep_from = index + 1;
106 }
107 }
108
109 // The last call is itself unreadable, so nothing survives it and
110 // the attribute is unset at every time. Also the empty log a caller
111 // could put here by hand.
112 let Some((_, last_defined)) = calls[keep_from..].last() else {
113 return Sampled::Unset;
114 };
115
116 Sampled::Yes {
117 // The same-time rule is `latest_per_time`'s, run over the
118 // survivors rather than over every call: a re-set that
119 // superseded an unreadable sample stands alone, where one that
120 // superseded a good sample merely replaces it.
121 samples: crate::scene::latest_per_time(&calls[keep_from..]),
122 last_defined,
123 }
124}
125
126/// Where a time falls among a set of samples.
127pub(super) enum Located<'a, T> {
128 /// Use this sample as it stands: an exact hit, or a held end.
129 At(&'a T),
130 /// Interpolate, `alpha` of the way from the first to the second.
131 Between(&'a T, &'a T, f64),
132}
133
134/// Locate `time` among samples ordered by time.
135///
136/// The one statement of ɴsɪ's sampling rule -- exact hit, hold the end
137/// outside the range, otherwise interpolate between the bracketing
138/// pair. Both the transform path and the instancer path read it here.
139///
140/// It exists because they did not. The instancer's copy dropped the
141/// exact-hit branch, so asking at an interior sample time -- shutter
142/// centre, the single most ordinary query -- errored on a scene the
143/// renderer draws. That was the fourth time a copied resolution rule
144/// drifted in this crate, and the commit before it removed three.
145///
146/// `None` when there are no samples, or when `time` names nothing: a
147/// NaN compares false against everything and brackets no pair.
148pub(super) fn locate_sample<T>(
149 samples: &[(f64, T)],
150 time: f64,
151) -> Option<Located<'_, T>> {
152 // `-0.0` names the sample at `0.0`: the recorder folds the two when
153 // storing, and the renderer reads `-0` as `+0`. Without this,
154 // `total_cmp` misses the exact hit, the `<=`/`>=` ends do not clamp
155 // an *interior* `0.0`, and the strict windows bracket nothing -- so
156 // querying at `-0.0` errored on a sample that exists.
157 let time = time + 0.0;
158
159 // A NaN names no sample and brackets nothing. The linear scan
160 // refused it for free -- every comparison against a NaN is false --
161 // but a search does not: `total_cmp` sorts a NaN above every real,
162 // so the partition would put it past the last sample and **hold
163 // the end**, answering where the scan errored. The suite caught
164 // that; this is what it caught.
165 if time.is_nan() {
166 return None;
167 }
168
169 let first = samples.first()?;
170 let last = samples.last()?;
171
172 // The samples are in time order, so the scan is a search. It used
173 // to be three linear passes -- an exact-hit `find`, then the two
174 // clamps, then a `windows(2)` -- which is the T x N that made
175 // `world_transform_samples` quadratic in a scene sampled per
176 // frame. The answers are the same three.
177 let at =
178 samples.partition_point(|(t, _)| t.total_cmp(&time) == Ordering::Less);
179
180 if let Some((t, value)) = samples.get(at)
181 && t.total_cmp(&time) == Ordering::Equal
182 {
183 return Some(Located::At(value));
184 }
185
186 // Before the first sample or after the last: the end is held,
187 // never extrapolated.
188 if at == 0 {
189 return Some(Located::At(&first.1));
190 }
191 if at == samples.len() {
192 return Some(Located::At(&last.1));
193 }
194
195 let (from_time, from) = &samples[at - 1];
196 let (to_time, to) = &samples[at];
197 let alpha = (time - from_time) / (to_time - from_time);
198 Some(Located::Between(from, to, alpha))
199}
200
201/// One chain node's transform with the typing rule already applied.
202pub(super) enum Local {
203 /// Constant at every time; `None` when the node sets none.
204 Constant(Option<[f64; 16]>),
205 /// Sampled, in time order.
206 Sampled(Vec<(f64, [f64; 16])>),
207}
208
209/// One node's transform at `time`.
210///
211/// Outside the sampled range the end sample is held, because that is
212/// what 3Delight does. Rendered: samples at `t=0` and `t=1` with the
213/// shutter open over `[-1, 2]` leaves **zero** alpha beyond the two
214/// sampled positions -- an extrapolating renderer would sweep half
215/// again as far each way -- with a peak at each end, 2.7x the swept
216/// middle, where a third of the shutter is held. `locate_sample`
217/// states that rule once.
218pub(super) fn local_at(
219 handle: &str,
220 local: &Local,
221 time: f64,
222) -> Result<Option<[f64; 16]>, ResolveError> {
223 let samples = match local {
224 Local::Constant(matrix) => return Ok(*matrix),
225 Local::Sampled(samples) => samples,
226 };
227
228 match locate_sample(samples, time) {
229 Some(Located::At(matrix)) => Ok(Some(*matrix)),
230 Some(Located::Between(from, to, alpha)) => {
231 let mut out = [0.0f64; 16];
232 for (index, slot) in out.iter_mut().enumerate() {
233 *slot = from[index] * (1.0 - alpha) + to[index] * alpha;
234 }
235 Ok(Some(out))
236 }
237 None => Err(ResolveError::MissingSampleAtTime {
238 handle: handle.to_string(),
239 time,
240 available: samples.iter().map(|(t, _)| *t).collect(),
241 }),
242 }
243}
244
245/// Compose an already-resolved chain at `time`.
246///
247/// The one interpolating fold: `world_transform_interpolated_at`
248/// resolves the chain and calls it once, `world_transform_samples`
249/// resolves the chain and calls it per time. A copied composition has
250/// drifted four times in this crate, which is why the second caller
251/// takes this rather than a fold of its own.
252pub(super) fn interpolate_resolved(
253 resolved: &[(&str, Local)],
254 time: f64,
255) -> Result<[f64; 16], ResolveError> {
256 resolved
257 .iter()
258 .try_fold(IDENTITY, |matrix, (handle, local)| {
259 Ok(match local_at(handle, local, time)? {
260 Some(local) => mul(matrix, local),
261 None => matrix,
262 })
263 })
264}
265
266/// A `transformationmatrix` argument as a row-major 4x4.
267///
268/// Non-`f64` matrices yield `None`: ɴsɪ documents the attribute as
269/// `doublematrix`, and silently reinterpreting an `f32` one would be
270/// worse than skipping it.
271pub(super) fn matrices_of(arg: &OwnedArgument) -> Option<&[f64]> {
272 // The declared type, array suffix included -- one statement of it,
273 // in `OwnedArgument::as_matrices`. Rendered twice over: sixteen
274 // `double`s are not a `doublematrix`, and a `doublematrix[2]` is
275 // not one either (`E6007`, nothing drawn, where the plain
276 // `doublematrix` draws two copies). Both leniencies drew what the
277 // renderer refuses, and the second outlived the first because the
278 // rule was stated in three places.
279 arg.as_matrices()
280}
281
282/// A `transformationmatrix` argument as a row-major 4x4.
283///
284/// Non-`f64` matrices yield `None`: ɴsɪ documents the attribute as
285/// `doublematrix`, and silently reinterpreting an `f32` one would be
286/// worse than skipping it.
287pub(super) fn matrix_of(arg: &OwnedArgument) -> Option<[f64; 16]> {
288 arg.as_matrix()
289}
290
291impl Scene {
292 /// Every time at which a transform in `handle`'s chain is sampled,
293 /// ascending, deduplicated.
294 ///
295 /// Empty for a wholly static chain, which is the check a backend
296 /// makes to decide between [`Scene::world_transform`] and
297 /// [`Scene::world_transform_samples`].
298 ///
299 /// **Transforms only.** An `instances` node whose
300 /// `transformationmatrices` are sampled reports no motion times
301 /// here, while [`Scene::instance_transforms`] refuses it and says to
302 /// ask at a time -- leaving a backend that used this as its
303 /// static-or-sampled check with no time to ask at. Use
304 /// [`Scene::attribute_times`] with `"transformationmatrices"` for an
305 /// instancer, and [`Scene::attribute_times`] with `"P"` for
306 /// deforming geometry.
307 ///
308 /// # Errors
309 ///
310 /// [`ResolveError::MultipleParents`] or [`ResolveError::Cycle`].
311 pub fn motion_times(&self, handle: &str) -> Result<Vec<f64>, ResolveError> {
312 let chain = self.transform_chain(handle)?;
313 Ok(self.motion_times_along(&chain))
314 }
315
316 /// The same, along a path already walked.
317 ///
318 /// [`Scene::motion_times`] refuses a geometry with more than one
319 /// parent, because it walks the chain itself and there is no single
320 /// chain. A backend emitting per-sample transforms for an instanced
321 /// object needs the times of *its* path, which is what a
322 /// [`Placement`] carries -- pass `placement.path`.
323 pub fn motion_times_along(&self, path: &[String]) -> Vec<f64> {
324 // The typing rule again: an unreadable sample is not a motion
325 // time. Reporting one made `world_transform_samples` iterate a
326 // time that `world_transform_at` then refused -- the same scene
327 // answered differently depending on which accessor asked.
328 let mut times = path
329 .iter()
330 .filter_map(|node| self.node(node))
331 .flat_map(|node| {
332 sampled_attr(node, TRANSFORMATION_MATRIX, |arg| {
333 matrix_of(arg).is_some()
334 })
335 .samples()
336 })
337 .map(|(time, _)| time)
338 .collect::<Vec<_>>();
339
340 // `total_cmp` throughout, matching how the samples were keyed.
341 times.sort_by(f64::total_cmp);
342 times.dedup_by(|a, b| a.total_cmp(b) == Ordering::Equal);
343
344 times
345 }
346
347 /// Every time at which `name` is sampled on `handle`, ascending.
348 ///
349 /// Empty when the attribute is static or absent, which is the check
350 /// a backend makes before asking for
351 /// [`Scene::attribute_samples`] -- the same shape as
352 /// [`Scene::motion_times`] and [`Scene::world_transform_samples`].
353 ///
354 /// This is what makes deforming geometry resolvable: a mesh whose
355 /// `P` is sampled under a *static* transform has no motion times at
356 /// all, so [`Scene::motion_times`] answers "static" for something
357 /// that plainly moves. Ask this for `"P"`, and take the union with
358 /// [`Scene::motion_times`] when a backend needs every time the
359 /// object changes -- ɴsɪ does not require the two to agree.
360 ///
361 /// # Every recorded time, including unreadable ones
362 ///
363 /// [`Scene::motion_times`] drops a sample whose type it cannot
364 /// read, because 3Delight unsets such an attribute and it knows
365 /// `transformationmatrix` is a `doublematrix`. This cannot: `name`
366 /// is any attribute, and the crate does not carry ɴsɪ's type for
367 /// each one, so "unreadable" has no meaning here. It reports what
368 /// was recorded and [`Scene::attribute_samples`] hands over the
369 /// arguments for a caller that knows the type to judge.
370 ///
371 /// So the two disagree by design on a scene with a wrong-typed
372 /// transform sample, and that is the one case worth knowing about.
373 ///
374 /// # Errors
375 ///
376 /// [`ResolveError::UnknownHandle`] if no such node exists.
377 pub fn attribute_times(
378 &self,
379 handle: &str,
380 name: &str,
381 ) -> Result<Vec<f64>, ResolveError> {
382 let Some(node) = self.existing_node(handle)? else {
383 return Ok(Vec::new());
384 };
385
386 // The times a value stands at, which is not one per call: a
387 // re-set at a time already recorded is another call and the
388 // same sample.
389 Ok(node
390 .sample_calls(name)
391 .map(|calls| {
392 crate::scene::latest_per_time(calls)
393 .into_iter()
394 .map(|(time, _)| time)
395 .collect()
396 })
397 .unwrap_or_default())
398 }
399
400 /// The recorded samples of `name` on `handle`, ascending by time.
401 ///
402 /// Empty on the same terms as [`Scene::attribute_times`]. The
403 /// static value, if any, is *not* included: a sampled attribute and
404 /// a static one are separate recordings, and mixing them would
405 /// invent a sample at a time the caller never set.
406 ///
407 /// # Errors
408 ///
409 /// [`ResolveError::UnknownHandle`] if no such node exists.
410 pub fn attribute_samples(
411 &self,
412 handle: &str,
413 name: &str,
414 ) -> Result<Vec<(f64, &OwnedArgument)>, ResolveError> {
415 let Some(node) = self.existing_node(handle)? else {
416 return Ok(Vec::new());
417 };
418
419 Ok(node
420 .sample_calls(name)
421 .map(crate::scene::latest_per_time)
422 .unwrap_or_default())
423 }
424
425 /// The same, with ɴsɪ's **typing rule** applied.
426 ///
427 /// [`Scene::attribute_samples`] reports what was recorded, because
428 /// `name` is any attribute and this crate does not carry ɴsɪ's
429 /// type for each one. A backend does know: it knows `P` is a
430 /// `point` and `N` a `normal`. Hand that knowledge in as
431 /// `readable` and this applies the rule the resolver applies to
432 /// `transformationmatrix`, rather than making every backend
433 /// re-derive it.
434 ///
435 /// The rule, rendered on a mesh's deforming `P` and identical to
436 /// the transform case: an unreadable call unsets the attribute
437 /// **at the call**, so it discards what was defined before it and
438 /// only later calls rebuild it. Good at `t=0` with a `float` at
439 /// `t=1` draws **nothing** (`Sampled::Unset`); the same two with a
440 /// good `P` re-set at `t=1` afterwards draws static at that `P`.
441 /// A backend that dropped the unreadable sample and kept the rest
442 /// would sweep through both, which is the answer 3Delight gives to
443 /// neither.
444 ///
445 /// # What `readable` should say
446 ///
447 /// 3Delight does not type-check every attribute, so the strictest
448 /// predicate is not always the right one. Rendered: `P` declared
449 /// `vector`, `normal`, `color`, `float 12` or `double 12` is
450 /// `E6007` and the mesh does not draw -- there an exact
451 /// `type_tag == Type::Point` matches the renderer. But `N`
452 /// declared `vector` raises **no** error and renders identically
453 /// to a `normal`, so a predicate demanding `Type::Normal` reports
454 /// `Unset` for a call 3Delight accepts. The rule this applies is
455 /// proven for the attributes the renderer type-checks; for the
456 /// others, `readable` is the backend's own policy and this crate
457 /// does not know better.
458 ///
459 /// # Errors
460 ///
461 /// [`ResolveError::UnknownHandle`] if no such node exists. A node
462 /// that exists but never had the attribute set is
463 /// [`Sampled::No`], not an error.
464 pub fn sampled_attribute(
465 &self,
466 handle: &str,
467 name: &str,
468 readable: impl Fn(&OwnedArgument) -> bool,
469 ) -> Result<Sampled<'_>, ResolveError> {
470 let Some(node) = self.existing_node(handle)? else {
471 return Ok(Sampled::No);
472 };
473 Ok(sampled_attr(node, name, readable))
474 }
475
476 /// The world transform at `time`, interpolating linearly between
477 /// the samples that bracket it.
478 ///
479 /// [`Scene::world_transform_at`] answers only at a recorded sample,
480 /// which is right for asking "what did the caller say". A backend
481 /// rendering motion blur needs a transform at an arbitrary shutter
482 /// time instead, and this is that.
483 ///
484 /// # Why component-wise is not a guess
485 ///
486 /// Blur moves *points*. Linearly interpolating a transformed point
487 /// gives `(1-a)·M₀p + a·M₁p`, which is `((1-a)·M₀ + a·M₁)·p` -- so
488 /// interpolating the matrix element by element is identical to
489 /// interpolating the moving point, for every point. It is not an
490 /// approximation of some better decomposition; it is what a
491 /// renderer blurring geometry already does. Long rotations look
492 /// wrong under it because they look wrong under blur, not because
493 /// this differs from the renderer.
494 ///
495 /// Each node on the chain is interpolated from **its own** samples
496 /// and the results composed, because each node is animated
497 /// separately. That is not the same as interpolating the composed
498 /// world matrices, and it is the accurate model of a hierarchy in
499 /// motion.
500 ///
501 /// # Outside the sampled range, the end sample is held
502 ///
503 /// Not extrapolated, and not refused -- because that is what
504 /// 3Delight does, and a backend that differed would render a
505 /// different picture. Rendered with samples at `t=0` and `t=1` and
506 /// the shutter open over `[-1, 2]`: there is **zero** alpha beyond
507 /// the two sampled positions, where extrapolation would sweep half
508 /// again as far each way, and a peak at each end 2.7 times the swept
509 /// middle, where a third of the shutter is held.
510 ///
511 /// An earlier version of this refused such a time, on the reasoning
512 /// that clamping "answers for a moment the caller never described".
513 /// The caller did describe it: they opened the shutter there.
514 ///
515 /// # Errors
516 ///
517 /// [`ResolveError::MissingSampleAtTime`] when `time` is not a
518 /// number, which names no sample and brackets no pair.
519 ///
520 /// Also [`ResolveError::MultipleParents`] or [`ResolveError::Cycle`]
521 /// from walking the chain.
522 pub fn world_transform_interpolated_at(
523 &self,
524 handle: &str,
525 time: f64,
526 ) -> Result<[f64; 16], ResolveError> {
527 let chain = self.transform_chain(handle)?;
528 self.interpolate_along(&chain, time)
529 }
530
531 /// Compose an already-walked path with each node interpolated at
532 /// `time`.
533 ///
534 /// The interpolating twin of [`Scene::compose_along`], and shared
535 /// the same way: `placements_at` had a verbatim copy of this fold,
536 /// which is the drift that copy was introduced to prevent. Nothing
537 /// constrained it -- reversing the multiplication and reversing the
538 /// path both left the suite green, because every fixture that
539 /// reached it used translations, which commute.
540 pub(super) fn interpolate_along(
541 &self,
542 path: &[String],
543 time: f64,
544 ) -> Result<[f64; 16], ResolveError> {
545 let resolved: Vec<(&str, Local)> = path
546 .iter()
547 .map(|node| (node.as_str(), self.local_resolved(node)))
548 .collect();
549 interpolate_resolved(&resolved, time)
550 }
551
552 /// Compose the transform chain applying to `handle` at `time`.
553 ///
554 /// A node with no motion samples is constant, so its static matrix
555 /// applies at every time. A node that *is* sampled contributes the
556 /// sample at exactly `time`, and having none there is an error
557 /// rather than an interpolation; see
558 /// [`ResolveError::MissingSampleAtTime`].
559 ///
560 /// A wholly static chain resolves at any time, and agrees with
561 /// [`Scene::world_transform`].
562 ///
563 /// # Errors
564 ///
565 /// Every variant of [`ResolveError`].
566 pub fn world_transform_at(
567 &self,
568 handle: &str,
569 time: f64,
570 ) -> Result<[f64; 16], ResolveError> {
571 let chain = self.transform_chain(handle)?;
572
573 chain.iter().try_fold(IDENTITY, |matrix, node| {
574 Ok(match self.local_transform_at(node, time)? {
575 Some(local) => mul(matrix, local),
576 None => matrix,
577 })
578 })
579 }
580
581 /// The world transform of `handle` at each of its
582 /// [`Scene::motion_times`].
583 ///
584 /// This is the shape a renderer wants for motion blur: the sample
585 /// times, and the composed matrix at each. Empty for a static chain.
586 ///
587 /// A chain whose nodes are sampled at *different* times resolves:
588 /// each node is interpolated from its own samples and the results
589 /// composed, and the answer agrees with
590 /// [`Scene::world_transform_interpolated_at`] at every time. This
591 /// paragraph said the opposite -- that such a chain was
592 /// `MissingSampleAtTime` -- for several commits after it stopped
593 /// being true.
594 ///
595 /// # Errors
596 ///
597 /// Whatever walking the chain refuses, and exactly what
598 /// [`Scene::world_transform_interpolated_at`] refuses for the same
599 /// scene: the two walk one chain and are held to the same error by
600 /// `the_two_interpolating_accessors_refuse_alike`.
601 /// `MissingSampleAtTime` cannot arise here -- the times come from
602 /// [`Scene::motion_times`], so every one of them has a sample.
603 pub fn world_transform_samples(
604 &self,
605 handle: &str,
606 ) -> Result<Vec<(f64, [f64; 16])>, ResolveError> {
607 // Resolve the chain **once**, then compose at each time. Asking
608 // `world_transform_interpolated_at` per time re-applied the
609 // typing rule and re-decoded every matrix on every node at
610 // every time, which is the T x N this row was `Open` for.
611 // `transform_chain`, as `world_transform_interpolated_at` and
612 // `motion_times` use: `chain` walks *through* an `instances`
613 // node, so the two accessors refused a prototype under a
614 // detached or shared instancer with different errors -- one
615 // saying `Detached`, its twin `Instanced`. A reviewer found it
616 // by mutating this line and watching nothing go red.
617 let chain = self.transform_chain(handle)?;
618 let resolved: Vec<(&str, Local)> = chain
619 .iter()
620 .map(|node| (node.as_str(), self.local_resolved(node)))
621 .collect();
622
623 self.motion_times_along(&chain)
624 .into_iter()
625 .map(|time| Ok((time, interpolate_resolved(&resolved, time)?)))
626 .collect()
627 }
628
629 /// Whether any motion sample on `handle` sets a transform.
630 ///
631 /// Read before composing, because [`Scene::world_transform`] reads
632 /// static attributes only and a motion-sampled node has none.
633 pub(super) fn has_motion_transform(&self, handle: &str) -> bool {
634 // The typing rule applies here too: a node whose samples are
635 // all unreadable, or whose last one is, has no motion -- and
636 // reporting motion for it made `world_transform` refuse a node
637 // the other accessors resolve to identity.
638 self.node(handle).is_some_and(|node| {
639 // No allocation: this runs per node per fold.
640 sampled_attr(node, TRANSFORMATION_MATRIX, |arg| {
641 matrix_of(arg).is_some()
642 })
643 .samples()
644 .next()
645 .is_some()
646 })
647 }
648
649 /// This node's own matrix, if it carries one.
650 ///
651 /// The node *type* is never consulted, matching classification: ɴsɪ
652 /// permits attributes the node type would not imply, and a
653 /// `transformationmatrix` on a non-transform node is composed like
654 /// any other. See `contracts/resolution.md`.
655 pub(super) fn local_transform(&self, handle: &str) -> Option<[f64; 16]> {
656 let node = self.node(handle)?;
657 matrix_of(node.attribute(TRANSFORMATION_MATRIX)?)
658 }
659
660 /// This node's matrix at `time`, interpolated.
661 ///
662 /// Linear between the bracketing samples, and held at the nearest
663 /// sample outside the sampled range -- which is what 3Delight does;
664 /// see [`Scene::world_transform_interpolated_at`].
665 /// One chain node's transform, resolved once: the typing rule
666 /// applied and the matrices decoded.
667 ///
668 /// Split from answering *at a time* because a caller asking at
669 /// many times paid for this at every one of them --
670 /// `world_transform_samples` asks at T times over N nodes, and
671 /// re-resolving made that T x N over the samples.
672 pub(super) fn local_resolved(&self, handle: &str) -> Local {
673 let Some(node) = self.node(handle) else {
674 return Local::Constant(None);
675 };
676
677 // A wrong-typed *last* sample unsets the attribute, so the
678 // static value applies -- rendered, 3Delight draws the node at
679 // identity rather than at the discarded earlier sample.
680 let found = sampled_attr(node, TRANSFORMATION_MATRIX, |arg| {
681 matrix_of(arg).is_some()
682 });
683 if matches!(found, Sampled::No | Sampled::Unset) {
684 return Local::Constant(self.local_transform(handle));
685 }
686
687 Local::Sampled(
688 found
689 .samples()
690 .filter_map(|(t, arg)| matrix_of(arg).map(|m| (t, m)))
691 .collect(),
692 )
693 }
694
695 pub(super) fn local_transform_at(
696 &self,
697 handle: &str,
698 time: f64,
699 ) -> Result<Option<[f64; 16]>, ResolveError> {
700 // `-0.0` names the sample at `0.0` here as well. This scan is a
701 // third statement of the exact-hit lookup -- it cannot use
702 // `locate_sample`, which clamps and interpolates where this must
703 // refuse -- so folding in one place left the two accessors
704 // disagreeing: `world_transform_interpolated_at` answered while
705 // `world_transform_at` named a sample the recorder had folded.
706 let time = time + 0.0;
707 let Some(node) = self.node(handle) else {
708 return Ok(None);
709 };
710
711 // Same typing rule as the interpolating twin: a wrong-typed
712 // last sample unsets the attribute at *every* time, rather than
713 // leaving this to error at one time and answer the discarded
714 // sample at another. That inconsistency had one scene giving
715 // three different answers across the three accessors.
716 let found = sampled_attr(node, TRANSFORMATION_MATRIX, |arg| {
717 matrix_of(arg).is_some()
718 });
719 if matches!(found, Sampled::No | Sampled::Unset) {
720 return Ok(self.local_transform(handle));
721 }
722
723 match found
724 .clone()
725 .samples()
726 .find(|(t, _)| t.total_cmp(&time) == Ordering::Equal)
727 {
728 Some((_, arg)) => Ok(matrix_of(arg)),
729 None => Err(ResolveError::MissingSampleAtTime {
730 handle: handle.to_string(),
731 time,
732 available: found.samples().map(|(t, _)| t).collect(),
733 }),
734 }
735 }
736}