Skip to main content

alpha2_render/
graph_execute.rs

1use std::collections::HashSet;
2use web_time::Instant;
3
4use crate::composite::CompositeTarget;
5use crate::graph::{GraphError, RenderCacheKey, RenderGraph, RenderNode, RenderNodeId};
6use crate::graph_cache::{renderer_cache_key, renderer_node_key};
7use crate::runtime_effect::{EffectPass, PendingEffectTiming};
8use crate::uniform::{
9    BATCH_UNIFORM_FLOATS, RUNTIME_UNIFORM_WORDS, UniformArenaLease, aligned_uniform_end,
10    float_uniform_bytes, param_uniform_bytes,
11};
12use crate::{
13    CompositeLayer, EffectId, EffectKind, RenderedTexture, Renderer, ShaderDiagnostics,
14    WarmupReport,
15};
16
17pub(crate) struct EncodedGraph {
18    texture: RenderedTexture,
19    /// Results to keep after the submission is accepted; keeping them earlier could leave
20    /// unwritten textures after a failure.
21    cache_inserts: Vec<(RenderCacheKey, RenderedTexture, bool)>,
22    /// The result cache's clear count at lookup; a later clear drops `cache_inserts`.
23    cache_clears: u64,
24    uniforms: UniformArenaLease,
25    pending_timings: Vec<PendingEffectTiming>,
26    encoded_nodes: u64,
27    encoded_render_passes: u64,
28}
29
30impl EncodedGraph {
31    pub(crate) fn texture(&self) -> &RenderedTexture {
32        &self.texture
33    }
34
35    pub(crate) fn flush_uniforms(&self, queue: &wgpu::Queue) {
36        self.uniforms.flush(queue);
37    }
38}
39
40impl Renderer {
41    /// A deterministic key for the graph and the settings that affect its pixels (blend space,
42    /// applied quality controls, intermediate format). Adapters that store pictures alike give
43    /// equal keys.
44    ///
45    /// # Errors
46    /// Returns [`GraphError::MissingOutput`] when no output was selected.
47    pub fn graph_cache_key(&self, graph: &RenderGraph<'_>) -> Result<RenderCacheKey, GraphError> {
48        let quality = self.quality_controls();
49        let plan = graph.compile_with_quality(quality)?;
50        Ok(renderer_cache_key(
51            plan.cache_key,
52            graph.blend_space.unwrap_or(self.blend_space).shader_value(),
53            quality,
54            self.intermediate_format(),
55        ))
56    }
57
58    /// Initializes all pipelines referenced by one graph.
59    ///
60    /// # Errors
61    /// Returns graph validation errors, or diagnostics for an unknown effect or a failed pipeline.
62    pub fn warmup_graph(&self, graph: &RenderGraph<'_>) -> Result<WarmupReport, ShaderDiagnostics> {
63        self.warmup_graphs(&[graph])
64    }
65
66    /// Initializes the deduplicated pipeline set referenced by project graphs.
67    ///
68    /// # Errors
69    /// Returns diagnostics for a malformed graph, an unknown effect or a failed pipeline.
70    pub fn warmup_graphs(
71        &self,
72        graphs: &[&RenderGraph<'_>],
73    ) -> Result<WarmupReport, ShaderDiagnostics> {
74        let mut effects = Vec::<EffectId>::new();
75        let mut seen = HashSet::<EffectId>::new();
76        let mut needs_composite = false;
77        let mut composite_layers = Vec::<usize>::new();
78        let mut vector_spaces = Vec::<crate::BlendSpace>::new();
79        for graph in graphs {
80            let plan = graph
81                .compile()
82                .map_err(|error| ShaderDiagnostics::error(error.to_string()))?;
83            for node in plan.order {
84                match &graph.nodes[node.index] {
85                    RenderNode::Effect { effect, .. }
86                    | RenderNode::Transition { effect, .. }
87                    | RenderNode::Generator { effect, .. } => {
88                        if seen.insert(effect.clone()) {
89                            effects.push(effect.clone());
90                        }
91                    }
92                    RenderNode::Composite { layers, .. } => {
93                        needs_composite = true;
94                        composite_layers.push(layers.len());
95                    }
96                    RenderNode::Vector { .. } => {
97                        let space = graph.blend_space.unwrap_or(self.blend_space);
98                        if !vector_spaces.contains(&space) {
99                            vector_spaces.push(space);
100                        }
101                    }
102                    RenderNode::Source(_) => {}
103                }
104            }
105        }
106        self.warmup(&effects)?;
107        let failed = |error: crate::RenderError| ShaderDiagnostics::error(error.to_string());
108        for layers in composite_layers {
109            self.warm_composite(layers).map_err(failed)?;
110        }
111        for space in &vector_spaces {
112            self.warm_vector(*space).map_err(failed)?;
113        }
114        Ok(WarmupReport {
115            runtime_effects: effects.len(),
116            builtins: usize::from(needs_composite) + usize::from(!vector_spaces.is_empty()),
117        })
118    }
119
120    /// Executes the reachable portion of a graph and returns its owned output.
121    ///
122    /// # Errors
123    /// Returns a structural error or the first rendering failure.
124    #[allow(clippy::too_many_lines)]
125    pub fn execute_graph(&self, graph: &RenderGraph<'_>) -> Result<RenderedTexture, GraphError> {
126        let mut command_encoder = self.command_encoder("alpha2 render graph encoder");
127        let graph_work = self.encode_graph(graph, &mut command_encoder)?;
128        graph_work.flush_uniforms(self.gpu.queue());
129        self.submit([command_encoder.finish()])
130            .map_err(GraphError::Render)?;
131        Ok(self.complete_graph_work(graph_work, true))
132    }
133
134    #[allow(clippy::too_many_lines)]
135    pub(crate) fn encode_graph(
136        &self,
137        graph: &RenderGraph<'_>,
138        encoder: &mut crate::renderer::RenderEncoder,
139    ) -> Result<EncodedGraph, GraphError> {
140        self.validate_size(graph.size)?;
141        let plan = graph.compile()?;
142        if matches!(graph.nodes[plan.output.index], RenderNode::Source(_)) {
143            return Err(GraphError::SourceOutput);
144        }
145        let format = self.intermediate_format();
146        let uniform_alignment = u64::from(self.limits.min_uniform_buffer_offset_alignment.max(1));
147        let uniform_capacity = graph_uniform_capacity(self, graph, &plan.order, uniform_alignment);
148        let mut uniforms = self
149            .uniform_buffers
150            .acquire(self.gpu.device(), uniform_capacity);
151        let mut outputs: Vec<Option<RenderedTexture>> =
152            (0..graph.nodes.len()).map(|_| None).collect();
153        let blend_space = graph.blend_space.unwrap_or(self.blend_space).shader_value();
154        let cached = self.cached_results(graph, &plan.order, plan.output, blend_space);
155        let pixels = u64::from(graph.size.width) * u64::from(graph.size.height);
156        let predicted = plan
157            .order
158            .iter()
159            .filter(|node| cached.hits[node.index].is_none() && cached.needed[node.index])
160            .fold(crate::FrameCost::default(), |mut total, node| {
161                if let Some(cost) = self.node_cost(&graph.nodes[node.index]) {
162                    total.add(cost, pixels);
163                }
164                total
165            });
166        self.plan_submissions(encoder, predicted);
167        if encoder.planner().is_planned() {
168            self.pilot_passes(
169                plan.order
170                    .iter()
171                    .filter(|node| cached.hits[node.index].is_none() && cached.needed[node.index])
172                    .map(|node| &graph.nodes[node.index]),
173                graph.size,
174            );
175        }
176        let mut pending_timings = Vec::<PendingEffectTiming>::new();
177        let mut encoded_nodes = 0_u64;
178        let mut encoded_render_passes = 0_u64;
179        let mut cache_inserts = Vec::new();
180        let timing = self.pass_timing_epoch();
181        for (position, node_id) in plan.order.iter().copied().enumerate() {
182            let started = timing.map(|epoch| (epoch, Instant::now()));
183            if let Some(hit) = cached.hits[node_id.index].clone() {
184                outputs[node_id.index] = Some(hit);
185                release_inputs(graph, &plan.last_use, &mut outputs, node_id, position);
186                continue;
187            }
188            if !cached.needed[node_id.index] {
189                // A cache hit still releases its inputs where drawing would have.
190                release_inputs(graph, &plan.last_use, &mut outputs, node_id, position);
191                continue;
192            }
193            // Recorded for the report of a loss this submission causes.
194            if let RenderNode::Effect { effect, .. }
195            | RenderNode::Transition { effect, .. }
196            | RenderNode::Generator { effect, .. } = &graph.nodes[node_id.index]
197            {
198                self.submission_clock.note_effect(effect);
199            }
200            let output = match &graph.nodes[node_id.index] {
201                RenderNode::Source(_) => None,
202                RenderNode::Effect {
203                    effect,
204                    source,
205                    inputs,
206                    params,
207                    resources,
208                    runtime,
209                } => {
210                    if self
211                        .effect_definition(effect)
212                        .is_some_and(|definition| definition.kind != EffectKind::Effect)
213                    {
214                        return Err(GraphError::EffectKindMismatch);
215                    }
216                    let source_view = graph_view(graph, &outputs, *source)?;
217                    let input_views: Vec<(&str, &wgpu::TextureView)> = inputs
218                        .iter()
219                        .map(|(name, node)| Ok((name, graph_view(graph, &outputs, node)?)))
220                        .collect::<Result<_, GraphError>>()?;
221                    let target = self.textures.acquire(
222                        self.gpu.device(),
223                        graph.size,
224                        format,
225                        "alpha2 graph effect target",
226                    );
227                    if let Some(pending) = self.encode_effect_pass(
228                        encoder,
229                        EffectPass {
230                            id: effect,
231                            kind: crate::RenderNodeKind::Effect,
232                            source_a: source_view,
233                            source_b: None,
234                            inputs: &input_views,
235                            size: graph.size,
236                            params,
237                            resources,
238                            runtime: *runtime,
239                            output: target.view(),
240                        },
241                        &mut uniforms,
242                    )? {
243                        pending_timings.push(pending);
244                    }
245                    encoded_render_passes = encoded_render_passes.saturating_add(1);
246                    Some(RenderedTexture::pooled(graph.size, format, target))
247                }
248                RenderNode::Transition {
249                    effect,
250                    from,
251                    to,
252                    params,
253                    resources,
254                    runtime,
255                } => {
256                    if self
257                        .effect_definition(effect)
258                        .is_some_and(|definition| definition.kind != EffectKind::Transition)
259                    {
260                        return Err(GraphError::EffectKindMismatch);
261                    }
262                    let from_view = graph_view(graph, &outputs, *from)?;
263                    let to_view = graph_view(graph, &outputs, *to)?;
264                    let target = self.textures.acquire(
265                        self.gpu.device(),
266                        graph.size,
267                        format,
268                        "alpha2 graph transition target",
269                    );
270                    if let Some(pending) = self.encode_effect_pass(
271                        encoder,
272                        EffectPass {
273                            id: effect,
274                            kind: crate::RenderNodeKind::Transition,
275                            source_a: from_view,
276                            source_b: Some(to_view),
277                            inputs: &[],
278                            size: graph.size,
279                            params,
280                            resources,
281                            runtime: *runtime,
282                            output: target.view(),
283                        },
284                        &mut uniforms,
285                    )? {
286                        pending_timings.push(pending);
287                    }
288                    encoded_render_passes = encoded_render_passes.saturating_add(1);
289                    Some(RenderedTexture::pooled(graph.size, format, target))
290                }
291                RenderNode::Generator {
292                    effect,
293                    params,
294                    resources,
295                    runtime,
296                } => {
297                    if self
298                        .effect_definition(effect)
299                        .is_some_and(|definition| definition.kind != EffectKind::Generator)
300                    {
301                        return Err(GraphError::EffectKindMismatch);
302                    }
303                    let target = self.textures.acquire(
304                        self.gpu.device(),
305                        graph.size,
306                        format,
307                        "alpha2 graph generator target",
308                    );
309                    // A generator samples nothing, but its bindings still need a texture.
310                    if let Some(pending) = self.encode_effect_pass(
311                        encoder,
312                        EffectPass {
313                            id: effect,
314                            kind: crate::RenderNodeKind::Generator,
315                            source_a: &self.empty_input,
316                            source_b: None,
317                            inputs: &[],
318                            size: graph.size,
319                            params,
320                            resources,
321                            runtime: *runtime,
322                            output: target.view(),
323                        },
324                        &mut uniforms,
325                    )? {
326                        pending_timings.push(pending);
327                    }
328                    encoded_render_passes = encoded_render_passes.saturating_add(1);
329                    Some(RenderedTexture::pooled(graph.size, format, target))
330                }
331                RenderNode::Vector { scene } => {
332                    encoder.place_pass(crate::submission_planner::VECTOR_COST, pixels, false, None);
333                    let target = self.textures.acquire(
334                        self.gpu.device(),
335                        graph.size,
336                        format,
337                        "alpha2 graph vector target",
338                    );
339                    encoded_render_passes =
340                        encoded_render_passes.saturating_add(self.encode_vector(
341                            encoder,
342                            scene,
343                            graph.size,
344                            graph.blend_space.unwrap_or(self.blend_space),
345                            target.view(),
346                            &mut uniforms,
347                        )?);
348                    Some(RenderedTexture::pooled(graph.size, format, target))
349                }
350                RenderNode::Composite { layers, background } => {
351                    encoder.place_pass(
352                        crate::submission_planner::COMPOSITE_LAYER_COST
353                            .times(u64::try_from(layers.len()).unwrap_or(u64::MAX)),
354                        pixels,
355                        false,
356                        None,
357                    );
358                    let views = layers
359                        .iter()
360                        .map(|layer| graph_view(graph, &outputs, layer.source))
361                        .collect::<Result<Vec<_>, _>>()?;
362                    let composite_layers = layers
363                        .iter()
364                        .zip(&views)
365                        .map(|(layer, view)| CompositeLayer {
366                            texture: view,
367                            visual: layer.visual,
368                            blend_mode: layer.blend_mode,
369                        })
370                        .collect::<Vec<_>>();
371                    let target = self.textures.acquire(
372                        self.gpu.device(),
373                        graph.size,
374                        format,
375                        "alpha2 graph composite target",
376                    );
377                    encoded_render_passes =
378                        encoded_render_passes.saturating_add(self.encode_layers_pass(
379                            encoder,
380                            graph.size,
381                            &composite_layers,
382                            CompositeTarget {
383                                background: *background,
384                                blend_space: graph.blend_space.unwrap_or(self.blend_space),
385                                output: target.texture(),
386                                output_view: target.view(),
387                            },
388                            &mut uniforms,
389                        )?);
390                    Some(RenderedTexture::pooled(graph.size, format, target))
391                }
392            };
393            if let Some((epoch, started)) = started
394                && !matches!(graph.nodes[node_id.index], RenderNode::Source(_))
395            {
396                let label = graph.nodes[node_id.index].kind().pass_label();
397                crate::diagnostics::record_pass(
398                    &self.diagnostics,
399                    epoch,
400                    label,
401                    started.elapsed(),
402                    crate::TimingSource::CpuEncoding,
403                );
404            }
405            if let (Some(output), Some((key, pinned))) = (&output, cached.store[node_id.index]) {
406                cache_inserts.push((key, output.clone(), pinned));
407            }
408            outputs[node_id.index] = output;
409            if !matches!(graph.nodes[node_id.index], RenderNode::Source(_)) {
410                encoded_nodes = encoded_nodes.saturating_add(1);
411            }
412            release_inputs(graph, &plan.last_use, &mut outputs, node_id, position);
413        }
414
415        let texture = outputs[plan.output.index]
416            .take()
417            .ok_or(GraphError::SourceOutput)?;
418        Ok(EncodedGraph {
419            texture,
420            cache_inserts,
421            cache_clears: cached.clears,
422            uniforms,
423            pending_timings,
424            encoded_nodes,
425            encoded_render_passes,
426        })
427    }
428
429    /// Predicted per-pixel cost of drawing `node`; `None` for sources.
430    fn node_cost(&self, node: &RenderNode<'_>) -> Option<crate::effect_cost::EffectCost> {
431        match node {
432            RenderNode::Effect { effect, .. }
433            | RenderNode::Transition { effect, .. }
434            | RenderNode::Generator { effect, .. } => {
435                self.effects().get(effect).map(|registered| registered.cost)
436            }
437            RenderNode::Composite { layers, .. } => Some(
438                crate::submission_planner::COMPOSITE_LAYER_COST
439                    .times(u64::try_from(layers.len()).unwrap_or(u64::MAX)),
440            ),
441            RenderNode::Vector { .. } => Some(crate::submission_planner::VECTOR_COST),
442            RenderNode::Source(_) => None,
443        }
444    }
445
446    pub(crate) fn complete_graph_work(
447        &self,
448        encoded: EncodedGraph,
449        standalone_submission: bool,
450    ) -> RenderedTexture {
451        let EncodedGraph {
452            texture,
453            cache_inserts,
454            cache_clears,
455            uniforms,
456            pending_timings,
457            encoded_nodes,
458            encoded_render_passes,
459        } = encoded;
460        uniforms.recycle();
461        if !cache_inserts.is_empty() {
462            let mut cache = self.lock_result_cache();
463            // A clear since the lookup may have changed what these results should show.
464            if cache.clears() == cache_clears {
465                for (key, result, pinned) in &cache_inserts {
466                    cache.insert(*key, result, *pinned);
467                }
468            }
469        }
470        crate::diagnostics::record_graph_work(
471            &self.diagnostics,
472            encoded_nodes,
473            encoded_render_passes,
474            standalone_submission,
475        );
476        for timing in pending_timings {
477            timing.map_after_submit();
478        }
479        texture
480    }
481}
482
483fn graph_uniform_capacity(
484    renderer: &Renderer,
485    graph: &RenderGraph<'_>,
486    order: &[RenderNodeId],
487    alignment: u64,
488) -> u64 {
489    let mut capacity = 0_u64;
490    for node in order {
491        match &graph.nodes[node.index] {
492            RenderNode::Effect { effect, .. }
493            | RenderNode::Transition { effect, .. }
494            | RenderNode::Generator { effect, .. } => {
495                let params = renderer
496                    .effects()
497                    .get(effect)
498                    .map_or(0, |registered| registered.definition.params.len());
499                capacity = effect_uniform_end(capacity, params, alignment);
500            }
501            RenderNode::Composite { layers, .. } => {
502                let passes = renderer
503                    .composite_batch_count(layers.iter().map(|layer| layer.visual), graph.size);
504                for _ in 0..passes {
505                    capacity = aligned_uniform_end(
506                        capacity,
507                        float_uniform_bytes(BATCH_UNIFORM_FLOATS),
508                        alignment,
509                    );
510                }
511            }
512            RenderNode::Vector { scene } => {
513                let slices = scene
514                    .ops
515                    .iter()
516                    .filter(|op| !matches!(op, alpha2_geometry::VectorOp::PushLayer { .. }))
517                    .count()
518                    + 1;
519                for _ in 0..slices {
520                    capacity = aligned_uniform_end(
521                        capacity,
522                        crate::vector::VECTOR_UNIFORM_BYTES,
523                        alignment,
524                    );
525                }
526            }
527            RenderNode::Source(_) => {}
528        }
529    }
530    capacity
531}
532
533fn effect_uniform_end(cursor: u64, params: usize, alignment: u64) -> u64 {
534    let parameter_bytes = u64::try_from(param_uniform_bytes(params)).unwrap_or(u64::MAX);
535    let cursor = aligned_uniform_end(cursor, parameter_bytes, alignment);
536    aligned_uniform_end(
537        cursor,
538        float_uniform_bytes(RUNTIME_UNIFORM_WORDS),
539        alignment,
540    )
541}
542
543pub(crate) fn effect_uniform_capacity(params: usize, alignment: u64) -> u64 {
544    effect_uniform_end(0, params, alignment)
545}
546
547/// The texture a dependency is drawn from; `None` for a CPU source.
548fn graph_view<'a>(
549    graph: &'a RenderGraph<'_>,
550    outputs: &'a [Option<RenderedTexture>],
551    node: RenderNodeId,
552) -> Result<&'a wgpu::TextureView, GraphError> {
553    match &graph.nodes[node.index] {
554        RenderNode::Source(view) => view
555            .wgpu_view()
556            .ok_or(GraphError::Render(crate::RenderError::InvalidSource)),
557        _ => Ok(outputs[node.index]
558            .as_ref()
559            .expect("compiled dependency has an output")
560            .view()),
561    }
562}
563
564/// Returns to the pool the results `node` was the last to read.
565fn release_inputs(
566    graph: &RenderGraph<'_>,
567    last_use: &[Option<usize>],
568    outputs: &mut [Option<RenderedTexture>],
569    node: RenderNodeId,
570    position: usize,
571) {
572    for dependency in graph.nodes[node.index].dependencies() {
573        if last_use[dependency.index] == Some(position) {
574            outputs[dependency.index] = None;
575        }
576    }
577}
578
579/// Cache hits, results to keep, and nodes still to draw for one graph.
580struct CachedResults {
581    hits: Vec<Option<RenderedTexture>>,
582    store: Vec<Option<(RenderCacheKey, bool)>>,
583    needed: Vec<bool>,
584    /// The cache's clear count read with the lookups.
585    clears: u64,
586}
587
588impl Renderer {
589    /// Looks up cache candidates and marks which nodes hits make unnecessary. With the cache off or
590    /// no candidates, everything is drawn and nothing kept.
591    fn cached_results(
592        &self,
593        graph: &RenderGraph<'_>,
594        order: &[RenderNodeId],
595        output: RenderNodeId,
596        blend_space: f32,
597    ) -> CachedResults {
598        let count = graph.nodes.len();
599        let mut cached = CachedResults {
600            hits: vec![None; count],
601            store: vec![None; count],
602            needed: vec![true; count],
603            clears: 0,
604        };
605        if graph.intents.iter().all(Option::is_none) {
606            return cached;
607        }
608        let mut cache = self.lock_result_cache();
609        if !cache.enabled() {
610            return cached;
611        }
612        cached.clears = cache.clears();
613        let eligibility = graph.eligibility();
614        let (mut hits, mut misses, mut ineligible) = (0, 0, 0);
615        // From the output down: look a node up only if still needed; a hit's inputs are then needed
616        // only by others.
617        cached.needed = vec![false; count];
618        cached.needed[output.index] = true;
619        for node in order.iter().rev() {
620            if !cached.needed[node.index] {
621                continue;
622            }
623            if let Some(intent) = graph.intents[node.index] {
624                if eligibility[node.index] == crate::CacheEligibility::Eligible {
625                    let key = renderer_node_key(graph.cache_keys[node.index], blend_space);
626                    let pinned = intent == crate::CacheIntent::Pin;
627                    if let Some(texture) = cache.get(key, pinned) {
628                        cached.hits[node.index] = Some(texture);
629                        hits += 1;
630                        continue;
631                    }
632                    cached.store[node.index] = Some((key, pinned));
633                    misses += 1;
634                } else if intent != crate::CacheIntent::Bypass {
635                    ineligible += 1;
636                }
637            }
638            for input in graph.nodes[node.index].dependencies() {
639                cached.needed[input.index] = true;
640            }
641        }
642        let skipped = order
643            .iter()
644            .filter(|node| {
645                !cached.needed[node.index]
646                    && cached.hits[node.index].is_none()
647                    && !matches!(graph.nodes[node.index], RenderNode::Source(_))
648            })
649            .count() as u64;
650        cache.record(hits, misses, ineligible, skipped);
651        cached
652    }
653}