nsi-intermediate 0.1.0

Renderer-agnostic intermediate representation for the Nodal Scene Interface – ɴsɪ.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Graph rewrites: turning ɴsɪ's scene-graph semantics into the flat
//! facts a renderer wants.
//!
//! Both target renderers need this and neither should re-derive it.
//! Mitsuba has no transform tree, only a `to_world` per shape; MoonRay
//! resolves geometry to world space too. So the chain has to be
//! composed here, once.

use crate::{Edge, EdgeKind, HashSet, Node, OwnedArgument, OwnedData, Scene};
use core::{cmp::Ordering, fmt};

mod attributes;
mod chain;
mod instances;
mod mesh;
mod motion;
mod outputs;
mod primvar;

// The types are here; the walks are in the five modules above. Split
// at 2530 lines against a stated 300-500, along the seams the code
// already had: a chain walk, a time rule, an attribute rule, the
// instancer, and the output chain. `mod.rs` keeps what all five need
// so none of them has to reach sideways.
pub use chain::WorldTransforms;
pub use instances::Instances;
pub use mesh::{Face, Faces};
pub use motion::Sampled;
pub use primvar::{Interpolation, PrimitiveVariable};

/// A 4x4 identity, row-major.
#[rustfmt::skip]
pub const IDENTITY: [f64; 16] = [
    1.0, 0.0, 0.0, 0.0,
    0.0, 1.0, 0.0, 0.0,
    0.0, 0.0, 1.0, 0.0,
    0.0, 0.0, 0.0, 1.0,
];

/// The ɴsɪ attribute holding a transform node's matrix.
const TRANSFORMATION_MATRIX: &str = "transformationmatrix";

/// An `instances` node's per-instance matrices.
const MATRICES: &str = "transformationmatrices";

/// Which prototype each instance draws.
const MODEL_INDICES: &str = "modelindices";

/// `mesh` topology, which only means something as a pair.
const FACE_VERTEX_COUNTS: &str = "nvertices";
const HOLE_COUNTS: &str = "nholes";

/// Positions, and ɴsɪ's indirect-lookup suffix.
const POSITIONS: &str = "P";
const INDICES: &str = ".indices";

// `outputlayer` attribute names, spelled once. The defaults they fall
// back to live with `Scene::output_layer`, next to the specification
// section that states them.
const VARIABLE_NAME: &str = "variablename";
const VARIABLE_SOURCE: &str = "variablesource";
const LAYER_NAME: &str = "layername";
const LAYER_TYPE: &str = "layertype";
const SCALAR_FORMAT: &str = "scalarformat";
const WITH_ALPHA: &str = "withalpha";
const DITHERING: &str = "dithering";
const FILTER: &str = "filter";
const FILTER_WIDTH: &str = "filterwidth";
const COLOR_PROFILE: &str = "colorprofile";
const SORT_KEY: &str = "sortkey";

/// The instances an `instances` node skips.
const DISABLED: &str = "disabledinstances";

/// Why a scene could not be resolved into flat facts.
///
/// Every variant is a scene ɴsɪ permits but this crate refuses to guess
/// about. Returning a matrix or a binding anyway would be the silent
/// failure the crate exists to prevent: it renders, with the wrong
/// answer.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ResolveError {
    /// A node is connected to more than one parent.
    ///
    /// Usually through `objects`; a prototype connected to two
    /// `instances` nodes is the same problem.
    ///
    /// That is ɴsɪ's lightweight instancing: the node appears once per
    /// path, each with its own world transform. A single matrix cannot
    /// describe it, so resolving one is refused rather than silently
    /// answering for whichever parent was connected first.
    MultipleParents {
        /// The node with more than one parent.
        handle: String,
        /// Every parent, in connection order.
        parents: Vec<String>,
    },
    /// A node carries motion-sampled placement data where a single
    /// answer was asked for.
    ///
    /// Either a `transformationmatrix` on a node in the chain, or an
    /// `instances` node's `transformationmatrices`, `modelindices` or
    /// `disabledinstances`. Answering with the static value would hand
    /// a motion-blurred scene back its unblurred pose, and answering
    /// with an empty list -- which the instancer path used to do --
    /// reads as "nothing to draw".
    ///
    /// Ask at a time instead:
    /// [`Scene::world_transform_interpolated_at`],
    /// [`Scene::placements_at`] or
    /// [`Scene::instance_transforms_at`].
    MotionSampledTransform {
        /// The node whose transform is motion-sampled.
        handle: String,
    },
    /// The transform chain revisits a node. ɴsɪ does not forbid a cycle;
    /// no correct answer exists for one.
    Cycle {
        /// The node the walk arrived at twice.
        handle: String,
    },
    /// The node is not connected to `.root`, directly or through
    /// transforms.
    ///
    /// ɴsɪ: "A node can exist in an nsi context without being connected
    /// to the root node but in that case it won't affect the render in
    /// any way." It has no world transform and no gathered attributes,
    /// and answering identity would put unrendered geometry at the
    /// origin.
    Detached {
        /// The node that does not reach `.root`.
        handle: String,
    },
    /// No node with that handle exists.
    ///
    /// Asking about an attribute of a node that was never created is a
    /// caller mistake, and answering "not sampled" would read as a fact
    /// about the scene rather than about the question.
    UnknownHandle {
        /// The handle that names nothing.
        handle: String,
    },
    /// The node is an instancing prototype, so it has no single world
    /// transform.
    ///
    /// A prototype reaches the scene through an `instances` node, and
    /// ɴsɪ gives that node "a transformation matrix for each instance".
    /// Answering with the instancer's own transform would put every
    /// instance in the same, wrong place.
    Instanced {
        /// The `instances` node the prototype is connected to.
        instancer: String,
    },
    /// An `instances` node's `transformationmatrices` is not a whole
    /// number of 4x4 matrices.
    MalformedInstanceMatrices {
        /// The `instances` node.
        instances: String,
        /// How many values it carries.
        values: usize,
    },
    /// Two prototype connections share one `index`.
    ///
    /// ɴsɪ: connections "must have an integer index attribute if there
    /// are several, so the models effectively form an ordered list" --
    /// which a duplicate does not.
    DuplicateModelIndex {
        /// The `instances` node.
        instances: String,
        /// The index used twice.
        index: i32,
    },
    /// A `modelindices` entry matches no prototype connection's
    /// `index`.
    UnknownModelIndex {
        /// The `instances` node.
        instances: String,
        /// The index that matches nothing.
        model: i32,
    },
    /// [`Scene::relative_transform`] was given a node that is not on the
    /// chain.
    NotAnAncestor {
        /// The node whose chain was walked.
        handle: String,
        /// The node that is not on it.
        ancestor: String,
    },
    /// A node in the chain is motion-sampled, but has no sample at the
    /// requested time.
    ///
    /// From the **exact-hit** accessors only -- [`Scene::world_transform_at`],
    /// [`Scene::world_transform_samples`] and
    /// [`Scene::instance_transforms`] answer where a sample exists and
    /// refuse elsewhere, which is the right answer to "what did the
    /// caller record".
    ///
    /// For "where is it mid-shutter", ask
    /// [`Scene::world_transform_interpolated_at`],
    /// [`Scene::placements_at`] or
    /// [`Scene::instance_transforms_at`]. Those interpolate
    /// element-wise, which is the renderer's own model rather than a
    /// guess -- 3Delight's rotation blur fits component-wise far better
    /// than slerp -- and they hold the end sample outside the sampled
    /// range, as it does.
    ///
    /// The interpolating accessors still return this for a time that
    /// names no sample at all, such as a NaN. An earlier version of
    /// this said the crate never interpolates and that the
    /// decomposition was the backend's; that stopped being true when
    /// those accessors were added.
    MissingSampleAtTime {
        /// The node with no sample at that time.
        handle: String,
        /// The time that was asked for.
        time: f64,
        /// The times that node does have, ascending.
        available: Vec<f64>,
    },
    /// A `mesh` has no `nvertices`, which ɴsɪ requires.
    MissingFaceCounts {
        /// The mesh.
        handle: String,
    },
    /// A `<name>.indices` is not one entry per face-vertex, or points
    /// outside the values it indexes.
    ///
    /// ɴsɪ says the indices say "which values of the other parameter to
    /// use" and nothing about how many values there are, so the
    /// indices are what must match the primitive.
    MalformedIndices {
        /// The primitive.
        handle: String,
        /// The attribute the indices belong to.
        attribute: String,
        /// How many indices there are.
        indices: usize,
        /// How many the primitive's face-vertices need.
        face_vertices: usize,
        /// How many values there are to index.
        values: usize,
    },
    /// A primitive variable's value count matches none of the four
    /// interpolations.
    ///
    /// Constant is one value, uniform is one per face, vertex is one
    /// per vertex and face-varying is one per face-vertex. A count
    /// that is none of those has no meaning ɴsɪ defines, and guessing
    /// one renders -- plausibly, and wrongly, which is how a wrong
    /// normal survives review.
    AmbiguousInterpolation {
        /// The primitive.
        handle: String,
        /// The attribute.
        attribute: String,
        /// How many values it carries.
        values: usize,
        /// How many faces the primitive has.
        faces: usize,
        /// How many vertices.
        vertices: usize,
        /// How many face-vertices.
        face_vertices: usize,
    },
    /// `nholes` and `nvertices` disagree.
    ///
    /// ɴsɪ: with `nholes` set, the face count is the number of `nholes`
    /// values, and each face takes `nholes + 1` values from
    /// `nvertices` -- the outer perimeter and then one per hole. A
    /// count that does not add up leaves the faces undefined, and a
    /// backend that reads `nvertices` as one-count-per-face draws a
    /// different mesh without reporting anything.
    MalformedFaceCounts {
        /// The mesh.
        handle: String,
        /// How many `nvertices` values the holes ask for.
        expected: usize,
        /// How many there are.
        found: usize,
    },
}

impl fmt::Display for ResolveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MultipleParents { handle, parents } => write!(
                f,
                "ɴsɪ node {handle:?} has {} parents ({}); that is \
                 instancing, which has one world transform per path, not \
                 one overall",
                parents.len(),
                parents.join(", ")
            ),
            Self::MotionSampledTransform { handle } => write!(
                f,
                "ɴsɪ node {handle:?} carries motion-sampled placement \
                 data; the static value would be the wrong answer, so \
                 ask at a time instead"
            ),
            Self::Cycle { handle } => write!(
                f,
                "ɴsɪ transform chain revisits node {handle:?}; a cyclic \
                 scene has no world transform"
            ),
            Self::UnknownHandle { handle } => {
                write!(f, "no ɴsɪ node is named {handle:?}")
            }
            Self::Detached { handle } => write!(
                f,
                "ɴsɪ node {handle:?} is not connected to {root:?}, so it \
                 is not in the scene and has no world transform",
                root = crate::ROOT
            ),
            Self::Instanced { instancer } => write!(
                f,
                "ɴsɪ node is an instancing prototype of {instancer:?}, \
                 which carries one transform per instance; there is no \
                 single world transform for it"
            ),
            Self::MalformedInstanceMatrices { instances, values } => {
                write!(
                    f,
                    "ɴsɪ node {instances:?} has {values} values in \
                     transformationmatrices, which is not a whole number \
                     of 4x4 matrices"
                )
            }
            Self::DuplicateModelIndex { instances, index } => write!(
                f,
                "ɴsɪ node {instances:?} has two sourcemodels connections \
                 at index {index}, so its models are not an ordered list"
            ),
            Self::UnknownModelIndex { instances, model } => write!(
                f,
                "ɴsɪ node {instances:?} selects model index {model}, which \
                 matches no sourcemodels connection"
            ),
            Self::NotAnAncestor { handle, ancestor } => write!(
                f,
                "ɴsɪ node {ancestor:?} is not on {handle:?}'s chain, so \
                 there is no transform of one relative to the other"
            ),
            Self::MissingSampleAtTime {
                handle,
                time,
                available,
            } => write!(
                f,
                "ɴsɪ node {handle:?} has no transform sample at time \
                 {time}; it has {available:?}, and this crate does not \
                 interpolate between them"
            ),
            Self::MalformedIndices {
                handle,
                attribute,
                indices,
                face_vertices,
                values,
            } => write!(
                f,
                "ɴsɪ primitive {handle:?} has {indices} {attribute:?} \
                 indices for {face_vertices} face-vertices into {values} \
                 values; indices are read per face-vertex"
            ),
            Self::AmbiguousInterpolation {
                handle,
                attribute,
                values,
                faces,
                vertices,
                face_vertices,
            } => write!(
                f,
                "ɴsɪ primitive {handle:?} has {values} {attribute:?} values, \
                 which is neither constant (1), per face ({faces}), per \
                 vertex ({vertices}) nor per face-vertex ({face_vertices})"
            ),
            Self::MissingFaceCounts { handle } => write!(
                f,
                "ɴsɪ mesh {handle:?} sets no \"nvertices\", which ɴsɪ \
                 requires; its faces are undefined"
            ),
            Self::MalformedFaceCounts {
                handle,
                expected,
                found,
            } => write!(
                f,
                "ɴsɪ mesh {handle:?} has \"nholes\" asking for {expected} \
                 \"nvertices\" values and carries {found}; with holes, each \
                 face takes its outer perimeter plus one count per hole"
            ),
        }
    }
}

impl core::error::Error for ResolveError {}

/// What an ɴsɪ `attributes` node resolves to for one piece of geometry.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Binding {
    /// Every `attributes` node gathered along the path, nearest the
    /// geometry first, then in connection order.
    ///
    /// The `priority` on a `geometryattributes` connection deliberately
    /// does **not** reorder this: 3Delight ignores it, whatever the
    /// specification says. A priority on a *shader* connection is
    /// honoured; see [`Binding::surface_shader`] and `research.md` D12.
    ///
    /// ɴsɪ gathers attributes along the whole path and considers
    /// *every* node on it -- "one attributes node can set object
    /// visibility and another can set the surface shader" -- so this is
    /// a list, not a winner. A backend looking for one attribute takes
    /// the first node in this list that defines it -- correct only while
    /// no node sets `ATTR.priority` and the attribute is not a
    /// visibility one. [`Scene::attribute_value`] applies those two
    /// rules and is the safe way to ask.
    ///
    /// When this [`Binding`] came from a [`Placement`], ask
    /// [`Scene::attribute_value_along`] with that placement's path
    /// instead: `attribute_value` takes a geometry, so it refuses the
    /// multi-parent node a placement exists for.
    ///
    /// The handles are returned rather than their contents because what
    /// lives on them -- visibility flags above all -- is encoded
    /// differently by each renderer, and inventing a common shape for it
    /// here would be guesswork.
    pub attributes: Vec<String>,
    /// The shader reached through `surfaceshader`, resolved across every
    /// gathered node by the same rule, using the priority of the
    /// `surfaceshader` connection itself.
    ///
    /// `None` when nothing on the path sets one.
    pub surface_shader: Option<String>,
    /// The `displacementshader`, resolved the same way.
    pub displacement_shader: Option<String>,
    /// The `volumeshader`, resolved the same way.
    pub volume_shader: Option<String>,
}

/// ɴsɪ's ray types: the suffixes a `visibility.<ray>` attribute takes.
///
/// Spelled out rather than accepting any suffix, because
/// `visibility.set.subsurface` is a *connection* to a `set` node and not
/// a per-ray visibility int; treating it as the more specific form of
/// `visibility` would rank a connection against a flag.
///
/// Public because a backend building a visibility mask needs exactly
/// this list, and a second copy of it would drift from this one.
pub const RAY_TYPES: [&str; 8] = [
    "camera",
    "diffuse",
    "hair",
    "reflection",
    "refraction",
    "shadow",
    "specular",
    "volume",
];

/// One placement of a geometry in the scene.
///
/// ɴsɪ's *lightweight* instancing: connecting a node to two transforms
/// draws it twice, once per path. Rendered, a quad under two transforms
/// translated `-2` and `+2` appears at both positions, and putting
/// `visibility 1` on one parent and `visibility 0` on the other draws
/// **one** copy -- so a path carries its own attributes as well as its
/// own transform, and a backend emitting one instance per placement
/// needs both together.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Placement {
    /// The nodes from the geometry to `.root`, geometry first.
    ///
    /// Two placements of one geometry differ here, and that is what
    /// makes them distinguishable: the handle alone does not.
    pub path: Vec<String>,
    /// The world transform along this path.
    pub transform: [f64; 16],
    /// What binds along this path, or `None` when nothing does.
    ///
    /// The same shape [`Scene::geometry_binding`] returns, resolved
    /// against this path rather than against "the" path.
    pub binding: Option<Binding>,
}

/// The winning definition of one attribute, gathered along a path.
///
/// Returned by [`Scene::attribute_value`].
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct AttributeValue<'a> {
    /// The node the winning definition sits on.
    ///
    /// Usually an `attributes` node. For a shader attribute it can be
    /// the geometry itself, which ɴsɪ ranks above every container.
    pub node: &'a str,
    /// The attribute that actually won, which is not always the one
    /// asked for: in [`Scene::attribute_value`] a `visibility.<ray>`
    /// query falls back to the less specific `visibility`, and this is
    /// how a backend tells the two apart.
    /// [`Scene::shader_attribute_value`] performs no such fallback, so
    /// there it always matches the query.
    pub name: &'a str,
    /// The definition itself, or `None` when the winning node carries
    /// only `<name>.priority`.
    ///
    /// 3Delight reads a lone `ATTR.priority` as a definition of `ATTR`
    /// **at its ɴsɪ default**, and it wins on the strength of that
    /// priority; [`Scene::attribute_value`] has the rendered evidence.
    /// This crate does not carry ɴsɪ's per-attribute defaults, so it
    /// names the winner and leaves the value to the backend: `None`
    /// means *the default of [`AttributeValue::name`]*, never
    /// *undefined*.
    pub arg: Option<&'a OwnedArgument>,
    /// The `ATTR.priority` that selected it; `0` when none is set.
    pub priority: i32,
}

/// One renderable output: a camera paired with a screen, and the AOVs
/// written from it.
/// `Eq` and `Hash` are absent for the reason `OwnedArgument`'s are
/// (research D7): a layer carries `filter_width`, and a float has no
/// total equality to derive one from.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RenderOutput {
    /// The camera the screen is connected to.
    pub camera: String,
    /// The screen, which is what carries resolution and oversampling.
    pub screen: String,
    /// AOVs in connection order; may be empty.
    pub layers: Vec<OutputLayer>,
}

/// One instance, borrowing the matrix the scene already holds.
///
/// [`Scene::instance_transforms`] copies: for a set-dressing
/// instancer with a million entries that is 136 MB of `Instance`
/// against the 128 MB `doublematrix` array it was copied from.
/// [`Scene::instances`] hands out these instead, which is the shape a
/// renderer's own instancer wants -- a prototype index and a matrix it
/// can read in place.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct InstanceRef<'a> {
    /// Which prototype this instance draws, as a position in
    /// [`Scene::instance_sources`].
    pub source: usize,
    /// This instance's transform, in the `instances` node's space.
    pub transform: &'a [f64; 16],
}

/// One instance an `instances` node places.
///
/// ɴsɪ gives an `instances` node "a transformation matrix for each
/// instance" and an optional `modelindices` selecting which prototype
/// each uses. This pairs the two, so a backend building a MoonRay
/// `InstanceGeometry` or a Mitsuba `shapegroup` reference does not have
/// to.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Instance {
    /// Which prototype this instance draws, as a position in
    /// [`Scene::instance_sources`].
    ///
    /// ɴsɪ matches `modelindices` against "the index attribute of the
    /// model connection", not against connection order, so this is the
    /// resolved position rather than the raw value.
    pub source: usize,
    /// This instance's transform, in the `instances` node's space.
    pub transform: [f64; 16],
}

/// One AOV, resolved: what to output, how to encode it, and where it
/// goes.
///
/// Every field but `handle` and `drivers` is an `outputlayer`
/// attribute, **with the specification's default already applied** --
/// `variablesource` "shader", `layertype` "color", `scalarformat`
/// "uint8", `filter` "blackman-harris", `filterwidth` 3.0,
/// `withalpha` and `dithering` off. A backend that re-derives these
/// gets them subtly wrong: the defaults are stated once in the
/// specification and nowhere in the scene, so a layer that sets none
/// of them still means "a uint8 colour from a shader closure".
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct OutputLayer {
    /// The `outputlayer` node's handle.
    pub handle: String,
    /// The variable to output. `None` when the layer does not name one,
    /// which is a scene error rather than a default.
    pub variable_name: Option<String>,
    /// Where the variable is read from: `"shader"`, `"attribute"` or
    /// `"builtin"`. Defaults to `"shader"`.
    pub variable_source: String,
    /// The layer's name as the driver writes it -- the layer name
    /// inside an EXR, say. `None` when unset; ɴsɪ gives no default, so
    /// a driver picks its own.
    pub layer_name: Option<String>,
    /// `"scalar"`, `"color"`, `"vector"` or `"quad"`. Defaults to
    /// `"color"`.
    pub layer_type: String,
    /// The quantisation: `"uint8"` through `"float"`. Defaults to
    /// `"uint8"`, which surprises a backend expecting float AOVs.
    pub scalar_format: String,
    /// Whether an alpha channel is included. Defaults to `false`.
    pub with_alpha: bool,
    /// Whether integer scalars are dithered. Defaults to `false`.
    pub dithering: bool,
    /// The reconstruction filter. Defaults to `"blackman-harris"`.
    pub filter: String,
    /// The filter's diameter in pixels. Defaults to `3.0`, and ɴsɪ says
    /// it is not applied for `"box"` or `"zmin"`.
    pub filter_width: f64,
    /// An ᴏᴄɪᴏ colour profile to apply before quantisation, if set.
    pub color_profile: Option<String>,
    /// The ordering key among layers on one driver, if set.
    ///
    /// See `drivers`: this crate applies it rather than leaving it to
    /// the backend.
    pub sort_key: Option<i32>,
    /// A layer may fan out to several drivers -- a file and a display,
    /// say.
    ///
    /// In connection order. ɴsɪ orders *layers* on a driver by
    /// `sortkey`, not drivers on a layer, so this stays as connected.
    pub drivers: Vec<String>,
}

/// Row-major 4x4 product, `a` then `b`.
///
/// ɴsɪ uses the RenderMan row-vector convention: a point is a row and
/// transforms multiply on the right, so `p * a * b` applies `a` first.
/// Composing a child with its parent is therefore `mul(child, parent)`,
/// not the other way round.
fn mul(a: [f64; 16], b: [f64; 16]) -> [f64; 16] {
    let mut out = [0.0; 16];
    for row in 0..4 {
        for col in 0..4 {
            let mut sum = 0.0;
            for k in 0..4 {
                sum += a[row * 4 + k] * b[k * 4 + col];
            }
            out[row * 4 + col] = sum;
        }
    }
    out
}

#[cfg(test)]
mod tests;