Skip to main content

alpha2_render/
composite.rs

1use crate::bind_group::OffsetBindGroup;
2use crate::effect_cost::EffectCost;
3use crate::{
4    BlendMode, Color, GraphError, GraphLayer, RenderError, RenderGraph, RenderSize,
5    RenderedTexture, Renderer, SourceView,
6    pipeline::CachedCompositePipeline,
7    uniform::{BATCH_UNIFORM_FLOATS, UniformArenaLease, float_uniform_bytes},
8};
9use alpha2_shaders::COMPOSITE_WGSL;
10
11/// Most layers per composite pass (`BATCH_LAYERS` in composite.wesl). With the backdrop this
12/// stays within the 16 sampled textures per stage of a WebGL2-class device.
13pub(crate) const COMPOSITE_BATCH_LAYERS: usize = 8;
14
15/// Placement and opacity of one composited layer.
16#[derive(Copy, Clone, Debug, PartialEq)]
17pub struct LayerTransform {
18    /// Normalized output translation, as `[x, y]`.
19    pub position: [f32; 2],
20    /// Normalized source anchor, as `[x, y]`.
21    pub anchor: [f32; 2],
22    /// Per-axis scale, as `[x, y]`.
23    pub scale: [f32; 2],
24    /// Clockwise rotation in degrees.
25    pub rotation_degrees: f32,
26    /// Opacity from zero to one.
27    pub opacity: f32,
28}
29
30/// One decoded, premultiplied sRGB layer and its presentation controls.
31#[derive(Copy, Clone, Debug)]
32#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
33pub struct CompositeLayer<'a> {
34    /// Source texture sampled by this layer.
35    pub texture: &'a wgpu::TextureView,
36    /// Layer transform and opacity.
37    pub visual: LayerTransform,
38    /// Artistic blend operation evaluated before source-over coverage.
39    pub blend_mode: BlendMode,
40}
41
42#[derive(Clone, Copy)]
43pub(crate) struct CompositeTarget<'a> {
44    /// Composited over by the first layer; transparent when `None`.
45    pub(crate) background: Option<Color>,
46    pub(crate) blend_space: crate::BlendSpace,
47    pub(crate) output: &'a wgpu::Texture,
48    pub(crate) output_view: &'a wgpu::TextureView,
49}
50
51impl Renderer {
52    /// Composites layers in slice order onto a transparent RGBA target.
53    ///
54    /// Inputs and output are premultiplied sRGB; blending uses the renderer's
55    /// [`crate::BlendSpace`].
56    ///
57    /// # Errors
58    /// Returns [`RenderError::InvalidVisual`] for non-finite or out-of-range layer values. A
59    /// zero-scale layer is valid and draws nothing.
60    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
61    pub fn render_layers(
62        &self,
63        size: RenderSize,
64        layers: &[CompositeLayer<'_>],
65    ) -> Result<RenderedTexture, RenderError> {
66        let mut graph = RenderGraph::new(size);
67        let mut graph_layers = Vec::with_capacity(layers.len());
68        for layer in layers {
69            graph_layers.push(GraphLayer {
70                source: graph.add_source(SourceView::from_wgpu(layer.texture)),
71                visual: layer.visual,
72                blend_mode: layer.blend_mode,
73            });
74        }
75        let output = graph
76            .add_composite(graph_layers)
77            .map_err(GraphError::into_render_error)?;
78        graph
79            .set_output(output)
80            .map_err(GraphError::into_render_error)?;
81        self.execute_graph(&graph)
82            .map_err(GraphError::into_render_error)
83    }
84
85    /// Composites `layers` over `background` into `output`, returning the passes encoded.
86    ///
87    /// Layers that miss the target or have zero opacity are skipped. Small layers batch up to
88    /// [`Self::composite_batch_layers`] per pass and always draw with the loop pipeline, so a lone
89    /// small layer and a batch run identical code. Large layers get their own one-layer pass.
90    /// The first pass clears to the background; a later batch covering half the target or more
91    /// ping-pongs full-frame between two textures, while a smaller one draws in place, scissored,
92    /// over a copy of its region.
93    #[allow(clippy::too_many_lines)]
94    pub(crate) fn encode_layers_pass(
95        &self,
96        encoder: &mut crate::renderer::RenderEncoder,
97        size: RenderSize,
98        layers: &[CompositeLayer<'_>],
99        prepared: &crate::prepared_frame::PreparedComposite,
100        target: CompositeTarget<'_>,
101        uniforms: &mut UniformArenaLease,
102    ) -> Result<u64, RenderError> {
103        let CompositeTarget {
104            background,
105            blend_space,
106            output,
107            output_view,
108        } = target;
109        for layer in layers {
110            validate_visual(layer.visual)?;
111        }
112        let format = self.intermediate_format();
113        let drawn = prepared
114            .drawn
115            .iter()
116            .map(|(index, bounds, tier)| (&layers[*index], *bounds, *tier))
117            .collect::<Vec<_>>();
118        let background = stored_background(background, format);
119        if drawn.is_empty() {
120            // What a first layer writes where it does not reach, so an empty canvas matches.
121            clear_target(encoder, output_view, background);
122            return Ok(1);
123        }
124
125        let cached = self.composite_pipeline()?;
126        let preparation = BatchPreparationContext {
127            renderer: self,
128            layout: &cached.bind_group_layout,
129            no_backdrop: &self.empty_input,
130            blend_space,
131            max_filter_samples: self.quality_controls().max_filter_samples,
132            output_size: size,
133            background,
134        };
135        let batches = prepared
136            .batches
137            .iter()
138            .map(|batch| (&drawn[batch.layers.clone()], batch))
139            .collect::<Vec<_>>();
140        let bounded = |bounds: &PixelRect| under_half(*bounds, size);
141        let ((first, first_batch), rest) = batches.split_first().expect("a layer is drawn");
142        let first_program = self.batch_program(first);
143        let first = prepare_batch(&preparation, None, first, uniforms)?;
144        // The clear writes the stored background, so a small first batch can draw only inside its
145        // bounds.
146        let first_pass = PassTarget {
147            load: wgpu::LoadOp::Clear(stored_color(background)),
148            scissor: bounded(&first_batch.bounds).then_some(first_batch.bounds),
149        };
150        if rest.is_empty() {
151            self.draw_batch(
152                encoder,
153                cached,
154                first_program,
155                &first,
156                (first_batch, prepared.pass),
157                (output_view, first_pass),
158                None,
159            )?;
160            return Ok(1);
161        }
162
163        let scratch = self.textures.acquire(
164            self.gpu.device(),
165            size,
166            format,
167            "alpha2 layer composition scratch",
168        );
169        let textures = [output, scratch.texture()];
170        let views = [output_view, scratch.view()];
171        // Each full-frame batch flips the target; start so the last one lands in `output`.
172        let mut current = rest
173            .iter()
174            .filter(|(_, batch)| !bounded(&batch.bounds))
175            .count()
176            % 2;
177        self.draw_batch(
178            encoder,
179            cached,
180            first_program,
181            &first,
182            (first_batch, prepared.pass),
183            (views[current], first_pass),
184            None,
185        )?;
186        for (layers, batch) in rest {
187            let other = 1 - current;
188            let program = self.batch_program(layers);
189            if bounded(&batch.bounds) {
190                let prepared_batch =
191                    prepare_batch(&preparation, Some(views[other]), layers, uniforms)?;
192                // A pass cannot read the texture it writes, so copy the backdrop region aside
193                // first.
194                self.draw_batch(
195                    encoder,
196                    cached,
197                    program,
198                    &prepared_batch,
199                    (batch, prepared.pass),
200                    (
201                        views[current],
202                        PassTarget {
203                            load: wgpu::LoadOp::Load,
204                            scissor: Some(batch.bounds),
205                        },
206                    ),
207                    Some((textures[current], textures[other])),
208                )?;
209            } else {
210                let prepared_batch =
211                    prepare_batch(&preparation, Some(views[current]), layers, uniforms)?;
212                self.draw_batch(
213                    encoder,
214                    cached,
215                    program,
216                    &prepared_batch,
217                    (batch, prepared.pass),
218                    (views[other], PassTarget::WHOLE),
219                    None,
220                )?;
221                current = other;
222            }
223        }
224        debug_assert_eq!(current, 0);
225        Ok(u64::try_from(batches.len()).unwrap_or(u64::MAX))
226    }
227
228    /// The program a batch draws with; a multi-layer batch always uses the loop.
229    fn batch_program(
230        &self,
231        batch: &[(&CompositeLayer<'_>, PixelRect, LayerTier)],
232    ) -> (CompositeProgram, LayerTier, usize) {
233        let tier = batch[0].2;
234        debug_assert!(batch.iter().all(|(_, _, other)| *other == tier));
235        let program = self.composite_program(tier);
236        debug_assert!(batch.len() == 1 || program == CompositeProgram::Loop);
237        (program, tier, batch.len())
238    }
239
240    #[allow(clippy::too_many_arguments)]
241    fn draw_batch(
242        &self,
243        encoder: &mut crate::renderer::RenderEncoder,
244        cached: &CachedCompositePipeline,
245        (program, tier, layers): (CompositeProgram, LayerTier, usize),
246        bind_group: &OffsetBindGroup<1>,
247        (batch, key): (&crate::prepared_frame::PreparedBatch, alpha2_gpu::PassKey),
248        (target, pass): (&wgpu::TextureView, PassTarget),
249        backdrop: Option<(&wgpu::Texture, &wgpu::Texture)>,
250    ) -> Result<(), RenderError> {
251        let pipeline = self.composite_program_pipeline(cached, program)?;
252        #[cfg(not(test))]
253        let _ = (tier, layers);
254        let placement = encoder.place_pass(batch.work, batch.region, true, Some(key), None);
255        if let Some((from, to)) = backdrop {
256            copy_region(encoder, from, to, batch.bounds);
257        }
258        encoder.encode_pieces(placement, batch.region, |encoder, piece| {
259            #[cfg(test)]
260            {
261                let mut log = self
262                    .composite_pipelines
263                    .lock()
264                    .unwrap_or_else(std::sync::PoisonError::into_inner);
265                log.passes += 1;
266                log.drawn
267                    .insert((program, pipeline.clone(), tier, layers > 1));
268            }
269            let piece = PassTarget {
270                load: if piece.first {
271                    pass.load
272                } else {
273                    wgpu::LoadOp::Load
274                },
275                scissor: piece.scissor.or(pass.scissor),
276            };
277            encode_batch(
278                encoder,
279                pipeline,
280                (bind_group, &self.linear_sampler),
281                target,
282                piece,
283            );
284        });
285        Ok(())
286    }
287
288    /// Whether small layers are batched and drawn with the loop pipeline: on a GPU, and in tests
289    /// that set `composite_batch_limit`.
290    pub(crate) fn batches_small_layers(&self) -> bool {
291        #[cfg(test)]
292        {
293            if self
294                .composite_batch_limit
295                .load(std::sync::atomic::Ordering::Relaxed)
296                > 0
297            {
298                return true;
299            }
300        }
301        !self.gpu.capabilities().software_rasterizer
302    }
303
304    /// The program for a layer of `tier`: the loop for small layers when batching, otherwise the
305    /// one-layer program.
306    ///
307    /// Small layers always use the loop, alone or batched, because Metal, D3D12 and GL compilers
308    /// contract two separate programs differently and the stored bytes differ in the last bit.
309    /// Software rasterizers execute every branch, so they never batch.
310    pub(crate) fn composite_program(&self, tier: LayerTier) -> CompositeProgram {
311        if tier == LayerTier::Small && self.batches_small_layers() {
312            CompositeProgram::Loop
313        } else {
314            CompositeProgram::OneLayer
315        }
316    }
317
318    /// Most layers per composite pass: [`COMPOSITE_BATCH_LAYERS`] on a GPU, one on a software
319    /// rasterizer, or `composite_batch_limit` in tests.
320    ///
321    /// A GPU runs a layer's step only on quads overlapping it, so batching saves passes, barriers
322    /// and backdrop copies. A software rasterizer pays for the whole batch area per layer.
323    pub(crate) fn composite_batch_layers(&self) -> usize {
324        #[cfg(test)]
325        {
326            let limit = self
327                .composite_batch_limit
328                .load(std::sync::atomic::Ordering::Relaxed);
329            if limit > 0 {
330                return limit.min(COMPOSITE_BATCH_LAYERS);
331            }
332        }
333        if self.batches_small_layers() {
334            COMPOSITE_BATCH_LAYERS
335        } else {
336            1
337        }
338    }
339
340    /// Shader and layout shared by both composite pipelines, created on first use.
341    pub(crate) fn composite_pipeline(&self) -> Result<&CachedCompositePipeline, RenderError> {
342        let device = self.gpu.device();
343        crate::gpu_errors::checked_cell(&self.pipelines.composite, device, || {
344            let bind_group_layout = batch_layout(device);
345            let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
346                label: Some("alpha2 layer composite shader"),
347                source: wgpu::ShaderSource::Wgsl(COMPOSITE_WGSL.into()),
348            });
349            CachedCompositePipeline {
350                bind_group_layout,
351                shader,
352                programs: Default::default(),
353            }
354        })
355    }
356
357    pub(crate) fn composite_program_pipeline<'a>(
358        &self,
359        cached: &'a CachedCompositePipeline,
360        program: CompositeProgram,
361    ) -> Result<&'a wgpu::RenderPipeline, RenderError> {
362        let (slot, entry, label) = match program {
363            CompositeProgram::Loop => (0, "fs", "alpha2 small layer composite pipeline"),
364            CompositeProgram::OneLayer => (1, "fs_layer", "alpha2 large layer composite pipeline"),
365        };
366        if let Some(pipeline) = cached.programs[slot].get() {
367            return Ok(pipeline);
368        }
369        #[cfg(test)]
370        let entry = if self
371            .fail_next_pipeline
372            .swap(false, std::sync::atomic::Ordering::Relaxed)
373        {
374            "an_entry_point_the_shader_lacks"
375        } else {
376            entry
377        };
378        let created = crate::diagnostics::timed_pipeline_creation(
379            &self.diagnostics,
380            || label.to_owned(),
381            || {
382                crate::gpu_errors::create_checked(self.gpu.device(), || {
383                    composite_pipeline(
384                        self.gpu.device(),
385                        [&cached.bind_group_layout, &self.linear_sampler.layout],
386                        &cached.shader,
387                        self.intermediate_format(),
388                        entry,
389                        label,
390                    )
391                })
392            },
393        )
394        .map_err(|kind| RenderError::Gpu { kind })?;
395        #[cfg(test)]
396        {
397            self.composite_pipelines
398                .lock()
399                .unwrap_or_else(std::sync::PoisonError::into_inner)
400                .created
401                .push(program);
402        }
403        Ok(cached.programs[slot].get_or_init(|| created))
404    }
405
406    /// Drawn layers by index with their reachable target pixels and tier; skips layers that miss
407    /// or have zero opacity.
408    #[cfg_attr(not(test), allow(clippy::unused_self))]
409    pub(crate) fn drawn_layers(
410        &self,
411        visuals: impl Iterator<Item = LayerTransform>,
412        size: RenderSize,
413    ) -> Vec<(usize, PixelRect, LayerTier)> {
414        #[cfg(test)]
415        let full_frame = self
416            .full_frame_layers
417            .load(std::sync::atomic::Ordering::Relaxed);
418        #[cfg(not(test))]
419        let full_frame = false;
420        visuals
421            .enumerate()
422            .filter_map(|(index, visual)| {
423                if is_degenerate(visual) || is_invisible(visual) {
424                    return None;
425                }
426                let bounds = layer_bounds(visual, size);
427                // Drawn full-frame in tests, a layer keeps its bounded tier so the pipeline
428                // matches.
429                let tier = LayerTier::of(bounds.unwrap_or(PixelRect::EMPTY), size);
430                if full_frame {
431                    Some((index, PixelRect::whole(size), tier))
432                } else {
433                    bounds.map(|bounds| (index, bounds, tier))
434                }
435            })
436            .collect()
437    }
438
439    pub(crate) fn warm_composite(&self, layers: usize) -> Result<(), RenderError> {
440        if layers == 0 {
441            return Ok(());
442        }
443        let cached = self.composite_pipeline()?;
444        self.composite_program_pipeline(cached, CompositeProgram::OneLayer)?;
445        if self.batches_small_layers() {
446            self.composite_program_pipeline(cached, CompositeProgram::Loop)?;
447        }
448        Ok(())
449    }
450}
451
452/// A drawn layer's size class. It alone decides both batching ([`composite_batches`]) and the
453/// program ([`Renderer::composite_program`]), so the two cannot disagree.
454#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
455pub(crate) enum LayerTier {
456    /// Bounds under half the target: may share a pass.
457    Small,
458    /// Bounds of half the target or more: always a pass of its own.
459    Large,
460}
461
462impl LayerTier {
463    pub(crate) fn of(bounds: PixelRect, size: RenderSize) -> Self {
464        if under_half(bounds, size) {
465            Self::Small
466        } else {
467            Self::Large
468        }
469    }
470}
471
472fn under_half(bounds: PixelRect, size: RenderSize) -> bool {
473    bounds.area() * 2 < PixelRect::whole(size).area()
474}
475
476/// Entry points of composite.wesl sharing `composite_layer`.
477#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
478pub(crate) enum CompositeProgram {
479    /// `fs`: the pass's layers in a loop, count in a uniform.
480    Loop,
481    /// `fs_layer`: one layer, no loop.
482    OneLayer,
483}
484
485/// Test-only record of composite pipelines created and drawn with.
486#[cfg(test)]
487#[derive(Debug, Default)]
488pub(crate) struct CompositePipelineLog {
489    pub(crate) created: Vec<CompositeProgram>,
490    pub(crate) passes: usize,
491    /// Distinct (program, pipeline, tier, multi-layer) combinations drawn.
492    pub(crate) drawn:
493        std::collections::HashSet<(CompositeProgram, wgpu::RenderPipeline, LayerTier, bool)>,
494}
495
496/// Groups drawn layers, in order, into passes, each with the union of its layers' bounds.
497///
498/// Only [`LayerTier::Small`] layers share a pass, up to `limit`. Batching saves a small layer's
499/// pass, barrier and backdrop copy; a large layer would make every batched step run over its
500/// area, so it gets its own pass.
501pub(crate) fn composite_batches<T>(
502    drawn: &[(T, PixelRect, LayerTier)],
503    limit: usize,
504) -> Vec<(std::ops::Range<usize>, PixelRect)> {
505    let mut batches: Vec<(std::ops::Range<usize>, PixelRect)> = Vec::new();
506    for (index, (_, bounds, tier)) in drawn.iter().enumerate() {
507        match batches.last_mut() {
508            Some((range, union))
509                if range.len() < limit
510                    && *tier == LayerTier::Small
511                    && drawn[range.start].2 == LayerTier::Small =>
512            {
513                range.end = index + 1;
514                *union = union.union(*bounds);
515            }
516            _ => batches.push((index..index + 1, *bounds)),
517        }
518    }
519    batches
520}
521
522pub(crate) const COMPOSITE_PASS_COST: EffectCost = EffectCost::fixed(1, 0);
523pub(crate) const COMPOSITE_SAMPLE_COST: EffectCost = EffectCost::fixed(1, 0);
524pub(crate) const COMPOSITE_BLEND_COST: EffectCost = EffectCost::fixed(0, 6);
525
526pub(crate) fn batch_region(bounds: PixelRect, size: RenderSize) -> PixelRect {
527    if under_half(bounds, size) {
528        bounds
529    } else {
530        PixelRect::whole(size)
531    }
532}
533
534/// Mirrors `filtered_source` in composite.wesl.
535#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
536pub(crate) fn layer_samples(
537    visual: LayerTransform,
538    texture: RenderSize,
539    size: RenderSize,
540    max_filter_samples: u32,
541) -> u64 {
542    let (turn_sin, turn_cos) = libm::sincos(f64::from(visual.rotation_degrees).to_radians());
543    let (output_width, output_height) = (f64::from(size.width), f64::from(size.height));
544    let (scale_x, scale_y) = (f64::from(visual.scale[0]), f64::from(visual.scale[1]));
545    let (texture_width, texture_height) = (f64::from(texture.width), f64::from(texture.height));
546    let wanted = |x: f64, y: f64| {
547        (libm::hypot(x * texture_width, y * texture_height) - 0.0001)
548            .ceil()
549            .clamp(1.0, 8.0)
550    };
551    let wanted_x = wanted(
552        turn_cos / output_width / scale_x,
553        -turn_sin / output_height / scale_y,
554    );
555    let wanted_y = wanted(
556        turn_sin / output_width / scale_x,
557        turn_cos / output_height / scale_y,
558    );
559    let budget = f64::from(max_filter_samples).clamp(1.0, 64.0);
560    let columns = wanted_x.min(budget);
561    let rows = wanted_y.min((budget / columns).floor().max(1.0));
562    if (columns * rows).is_finite() {
563        (columns * rows) as u64
564    } else {
565        1
566    }
567}
568
569/// How the intermediate stores a value; the shader rounds to match (`STORED_FORMAT`).
570#[derive(Copy, Clone, Debug)]
571enum StoredValue {
572    /// Kept as computed.
573    AsIs,
574    /// Rounded to a half float.
575    Half,
576    /// Rounded to an 8-bit unorm code.
577    Unorm8,
578}
579
580impl StoredValue {
581    fn of(format: wgpu::TextureFormat) -> Self {
582        match format {
583            wgpu::TextureFormat::Rgba16Float => Self::Half,
584            wgpu::TextureFormat::Rgba8Unorm => Self::Unorm8,
585            _ => Self::AsIs,
586        }
587    }
588
589    const fn shader_value(self) -> f64 {
590        match self {
591            Self::AsIs => 0.0,
592            Self::Half => 1.0,
593            Self::Unorm8 => 2.0,
594        }
595    }
596}
597
598struct BatchPreparationContext<'a> {
599    renderer: &'a crate::Renderer,
600    layout: &'a wgpu::BindGroupLayout,
601    /// Bound as the first pass's backdrop, which composites over `background` and reads nothing.
602    no_backdrop: &'a wgpu::TextureView,
603    blend_space: crate::BlendSpace,
604    max_filter_samples: u32,
605    output_size: RenderSize,
606    background: [f32; 4],
607}
608
609/// Writes a batch's `BatchParams` and binds its textures, filling unused slots with the first
610/// layer's. Without `backdrop` the batch composites over the background.
611fn prepare_batch(
612    context: &BatchPreparationContext<'_>,
613    backdrop: Option<&wgpu::TextureView>,
614    batch: &[(&CompositeLayer<'_>, PixelRect, LayerTier)],
615    uniforms: &mut UniformArenaLease,
616) -> Result<OffsetBindGroup<1>, RenderError> {
617    debug_assert!(!batch.is_empty() && batch.len() <= COMPOSITE_BATCH_LAYERS);
618    let mut values = [0.0_f32; BATCH_UNIFORM_FLOATS];
619    #[allow(clippy::cast_precision_loss)]
620    let controls = [
621        context.blend_space.shader_value(),
622        context.max_filter_samples as f32,
623        batch.len() as f32,
624        if backdrop.is_some() { 0.0 } else { 1.0 },
625        context.output_size.width as f32,
626        context.output_size.height as f32,
627        0.0,
628        0.0,
629        context.background[0],
630        context.background[1],
631        context.background[2],
632        context.background[3],
633    ];
634    values[..controls.len()].copy_from_slice(&controls);
635    for ((layer, bounds, _), slot) in batch
636        .iter()
637        .zip(values[controls.len()..].as_chunks_mut::<16>().0)
638    {
639        let visual = layer.visual;
640        #[allow(clippy::cast_precision_loss)]
641        slot.copy_from_slice(&[
642            visual.position[0],
643            visual.position[1],
644            visual.anchor[0],
645            visual.anchor[1],
646            visual.scale[0],
647            visual.scale[1],
648            visual.rotation_degrees.to_radians(),
649            visual.opacity,
650            layer.blend_mode.shader_value(),
651            0.0,
652            0.0,
653            0.0,
654            bounds.x as f32,
655            bounds.y as f32,
656            (bounds.x + bounds.width) as f32,
657            (bounds.y + bounds.height) as f32,
658        ]);
659    }
660    let uniform = uniforms.write(bytemuck::cast_slice(&values))?;
661    let texture = |slot: usize| {
662        let (layer, _, _) = batch.get(slot).unwrap_or(&batch[0]);
663        layer.texture
664    };
665    let mut entries = arrayvec::ArrayVec::<_, { COMPOSITE_BATCH_LAYERS + 2 }>::new();
666    entries.extend(
667        (0..COMPOSITE_BATCH_LAYERS).map(|slot| wgpu::BindGroupEntry {
668            binding: u32::try_from(slot).expect("few layer slots"),
669            resource: wgpu::BindingResource::TextureView(texture(slot)),
670        }),
671    );
672    entries.push(wgpu::BindGroupEntry {
673        binding: BACKDROP_BINDING,
674        resource: wgpu::BindingResource::TextureView(backdrop.unwrap_or(context.no_backdrop)),
675    });
676    entries.push(wgpu::BindGroupEntry {
677        binding: UNIFORM_BINDING,
678        resource: uniforms.dynamic_binding(uniform.size()),
679    });
680    Ok(OffsetBindGroup {
681        group: context.renderer.bind_group(&wgpu::BindGroupDescriptor {
682            label: Some("alpha2 layer batch bind group"),
683            layout: context.layout,
684            entries: &entries,
685        }),
686        offsets: [uniform.dynamic_offset()],
687    })
688}
689
690/// Clears `target` to `stored`, a value its format holds exactly, so the clear matches what a
691/// layer pass writes for the same background.
692fn clear_target(encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, stored: [f32; 4]) {
693    let color = stored_color(stored);
694    let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
695        label: Some("alpha2 layer clear pass"),
696        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
697            view: target,
698            depth_slice: None,
699            resolve_target: None,
700            ops: wgpu::Operations {
701                load: wgpu::LoadOp::Clear(color),
702                store: wgpu::StoreOp::Store,
703            },
704        })],
705        depth_stencil_attachment: None,
706        timestamp_writes: None,
707        occlusion_query_set: None,
708        multiview_mask: None,
709    });
710}
711
712#[derive(Copy, Clone)]
713struct PassTarget {
714    load: wgpu::LoadOp<wgpu::Color>,
715    /// Only these pixels are drawn; the whole target when `None`.
716    scissor: Option<PixelRect>,
717}
718
719impl PassTarget {
720    /// Writes every pixel, so previous contents do not matter.
721    const WHOLE: Self = Self {
722        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
723        scissor: None,
724    };
725}
726
727/// A stored value as a clear color, exact in the target format so no device rounds it.
728fn stored_color(stored: [f32; 4]) -> wgpu::Color {
729    let [r, g, b, a] = stored.map(f64::from);
730    wgpu::Color { r, g, b, a }
731}
732
733/// Draws one batch into `target`, full-frame or scissored, after loading or clearing it.
734fn encode_batch(
735    encoder: &mut wgpu::CommandEncoder,
736    pipeline: &wgpu::RenderPipeline,
737    (bind_group, sampler): (&OffsetBindGroup<1>, &crate::bind_group::LinearSampler),
738    target: &wgpu::TextureView,
739    PassTarget { load, scissor }: PassTarget,
740) {
741    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
742        label: Some("alpha2 layer composition pass"),
743        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
744            view: target,
745            depth_slice: None,
746            resolve_target: None,
747            ops: wgpu::Operations {
748                load,
749                store: wgpu::StoreOp::Store,
750            },
751        })],
752        depth_stencil_attachment: None,
753        timestamp_writes: None,
754        occlusion_query_set: None,
755        multiview_mask: None,
756    });
757    pass.set_pipeline(pipeline);
758    bind_group.set(&mut pass, 0);
759    sampler.set(&mut pass);
760    if let Some(scissor) = scissor {
761        if scissor.area() == 0 {
762            return;
763        }
764        pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
765    }
766    pass.draw(0..3, 0..1);
767}
768
769fn copy_region(
770    encoder: &mut wgpu::CommandEncoder,
771    source: &wgpu::Texture,
772    destination: &wgpu::Texture,
773    region: PixelRect,
774) {
775    let at = |texture| wgpu::TexelCopyTextureInfo {
776        texture,
777        mip_level: 0,
778        origin: wgpu::Origin3d {
779            x: region.x,
780            y: region.y,
781            z: 0,
782        },
783        aspect: wgpu::TextureAspect::All,
784    };
785    encoder.copy_texture_to_texture(
786        at(source),
787        at(destination),
788        wgpu::Extent3d {
789            width: region.width,
790            height: region.height,
791            depth_or_array_layers: 1,
792        },
793    );
794}
795
796/// A rectangle of target pixels.
797#[derive(Copy, Clone, Debug, Eq, PartialEq)]
798pub(crate) struct PixelRect {
799    pub(crate) x: u32,
800    pub(crate) y: u32,
801    pub(crate) width: u32,
802    pub(crate) height: u32,
803}
804
805impl PixelRect {
806    /// No pixels; the bounds of a layer that misses the target.
807    pub(crate) const EMPTY: Self = Self {
808        x: 0,
809        y: 0,
810        width: 0,
811        height: 0,
812    };
813
814    pub(crate) const fn whole(size: RenderSize) -> Self {
815        Self {
816            x: 0,
817            y: 0,
818            width: size.width,
819            height: size.height,
820        }
821    }
822
823    pub(crate) fn area(self) -> u64 {
824        u64::from(self.width) * u64::from(self.height)
825    }
826
827    pub(crate) fn intersection(self, other: Self) -> Self {
828        let x = self.x.max(other.x);
829        let y = self.y.max(other.y);
830        let right = (self.x + self.width).min(other.x + other.width);
831        let bottom = (self.y + self.height).min(other.y + other.height);
832        if right <= x || bottom <= y {
833            return Self::EMPTY;
834        }
835        Self {
836            x,
837            y,
838            width: right - x,
839            height: bottom - y,
840        }
841    }
842
843    fn union(self, other: Self) -> Self {
844        let x = self.x.min(other.x);
845        let y = self.y.min(other.y);
846        let right = (self.x + self.width).max(other.x + other.width);
847        let bottom = (self.y + self.height).max(other.y + other.height);
848        Self {
849            x,
850            y,
851            width: right - x,
852            height: bottom - y,
853        }
854    }
855}
856
857/// Pixels beyond a layer's edges its coverage can still reach. Antialiasing reaches about
858/// 1.5 pixels, so this is generous.
859const COVERAGE_MARGIN: f64 = 4.0;
860
861/// Target pixels a layer can change: its transformed rectangle widened by [`COVERAGE_MARGIN`]
862/// and clamped, or `None` if it misses. Elsewhere coverage is zero.
863///
864/// Mirrors the shader: source corner `(u, v)` lands at
865/// `position * size + R^T ((u, v) - anchor) * scale * size`, with `R` the shader's rotation.
866pub(crate) fn layer_bounds(visual: LayerTransform, size: RenderSize) -> Option<PixelRect> {
867    let (width, height) = (f64::from(size.width), f64::from(size.height));
868    let (turn_sin, turn_cos) = libm::sincos(f64::from(visual.rotation_degrees).to_radians());
869    let corner = |u: f64, v: f64| {
870        let x = (u - f64::from(visual.anchor[0])) * f64::from(visual.scale[0]) * width;
871        let y = (v - f64::from(visual.anchor[1])) * f64::from(visual.scale[1]) * height;
872        (
873            f64::from(visual.position[0]) * width + turn_cos * x - turn_sin * y,
874            f64::from(visual.position[1]) * height + turn_sin * x + turn_cos * y,
875        )
876    };
877    let corners = [
878        corner(0.0, 0.0),
879        corner(1.0, 0.0),
880        corner(0.0, 1.0),
881        corner(1.0, 1.0),
882    ];
883    let fold = |pick: fn(&(f64, f64)) -> f64, extreme: fn(f64, f64) -> f64, start: f64| {
884        corners.iter().map(pick).fold(start, extreme)
885    };
886    let left = (fold(|c| c.0, f64::min, f64::INFINITY) - COVERAGE_MARGIN)
887        .floor()
888        .max(0.0);
889    let top = (fold(|c| c.1, f64::min, f64::INFINITY) - COVERAGE_MARGIN)
890        .floor()
891        .max(0.0);
892    let right = (fold(|c| c.0, f64::max, f64::NEG_INFINITY) + COVERAGE_MARGIN)
893        .ceil()
894        .min(width);
895    let bottom = (fold(|c| c.1, f64::max, f64::NEG_INFINITY) + COVERAGE_MARGIN)
896        .ceil()
897        .min(height);
898    if !(right > left && bottom > top) {
899        return None;
900    }
901    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
902    Some(PixelRect {
903        x: left as u32,
904        y: top as u32,
905        width: (right - left) as u32,
906        height: (bottom - top) as u32,
907    })
908}
909
910/// The canvas background as the intermediate stores it (8-bit or half, round to nearest),
911/// transparent when absent.
912///
913/// Both the empty-canvas clear and the first layer pass use this value. Letting the device
914/// convert the original can round a tie differently (0.7 is 178.49999 in `f32`), so an empty
915/// frame would differ from its neighbour by one code.
916pub(crate) fn stored_background(
917    background: Option<Color>,
918    format: wgpu::TextureFormat,
919) -> [f32; 4] {
920    let Some(color) = background else {
921        return [0.0; 4];
922    };
923    // Clear values reach the device as `f32`.
924    #[allow(clippy::cast_possible_truncation)]
925    let channel = |value: f64| {
926        let value = value as f32;
927        match format {
928            wgpu::TextureFormat::Rgba8Unorm => (value.clamp(0.0, 1.0) * 255.0).round() / 255.0,
929            wgpu::TextureFormat::Rgba16Float => half::f16::from_f32(value).to_f32(),
930            _ => value,
931        }
932    };
933    [
934        channel(color.red),
935        channel(color.green),
936        channel(color.blue),
937        channel(color.alpha),
938    ]
939}
940
941const BACKDROP_BINDING: u32 = 8;
942const UNIFORM_BINDING: u32 = 9;
943
944/// Composite pass layout: a texture per layer slot, backdrop and batch uniform.
945fn batch_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
946    let mut entries = (0..COMPOSITE_BATCH_LAYERS)
947        .map(|slot| texture_entry(u32::try_from(slot).expect("few layer slots"), true))
948        .collect::<Vec<_>>();
949    entries.push(texture_entry(BACKDROP_BINDING, false));
950    entries.push(wgpu::BindGroupLayoutEntry {
951        binding: UNIFORM_BINDING,
952        visibility: wgpu::ShaderStages::FRAGMENT,
953        ty: batch_uniform_binding(),
954        count: None,
955    });
956    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
957        label: Some("alpha2 layer batch bind group layout"),
958        entries: &entries,
959    })
960}
961
962/// Sized to the graph's reservation so an oversized `BatchParams` fails pipeline creation
963/// instead of overrunning the uniform arena.
964fn batch_uniform_binding() -> wgpu::BindingType {
965    wgpu::BindingType::Buffer {
966        ty: wgpu::BufferBindingType::Uniform,
967        has_dynamic_offset: true,
968        min_binding_size: std::num::NonZeroU64::new(float_uniform_bytes(BATCH_UNIFORM_FLOATS)),
969    }
970}
971
972fn texture_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
973    wgpu::BindGroupLayoutEntry {
974        binding,
975        visibility: wgpu::ShaderStages::FRAGMENT,
976        ty: wgpu::BindingType::Texture {
977            sample_type: wgpu::TextureSampleType::Float { filterable },
978            view_dimension: wgpu::TextureViewDimension::D2,
979            multisampled: false,
980        },
981        count: None,
982    }
983}
984
985fn composite_pipeline(
986    device: &wgpu::Device,
987    [layout, sampler_layout]: [&wgpu::BindGroupLayout; 2],
988    shader: &wgpu::ShaderModule,
989    format: wgpu::TextureFormat,
990    fragment_entry: &str,
991    label: &str,
992) -> wgpu::RenderPipeline {
993    let label = Some(label);
994    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
995        label,
996        bind_group_layouts: &[Some(layout), Some(sampler_layout)],
997        immediate_size: 0,
998    });
999    let constants = [("STORED_FORMAT", StoredValue::of(format).shader_value())];
1000    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1001        label,
1002        layout: Some(&pipeline_layout),
1003        vertex: wgpu::VertexState {
1004            module: shader,
1005            entry_point: Some("vs"),
1006            buffers: &[],
1007            compilation_options: wgpu::PipelineCompilationOptions::default(),
1008        },
1009        fragment: Some(wgpu::FragmentState {
1010            module: shader,
1011            entry_point: Some(fragment_entry),
1012            targets: &[Some(format.into())],
1013            compilation_options: wgpu::PipelineCompilationOptions {
1014                constants: &constants,
1015                ..wgpu::PipelineCompilationOptions::default()
1016            },
1017        }),
1018        primitive: wgpu::PrimitiveState::default(),
1019        depth_stencil: None,
1020        multisample: wgpu::MultisampleState::default(),
1021        multiview_mask: None,
1022        cache: None,
1023    })
1024}
1025
1026pub(crate) fn validate_visual(visual: LayerTransform) -> Result<(), RenderError> {
1027    let values = [
1028        visual.position[0],
1029        visual.position[1],
1030        visual.anchor[0],
1031        visual.anchor[1],
1032        visual.scale[0],
1033        visual.scale[1],
1034        visual.rotation_degrees,
1035        visual.opacity,
1036    ];
1037    if values.into_iter().any(|value| !value.is_finite()) || !(0.0..=1.0).contains(&visual.opacity)
1038    {
1039        return Err(RenderError::InvalidVisual);
1040    }
1041    Ok(())
1042}
1043
1044/// Whether a layer collapses to a line or point and covers no pixel.
1045///
1046/// A scale passing through zero is a valid instant, not an error; the transform just has no
1047/// inverse.
1048pub(crate) fn is_degenerate(visual: LayerTransform) -> bool {
1049    visual.scale[0].abs() <= f32::EPSILON || visual.scale[1].abs() <= f32::EPSILON
1050}
1051
1052/// Whether a layer has zero opacity and so leaves every pixel unchanged.
1053///
1054/// Drawing it would only round the backdrop through the blend space.
1055pub(crate) fn is_invisible(visual: LayerTransform) -> bool {
1056    visual.opacity <= 0.0
1057}