alpha2-render 0.5.0

Render graph and effect registry for alpha2.
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
use std::borrow::Cow;
use std::fmt;
use std::sync::atomic::{AtomicU32, Ordering};

use crate::graph_cache::{
    composite_cache_key, effect_cache_key_with_resources, named_inputs_key, transient_source_key,
    vector_cache_key,
};
use crate::{
    BlendMode, Color, EffectId, EffectParams, EffectResources, EffectRuntime, LayerTransform,
    RenderError, RenderSize, SourceView,
};

/// Stable handle to a node within one render graph.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct RenderNodeId {
    pub(crate) graph: u32,
    pub(crate) index: usize,
}

impl RenderNodeId {
    /// Returns the node's insertion-order index.
    #[must_use]
    pub const fn index(self) -> usize {
        self.index
    }
}

/// Public category of a render graph node.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum RenderNodeKind {
    /// Externally owned input texture.
    Source,
    /// Registered effect with one source and any declared named inputs.
    Effect,
    /// Registered two-input transition.
    Transition,
    /// Registered zero-input generator.
    Generator,
    /// Ordered layer composition.
    Composite,
    /// A vector scene: fills drawn from tile coverage.
    Vector,
}

/// Named images an effect node samples besides its source, sorted by name, one node per name.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct EffectInputs<'a> {
    values: Vec<(Cow<'a, str>, RenderNodeId)>,
}

impl<'a> EffectInputs<'a> {
    /// Creates an empty set, without allocating.
    #[must_use]
    pub const fn new() -> Self {
        Self { values: Vec::new() }
    }

    /// Adds or replaces one named input.
    #[must_use]
    pub fn with(mut self, name: impl Into<Cow<'a, str>>, node: RenderNodeId) -> Self {
        self.insert(name, node);
        self
    }

    /// Adds or replaces one named input in place.
    pub fn insert(&mut self, name: impl Into<Cow<'a, str>>, node: RenderNodeId) {
        let name = name.into();
        match self
            .values
            .binary_search_by(|(held, _)| held.as_ref().cmp(name.as_ref()))
        {
            Ok(index) => self.values[index].1 = node,
            Err(index) => self.values.insert(index, (name, node)),
        }
    }

    /// Whether no input is named.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// The number of named inputs.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Every input by name, in name order.
    pub(crate) fn iter(&self) -> impl Iterator<Item = (&str, RenderNodeId)> {
        self.values
            .iter()
            .map(|(name, node)| (name.as_ref(), *node))
    }
}

/// One owned layer reference in a graph composition node.
#[derive(Copy, Clone, Debug)]
pub struct GraphLayer {
    /// Node whose result is sampled as this layer.
    pub source: RenderNodeId,
    /// Layer transform and opacity.
    pub visual: LayerTransform,
    /// Artistic blend operation.
    pub blend_mode: BlendMode,
}

/// An insertion-ordered, acyclic render program.
#[derive(Debug)]
pub struct RenderGraph<'a> {
    pub(crate) id: u32,
    pub(crate) size: RenderSize,
    pub(crate) nodes: Vec<RenderNode<'a>>,
    pub(crate) cache_keys: Vec<RenderCacheKey>,
    /// Whether each node's key is complete (no unkeyed source beneath it).
    pub(crate) stable: Vec<bool>,
    /// Each node's cache intent; `None` when not a candidate.
    pub(crate) intents: Vec<Option<crate::CacheIntent>>,
    pub(crate) output: Option<RenderNodeId>,
    /// Blend space for this graph's composites; `None` uses the renderer's.
    pub(crate) blend_space: Option<crate::BlendSpace>,
}

static NEXT_GRAPH_ID: AtomicU32 = AtomicU32::new(1);

#[derive(Debug)]
pub(crate) enum RenderNode<'a> {
    Source(SourceView<'a>),
    Effect {
        effect: EffectId,
        source: RenderNodeId,
        inputs: EffectInputs<'a>,
        params: EffectParams<'a>,
        resources: EffectResources,
        runtime: EffectRuntime,
    },
    Transition {
        effect: EffectId,
        from: RenderNodeId,
        to: RenderNodeId,
        params: EffectParams<'a>,
        resources: EffectResources,
        runtime: EffectRuntime,
    },
    Generator {
        effect: EffectId,
        params: EffectParams<'a>,
        resources: EffectResources,
        runtime: EffectRuntime,
    },
    Composite {
        layers: Vec<GraphLayer>,
        background: Option<Color>,
    },
    Vector {
        scene: std::sync::Arc<alpha2_geometry::VectorScene>,
    },
}

/// Deterministic 128-bit key for a source or rendered graph result.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct RenderCacheKey(pub(crate) u128);

impl RenderCacheKey {
    /// Creates a stable source key supplied by a decode or asset cache.
    #[must_use]
    pub const fn source(value: u64) -> Self {
        Self(value as u128)
    }

    /// Creates a key from all 128 bits. Keys not derived from a decoded source set high bits, so
    /// they never equal a [`Self::source`] key.
    #[must_use]
    pub const fn from_value(value: u128) -> Self {
        Self(value)
    }

    /// Returns the stable 128-bit representation.
    #[must_use]
    pub const fn value(self) -> u128 {
        self.0
    }
}

/// Structural or execution failure in a render graph.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GraphError {
    /// A node references an ID not already present in the graph.
    InvalidDependency,
    /// No final output node was selected.
    MissingOutput,
    /// An external source cannot be returned as an owned render result.
    SourceOutput,
    /// A registered shader kind does not match its graph node.
    EffectKindMismatch,
    /// A rendering operation failed.
    Render(RenderError),
}

impl fmt::Display for GraphError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidDependency => {
                formatter.write_str("render graph dependency must name an earlier node")
            }
            Self::MissingOutput => formatter.write_str("render graph has no selected output"),
            Self::SourceOutput => {
                formatter.write_str("render graph output must be a rendered node")
            }
            Self::EffectKindMismatch => {
                formatter.write_str("registered effect kind does not match its graph node")
            }
            Self::Render(error) => write!(formatter, "render graph execution failed: {error}"),
        }
    }
}

impl std::error::Error for GraphError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Render(error) => Some(error),
            _ => None,
        }
    }
}

impl From<RenderError> for GraphError {
    fn from(error: RenderError) -> Self {
        Self::Render(error)
    }
}

impl GraphError {
    /// Converts to [`RenderError`], reporting structural faults as [`RenderError::InvalidGraph`].
    #[must_use]
    pub const fn into_render_error(self) -> RenderError {
        match self {
            Self::Render(error) => error,
            Self::InvalidDependency
            | Self::MissingOutput
            | Self::SourceOutput
            | Self::EffectKindMismatch => RenderError::InvalidGraph,
        }
    }
}

impl<'a> RenderGraph<'a> {
    /// Creates an empty graph whose rendered nodes share one output size.
    #[must_use]
    pub fn new(size: RenderSize) -> Self {
        Self {
            id: NEXT_GRAPH_ID.fetch_add(1, Ordering::Relaxed),
            size,
            nodes: Vec::new(),
            cache_keys: Vec::new(),
            stable: Vec::new(),
            intents: Vec::new(),
            output: None,
            blend_space: None,
        }
    }

    /// The size every rendered node of this graph has.
    #[must_use]
    pub const fn size(&self) -> RenderSize {
        self.size
    }

    /// Blends this graph's composites in `space` instead of the renderer default, so preview and
    /// export match.
    pub fn set_blend_space(&mut self, space: crate::BlendSpace) {
        self.blend_space = Some(space);
    }

    /// Adds an externally owned source texture.
    pub fn add_source(&mut self, texture: SourceView<'a>) -> RenderNodeId {
        let key = transient_source_key(self.id, self.nodes.len());
        self.push(RenderNode::Source(texture), key, false)
    }

    /// Adds an external texture with a stable cache key.
    ///
    /// The key must cover everything the pixels depend on (content, frame, decode and conversion);
    /// results drawn from it can then be cached.
    pub fn add_source_with_key(
        &mut self,
        texture: SourceView<'a>,
        key: RenderCacheKey,
    ) -> RenderNodeId {
        self.push(RenderNode::Source(texture), key, true)
    }

    /// Adds a registered one-input effect node.
    ///
    /// # Errors
    /// Returns [`GraphError::InvalidDependency`] unless `source` is earlier.
    pub fn add_effect(
        &mut self,
        effect: EffectId,
        source: RenderNodeId,
        params: EffectParams<'a>,
        runtime: EffectRuntime,
    ) -> Result<RenderNodeId, GraphError> {
        self.add_effect_with_resources(effect, source, params, EffectResources::new(), runtime)
    }

    /// Adds a registered one-input effect node with external resources.
    ///
    /// Built-in Gaussian blur and glow expand into internal passes; the last is returned.
    ///
    /// # Errors
    /// [`GraphError::InvalidDependency`] unless `source` is earlier; for an expanded built-in, also
    /// [`RenderError::InvalidEffectParams`] for unknown or out-of-range parameters.
    pub fn add_effect_with_resources(
        &mut self,
        effect: EffectId,
        source: RenderNodeId,
        params: EffectParams<'a>,
        resources: EffectResources,
        runtime: EffectRuntime,
    ) -> Result<RenderNodeId, GraphError> {
        self.add_effect_with_inputs(
            effect,
            source,
            EffectInputs::new(),
            params,
            resources,
            runtime,
        )
    }

    /// Adds a registered effect node that also samples `inputs` by their declared names.
    ///
    /// # Errors
    /// [`GraphError::InvalidDependency`] unless `source` and every input are earlier,
    /// [`RenderError::InvalidEffectParams`] for named inputs on an expanded built-in, and otherwise
    /// the errors of [`Self::add_effect_with_resources`].
    pub fn add_effect_with_inputs(
        &mut self,
        effect: EffectId,
        source: RenderNodeId,
        inputs: EffectInputs<'a>,
        params: EffectParams<'a>,
        resources: EffectResources,
        runtime: EffectRuntime,
    ) -> Result<RenderNodeId, GraphError> {
        self.validate_dependency(source)?;
        for (_, input) in inputs.iter() {
            self.validate_dependency(input)?;
        }
        // Expanded built-ins take no resources or inputs; check before expanding so no node is
        // left.
        if !inputs.is_empty() && crate::gaussian_blur::expanded_passes(effect.as_str()).is_some() {
            return Err(RenderError::InvalidEffectParams.into());
        }
        if let Some(expanded) = self.add_expanded_effect(&effect, source, &params, runtime) {
            if resources.iter().next().is_some() {
                return Err(RenderError::InvalidEffectParams.into());
            }
            return expanded;
        }
        let source_key = self.cache_keys[source.index];
        let input_keys: &[RenderCacheKey] = if inputs.is_empty() {
            &[source_key]
        } else {
            &[source_key, named_inputs_key(&inputs, &self.cache_keys)]
        };
        let key = effect_cache_key_with_resources(
            b"effect", self.size, &effect, input_keys, &params, &resources, runtime,
        );
        let stable =
            self.stable[source.index] && inputs.iter().all(|(_, input)| self.stable[input.index]);
        Ok(self.push(
            RenderNode::Effect {
                effect,
                source,
                inputs,
                params,
                resources,
                runtime,
            },
            key,
            stable,
        ))
    }

    /// Adds a registered generator node drawn from its parameters at the graph's size.
    pub fn add_generator(
        &mut self,
        effect: EffectId,
        params: EffectParams<'a>,
        runtime: EffectRuntime,
    ) -> RenderNodeId {
        self.add_generator_with_resources(effect, params, EffectResources::new(), runtime)
    }

    /// Adds a registered generator node that samples external resources by declared name.
    pub fn add_generator_with_resources(
        &mut self,
        effect: EffectId,
        params: EffectParams<'a>,
        resources: EffectResources,
        runtime: EffectRuntime,
    ) -> RenderNodeId {
        let key = effect_cache_key_with_resources(
            b"generator",
            self.size,
            &effect,
            &[],
            &params,
            &resources,
            runtime,
        );
        self.push(
            RenderNode::Generator {
                effect,
                params,
                resources,
                runtime,
            },
            key,
            true,
        )
    }

    /// Adds a vector scene drawn from tile coverage over transparency
    /// (see [`alpha2_geometry::VectorScene`]).
    ///
    /// Keyed by the scene, so an unchanged scene is a cache hit. Scene coordinates are this graph's
    /// pixels.
    pub fn add_vector(
        &mut self,
        scene: std::sync::Arc<alpha2_geometry::VectorScene>,
    ) -> RenderNodeId {
        let key = vector_cache_key(self.size, scene.key);
        self.push(RenderNode::Vector { scene }, key, true)
    }

    /// Adds a registered two-input transition node.
    ///
    /// # Errors
    /// Returns [`GraphError::InvalidDependency`] unless both inputs are earlier.
    pub fn add_transition(
        &mut self,
        effect: EffectId,
        from: RenderNodeId,
        to: RenderNodeId,
        params: EffectParams<'a>,
        runtime: EffectRuntime,
    ) -> Result<RenderNodeId, GraphError> {
        self.add_transition_with_resources(
            effect,
            from,
            to,
            params,
            EffectResources::new(),
            runtime,
        )
    }

    /// Adds a registered two-input transition node with external resources.
    ///
    /// # Errors
    /// Returns [`GraphError::InvalidDependency`] unless both inputs are earlier.
    pub fn add_transition_with_resources(
        &mut self,
        effect: EffectId,
        from: RenderNodeId,
        to: RenderNodeId,
        params: EffectParams<'a>,
        resources: EffectResources,
        runtime: EffectRuntime,
    ) -> Result<RenderNodeId, GraphError> {
        self.validate_dependency(from)?;
        self.validate_dependency(to)?;
        let key = effect_cache_key_with_resources(
            b"transition",
            self.size,
            &effect,
            &[self.cache_keys[from.index], self.cache_keys[to.index]],
            &params,
            &resources,
            runtime,
        );
        let stable = self.stable[from.index] && self.stable[to.index];
        Ok(self.push(
            RenderNode::Transition {
                effect,
                from,
                to,
                params,
                resources,
                runtime,
            },
            key,
            stable,
        ))
    }

    /// Adds an ordered layer-composition node over a transparent target.
    ///
    /// # Errors
    /// Returns [`GraphError::InvalidDependency`] for a missing layer source.
    pub fn add_composite(&mut self, layers: Vec<GraphLayer>) -> Result<RenderNodeId, GraphError> {
        self.push_composite(layers, None)
    }

    /// Adds an ordered layer-composition node over a solid background.
    ///
    /// `background` acts as the bottom layer and is a premultiplied sRGB storage value, like
    /// [`crate::Renderer::render_solid`]'s color.
    ///
    /// # Errors
    /// [`GraphError::InvalidDependency`] for a missing layer source, or
    /// [`RenderError::InvalidColor`] for an out-of-range or non-premultiplied background.
    pub fn add_composite_over(
        &mut self,
        layers: Vec<GraphLayer>,
        background: Color,
    ) -> Result<RenderNodeId, GraphError> {
        if !background.is_valid() {
            return Err(GraphError::Render(RenderError::InvalidColor));
        }
        self.push_composite(layers, Some(background))
    }

    fn push_composite(
        &mut self,
        layers: Vec<GraphLayer>,
        background: Option<Color>,
    ) -> Result<RenderNodeId, GraphError> {
        for layer in &layers {
            self.validate_dependency(layer.source)?;
        }
        let key = composite_cache_key(self.size, &layers, background, &self.cache_keys);
        let stable = layers.iter().all(|layer| self.stable[layer.source.index]);
        Ok(self.push(RenderNode::Composite { layers, background }, key, stable))
    }

    /// Selects the graph result.
    ///
    /// # Errors
    /// Returns [`GraphError::InvalidDependency`] for an unknown node.
    pub fn set_output(&mut self, output: RenderNodeId) -> Result<(), GraphError> {
        self.validate_dependency(output)?;
        self.output = Some(output);
        Ok(())
    }

    /// The selected graph result, if one was selected.
    #[must_use]
    pub const fn output(&self) -> Option<RenderNodeId> {
        self.output
    }

    /// Returns the number of nodes in insertion order.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Returns the public category of a node.
    #[must_use]
    pub fn node_kind(&self, id: RenderNodeId) -> Option<RenderNodeKind> {
        if id.graph == self.id {
            self.nodes.get(id.index).map(RenderNode::kind)
        } else {
            None
        }
    }

    /// Makes `node` a cache candidate under `intent`, used when its key is complete.
    /// [`crate::CacheIntent::Bypass`] excludes the node, its inputs and its dependents.
    ///
    /// # Errors
    /// Returns [`GraphError::InvalidDependency`] for an unknown node.
    pub fn set_cache_intent(
        &mut self,
        node: RenderNodeId,
        intent: crate::CacheIntent,
    ) -> Result<(), GraphError> {
        self.validate_dependency(node)?;
        self.intents[node.index] = Some(intent);
        Ok(())
    }

    /// Whether `node`'s result can be cached, and if not, why.
    ///
    /// # Errors
    /// Returns [`GraphError::InvalidDependency`] for an unknown node.
    pub fn cache_eligibility(
        &self,
        node: RenderNodeId,
    ) -> Result<crate::CacheEligibility, GraphError> {
        self.validate_dependency(node)?;
        Ok(self.eligibility()[node.index])
    }

    /// Every node's eligibility. A bypass spreads down to inputs and up to dependents; a transient
    /// source only up.
    pub(crate) fn eligibility(&self) -> Vec<crate::CacheEligibility> {
        let count = self.nodes.len();
        let mut bypassed: Vec<bool> = self
            .intents
            .iter()
            .map(|intent| *intent == Some(crate::CacheIntent::Bypass))
            .collect();
        // Up: nodes are in dependency order, so inputs come first.
        for index in 0..count {
            if self.nodes[index]
                .dependencies()
                .iter()
                .any(|input| bypassed[input.index])
            {
                bypassed[index] = true;
            }
        }
        // Down: from each explicitly bypassed node to its inputs.
        let mut down: Vec<bool> = self
            .intents
            .iter()
            .map(|intent| *intent == Some(crate::CacheIntent::Bypass))
            .collect();
        for index in (0..count).rev() {
            if down[index] {
                for input in self.nodes[index].dependencies() {
                    down[input.index] = true;
                }
            }
        }
        (0..count)
            .map(|index| {
                if bypassed[index] || down[index] {
                    crate::CacheEligibility::Bypassed
                } else if self.stable[index] {
                    crate::CacheEligibility::Eligible
                } else {
                    crate::CacheEligibility::TransientSource
                }
            })
            .collect()
    }

    fn push(
        &mut self,
        node: RenderNode<'a>,
        cache_key: RenderCacheKey,
        stable: bool,
    ) -> RenderNodeId {
        let id = RenderNodeId {
            graph: self.id,
            index: self.nodes.len(),
        };
        self.nodes.push(node);
        self.cache_keys.push(cache_key);
        self.stable.push(stable);
        self.intents.push(None);
        id
    }

    fn validate_dependency(&self, dependency: RenderNodeId) -> Result<(), GraphError> {
        if dependency.graph == self.id && dependency.index < self.nodes.len() {
            Ok(())
        } else {
            Err(GraphError::InvalidDependency)
        }
    }
}

impl RenderNodeKind {
    /// Label for pass timing ([`crate::PassTiming::label`]).
    pub(crate) const fn pass_label(self) -> &'static str {
        match self {
            Self::Source => "source",
            Self::Effect => "effect",
            Self::Transition => "transition",
            Self::Generator => "generator",
            Self::Composite => "composite",
            Self::Vector => "vector",
        }
    }
}

impl RenderNode<'_> {
    pub(crate) const fn kind(&self) -> RenderNodeKind {
        match self {
            Self::Source(_) => RenderNodeKind::Source,
            Self::Effect { .. } => RenderNodeKind::Effect,
            Self::Transition { .. } => RenderNodeKind::Transition,
            Self::Generator { .. } => RenderNodeKind::Generator,
            Self::Composite { .. } => RenderNodeKind::Composite,
            Self::Vector { .. } => RenderNodeKind::Vector,
        }
    }

    pub(crate) fn dependencies(&self) -> Vec<RenderNodeId> {
        match self {
            Self::Source(_) | Self::Generator { .. } | Self::Vector { .. } => Vec::new(),
            Self::Effect { source, inputs, .. } => std::iter::once(*source)
                .chain(inputs.iter().map(|(_, input)| input))
                .collect(),
            Self::Transition { from, to, .. } => vec![*from, *to],
            Self::Composite { layers, .. } => layers.iter().map(|layer| layer.source).collect(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_node_and_setting_refuses_a_node_of_another_graph_or_one_not_yet_added() {
        // Node ids carry their graph; every method must refuse another graph's node with the same
        // index.
        let size = RenderSize::new(16, 9).expect("non-zero size");
        let effect = EffectId::new("test.effect".into(), 1);
        let mut other = RenderGraph::new(size);
        let foreign = other.add_generator(
            effect.clone(),
            EffectParams::new(),
            EffectRuntime::default(),
        );
        let mut graph = RenderGraph::new(size);
        let own = graph.add_generator(
            effect.clone(),
            EffectParams::new(),
            EffectRuntime::default(),
        );
        // The same index as a node of this graph, but another graph's.
        assert_eq!(foreign.index, own.index);
        let unknown = RenderNodeId {
            graph: graph.id,
            index: 1,
        };
        let layer = |source| GraphLayer {
            source,
            visual: crate::LayerTransform {
                position: [0.5, 0.5],
                anchor: [0.5, 0.5],
                scale: [1.0, 1.0],
                rotation_degrees: 0.0,
                opacity: 1.0,
            },
            blend_mode: crate::BlendMode::Normal,
        };
        for bad in [foreign, unknown] {
            let invalid = Err(GraphError::InvalidDependency);
            assert_eq!(
                graph.add_effect(
                    effect.clone(),
                    bad,
                    EffectParams::new(),
                    EffectRuntime::default()
                ),
                invalid
            );
            assert_eq!(
                graph.add_transition(
                    effect.clone(),
                    own,
                    bad,
                    EffectParams::new(),
                    EffectRuntime::default()
                ),
                invalid
            );
            assert_eq!(
                graph.add_transition(
                    effect.clone(),
                    bad,
                    own,
                    EffectParams::new(),
                    EffectRuntime::default()
                ),
                invalid
            );
            assert_eq!(graph.add_composite(vec![layer(own), layer(bad)]), invalid);
            assert_eq!(
                graph.add_composite_over(vec![layer(bad)], Color::BLACK),
                invalid
            );
            assert_eq!(graph.set_output(bad), Err(GraphError::InvalidDependency));
            assert_eq!(
                graph.set_cache_intent(bad, crate::CacheIntent::Pin),
                Err(GraphError::InvalidDependency)
            );
            assert_eq!(
                graph.cache_eligibility(bad),
                Err(GraphError::InvalidDependency)
            );
            assert_eq!(graph.node_kind(bad), None);
        }
        assert_eq!(graph.node_count(), 1);
        assert_eq!(graph.node_kind(own), Some(RenderNodeKind::Generator));
        // An out-of-range background is refused before its layers are looked at.
        assert_eq!(
            graph.add_composite_over(vec![layer(foreign)], Color::rgba(1.5, 0.0, 0.0, 1.0)),
            Err(GraphError::Render(RenderError::InvalidColor))
        );
        assert_eq!(graph.node_count(), 1);
    }

    fn generator(graph: &mut RenderGraph<'_>, id: &'static str) -> RenderNodeId {
        graph.add_generator(
            EffectId::from_static(id, 1),
            EffectParams::new(),
            EffectRuntime::default(),
        )
    }

    fn effect_with_inputs(
        graph: &mut RenderGraph<'static>,
        source: RenderNodeId,
        inputs: EffectInputs<'static>,
    ) -> Result<RenderNodeId, GraphError> {
        graph.add_effect_with_inputs(
            EffectId::from_static("test.multi-input", 1),
            source,
            inputs,
            EffectParams::new(),
            EffectResources::new(),
            EffectRuntime::default(),
        )
    }

    #[test]
    fn named_inputs_are_dependencies() {
        // A node read only as a named input is drawn before the effect.
        let size = RenderSize::new(16, 9).expect("non-zero size");
        let mut graph = RenderGraph::new(size);
        let source = generator(&mut graph, "test.source");
        let map = generator(&mut graph, "test.map");
        let unused = generator(&mut graph, "test.unused");
        let effect = effect_with_inputs(&mut graph, source, EffectInputs::new().with("map", map))
            .expect("earlier nodes");
        graph.set_output(effect).expect("known output");
        let plan = graph.compile().expect("compiles");
        assert_eq!(plan.execution_order(), [source, map, effect]);
        assert_eq!(plan.last_use(map), Some(2));
        assert_eq!(plan.last_use(unused), None);
        let later = RenderNodeId {
            graph: graph.id,
            index: graph.node_count(),
        };
        assert_eq!(
            effect_with_inputs(&mut graph, source, EffectInputs::new().with("map", later)),
            Err(GraphError::InvalidDependency)
        );
    }

    #[test]
    fn named_inputs_on_a_built_in_drawn_as_passes_are_refused() {
        let size = RenderSize::new(16, 9).expect("non-zero size");
        let mut graph = RenderGraph::new(size);
        let source = generator(&mut graph, "test.source");
        let map = generator(&mut graph, "test.map");
        let count = graph.node_count();
        for id in [crate::builtins::GAUSSIAN_BLUR_ID, crate::builtins::GLOW_ID] {
            assert_eq!(
                graph.add_effect_with_inputs(
                    EffectId::from_static(id, 1),
                    source,
                    EffectInputs::new().with("map", map),
                    EffectParams::new(),
                    EffectResources::new(),
                    EffectRuntime::default(),
                ),
                Err(GraphError::Render(RenderError::InvalidEffectParams)),
                "{id}"
            );
        }
        assert_eq!(graph.node_count(), count, "no pass is left behind");
    }

    #[test]
    fn a_named_input_is_part_of_the_cache_key() {
        let size = RenderSize::new(16, 9).expect("non-zero size");
        let key = |build: &dyn Fn(&mut RenderGraph<'static>, [RenderNodeId; 3]) -> RenderNodeId| {
            let mut graph = RenderGraph::new(size);
            let nodes = [
                generator(&mut graph, "test.source"),
                generator(&mut graph, "test.map"),
                generator(&mut graph, "test.other-map"),
            ];
            let node = build(&mut graph, nodes);
            graph.cache_keys[node.index]
        };
        let named = |name: &'static str, input: usize| {
            key(&move |graph, nodes| {
                effect_with_inputs(
                    graph,
                    nodes[0],
                    EffectInputs::new().with(name, nodes[input]),
                )
                .expect("earlier nodes")
            })
        };
        assert_eq!(named("map", 1), named("map", 1));
        assert_ne!(named("map", 1), named("map", 2));
        assert_ne!(named("map", 1), named("mask", 1));
        let none = key(&|graph, nodes| {
            effect_with_inputs(graph, nodes[0], EffectInputs::new()).expect("earlier node")
        });
        assert_ne!(named("map", 1), none);
        let plain = key(&|graph, nodes| {
            graph
                .add_effect_with_resources(
                    EffectId::from_static("test.multi-input", 1),
                    nodes[0],
                    EffectParams::new(),
                    EffectResources::new(),
                    EffectRuntime::default(),
                )
                .expect("earlier node")
        });
        assert_eq!(none, plain);
    }

    #[test]
    fn a_graph_compiles_only_once_an_output_is_chosen() {
        let size = RenderSize::new(16, 9).expect("non-zero size");
        let mut graph = RenderGraph::new(size);
        let output = graph.add_composite(Vec::new()).expect("empty clear node");
        assert_eq!(graph.compile().err(), Some(GraphError::MissingOutput));
        assert_eq!(
            GraphError::MissingOutput.into_render_error(),
            RenderError::InvalidGraph
        );
        graph.set_output(output).expect("known output");
        assert_eq!(
            graph.compile().expect("compiles").execution_order(),
            [output]
        );
    }

    #[test]
    fn quality_compilation_exposes_centered_temporal_schedule() {
        let size = RenderSize::new(16, 9).expect("non-zero size");
        let mut graph = RenderGraph::new(size);
        let output = graph.add_composite(Vec::new()).expect("empty clear node");
        graph.set_output(output).expect("known output");
        let plan = graph
            .compile_with_quality(crate::RenderQualityControls {
                max_filter_samples: 12,
                motion_blur_subframes: 4,
            })
            .expect("compiled");
        assert_eq!(plan.temporal_offsets(), [-0.375, -0.125, 0.125, 0.375]);
        assert_eq!(plan.filter_sample_limit(output), None);
    }
}