hephaestus 0.2.0

Backend-agnostic 2D scene renderer for data visualization.
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
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
//! Vello backend. Wraps `vello::Scene` to implement [`SceneBuilder`] and owns
//! the wgpu device/queue/renderer needed for headless rasterization.

use crate::backend::convert;
use crate::backend::mesh;

use std::num::NonZeroUsize;

use crate::geometry::Shape as _;
use vello::{AaConfig, AaSupport, RenderParams, Renderer as VRenderer, RendererOptions, Scene};

use crate::backend::{BackendError, Renderer, WgpuRenderer};
use crate::blend::BlendMode;
use crate::brush::{Brush, Image, Sampling};
use crate::color::Color;
use crate::geometry::Affine;
use crate::mesh::Mesh;

use crate::path::{FillRule, Path};
use crate::pick::{self, PickId};
use crate::scene::{GlyphRun, SceneBuilder};
use crate::stroke::Stroke;

/// Minimum stroke width (in pixels) the pick pass uses, so hairline strokes
/// remain hittable even when the visual stroke is sub-pixel.
const MIN_PICK_STROKE_WIDTH: f64 = 2.0;

/// Largest number of draw-info words vello can rasterise in one pass.
///
/// Vello sizes its `bin_data` GPU buffer to a fixed `1 << 18` words and stores
/// the scene's draw-info stream at its front. A scene whose stream is longer
/// cannot be configured at all — the size arithmetic underflows before any GPU
/// work is dispatched. [`VelloScene::draw_info_words`] measures a scene against
/// this budget; the render entry points reject an over-budget scene with
/// [`BackendError::SceneTooLarge`].
///
/// A solid-brush fill or stroke costs one word, so this caps a scene at ~262k
/// flat-coloured objects. Gradient and image brushes cost more per draw.
pub const MAX_DRAW_INFO_WORDS: u32 = 1 << 18;

/// A `SceneBuilder` that writes into a `vello::Scene`.
///
/// When picking is enabled (constructed via `with_picking`), every
/// drawing call is also recorded into a parallel "pick" scene with its brush
/// replaced by a solid colour encoding the call's [`PickId`]. The renderer
/// rasterises both scenes; the pick scene is read back to a CPU u32 buffer
/// that powers hit tests.
pub struct VelloScene {
    inner: Scene,
    pick: Option<Scene>,
}

impl VelloScene {
    /// Build a scene with no picking machinery — file-export workloads should
    /// use this form (zero overhead).
    pub fn new() -> Self {
        Self {
            inner: Scene::new(),
            pick: None,
        }
    }

    /// Build a scene that records into both the display scene and a parallel
    /// pick scene. Used internally by [`VelloRenderer::with_picking`].
    pub(crate) fn with_picking() -> Self {
        Self {
            inner: Scene::new(),
            pick: Some(Scene::new()),
        }
    }

    /// Borrow the underlying `vello::Scene` (e.g. to render it).
    pub fn raw(&self) -> &Scene {
        &self.inner
    }

    /// Borrow the parallel pick scene, if picking is enabled.
    pub(crate) fn raw_pick(&self) -> Option<&Scene> {
        self.pick.as_ref()
    }

    /// Draw-info words the encoded display scene occupies, to be compared
    /// against [`MAX_DRAW_INFO_WORDS`].
    pub fn draw_info_words(&self) -> u32 {
        draw_info_words(&self.inner)
    }

    /// True when both the display scene and the pick scene fit the backend's
    /// draw budget, so a render will not be rejected.
    pub fn fits_draw_budget(&self) -> bool {
        check_draw_budget(&self.inner).is_ok()
            && self
                .pick
                .as_ref()
                .is_none_or(|p| check_draw_budget(p).is_ok())
    }
}

/// Length of a scene's draw-info stream, measured the way vello sizes it.
fn draw_info_words(scene: &Scene) -> u32 {
    scene
        .encoding()
        .draw_tags
        .iter()
        .map(|tag| tag.info_size())
        .sum()
}

fn check_draw_budget(scene: &Scene) -> Result<(), BackendError> {
    let used = draw_info_words(scene);
    if used > MAX_DRAW_INFO_WORDS {
        return Err(BackendError::SceneTooLarge {
            used,
            max: MAX_DRAW_INFO_WORDS,
        });
    }
    Ok(())
}

impl Default for VelloScene {
    fn default() -> Self {
        Self::new()
    }
}

impl SceneBuilder for VelloScene {
    /// Clears both the display scene and, when picking is enabled, the
    /// parallel pick scene.
    fn clear(&mut self) {
        self.inner.reset();
        if let Some(p) = &mut self.pick {
            p.reset();
        }
    }

    fn fill(
        &mut self,
        rule: FillRule,
        transform: Affine,
        brush: &Brush,
        brush_transform: Option<Affine>,
        path: &Path,
        pick_id: PickId,
    ) {
        let fill_rule = convert::fill_rule(rule);
        self.inner
            .fill(fill_rule, transform, brush, brush_transform, path);
        if let Some(pick) = &mut self.pick {
            if let Some(id) = pick::raw_id(pick_id) {
                let pick_brush = Brush::Solid(pick::id_to_color(id));
                pick.fill(fill_rule, transform, &pick_brush, None, path);
            }
        }
    }

    fn stroke(
        &mut self,
        stroke: &Stroke,
        transform: Affine,
        brush: &Brush,
        brush_transform: Option<Affine>,
        path: &Path,
        pick_id: PickId,
    ) {
        self.inner
            .stroke(stroke, transform, brush, brush_transform, path);
        if let Some(pick) = &mut self.pick {
            if let Some(id) = pick::raw_id(pick_id) {
                let pick_brush = Brush::Solid(pick::id_to_color(id));
                let mut pick_stroke = stroke.clone();
                if pick_stroke.width < MIN_PICK_STROKE_WIDTH {
                    pick_stroke.width = MIN_PICK_STROKE_WIDTH;
                }
                pick.stroke(&pick_stroke, transform, &pick_brush, None, path);
            }
        }
    }

    fn draw_image(
        &mut self,
        image: &Image,
        transform: Affine,
        sampling: Sampling,
        alpha: f32,
        pick_id: PickId,
    ) {
        let sampler = peniko::ImageSampler {
            x_extend: peniko::Extend::Pad,
            y_extend: peniko::Extend::Pad,
            quality: convert::sampling_to_quality(sampling),
            alpha,
        };
        let brush = peniko::ImageBrush {
            image: image.clone(),
            sampler,
        };
        self.inner.draw_image(&brush, transform);
        if let Some(pick) = &mut self.pick {
            if let Some(id) = pick::raw_id(pick_id) {
                let pick_brush = Brush::Solid(pick::id_to_color(id));
                let bounds =
                    crate::geometry::Rect::new(0.0, 0.0, image.width as f64, image.height as f64)
                        .to_path(0.1);
                pick.fill(peniko::Fill::NonZero, transform, &pick_brush, None, &bounds);
            }
        }
    }

    fn draw_glyphs(&mut self, run: &GlyphRun<'_>, pick_id: PickId) {
        let style: peniko::StyleRef<'_> = match run.style {
            Some(stroke) => peniko::StyleRef::from(stroke),
            None => peniko::StyleRef::from(peniko::Fill::NonZero),
        };
        let builder = self
            .inner
            .draw_glyphs(run.font.data())
            .font_size(run.font_size)
            .transform(run.transform)
            .glyph_transform(run.glyph_transform)
            .brush(run.brush)
            .brush_alpha(run.brush_alpha)
            .hint(run.hint);
        builder.draw(
            style,
            run.glyphs.iter().map(|g| vello::Glyph {
                id: g.id,
                x: g.x,
                y: g.y,
            }),
        );

        if let Some(pick) = &mut self.pick {
            if let Some(id) = pick::raw_id(pick_id) {
                let pick_brush = Brush::Solid(pick::id_to_color(id));
                let pick_style: peniko::StyleRef<'_> = match run.style {
                    Some(stroke) => peniko::StyleRef::from(stroke),
                    None => peniko::StyleRef::from(peniko::Fill::NonZero),
                };
                let pick_builder = pick
                    .draw_glyphs(run.font.data())
                    .font_size(run.font_size)
                    .transform(run.transform)
                    .glyph_transform(run.glyph_transform)
                    .brush(&pick_brush)
                    .brush_alpha(1.0)
                    .hint(run.hint);
                pick_builder.draw(
                    pick_style,
                    run.glyphs.iter().map(|g| vello::Glyph {
                        id: g.id,
                        x: g.x,
                        y: g.y,
                    }),
                );
            }
        }
    }

    fn draw_mesh(&mut self, mesh: &Mesh, transform: Affine, pick_id: PickId) {
        // Neither vello nor peniko has an indexed-mesh primitive, so the mesh
        // becomes fills. Routing them back through `self.fill` is what gives
        // the pick scene its copy of each triangle.
        mesh::decompose(mesh, transform, pick_id, self);
    }

    fn push_layer(&mut self, blend: BlendMode, alpha: f32, transform: Affine, clip: &Path) {
        self.inner.push_layer(
            peniko::Fill::NonZero,
            convert::blend_mode(blend),
            alpha,
            transform,
            clip,
        );
        if let Some(pick) = &mut self.pick {
            // Mirror the layer's clip/transform so subsequent draws are clipped
            // identically in the pick buffer, but normalize the blend so it
            // doesn't distort id colors. Alpha = 1 prevents translucent layers
            // from fading ids into the no-hit sentinel.
            pick.push_layer(
                peniko::Fill::NonZero,
                convert::blend_mode(BlendMode::NORMAL),
                1.0,
                transform,
                clip,
            );
        }
    }

    fn pop_layer(&mut self) {
        self.inner.pop_layer();
        if let Some(pick) = &mut self.pick {
            pick.pop_layer();
        }
    }
}

// ---------- Renderer ----------

/// Headless target: storage texture + readback buffer, both sized for the
/// current frame. Recreated on size change.
struct HeadlessTarget {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
    readback: wgpu::Buffer,
    width: u32,
    height: u32,
    /// Bytes per row in the readback buffer (padded to wgpu's alignment).
    padded_bytes_per_row: u32,
}

impl HeadlessTarget {
    /// Allocate a storage texture and a `width`-row-padded readback
    /// buffer at the given dimensions.
    fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
        let bytes_per_row = width * 4;
        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
        let padded_bytes_per_row = bytes_per_row.div_ceil(align) * align;
        let buffer_size = (padded_bytes_per_row as u64) * (height as u64);

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("hephaestus.vello.target"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let readback = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("hephaestus.vello.readback"),
            size: buffer_size,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        Self {
            texture,
            view,
            readback,
            width,
            height,
            padded_bytes_per_row,
        }
    }
}

/// Hephaestus Vello renderer: owns wgpu device/queue, the vello::Renderer, the
/// scene being built, and per-size headless targets.
///
/// When constructed via [`Self::with_picking`], the renderer also rasterises a
/// parallel "pick" scene to a second target, reads it back after each render,
/// A pick readback in flight: a slot the `map_async` callback fills, and the
/// dimensions it covers.
///
/// A slot rather than a future, so completion can be *checked* instead of
/// awaited. Awaiting would mean holding a borrow of the renderer across a
/// suspension point, which a browser host — where the only caller is a
/// callback that may re-enter — cannot do safely.
struct PendingPick {
    slot: std::sync::Arc<std::sync::Mutex<Option<Result<(), wgpu::BufferAsyncError>>>>,
    width: u32,
    height: u32,
}

/// and caches the result in a CPU-side hitmap that powers [`Self::pick_at`].
pub struct VelloRenderer {
    device: wgpu::Device,
    queue: wgpu::Queue,
    renderer: VRenderer,
    scene: VelloScene,
    target: Option<HeadlessTarget>,
    pick_target: Option<HeadlessTarget>,
    /// Tightly-packed RGBA8 bytes of the most-recent pick render, viewable as
    /// `&[u32]` via bytemuck. `None` until the first picking-enabled render.
    hitmap: Option<Vec<u32>>,
    hitmap_dims: Option<(u32, u32)>,
    /// A pick readback that has been submitted but not yet drained, with the
    /// dimensions it was submitted at. `Some` only between `submit_pick` and
    /// `finish_pick`, which is the window a browser has to await across.
    pick_pending: Option<PendingPick>,
    /// Whether the coming render refreshes the hitmap. See
    /// [`VelloRenderer::set_refresh_pick`].
    refresh_pick: bool,
}

impl VelloRenderer {
    /// Build a renderer with no picking machinery. File-export workloads
    /// should use this form; nothing in the pick path is allocated.
    pub fn new() -> Result<Self, BackendError> {
        pollster::block_on(Self::new_async(false))
    }

    /// Build a renderer with picking enabled. Each call to
    /// [`Self::render_to_buffer`] additionally rasterises the pick scene and
    /// reads it back into an internal hitmap.
    pub fn with_picking() -> Result<Self, BackendError> {
        pollster::block_on(Self::new_async(true))
    }

    /// Build a renderer that shares an existing wgpu device and queue —
    /// e.g. the device backing a window's swap chain. Use this together
    /// with [`crate::backend::WgpuRenderer::render_to_texture`]
    /// to display the scene without a CPU readback round-trip.
    ///
    /// `device` and `queue` are handles (Arc-backed in wgpu); the host
    /// keeps its own and the renderer holds clones.
    pub fn with_device(device: &wgpu::Device, queue: &wgpu::Queue) -> Result<Self, BackendError> {
        Self::build(device.clone(), queue.clone(), false)
    }

    /// Like [`Self::with_device`] but enables picking. The pick scene is
    /// rasterised into a backend-owned headless target and read back to
    /// CPU on every render, regardless of whether the display render goes
    /// to a buffer or directly to a texture.
    pub fn with_device_and_picking(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
    ) -> Result<Self, BackendError> {
        Self::build(device.clone(), queue.clone(), true)
    }

    async fn new_async(picking: bool) -> Result<Self, BackendError> {
        let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
        // GL is included alongside PRIMARY so the GLES backend compiled in
        // for unix is actually reachable: a Linux host without Vulkan falls
        // back to it rather than finding no adapter at all. `WGPU_BACKENDS`
        // overrides the choice when a host needs to pin one. On wasm the
        // flag finds nothing — vello rasterises through compute pipelines,
        // which WebGL2 has no stage for, so only WebGPU is compiled in.
        desc.backends =
            wgpu::Backends::from_env().unwrap_or(wgpu::Backends::PRIMARY | wgpu::Backends::GL);
        let instance = wgpu::Instance::new(desc);
        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
            .map_err(|_| BackendError::NoAdapter)?;

        let limits = wgpu::Limits::default();
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("hephaestus.vello.device"),
                required_features: wgpu::Features::empty(),
                required_limits: limits,
                memory_hints: wgpu::MemoryHints::default(),
                trace: wgpu::Trace::Off,
                experimental_features: wgpu::ExperimentalFeatures::default(),
            })
            .await
            .map_err(|e| BackendError::DeviceRequest(e.to_string()))?;

        Self::build(device, queue, picking)
    }

    /// Shared post-device construction: build the vello renderer and the
    /// (optionally picking) scene against an already-owned device/queue.
    fn build(
        device: wgpu::Device,
        queue: wgpu::Queue,
        picking: bool,
    ) -> Result<Self, BackendError> {
        let renderer = VRenderer::new(
            &device,
            RendererOptions {
                use_cpu: false,
                antialiasing_support: AaSupport::area_only(),
                num_init_threads: NonZeroUsize::new(1),
                pipeline_cache: None,
            },
        )
        .map_err(|e| BackendError::Other(format!("vello renderer init: {e}")))?;

        let scene = if picking {
            VelloScene::with_picking()
        } else {
            VelloScene::new()
        };

        Ok(Self {
            device,
            queue,
            renderer,
            scene,
            target: None,
            pick_target: None,
            hitmap: None,
            hitmap_dims: None,
            pick_pending: None,
            refresh_pick: true,
        })
    }

    /// Re-allocate the display headless target when the requested
    /// dimensions don't match the cached ones. Only used by the
    /// [`Renderer::render_to_buffer`] path — the texture-target path
    /// writes directly into the host's view and skips this entirely.
    fn ensure_display_target(&mut self, width: u32, height: u32) {
        let need_new = match &self.target {
            None => true,
            Some(t) => t.width != width || t.height != height,
        };
        if need_new {
            self.target = Some(HeadlessTarget::new(&self.device, width, height));
        }
    }

    /// Re-allocate the pick headless target when picking is enabled and
    /// the dimensions don't match the cached ones. No-op when picking is
    /// disabled.
    fn ensure_pick_target(&mut self, width: u32, height: u32) {
        if self.scene.raw_pick().is_none() {
            return;
        }
        let need_new = match &self.pick_target {
            None => true,
            Some(t) => t.width != width || t.height != height,
        };
        if need_new {
            self.pick_target = Some(HeadlessTarget::new(&self.device, width, height));
        }
    }

    /// Reject a scene vello cannot configure, before any GPU work is queued.
    fn check_scene_budget(&self) -> Result<(), BackendError> {
        check_draw_budget(self.scene.raw())?;
        if let Some(pick) = self.scene.raw_pick() {
            check_draw_budget(pick)?;
        }
        Ok(())
    }

    /// Rasterise the pick scene into the cached pick target, copy it back
    /// to CPU, and refresh the hitmap. Assumes [`Self::ensure_pick_target`]
    /// has already been called and picking is enabled.
    ///
    /// Blocks until the readback lands. [`Self::submit_pick`] and
    /// [`Self::finish_pick`] are the same work either side of the wait, for a
    /// host that cannot park a thread.
    fn render_pick_and_readback(&mut self, width: u32, height: u32) -> Result<(), BackendError> {
        self.submit_pick(width, height)?;
        // A waiting poll returns only once the map callback has run, so the
        // slot is filled by the time this is reached.
        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
        if !self.try_finish_pick()? {
            return Err(BackendError::Readback(
                "pick readback did not complete after a blocking device poll".into(),
            ));
        }
        Ok(())
    }

    /// Rasterise the pick scene and submit its readback, without waiting.
    ///
    /// Pair with [`Self::finish_pick`]. Assumes [`Self::ensure_pick_target`]
    /// has already been called and picking is enabled.
    fn submit_pick(&mut self, width: u32, height: u32) -> Result<(), BackendError> {
        let pick_scene = self.scene.raw_pick().expect("pick scene present");
        let pick_target = self.pick_target.as_ref().expect("pick target ensured");

        // AaConfig::Area is the only mode vello offers that our AaSupport
        // opted into, and vello has no way to turn antialiasing off — so the
        // pick scene is antialiased whether or not that suits it, and edge
        // pixels blend.
        //
        // The transparent base is what makes that survivable. Vello
        // unpremultiplies on output, so a mark's fringe over *nothing*
        // divides back out to its exact id with coverage left in alpha. An
        // opaque base would instead blend every fringe toward black and hand
        // back a plausible but wrong id at full alpha. Measured on one mark
        // tagged 200: transparent base leaves 140 stray pixels, all at alpha
        // 0 and rejected by `pick::decode`; an opaque base leaves 228, all at
        // alpha 255 and undetectable.
        //
        // What neither base fixes: a fringe over *other picked content*
        // blends two real ids and lands at full alpha. See the conflation
        // note on `crate::pick`.
        self.renderer
            .render_to_texture(
                &self.device,
                &self.queue,
                pick_scene,
                &pick_target.view,
                &RenderParams {
                    base_color: Color::new([0.0, 0.0, 0.0, 0.0]),
                    width,
                    height,
                    antialiasing_method: AaConfig::Area,
                },
            )
            .map_err(|e| BackendError::Other(format!("vello pick render: {e}")))?;

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("hephaestus.vello.pick_readback"),
            });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &pick_target.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &pick_target.readback,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(pick_target.padded_bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        self.queue.submit(std::iter::once(encoder.finish()));

        let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
        let sink = std::sync::Arc::clone(&slot);
        pick_target
            .readback
            .slice(..)
            .map_async(wgpu::MapMode::Read, move |res| {
                if let Ok(mut guard) = sink.lock() {
                    *guard = Some(res);
                }
            });
        self.pick_pending = Some(PendingPick {
            slot,
            width,
            height,
        });
        Ok(())
    }

    /// Drain a readback submitted by [`Self::submit_pick`] into the hitmap,
    /// if it has landed.
    ///
    /// Returns whether the hitmap was refreshed: `false` means nothing was in
    /// flight, or the GPU has not finished. Never blocks, so a host that
    /// cannot park a thread calls this and accepts that the hitmap may lag
    /// the drawn frame.
    ///
    /// Only meaningful after [`Self::render_to_texture_deferring_pick`]; the
    /// blocking render paths drain their own readback before returning.
    pub fn try_finish_pick(&mut self) -> Result<bool, BackendError> {
        let Some(pending) = self.pick_pending.as_ref() else {
            return Ok(false);
        };
        let landed = pending
            .slot
            .lock()
            .map_err(|_| BackendError::Readback("pick readback slot poisoned".into()))?
            .take();
        let Some(result) = landed else {
            return Ok(false);
        };

        let PendingPick { width, height, .. } =
            self.pick_pending.take().expect("checked just above");
        result.map_err(|e| BackendError::Readback(e.to_string()))?;

        let pick_target = self.pick_target.as_ref().expect("pick target ensured");
        let pick_slice = pick_target.readback.slice(..);

        let row_bytes = (width as usize) * 4;
        let row_px = width as usize;
        let total_px = (width as usize) * (height as usize);
        let hitmap = self.hitmap.get_or_insert_with(Vec::new);
        if hitmap.len() != total_px {
            hitmap.resize(total_px, 0);
        }
        {
            let data = pick_slice.get_mapped_range();
            let padded = pick_target.padded_bytes_per_row as usize;
            for y in 0..height as usize {
                let src = &data[y * padded..y * padded + row_bytes];
                let dst: &mut [u8] =
                    bytemuck::cast_slice_mut(&mut hitmap[y * row_px..y * row_px + row_px]);
                dst.copy_from_slice(src);
            }
        }
        pick_target.readback.unmap();
        self.hitmap_dims = Some((width, height));
        Ok(true)
    }

    /// Rasterise into `view` and submit the pick pass without waiting on it.
    ///
    /// The non-blocking counterpart to
    /// [`WgpuRenderer::render_to_texture`](crate::WgpuRenderer::render_to_texture),
    /// whose pick readback parks the calling thread until the GPU is done —
    /// which a browser's main thread cannot do. Pair with
    /// [`Self::try_finish_pick`]: until that drains, [`Self::pick_at`] keeps
    /// answering from the previous frame's hitmap.
    ///
    /// Identical to the trait method when picking is disabled.
    pub fn render_to_texture_deferring_pick(
        &mut self,
        view: &wgpu::TextureView,
        width: u32,
        height: u32,
        background: Color,
    ) -> Result<(), BackendError> {
        self.check_scene_budget()?;
        self.renderer
            .render_to_texture(
                &self.device,
                &self.queue,
                self.scene.raw(),
                view,
                &RenderParams {
                    base_color: background,
                    width,
                    height,
                    antialiasing_method: AaConfig::Area,
                },
            )
            .map_err(|e| BackendError::Other(format!("vello render: {e}")))?;

        if self.refreshes_pick() {
            // Drain first: that unmaps the readback buffer, and `map_async`
            // on a still-mapped buffer is a validation error. Draining also
            // has to happen before `ensure_pick_target`, which may reallocate
            // the target the in-flight readback is reading from.
            self.try_finish_pick()?;
            // Still in flight — skip this frame rather than queue a second
            // map on the same buffer. The hitmap lags until it lands, which
            // `pick_at` already documents.
            if self.pick_pending.is_none() {
                self.ensure_pick_target(width, height);
                self.submit_pick(width, height)?;
            }
        }
        Ok(())
    }

    /// Control whether the coming render refreshes the hitmap.
    ///
    /// The pick pass here is a second GPU rasterisation plus a readback, so it
    /// costs less than it does on a CPU-coverage backend but is not free. A
    /// host redrawing faster than it queries — mid-resize, say — can leave the
    /// hitmap alone for a few frames.
    ///
    /// While it is off, [`Self::pick_at`] keeps answering from the last render
    /// that refreshed. Set it back to `true` (the default) and the next render
    /// brings the hitmap up to date. No effect when picking was not enabled at
    /// construction.
    pub fn set_refresh_pick(&mut self, refresh: bool) {
        self.refresh_pick = refresh;
    }

    /// Whether the coming render will refresh the hitmap.
    pub fn refreshes_pick(&self) -> bool {
        self.refresh_pick && self.scene.raw_pick().is_some()
    }

    /// Look up the id at pixel `(x, y)` in the most-recent pick render.
    /// Returns `None` if picking is disabled, no render has been performed
    /// yet, the coordinates are out of range, or the pixel is the "no hit"
    /// sentinel (uncovered or [`PickId::Block`]).
    ///
    /// Note: picking does not respect display alpha; see the [`crate::pick`]
    /// module docs for the alpha-insensitive picking limitation.
    pub fn pick_at(&self, x: u32, y: u32) -> Option<u32> {
        let (w, h) = self.hitmap_dims?;
        if x >= w || y >= h {
            return None;
        }
        let map = self.hitmap.as_deref()?;
        pick::decode(map[(y * w + x) as usize])
    }

    /// Borrow the full hitmap as a flat `&[u32]` of `width * height` pixels
    /// laid out row-major. Useful for bulk queries (marquee selection etc.).
    /// Returns `None` if picking is disabled or no render has been performed.
    pub fn hitmap(&self) -> Option<&[u32]> {
        self.hitmap.as_deref()
    }
}

impl Renderer for VelloRenderer {
    type Scene = VelloScene;

    fn scene(&mut self) -> &mut Self::Scene {
        &mut self.scene
    }

    fn render_to_buffer(
        &mut self,
        width: u32,
        height: u32,
        background: Color,
        out: &mut [u8],
    ) -> Result<(), BackendError> {
        let expected = (width as usize) * (height as usize) * 4;
        if out.len() != expected {
            return Err(BackendError::BufferSize {
                expected,
                actual: out.len(),
            });
        }
        self.check_scene_budget()?;

        self.ensure_display_target(width, height);
        self.ensure_pick_target(width, height);
        let target = self.target.as_ref().unwrap();

        self.renderer
            .render_to_texture(
                &self.device,
                &self.queue,
                self.scene.raw(),
                &target.view,
                &RenderParams {
                    base_color: background,
                    width,
                    height,
                    antialiasing_method: AaConfig::Area,
                },
            )
            .map_err(|e| BackendError::Other(format!("vello render: {e}")))?;

        // If picking is enabled, render the parallel pick scene over a
        // transparent base. See `render_pick_and_readback` for why the base
        // must stay transparent.
        let picking = self.refreshes_pick();
        if picking {
            let pick_scene = self.scene.raw_pick().unwrap();
            let pick_target = self.pick_target.as_ref().expect("pick target ensured");
            // Same AA and base-colour contract as `render_pick_and_readback`.
            self.renderer
                .render_to_texture(
                    &self.device,
                    &self.queue,
                    pick_scene,
                    &pick_target.view,
                    &RenderParams {
                        base_color: Color::new([0.0, 0.0, 0.0, 0.0]),
                        width,
                        height,
                        antialiasing_method: AaConfig::Area,
                    },
                )
                .map_err(|e| BackendError::Other(format!("vello pick render: {e}")))?;
        }

        // Encode both texture→buffer copies into one command buffer so they
        // share a single submit + map round-trip.
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("hephaestus.vello.readback"),
            });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &target.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &target.readback,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(target.padded_bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        if picking {
            let pick_target = self.pick_target.as_ref().unwrap();
            encoder.copy_texture_to_buffer(
                wgpu::TexelCopyTextureInfo {
                    texture: &pick_target.texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::TexelCopyBufferInfo {
                    buffer: &pick_target.readback,
                    layout: wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(pick_target.padded_bytes_per_row),
                        rows_per_image: Some(height),
                    },
                },
                wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
            );
        }
        self.queue.submit(std::iter::once(encoder.finish()));

        let display_slice = target.readback.slice(..);
        let (display_tx, display_rx) = futures_intrusive::channel::shared::oneshot_channel();
        display_slice.map_async(wgpu::MapMode::Read, move |res| {
            let _ = display_tx.send(res);
        });

        let pick_rx = if picking {
            let pick_target = self.pick_target.as_ref().unwrap();
            let pick_slice = pick_target.readback.slice(..);
            let (pick_tx, pick_rx) = futures_intrusive::channel::shared::oneshot_channel();
            pick_slice.map_async(wgpu::MapMode::Read, move |res| {
                let _ = pick_tx.send(res);
            });
            Some(pick_rx)
        } else {
            None
        };

        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());

        match pollster::block_on(display_rx.receive()) {
            Some(Ok(())) => {}
            Some(Err(e)) => return Err(BackendError::Readback(e.to_string())),
            None => return Err(BackendError::Readback("map_async sender dropped".into())),
        }
        if let Some(rx) = pick_rx.as_ref() {
            match pollster::block_on(rx.receive()) {
                Some(Ok(())) => {}
                Some(Err(e)) => return Err(BackendError::Readback(e.to_string())),
                None => {
                    return Err(BackendError::Readback(
                        "map_async pick sender dropped".into(),
                    ))
                }
            }
        }

        let row_bytes = (width as usize) * 4;
        {
            let data = display_slice.get_mapped_range();
            let padded = target.padded_bytes_per_row as usize;
            for y in 0..height as usize {
                let src = &data[y * padded..y * padded + row_bytes];
                let dst = &mut out[y * row_bytes..y * row_bytes + row_bytes];
                dst.copy_from_slice(src);
            }
        }
        target.readback.unmap();

        if picking {
            let pick_target = self.pick_target.as_ref().unwrap();
            let row_px = width as usize;
            let total_px = (width as usize) * (height as usize);
            let hitmap = self.hitmap.get_or_insert_with(Vec::new);
            if hitmap.len() != total_px {
                hitmap.resize(total_px, 0);
            }
            let pick_slice = pick_target.readback.slice(..);
            {
                let data = pick_slice.get_mapped_range();
                let padded = pick_target.padded_bytes_per_row as usize;
                for y in 0..height as usize {
                    let src = &data[y * padded..y * padded + row_bytes];
                    let dst: &mut [u8] =
                        bytemuck::cast_slice_mut(&mut hitmap[y * row_px..y * row_px + row_px]);
                    dst.copy_from_slice(src);
                }
            }
            pick_target.readback.unmap();
            self.hitmap_dims = Some((width, height));
        }

        Ok(())
    }
}

impl WgpuRenderer for VelloRenderer {
    const REQUIRED_TARGET_USAGE: wgpu::TextureUsages = wgpu::TextureUsages::STORAGE_BINDING;

    const TARGET_IS_PREMULTIPLIED: bool = false;

    fn render_to_texture(
        &mut self,
        view: &wgpu::TextureView,
        width: u32,
        height: u32,
        background: Color,
    ) -> Result<(), BackendError> {
        self.check_scene_budget()?;
        self.renderer
            .render_to_texture(
                &self.device,
                &self.queue,
                self.scene.raw(),
                view,
                &RenderParams {
                    base_color: background,
                    width,
                    height,
                    antialiasing_method: AaConfig::Area,
                },
            )
            .map_err(|e| BackendError::Other(format!("vello render: {e}")))?;

        // Picking still goes through the backend-owned pick target +
        // CPU readback. Display has no readback to wait on, so the pick
        // submit / poll happens after the display submit returns.
        if self.refreshes_pick() {
            self.ensure_pick_target(width, height);
            self.render_pick_and_readback(width, height)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::color::rgb8;
    use crate::geometry::Point;

    /// Add `n` flat-coloured triangles, each its own draw object.
    fn solid_fills(scene: &mut VelloScene, n: usize) {
        let brush = Brush::Solid(rgb8(10, 20, 30));
        for i in 0..n {
            let x = (i % 256) as f64;
            let mut path = Path::new();
            path.move_to(Point::new(x, 0.0));
            path.line_to(Point::new(x + 1.0, 0.0));
            path.line_to(Point::new(x + 1.0, 1.0));
            path.close_path();
            scene.fill(
                FillRule::NonZero,
                Affine::IDENTITY,
                &brush,
                None,
                &path,
                PickId::Skip,
            );
        }
    }

    #[test]
    fn an_empty_scene_spends_no_draw_budget() {
        let scene = VelloScene::new();
        assert_eq!(scene.draw_info_words(), 0);
        assert!(scene.fits_draw_budget());
    }

    #[test]
    fn each_solid_fill_costs_one_draw_info_word() {
        let mut scene = VelloScene::new();
        solid_fills(&mut scene, 3);
        assert_eq!(scene.draw_info_words(), 3);
    }

    #[test]
    fn clearing_a_scene_returns_its_draw_budget() {
        let mut scene = VelloScene::new();
        solid_fills(&mut scene, 5);
        scene.clear();
        assert_eq!(scene.draw_info_words(), 0);
    }

    #[test]
    fn a_scene_at_the_cap_fits_but_one_draw_more_does_not() {
        let mut scene = VelloScene::new();
        solid_fills(&mut scene, MAX_DRAW_INFO_WORDS as usize);
        assert!(scene.fits_draw_budget());

        solid_fills(&mut scene, 1);
        assert!(!scene.fits_draw_budget());
        assert!(matches!(
            check_draw_budget(scene.raw()),
            Err(BackendError::SceneTooLarge { used, max })
                if used == MAX_DRAW_INFO_WORDS + 1 && max == MAX_DRAW_INFO_WORDS
        ));
    }
}