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