alpha2-render 0.10.0

Render graph and effect registry for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
//! The vector pass: a [`VectorScene`] drawn from tile coverage.
//!
//! Fill coverage is computed on the CPU ([`alpha2_geometry::raster`]) and cached by path key.
//! Partial tiles go into `R8Unorm` atlas pages, and all tiles draw as instanced 16x16 quads
//! painted with the generator pass's paint code. Group layers render to their own texture and
//! composite at their opacity.
//!
//! When the graph blends in linear light and half floats are blendable, the scene draws in
//! linear light into `Rgba16Float` and is then encoded to the premultiplied sRGB intermediate.
//! Otherwise it blends directly in encoded space, like the 8-bit composite fallback.

use std::num::NonZeroU64;
use std::sync::Arc;

use alpha2_geometry::raster::{RasterScratch, TILE, TILE_BYTES, TileCoverage, TileState};
use alpha2_geometry::{IRect, PaintKind, ScenePaint, VectorOp, VectorScene};
use wgpu::util::DeviceExt;

use crate::composite::PixelRect;
use crate::uniform::UniformArenaLease;
use crate::{RenderError, RenderSize, Renderer};

/// Atlas page width in pixels: 128 tile slots across.
const ATLAS_WIDTH: u32 = 2048;

/// Tile slots in one atlas row of tiles.
const SLOTS_PER_ROW: u32 = ATLAS_WIDTH / 16;

/// Slot of a full tile: no atlas read, coverage one.
const FULL_SLOT: u32 = u32::MAX;

const VECTOR_UNIFORM_HEAD: usize = 20;

const VECTOR_UNIFORM_WORDS: usize =
    VECTOR_UNIFORM_HEAD + crate::MAX_GENERATOR_STOPS + 4 * crate::MAX_GENERATOR_STOPS;

/// One op's uniform: twenty-five `vec4`s.
pub(crate) const VECTOR_UNIFORM_BYTES: u64 = VECTOR_UNIFORM_WORDS as u64 * 4;

const _: () = assert!(
    size_of::<[u32; VECTOR_UNIFORM_WORDS]>() as u64 == VECTOR_UNIFORM_BYTES,
    "the vector uniform writers fill the bytes the arena reserves"
);

/// One tile instance: position (two `u16`) and slot.
const INSTANCE_BYTES: u64 = 8;

const _: () = assert!(TILE == 16, "the shader draws 16-pixel tiles");

const TILE_PIXELS: u64 = 16 * 16;

const VECTOR_LAYER_COST: crate::effect_cost::EffectCost =
    crate::effect_cost::EffectCost::fixed(2, 0);
const VECTOR_ENCODE_COST: crate::effect_cost::EffectCost =
    crate::effect_cost::EffectCost::fixed(1, 3);
const VECTOR_FILL_READS: u64 = 2;
const STORE_TRANSCENDENTALS: u64 = 3;
const STOP_ARITHMETIC: u64 = 8;

fn fill_cost(paint: &ScenePaint, encoded: bool) -> crate::effect_cost::EffectCost {
    let paint_transcendentals = match paint.kind {
        PaintKind::Solid | PaintKind::Linear => 0,
        PaintKind::Radial | PaintKind::Conic => 1,
    };
    let store = if encoded { STORE_TRANSCENDENTALS } else { 0 };
    let stops = u64::try_from(paint.stops.len()).unwrap_or(u64::MAX);
    crate::effect_cost::EffectCost::fixed(VECTOR_FILL_READS, paint_transcendentals + store).plus(
        crate::effect_cost::EffectCost {
            fetches: 0,
            transcendentals: 0,
            arithmetic: STOP_ARITHMETIC.saturating_mul(stops),
        },
    )
}

pub(crate) fn vector_wgsl() -> String {
    format!(
        r"{paint}
struct VectorUniform {{
    // Device pixels to paint-space pixels: rows of a 2x3 matrix, then the
    // paint space's width (in the first) and height (in the second).
    inverse0: vec4f,
    inverse1: vec4f,
    // Canvas width and height, opacity, and 1 to store sRGB-encoded.
    canvas: vec4f,
    paint_ab: vec4f,
    // Kind, spread, stop count.
    paint_info: vec4u,
    offsets: array<vec4f, {offset_vectors}>,
    colors: array<vec4f, {stops}>,
}};

@group(0) @binding(0) var<uniform> op: VectorUniform;
@group(0) @binding(1) var picture: texture_2d<f32>;

struct TileOut {{
    @builtin(position) position: vec4f,
    @location(0) @interpolate(flat) tile: vec2u,
    @location(1) @interpolate(flat) slot: u32,
}};

fn clip_position(pixel: vec2f) -> vec4f {{
    let size = op.canvas.xy;
    return vec4f(pixel.x / size.x * 2.0 - 1.0, 1.0 - pixel.y / size.y * 2.0, 0.0, 1.0);
}}

@vertex
fn vs_tile(@builtin(vertex_index) index: u32, @location(0) tile: vec2u, @location(1) slot: u32) -> TileOut {{
    var corners = array<vec2f, 6>(
        vec2f(0.0, 0.0), vec2f(1.0, 0.0), vec2f(0.0, 1.0),
        vec2f(0.0, 1.0), vec2f(1.0, 0.0), vec2f(1.0, 1.0),
    );
    var out: TileOut;
    out.position = clip_position((vec2f(tile) + corners[index]) * 16.0);
    out.tile = tile;
    out.slot = slot;
    return out;
}}

fn builtin_op_paint() -> AlphaPaint {{
    return AlphaPaint(
        op.paint_info.x,
        op.paint_ab.xy,
        op.paint_ab.zw,
        op.paint_info.y,
        op.paint_info.z,
        array<f32, {stops}>({offsets}),
        op.colors,
    );
}}

@fragment
fn fs_tile(in: TileOut) -> @location(0) vec4f {{
    var coverage = 1.0;
    if (in.slot != 0xffffffffu) {{
        let pixel = vec2u(in.position.xy);
        let local = pixel - in.tile * 16u;
        let origin = vec2u(in.slot % {SLOTS_PER_ROW}u, in.slot / {SLOTS_PER_ROW}u) * 16u;
        coverage = textureLoad(picture, origin + local, 0).r;
    }}
    let device = in.position.xy;
    let painted = vec2f(
        dot(op.inverse0.xy, device) + op.inverse0.z,
        dot(op.inverse1.xy, device) + op.inverse1.z,
    );
    let res = vec2f(op.inverse0.w, op.inverse1.w);
    var color = builtin_paint(builtin_op_paint(), painted / res, res);
    if (op.canvas.w > 0.5) {{ color = builtin_generator_store(color); }}
    return color * (coverage * op.canvas.z);
}}

struct FullOut {{
    @builtin(position) position: vec4f,
}};

@vertex
fn vs_full(@builtin(vertex_index) index: u32) -> FullOut {{
    var corners = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
    var out: FullOut;
    out.position = vec4f(corners[index], 0.0, 1.0);
    return out;
}}

// A layer composited at the op's opacity.
@fragment
fn fs_layer(in: FullOut) -> @location(0) vec4f {{
    return textureLoad(picture, vec2u(in.position.xy), 0) * op.canvas.z;
}}

// A linear-light picture stored as the engine stores pictures.
@fragment
fn fs_encode(in: FullOut) -> @location(0) vec4f {{
    return builtin_generator_store(textureLoad(picture, vec2u(in.position.xy), 0));
}}
",
        paint = crate::paint_wgsl::paint_wgsl(),
        stops = crate::MAX_GENERATOR_STOPS,
        offset_vectors = crate::generator::OFFSET_VECTORS,
        offsets = crate::generator::offset_list(|vector| format!("op.offsets[{vector}]")),
    )
}

#[derive(Debug)]
pub(crate) struct VectorPipelines {
    tile: wgpu::RenderPipeline,
    layer: wgpu::RenderPipeline,
    encode: wgpu::RenderPipeline,
}

#[derive(Debug)]
pub(crate) struct CachedVectorPipeline {
    pub(crate) layout: wgpu::BindGroupLayout,
    shader: wgpu::ShaderModule,
    pipeline_layout: wgpu::PipelineLayout,
    by_format: std::sync::Mutex<Vec<(wgpu::TextureFormat, crate::Shared<VectorPipelines>)>>,
}

#[derive(Debug, Default)]
pub(crate) struct VectorState {
    pub(crate) cache: alpha2_geometry::raster::CoverageCache,
    pub(crate) scratch: RasterScratch,
}

/// Destination of a scene's partial tiles, filled in op order.
struct Atlas {
    pages: Vec<Vec<u8>>,
    page_slots: u32,
    used: u32,
}

impl Atlas {
    fn new(page_slots: u32) -> Self {
        Self {
            pages: Vec::new(),
            page_slots,
            used: page_slots,
        }
    }

    fn push(&mut self, bytes: &[u8; TILE_BYTES]) -> (usize, u32) {
        if self.used == self.page_slots {
            self.pages.push(Vec::new());
            self.used = 0;
        }
        let page = self.pages.len() - 1;
        let slot = self.used;
        self.used += 1;
        let rows = (slot / SLOTS_PER_ROW + 1) as usize * TILE;
        let data = &mut self.pages[page];
        let width = ATLAS_WIDTH as usize;
        if data.len() < rows * width {
            data.resize(rows * width, 0);
        }
        let (x, y) = (
            (slot % SLOTS_PER_ROW) as usize * TILE,
            (slot / SLOTS_PER_ROW) as usize * TILE,
        );
        for row in 0..TILE {
            let start = (y + row) * width + x;
            data[start..start + TILE].copy_from_slice(&bytes[row * TILE..row * TILE + TILE]);
        }
        (page, slot)
    }
}

struct FillDraw {
    /// Instance ranges by page. A full tile joins the preceding range, whose atlas it ignores.
    ranges: Vec<(usize, std::ops::Range<u32>)>,
    uniform: [u32; VECTOR_UNIFORM_WORDS],
    region: PixelRect,
    work: crate::FrameCost,
}

enum Step {
    Fill(FillDraw),
    Push,
    Pop {
        bounds: IRect,
        region: PixelRect,
        uniform: [u32; VECTOR_UNIFORM_WORDS],
        work: crate::FrameCost,
    },
}

pub(crate) struct PreparedVector {
    linear: bool,
    fills: usize,
    pages: Vec<Vec<u8>>,
    page_rows: u32,
    instances: Vec<u8>,
    steps: Vec<Step>,
    encode_uniform: [u32; VECTOR_UNIFORM_WORDS],
    encode_region: PixelRect,
    encode_work: crate::FrameCost,
}

impl PreparedVector {
    pub(crate) fn pilot_work(&self, rows: u32) -> f64 {
        let drawn = |work: crate::FrameCost, region: PixelRect| {
            if region.height == 0 {
                0.0
            } else {
                work.unit_pixels() * f64::from(rows.min(region.height)) / f64::from(region.height)
            }
        };
        let mut total = if self.linear {
            drawn(self.encode_work, self.encode_region)
        } else {
            0.0
        };
        for step in &self.steps {
            total += match step {
                Step::Fill(fill) => drawn(fill.work, fill.region),
                Step::Pop { work, region, .. } => drawn(*work, *region),
                Step::Push => 0.0,
            };
        }
        total
    }

    pub(crate) fn texture_bytes(&self, size: RenderSize, format_bytes: u64) -> u64 {
        let frame = size.pixels();
        let mut depth = 0_u64;
        let mut deepest = 0_u64;
        for step in &self.steps {
            match step {
                Step::Push => {
                    depth += 1;
                    deepest = deepest.max(depth);
                }
                Step::Pop { .. } => depth = depth.saturating_sub(1),
                Step::Fill(_) => {}
            }
        }
        let layer_bytes = if self.linear { 8 } else { format_bytes };
        let pages = u64::try_from(self.pages.len()).unwrap_or(u64::MAX)
            * u64::from(ATLAS_WIDTH)
            * u64::from(self.page_rows)
            * 16;
        let linear = if self.linear { frame * 8 } else { 0 };
        linear + deepest * frame * layer_bytes + pages
    }

    pub(crate) fn uniform_bytes(&self, alignment: u64) -> u64 {
        let slices = self
            .steps
            .iter()
            .filter(|step| !matches!(step, Step::Push))
            .count()
            + 1;
        (0..slices).fold(0, |cursor, _| {
            crate::uniform::aligned_uniform_end(cursor, VECTOR_UNIFORM_BYTES, alignment)
        })
    }

    pub(crate) fn work(&self) -> crate::FrameCost {
        let mut total = if self.linear {
            self.encode_work
        } else {
            crate::FrameCost::default()
        };
        for step in &self.steps {
            match step {
                Step::Fill(fill) => total.add_cost(fill.work),
                Step::Pop { work, .. } => total.add_cost(*work),
                Step::Push => {}
            }
        }
        total
    }
}

impl Renderer {
    /// Whether vector scenes draw in linear light: the graph blends in linear light into a
    /// half-float intermediate, which is blendable wherever it is chosen.
    pub(crate) fn vector_linear(&self, blend_space: crate::BlendSpace) -> bool {
        blend_space == crate::BlendSpace::LinearLight
            && self.intermediate_format() == wgpu::TextureFormat::Rgba16Float
    }

    fn vector_pipeline(&self) -> Result<&CachedVectorPipeline, RenderError> {
        let device = self.gpu.device();
        crate::gpu_errors::checked_cell(&self.pipelines.vector, device, || {
            let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("alpha2 vector layout"),
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: true,
                            min_binding_size: NonZeroU64::new(VECTOR_UNIFORM_BYTES),
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Texture {
                            sample_type: wgpu::TextureSampleType::Float { filterable: false },
                            view_dimension: wgpu::TextureViewDimension::D2,
                            multisampled: false,
                        },
                        count: None,
                    },
                ],
            });
            let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("alpha2 vector shader"),
                source: wgpu::ShaderSource::Wgsl(vector_wgsl().into()),
            });
            let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("alpha2 vector pipeline layout"),
                bind_group_layouts: &[Some(&layout)],
                immediate_size: 0,
            });
            CachedVectorPipeline {
                layout,
                shader,
                pipeline_layout,
                by_format: std::sync::Mutex::default(),
            }
        })
    }

    fn vector_pipelines(
        &self,
        format: wgpu::TextureFormat,
    ) -> Result<crate::Shared<VectorPipelines>, RenderError> {
        let cached = self.vector_pipeline()?;
        let mut by_format = cached
            .by_format
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some((_, pipelines)) = by_format.iter().find(|(held, _)| *held == format) {
            return Ok(crate::Shared::clone(pipelines));
        }
        let device = self.gpu.device();
        let make = |label: &'static str,
                    vertex: &'static str,
                    fragment: &'static str,
                    buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
                    blend: Option<wgpu::BlendState>| {
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some(label),
                layout: Some(&cached.pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &cached.shader,
                    entry_point: Some(vertex),
                    buffers,
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &cached.shader,
                    entry_point: Some(fragment),
                    targets: &[Some(wgpu::ColorTargetState {
                        format,
                        blend,
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState::default(),
                depth_stencil: None,
                multisample: wgpu::MultisampleState::default(),
                multiview_mask: None,
                cache: None,
            })
        };
        let instances = [Some(wgpu::VertexBufferLayout {
            array_stride: INSTANCE_BYTES,
            step_mode: wgpu::VertexStepMode::Instance,
            attributes: &[
                wgpu::VertexAttribute {
                    format: wgpu::VertexFormat::Uint16x2,
                    offset: 0,
                    shader_location: 0,
                },
                wgpu::VertexAttribute {
                    format: wgpu::VertexFormat::Uint32,
                    offset: 4,
                    shader_location: 1,
                },
            ],
        })];
        let over = Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING);
        let pipelines = crate::gpu_errors::create_checked(device, || VectorPipelines {
            tile: make(
                "alpha2 vector tile pipeline",
                "vs_tile",
                "fs_tile",
                &instances,
                over,
            ),
            layer: make(
                "alpha2 vector layer pipeline",
                "vs_full",
                "fs_layer",
                &[],
                over,
            ),
            encode: make(
                "alpha2 vector encode pipeline",
                "vs_full",
                "fs_encode",
                &[],
                None,
            ),
        })
        .map_err(|kind| RenderError::Gpu { kind })?;
        let pipelines = crate::Shared::new(pipelines);
        by_format.push((format, crate::Shared::clone(&pipelines)));
        Ok(pipelines)
    }

    pub(crate) fn warm_vector(&self, blend_space: crate::BlendSpace) -> Result<(), RenderError> {
        let format = self.intermediate_format();
        self.vector_pipelines(format)?;
        if self.vector_linear(blend_space) {
            self.vector_pipelines(wgpu::TextureFormat::Rgba16Float)?;
        }
        Ok(())
    }

    fn scene_coverage(&self, scene: &VectorScene) -> Vec<Option<Arc<TileCoverage>>> {
        let mut state = self
            .vector_state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let VectorState { cache, scratch } = &mut *state;
        scene
            .ops
            .iter()
            .map(|op| {
                let VectorOp::Fill {
                    path, rule, bounds, ..
                } = op
                else {
                    return None;
                };
                let key = alpha2_geometry::raster::coverage_key(path, *rule, *bounds);
                if let Some(coverage) = cache.get(key) {
                    return Some(coverage);
                }
                let coverage = Arc::new(alpha2_geometry::raster::rasterize(
                    path, *rule, *bounds, scratch,
                ));
                cache.insert(key, Arc::clone(&coverage));
                Some(coverage)
            })
            .collect()
    }

    pub(crate) fn prepare_vector(
        &self,
        scene: &VectorScene,
        size: RenderSize,
        blend_space: crate::BlendSpace,
    ) -> Result<PreparedVector, RenderError> {
        let linear = self.vector_linear(blend_space);
        let page_rows = (self.limits.max_texture_dimension_2d.min(ATLAS_WIDTH) / 16).max(1);
        #[cfg(test)]
        let page_rows = match self
            .vector_page_rows
            .load(std::sync::atomic::Ordering::Relaxed)
        {
            0 => page_rows,
            rows => rows,
        };
        // Canvas edges are at most 16384, exact in `f32`.
        #[allow(clippy::cast_precision_loss)]
        let canvas = [size.width as f32, size.height as f32];
        let encode_region = irect_region(scene.bounds, size);
        let mut prepared = PreparedVector {
            linear,
            fills: scene.fill_count(),
            pages: Vec::new(),
            page_rows,
            instances: Vec::new(),
            steps: Vec::new(),
            encode_uniform: op_uniform_plain(canvas, 1.0),
            encode_region,
            encode_work: crate::FrameCost::of(VECTOR_ENCODE_COST, encode_region.area()),
        };
        if prepared.fills == 0 {
            return Ok(prepared);
        }
        let raster_started = self
            .pass_timing_epoch()
            .map(|epoch| (epoch, web_time::Instant::now()));
        let coverage = self.scene_coverage(scene);
        if let Some((epoch, started)) = raster_started {
            crate::diagnostics::record_pass(
                &self.diagnostics,
                epoch,
                "vector raster",
                started.elapsed(),
                crate::TimingSource::CpuEncoding,
            );
        }
        let mut atlas = Atlas::new(page_rows * SLOTS_PER_ROW);
        prepared.steps.reserve(scene.ops.len());
        let mut open: Vec<(IRect, f32)> = Vec::new();
        for (op, coverage) in scene.ops.iter().zip(&coverage) {
            match op {
                VectorOp::PushLayer { bounds, opacity } => {
                    open.push((*bounds, *opacity));
                    prepared.steps.push(Step::Push);
                }
                VectorOp::PopLayer => {
                    let (bounds, opacity) = open.pop().ok_or(RenderError::InvalidGraph)?;
                    let region = irect_region(bounds, size);
                    prepared.steps.push(Step::Pop {
                        bounds,
                        region,
                        uniform: op_uniform_plain(canvas, opacity),
                        work: crate::FrameCost::of(VECTOR_LAYER_COST, region.area()),
                    });
                }
                VectorOp::Fill { paint, opacity, .. } => {
                    let coverage = coverage.as_ref().ok_or(RenderError::InvalidGraph)?;
                    let (ranges, tiles, region) =
                        lay_out_tiles(coverage, &mut atlas, &mut prepared.instances, size);
                    prepared.steps.push(Step::Fill(FillDraw {
                        ranges,
                        uniform: op_uniform(paint, canvas, *opacity, !linear),
                        region,
                        work: crate::FrameCost::of(fill_cost(paint, !linear), tiles * TILE_PIXELS),
                    }));
                }
            }
        }
        prepared.pages = atlas.pages;
        Ok(prepared)
    }

    /// Encodes `scene` into `output` and returns the render passes encoded.
    #[allow(clippy::too_many_lines)]
    pub(crate) fn encode_vector(
        &self,
        encoder: &mut crate::renderer::RenderEncoder,
        prepared: &PreparedVector,
        size: RenderSize,
        output: &wgpu::TextureView,
        uniforms: &mut UniformArenaLease,
    ) -> Result<u64, RenderError> {
        let device = self.gpu.device();
        let linear = prepared.linear;
        let format = if linear {
            wgpu::TextureFormat::Rgba16Float
        } else {
            self.intermediate_format()
        };
        if prepared.fills == 0 {
            clear(encoder, output);
            return Ok(1);
        }
        let pipelines = self.vector_pipelines(format)?;
        let cached = self.vector_pipeline()?;
        let pass = crate::submission_pilot::PassKind::Vector.key(size.pixels());
        let mut offsets = Vec::with_capacity(prepared.steps.len());
        for step in &prepared.steps {
            offsets.push(match step {
                Step::Fill(FillDraw { uniform, .. }) | Step::Pop { uniform, .. } => {
                    uniforms.write(bytemuck::cast_slice(uniform))?.offset()
                }
                Step::Push => 0,
            });
        }
        let encode_uniform = uniforms
            .write(bytemuck::cast_slice(&prepared.encode_uniform))?
            .offset();

        let mut transient = crate::retire::TransientBuffers::new(&self.retirement);
        // Upload pages in encoder order so a page reused later in the frame still holds these
        // tiles.
        let page_textures: Vec<crate::pool::TextureLease> = prepared
            .pages
            .iter()
            .map(|bytes| {
                let rows = u32::try_from(bytes.len() / ATLAS_WIDTH as usize)
                    .unwrap_or(16)
                    .max(16);
                // Power-of-two heights so pages pool across frames.
                let height = rows
                    .next_power_of_two()
                    .min(prepared.page_rows * 16)
                    .max(rows);
                let texture = self.textures.acquire(
                    device,
                    RenderSize::new(ATLAS_WIDTH, height).expect("a non-empty atlas page"),
                    wgpu::TextureFormat::R8Unorm,
                    "alpha2 vector atlas page",
                );
                let staging = transient.keep(device.create_buffer_init(
                    &wgpu::util::BufferInitDescriptor {
                        label: Some("alpha2 vector atlas upload"),
                        contents: bytes,
                        usage: wgpu::BufferUsages::COPY_SRC,
                    },
                ));
                encoder.copy_buffer_to_texture(
                    wgpu::TexelCopyBufferInfo {
                        buffer: &staging,
                        layout: wgpu::TexelCopyBufferLayout {
                            offset: 0,
                            bytes_per_row: Some(ATLAS_WIDTH),
                            rows_per_image: Some(rows),
                        },
                    },
                    wgpu::TexelCopyTextureInfo {
                        texture: texture.texture(),
                        mip_level: 0,
                        origin: wgpu::Origin3d::ZERO,
                        aspect: wgpu::TextureAspect::All,
                    },
                    wgpu::Extent3d {
                        width: ATLAS_WIDTH,
                        height: rows,
                        depth_or_array_layers: 1,
                    },
                );
                texture
            })
            .collect();
        let instance_buffer = transient.keep(device.create_buffer_init(
            &wgpu::util::BufferInitDescriptor {
                label: Some("alpha2 vector tiles"),
                contents: if prepared.instances.is_empty() {
                    &[0; 8]
                } else {
                    &prepared.instances
                },
                usage: wgpu::BufferUsages::VERTEX,
            },
        ));
        let binding =
            uniforms.dynamic_binding(NonZeroU64::new(VECTOR_UNIFORM_BYTES).expect("non-zero"));
        let group = |view: &wgpu::TextureView| {
            self.bind_group(&wgpu::BindGroupDescriptor {
                label: Some("alpha2 vector group"),
                layout: &cached.layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: binding.clone(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(view),
                    },
                ],
            })
        };
        let page_groups: Vec<wgpu::BindGroup> = if page_textures.is_empty() {
            vec![group(&self.empty_input)]
        } else {
            page_textures
                .iter()
                .map(|page| group(page.view()))
                .collect()
        };
        let draw_fill = |pass: &mut wgpu::RenderPass<'_>, fill: &FillDraw, offset: u64| {
            for (page, range) in &fill.ranges {
                pass.set_bind_group(
                    0,
                    &page_groups[(*page).min(page_groups.len() - 1)],
                    &[dynamic_offset(offset)],
                );
                pass.draw(0..6, range.clone());
            }
        };

        let linear_target = linear.then(|| {
            self.textures.acquire(
                device,
                size,
                wgpu::TextureFormat::Rgba16Float,
                "alpha2 vector linear target",
            )
        });
        let base: &wgpu::TextureView = linear_target
            .as_ref()
            .map_or(output, |target| target.view());
        let mut passes = 0_u64;
        let mut layers: Vec<crate::pool::TextureLease> = Vec::new();
        let mut cleared = vec![false];
        let mut fills_pass: Option<wgpu::RenderPass<'static>> = None;
        for (step, offset) in prepared.steps.iter().zip(&offsets) {
            match step {
                Step::Push => {
                    drop(fills_pass.take());
                    layers.push(
                        self.textures
                            .acquire(device, size, format, "alpha2 vector layer"),
                    );
                    cleared.push(false);
                }
                Step::Pop { bounds, work, .. } => {
                    drop(fills_pass.take());
                    let layer = layers.pop().ok_or(RenderError::InvalidGraph)?;
                    let layer_cleared = cleared.pop().unwrap_or(true);
                    let parent = layers.last().map_or(base, crate::pool::TextureLease::view);
                    let parent_cleared = cleared.last_mut().expect("the base is on the stack");
                    if layer_cleared {
                        let layer_group = group(layer.view());
                        let clear_first = !*parent_cleared;
                        *parent_cleared = true;
                        let region = irect_region(*bounds, size);
                        let placement = encoder.place_pass(*work, region, true, Some(pass), None);
                        encoder.encode_pieces(placement, region, |encoder, piece| {
                            let mut pass = begin(encoder, parent, piece.first && clear_first);
                            passes += 1;
                            let scissor = piece.scissor.unwrap_or(region);
                            if scissor.area() > 0 {
                                pass.set_scissor_rect(
                                    scissor.x,
                                    scissor.y,
                                    scissor.width,
                                    scissor.height,
                                );
                                pass.set_pipeline(&pipelines.layer);
                                pass.set_bind_group(0, &layer_group, &[dynamic_offset(*offset)]);
                                pass.draw(0..3, 0..1);
                            }
                        });
                    }
                }
                Step::Fill(fill) => {
                    let target = layers.last().map_or(base, crate::pool::TextureLease::view);
                    let clear_first = !*cleared.last().expect("a target");
                    *cleared.last_mut().expect("a target") = true;
                    let placement =
                        encoder
                            .planner()
                            .pass(fill.work, fill.region, true, Some(pass));
                    let whole = !placement.cut_before
                        && placement.pieces.count() <= 1
                        && placement.pilot.is_none();
                    if !whole {
                        drop(fills_pass.take());
                    }
                    encoder.apply(placement, None);
                    if whole {
                        let pass = fills_pass.get_or_insert_with(|| {
                            passes += 1;
                            let mut pass = begin(encoder, target, clear_first).forget_lifetime();
                            pass.set_pipeline(&pipelines.tile);
                            pass.set_vertex_buffer(0, instance_buffer.slice(..));
                            pass
                        });
                        draw_fill(pass, fill, *offset);
                    } else {
                        encoder.encode_pieces(placement, fill.region, |encoder, piece| {
                            let mut pass = begin(encoder, target, piece.first && clear_first);
                            passes += 1;
                            if let Some(scissor) = piece.scissor {
                                if scissor.area() == 0 {
                                    return;
                                }
                                pass.set_scissor_rect(
                                    scissor.x,
                                    scissor.y,
                                    scissor.width,
                                    scissor.height,
                                );
                            }
                            pass.set_pipeline(&pipelines.tile);
                            pass.set_vertex_buffer(0, instance_buffer.slice(..));
                            draw_fill(&mut pass, fill, *offset);
                        });
                    }
                }
            }
        }
        drop(fills_pass);
        if !cleared[0] {
            clear(encoder, base);
            passes += 1;
        }
        if let Some(linear_target) = &linear_target {
            let encode_group = group(linear_target.view());
            let region = prepared.encode_region;
            let placement =
                encoder.place_pass(prepared.encode_work, region, true, Some(pass), None);
            encoder.encode_pieces(placement, region, |encoder, piece| {
                let mut pass = begin(encoder, output, piece.first);
                passes += 1;
                let scissor = piece.scissor.unwrap_or(region);
                if scissor.area() > 0 {
                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
                    pass.set_pipeline(&pipelines.encode);
                    pass.set_bind_group(0, &encode_group, &[dynamic_offset(encode_uniform)]);
                    pass.draw(0..3, 0..1);
                }
            });
        }
        Ok(passes)
    }
}

fn lay_out_tiles(
    coverage: &TileCoverage,
    atlas: &mut Atlas,
    instances: &mut Vec<u8>,
    size: RenderSize,
) -> (Vec<(usize, std::ops::Range<u32>)>, u64, PixelRect) {
    let mut ranges: Vec<(usize, std::ops::Range<u32>)> = Vec::new();
    let (tiles_x, _) = coverage.size;
    let mut tiles = 0_u64;
    let mut reach: Option<(i32, i32, i32, i32)> = None;
    for (index, tile) in coverage.tiles.iter().enumerate() {
        let index = u32::try_from(index).unwrap_or(u32::MAX);
        let x = coverage.origin.0 + i32::try_from(index % tiles_x).unwrap_or(0);
        let y = coverage.origin.1 + i32::try_from(index / tiles_x).unwrap_or(0);
        let (page, slot) = match tile {
            TileState::Empty => continue,
            TileState::Full => (ranges.last().map_or(0, |(page, _)| *page), FULL_SLOT),
            TileState::Partial(partial) => atlas.push(&coverage.partial[*partial as usize]),
        };
        push_instance(&mut ranges, instances, page, (x, y), slot);
        tiles += 1;
        reach = Some(reach.map_or((x, y, x, y), |(x0, y0, x1, y1)| {
            (x0.min(x), y0.min(y), x1.max(x), y1.max(y))
        }));
    }
    let tile = i32::try_from(TILE).unwrap_or(16);
    let region = reach.map_or(PixelRect::EMPTY, |(x0, y0, x1, y1)| {
        irect_region(
            IRect::new(x0 * tile, y0 * tile, (x1 + 1) * tile, (y1 + 1) * tile),
            size,
        )
    });
    (ranges, tiles, region)
}

/// Appends a tile instance to the last range for `page`, or starts a new one.
fn push_instance(
    ranges: &mut Vec<(usize, std::ops::Range<u32>)>,
    instances: &mut Vec<u8>,
    page: usize,
    (x, y): (i32, i32),
    slot: u32,
) {
    let index = u32::try_from(instances.len() as u64 / INSTANCE_BYTES).unwrap_or(u32::MAX);
    match ranges.last_mut() {
        Some((held, range)) if *held == page && range.end == index => range.end += 1,
        _ => ranges.push((page, index..index + 1)),
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let (tx, ty) = (x as u16, y as u16);
    instances.extend_from_slice(&tx.to_le_bytes());
    instances.extend_from_slice(&ty.to_le_bytes());
    instances.extend_from_slice(&slot.to_le_bytes());
}

/// Arena offsets fit in `u32`.
fn dynamic_offset(offset: u64) -> u32 {
    u32::try_from(offset).expect("a uniform arena is smaller than 4 GiB")
}

fn clear(encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView) {
    let _pass = begin(encoder, target, true);
}

fn begin<'e>(
    encoder: &'e mut wgpu::CommandEncoder,
    target: &wgpu::TextureView,
    clear: bool,
) -> wgpu::RenderPass<'e> {
    encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some("alpha2 vector pass"),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: target,
            depth_slice: None,
            resolve_target: None,
            ops: wgpu::Operations {
                load: if clear {
                    wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
                } else {
                    wgpu::LoadOp::Load
                },
                store: wgpu::StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
        multiview_mask: None,
    })
}

fn irect_region(bounds: IRect, size: RenderSize) -> PixelRect {
    let canvas = IRect::new(
        0,
        0,
        i32::try_from(size.width).unwrap_or(i32::MAX),
        i32::try_from(size.height).unwrap_or(i32::MAX),
    );
    let inside = bounds.intersect(canvas);
    if inside.is_empty() {
        return PixelRect::EMPTY;
    }
    PixelRect {
        x: u32::try_from(inside.x0).unwrap_or(0),
        y: u32::try_from(inside.y0).unwrap_or(0),
        width: inside.width(),
        height: inside.height(),
    }
}

/// A fill op's uniform: inverse paint transform, canvas, opacity and the sRGB-store flag.
fn op_uniform(
    paint: &ScenePaint,
    canvas: [f32; 2],
    opacity: f32,
    encoded: bool,
) -> [u32; VECTOR_UNIFORM_WORDS] {
    let [xx, yx, xy, yy, x0, y0] = paint.inverse.as_coeffs();
    #[allow(clippy::cast_possible_truncation)]
    let narrow = |value: f64| value as f32;
    let mut floats = [0.0_f32; VECTOR_UNIFORM_WORDS];
    // Paint-space x = xx * x + xy * y + x0; y = yx * x + yy * y + y0.
    floats[0..4].copy_from_slice(&[narrow(xx), narrow(xy), narrow(x0), paint.space[0]]);
    floats[4..8].copy_from_slice(&[narrow(yx), narrow(yy), narrow(y0), paint.space[1]]);
    floats[8..12].copy_from_slice(&[
        canvas[0],
        canvas[1],
        opacity,
        if encoded { 1.0 } else { 0.0 },
    ]);
    floats[12..16].copy_from_slice(&[paint.a[0], paint.a[1], paint.b[0], paint.b[1]]);
    let kind: u32 = match paint.kind {
        PaintKind::Solid => 1,
        PaintKind::Linear => 2,
        PaintKind::Radial => 3,
        PaintKind::Conic => 4,
    };
    let count = u32::try_from(paint.stops.len().min(crate::MAX_GENERATOR_STOPS)).unwrap_or(0);
    for (index, stop) in paint
        .stops
        .iter()
        .take(crate::MAX_GENERATOR_STOPS)
        .enumerate()
    {
        let colors = VECTOR_UNIFORM_HEAD + crate::MAX_GENERATOR_STOPS + index * 4;
        floats[VECTOR_UNIFORM_HEAD + index] = stop.offset;
        floats[colors..colors + 4].copy_from_slice(&stop.color);
    }
    let mut words = floats.map(f32::to_bits);
    words[16..20].copy_from_slice(&[kind, paint.spread, count, 0]);
    words
}

fn op_uniform_plain(canvas: [f32; 2], opacity: f32) -> [u32; VECTOR_UNIFORM_WORDS] {
    let mut floats = [0.0_f32; VECTOR_UNIFORM_WORDS];
    floats[8..12].copy_from_slice(&[canvas[0], canvas[1], opacity, 0.0]);
    floats.map(f32::to_bits)
}

impl CachedVectorPipeline {
    pub(crate) fn pipeline_count(&self) -> usize {
        self.by_format
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
    }
}