nsi_intermediate/resolve/attributes.rs
1//! What applies to a geometry: the `attributes` nodes gathered along
2//! its path, and ɴsɪ's precedence between them.
3
4use super::*;
5use core::iter;
6
7/// Read an `ATTR.priority`.
8///
9/// ɴsɪ declares it `int`, and 3Delight reads nothing else -- **not even
10/// `int64`**. Rendered: `visibility 1` with `"visibility.priority"` as
11/// an `int64` 10 loses to a nearer `visibility 0`, and loses to a rival
12/// `int` priority of 5. The `int64` is echoed back by `renderdl -cat`,
13/// so it is parsed and then ignored. `int64` *is* accepted for the
14/// `visibility` value itself, so the rejection is specific to the
15/// priority.
16///
17/// The **count** is as strict as the type: exactly one, which is what
18/// [`OwnedArgument::as_i32`] means. Rendered: the same scene with the
19/// priority written `"int" 2 [ 10 10 ]` -- or `"int[2]" 1 [ 10 10 ]`,
20/// which is the same argument spelled the other way -- leaves the
21/// geometry hidden, so 3Delight ranked nothing on it, while the
22/// one-value control shows it. Taking the first of several would rank
23/// a node the renderer does not, which is the same mistake as reading
24/// the `int64`.
25pub(super) fn priority_value(arg: &OwnedArgument) -> Option<i32> {
26 arg.as_i32()
27}
28
29impl Scene {
30 /// Gather the `attributes` nodes gathered along a geometry's path,
31 /// and the surface shader they resolve to.
32 ///
33 /// ɴsɪ routes material through an intermediate node --
34 /// `shader -> attributes -> geometry` -- that no target renderer
35 /// has. Mitsuba wants a `bsdf` on the shape; MoonRay wants a `Layer`
36 /// entry. Both need the same walk, so it happens here once.
37 ///
38 /// # Gathering
39 ///
40 /// ɴsɪ gathers attribute values "along the path starting from the
41 /// geometric primitive, through all the transform nodes it is
42 /// connected to, until the scene root is reached", and *every*
43 /// `attributes` node on that path is considered: "one attributes
44 /// node can set object visibility and another can set the surface
45 /// shader". So this returns all of them, nearest the geometry
46 /// first -- ɴsɪ selects "the definition that is the closest to the
47 /// geometric primitive" -- and a backend takes the first that
48 /// defines the attribute it wants.
49 ///
50 /// **That is not the whole rule.** ɴsɪ ranks a definition by
51 /// `ATTR.priority`, set on an `attributes` node beside the attribute
52 /// it applies to; and at equal priority a more specific
53 /// `visibility.<ray>` beats `visibility`. This method applies
54 /// neither -- it orders nodes, not the attributes on them. Ask
55 /// [`Scene::attribute_value`] for one attribute's value and both
56 /// rules are applied.
57 ///
58 /// Returns `Ok(None)` for geometry with nothing bound anywhere on
59 /// its path.
60 ///
61 /// # Errors
62 ///
63 /// [`ResolveError::MultipleParents`], [`ResolveError::Cycle`] or
64 /// [`ResolveError::Detached`], from walking the path. A
65 /// motion-sampled transform does not affect which attributes bind,
66 /// so it is not an error here.
67 pub fn geometry_binding(
68 &self,
69 geometry: &str,
70 ) -> Result<Option<Binding>, ResolveError> {
71 let gathered = self.gathered_attributes(geometry)?;
72
73 if gathered.is_empty() {
74 Ok(None)
75 } else {
76 // A shader connection carries its own priority, "used in
77 // the same way as for regular attributes".
78 let shader = |kind: &EdgeKind| self.shader_on(&gathered, kind);
79
80 Ok(Some(Binding {
81 surface_shader: shader(&EdgeKind::SurfaceShader),
82 displacement_shader: shader(&EdgeKind::DisplacementShader),
83 volume_shader: shader(&EdgeKind::VolumeShader),
84 attributes: gathered
85 .iter()
86 .map(|(_, _, edge)| edge.from().to_string())
87 .collect(),
88 }))
89 }
90 }
91
92 /// The value of one attribute, gathered along a geometry's path by
93 /// ɴsɪ's full precedence rule.
94 ///
95 /// [`Binding::attributes`] hands back the `attributes` nodes and
96 /// lets a backend take the first that defines what it wants. That is
97 /// right only while no node sets `ATTR.priority` and the attribute
98 /// is not a visibility one. This applies both rules and returns the
99 /// answer itself.
100 ///
101 /// # Scope
102 ///
103 /// This resolves `attributes` nodes reached through
104 /// `geometryattributes`. ɴsɪ has a *second* container with a
105 /// *different* rule: a `shaderattributes` node is gathered along the
106 /// same path, but "priority is given to nodes attached closest to
107 /// the geometric primitive, with the highest priority given to
108 /// attributes set directly on the geometric primitive", with no
109 /// `ATTR.priority` in it at all. Ask
110 /// [`Scene::shader_attribute_value`] for those; this one returns
111 /// `None` for them.
112 ///
113 /// # Precedence
114 ///
115 /// ɴsɪ: "When an attribute is defined multiple times along this
116 /// path, the definition with the highest priority is selected. In
117 /// case of conflicting priorities, the definition that is the
118 /// closest to the geometric primitive [...] is selected." A
119 /// definition's priority is the `ATTR.priority` int sitting beside
120 /// it on the same `attributes` node, `0` when absent.
121 ///
122 /// For a `visibility.<ray>` query the default `visibility` is a
123 /// candidate too: "When visibility is set both per ray type and with
124 /// this default visibility, the attribute with the highest priority
125 /// is used. If their priority is the same, the more specific
126 /// attribute (i.e. per ray type) is used."
127 ///
128 /// Candidates therefore rank by priority, then specificity, then the
129 /// [`Binding::attributes`] order.
130 ///
131 /// # Assumptions
132 ///
133 /// Two orderings the specification does not settle. Both are
134 /// recorded in `contracts/resolution.md` rather than left implicit:
135 ///
136 /// - Specificity is compared *before* proximity, so a distant
137 /// `visibility.camera` beats a nearer plain `visibility` at equal
138 /// priority. ɴsɪ gives the specificity rule without saying whether
139 /// it outranks proximity. Confirmed against 3Delight.
140 /// - A priority that is not an `int` is ignored, leaving `0`. That
141 /// includes `int64`, which 3Delight also ignores here.
142 ///
143 /// # A priority with no attribute beside it
144 ///
145 /// A node that sets `ATTR.priority` but **not** `ATTR` is a
146 /// definition too -- of `ATTR` at its ɴsɪ default -- and it ranks on
147 /// that priority like any other. Rendered: an `attributes` node
148 /// carrying only `visibility.priority` makes the geometry visible
149 /// over a farther `visibility 0`, at priority `10` and at `0`
150 /// alike; and one two levels up at priority `10` beats a
151 /// `visibility 0` on the node attached to the primitive itself, so
152 /// it is not merely winning on proximity. A node with no attributes
153 /// at all is not a definition, and neither is one whose priority is
154 /// an `int64`, which 3Delight cannot read.
155 ///
156 /// # Reading the value is not [`OwnedArgument::as_i32`]
157 ///
158 /// 3Delight is far looser about an attribute's **value** than
159 /// about its priority. Rendered, on `visibility`: `float 0.4` is
160 /// visible and `float 0` is hidden, so a float is read and
161 /// non-zero is true; `int64 0` hides; `int 2 [ 0 0 ]` hides, where
162 /// the same shape as a *priority* is ignored outright; and a
163 /// `string` reads as **true**.
164 ///
165 /// A wrong-typed value is still a *definition*: rendered, a
166 /// `string` on the nearest node beats a `visibility 0` two levels
167 /// up and the object is visible, so it wins its ranking rather
168 /// than falling through to the next candidate. The trap therefore
169 /// has two jaws. A backend that reaches for [`OwnedArgument::as_i32`]
170 /// here gets `None` for the numeric three and draws an object the
171 /// renderer hides; one that reads that `None` as "not defined" and
172 /// looks further along the chain draws hidden where the renderer
173 /// draws visible. This crate hands back the argument rather than a
174 /// decoded flag precisely because the rule is the renderer's, and
175 /// it is not the rule beside it.
176 ///
177 /// Such a winner comes back with [`AttributeValue::arg`] `None`:
178 /// this crate names the attribute and leaves ɴsɪ's default for it to
179 /// the backend, which is the one thing it cannot supply.
180 ///
181 /// # Errors
182 ///
183 /// As [`Scene::geometry_binding`]: walking the path can fail.
184 pub fn attribute_value(
185 &self,
186 geometry: &str,
187 name: &str,
188 ) -> Result<Option<AttributeValue<'_>>, ResolveError> {
189 // As above: the geometry form is the path form over its chain.
190 let chain = self.chain(geometry)?;
191 Ok(self.attribute_value_along(&chain, name))
192 }
193
194 /// The same, along one [`Placement`]'s path.
195 ///
196 /// A geometry with more than one parent has no single path, so
197 /// [`Scene::attribute_value`] refuses it -- and then the rules it
198 /// applies could not be applied to an instanced object at all.
199 /// This takes the path from a placement instead.
200 ///
201 /// Infallible: the path has already been walked, so there is
202 /// nothing left to refuse.
203 pub fn attribute_value_along(
204 &self,
205 path: &[String],
206 name: &str,
207 ) -> Option<AttributeValue<'_>> {
208 let gathered = self.gathered_along(path, &EdgeKind::AttributeBinding);
209 self.resolve_attribute(&gathered, name)
210 }
211
212 /// The same, for the `shaderattributes` container.
213 ///
214 /// Proximity only, as [`Scene::shader_attribute_value`] explains,
215 /// and the path's first node -- the geometry -- still outranks every
216 /// container. This is the body
217 /// [`Scene::shader_attribute_value`] runs over a geometry's own
218 /// chain, not a second copy of the rule.
219 pub fn shader_attribute_value_along(
220 &self,
221 path: &[String],
222 name: &str,
223 ) -> Option<AttributeValue<'_>> {
224 if let Some(geometry) = path.first()
225 && let Some((handle, node)) = self.node_entry(geometry)
226 && let Some(arg) = node.effective(name)
227 {
228 return Some(AttributeValue {
229 node: handle,
230 name: &arg.name,
231 arg: Some(arg),
232 priority: 0,
233 });
234 }
235
236 for (_, _, edge) in
237 self.gathered_along(path, &EdgeKind::ShaderAttributes)
238 {
239 let Some(node) = self.node(edge.from()) else {
240 continue;
241 };
242 if let Some(arg) = node.effective(name) {
243 return Some(AttributeValue {
244 node: edge.from(),
245 name: &arg.name,
246 arg: Some(arg),
247 priority: 0,
248 });
249 }
250 }
251 None
252 }
253
254 /// ɴsɪ's attribute precedence over an already-gathered list.
255 pub(super) fn resolve_attribute<'a>(
256 &'a self,
257 gathered: &[(usize, usize, &'a Edge)],
258 name: &str,
259 ) -> Option<AttributeValue<'a>> {
260 // A per-ray visibility query also matches the default.
261 let fallback = name
262 .strip_prefix("visibility.")
263 .filter(|ray| RAY_TYPES.contains(ray))
264 .map(|_| "visibility");
265
266 let mut candidates = Vec::new();
267 for (rank, (_, _, edge)) in gathered.iter().enumerate() {
268 let Some(node) = self.node(edge.from()) else {
269 continue;
270 };
271
272 let keys = core::iter::once((1u8, name))
273 .chain(fallback.map(|name| (0u8, name)));
274
275 for (specificity, key) in keys {
276 let beside = node.effective(&format!("{key}.priority"));
277 let priority = beside.and_then(priority_value);
278
279 // A lone `ATTR.priority` is a definition of `ATTR` at
280 // its ɴsɪ default, so it is a candidate with no value.
281 // Its name is the priority argument's own, less the
282 // suffix: a borrow of the scene, where `key` is only
283 // borrowed from the caller. An unreadable priority is
284 // not a definition -- 3Delight ignores that node.
285 let (attribute, arg) = match (node.effective(key), beside) {
286 (Some(arg), _) => (arg.name.as_str(), Some(arg)),
287 (None, Some(beside)) if priority.is_some() => (
288 &beside.name[..beside.name.len() - ".priority".len()],
289 None,
290 ),
291 (None, _) => continue,
292 };
293 let priority = priority.unwrap_or(0);
294
295 candidates.push((
296 priority,
297 specificity,
298 rank,
299 AttributeValue {
300 node: edge.from(),
301 name: attribute,
302 arg,
303 priority,
304 },
305 ));
306 }
307 }
308
309 // Highest priority, then the more specific attribute, then the
310 // gathered order.
311 candidates.sort_by(|a, b| {
312 b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2))
313 });
314
315 candidates.into_iter().next().map(|(_, _, _, value)| value)
316 }
317
318 /// The sources of *shader* attributes for a geometry, in ɴsɪ's
319 /// precedence order.
320 ///
321 /// **The first entry is the geometry itself**, which is a source in
322 /// its own right and outranks every container: ɴsɪ gives "the
323 /// highest priority ... to attributes set directly on the geometric
324 /// primitive". It is listed unconditionally, so a caller walking
325 /// this in order and taking the first handle that defines what it
326 /// wants gets the same answer as
327 /// [`Scene::shader_attribute_value`]. Every later entry is an
328 /// `attributes` node.
329 ///
330 /// After it come ɴsɪ's second attribute container, nearest the
331 /// geometry first. The same `attributes` node type reaches it,
332 /// through the `shaderattributes` connection rather than
333 /// `geometryattributes`, gathered "along the path starting from the
334 /// geometric primitive, through all the transform nodes it is
335 /// connected to, until the scene root is reached".
336 ///
337 /// # Errors
338 ///
339 /// As [`Scene::geometry_binding`]: walking the path can fail.
340 pub fn shader_attributes(
341 &self,
342 geometry: &str,
343 ) -> Result<Vec<String>, ResolveError> {
344 let own = self
345 .node_entry(geometry)
346 .map(|(handle, _)| handle.to_string());
347 Ok(own
348 .into_iter()
349 .chain(
350 self.gathered_containers(
351 geometry,
352 &EdgeKind::ShaderAttributes,
353 )?
354 .into_iter()
355 .map(|(_, _, edge)| edge.from().to_string()),
356 )
357 .collect())
358 }
359
360 /// The value of one shader attribute, gathered along a geometry's
361 /// path.
362 ///
363 /// # Precedence
364 ///
365 /// **Not** the rule [`Scene::attribute_value`] applies. ɴsɪ gives
366 /// this container its own, and it is simpler: "Priority is given to
367 /// nodes attached closest to the geometric primitive, with the
368 /// highest priority given to attributes set directly on the
369 /// geometric primitive." There is no `ATTR.priority` here and no
370 /// per-ray fallback -- nearest wins, then connection order. Reusing
371 /// the `geometryattributes` rule would invent a priority the
372 /// specification does not give this node.
373 ///
374 /// [`AttributeValue::priority`] is therefore always `0`.
375 ///
376 /// ɴsɪ adds that attributes on such a node "may only have a single
377 /// value"; this does not enforce that, and returns what was
378 /// recorded.
379 ///
380 /// # Scope
381 ///
382 /// ɴsɪ allows these on "geometric primitives, transform nodes or
383 /// **set nodes**". All three are walked; see `gathered_containers`
384 /// for where a set ranks.
385 ///
386 /// # Errors
387 ///
388 /// As [`Scene::geometry_binding`]: walking the path can fail.
389 pub fn shader_attribute_value(
390 &self,
391 geometry: &str,
392 name: &str,
393 ) -> Result<Option<AttributeValue<'_>>, ResolveError> {
394 // The path form *is* this rule; asking about a geometry is
395 // asking along its own chain. Kept as one body because a copy
396 // of a resolution rule has drifted three times in this crate --
397 // `compose_along` from `world_transform`'s fold, `placements_at`
398 // from the interpolating one, and these two were next.
399 let chain = self.chain(geometry)?;
400 Ok(self.shader_attribute_value_along(&chain, name))
401 }
402
403 /// Every `attributes` node on a geometry's path, in ɴsɪ's
404 /// precedence order.
405 ///
406 /// `(depth, connection order, edge)`, nearest the geometry first.
407 /// [`Scene::geometry_binding`] and [`Scene::attribute_value`] share
408 /// it so the two cannot disagree about which node outranks which.
409 ///
410 /// # The `priority` on a `geometryattributes` connection is ignored
411 ///
412 /// ɴsɪ documents `connect`'s `priority` as "when connecting
413 /// attributes nodes, indicates in which order the nodes should be
414 /// considered when evaluating the value of an attribute", and this
415 /// function used to sort by it. **3Delight does not implement
416 /// that.** Rendering `mesh -> xf -> .root`, `visibility 0` on the
417 /// geometry's own `attributes` node and `visibility 1` on a node
418 /// connected to the transform with `"priority" 10`, 3Delight leaves
419 /// the object invisible: proximity wins and the connection priority
420 /// does nothing. Moving the same `10` onto the far node as
421 /// `visibility.priority` *does* flip it. Six probe scenes agree.
422 ///
423 /// The prose the renderer follows is the other sentence:
424 /// "Connections **(for shaders, essentially)** can also be assigned
425 /// priorities". A priority on a *shader* connection is honoured, and
426 /// `shader_on` still applies it; one on the `geometryattributes`
427 /// connection is not.
428 pub(super) fn gathered_attributes(
429 &self,
430 geometry: &str,
431 ) -> Result<Vec<(usize, usize, &Edge)>, ResolveError> {
432 self.gathered_containers(geometry, &EdgeKind::AttributeBinding)
433 }
434
435 /// The same walk for any container class, nearest the geometry
436 /// first.
437 ///
438 /// # Where a `set` ranks
439 ///
440 /// ɴsɪ describes gathering as running "from the geometric
441 /// primitive, through all the transform nodes it is connected to,
442 /// until the scene root is reached", and names `set` nodes only as
443 /// a place a `shaderattributes` node may hang. 3Delight honours a
444 /// container on a set for **both** classes, and the rule is per node
445 /// on that path rather than for the geometry alone: each node
446 /// contributes its own containers, then those on the sets it is
447 /// *directly* a member of. Rendered, each direction mirrored so no
448 /// answer is an artefact of which value happened to be `0`:
449 ///
450 /// - a node's own container beats one on a set it belongs to;
451 /// - a set of the geometry beats a set of its transform;
452 /// - a set of a transform beats that transform's parent, and beats
453 /// a container on `.root`;
454 /// - with two memberships the first connection wins;
455 /// - a set nested inside another set contributes **nothing** --
456 /// only direct membership counts;
457 /// - a set holding two nodes of the chain is one source, at its
458 /// nearest occurrence.
459 ///
460 /// `ATTR.priority` still outranks all of it, as everywhere else.
461 pub(super) fn gathered_containers(
462 &self,
463 geometry: &str,
464 kind: &EdgeKind,
465 ) -> Result<Vec<(usize, usize, &Edge)>, ResolveError> {
466 let chain = self.chain(geometry)?;
467 Ok(self.gathered_along(&chain, kind))
468 }
469
470 /// The same, along a path already walked.
471 ///
472 /// Split out because a geometry with more than one parent has more
473 /// than one path, and the containers on each are **different** --
474 /// rendered, two parents carrying `visibility 1` and `visibility 0`
475 /// draw one copy, not two or none.
476 pub(super) fn gathered_along(
477 &self,
478 chain: &[String],
479 kind: &EdgeKind,
480 ) -> Vec<(usize, usize, &Edge)> {
481 // The geometry, then the sets it belongs to directly, then the
482 // transforms above it. With no set memberships this is `chain`
483 // and the walk is unchanged.
484 // One set can hold several nodes on the chain. It is a single
485 // source at its nearest occurrence -- rendered, a set holding
486 // both the mesh and its transform ranks where the mesh does --
487 // so the `filter` keeps the first sighting and drops the rest,
488 // in the same pass that gathers them.
489 let mut seen = HashSet::new();
490 let sources: Vec<&str> = chain
491 .iter()
492 .flat_map(|node| {
493 iter::once(node.as_str()).chain(
494 self.edges_from(node.as_str())
495 .filter(|edge| edge.kind == EdgeKind::SetMember)
496 .map(|edge| edge.to()),
497 )
498 })
499 .filter(|handle| seen.insert(*handle))
500 .collect();
501
502 let mut gathered: Vec<(usize, usize, &Edge)> = sources
503 .into_iter()
504 .enumerate()
505 .flat_map(|(depth, node)| {
506 self.edges_to_attribute(node, kind.to_attribute())
507 // A shader-network edge's `to_attribute` is its *port*
508 // name, so it shares this bucket with the named
509 // class. Without the filter a port called
510 // `geometryattributes` resolved as a binding.
511 .filter(move |edge| edge.kind == *kind)
512 .enumerate()
513 .map(move |(order, edge)| (depth, order, edge))
514 })
515 .collect::<Vec<_>>();
516
517 // Nearest the geometry, then connection order. `chain` already
518 // runs geometry-first, so this states the invariant rather than
519 // establishing it.
520 gathered.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
521
522 gathered
523 }
524
525 /// The shader of one kind reached from any gathered `attributes`
526 /// node, by ɴsɪ's precedence.
527 ///
528 /// Ranked by the *connection's* priority first -- ɴsɪ calls that
529 /// "useful for overriding a shader from higher in the scene graph"
530 /// -- then by the gathered order, so this agrees with
531 /// [`Binding::attributes`] rather than disagreeing with it.
532 pub(super) fn shader_on(
533 &self,
534 gathered: &[(usize, usize, &Edge)],
535 kind: &EdgeKind,
536 ) -> Option<String> {
537 gathered
538 .iter()
539 .enumerate()
540 .flat_map(|(rank, (_, _, edge))| {
541 self.edges_to_attribute(edge.from(), kind.to_attribute())
542 .filter(move |shader| shader.kind == *kind)
543 .map(move |shader| (shader.priority(), rank, shader))
544 })
545 // Highest priority, then earliest in the gathered order.
546 .min_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)))
547 .map(|(_, _, shader)| shader.from().to_string())
548 }
549}