aetna-wgpu 0.3.0

Aetna — wgpu backend (native + wasm)
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
//! `wgpu` backend for custom Aetna hosts.
//!
//! Most applications should implement `aetna_core::App` and run it
//! through `aetna-winit-wgpu`. Use this crate directly when you are
//! writing your own host, embedding Aetna into an existing `wgpu`
//! renderer, or producing headless render artifacts.
//!
//! The public entry point is [`Runner`]. It owns:
//!
//! - GPU resources: pipelines, buffers, text atlas, and icon atlas.
//! - Backend-agnostic interaction state shared through
//!   `aetna_core::runtime::RunnerCore`.
//! - A snapshot of the last laid-out tree so input arriving between
//!   frames hit-tests against the geometry the user can see.
//!
//! # Custom host loop
//!
//! The runner does not own the device, queue, swapchain, window, or
//! event loop. A host creates those resources, forwards input into the
//! runner, builds a fresh `El` tree, prepares GPU buffers, and renders:
//!
//! ```ignore
//! use aetna_core::prelude::*;
//! use aetna_wgpu::Runner;
//!
//! let mut runner = Runner::new(&device, &queue, surface_format);
//! runner.set_surface_size(surface_width, surface_height);
//!
//! // Per frame:
//! app.before_build();
//! let theme = app.theme();
//! let mut tree = app.build(&aetna_core::BuildCx::new(&theme));
//! runner.set_hotkeys(app.hotkeys());
//! runner.set_theme(theme);
//! runner.prepare(&device, &queue, &mut tree, viewport, scale_factor);
//! runner.render(&device, &mut encoder, target_texture, target_view, None, load_op);
//! ```
//!
//! `prepare` is split from `render`/`draw` so all `queue.write_buffer`
//! calls and atlas uploads happen before render-pass recording, matching
//! `wgpu`'s expected order. Coordinates passed to pointer methods are
//! logical pixels; render targets are physical pixels, so pass the host
//! scale factor to [`Runner::prepare`].
//!
//! Use [`Runner::render`] when Aetna should own pass boundaries. This is
//! required for backdrop-sampling custom shaders. Use [`Runner::draw`]
//! only when you are already inside a host-owned pass and do not need
//! backdrop sampling.
//!
//! # Custom shaders
//!
//! Call [`Runner::register_shader`] with a name and WGSL source. The
//! shader's vertex/fragment must use the shared instance layout — see
//! `shaders/rounded_rect.wgsl` (in aetna-core) for the canonical
//! example. Bind the shader at a node via
//! `El::shader(ShaderBinding::custom(name).with(...))`. Per-instance
//! uniforms map to three generic `vec4` slots:
//!
//! | Uniform key | Slot (`@location`) | Accepted types |
//! |---|---|---|
//! | `vec_a` | 2 | `Color` (rgba 0..1) or `Vec4` |
//! | `vec_b` | 3 | `Color` or `Vec4` |
//! | `vec_c` | 4 | `Vec4` (or fall back to scalar `f32` packed in `.x`) |
//!
//! Stock `rounded_rect` reuses the same layout but reads its own named
//! uniforms (`fill`, `stroke`, `stroke_width`, `radius`, `shadow`).

mod icon;
mod image;
mod instance;
mod msaa;
mod pipeline;
mod text;

pub use crate::msaa::MsaaTarget;

use std::collections::{HashMap, HashSet};
// `web_time::Instant` is API-identical to `std::time::Instant` on
// native and uses `performance.now()` on wasm32 — std's `Instant::now()`
// panics in the browser because there is no monotonic clock there.
use web_time::Instant;

use wgpu::util::DeviceExt;

use aetna_core::event::{KeyChord, KeyModifiers, PointerButton, UiEvent, UiKey};
use aetna_core::ir::TextAnchor;
use aetna_core::paint::{IconRunKind, PhysicalScissor, QuadInstance};
use aetna_core::runtime::{RecordedPaint, RunnerCore, TextRecorder};
use aetna_core::shader::{ShaderHandle, StockShader, stock_wgsl};
use aetna_core::state::{AnimationMode, UiState};
use aetna_core::text::atlas::RunStyle;
use aetna_core::theme::Theme;
use aetna_core::tree::{Color, El, Rect, TextWrap};
use aetna_core::vector::IconMaterial;

pub use aetna_core::paint::PaintItem;
pub use aetna_core::runtime::{PointerMove, PrepareResult, PrepareTimings};

use crate::icon::IconPaint;
use crate::image::ImagePaint;
use crate::instance::set_scissor;
use crate::pipeline::{FrameUniforms, build_quad_pipeline};
use crate::text::TextPaint;

/// Initial size for the dynamic instance buffer (grows as needed).
const INITIAL_INSTANCE_CAPACITY: usize = 256;

/// Wgpu runtime owned by the host. One instance per surface/format.
///
/// All backend-agnostic state — interaction state, paint-stream scratch,
/// per-stage layout/animation hooks — lives in `core: RunnerCore` and
/// is shared with the vulkano backend. The fields below are wgpu-specific
/// resources only.
pub struct Runner {
    target_format: wgpu::TextureFormat,
    sample_count: u32,

    // Shared resources.
    pipeline_layout: wgpu::PipelineLayout,
    /// Pipeline layout for `samples_backdrop` custom shaders — adds
    /// `@group(1)` for the snapshot texture + sampler.
    backdrop_pipeline_layout: wgpu::PipelineLayout,
    quad_bind_group: wgpu::BindGroup,
    backdrop_bind_layout: wgpu::BindGroupLayout,
    backdrop_sampler: wgpu::Sampler,
    frame_buf: wgpu::Buffer,
    quad_vbo: wgpu::Buffer,
    instance_buf: wgpu::Buffer,
    instance_capacity: usize,

    // One pipeline per registered shader (stock + custom).
    pipelines: HashMap<ShaderHandle, wgpu::RenderPipeline>,
    // Custom shader names registered with `samples_backdrop=true`. The
    // paint scheduler queries this to insert pass boundaries before the
    // first backdrop-sampling draw.
    backdrop_shaders: HashSet<&'static str>,

    // stock::text resources — atlas, page textures, glyph instances.
    text_paint: TextPaint,
    // stock::icon_line resources — vector icon stroke instances.
    icon_paint: IconPaint,
    // stock::image resources — per-image texture cache + instance buf.
    image_paint: ImagePaint,

    /// Lazily-allocated snapshot of the color target, sized to match
    /// the current target on each `render()`. Backdrop-sampling
    /// shaders read this via `@group(1)` after Pass A.
    snapshot: Option<SnapshotTexture>,
    /// Bind group binding the snapshot view + sampler. Rebuilt each
    /// time the snapshot texture is reallocated.
    backdrop_bind_group: Option<wgpu::BindGroup>,

    /// Wall-clock origin for the `time` field in `FrameUniforms`.
    /// `prepare()` writes `(now - start_time).as_secs_f32()`.
    start_time: Instant,

    // Backend-agnostic state shared with aetna-vulkano: interaction
    // state, paint-stream scratch (quad_scratch / runs / paint_items),
    // viewport_px, last_tree, the 13 input plumbing methods.
    core: RunnerCore,
}

struct SnapshotTexture {
    texture: wgpu::Texture,
    extent: (u32, u32),
}

struct PaintRecorder<'a> {
    text: &'a mut TextPaint,
    icons: &'a mut IconPaint,
    images: &'a mut ImagePaint,
    device: &'a wgpu::Device,
    queue: &'a wgpu::Queue,
}

impl TextRecorder for PaintRecorder<'_> {
    fn record(
        &mut self,
        rect: Rect,
        scissor: Option<PhysicalScissor>,
        style: &aetna_core::text::atlas::RunStyle,
        text: &str,
        size: f32,
        line_height: f32,
        wrap: TextWrap,
        anchor: TextAnchor,
        scale_factor: f32,
    ) -> std::ops::Range<usize> {
        self.text.record(
            rect,
            scissor,
            style,
            text,
            size,
            line_height,
            wrap,
            anchor,
            scale_factor,
        )
    }

    fn record_runs(
        &mut self,
        rect: Rect,
        scissor: Option<PhysicalScissor>,
        runs: &[(String, RunStyle)],
        size: f32,
        line_height: f32,
        wrap: TextWrap,
        anchor: TextAnchor,
        scale_factor: f32,
    ) -> std::ops::Range<usize> {
        self.text.record_runs(
            rect,
            scissor,
            runs,
            size,
            line_height,
            wrap,
            anchor,
            scale_factor,
        )
    }

    fn record_icon(
        &mut self,
        rect: Rect,
        scissor: Option<PhysicalScissor>,
        source: &aetna_core::svg_icon::IconSource,
        color: Color,
        _size: f32,
        stroke_width: f32,
        _scale_factor: f32,
    ) -> RecordedPaint {
        RecordedPaint::Icon(
            self.icons
                .record(rect, scissor, source, color, stroke_width),
        )
    }

    fn record_image(
        &mut self,
        rect: Rect,
        scissor: Option<PhysicalScissor>,
        image: &aetna_core::image::Image,
        tint: Option<Color>,
        radius: f32,
        _fit: aetna_core::image::ImageFit,
        _scale_factor: f32,
    ) -> std::ops::Range<usize> {
        self.images
            .record(self.device, self.queue, rect, scissor, image, tint, radius)
    }
}

impl Runner {
    /// Create a runner for the given target color format. The host
    /// passes its swapchain/render-target format here so pipelines and
    /// the glyph atlas are built compatible.
    pub fn new(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target_format: wgpu::TextureFormat,
    ) -> Self {
        Self::with_sample_count(device, queue, target_format, 1)
    }

    /// Like [`Self::new`], but builds all pipelines with `sample_count`
    /// MSAA samples. The host must provide a matching multisampled
    /// render target and a single-sample resolve target. `sample_count`
    /// of 1 is the non-MSAA default.
    pub fn with_sample_count(
        device: &wgpu::Device,
        _queue: &wgpu::Queue,
        target_format: wgpu::TextureFormat,
        sample_count: u32,
    ) -> Self {
        // ---- Shared resources ----
        let frame_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("aetna_wgpu::frame_uniforms"),
            size: std::mem::size_of::<FrameUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let frame_bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("aetna_wgpu::frame_bind_layout"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });

        let quad_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("aetna_wgpu::frame_bind_group"),
            layout: &frame_bind_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: frame_buf.as_entire_binding(),
            }],
        });

        let quad_vbo = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("aetna_wgpu::quad_vbo"),
            // Triangle strip: 4 corners, uv 0..1.
            contents: bytemuck::cast_slice::<f32, u8>(&[0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]),
            usage: wgpu::BufferUsages::VERTEX,
        });

        let instance_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("aetna_wgpu::instance_buf"),
            size: (INITIAL_INSTANCE_CAPACITY * std::mem::size_of::<QuadInstance>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("aetna_wgpu::pipeline_layout"),
            bind_group_layouts: &[Some(&frame_bind_layout)],
            immediate_size: 0,
        });

        // ---- Backdrop sampling resources ----
        //
        // Custom shaders that opt into backdrop sampling (registered
        // via `register_shader_with(..samples_backdrop=true)`) get a
        // pipeline layout with `@group(1)` for the snapshot texture
        // and sampler. The bind group is rebuilt whenever the
        // snapshot is (re)allocated.
        let backdrop_bind_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("aetna_wgpu::backdrop_bind_layout"),
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Texture {
                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
                            view_dimension: wgpu::TextureViewDimension::D2,
                            multisampled: false,
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                        count: None,
                    },
                ],
            });
        let backdrop_pipeline_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("aetna_wgpu::backdrop_pipeline_layout"),
                bind_group_layouts: &[Some(&frame_bind_layout), Some(&backdrop_bind_layout)],
                immediate_size: 0,
            });
        let backdrop_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("aetna_wgpu::backdrop_sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });

        // Build stock rect-shaped pipelines up-front; custom shaders are
        // added on demand by the host.
        let mut pipelines = HashMap::new();
        let rr_pipeline = build_quad_pipeline(
            device,
            &pipeline_layout,
            target_format,
            sample_count,
            "stock::rounded_rect",
            stock_wgsl::ROUNDED_RECT,
        );
        pipelines.insert(ShaderHandle::Stock(StockShader::RoundedRect), rr_pipeline);

        // Text pipeline + atlas (replaces glyphon).
        let text_paint = TextPaint::new(device, target_format, sample_count, &frame_bind_layout);
        let icon_paint = IconPaint::new(device, target_format, sample_count, &frame_bind_layout);
        let image_paint = ImagePaint::new(device, target_format, sample_count, &frame_bind_layout);

        let mut core = RunnerCore::new();
        core.quad_scratch = Vec::with_capacity(INITIAL_INSTANCE_CAPACITY);

        Self {
            target_format,
            sample_count,
            pipeline_layout,
            backdrop_pipeline_layout,
            quad_bind_group,
            backdrop_bind_layout,
            backdrop_sampler,
            frame_buf,
            quad_vbo,
            instance_buf,
            instance_capacity: INITIAL_INSTANCE_CAPACITY,
            pipelines,
            backdrop_shaders: HashSet::new(),
            text_paint,
            icon_paint,
            image_paint,
            snapshot: None,
            backdrop_bind_group: None,
            start_time: Instant::now(),
            core,
        }
    }

    /// Tell the runner the swapchain texture size in physical pixels.
    /// Call this once after `surface.configure(...)` and again on every
    /// `WindowEvent::Resized`. The runner uses this as the canonical
    /// `viewport_px` for scissor math; without it, the value is derived
    /// from `viewport.w * scale_factor`, which can drift by one pixel
    /// when `scale_factor` is fractional and trip wgpu's
    /// `set_scissor_rect` validation.
    pub fn set_surface_size(&mut self, width: u32, height: u32) {
        self.core.set_surface_size(width, height);
    }

    /// Set the theme used to resolve implicit widget surfaces to shaders.
    pub fn set_theme(&mut self, theme: Theme) {
        self.icon_paint.set_material(theme.icon_material());
        self.core.set_theme(theme);
    }

    pub fn theme(&self) -> &Theme {
        self.core.theme()
    }

    /// Select the stock material used by the vector-icon painter.
    /// Prefer [`Theme::with_icon_material`] for app-level routing; this
    /// remains useful for low-level render fixtures.
    pub fn set_icon_material(&mut self, material: IconMaterial) {
        self.icon_paint.set_material(material);
    }

    pub fn icon_material(&self) -> IconMaterial {
        self.icon_paint.material()
    }

    /// Register a custom shader. `name` is the same string passed to
    /// `aetna_core::shader::ShaderBinding::custom`; nodes bound to it
    /// via [`El::shader`](aetna_core::tree::El) paint through this
    /// pipeline.
    ///
    /// The WGSL source must use the shared `(rect, vec_a, vec_b, vec_c)`
    /// instance layout and the `FrameUniforms` bind group described in
    /// the module docs. Compilation happens at register time — invalid
    /// WGSL panics here, not mid-frame.
    ///
    /// Re-registering the same name replaces the previous pipeline
    /// (useful for hot-reload during development).
    pub fn register_shader(&mut self, device: &wgpu::Device, name: &'static str, wgsl: &str) {
        self.register_shader_with(device, name, wgsl, false);
    }

    /// Register a custom shader, with an opt-in flag for backdrop
    /// sampling. When `samples_backdrop` is true, the renderer schedules
    /// the shader's draws into Pass B (after a snapshot of Pass A's
    /// rendered content) and binds the snapshot texture as
    /// `@group(2) binding=0` (`backdrop_tex`) plus a sampler at
    /// `binding=1` (`backdrop_smp`). See `docs/SHADER_VISION.md`
    /// §"Backdrop sampling architecture".
    ///
    /// Backdrop depth is capped at 1: glass-on-glass shows the same
    /// underlying content, not a second snapshot of the first glass
    /// composited.
    pub fn register_shader_with(
        &mut self,
        device: &wgpu::Device,
        name: &'static str,
        wgsl: &str,
        samples_backdrop: bool,
    ) {
        let label = format!("custom::{name}");
        let layout = if samples_backdrop {
            &self.backdrop_pipeline_layout
        } else {
            &self.pipeline_layout
        };
        let pipeline = build_quad_pipeline(
            device,
            layout,
            self.target_format,
            self.sample_count,
            &label,
            wgsl,
        );
        self.pipelines.insert(ShaderHandle::Custom(name), pipeline);
        if samples_backdrop {
            self.backdrop_shaders.insert(name);
        } else {
            self.backdrop_shaders.remove(name);
        }
    }

    /// Borrow the internal [`UiState`] — primarily for headless fixtures
    /// that want to look up a node's rect after `prepare` (e.g., to
    /// simulate a pointer at a specific button's center).
    pub fn ui_state(&self) -> &UiState {
        self.core.ui_state()
    }

    /// One-line diagnostic snapshot of interactive state — passes through
    /// to [`UiState::debug_summary`]. Intended for per-frame logging
    /// (e.g., `console.log` from the wasm host while debugging hover /
    /// animation glitches).
    pub fn debug_summary(&self) -> String {
        self.core.debug_summary()
    }

    /// Return the most recently laid-out rectangle for a keyed node.
    ///
    /// Call after [`Self::prepare`]. This is the host-composition hook:
    /// reserve a keyed Aetna element in the UI tree, ask for its rect
    /// here, then record host-owned rendering into that region using the
    /// same encoder / render flow that surrounds Aetna's pass.
    pub fn rect_of_key(&self, key: &str) -> Option<Rect> {
        self.core.rect_of_key(key)
    }

    /// Lay out the tree, resolve to draw ops, and upload per-frame
    /// buffers (quad instances + glyph atlas). Must be called before
    /// [`Self::draw`] and outside of any render pass.
    ///
    /// `viewport` is in **logical** pixels — the units the layout pass
    /// works in. `scale_factor` is the HiDPI multiplier (1.0 on a
    /// regular display, 2.0 on most modern HiDPI, can be fractional).
    /// The host's render-pass target should be sized at physical pixels
    /// (`viewport × scale_factor`); the runner maps logical → physical
    /// internally so layout, fonts, and SDF math stay device-independent.
    pub fn prepare(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        root: &mut El,
        viewport: Rect,
        scale_factor: f32,
    ) -> PrepareResult {
        let mut timings = PrepareTimings::default();

        // Layout + state apply + animation tick + draw_ops resolution.
        // Writes timings.layout + timings.draw_ops.
        let (ops, needs_redraw) =
            self.core
                .prepare_layout(root, viewport, scale_factor, &mut timings);

        // Paint stream: pack quads, record text, preserve z-order. The
        // closure is the wgpu-specific "is this shader registered?"
        // query (different pipeline types per backend prevent moving the
        // check itself into core).
        self.text_paint.frame_begin();
        self.icon_paint.frame_begin();
        self.image_paint.frame_begin();
        let pipelines = &self.pipelines;
        let backdrop_shaders = &self.backdrop_shaders;
        let mut recorder = PaintRecorder {
            text: &mut self.text_paint,
            icons: &mut self.icon_paint,
            images: &mut self.image_paint,
            device,
            queue,
        };
        self.core.prepare_paint(
            &ops,
            |shader| pipelines.contains_key(shader),
            |shader| match shader {
                ShaderHandle::Custom(name) => backdrop_shaders.contains(name),
                ShaderHandle::Stock(_) => false,
            },
            &mut recorder,
            scale_factor,
            &mut timings,
        );

        // GPU upload — wgpu-specific. Resize the instance buffer if
        // needed, then write quad_scratch + frame uniforms + flush text
        // atlas dirty regions.
        let t_paint_end = Instant::now();
        if self.core.quad_scratch.len() > self.instance_capacity {
            let new_cap = self.core.quad_scratch.len().next_power_of_two();
            self.instance_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("aetna_wgpu::instance_buf (resized)"),
                size: (new_cap * std::mem::size_of::<QuadInstance>()) as u64,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            self.instance_capacity = new_cap;
        }
        if !self.core.quad_scratch.is_empty() {
            queue.write_buffer(
                &self.instance_buf,
                0,
                bytemuck::cast_slice(&self.core.quad_scratch),
            );
        }
        self.text_paint.flush(device, queue);
        self.icon_paint.flush(device, queue);
        self.image_paint.flush(device, queue);
        let time = (Instant::now() - self.start_time).as_secs_f32();
        let frame = FrameUniforms {
            viewport: [viewport.w, viewport.h],
            time,
            scale_factor,
        };
        queue.write_buffer(&self.frame_buf, 0, bytemuck::bytes_of(&frame));
        timings.gpu_upload = Instant::now() - t_paint_end;

        // Snapshot the laid-out tree for next-frame hit-testing.
        self.core.snapshot(root, &mut timings);

        PrepareResult {
            needs_redraw,
            timings,
        }
    }

    // ---- Input plumbing ----
    //
    // The host (winit-side) calls these from its event loop.
    // Coordinates are **logical pixels** — divide winit's physical
    // PhysicalPosition by the window scale factor before handing them in.

    /// Update pointer position and recompute the hovered key.
    /// Returns the new hovered key, if any (host can use it for cursor
    /// styling or to decide whether to call `request_redraw`).
    /// Pointer moved to `(x, y)` (logical px). Returns the events to
    /// dispatch via `App::on_event` plus a `needs_redraw` flag — see
    /// [`PointerMove`] for why hosts must gate `request_redraw` on
    /// the flag. The hovered node is updated on `ui_state().hovered`
    /// regardless.
    pub fn pointer_moved(&mut self, x: f32, y: f32) -> PointerMove {
        self.core.pointer_moved(x, y)
    }

    /// Pointer left the window — clear hover/press.
    pub fn pointer_left(&mut self) {
        self.core.pointer_left();
    }

    /// Mouse button down at `(x, y)` (logical px) for the given
    /// `button`. For `Primary`, records the pressed key for press-
    /// visual feedback, updates focus, and returns a `PointerDown`
    /// event so widgets that need to react at down-time (text input
    /// selection anchor, draggable handles) can do so. For
    /// `Secondary` / `Middle`, records on a side channel and returns
    /// `None`. The actual click event fires on `pointer_up`.
    pub fn pointer_down(&mut self, x: f32, y: f32, button: PointerButton) -> Vec<UiEvent> {
        self.core.pointer_down(x, y, button)
    }

    /// Replace the tracked modifier mask. Hosts call this from their
    /// platform's "modifiers changed" hook so subsequent pointer
    /// events (PointerDown, Drag, Click, …) stamp the current mask
    /// into `UiEvent.modifiers`.
    pub fn set_modifiers(&mut self, modifiers: KeyModifiers) {
        self.core.ui_state.set_modifiers(modifiers);
    }

    /// Mouse button up at `(x, y)` for the given `button`. Returns
    /// the events the host should dispatch in order: for `Primary`,
    /// always a `PointerUp` (when there was a corresponding down)
    /// followed by an optional `Click` (when the up landed on the
    /// down's node). For `Secondary` / `Middle`, an optional
    /// `SecondaryClick` / `MiddleClick` on the same-node match.
    pub fn pointer_up(&mut self, x: f32, y: f32, button: PointerButton) -> Vec<UiEvent> {
        self.core.pointer_up(x, y, button)
    }

    pub fn key_down(&mut self, key: UiKey, modifiers: KeyModifiers, repeat: bool) -> Vec<UiEvent> {
        self.core.key_down(key, modifiers, repeat)
    }

    /// Forward an OS-composed text-input string (winit's keyboard event
    /// `.text` field, or an `Ime::Commit`) to the focused element as a
    /// `TextInput` event.
    pub fn text_input(&mut self, text: String) -> Option<UiEvent> {
        self.core.text_input(text)
    }

    /// Replace the hotkey registry. Call once per frame, after `app.build()`,
    /// passing `app.hotkeys()` so chords stay in sync with state.
    pub fn set_hotkeys(&mut self, hotkeys: Vec<(KeyChord, String)>) {
        self.core.set_hotkeys(hotkeys);
    }

    /// Push the app's current selection to the runtime so the painter
    /// can draw highlight bands. Hosts call this once per frame
    /// alongside [`Self::set_hotkeys`].
    pub fn set_selection(&mut self, selection: aetna_core::selection::Selection) {
        self.core.set_selection(selection);
    }

    /// Queue toast specs onto the runtime's toast stack. Hosts call
    /// this once per frame with `app.drain_toasts()`. Each spec is
    /// stamped with a monotonic id and an `expires_at` deadline
    /// (`now + ttl`); the next `prepare` call drops expired entries
    /// and synthesizes a `toast_stack` floating layer over the rest.
    pub fn push_toasts(&mut self, specs: Vec<aetna_core::toast::ToastSpec>) {
        self.core.push_toasts(specs);
    }

    /// Programmatically dismiss a toast by id. Useful for cancelling
    /// long-TTL toasts when an external condition resolves (e.g.,
    /// "reconnecting…" turning into "connected").
    pub fn dismiss_toast(&mut self, id: u64) {
        self.core.dismiss_toast(id);
    }

    /// Switch animation pacing. Default is [`AnimationMode::Live`].
    /// Headless render binaries should call this with
    /// [`AnimationMode::Settled`] so a single-frame snapshot reflects
    /// the post-animation visual without depending on integrator timing.
    pub fn set_animation_mode(&mut self, mode: AnimationMode) {
        self.core.set_animation_mode(mode);
    }

    /// Apply a wheel delta in **logical** pixels at `(x, y)`. Routes to
    /// the deepest scrollable container under the cursor in the last
    /// laid-out tree. Returns `true` if the event landed on a scrollable
    /// (host should `request_redraw` so the next frame applies the new
    /// offset).
    pub fn pointer_wheel(&mut self, x: f32, y: f32, dy: f32) -> bool {
        self.core.pointer_wheel(x, y, dy)
    }

    /// Record draws into the host-managed render pass. Call after
    /// [`Self::prepare`]. Paint order follows the draw-op stream.
    ///
    /// **No backdrop sampling.** This entry point cannot honor pass
    /// boundaries (the host owns the pass lifetime), so any
    /// `BackdropSnapshot` items in the paint stream are no-ops and any
    /// shader bound with `samples_backdrop=true` reads an undefined
    /// backdrop binding. Use [`Self::render`] for backdrop-aware
    /// rendering.
    pub fn draw<'pass>(&'pass self, pass: &mut wgpu::RenderPass<'pass>) {
        self.draw_items(pass, &self.core.paint_items);
    }

    /// Record draws into a host-supplied encoder, owning pass
    /// lifetimes ourselves so backdrop-sampling shaders can sample a
    /// snapshot of Pass A's content.
    ///
    /// The host hands us:
    /// - the encoder (we record into it),
    /// - the color target's `wgpu::Texture` (used as `copy_src` when
    ///   we snapshot it; must include `COPY_SRC` in its usage flags),
    /// - the corresponding `wgpu::TextureView` (we attach it to every
    ///   render pass we begin), and
    /// - the `LoadOp` to use on the *first* pass — `Clear(color)` to
    ///   clear behind us, `Load` to composite onto whatever was
    ///   already in the target.
    ///
    /// Multi-pass schedule when the paint stream contains a
    /// `BackdropSnapshot`:
    ///
    /// 1. Pass A — every paint item before the snapshot, with the
    ///    caller-supplied `LoadOp`.
    /// 2. `copy_texture_to_texture` — target → snapshot.
    /// 3. Pass B — paint items from the snapshot onward, with
    ///    `LoadOp::Load` so Pass A's pixels remain underneath.
    ///
    /// Without a snapshot, this collapses to a single pass and is
    /// equivalent to [`Self::draw`] called inside a host-managed
    /// pass with the same `LoadOp`.
    pub fn render(
        &mut self,
        device: &wgpu::Device,
        encoder: &mut wgpu::CommandEncoder,
        target_tex: &wgpu::Texture,
        target_view: &wgpu::TextureView,
        msaa_view: Option<&wgpu::TextureView>,
        load_op: wgpu::LoadOp<wgpu::Color>,
    ) {
        // When MSAA is in use, the actual color attachment is the
        // multisampled view and `target_view` becomes its resolve
        // target. `target_tex` is always the resolved (single-sample)
        // texture, so the snapshot copy below works whether MSAA is on
        // or not — the resolve happens at end-of-Pass-A.
        let attachment_view = msaa_view.unwrap_or(target_view);
        let resolve_target = msaa_view.map(|_| target_view);

        // Locate the (at most one) snapshot boundary.
        let split_at = self
            .core
            .paint_items
            .iter()
            .position(|p| matches!(p, PaintItem::BackdropSnapshot));

        if let Some(idx) = split_at {
            self.ensure_snapshot(device, target_tex);
            // Pass A
            {
                let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("aetna_wgpu::pass_a"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: attachment_view,
                        resolve_target,
                        depth_slice: None,
                        ops: wgpu::Operations {
                            load: load_op,
                            store: wgpu::StoreOp::Store,
                        },
                    })],
                    depth_stencil_attachment: None,
                    timestamp_writes: None,
                    occlusion_query_set: None,
                    multiview_mask: None,
                });
                self.draw_items(&mut pass, &self.core.paint_items[..idx]);
            }
            // Snapshot copy. Target must support COPY_SRC; snapshot
            // texture (created in `ensure_snapshot`) supports COPY_DST
            // + TEXTURE_BINDING.
            let snapshot = self.snapshot.as_ref().expect("snapshot ensured");
            encoder.copy_texture_to_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: target_tex,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::TexelCopyTextureInfo {
                    texture: &snapshot.texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::Extent3d {
                    width: snapshot.extent.0,
                    height: snapshot.extent.1,
                    depth_or_array_layers: 1,
                },
            );
            // Pass B
            {
                let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("aetna_wgpu::pass_b"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: attachment_view,
                        resolve_target,
                        depth_slice: None,
                        ops: wgpu::Operations {
                            load: wgpu::LoadOp::Load,
                            store: wgpu::StoreOp::Store,
                        },
                    })],
                    depth_stencil_attachment: None,
                    timestamp_writes: None,
                    occlusion_query_set: None,
                    multiview_mask: None,
                });
                // Skip the snapshot item itself; it's a marker, not a draw.
                self.draw_items(&mut pass, &self.core.paint_items[idx + 1..]);
            }
        } else {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("aetna_wgpu::pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: attachment_view,
                    resolve_target,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: load_op,
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            self.draw_items(&mut pass, &self.core.paint_items);
        }
    }

    /// (Re)allocate the snapshot texture to match `target_tex`'s
    /// extent + format. Idempotent when the size matches; rebuilds the
    /// `backdrop_bind_group` whenever the snapshot is recreated.
    fn ensure_snapshot(&mut self, device: &wgpu::Device, target_tex: &wgpu::Texture) {
        let extent = target_tex.size();
        let want = (extent.width, extent.height);
        if let Some(s) = &self.snapshot
            && s.extent == want
        {
            return;
        }
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("aetna_wgpu::backdrop_snapshot"),
            size: wgpu::Extent3d {
                width: want.0,
                height: want.1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: self.target_format,
            usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("aetna_wgpu::backdrop_bind_group"),
            layout: &self.backdrop_bind_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.backdrop_sampler),
                },
            ],
        });
        self.snapshot = Some(SnapshotTexture {
            texture,
            extent: want,
        });
        self.backdrop_bind_group = Some(bind_group);
    }

    /// Walk a slice of `PaintItem`s into the given pass. Helper shared
    /// by [`Self::draw`] and [`Self::render`]. `BackdropSnapshot`
    /// items are no-ops here; `render()` handles them by splitting
    /// the slice before passing to this helper.
    fn draw_items<'pass>(
        &'pass self,
        pass: &mut wgpu::RenderPass<'pass>,
        items: &'pass [PaintItem],
    ) {
        let full = PhysicalScissor {
            x: 0,
            y: 0,
            w: self.core.viewport_px.0,
            h: self.core.viewport_px.1,
        };
        for item in items {
            match *item {
                PaintItem::QuadRun(index) => {
                    let run = &self.core.runs[index];
                    set_scissor(pass, run.scissor, full);
                    pass.set_bind_group(0, &self.quad_bind_group, &[]);
                    let is_backdrop_shader = matches!(
                        run.handle,
                        ShaderHandle::Custom(name) if self.backdrop_shaders.contains(name)
                    );
                    if is_backdrop_shader && let Some(bg) = &self.backdrop_bind_group {
                        pass.set_bind_group(1, bg, &[]);
                    }
                    pass.set_vertex_buffer(0, self.quad_vbo.slice(..));
                    pass.set_vertex_buffer(1, self.instance_buf.slice(..));
                    let pipeline = self
                        .pipelines
                        .get(&run.handle)
                        .expect("run handle has no pipeline (bug in prepare)");
                    pass.set_pipeline(pipeline);
                    pass.draw(0..4, run.first..run.first + run.count);
                }
                PaintItem::Text(index) => {
                    let run = self.text_paint.run(index);
                    set_scissor(pass, run.scissor, full);
                    pass.set_pipeline(self.text_paint.pipeline_for(run.kind));
                    pass.set_bind_group(0, &self.quad_bind_group, &[]);
                    // Highlight runs use a frame-uniform-only pipeline.
                    // Glyph kinds bind the active atlas page at group 1.
                    if !matches!(run.kind, crate::text::TextRunKind::Highlight) {
                        pass.set_bind_group(
                            1,
                            self.text_paint.page_bind_group(run.kind, run.page),
                            &[],
                        );
                    }
                    pass.set_vertex_buffer(0, self.quad_vbo.slice(..));
                    pass.set_vertex_buffer(1, self.text_paint.instance_buf_for(run.kind).slice(..));
                    pass.draw(0..4, run.first..run.first + run.count);
                }
                PaintItem::IconRun(index) => {
                    let run = self.icon_paint.run(index);
                    set_scissor(pass, run.scissor, full);
                    match run.kind {
                        IconRunKind::Tess => {
                            pass.set_pipeline(self.icon_paint.tess_pipeline(run.material));
                            pass.set_bind_group(0, &self.quad_bind_group, &[]);
                            pass.set_vertex_buffer(0, self.icon_paint.tess_vertex_buf().slice(..));
                            pass.draw(run.first..run.first + run.count, 0..1);
                        }
                        IconRunKind::Msdf => {
                            pass.set_pipeline(self.icon_paint.msdf_pipeline());
                            pass.set_bind_group(0, &self.quad_bind_group, &[]);
                            pass.set_bind_group(
                                1,
                                self.icon_paint.msdf_page_bind_group(run.page),
                                &[],
                            );
                            pass.set_vertex_buffer(0, self.quad_vbo.slice(..));
                            pass.set_vertex_buffer(
                                1,
                                self.icon_paint.msdf_instance_buf().slice(..),
                            );
                            pass.draw(0..4, run.first..run.first + run.count);
                        }
                    }
                }
                PaintItem::Image(index) => {
                    let run = self.image_paint.run(index);
                    set_scissor(pass, run.scissor, full);
                    pass.set_pipeline(self.image_paint.pipeline());
                    pass.set_bind_group(0, &self.quad_bind_group, &[]);
                    pass.set_bind_group(1, self.image_paint.bind_group_for_run(run), &[]);
                    pass.set_vertex_buffer(0, self.quad_vbo.slice(..));
                    pass.set_vertex_buffer(1, self.image_paint.instance_buf().slice(..));
                    pass.draw(0..4, run.first..run.first + run.count);
                }
                PaintItem::BackdropSnapshot => {
                    // Marker only — `render()` splits the slice on
                    // these and never includes one in a draw range.
                }
            }
        }
    }
}