Skip to main content

alpha2_render/
composite.rs

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