Skip to main content

repose_render_wgpu/
lib.rs

1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::num::NonZero;
4#[cfg(feature = "winit-surface")]
5use std::panic::{AssertUnwindSafe, catch_unwind};
6#[cfg(feature = "winit-surface")]
7use std::sync::Arc;
8
9use repose_core::color::{ChromaSiting, ColorInfo, PixelFormat};
10use repose_core::request_frame;
11use repose_core::{
12    Brush, FontStyle, GlyphRasterConfig, PresentModePref, RenderBackend, Scene, SceneNode,
13    StrokeCap, Transform,
14};
15use wgpu::Instance;
16
17mod slug;
18
19mod commands;
20pub use commands::apply_render_commands;
21
22#[derive(Clone)]
23struct UploadRing {
24    buf: wgpu::Buffer,
25    cap: u64,
26    head: u64,
27    usage: wgpu::BufferUsages,
28}
29
30impl UploadRing {
31    fn new(device: &wgpu::Device, label: &str, cap: u64, usage: wgpu::BufferUsages) -> Self {
32        let buf = device.create_buffer(&wgpu::BufferDescriptor {
33            label: Some(label),
34            size: cap,
35            usage,
36            mapped_at_creation: false,
37        });
38        Self {
39            buf,
40            cap,
41            head: 0,
42            usage,
43        }
44    }
45
46    fn reset(&mut self) {
47        self.head = 0;
48    }
49
50    fn grow_to_fit(&mut self, device: &wgpu::Device, needed: u64) {
51        let start = (self.head + 3) & !3;
52        if start + needed <= self.cap {
53            return;
54        }
55        let new_cap = (start + needed).next_power_of_two();
56        self.buf = device.create_buffer(&wgpu::BufferDescriptor {
57            label: Some("upload ring (grown)"),
58            size: new_cap,
59            usage: self.usage,
60            mapped_at_creation: false,
61        });
62        self.cap = new_cap;
63    }
64
65    fn alloc_write(&mut self, queue: &wgpu::Queue, bytes: &[u8]) -> (u64, u64) {
66        let len = bytes.len() as u64;
67        let start = (self.head + 3) & !3; // align to 4
68        let end = start + len;
69        assert!(end <= self.cap, "ring overflow - call grow_to_fit first");
70        queue.write_buffer(&self.buf, start, bytes);
71        self.head = end;
72        (start, len)
73    }
74}
75
76struct InstancedPipe<I: bytemuck::Pod> {
77    ring: UploadRing,
78    _marker: std::marker::PhantomData<I>,
79}
80
81impl<I: bytemuck::Pod> InstancedPipe<I> {
82    fn new(ring: UploadRing) -> Self {
83        Self {
84            ring,
85            _marker: std::marker::PhantomData,
86        }
87    }
88
89    fn upload(
90        &mut self,
91        device: &wgpu::Device,
92        queue: &wgpu::Queue,
93        data: &[I],
94    ) -> Option<(u64, u32)> {
95        if data.is_empty() {
96            return None;
97        }
98        let bytes = bytemuck::cast_slice(data);
99        self.ring.grow_to_fit(device, bytes.len() as u64);
100        let (off, wrote) = self.ring.alloc_write(queue, bytes);
101        debug_assert_eq!(wrote as usize, bytes.len());
102        Some((off, data.len() as u32))
103    }
104
105    fn reset(&mut self) {
106        self.ring.reset();
107    }
108}
109
110#[repr(C)]
111#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
112struct Globals {
113    ndc_to_px: [f32; 2],
114    _pad: [f32; 2],
115}
116
117fn make_globals(target_w: f32, target_h: f32) -> Globals {
118    Globals {
119        ndc_to_px: [target_w * 0.5, target_h * 0.5],
120        _pad: [0.0, 0.0],
121    }
122}
123
124pub struct WgpuSceneRenderer {
125    pub device: wgpu::Device,
126    pub queue: wgpu::Queue,
127    pub output_format: wgpu::TextureFormat,
128    pub output_width: u32,
129    pub output_height: u32,
130
131    // Render pipelines. Two sets: one for the MSAA surface pass, one for
132    // graphics-layer render-to-texture passes (sample_count = 1).
133    surface_pipes: Pipelines,
134    layer_pipes: Pipelines,
135
136    // Instanced draw rings
137    rects: InstancedPipe<RectInstance>,
138    borders: InstancedPipe<BorderInstance>,
139    ellipses: InstancedPipe<EllipseInstance>,
140    ellipse_borders: InstancedPipe<EllipseBorderInstance>,
141    arcs: InstancedPipe<ArcInstance>,
142    glyph_mask: InstancedPipe<GlyphInstance>,
143    glyph_color: InstancedPipe<GlyphInstance>,
144
145    // Image bind layouts and shared sampler
146    image_bind_layout_rgba: wgpu::BindGroupLayout,
147    image_bind_layout_nv12: wgpu::BindGroupLayout,
148    image_sampler: wgpu::Sampler,
149    layer_sampler: wgpu::Sampler,
150    layer_sampler_linear: wgpu::Sampler,
151
152    // Blur composite ring (for graphics-layer drop shadows)
153    blur_ring: UploadRing,
154
155    text_bind_layout: wgpu::BindGroupLayout,
156
157    // Stencil clip ring
158    clip_ring: UploadRing,
159
160    // Tessellated vector glyph pipeline (always enabled)
161    slug_enabled: bool,
162    slug_ring: UploadRing,
163    slug_cache: slug::GlyphSlugCache,
164
165    // Instanced NV12 ring
166    nv12: InstancedPipe<Nv12Instance>,
167
168    // Tessellated vector mesh rendering (host-provided, e.g. lyon output).
169    mesh_verts: UploadRing,
170    mesh_indices: UploadRing,
171    mesh_uniform_buf: wgpu::Buffer,
172    mesh_bind_layout: wgpu::BindGroupLayout,
173    mesh_bind: wgpu::BindGroup,
174    mesh_uniform_head: u64,
175    /// CPU mirror of the active vector-clip stack: (voff, vcnt, ioff, icnt,
176    /// uoff) of each pushed mask so `PopVectorClip` can re-draw it to
177    /// decrement the stencil.
178    mesh_clip_stack: Vec<(u64, u32, u64, u32, u64)>,
179
180    msaa_samples: u32,
181
182    // Depth-stencil target
183    depth_stencil_tex: wgpu::Texture,
184    depth_stencil_view: wgpu::TextureView,
185
186    // Optional MSAA color target
187    msaa_tex: Option<wgpu::Texture>,
188    msaa_view: Option<wgpu::TextureView>,
189
190    globals_buf: wgpu::Buffer,
191    globals_bind: wgpu::BindGroup,
192
193    // Glyph atlas
194    atlas_mask: AtlasA8,
195    atlas_color: AtlasRGBA,
196
197    // Image management
198    next_image_handle: u64,
199    images: HashMap<u64, ImageTex>,
200    retained: HashMap<u64, RetainedImage>,
201
202    // Eviction stats
203    frame_index: u64,
204    image_bytes_total: u64,
205    image_evict_after_frames: u64,
206    image_budget_bytes: u64,
207
208    // Graphics layer pool. Maps `SceneNode::BeginLayer::layer_id` to a
209    // cached offscreen render target.
210    layer_pool: HashMap<u32, LayerTarget>,
211
212    // Linear working-space mode (default off -> fast playback path).
213    // When enabled, the scene is rendered into an Rgba16Float intermediate
214    // texture, then a final full-screen pass applies the display OETF.
215    working_space: bool,
216    ws_tex: Option<wgpu::Texture>,
217    ws_view: Option<wgpu::TextureView>,
218    ws_bind: Option<wgpu::BindGroup>,
219    display_pipeline: Option<wgpu::RenderPipeline>,
220    display_layout: Option<wgpu::BindGroupLayout>,
221}
222
223pub struct WgpuSurfaceBackend {
224    pub surface: Option<wgpu::Surface<'static>>,
225    pub surface_config: Option<wgpu::SurfaceConfiguration>,
226    pub renderer: WgpuSceneRenderer,
227}
228
229impl std::ops::Deref for WgpuSurfaceBackend {
230    type Target = WgpuSceneRenderer;
231    fn deref(&self) -> &Self::Target {
232        &self.renderer
233    }
234}
235impl std::ops::DerefMut for WgpuSurfaceBackend {
236    fn deref_mut(&mut self) -> &mut Self::Target {
237        &mut self.renderer
238    }
239}
240
241#[cfg(feature = "winit-surface")]
242pub type WgpuBackend = WgpuSurfaceBackend;
243
244impl Drop for WgpuSceneRenderer {
245    fn drop(&mut self) {
246        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
247    }
248}
249
250#[derive(Clone)]
251struct LayerTarget {
252    view: wgpu::TextureView,
253    bind: wgpu::BindGroup,
254    bind_linear: wgpu::BindGroup,
255    depth_stencil_view: wgpu::TextureView,
256    width: u32,
257    height: u32,
258    rect_px: (f32, f32, f32, f32),
259}
260
261/// Identifies which render target a `Pass` draws into.
262#[derive(Clone, Copy)]
263enum PassTarget {
264    Surface,
265    Layer(u32),
266}
267
268/// A bundle of render pipelines for a single sample-count target. Created
269/// twice: once with `sample_count = msaa_samples` for the surface pass, and
270/// once with `sample_count = 1` for graphics-layer render-to-texture passes
271/// (where MSAA is wasted).
272struct Pipelines {
273    rects: wgpu::RenderPipeline,
274    borders: wgpu::RenderPipeline,
275    ellipses: wgpu::RenderPipeline,
276    ellipse_borders: wgpu::RenderPipeline,
277    arcs: wgpu::RenderPipeline,
278    text_mask: wgpu::RenderPipeline,
279    text_color: wgpu::RenderPipeline,
280    image_rgba: wgpu::RenderPipeline,
281    image_nv12: wgpu::RenderPipeline,
282    blur: wgpu::RenderPipeline,
283    blur_content: wgpu::RenderPipeline,
284    clip_a2c: wgpu::RenderPipeline,
285    clip_bin: wgpu::RenderPipeline,
286    clip_dec: wgpu::RenderPipeline,
287    slug: Option<wgpu::RenderPipeline>,
288    /// Tessellated vector mesh (fill/stroke). Uses an `Equal` stencil compare
289    /// so world content is correctly masked to the active `PushVectorClip`
290    /// shape (outside any clip the stencil is 0 == ref 0, so it draws).
291    mesh: wgpu::RenderPipeline,
292    /// Screen-space overlay meshes: `LessEqual` compare so they always draw
293    /// regardless of any active vector clip.
294    mesh_overlay: wgpu::RenderPipeline,
295    /// Stencil increment for vector clips.
296    mesh_clip_inc: wgpu::RenderPipeline,
297    /// Stencil decrement for vector clips.
298    mesh_clip_dec: wgpu::RenderPipeline,
299}
300
301impl Pipelines {
302    fn create(
303        device: &wgpu::Device,
304        format: wgpu::TextureFormat,
305        sample_count: u32,
306        globals_layout: &wgpu::BindGroupLayout,
307        text_bind_layout: &wgpu::BindGroupLayout,
308        image_bind_layout_nv12: &wgpu::BindGroupLayout,
309        clip_pipeline_layout: &wgpu::PipelineLayout,
310        stencil_for_content: &wgpu::DepthStencilState,
311        stencil_for_clip_inc: &wgpu::DepthStencilState,
312        stencil_for_clip_dec: &wgpu::DepthStencilState,
313        clip_color_target: &wgpu::ColorTargetState,
314        clip_vertex_layout: &wgpu::VertexBufferLayout,
315        mesh_bind_layout: &wgpu::BindGroupLayout,
316    ) -> Self {
317        let msaa_state = wgpu::MultisampleState {
318            count: sample_count,
319            mask: !0,
320            alpha_to_coverage_enabled: false,
321        };
322
323        macro_rules! make_content_pipeline {
324            ($name:ident, $shader:literal, $inst_type:ty, $attrs:expr) => {
325                let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
326                    label: Some(concat!($shader, ".wgsl")),
327                    source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(concat!(
328                        "shaders/", $shader, ".wgsl"
329                    )))),
330                });
331                let pipeline_layout =
332                    device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
333                        label: Some(concat!($shader, " pipeline layout")),
334                        bind_group_layouts: &[Some(globals_layout)],
335                        immediate_size: 0,
336                    });
337                let $name = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
338                    label: Some(concat!($shader, " pipeline")),
339                    layout: Some(&pipeline_layout),
340                    vertex: wgpu::VertexState {
341                        module: &shader_module,
342                        entry_point: Some("vs_main"),
343                        buffers: &[Some(wgpu::VertexBufferLayout {
344                            array_stride: std::mem::size_of::<$inst_type>() as u64,
345                            step_mode: wgpu::VertexStepMode::Instance,
346                            attributes: $attrs,
347                        })],
348                        compilation_options: wgpu::PipelineCompilationOptions::default(),
349                    },
350                    fragment: Some(wgpu::FragmentState {
351                        module: &shader_module,
352                        entry_point: Some("fs_main"),
353                        targets: &[Some(wgpu::ColorTargetState {
354                            format,
355                            blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
356                            write_mask: wgpu::ColorWrites::ALL,
357                        })],
358                        compilation_options: wgpu::PipelineCompilationOptions::default(),
359                    }),
360                    primitive: wgpu::PrimitiveState::default(),
361                    depth_stencil: Some(stencil_for_content.clone()),
362                    multisample: msaa_state,
363                    multiview_mask: None,
364                    cache: None,
365                });
366            };
367        }
368
369        let rect_attrs: &[wgpu::VertexAttribute] = &[
370            wgpu::VertexAttribute {
371                shader_location: 0,
372                offset: 0,
373                format: wgpu::VertexFormat::Float32x4,
374            },
375            wgpu::VertexAttribute {
376                shader_location: 1,
377                offset: 16,
378                format: wgpu::VertexFormat::Float32x4,
379            },
380            wgpu::VertexAttribute {
381                shader_location: 2,
382                offset: 32,
383                format: wgpu::VertexFormat::Uint32,
384            },
385            wgpu::VertexAttribute {
386                shader_location: 3,
387                offset: 48,
388                format: wgpu::VertexFormat::Float32x4,
389            },
390            wgpu::VertexAttribute {
391                shader_location: 4,
392                offset: 64,
393                format: wgpu::VertexFormat::Float32x4,
394            },
395            wgpu::VertexAttribute {
396                shader_location: 5,
397                offset: 80,
398                format: wgpu::VertexFormat::Float32x2,
399            },
400            wgpu::VertexAttribute {
401                shader_location: 6,
402                offset: 88,
403                format: wgpu::VertexFormat::Float32x2,
404            },
405            wgpu::VertexAttribute {
406                shader_location: 7,
407                offset: 96,
408                format: wgpu::VertexFormat::Float32x2,
409            },
410        ];
411        let border_attrs: &[wgpu::VertexAttribute] = &[
412            wgpu::VertexAttribute {
413                shader_location: 0,
414                offset: 0,
415                format: wgpu::VertexFormat::Float32x4,
416            },
417            wgpu::VertexAttribute {
418                shader_location: 1,
419                offset: 16,
420                format: wgpu::VertexFormat::Float32x4,
421            },
422            wgpu::VertexAttribute {
423                shader_location: 2,
424                offset: 32,
425                format: wgpu::VertexFormat::Float32,
426            },
427            wgpu::VertexAttribute {
428                shader_location: 3,
429                offset: 36,
430                format: wgpu::VertexFormat::Float32x4,
431            },
432            wgpu::VertexAttribute {
433                shader_location: 4,
434                offset: 52,
435                format: wgpu::VertexFormat::Float32x2,
436            },
437        ];
438        let ellipse_attrs: &[wgpu::VertexAttribute] = &[
439            wgpu::VertexAttribute {
440                shader_location: 0,
441                offset: 0,
442                format: wgpu::VertexFormat::Float32x4,
443            },
444            wgpu::VertexAttribute {
445                shader_location: 1,
446                offset: 16,
447                format: wgpu::VertexFormat::Float32x4,
448            },
449            wgpu::VertexAttribute {
450                shader_location: 2,
451                offset: 32,
452                format: wgpu::VertexFormat::Float32x2,
453            },
454        ];
455        let ellipse_border_attrs: &[wgpu::VertexAttribute] = &[
456            wgpu::VertexAttribute {
457                shader_location: 0,
458                offset: 0,
459                format: wgpu::VertexFormat::Float32x4,
460            },
461            wgpu::VertexAttribute {
462                shader_location: 1,
463                offset: 16,
464                format: wgpu::VertexFormat::Float32,
465            },
466            wgpu::VertexAttribute {
467                shader_location: 2,
468                offset: 20,
469                format: wgpu::VertexFormat::Float32,
470            },
471            wgpu::VertexAttribute {
472                shader_location: 3,
473                offset: 24,
474                format: wgpu::VertexFormat::Float32x4,
475            },
476            wgpu::VertexAttribute {
477                shader_location: 4,
478                offset: 40,
479                format: wgpu::VertexFormat::Float32x2,
480            },
481        ];
482
483        make_content_pipeline!(rects, "rect", RectInstance, rect_attrs);
484        make_content_pipeline!(borders, "border", BorderInstance, border_attrs);
485        make_content_pipeline!(ellipses, "ellipse", EllipseInstance, ellipse_attrs);
486        make_content_pipeline!(
487            ellipse_borders,
488            "ellipse_border",
489            EllipseBorderInstance,
490            ellipse_border_attrs
491        );
492
493        let arc_attrs: &[wgpu::VertexAttribute] = &[
494            wgpu::VertexAttribute {
495                shader_location: 0,
496                offset: 0,
497                format: wgpu::VertexFormat::Float32x4,
498            },
499            wgpu::VertexAttribute {
500                shader_location: 1,
501                offset: 16,
502                format: wgpu::VertexFormat::Float32,
503            },
504            wgpu::VertexAttribute {
505                shader_location: 2,
506                offset: 20,
507                format: wgpu::VertexFormat::Float32,
508            },
509            wgpu::VertexAttribute {
510                shader_location: 3,
511                offset: 24,
512                format: wgpu::VertexFormat::Float32,
513            },
514            wgpu::VertexAttribute {
515                shader_location: 4,
516                offset: 28,
517                format: wgpu::VertexFormat::Float32,
518            },
519            wgpu::VertexAttribute {
520                shader_location: 5,
521                offset: 32,
522                format: wgpu::VertexFormat::Float32x4,
523            },
524            wgpu::VertexAttribute {
525                shader_location: 6,
526                offset: 48,
527                format: wgpu::VertexFormat::Float32x2,
528            },
529            wgpu::VertexAttribute {
530                shader_location: 7,
531                offset: 56,
532                format: wgpu::VertexFormat::Float32,
533            },
534        ];
535
536        make_content_pipeline!(arcs, "arc", ArcInstance, arc_attrs);
537
538        // Text (mask)
539        let text_mask_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
540            label: Some("text.wgsl"),
541            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shaders/text.wgsl"))),
542        });
543        // Text (color)
544        let text_color_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
545            label: Some("text_color.wgsl"),
546            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
547                "shaders/text_color.wgsl"
548            ))),
549        });
550        let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
551            label: Some("text pipeline layout"),
552            bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
553            immediate_size: 0,
554        });
555        let glyph_vertex = wgpu::VertexBufferLayout {
556            array_stride: std::mem::size_of::<GlyphInstance>() as u64,
557            step_mode: wgpu::VertexStepMode::Instance,
558            attributes: &[
559                wgpu::VertexAttribute {
560                    shader_location: 0,
561                    offset: 0,
562                    format: wgpu::VertexFormat::Float32x4,
563                },
564                wgpu::VertexAttribute {
565                    shader_location: 1,
566                    offset: 16,
567                    format: wgpu::VertexFormat::Float32x4,
568                },
569                wgpu::VertexAttribute {
570                    shader_location: 2,
571                    offset: 32,
572                    format: wgpu::VertexFormat::Float32x4,
573                },
574                wgpu::VertexAttribute {
575                    shader_location: 3,
576                    offset: 48,
577                    format: wgpu::VertexFormat::Float32x2,
578                },
579            ],
580        };
581        let text_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
582            label: Some("text pipeline (mask)"),
583            layout: Some(&text_pipeline_layout),
584            vertex: wgpu::VertexState {
585                module: &text_mask_shader,
586                entry_point: Some("vs_main"),
587                buffers: &[Some(glyph_vertex.clone())],
588                compilation_options: wgpu::PipelineCompilationOptions::default(),
589            },
590            fragment: Some(wgpu::FragmentState {
591                module: &text_mask_shader,
592                entry_point: Some("fs_main"),
593                targets: &[Some(wgpu::ColorTargetState {
594                    format,
595                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
596                    write_mask: wgpu::ColorWrites::ALL,
597                })],
598                compilation_options: wgpu::PipelineCompilationOptions::default(),
599            }),
600            primitive: wgpu::PrimitiveState::default(),
601            depth_stencil: Some(stencil_for_content.clone()),
602            multisample: msaa_state,
603            multiview_mask: None,
604            cache: None,
605        });
606        let text_color = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
607            label: Some("text pipeline (color)"),
608            layout: Some(&text_pipeline_layout),
609            vertex: wgpu::VertexState {
610                module: &text_color_shader,
611                entry_point: Some("vs_main"),
612                buffers: &[Some(glyph_vertex)],
613                compilation_options: wgpu::PipelineCompilationOptions::default(),
614            },
615            fragment: Some(wgpu::FragmentState {
616                module: &text_color_shader,
617                entry_point: Some("fs_main"),
618                targets: &[Some(wgpu::ColorTargetState {
619                    format,
620                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
621                    write_mask: wgpu::ColorWrites::ALL,
622                })],
623                compilation_options: wgpu::PipelineCompilationOptions::default(),
624            }),
625            primitive: wgpu::PrimitiveState::default(),
626            depth_stencil: Some(stencil_for_content.clone()),
627            multisample: msaa_state,
628            multiview_mask: None,
629            cache: None,
630        });
631        // image_rgba reuses the text color pipeline (same vertex/bindings).
632        let image_rgba = text_color.clone();
633
634        // Blur composite pipeline (graphics-layer drop shadow)
635        let blur_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
636            label: Some("blur_shadow.wgsl"),
637            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
638                "shaders/blur_shadow.wgsl"
639            ))),
640        });
641        let blur_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
642            label: Some("blur pipeline layout"),
643            bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
644            immediate_size: 0,
645        });
646        let blur = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
647            label: Some("blur pipeline"),
648            layout: Some(&blur_pipeline_layout),
649            vertex: wgpu::VertexState {
650                module: &blur_shader,
651                entry_point: Some("vs_main"),
652                buffers: &[Some(wgpu::VertexBufferLayout {
653                    array_stride: std::mem::size_of::<BlurInstance>() as u64,
654                    step_mode: wgpu::VertexStepMode::Instance,
655                    attributes: &[
656                        wgpu::VertexAttribute {
657                            shader_location: 0,
658                            offset: 0,
659                            format: wgpu::VertexFormat::Float32x4,
660                        },
661                        wgpu::VertexAttribute {
662                            shader_location: 1,
663                            offset: 16,
664                            format: wgpu::VertexFormat::Float32x4,
665                        },
666                        wgpu::VertexAttribute {
667                            shader_location: 2,
668                            offset: 32,
669                            format: wgpu::VertexFormat::Float32x4,
670                        },
671                        wgpu::VertexAttribute {
672                            shader_location: 3,
673                            offset: 48,
674                            format: wgpu::VertexFormat::Float32x2,
675                        },
676                        wgpu::VertexAttribute {
677                            shader_location: 4,
678                            offset: 56,
679                            format: wgpu::VertexFormat::Float32x2,
680                        },
681                    ],
682                })],
683                compilation_options: wgpu::PipelineCompilationOptions::default(),
684            },
685            fragment: Some(wgpu::FragmentState {
686                module: &blur_shader,
687                entry_point: Some("fs_main"),
688                targets: &[Some(wgpu::ColorTargetState {
689                    format,
690                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
691                    write_mask: wgpu::ColorWrites::ALL,
692                })],
693                compilation_options: wgpu::PipelineCompilationOptions::default(),
694            }),
695            primitive: wgpu::PrimitiveState::default(),
696            depth_stencil: Some(stencil_for_content.clone()),
697            multisample: msaa_state,
698            multiview_mask: None,
699            cache: None,
700        });
701
702        // Content blur pipeline (full RGBA gaussian blur)
703        let blur_content_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
704            label: Some("blur_content.wgsl"),
705            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
706                "shaders/blur_content.wgsl"
707            ))),
708        });
709        let blur_content = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
710            label: Some("blur content pipeline"),
711            layout: Some(&blur_pipeline_layout),
712            vertex: wgpu::VertexState {
713                module: &blur_content_shader,
714                entry_point: Some("vs_main"),
715                buffers: &[Some(wgpu::VertexBufferLayout {
716                    array_stride: std::mem::size_of::<BlurInstance>() as u64,
717                    step_mode: wgpu::VertexStepMode::Instance,
718                    attributes: &[
719                        wgpu::VertexAttribute {
720                            shader_location: 0,
721                            offset: 0,
722                            format: wgpu::VertexFormat::Float32x4,
723                        },
724                        wgpu::VertexAttribute {
725                            shader_location: 1,
726                            offset: 16,
727                            format: wgpu::VertexFormat::Float32x4,
728                        },
729                        wgpu::VertexAttribute {
730                            shader_location: 2,
731                            offset: 32,
732                            format: wgpu::VertexFormat::Float32x4,
733                        },
734                        wgpu::VertexAttribute {
735                            shader_location: 3,
736                            offset: 48,
737                            format: wgpu::VertexFormat::Float32x2,
738                        },
739                        wgpu::VertexAttribute {
740                            shader_location: 4,
741                            offset: 56,
742                            format: wgpu::VertexFormat::Float32x2,
743                        },
744                    ],
745                })],
746                compilation_options: wgpu::PipelineCompilationOptions::default(),
747            },
748            fragment: Some(wgpu::FragmentState {
749                module: &blur_content_shader,
750                entry_point: Some("fs_main"),
751                targets: &[Some(wgpu::ColorTargetState {
752                    format,
753                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
754                    write_mask: wgpu::ColorWrites::ALL,
755                })],
756                compilation_options: wgpu::PipelineCompilationOptions::default(),
757            }),
758            primitive: wgpu::PrimitiveState::default(),
759            depth_stencil: Some(stencil_for_content.clone()),
760            multisample: msaa_state,
761            multiview_mask: None,
762            cache: None,
763        });
764
765        // NV12 Image Pipeline
766        let image_nv12_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
767            label: Some("image_nv12.wgsl"),
768            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
769                "shaders/image_nv12.wgsl"
770            ))),
771        });
772        let image_nv12_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
773            label: Some("image nv12 pipeline layout"),
774            bind_group_layouts: &[Some(globals_layout), Some(image_bind_layout_nv12)],
775            immediate_size: 0,
776        });
777        let image_nv12 = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
778            label: Some("image nv12 pipeline"),
779            layout: Some(&image_nv12_layout),
780            vertex: wgpu::VertexState {
781                module: &image_nv12_shader,
782                entry_point: Some("vs_main"),
783                buffers: &[Some(wgpu::VertexBufferLayout {
784                    array_stride: std::mem::size_of::<Nv12Instance>() as u64,
785                    step_mode: wgpu::VertexStepMode::Instance,
786                    attributes: &[
787                        wgpu::VertexAttribute {
788                            shader_location: 0,
789                            offset: 0,
790                            format: wgpu::VertexFormat::Float32x4,
791                        },
792                        wgpu::VertexAttribute {
793                            shader_location: 1,
794                            offset: 16,
795                            format: wgpu::VertexFormat::Float32x4,
796                        },
797                        wgpu::VertexAttribute {
798                            shader_location: 2,
799                            offset: 32,
800                            format: wgpu::VertexFormat::Float32x4,
801                        },
802                        wgpu::VertexAttribute {
803                            shader_location: 3,
804                            offset: 48,
805                            format: wgpu::VertexFormat::Float32,
806                        },
807                        wgpu::VertexAttribute {
808                            shader_location: 4,
809                            offset: 52,
810                            format: wgpu::VertexFormat::Float32x2,
811                        },
812                    ],
813                })],
814                compilation_options: wgpu::PipelineCompilationOptions::default(),
815            },
816            fragment: Some(wgpu::FragmentState {
817                module: &image_nv12_shader,
818                entry_point: Some("fs_main"),
819                targets: &[Some(wgpu::ColorTargetState {
820                    format,
821                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
822                    write_mask: wgpu::ColorWrites::ALL,
823                })],
824                compilation_options: wgpu::PipelineCompilationOptions::default(),
825            }),
826            primitive: wgpu::PrimitiveState::default(),
827            depth_stencil: Some(stencil_for_content.clone()),
828            multisample: msaa_state,
829            multiview_mask: None,
830            cache: None,
831        });
832
833        // Clipping
834        let clip_shader_a2c = device.create_shader_module(wgpu::ShaderModuleDescriptor {
835            label: Some("clip_round_rect_a2c.wgsl"),
836            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
837                "shaders/clip_round_rect_a2c.wgsl"
838            ))),
839        });
840        let clip_shader_bin = device.create_shader_module(wgpu::ShaderModuleDescriptor {
841            label: Some("clip_round_rect_bin.wgsl"),
842            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
843                "shaders/clip_round_rect_bin.wgsl"
844            ))),
845        });
846        let clip_a2c = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
847            label: Some("clip pipeline (a2c)"),
848            layout: Some(clip_pipeline_layout),
849            vertex: wgpu::VertexState {
850                module: &clip_shader_a2c,
851                entry_point: Some("vs_main"),
852                buffers: &[Some(clip_vertex_layout.clone())],
853                compilation_options: wgpu::PipelineCompilationOptions::default(),
854            },
855            fragment: Some(wgpu::FragmentState {
856                module: &clip_shader_a2c,
857                entry_point: Some("fs_main"),
858                targets: &[Some(clip_color_target.clone())],
859                compilation_options: wgpu::PipelineCompilationOptions::default(),
860            }),
861            primitive: wgpu::PrimitiveState::default(),
862            depth_stencil: Some(stencil_for_clip_inc.clone()),
863            multisample: wgpu::MultisampleState {
864                count: sample_count,
865                mask: !0,
866                alpha_to_coverage_enabled: sample_count > 1,
867            },
868            multiview_mask: None,
869            cache: None,
870        });
871        let clip_bin = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
872            label: Some("clip pipeline (bin)"),
873            layout: Some(clip_pipeline_layout),
874            vertex: wgpu::VertexState {
875                module: &clip_shader_bin,
876                entry_point: Some("vs_main"),
877                buffers: &[Some(clip_vertex_layout.clone())],
878                compilation_options: wgpu::PipelineCompilationOptions::default(),
879            },
880            fragment: Some(wgpu::FragmentState {
881                module: &clip_shader_bin,
882                entry_point: Some("fs_main"),
883                targets: &[Some(clip_color_target.clone())],
884                compilation_options: wgpu::PipelineCompilationOptions::default(),
885            }),
886            primitive: wgpu::PrimitiveState::default(),
887            depth_stencil: Some(stencil_for_clip_inc.clone()),
888            multisample: wgpu::MultisampleState {
889                count: sample_count,
890                mask: !0,
891                alpha_to_coverage_enabled: false,
892            },
893            multiview_mask: None,
894            cache: None,
895        });
896        let clip_dec = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
897            label: Some("clip pipeline (dec)"),
898            layout: Some(clip_pipeline_layout),
899            vertex: wgpu::VertexState {
900                module: &clip_shader_bin,
901                entry_point: Some("vs_main"),
902                buffers: &[Some(clip_vertex_layout.clone())],
903                compilation_options: wgpu::PipelineCompilationOptions::default(),
904            },
905            fragment: Some(wgpu::FragmentState {
906                module: &clip_shader_bin,
907                entry_point: Some("fs_main"),
908                targets: &[Some(clip_color_target.clone())],
909                compilation_options: wgpu::PipelineCompilationOptions::default(),
910            }),
911            primitive: wgpu::PrimitiveState::default(),
912            depth_stencil: Some(stencil_for_clip_dec.clone()),
913            multisample: wgpu::MultisampleState {
914                count: sample_count,
915                mask: !0,
916                alpha_to_coverage_enabled: false,
917            },
918            multiview_mask: None,
919            cache: None,
920        });
921
922        let slug = Some(slug::create_pipeline(
923            device,
924            format,
925            sample_count,
926            stencil_for_content,
927        ));
928
929        // Tessellated vector mesh pipeline (host-supplied vertex/index data).
930        let mesh_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
931            label: Some("mesh.wgsl"),
932            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shaders/mesh.wgsl"))),
933        });
934        let mesh_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
935            label: Some("mesh pipeline layout"),
936            bind_group_layouts: &[Some(globals_layout), Some(mesh_bind_layout)],
937            immediate_size: 0,
938        });
939        let mesh_vertex_layout = wgpu::VertexBufferLayout {
940            array_stride: std::mem::size_of::<MeshVertex>() as u64,
941            step_mode: wgpu::VertexStepMode::Vertex,
942            attributes: &[
943                wgpu::VertexAttribute {
944                    shader_location: 0,
945                    offset: 0,
946                    format: wgpu::VertexFormat::Float32x2,
947                },
948                wgpu::VertexAttribute {
949                    shader_location: 1,
950                    offset: 8,
951                    format: wgpu::VertexFormat::Float32x4,
952                },
953                wgpu::VertexAttribute {
954                    shader_location: 2,
955                    offset: 24,
956                    format: wgpu::VertexFormat::Float32x2,
957                },
958            ],
959        };
960        let make_mesh_pipeline =
961            |label: &str, depth: &wgpu::DepthStencilState, color: &wgpu::ColorTargetState| {
962                device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
963                    label: Some(label),
964                    layout: Some(&mesh_pipeline_layout),
965                    vertex: wgpu::VertexState {
966                        module: &mesh_shader,
967                        entry_point: Some("vs_main"),
968                        buffers: &[Some(mesh_vertex_layout.clone())],
969                        compilation_options: wgpu::PipelineCompilationOptions::default(),
970                    },
971                    fragment: Some(wgpu::FragmentState {
972                        module: &mesh_shader,
973                        entry_point: Some("fs_main"),
974                        targets: &[Some(color.clone())],
975                        compilation_options: wgpu::PipelineCompilationOptions::default(),
976                    }),
977                    primitive: wgpu::PrimitiveState {
978                        topology: wgpu::PrimitiveTopology::TriangleList,
979                        ..Default::default()
980                    },
981                    depth_stencil: Some(depth.clone()),
982                    multisample: msaa_state,
983                    multiview_mask: None,
984                    cache: None,
985                })
986            };
987        let mesh_color_target = wgpu::ColorTargetState {
988            format,
989            blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
990            write_mask: wgpu::ColorWrites::ALL,
991        };
992        let mut stencil_for_mesh = stencil_for_content.clone();
993        stencil_for_mesh.stencil.front.compare = wgpu::CompareFunction::Equal;
994        stencil_for_mesh.stencil.back.compare = wgpu::CompareFunction::Equal;
995        let mesh = make_mesh_pipeline("mesh pipeline", &stencil_for_mesh, &mesh_color_target);
996        let mesh_overlay = make_mesh_pipeline(
997            "mesh overlay pipeline",
998            stencil_for_content,
999            &mesh_color_target,
1000        );
1001        let mesh_clip_inc = make_mesh_pipeline(
1002            "mesh clip (inc) pipeline",
1003            stencil_for_clip_inc,
1004            clip_color_target,
1005        );
1006        let mesh_clip_dec = make_mesh_pipeline(
1007            "mesh clip (dec) pipeline",
1008            stencil_for_clip_dec,
1009            clip_color_target,
1010        );
1011
1012        Self {
1013            rects,
1014            borders,
1015            ellipses,
1016            ellipse_borders,
1017            arcs,
1018            text_mask,
1019            text_color,
1020            image_rgba,
1021            image_nv12,
1022            blur,
1023            blur_content,
1024            clip_a2c,
1025            clip_bin,
1026            clip_dec,
1027            slug,
1028            mesh,
1029            mesh_overlay,
1030            mesh_clip_inc,
1031            mesh_clip_dec,
1032        }
1033    }
1034}
1035
1036/// A segment of the frame that draws into a single render target.
1037struct Pass {
1038    target: PassTarget,
1039    /// The initial scissor to apply to the rpass when it is opened.
1040    initial_scissor: (u32, u32, u32, u32),
1041    /// `None` means `LoadOp::Load` (resume existing content);
1042    /// `Some(c)` means `LoadOp::Clear(c)`.
1043    clear_color: Option<[f32; 4]>,
1044    cmds: Vec<Cmd>,
1045}
1046
1047#[allow(non_snake_case)]
1048enum Cmd {
1049    ClipPush {
1050        off: u64,
1051        cnt: u32,
1052        scissor: (u32, u32, u32, u32),
1053        difference: bool,
1054        rounded: bool,
1055    },
1056    ClipPop {
1057        off: u64,
1058        cnt: u32,
1059        scissor: (u32, u32, u32, u32),
1060        difference: bool,
1061    },
1062    Rect {
1063        off: u64,
1064        cnt: u32,
1065    },
1066    Border {
1067        off: u64,
1068        cnt: u32,
1069    },
1070    Ellipse {
1071        off: u64,
1072        cnt: u32,
1073    },
1074    EllipseBorder {
1075        off: u64,
1076        cnt: u32,
1077    },
1078    Arc {
1079        off: u64,
1080        cnt: u32,
1081    },
1082    GlyphsMask {
1083        off: u64,
1084        cnt: u32,
1085    },
1086    GlyphsColor {
1087        off: u64,
1088        cnt: u32,
1089    },
1090    GlyphsVector {
1091        off: u64,
1092        cnt: u32,
1093    },
1094    ImageRgba {
1095        off: u64,
1096        cnt: u32,
1097        handle: u64,
1098    },
1099    ImageNv12 {
1100        off: u64,
1101        cnt: u32,
1102        handle: u64,
1103    },
1104    /// Composite a previously-rendered graphics layer back into the
1105    /// current target as a textured quad. The quad's vertex buffer
1106    /// lives in `self.glyph_color.ring` (a `GlyphInstance`).
1107    CompositeLayer {
1108        off: u64,
1109        cnt: u32,
1110        layer_id: u32,
1111    },
1112    /// Composite a blurred drop shadow of a previously-rendered graphics
1113    /// layer. The quad's vertex buffer lives in `self.blur_ring` (a
1114    /// `BlurInstance`).
1115    CompositeShadow {
1116        off: u64,
1117        cnt: u32,
1118        layer_id: u32,
1119    },
1120    /// Apply gaussian blur to a layer and composite the blurred result.
1121    /// Uses the `blur_content` pipeline (full RGBA blur).
1122    CompositeBlur {
1123        off: u64,
1124        cnt: u32,
1125        layer_id: u32,
1126    },
1127    /// Draw a tessellated vector mesh (solid or gradient paint).
1128    VectorMesh {
1129        voff: u64,
1130        vcnt: u32,
1131        ioff: u64,
1132        icnt: u32,
1133        uoff: u64,
1134    },
1135    /// Draw a screen-space overlay mesh (identity transform, device pixels).
1136    VectorOverlay {
1137        voff: u64,
1138        vcnt: u32,
1139        ioff: u64,
1140        icnt: u32,
1141        uoff: u64,
1142    },
1143    /// Increment the stencil buffer with a tessellated vector mask.
1144    VectorClipPush {
1145        voff: u64,
1146        vcnt: u32,
1147        ioff: u64,
1148        icnt: u32,
1149        uoff: u64,
1150        scissor: (u32, u32, u32, u32),
1151    },
1152    /// Decrement the stencil buffer with the matching vector mask.
1153    VectorClipPop {
1154        voff: u64,
1155        vcnt: u32,
1156        ioff: u64,
1157        icnt: u32,
1158        uoff: u64,
1159        scissor: (u32, u32, u32, u32),
1160    },
1161}
1162
1163enum ImageTex {
1164    Rgba {
1165        tex: wgpu::Texture,
1166        bind: wgpu::BindGroup,
1167        w: u32,
1168        h: u32,
1169        format: wgpu::TextureFormat,
1170        last_used_frame: u64,
1171        bytes: u64,
1172    },
1173    Nv12 {
1174        tex_y: wgpu::Texture,
1175        tex_uv: wgpu::Texture,
1176        bind: wgpu::BindGroup,
1177        yuv_buf: wgpu::Buffer,
1178        w: u32,
1179        h: u32,
1180        color_info: ColorInfo,
1181        last_used_frame: u64,
1182        bytes: u64,
1183    },
1184}
1185
1186#[derive(Clone)]
1187struct RetainedImage {
1188    w: u32,
1189    h: u32,
1190    format: wgpu::TextureFormat,
1191    rgba: Vec<u8>,
1192}
1193
1194struct AtlasA8 {
1195    tex: wgpu::Texture,
1196    view: wgpu::TextureView,
1197    sampler: wgpu::Sampler,
1198    size: u32,
1199    next_x: u32,
1200    next_y: u32,
1201    row_h: u32,
1202    map: HashMap<(repose_text::GlyphKey, u32), GlyphInfo>,
1203}
1204
1205struct AtlasRGBA {
1206    tex: wgpu::Texture,
1207    view: wgpu::TextureView,
1208    sampler: wgpu::Sampler,
1209    size: u32,
1210    next_x: u32,
1211    next_y: u32,
1212    row_h: u32,
1213    map: HashMap<(repose_text::GlyphKey, u32), GlyphInfo>,
1214}
1215
1216#[derive(Clone, Copy)]
1217struct GlyphInfo {
1218    u0: f32,
1219    v0: f32,
1220    u1: f32,
1221    v1: f32,
1222    w: f32,
1223    h: f32,
1224}
1225
1226#[repr(C)]
1227#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1228struct RectInstance {
1229    xywh: [f32; 4],
1230    radii: [f32; 4],
1231    brush_type: u32,
1232    _pad: [f32; 3],
1233    color0: [f32; 4],
1234    color1: [f32; 4],
1235    grad_start: [f32; 2],
1236    grad_end: [f32; 2],
1237    sin_cos: [f32; 2],
1238}
1239
1240#[repr(C)]
1241#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1242struct BorderInstance {
1243    xywh: [f32; 4],
1244    radii: [f32; 4],
1245    stroke: f32,
1246    color: [f32; 4],
1247    sin_cos: [f32; 2],
1248}
1249
1250#[repr(C)]
1251#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1252struct EllipseInstance {
1253    xywh: [f32; 4],
1254    color: [f32; 4],
1255    sin_cos: [f32; 2],
1256}
1257
1258#[repr(C)]
1259#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1260struct EllipseBorderInstance {
1261    xywh: [f32; 4],
1262    stroke: f32,
1263    pad: f32,
1264    color: [f32; 4],
1265    sin_cos: [f32; 2],
1266}
1267
1268#[repr(C)]
1269#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1270struct ArcInstance {
1271    xywh: [f32; 4],
1272    start_angle: f32,
1273    sweep_angle: f32,
1274    stroke: f32,
1275    pad: f32,
1276    color: [f32; 4],
1277    sin_cos: [f32; 2],
1278    cap: f32, // 0=Butt, 1=Round, 2=Square
1279}
1280
1281#[repr(C)]
1282#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1283struct GlyphInstance {
1284    xywh: [f32; 4],
1285    uv: [f32; 4],
1286    color: [f32; 4],
1287    sin_cos: [f32; 2],
1288}
1289
1290#[repr(C)]
1291#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1292struct BlurInstance {
1293    xywh: [f32; 4],
1294    uv: [f32; 4],
1295    color: [f32; 4],
1296    blur_uv: [f32; 2],
1297    sin_cos: [f32; 2],
1298}
1299
1300/// CPU-computed Y′CbCr -> R′G′B′ transform uploaded as a uniform buffer.
1301/// Layout matches the WGSL `YuvTransform` struct (4 × vec4<f32>).
1302#[repr(C)]
1303#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1304struct YuvTransformRaw {
1305    row0: [f32; 4],
1306    row1: [f32; 4],
1307    row2: [f32; 4],
1308    b: [f32; 4],
1309}
1310
1311#[repr(C)]
1312#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1313struct Nv12Instance {
1314    xywh: [f32; 4],
1315    uv: [f32; 4],
1316    color: [f32; 4], // tint
1317    uv_x_offset: f32,
1318    sin_cos: [f32; 2],
1319    _pad: [f32; 1],
1320}
1321
1322#[repr(C)]
1323#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1324struct ClipInstance {
1325    xywh: [f32; 4],
1326    radii: [f32; 4],
1327    sin_cos: [f32; 2],
1328}
1329
1330#[repr(C)]
1331#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1332struct MeshVertex {
1333    pos: [f32; 2],
1334    color: [f32; 4],
1335    uv: [f32; 2],
1336}
1337
1338#[repr(C)]
1339#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1340struct MeshUniform {
1341    m0: [f32; 4],
1342    m1: [f32; 4],
1343    paint: [u32; 4],
1344    color0: [f32; 4],
1345    color1: [f32; 4],
1346    grad_start: [f32; 2],
1347    _p3: [f32; 2],
1348    grad_end: [f32; 2],
1349    _p4: [f32; 2],
1350}
1351
1352/// Dynamic uniform slots are aligned to 256 bytes by wgpu.
1353const MESH_UNIFORM_SLOT: u64 = 256;
1354const MESH_UNIFORM_CAP: u64 = 4 * 1024 * 1024;
1355
1356impl MeshUniform {
1357    fn identity() -> Self {
1358        Self {
1359            m0: [1.0, 0.0, 0.0, 0.0],
1360            m1: [0.0, 1.0, 0.0, 0.0],
1361            paint: [0; 4],
1362            color0: [0.0; 4],
1363            color1: [0.0; 4],
1364            grad_start: [0.0; 2],
1365            _p3: [0.0; 2],
1366            grad_end: [0.0; 2],
1367            _p4: [0.0; 2],
1368        }
1369    }
1370}
1371
1372fn mesh_uniform_from_paint(affine: [f32; 6], paint: &repose_core::PaintDesc) -> MeshUniform {
1373    let (paint_type, color0, color1, grad_start, grad_end) = match paint {
1374        repose_core::PaintDesc::Solid => (0u32, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2]),
1375        repose_core::PaintDesc::Linear {
1376            start,
1377            end,
1378            start_color,
1379            end_color,
1380        } => (
1381            1u32,
1382            start_color.to_linear(),
1383            end_color.to_linear(),
1384            [start.x, start.y],
1385            [end.x, end.y],
1386        ),
1387        // PaintDesc is #[non_exhaustive]; treat unknown paints as solid.
1388        _ => (0u32, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2]),
1389    };
1390    MeshUniform {
1391        m0: [affine[0], affine[1], affine[2], 0.0],
1392        m1: [affine[3], affine[4], affine[5], 0.0],
1393        paint: [paint_type, 0, 0, 0],
1394        color0,
1395        color1,
1396        grad_start,
1397        _p3: [0.0; 2],
1398        grad_end,
1399        _p4: [0.0; 2],
1400    }
1401}
1402
1403fn combine_mesh_affine(current: &Transform, mesh: [f32; 6]) -> [f32; 6] {
1404    let cos_a = current.rotate.cos();
1405    let sin_a = current.rotate.sin();
1406    // current transform linear part: [[sx*cos, -sy*sin],[sx*sin, sy*cos]]
1407    let cm00 = current.scale_x * cos_a;
1408    let cm01 = -current.scale_y * sin_a;
1409    let cm10 = current.scale_x * sin_a;
1410    let cm11 = current.scale_y * cos_a;
1411    // mesh affine: out = [[mm00, mm01],[mm10, mm11]] * local + (mtx, mty)
1412    let mm00 = mesh[0];
1413    let mm01 = mesh[1];
1414    let mm10 = mesh[2];
1415    let mm11 = mesh[3];
1416    let mtx = mesh[4];
1417    let mty = mesh[5];
1418    let r00 = cm00 * mm00 + cm01 * mm10;
1419    let r01 = cm00 * mm01 + cm01 * mm11;
1420    let r10 = cm10 * mm00 + cm11 * mm10;
1421    let r11 = cm10 * mm01 + cm11 * mm11;
1422    let tx = cm00 * mtx + cm01 * mty + current.translate_x;
1423    let ty = cm10 * mtx + cm11 * mty + current.translate_y;
1424    // Canonical slot order consumed by `MeshUniform`/shader and `mesh_aabb`:
1425    // [A, B, tx, C, D, ty] where world = [[A,B],[C,D]] * local + (tx, ty).
1426    [r00, r01, tx, r10, r11, ty]
1427}
1428
1429fn mesh_aabb(mesh: &repose_core::VectorMeshData, affine: [f32; 6]) -> repose_core::Rect {
1430    let mut min_x = f32::MAX;
1431    let mut min_y = f32::MAX;
1432    let mut max_x = f32::MIN;
1433    let mut max_y = f32::MIN;
1434    for v in mesh.vertices.iter() {
1435        let x = affine[0] * v.pos[0] + affine[1] * v.pos[1] + affine[2];
1436        let y = affine[3] * v.pos[0] + affine[4] * v.pos[1] + affine[5];
1437        min_x = min_x.min(x);
1438        min_y = min_y.min(y);
1439        max_x = max_x.max(x);
1440        max_y = max_y.max(y);
1441    }
1442    let w = (max_x - min_x).max(0.0);
1443    let h = (max_y - min_y).max(0.0);
1444    if !min_x.is_finite() || !min_y.is_finite() {
1445        return repose_core::Rect {
1446            x: 0.0,
1447            y: 0.0,
1448            w: 0.0,
1449            h: 0.0,
1450        };
1451    }
1452    repose_core::Rect {
1453        x: min_x,
1454        y: min_y,
1455        w,
1456        h,
1457    }
1458}
1459
1460fn swash_to_a8_coverage(content: repose_text::SwashContent, data: &[u8]) -> Option<Vec<u8>> {
1461    match content {
1462        repose_text::SwashContent::Mask => Some(data.to_vec()),
1463        repose_text::SwashContent::SubpixelMask => {
1464            let mut out = Vec::with_capacity(data.len() / 4);
1465            for px in data.chunks_exact(4) {
1466                let r = px[0];
1467                let g = px[1];
1468                let b = px[2];
1469                out.push(r.max(g).max(b));
1470            }
1471            Some(out)
1472        }
1473        repose_text::SwashContent::Color => None,
1474    }
1475}
1476
1477impl WgpuSceneRenderer {
1478    pub fn from_device(
1479        device: wgpu::Device,
1480        queue: wgpu::Queue,
1481        output_format: wgpu::TextureFormat,
1482        msaa_samples: u32,
1483    ) -> Self {
1484        let globals_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1485            label: Some("globals layout"),
1486            entries: &[wgpu::BindGroupLayoutEntry {
1487                binding: 0,
1488                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
1489                ty: wgpu::BindingType::Buffer {
1490                    ty: wgpu::BufferBindingType::Uniform,
1491                    has_dynamic_offset: false,
1492                    min_binding_size: None,
1493                },
1494                count: None,
1495            }],
1496        });
1497
1498        let globals_buf = device.create_buffer(&wgpu::BufferDescriptor {
1499            label: Some("globals buf"),
1500            size: std::mem::size_of::<Globals>() as u64,
1501            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1502            mapped_at_creation: false,
1503        });
1504
1505        let globals_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
1506            label: Some("globals bind"),
1507            layout: &globals_layout,
1508            entries: &[wgpu::BindGroupEntry {
1509                binding: 0,
1510                resource: globals_buf.as_entire_binding(),
1511            }],
1512        });
1513
1514        let ds_format = wgpu::TextureFormat::Depth24PlusStencil8;
1515
1516        let stencil_for_content = wgpu::DepthStencilState {
1517            format: ds_format,
1518            depth_write_enabled: Some(false),
1519            depth_compare: Some(wgpu::CompareFunction::Always),
1520            stencil: wgpu::StencilState {
1521                front: wgpu::StencilFaceState {
1522                    compare: wgpu::CompareFunction::LessEqual,
1523                    fail_op: wgpu::StencilOperation::Keep,
1524                    depth_fail_op: wgpu::StencilOperation::Keep,
1525                    pass_op: wgpu::StencilOperation::Keep,
1526                },
1527                back: wgpu::StencilFaceState {
1528                    compare: wgpu::CompareFunction::LessEqual,
1529                    fail_op: wgpu::StencilOperation::Keep,
1530                    depth_fail_op: wgpu::StencilOperation::Keep,
1531                    pass_op: wgpu::StencilOperation::Keep,
1532                },
1533                read_mask: 0xFF,
1534                write_mask: 0x00,
1535            },
1536            bias: wgpu::DepthBiasState::default(),
1537        };
1538
1539        let stencil_for_clip_inc = wgpu::DepthStencilState {
1540            format: ds_format,
1541            depth_write_enabled: Some(false),
1542            depth_compare: Some(wgpu::CompareFunction::Always),
1543            stencil: wgpu::StencilState {
1544                front: wgpu::StencilFaceState {
1545                    compare: wgpu::CompareFunction::Equal,
1546                    fail_op: wgpu::StencilOperation::Keep,
1547                    depth_fail_op: wgpu::StencilOperation::Keep,
1548                    pass_op: wgpu::StencilOperation::IncrementClamp,
1549                },
1550                back: wgpu::StencilFaceState {
1551                    compare: wgpu::CompareFunction::Equal,
1552                    fail_op: wgpu::StencilOperation::Keep,
1553                    depth_fail_op: wgpu::StencilOperation::Keep,
1554                    pass_op: wgpu::StencilOperation::IncrementClamp,
1555                },
1556                read_mask: 0xFF,
1557                write_mask: 0xFF,
1558            },
1559            bias: wgpu::DepthBiasState::default(),
1560        };
1561
1562        let stencil_for_clip_dec = wgpu::DepthStencilState {
1563            format: ds_format,
1564            depth_write_enabled: Some(false),
1565            depth_compare: Some(wgpu::CompareFunction::Always),
1566            stencil: wgpu::StencilState {
1567                front: wgpu::StencilFaceState {
1568                    compare: wgpu::CompareFunction::Equal,
1569                    fail_op: wgpu::StencilOperation::Keep,
1570                    depth_fail_op: wgpu::StencilOperation::Keep,
1571                    pass_op: wgpu::StencilOperation::DecrementClamp,
1572                },
1573                back: wgpu::StencilFaceState {
1574                    compare: wgpu::CompareFunction::Equal,
1575                    fail_op: wgpu::StencilOperation::Keep,
1576                    depth_fail_op: wgpu::StencilOperation::Keep,
1577                    pass_op: wgpu::StencilOperation::DecrementClamp,
1578                },
1579                read_mask: 0xFF,
1580                write_mask: 0xFF,
1581            },
1582            bias: wgpu::DepthBiasState::default(),
1583        };
1584
1585        let _multisample_state = wgpu::MultisampleState {
1586            count: msaa_samples,
1587            mask: !0,
1588            alpha_to_coverage_enabled: false,
1589        };
1590
1591        // PIPELINES
1592
1593        // Single shared sampler for images/text
1594        let image_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
1595            label: Some("image/text sampler"),
1596            address_mode_u: wgpu::AddressMode::ClampToEdge,
1597            address_mode_v: wgpu::AddressMode::ClampToEdge,
1598            mag_filter: wgpu::FilterMode::Linear,
1599            min_filter: wgpu::FilterMode::Linear,
1600            mipmap_filter: wgpu::MipmapFilterMode::Linear,
1601            ..Default::default()
1602        });
1603
1604        // linear filtering only blurs them; nearest keeps the blit crisp.
1605        let layer_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
1606            label: Some("layer nearest sampler"),
1607            address_mode_u: wgpu::AddressMode::ClampToEdge,
1608            address_mode_v: wgpu::AddressMode::ClampToEdge,
1609            mag_filter: wgpu::FilterMode::Nearest,
1610            min_filter: wgpu::FilterMode::Nearest,
1611            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
1612            ..Default::default()
1613        });
1614
1615        // Linear taps for Gaussian blur/shadow passes; nearest is kept for
1616        // the sharp 1:1 layer composite.
1617        let layer_sampler_linear = device.create_sampler(&wgpu::SamplerDescriptor {
1618            label: Some("layer linear sampler"),
1619            address_mode_u: wgpu::AddressMode::ClampToEdge,
1620            address_mode_v: wgpu::AddressMode::ClampToEdge,
1621            mag_filter: wgpu::FilterMode::Linear,
1622            min_filter: wgpu::FilterMode::Linear,
1623            mipmap_filter: wgpu::MipmapFilterMode::Linear,
1624            ..Default::default()
1625        });
1626
1627        // Layout for Text / RGBA Images (Texture + Sampler)
1628        let text_bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1629            label: Some("text/rgba bind layout"),
1630            entries: &[
1631                wgpu::BindGroupLayoutEntry {
1632                    binding: 0,
1633                    visibility: wgpu::ShaderStages::FRAGMENT,
1634                    ty: wgpu::BindingType::Texture {
1635                        multisampled: false,
1636                        view_dimension: wgpu::TextureViewDimension::D2,
1637                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
1638                    },
1639                    count: None,
1640                },
1641                wgpu::BindGroupLayoutEntry {
1642                    binding: 1,
1643                    visibility: wgpu::ShaderStages::FRAGMENT,
1644                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1645                    count: None,
1646                },
1647            ],
1648        });
1649        // We reuse this for RGBA images for simplicity, or create a distinct one
1650        let image_bind_layout_rgba = text_bind_layout.clone();
1651
1652        // Layout for NV12 Images (TextureY + TextureUV + Sampler + YuvTransform uniform)
1653        let image_bind_layout_nv12 =
1654            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1655                label: Some("image bind layout nv12"),
1656                entries: &[
1657                    // Y plane
1658                    wgpu::BindGroupLayoutEntry {
1659                        binding: 0,
1660                        visibility: wgpu::ShaderStages::FRAGMENT,
1661                        ty: wgpu::BindingType::Texture {
1662                            multisampled: false,
1663                            view_dimension: wgpu::TextureViewDimension::D2,
1664                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
1665                        },
1666                        count: None,
1667                    },
1668                    // UV plane
1669                    wgpu::BindGroupLayoutEntry {
1670                        binding: 1,
1671                        visibility: wgpu::ShaderStages::FRAGMENT,
1672                        ty: wgpu::BindingType::Texture {
1673                            multisampled: false,
1674                            view_dimension: wgpu::TextureViewDimension::D2,
1675                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
1676                        },
1677                        count: None,
1678                    },
1679                    // Sampler
1680                    wgpu::BindGroupLayoutEntry {
1681                        binding: 2,
1682                        visibility: wgpu::ShaderStages::FRAGMENT,
1683                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1684                        count: None,
1685                    },
1686                    // YUV transform uniform buffer
1687                    wgpu::BindGroupLayoutEntry {
1688                        binding: 3,
1689                        visibility: wgpu::ShaderStages::FRAGMENT,
1690                        ty: wgpu::BindingType::Buffer {
1691                            ty: wgpu::BufferBindingType::Uniform,
1692                            has_dynamic_offset: false,
1693                            min_binding_size: None,
1694                        },
1695                        count: None,
1696                    },
1697                ],
1698            });
1699
1700        // Clipping layout
1701        let clip_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1702            label: Some("clip pipeline layout"),
1703            bind_group_layouts: &[Some(&globals_layout)],
1704            immediate_size: 0,
1705        });
1706        let clip_vertex_layout = wgpu::VertexBufferLayout {
1707            array_stride: std::mem::size_of::<ClipInstance>() as u64,
1708            step_mode: wgpu::VertexStepMode::Instance,
1709            attributes: &[
1710                wgpu::VertexAttribute {
1711                    shader_location: 0,
1712                    offset: 0,
1713                    format: wgpu::VertexFormat::Float32x4,
1714                },
1715                wgpu::VertexAttribute {
1716                    shader_location: 1,
1717                    offset: 16,
1718                    format: wgpu::VertexFormat::Float32x4,
1719                },
1720                wgpu::VertexAttribute {
1721                    shader_location: 2,
1722                    offset: 32,
1723                    format: wgpu::VertexFormat::Float32x2,
1724                },
1725            ],
1726        };
1727        let clip_color_target = wgpu::ColorTargetState {
1728            format: output_format,
1729            blend: None,
1730            write_mask: wgpu::ColorWrites::empty(),
1731        };
1732
1733        // Bind layout for per-draw vector mesh uniforms (dynamic offset).
1734        let mesh_bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1735            label: Some("mesh uniform layout"),
1736            entries: &[wgpu::BindGroupLayoutEntry {
1737                binding: 0,
1738                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
1739                ty: wgpu::BindingType::Buffer {
1740                    ty: wgpu::BufferBindingType::Uniform,
1741                    has_dynamic_offset: true,
1742                    min_binding_size: NonZero::new(MESH_UNIFORM_SLOT),
1743                },
1744                count: None,
1745            }],
1746        });
1747        let mesh_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
1748            label: Some("mesh uniform buffer"),
1749            size: MESH_UNIFORM_CAP,
1750            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1751            mapped_at_creation: false,
1752        });
1753        let mesh_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
1754            label: Some("mesh uniform bind"),
1755            layout: &mesh_bind_layout,
1756            entries: &[wgpu::BindGroupEntry {
1757                binding: 0,
1758                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1759                    buffer: &mesh_uniform_buf,
1760                    offset: 0,
1761                    size: NonZero::new(MESH_UNIFORM_SLOT),
1762                }),
1763            }],
1764        });
1765
1766        // Two sets of pipelines: one for the MSAA surface pass, one for layer
1767        // render-to-texture passes (sample_count = 1).
1768        let surface_pipes = Pipelines::create(
1769            &device,
1770            output_format,
1771            msaa_samples,
1772            &globals_layout,
1773            &text_bind_layout,
1774            &image_bind_layout_nv12,
1775            &clip_pipeline_layout,
1776            &stencil_for_content,
1777            &stencil_for_clip_inc,
1778            &stencil_for_clip_dec,
1779            &clip_color_target,
1780            &clip_vertex_layout,
1781            &mesh_bind_layout,
1782        );
1783        let layer_pipes = Pipelines::create(
1784            &device,
1785            output_format,
1786            1,
1787            &globals_layout,
1788            &text_bind_layout,
1789            &image_bind_layout_nv12,
1790            &clip_pipeline_layout,
1791            &stencil_for_content,
1792            &stencil_for_clip_inc,
1793            &stencil_for_clip_dec,
1794            &clip_color_target,
1795            &clip_vertex_layout,
1796            &mesh_bind_layout,
1797        );
1798
1799        // Vector glyph rendering always available with tessellation+MSAA approach.
1800        let slug_enabled = true;
1801
1802        // Blur composite ring (for graphics-layer drop shadows)
1803        let blur_ring = UploadRing::new(
1804            &device,
1805            "blur ring",
1806            1024 * 1024,
1807            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1808        );
1809
1810        // Atlases
1811        let atlas_mask = init_atlas_mask(&device);
1812        let atlas_color = init_atlas_color(&device);
1813
1814        // Upload rings
1815        let ring_rect = UploadRing::new(
1816            &device,
1817            "ring rect",
1818            1 << 20,
1819            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1820        );
1821        let ring_border = UploadRing::new(
1822            &device,
1823            "ring border",
1824            1 << 20,
1825            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1826        );
1827        let ring_ellipse = UploadRing::new(
1828            &device,
1829            "ring ellipse",
1830            1 << 20,
1831            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1832        );
1833        let ring_ellipse_border = UploadRing::new(
1834            &device,
1835            "ring ellipse border",
1836            1 << 20,
1837            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1838        );
1839        let ring_arc = UploadRing::new(
1840            &device,
1841            "ring arc",
1842            1 << 20,
1843            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1844        );
1845        let ring_glyph_mask = UploadRing::new(
1846            &device,
1847            "ring glyph mask",
1848            1 << 20,
1849            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1850        );
1851        let ring_glyph_color = UploadRing::new(
1852            &device,
1853            "ring glyph color",
1854            1 << 20,
1855            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1856        );
1857        let ring_slug = UploadRing::new(
1858            &device,
1859            "ring slug",
1860            1 << 22,
1861            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1862        );
1863        let ring_clip = UploadRing::new(
1864            &device,
1865            "ring clip",
1866            1 << 16,
1867            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1868        );
1869        let ring_nv12 = UploadRing::new(
1870            &device,
1871            "ring nv12",
1872            1 << 20,
1873            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1874        );
1875        let ring_mesh_verts = UploadRing::new(
1876            &device,
1877            "ring mesh verts",
1878            1 << 22,
1879            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1880        );
1881        let ring_mesh_indices = UploadRing::new(
1882            &device,
1883            "ring mesh indices",
1884            1 << 22,
1885            wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
1886        );
1887
1888        // Placeholder textures
1889        let depth_stencil_tex = device.create_texture(&wgpu::TextureDescriptor {
1890            label: Some("temp ds"),
1891            size: wgpu::Extent3d {
1892                width: 1,
1893                height: 1,
1894                depth_or_array_layers: 1,
1895            },
1896            mip_level_count: 1,
1897            sample_count: 1,
1898            dimension: wgpu::TextureDimension::D2,
1899            format: wgpu::TextureFormat::Depth24PlusStencil8,
1900            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1901            view_formats: &[],
1902        });
1903        let depth_stencil_view =
1904            depth_stencil_tex.create_view(&wgpu::TextureViewDescriptor::default());
1905
1906        let mut renderer = WgpuSceneRenderer {
1907            device,
1908            queue,
1909            output_format,
1910            output_width: 0,
1911            output_height: 0,
1912
1913            surface_pipes,
1914            layer_pipes,
1915
1916            rects: InstancedPipe::new(ring_rect),
1917            borders: InstancedPipe::new(ring_border),
1918            ellipses: InstancedPipe::new(ring_ellipse),
1919            ellipse_borders: InstancedPipe::new(ring_ellipse_border),
1920            arcs: InstancedPipe::new(ring_arc),
1921            glyph_mask: InstancedPipe::new(ring_glyph_mask),
1922            glyph_color: InstancedPipe::new(ring_glyph_color),
1923
1924            text_bind_layout,
1925
1926            image_bind_layout_rgba,
1927            image_bind_layout_nv12,
1928            image_sampler,
1929            layer_sampler,
1930            layer_sampler_linear,
1931
1932            blur_ring,
1933
1934            slug_enabled,
1935            slug_ring: ring_slug,
1936            slug_cache: slug::GlyphSlugCache::new(),
1937
1938            clip_ring: ring_clip,
1939
1940            nv12: InstancedPipe::new(ring_nv12),
1941
1942            mesh_verts: ring_mesh_verts,
1943            mesh_indices: ring_mesh_indices,
1944            mesh_uniform_buf,
1945            mesh_bind_layout,
1946            mesh_bind,
1947            mesh_uniform_head: 0,
1948            mesh_clip_stack: Vec::new(),
1949
1950            msaa_samples,
1951            depth_stencil_tex,
1952            depth_stencil_view,
1953            msaa_tex: None,
1954            msaa_view: None,
1955            globals_bind,
1956            globals_buf,
1957
1958            atlas_mask,
1959            atlas_color,
1960
1961            next_image_handle: 1,
1962            images: HashMap::new(),
1963            retained: HashMap::new(),
1964
1965            frame_index: 0,
1966            image_bytes_total: 0,
1967            image_evict_after_frames: 600,         // ~10s @ 60fps
1968            image_budget_bytes: 512 * 1024 * 1024, // 512 MB
1969            layer_pool: HashMap::new(),
1970
1971            working_space: false,
1972            ws_tex: None,
1973            ws_view: None,
1974            ws_bind: None,
1975            display_pipeline: None,
1976            display_layout: None,
1977        };
1978
1979        renderer.recreate_msaa_and_depth_stencil();
1980        renderer
1981    }
1982}
1983
1984impl WgpuSurfaceBackend {
1985    #[cfg(feature = "winit-surface")]
1986    pub async fn new_async(
1987        window: Arc<winit::window::Window>,
1988    ) -> anyhow::Result<WgpuSurfaceBackend> {
1989        Self::new_async_with_options(window, 4, PresentModePref::Auto).await
1990    }
1991
1992    /// Create a windowed surface backend, honoring the requested MSAA sample
1993    /// count (falling back to the largest supported count <= `msaa_samples`).
1994    #[cfg(feature = "winit-surface")]
1995    pub async fn new_async_with_msaa(
1996        window: Arc<winit::window::Window>,
1997        msaa_samples: u32,
1998    ) -> anyhow::Result<WgpuSurfaceBackend> {
1999        Self::new_async_with_options(window, msaa_samples, PresentModePref::Auto).await
2000    }
2001
2002    /// Create a windowed surface backend, honoring the requested MSAA sample
2003    /// count and present-mode preference.
2004    #[cfg(feature = "winit-surface")]
2005    pub async fn new_async_with_options(
2006        window: Arc<winit::window::Window>,
2007        msaa_samples: u32,
2008        present_mode: PresentModePref,
2009    ) -> anyhow::Result<WgpuSurfaceBackend> {
2010        let instance: Instance;
2011
2012        if cfg!(target_arch = "wasm32") {
2013            let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
2014            desc.backends = wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL;
2015            instance = wgpu::util::new_instance_with_webgpu_detection(desc).await;
2016        } else {
2017            instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
2018        };
2019
2020        let surface = instance.create_surface(window.clone())?;
2021
2022        let adapter = instance
2023            .request_adapter(&wgpu::RequestAdapterOptions {
2024                power_preference: wgpu::PowerPreference::HighPerformance,
2025                compatible_surface: Some(&surface),
2026                force_fallback_adapter: false,
2027                apply_limit_buckets: false,
2028            })
2029            .await
2030            .map_err(|e| anyhow::anyhow!("No suitable adapter: {e:?}"))?;
2031
2032        let limits = adapter.limits();
2033
2034        #[cfg(target_os = "linux")]
2035        let features = {
2036            let af = adapter.features();
2037            let mut f = wgpu::Features::empty();
2038            if af.contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_FD) {
2039                f |= wgpu::Features::VULKAN_EXTERNAL_MEMORY_FD;
2040            }
2041            if af.contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF) {
2042                f |= wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF;
2043            }
2044            f
2045        };
2046        #[cfg(not(target_os = "linux"))]
2047        let features = wgpu::Features::empty();
2048
2049        let (device, queue) = adapter
2050            .request_device(&wgpu::DeviceDescriptor {
2051                label: Some("repose-rs device"),
2052                required_features: features,
2053                required_limits: limits,
2054                experimental_features: wgpu::ExperimentalFeatures::disabled(),
2055                memory_hints: wgpu::MemoryHints::default(),
2056                trace: wgpu::Trace::Off,
2057            })
2058            .await
2059            .map_err(|e| anyhow::anyhow!("request_device failed: {e:?}"))?;
2060
2061        let size = window.inner_size();
2062
2063        let caps = surface.get_capabilities(&adapter);
2064        let format = caps
2065            .formats
2066            .iter()
2067            .copied()
2068            .find(|f| f.is_srgb())
2069            .unwrap_or(caps.formats[0]);
2070        let present_mode = pick_present_mode(&caps, present_mode);
2071        let alpha_mode = caps.alpha_modes[0];
2072
2073        // Pick MSAA sample count, honoring the requested value. The depth
2074        // target is created at the same sample count and the MSAA color target
2075        // resolves to the surface, so both must support the count.
2076        let msaa_samples = pick_surface_msaa(&adapter, format, msaa_samples);
2077
2078        let renderer = WgpuSceneRenderer::from_device(device, queue, format, msaa_samples);
2079
2080        let config = wgpu::SurfaceConfiguration {
2081            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
2082            format,
2083            width: size.width.max(1),
2084            height: size.height.max(1),
2085            present_mode,
2086            alpha_mode,
2087            color_space: wgpu::SurfaceColorSpace::Auto,
2088            view_formats: vec![],
2089            desired_maximum_frame_latency: 1,
2090        };
2091        surface.configure(&renderer.device, &config);
2092
2093        Ok(WgpuSurfaceBackend {
2094            surface: Some(surface),
2095            surface_config: Some(config),
2096            renderer,
2097        })
2098    }
2099
2100    #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
2101    pub fn new(window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
2102        pollster::block_on(Self::new_async(window))
2103    }
2104
2105    #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
2106    pub fn new_with_msaa(
2107        window: Arc<winit::window::Window>,
2108        msaa_samples: u32,
2109    ) -> anyhow::Result<WgpuSurfaceBackend> {
2110        pollster::block_on(Self::new_async_with_msaa(window, msaa_samples))
2111    }
2112
2113    #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
2114    pub fn new_with_options(
2115        window: Arc<winit::window::Window>,
2116        msaa_samples: u32,
2117        present_mode: PresentModePref,
2118    ) -> anyhow::Result<WgpuSurfaceBackend> {
2119        pollster::block_on(Self::new_async_with_options(
2120            window,
2121            msaa_samples,
2122            present_mode,
2123        ))
2124    }
2125
2126    #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
2127    pub fn new(_window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
2128        anyhow::bail!("Use WgpuSurfaceBackend::new_async(window).await on wasm32")
2129    }
2130
2131    #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
2132    pub fn new_with_msaa(
2133        _window: Arc<winit::window::Window>,
2134        _msaa_samples: u32,
2135    ) -> anyhow::Result<WgpuSurfaceBackend> {
2136        anyhow::bail!("Use WgpuSurfaceBackend::new_async_with_msaa(window, msaa).await on wasm32")
2137    }
2138
2139    #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
2140    pub fn new_with_options(
2141        _window: Arc<winit::window::Window>,
2142        _msaa_samples: u32,
2143        _present_mode: PresentModePref,
2144    ) -> anyhow::Result<WgpuSurfaceBackend> {
2145        anyhow::bail!(
2146            "Use WgpuSurfaceBackend::new_async_with_options(window, msaa, mode).await on wasm32"
2147        )
2148    }
2149}
2150
2151/// Pick the swapchain present mode honoring `pref`, falling back to an "auto"
2152/// Fifo-first selection when the preferred mode is unavailable.
2153fn pick_present_mode(caps: &wgpu::SurfaceCapabilities, pref: PresentModePref) -> wgpu::PresentMode {
2154    let auto = || {
2155        caps.present_modes
2156            .iter()
2157            .copied()
2158            .find(|m| *m == wgpu::PresentMode::Fifo)
2159            .or_else(|| {
2160                caps.present_modes
2161                    .iter()
2162                    .copied()
2163                    .find(|m| *m == wgpu::PresentMode::Mailbox)
2164            })
2165            .unwrap_or(wgpu::PresentMode::Immediate)
2166    };
2167    match pref {
2168        PresentModePref::Auto => auto(),
2169        PresentModePref::Fifo if caps.present_modes.contains(&wgpu::PresentMode::Fifo) => {
2170            wgpu::PresentMode::Fifo
2171        }
2172        PresentModePref::Mailbox if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) => {
2173            wgpu::PresentMode::Mailbox
2174        }
2175        PresentModePref::Immediate
2176            if caps.present_modes.contains(&wgpu::PresentMode::Immediate) =>
2177        {
2178            wgpu::PresentMode::Immediate
2179        }
2180        _ => auto(),
2181    }
2182}
2183
2184/// Pick the MSAA sample count for the surface pass, honoring `requested` and
2185/// falling back to the largest supported count <= it.
2186fn pick_surface_msaa(adapter: &wgpu::Adapter, format: wgpu::TextureFormat, requested: u32) -> u32 {
2187    let requested = requested.max(1);
2188    let color_feat = adapter.get_texture_format_features(format);
2189    let depth_feat = adapter.get_texture_format_features(wgpu::TextureFormat::Depth24PlusStencil8);
2190    let supported = |n: u32| {
2191        color_feat.flags.sample_count_supported(n)
2192            && color_feat
2193                .flags
2194                .contains(wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE)
2195            && depth_feat.flags.sample_count_supported(n)
2196    };
2197    let mut candidates = vec![requested];
2198    for n in [8, 4, 2, 1] {
2199        if n < requested {
2200            candidates.push(n);
2201        }
2202    }
2203    let chosen = candidates.into_iter().find(|&n| supported(n)).unwrap_or(1);
2204    if chosen != requested {
2205        log::info!("requested MSAA x{requested}, using x{chosen}");
2206    }
2207    chosen
2208}
2209
2210impl WgpuSceneRenderer {
2211    // Image API
2212
2213    pub fn set_image_from_bytes(
2214        &mut self,
2215        handle: u64,
2216        data: &[u8],
2217        srgb: bool,
2218    ) -> anyhow::Result<()> {
2219        let img = image::load_from_memory(data)?;
2220        let rgba = img.to_rgba8();
2221        let (w, h) = rgba.dimensions();
2222        self.set_image_rgba8(handle, w, h, &rgba, srgb)
2223    }
2224
2225    pub fn set_image_rgba8(
2226        &mut self,
2227        handle: u64,
2228        w: u32,
2229        h: u32,
2230        rgba: &[u8],
2231        srgb: bool,
2232    ) -> anyhow::Result<()> {
2233        let expected = (w as usize) * (h as usize) * 4;
2234        if rgba.len() < expected {
2235            return Err(anyhow::anyhow!(
2236                "RGBA buffer too small: {} < {}",
2237                rgba.len(),
2238                expected
2239            ));
2240        }
2241
2242        let format = if srgb {
2243            wgpu::TextureFormat::Rgba8UnormSrgb
2244        } else {
2245            wgpu::TextureFormat::Rgba8Unorm
2246        };
2247
2248        let needs_recreate = match self.images.get(&handle) {
2249            Some(ImageTex::Rgba {
2250                w: cw,
2251                h: ch,
2252                format: cf,
2253                ..
2254            }) => *cw != w || *ch != h || *cf != format,
2255            _ => true,
2256        };
2257
2258        if needs_recreate {
2259            // Remove old to track budget correctly
2260            self.remove_image(handle);
2261
2262            let (tex, bind) = self.create_rgba_tex(w, h, format);
2263            let bytes = (w as u64) * (h as u64) * 4;
2264            self.image_bytes_total += bytes;
2265
2266            self.images.insert(
2267                handle,
2268                ImageTex::Rgba {
2269                    tex,
2270                    bind,
2271                    w,
2272                    h,
2273                    format,
2274                    last_used_frame: self.frame_index,
2275                    bytes,
2276                },
2277            );
2278        }
2279
2280        self.retained.insert(
2281            handle,
2282            RetainedImage {
2283                w,
2284                h,
2285                format,
2286                rgba: rgba[..expected].to_vec(),
2287            },
2288        );
2289
2290        let tex = match self.images.get(&handle) {
2291            Some(ImageTex::Rgba { tex, .. }) => tex,
2292            _ => unreachable!(),
2293        };
2294
2295        self.queue.write_texture(
2296            wgpu::TexelCopyTextureInfo {
2297                texture: tex,
2298                mip_level: 0,
2299                origin: wgpu::Origin3d::ZERO,
2300                aspect: wgpu::TextureAspect::All,
2301            },
2302            &rgba[..expected],
2303            wgpu::TexelCopyBufferLayout {
2304                offset: 0,
2305                bytes_per_row: Some(4 * w),
2306                rows_per_image: Some(h),
2307            },
2308            wgpu::Extent3d {
2309                width: w,
2310                height: h,
2311                depth_or_array_layers: 1,
2312            },
2313        );
2314
2315        // Ensure budget limits
2316        self.evict_budget_excess();
2317
2318        Ok(())
2319    }
2320
2321    /// Create (but do not populate) the GPU texture, view and bind group for an
2322    /// RGBA image. Pixels are written separately via `write_texture`.
2323    fn create_rgba_tex(
2324        &self,
2325        w: u32,
2326        h: u32,
2327        format: wgpu::TextureFormat,
2328    ) -> (wgpu::Texture, wgpu::BindGroup) {
2329        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2330            label: Some("user image rgba"),
2331            size: wgpu::Extent3d {
2332                width: w,
2333                height: h,
2334                depth_or_array_layers: 1,
2335            },
2336            mip_level_count: 1,
2337            sample_count: 1,
2338            dimension: wgpu::TextureDimension::D2,
2339            format,
2340            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2341            view_formats: &[],
2342        });
2343        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2344
2345        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2346            label: Some("image bind rgba"),
2347            layout: &self.image_bind_layout_rgba,
2348            entries: &[
2349                wgpu::BindGroupEntry {
2350                    binding: 0,
2351                    resource: wgpu::BindingResource::TextureView(&view),
2352                },
2353                wgpu::BindGroupEntry {
2354                    binding: 1,
2355                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2356                },
2357            ],
2358        });
2359
2360        (tex, bind)
2361    }
2362
2363    pub fn set_image_nv12(
2364        &mut self,
2365        handle: u64,
2366        w: u32,
2367        h: u32,
2368        y: &[u8],
2369        uv: &[u8],
2370        color_info: ColorInfo,
2371    ) -> anyhow::Result<()> {
2372        let y_expected = (w as usize) * (h as usize);
2373        let uv_w = w.div_ceil(2);
2374        let uv_h = h.div_ceil(2);
2375        let uv_expected = (uv_w as usize) * (uv_h as usize) * 2;
2376
2377        if y.len() < y_expected {
2378            return Err(anyhow::anyhow!("Y plane too small"));
2379        }
2380        if uv.len() < uv_expected {
2381            return Err(anyhow::anyhow!("UV plane too small"));
2382        }
2383
2384        let needs_recreate = match self.images.get(&handle) {
2385            Some(ImageTex::Nv12 { w: ww, h: hh, .. }) => *ww != w || *hh != h,
2386            _ => true,
2387        };
2388
2389        // Compute the YUV->RGB transform on the CPU.
2390        let yuv = color_info.to_yuv_transform();
2391        let yuv_raw = YuvTransformRaw {
2392            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2393            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2394            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2395            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
2396        };
2397
2398        if needs_recreate {
2399            self.remove_image(handle);
2400
2401            let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
2402                label: Some("nv12 Y"),
2403                size: wgpu::Extent3d {
2404                    width: w,
2405                    height: h,
2406                    depth_or_array_layers: 1,
2407                },
2408                mip_level_count: 1,
2409                sample_count: 1,
2410                dimension: wgpu::TextureDimension::D2,
2411                format: wgpu::TextureFormat::R8Unorm,
2412                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2413                view_formats: &[],
2414            });
2415            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
2416
2417            let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
2418                label: Some("nv12 UV"),
2419                size: wgpu::Extent3d {
2420                    width: uv_w,
2421                    height: uv_h,
2422                    depth_or_array_layers: 1,
2423                },
2424                mip_level_count: 1,
2425                sample_count: 1,
2426                dimension: wgpu::TextureDimension::D2,
2427                format: wgpu::TextureFormat::Rg8Unorm,
2428                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2429                view_formats: &[],
2430            });
2431            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
2432
2433            // Create a uniform buffer for the YUV transform (per-image).
2434            let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
2435                label: Some("nv12 yuv transform"),
2436                size: std::mem::size_of::<YuvTransformRaw>() as u64,
2437                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2438                mapped_at_creation: false,
2439            });
2440
2441            // Write initial transform.
2442            self.queue
2443                .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2444
2445            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2446                label: Some("nv12 bind"),
2447                layout: &self.image_bind_layout_nv12,
2448                entries: &[
2449                    wgpu::BindGroupEntry {
2450                        binding: 0,
2451                        resource: wgpu::BindingResource::TextureView(&view_y),
2452                    },
2453                    wgpu::BindGroupEntry {
2454                        binding: 1,
2455                        resource: wgpu::BindingResource::TextureView(&view_uv),
2456                    },
2457                    wgpu::BindGroupEntry {
2458                        binding: 2,
2459                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2460                    },
2461                    wgpu::BindGroupEntry {
2462                        binding: 3,
2463                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
2464                            buffer: &yuv_buf,
2465                            offset: 0,
2466                            size: None,
2467                        }),
2468                    },
2469                ],
2470            });
2471
2472            let bytes = (w as u64) * (h as u64)
2473                + (uv_w as u64) * (uv_h as u64) * 2
2474                + std::mem::size_of::<YuvTransformRaw>() as u64;
2475            self.image_bytes_total += bytes;
2476
2477            self.images.insert(
2478                handle,
2479                ImageTex::Nv12 {
2480                    tex_y,
2481                    tex_uv,
2482                    bind,
2483                    yuv_buf,
2484                    w,
2485                    h,
2486                    color_info,
2487                    last_used_frame: self.frame_index,
2488                    bytes,
2489                },
2490            );
2491        } else {
2492            // Re-use existing textures; just update the YUV transform if needed.
2493            if let Some(ImageTex::Nv12 { yuv_buf, .. }) = self.images.get(&handle) {
2494                self.queue
2495                    .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2496            }
2497        }
2498
2499        let (tex_y, tex_uv, _bind) = match self.images.get(&handle) {
2500            Some(ImageTex::Nv12 {
2501                tex_y,
2502                tex_uv,
2503                bind,
2504                ..
2505            }) => (tex_y, tex_uv, bind),
2506            _ => return Err(anyhow::anyhow!("Handle is not NV12")),
2507        };
2508
2509        self.queue.write_texture(
2510            wgpu::TexelCopyTextureInfo {
2511                texture: tex_y,
2512                mip_level: 0,
2513                origin: wgpu::Origin3d::ZERO,
2514                aspect: wgpu::TextureAspect::All,
2515            },
2516            &y[..y_expected],
2517            wgpu::TexelCopyBufferLayout {
2518                offset: 0,
2519                bytes_per_row: Some(w),
2520                rows_per_image: Some(h),
2521            },
2522            wgpu::Extent3d {
2523                width: w,
2524                height: h,
2525                depth_or_array_layers: 1,
2526            },
2527        );
2528
2529        self.queue.write_texture(
2530            wgpu::TexelCopyTextureInfo {
2531                texture: tex_uv,
2532                mip_level: 0,
2533                origin: wgpu::Origin3d::ZERO,
2534                aspect: wgpu::TextureAspect::All,
2535            },
2536            &uv[..uv_expected],
2537            wgpu::TexelCopyBufferLayout {
2538                offset: 0,
2539                bytes_per_row: Some(2 * uv_w),
2540                rows_per_image: Some(uv_h),
2541            },
2542            wgpu::Extent3d {
2543                width: uv_w,
2544                height: uv_h,
2545                depth_or_array_layers: 1,
2546            },
2547        );
2548
2549        self.evict_budget_excess();
2550        Ok(())
2551    }
2552
2553    pub fn set_image_planes(
2554        &mut self,
2555        handle: u64,
2556        w: u32,
2557        h: u32,
2558        pixel_format: PixelFormat,
2559        planes: &[&[u8]],
2560        color_info: ColorInfo,
2561    ) -> anyhow::Result<()> {
2562        match pixel_format {
2563            PixelFormat::Nv12 => {
2564                let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
2565                let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
2566                self.set_image_nv12(handle, w, h, y, uv, color_info)
2567            }
2568            PixelFormat::P010 => {
2569                let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
2570                let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
2571                self.set_image_p010(handle, w, h, y, uv, color_info)
2572            }
2573            PixelFormat::I420 | PixelFormat::I444 => Err(anyhow::anyhow!(
2574                "I420/I444 not implemented and unlikely -> cheap to convert to NV12 (better for the GPU too)"
2575            )),
2576            PixelFormat::Rgba => {
2577                let rgba = planes
2578                    .first()
2579                    .ok_or(anyhow::anyhow!("missing RGBA plane"))?;
2580                self.set_image_rgba8(handle, w, h, rgba, false)
2581            }
2582        }
2583    }
2584
2585    fn set_image_p010(
2586        &mut self,
2587        handle: u64,
2588        w: u32,
2589        h: u32,
2590        y: &[u8],
2591        uv: &[u8],
2592        color_info: ColorInfo,
2593    ) -> anyhow::Result<()> {
2594        let uv_w = w.div_ceil(2);
2595        let uv_h = h.div_ceil(2);
2596
2597        let y_expected = (w as usize) * 2;
2598        let uv_expected = (uv_w as usize) * (uv_h as usize) * 4;
2599
2600        if y.len() < y_expected {
2601            return Err(anyhow::anyhow!("P010 Y plane too small"));
2602        }
2603        if uv.len() < uv_expected {
2604            return Err(anyhow::anyhow!("P010 UV plane too small"));
2605        }
2606
2607        // P010 reuses the NV12 pipeline (same bind group layout -> wgpu
2608        // abstracts the storage format so R16Unorm/Rg16Unorm are
2609        // filterable float textures just like R8Unorm/Rg8Unorm).
2610        let needs_recreate = match self.images.get(&handle) {
2611            Some(ImageTex::Nv12 { w: ww, h: hh, .. }) => *ww != w || *hh != h,
2612            _ => true,
2613        };
2614
2615        let yuv = color_info.to_yuv_transform();
2616        let yuv_raw = YuvTransformRaw {
2617            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2618            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2619            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2620            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
2621        };
2622
2623        if needs_recreate {
2624            self.remove_image(handle);
2625
2626            let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
2627                label: Some("p010 Y"),
2628                size: wgpu::Extent3d {
2629                    width: w,
2630                    height: h,
2631                    depth_or_array_layers: 1,
2632                },
2633                mip_level_count: 1,
2634                sample_count: 1,
2635                dimension: wgpu::TextureDimension::D2,
2636                format: wgpu::TextureFormat::R16Unorm,
2637                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2638                view_formats: &[],
2639            });
2640            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
2641
2642            let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
2643                label: Some("p010 UV"),
2644                size: wgpu::Extent3d {
2645                    width: uv_w,
2646                    height: uv_h,
2647                    depth_or_array_layers: 1,
2648                },
2649                mip_level_count: 1,
2650                sample_count: 1,
2651                dimension: wgpu::TextureDimension::D2,
2652                format: wgpu::TextureFormat::Rg16Unorm,
2653                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2654                view_formats: &[],
2655            });
2656            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
2657
2658            let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
2659                label: Some("p010 yuv transform"),
2660                size: std::mem::size_of::<YuvTransformRaw>() as u64,
2661                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2662                mapped_at_creation: false,
2663            });
2664            self.queue
2665                .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2666
2667            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2668                label: Some("p010 bind"),
2669                layout: &self.image_bind_layout_nv12,
2670                entries: &[
2671                    wgpu::BindGroupEntry {
2672                        binding: 0,
2673                        resource: wgpu::BindingResource::TextureView(&view_y),
2674                    },
2675                    wgpu::BindGroupEntry {
2676                        binding: 1,
2677                        resource: wgpu::BindingResource::TextureView(&view_uv),
2678                    },
2679                    wgpu::BindGroupEntry {
2680                        binding: 2,
2681                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2682                    },
2683                    wgpu::BindGroupEntry {
2684                        binding: 3,
2685                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
2686                            buffer: &yuv_buf,
2687                            offset: 0,
2688                            size: None,
2689                        }),
2690                    },
2691                ],
2692            });
2693
2694            let bytes = (w as u64) * 2
2695                + (uv_w as u64) * (uv_h as u64) * 4
2696                + std::mem::size_of::<YuvTransformRaw>() as u64;
2697            self.image_bytes_total += bytes;
2698
2699            self.images.insert(
2700                handle,
2701                ImageTex::Nv12 {
2702                    tex_y,
2703                    tex_uv,
2704                    bind,
2705                    yuv_buf,
2706                    w,
2707                    h,
2708                    color_info,
2709                    last_used_frame: self.frame_index,
2710                    bytes,
2711                },
2712            );
2713        } else {
2714            if let Some(ImageTex::Nv12 { yuv_buf, .. }) = self.images.get(&handle) {
2715                self.queue
2716                    .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2717            }
2718        }
2719
2720        let (tex_y, tex_uv, _bind) = match self.images.get(&handle) {
2721            Some(ImageTex::Nv12 {
2722                tex_y,
2723                tex_uv,
2724                bind,
2725                ..
2726            }) => (tex_y, tex_uv, bind),
2727            _ => return Err(anyhow::anyhow!("Handle is not P010/NV12")),
2728        };
2729
2730        self.queue.write_texture(
2731            wgpu::TexelCopyTextureInfo {
2732                texture: tex_y,
2733                mip_level: 0,
2734                origin: wgpu::Origin3d::ZERO,
2735                aspect: wgpu::TextureAspect::All,
2736            },
2737            &y[..y_expected],
2738            wgpu::TexelCopyBufferLayout {
2739                offset: 0,
2740                bytes_per_row: Some(w * 2),
2741                rows_per_image: Some(h),
2742            },
2743            wgpu::Extent3d {
2744                width: w,
2745                height: h,
2746                depth_or_array_layers: 1,
2747            },
2748        );
2749        self.queue.write_texture(
2750            wgpu::TexelCopyTextureInfo {
2751                texture: tex_uv,
2752                mip_level: 0,
2753                origin: wgpu::Origin3d::ZERO,
2754                aspect: wgpu::TextureAspect::All,
2755            },
2756            &uv[..uv_expected],
2757            wgpu::TexelCopyBufferLayout {
2758                offset: 0,
2759                bytes_per_row: Some(uv_w * 4),
2760                rows_per_image: Some(uv_h),
2761            },
2762            wgpu::Extent3d {
2763                width: uv_w,
2764                height: uv_h,
2765                depth_or_array_layers: 1,
2766            },
2767        );
2768
2769        self.evict_budget_excess();
2770        Ok(())
2771    }
2772
2773    #[cfg(target_os = "linux")]
2774    pub fn set_image_dmabuf(
2775        &mut self,
2776        handle: u64,
2777        w: u32,
2778        h: u32,
2779        fds: Vec<std::os::unix::io::OwnedFd>,
2780        modifier: u64,
2781        strides: Vec<u32>,
2782        offsets: Vec<u64>,
2783        color_info: ColorInfo,
2784    ) -> anyhow::Result<()> {
2785        log::info!(
2786            "set_image_dmabuf handle={handle} {}x{} fds={} modifier=0x{modifier:x}",
2787            w,
2788            h,
2789            fds.len()
2790        );
2791
2792        self.remove_image(handle);
2793
2794        let yuv = color_info.to_yuv_transform();
2795        let yuv_raw = YuvTransformRaw {
2796            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2797            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2798            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2799            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
2800        };
2801
2802        if fds.len() != 2 {
2803            return Err(anyhow::anyhow!(
2804                "unsupported fd count {} - need exactly 2 for separate Y/UV planes",
2805                fds.len()
2806            ));
2807        }
2808
2809        let uv_w = w.div_ceil(2);
2810        let uv_h = h.div_ceil(2);
2811
2812        let hal_y_desc = wgpu::hal::TextureDescriptor {
2813            label: Some("dmabuf y"),
2814            size: wgpu::Extent3d {
2815                width: w,
2816                height: h,
2817                depth_or_array_layers: 1,
2818            },
2819            mip_level_count: 1,
2820            sample_count: 1,
2821            dimension: wgpu::TextureDimension::D2,
2822            format: wgpu::TextureFormat::R8Unorm,
2823            usage: wgpu::wgt::TextureUses::RESOURCE,
2824            memory_flags: wgpu::hal::MemoryFlags::empty(),
2825            view_formats: vec![],
2826        };
2827        let hal_uv_desc = wgpu::hal::TextureDescriptor {
2828            label: Some("dmabuf uv"),
2829            size: wgpu::Extent3d {
2830                width: uv_w,
2831                height: uv_h,
2832                depth_or_array_layers: 1,
2833            },
2834            mip_level_count: 1,
2835            sample_count: 1,
2836            dimension: wgpu::TextureDimension::D2,
2837            format: wgpu::TextureFormat::Rg8Unorm,
2838            usage: wgpu::wgt::TextureUses::RESOURCE,
2839            memory_flags: wgpu::hal::MemoryFlags::empty(),
2840            view_formats: vec![],
2841        };
2842
2843        let wgpu_y_desc = wgpu::TextureDescriptor {
2844            label: Some("dmabuf y"),
2845            size: wgpu::Extent3d {
2846                width: w,
2847                height: h,
2848                depth_or_array_layers: 1,
2849            },
2850            mip_level_count: 1,
2851            sample_count: 1,
2852            dimension: wgpu::TextureDimension::D2,
2853            format: wgpu::TextureFormat::R8Unorm,
2854            usage: wgpu::TextureUsages::TEXTURE_BINDING,
2855            view_formats: &[],
2856        };
2857        let wgpu_uv_desc = wgpu::TextureDescriptor {
2858            label: Some("dmabuf uv"),
2859            size: wgpu::Extent3d {
2860                width: uv_w,
2861                height: uv_h,
2862                depth_or_array_layers: 1,
2863            },
2864            mip_level_count: 1,
2865            sample_count: 1,
2866            dimension: wgpu::TextureDimension::D2,
2867            format: wgpu::TextureFormat::Rg8Unorm,
2868            usage: wgpu::TextureUsages::TEXTURE_BINDING,
2869            view_formats: &[],
2870        };
2871
2872        let (tex_y, view_y, tex_uv, view_uv) = unsafe {
2873            let hal_guard = self
2874                .device
2875                .as_hal::<wgpu::hal::vulkan::Api>()
2876                .ok_or_else(|| {
2877                    log::warn!("as_hal::<vulkan::Api> returned None");
2878                    anyhow::anyhow!("Device is not Vulkan")
2879                })?;
2880
2881            let mut fds = fds;
2882            let uv_fd = fds.remove(1);
2883            let y_fd = fds.remove(0);
2884
2885            let yt = hal_guard
2886                .texture_from_dmabuf_fd(y_fd, &hal_y_desc, modifier, strides[0] as u64, offsets[0])
2887                .map_err(|e| anyhow::anyhow!("import Y dmabuf: {e:?}"))?;
2888            log::info!("imported Y dmabuf OK");
2889
2890            let uvt = hal_guard
2891                .texture_from_dmabuf_fd(
2892                    uv_fd,
2893                    &hal_uv_desc,
2894                    modifier,
2895                    strides[1] as u64,
2896                    offsets[1],
2897                )
2898                .map_err(|e| anyhow::anyhow!("import UV dmabuf: {e:?}"))?;
2899            log::info!("imported UV dmabuf OK");
2900
2901            drop(hal_guard);
2902
2903            let tex_y = self
2904                .device
2905                .create_texture_from_hal::<wgpu::hal::vulkan::Api>(
2906                    yt,
2907                    &wgpu_y_desc,
2908                    wgpu::wgt::TextureUses::UNINITIALIZED,
2909                );
2910            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
2911
2912            let tex_uv = self
2913                .device
2914                .create_texture_from_hal::<wgpu::hal::vulkan::Api>(
2915                    uvt,
2916                    &wgpu_uv_desc,
2917                    wgpu::wgt::TextureUses::UNINITIALIZED,
2918                );
2919            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
2920
2921            (tex_y, view_y, tex_uv, view_uv)
2922        };
2923
2924        let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
2925            label: Some("dmabuf yuv transform"),
2926            size: std::mem::size_of::<YuvTransformRaw>() as u64,
2927            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2928            mapped_at_creation: false,
2929        });
2930        self.queue
2931            .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2932
2933        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2934            label: Some("dmabuf nv12 bind"),
2935            layout: &self.image_bind_layout_nv12,
2936            entries: &[
2937                wgpu::BindGroupEntry {
2938                    binding: 0,
2939                    resource: wgpu::BindingResource::TextureView(&view_y),
2940                },
2941                wgpu::BindGroupEntry {
2942                    binding: 1,
2943                    resource: wgpu::BindingResource::TextureView(&view_uv),
2944                },
2945                wgpu::BindGroupEntry {
2946                    binding: 2,
2947                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2948                },
2949                wgpu::BindGroupEntry {
2950                    binding: 3,
2951                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
2952                        buffer: &yuv_buf,
2953                        offset: 0,
2954                        size: None,
2955                    }),
2956                },
2957            ],
2958        });
2959
2960        let bytes = (w as u64) * (h as u64)
2961            + (uv_w as u64) * (uv_h as u64) * 2
2962            + std::mem::size_of::<YuvTransformRaw>() as u64;
2963
2964        self.images.insert(
2965            handle,
2966            ImageTex::Nv12 {
2967                tex_y,
2968                tex_uv,
2969                bind,
2970                yuv_buf,
2971                w,
2972                h,
2973                color_info,
2974                last_used_frame: self.frame_index,
2975                bytes,
2976            },
2977        );
2978
2979        self.evict_budget_excess();
2980        Ok(())
2981    }
2982
2983    pub fn remove_image(&mut self, handle: u64) {
2984        if let Some(img) = self.images.remove(&handle) {
2985            let b = match &img {
2986                ImageTex::Rgba { bytes, .. } => *bytes,
2987                ImageTex::Nv12 { bytes, .. } => *bytes,
2988            };
2989            self.image_bytes_total = self.image_bytes_total.saturating_sub(b);
2990        }
2991        self.retained.remove(&handle);
2992    }
2993
2994    fn evict_image_gpu(&mut self, handle: u64) -> u64 {
2995        let Some(img) = self.images.remove(&handle) else {
2996            return 0;
2997        };
2998        let b = match &img {
2999            ImageTex::Rgba { bytes, .. } => *bytes,
3000            ImageTex::Nv12 { bytes, .. } => *bytes,
3001        };
3002        self.image_bytes_total = self.image_bytes_total.saturating_sub(b);
3003        b
3004    }
3005
3006    fn revive_retained_image(&mut self, handle: u64) -> bool {
3007        if self.images.contains_key(&handle) {
3008            return true;
3009        }
3010        let Some(r) = self.retained.get(&handle).cloned() else {
3011            return false;
3012        };
3013        let (tex, bind) = self.create_rgba_tex(r.w, r.h, r.format);
3014
3015        self.queue.write_texture(
3016            wgpu::TexelCopyTextureInfo {
3017                texture: &tex,
3018                mip_level: 0,
3019                origin: wgpu::Origin3d::ZERO,
3020                aspect: wgpu::TextureAspect::All,
3021            },
3022            &r.rgba,
3023            wgpu::TexelCopyBufferLayout {
3024                offset: 0,
3025                bytes_per_row: Some(4 * r.w),
3026                rows_per_image: Some(r.h),
3027            },
3028            wgpu::Extent3d {
3029                width: r.w,
3030                height: r.h,
3031                depth_or_array_layers: 1,
3032            },
3033        );
3034
3035        let bytes = (r.w as u64) * (r.h as u64) * 4;
3036        self.image_bytes_total += bytes;
3037        self.images.insert(
3038            handle,
3039            ImageTex::Rgba {
3040                tex,
3041                bind,
3042                w: r.w,
3043                h: r.h,
3044                format: r.format,
3045                last_used_frame: self.frame_index,
3046                bytes,
3047            },
3048        );
3049        true
3050    }
3051
3052    fn resolve_image_for_draw(&mut self, handle: u64) -> Option<(u32, u32, bool)> {
3053        if let Some(t) = self.images.get_mut(&handle) {
3054            return match t {
3055                ImageTex::Rgba {
3056                    w,
3057                    h,
3058                    last_used_frame,
3059                    ..
3060                } => {
3061                    *last_used_frame = self.frame_index;
3062                    Some((*w, *h, false))
3063                }
3064                ImageTex::Nv12 {
3065                    w,
3066                    h,
3067                    last_used_frame,
3068                    ..
3069                } => {
3070                    *last_used_frame = self.frame_index;
3071                    Some((*w, *h, true))
3072                }
3073            };
3074        }
3075        if self.revive_retained_image(handle)
3076            && let Some(ImageTex::Rgba {
3077                w,
3078                h,
3079                last_used_frame,
3080                ..
3081            }) = self.images.get_mut(&handle)
3082        {
3083            *last_used_frame = self.frame_index;
3084            return Some((*w, *h, false));
3085        }
3086        None
3087    }
3088
3089    // Legacy support from Step 1 instructions (temporary until platform render logic is fully swapped)
3090    pub fn register_image_from_bytes(&mut self, data: &[u8], srgb: bool) -> u64 {
3091        let handle = self.next_image_handle;
3092        self.next_image_handle += 1;
3093        if let Err(e) = self.set_image_from_bytes(handle, data, srgb) {
3094            log::error!("Failed to register image: {e}");
3095        }
3096        handle
3097    }
3098
3099    fn evict_unused_images(&mut self) {
3100        let now = self.frame_index;
3101        let evict_after = self.image_evict_after_frames;
3102
3103        // Time based eviction. Eviction only frees GPU memory: retained RGBA
3104        // sources stay so the image can be lazily re-uploaded when drawn again.
3105        let mut to_evict = Vec::new();
3106        for (h, t) in self.images.iter() {
3107            let last = match t {
3108                ImageTex::Rgba {
3109                    last_used_frame, ..
3110                } => *last_used_frame,
3111                ImageTex::Nv12 {
3112                    last_used_frame, ..
3113                } => *last_used_frame,
3114            };
3115            if now.saturating_sub(last) > evict_after {
3116                to_evict.push(*h);
3117            }
3118        }
3119        for h in to_evict {
3120            if self.retained.contains_key(&h) {
3121                self.evict_image_gpu(h);
3122            } else {
3123                self.remove_image(h);
3124            }
3125        }
3126
3127        self.evict_budget_excess();
3128    }
3129
3130    fn evict_budget_excess(&mut self) {
3131        if self.image_bytes_total <= self.image_budget_bytes {
3132            return;
3133        }
3134        // Collect (handle, last_used, bytes)
3135        let mut candidates: Vec<(u64, u64, u64)> = self
3136            .images
3137            .iter()
3138            .map(|(h, t)| {
3139                let (last, bytes) = match t {
3140                    ImageTex::Rgba {
3141                        last_used_frame,
3142                        bytes,
3143                        ..
3144                    } => (*last_used_frame, *bytes),
3145                    ImageTex::Nv12 {
3146                        last_used_frame,
3147                        bytes,
3148                        ..
3149                    } => (*last_used_frame, *bytes),
3150                };
3151                (*h, last, bytes)
3152            })
3153            .collect();
3154
3155        // Sort by last_used ascending (LRU first)
3156        candidates.sort_by_key(|k| k.1);
3157
3158        let now = self.frame_index;
3159        for (h, last, _bytes) in candidates {
3160            if self.image_bytes_total <= self.image_budget_bytes {
3161                break;
3162            }
3163            // Don't evict something used this frame
3164            if last == now {
3165                continue;
3166            }
3167            if self.retained.contains_key(&h) {
3168                self.evict_image_gpu(h);
3169            } else {
3170                self.remove_image(h);
3171            }
3172        }
3173    }
3174
3175    /// Enable or disable linear working-space rendering.
3176    /// When enabled, the scene is rendered into an Rgba16Float intermediate
3177    /// and a final full-screen pass applies the display OETF.
3178    pub fn set_working_space(&mut self, enabled: bool) {
3179        if enabled == self.working_space {
3180            return;
3181        }
3182        self.working_space = enabled;
3183        if enabled {
3184            self.ensure_display_pipeline();
3185            self.recreate_working_space_texture();
3186        } else {
3187            self.ws_tex = None;
3188            self.ws_view = None;
3189            self.ws_bind = None;
3190        }
3191    }
3192
3193    fn ensure_display_pipeline(&mut self) {
3194        if self.display_pipeline.is_some() {
3195            return;
3196        }
3197
3198        let layout = self
3199            .device
3200            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3201                label: Some("display transform layout"),
3202                entries: &[
3203                    wgpu::BindGroupLayoutEntry {
3204                        binding: 0,
3205                        visibility: wgpu::ShaderStages::FRAGMENT,
3206                        ty: wgpu::BindingType::Texture {
3207                            multisampled: false,
3208                            view_dimension: wgpu::TextureViewDimension::D2,
3209                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
3210                        },
3211                        count: None,
3212                    },
3213                    wgpu::BindGroupLayoutEntry {
3214                        binding: 1,
3215                        visibility: wgpu::ShaderStages::FRAGMENT,
3216                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3217                        count: None,
3218                    },
3219                ],
3220            });
3221        self.display_layout = Some(layout);
3222
3223        let shader = self
3224            .device
3225            .create_shader_module(wgpu::ShaderModuleDescriptor {
3226                label: Some("display_transform.wgsl"),
3227                source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
3228                    "shaders/display_transform.wgsl"
3229                ))),
3230            });
3231
3232        let pipeline_layout = self
3233            .device
3234            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
3235                label: Some("display transform pipeline layout"),
3236                bind_group_layouts: &[None, self.display_layout.as_ref()],
3237                immediate_size: 0,
3238            });
3239
3240        let pipeline = self
3241            .device
3242            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
3243                label: Some("display transform pipeline"),
3244                layout: Some(&pipeline_layout),
3245                vertex: wgpu::VertexState {
3246                    module: &shader,
3247                    entry_point: Some("vs_main"),
3248                    buffers: &[],
3249                    compilation_options: wgpu::PipelineCompilationOptions::default(),
3250                },
3251                fragment: Some(wgpu::FragmentState {
3252                    module: &shader,
3253                    entry_point: Some("fs_main"),
3254                    targets: &[Some(wgpu::ColorTargetState {
3255                        format: self.output_format,
3256                        blend: None,
3257                        write_mask: wgpu::ColorWrites::ALL,
3258                    })],
3259                    compilation_options: wgpu::PipelineCompilationOptions::default(),
3260                }),
3261                primitive: wgpu::PrimitiveState::default(),
3262                depth_stencil: None,
3263                multisample: wgpu::MultisampleState::default(),
3264                multiview_mask: None,
3265                cache: None,
3266            });
3267        self.display_pipeline = Some(pipeline);
3268    }
3269
3270    /// Resize the render target dimensions.
3271    ///
3272    /// Recreates MSAA, depth-stencil, and working-space textures to match the
3273    /// new size..
3274    pub fn resize(&mut self, width: u32, height: u32) {
3275        self.output_width = width;
3276        self.output_height = height;
3277        self.recreate_msaa_and_depth_stencil();
3278        self.recreate_working_space_texture();
3279    }
3280
3281    fn recreate_working_space_texture(&mut self) {
3282        if !self.working_space {
3283            return;
3284        }
3285        let w = self.output_width.max(1);
3286        let h = self.output_height.max(1);
3287
3288        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3289            label: Some("working space"),
3290            size: wgpu::Extent3d {
3291                width: w,
3292                height: h,
3293                depth_or_array_layers: 1,
3294            },
3295            mip_level_count: 1,
3296            sample_count: 1,
3297            dimension: wgpu::TextureDimension::D2,
3298            format: wgpu::TextureFormat::Rgba16Float,
3299            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
3300            view_formats: &[],
3301        });
3302        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3303
3304        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3305            label: Some("working space bind"),
3306            layout: self.display_layout.as_ref().unwrap(),
3307            entries: &[
3308                wgpu::BindGroupEntry {
3309                    binding: 0,
3310                    resource: wgpu::BindingResource::TextureView(&view),
3311                },
3312                wgpu::BindGroupEntry {
3313                    binding: 1,
3314                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
3315                },
3316            ],
3317        });
3318
3319        self.ws_tex = Some(tex);
3320        self.ws_view = Some(view);
3321        self.ws_bind = Some(bind);
3322    }
3323
3324    fn recreate_msaa_and_depth_stencil(&mut self) {
3325        if self.msaa_samples > 1 {
3326            let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3327                label: Some("msaa color"),
3328                size: wgpu::Extent3d {
3329                    width: self.output_width.max(1),
3330                    height: self.output_height.max(1),
3331                    depth_or_array_layers: 1,
3332                },
3333                mip_level_count: 1,
3334                sample_count: self.msaa_samples,
3335                dimension: wgpu::TextureDimension::D2,
3336                format: self.output_format,
3337                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
3338                view_formats: &[],
3339            });
3340            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3341            self.msaa_tex = Some(tex);
3342            self.msaa_view = Some(view);
3343        } else {
3344            self.msaa_tex = None;
3345            self.msaa_view = None;
3346        }
3347
3348        self.depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
3349            label: Some("depth-stencil (stencil clips)"),
3350            size: wgpu::Extent3d {
3351                width: self.output_width.max(1),
3352                height: self.output_height.max(1),
3353                depth_or_array_layers: 1,
3354            },
3355            mip_level_count: 1,
3356            sample_count: self.msaa_samples,
3357            dimension: wgpu::TextureDimension::D2,
3358            format: wgpu::TextureFormat::Depth24PlusStencil8,
3359            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
3360            view_formats: &[],
3361        });
3362        self.depth_stencil_view = self
3363            .depth_stencil_tex
3364            .create_view(&wgpu::TextureViewDescriptor::default());
3365    }
3366
3367    fn get_or_create_layer(
3368        &mut self,
3369        layer_id: u32,
3370        width: u32,
3371        height: u32,
3372        rect: repose_core::Rect,
3373    ) {
3374        let needs_alloc = match self.layer_pool.get(&layer_id) {
3375            Some(lt) => lt.width != width || lt.height != height,
3376            None => true,
3377        };
3378        if !needs_alloc {
3379            if let Some(lt) = self.layer_pool.get_mut(&layer_id) {
3380                lt.rect_px = (rect.x, rect.y, rect.w, rect.h);
3381            }
3382            return;
3383        }
3384        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3385            label: Some("graphics layer"),
3386            size: wgpu::Extent3d {
3387                width: width.max(1),
3388                height: height.max(1),
3389                depth_or_array_layers: 1,
3390            },
3391            mip_level_count: 1,
3392            sample_count: 1,
3393            dimension: wgpu::TextureDimension::D2,
3394            format: self.output_format,
3395            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
3396            view_formats: &[],
3397        });
3398        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3399        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3400            label: Some("layer bind"),
3401            layout: &self.image_bind_layout_rgba,
3402            entries: &[
3403                wgpu::BindGroupEntry {
3404                    binding: 0,
3405                    resource: wgpu::BindingResource::TextureView(&view),
3406                },
3407                wgpu::BindGroupEntry {
3408                    binding: 1,
3409                    resource: wgpu::BindingResource::Sampler(&self.layer_sampler),
3410                },
3411            ],
3412        });
3413        let bind_linear = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3414            label: Some("layer bind linear"),
3415            layout: &self.image_bind_layout_rgba,
3416            entries: &[
3417                wgpu::BindGroupEntry {
3418                    binding: 0,
3419                    resource: wgpu::BindingResource::TextureView(&view),
3420                },
3421                wgpu::BindGroupEntry {
3422                    binding: 1,
3423                    resource: wgpu::BindingResource::Sampler(&self.layer_sampler_linear),
3424                },
3425            ],
3426        });
3427        let depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
3428            label: Some("graphics layer depth-stencil"),
3429            size: wgpu::Extent3d {
3430                width: width.max(1),
3431                height: height.max(1),
3432                depth_or_array_layers: 1,
3433            },
3434            mip_level_count: 1,
3435            sample_count: 1,
3436            dimension: wgpu::TextureDimension::D2,
3437            format: wgpu::TextureFormat::Depth24PlusStencil8,
3438            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
3439            view_formats: &[],
3440        });
3441        let depth_stencil_view =
3442            depth_stencil_tex.create_view(&wgpu::TextureViewDescriptor::default());
3443        self.layer_pool.insert(
3444            layer_id,
3445            LayerTarget {
3446                view,
3447                bind,
3448                bind_linear,
3449                depth_stencil_view,
3450                width,
3451                height,
3452                rect_px: (rect.x, rect.y, rect.w, rect.h),
3453            },
3454        );
3455    }
3456
3457    fn atlas_bind_group_mask(&self) -> wgpu::BindGroup {
3458        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3459            label: Some("atlas bind"),
3460            layout: &self.text_bind_layout,
3461            entries: &[
3462                wgpu::BindGroupEntry {
3463                    binding: 0,
3464                    resource: wgpu::BindingResource::TextureView(&self.atlas_mask.view),
3465                },
3466                wgpu::BindGroupEntry {
3467                    binding: 1,
3468                    resource: wgpu::BindingResource::Sampler(&self.atlas_mask.sampler),
3469                },
3470            ],
3471        })
3472    }
3473
3474    fn atlas_bind_group_color(&self) -> wgpu::BindGroup {
3475        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3476            label: Some("atlas bind color"),
3477            layout: &self.text_bind_layout,
3478            entries: &[
3479                wgpu::BindGroupEntry {
3480                    binding: 0,
3481                    resource: wgpu::BindingResource::TextureView(&self.atlas_color.view),
3482                },
3483                wgpu::BindGroupEntry {
3484                    binding: 1,
3485                    resource: wgpu::BindingResource::Sampler(&self.atlas_color.sampler),
3486                },
3487            ],
3488        })
3489    }
3490
3491    fn upload_glyph_mask(&mut self, key: repose_text::GlyphKey, px: f32) -> Option<GlyphInfo> {
3492        let keyp = (key, px.to_bits());
3493        if let Some(info) = self.atlas_mask.map.get(&keyp) {
3494            return Some(*info);
3495        }
3496
3497        let gb = repose_text::rasterize(key, px)?;
3498        if gb.w == 0 || gb.h == 0 || gb.data.is_empty() {
3499            return None;
3500        }
3501
3502        let coverage = swash_to_a8_coverage(gb.content, &gb.data)?;
3503
3504        let w = gb.w.max(1);
3505        let h = gb.h.max(1);
3506
3507        if !self.alloc_space_mask(w, h) {
3508            self.grow_mask_and_rebuild();
3509        }
3510        if !self.alloc_space_mask(w, h) {
3511            return None;
3512        }
3513        let x = self.atlas_mask.next_x;
3514        let y = self.atlas_mask.next_y;
3515        self.atlas_mask.next_x += w + 1;
3516        self.atlas_mask.row_h = self.atlas_mask.row_h.max(h + 1);
3517
3518        let layout = wgpu::TexelCopyBufferLayout {
3519            offset: 0,
3520            bytes_per_row: Some(w),
3521            rows_per_image: Some(h),
3522        };
3523        let size = wgpu::Extent3d {
3524            width: w,
3525            height: h,
3526            depth_or_array_layers: 1,
3527        };
3528        self.queue.write_texture(
3529            wgpu::TexelCopyTextureInfoBase {
3530                texture: &self.atlas_mask.tex,
3531                mip_level: 0,
3532                origin: wgpu::Origin3d { x, y, z: 0 },
3533                aspect: wgpu::TextureAspect::All,
3534            },
3535            &coverage,
3536            layout,
3537            size,
3538        );
3539
3540        let info = GlyphInfo {
3541            u0: x as f32 / self.atlas_mask.size as f32,
3542            v0: y as f32 / self.atlas_mask.size as f32,
3543            u1: (x + w) as f32 / self.atlas_mask.size as f32,
3544            v1: (y + h) as f32 / self.atlas_mask.size as f32,
3545            w: w as f32,
3546            h: h as f32,
3547        };
3548        self.atlas_mask.map.insert(keyp, info);
3549        Some(info)
3550    }
3551
3552    fn upload_glyph_color(&mut self, key: repose_text::GlyphKey, px: f32) -> Option<GlyphInfo> {
3553        let keyp = (key, px.to_bits());
3554        if let Some(info) = self.atlas_color.map.get(&keyp) {
3555            return Some(*info);
3556        }
3557        let gb = repose_text::rasterize(key, px)?;
3558        if !matches!(gb.content, repose_text::SwashContent::Color) {
3559            return None;
3560        }
3561        let w = gb.w.max(1);
3562        let h = gb.h.max(1);
3563        if !self.alloc_space_color(w, h) {
3564            self.grow_color_and_rebuild();
3565        }
3566        if !self.alloc_space_color(w, h) {
3567            return None;
3568        }
3569        let x = self.atlas_color.next_x;
3570        let y = self.atlas_color.next_y;
3571        self.atlas_color.next_x += w + 1;
3572        self.atlas_color.row_h = self.atlas_color.row_h.max(h + 1);
3573
3574        let layout = wgpu::TexelCopyBufferLayout {
3575            offset: 0,
3576            bytes_per_row: Some(w * 4),
3577            rows_per_image: Some(h),
3578        };
3579        let size = wgpu::Extent3d {
3580            width: w,
3581            height: h,
3582            depth_or_array_layers: 1,
3583        };
3584        self.queue.write_texture(
3585            wgpu::TexelCopyTextureInfoBase {
3586                texture: &self.atlas_color.tex,
3587                mip_level: 0,
3588                origin: wgpu::Origin3d { x, y, z: 0 },
3589                aspect: wgpu::TextureAspect::All,
3590            },
3591            &gb.data,
3592            layout,
3593            size,
3594        );
3595        let info = GlyphInfo {
3596            u0: x as f32 / self.atlas_color.size as f32,
3597            v0: y as f32 / self.atlas_color.size as f32,
3598            u1: (x + w) as f32 / self.atlas_color.size as f32,
3599            v1: (y + h) as f32 / self.atlas_color.size as f32,
3600            w: w as f32,
3601            h: h as f32,
3602        };
3603        self.atlas_color.map.insert(keyp, info);
3604        Some(info)
3605    }
3606
3607    fn alloc_space_mask(&mut self, w: u32, h: u32) -> bool {
3608        if self.atlas_mask.next_x + w + 1 >= self.atlas_mask.size {
3609            self.atlas_mask.next_x = 1;
3610            self.atlas_mask.next_y += self.atlas_mask.row_h + 1;
3611            self.atlas_mask.row_h = 0;
3612        }
3613        if self.atlas_mask.next_y + h + 1 >= self.atlas_mask.size {
3614            return false;
3615        }
3616        true
3617    }
3618
3619    fn grow_mask_and_rebuild(&mut self) {
3620        let new_size = (self.atlas_mask.size * 2).min(4096);
3621        if new_size == self.atlas_mask.size {
3622            return;
3623        }
3624        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3625            label: Some("glyph atlas A8 (grown)"),
3626            size: wgpu::Extent3d {
3627                width: new_size,
3628                height: new_size,
3629                depth_or_array_layers: 1,
3630            },
3631            mip_level_count: 1,
3632            sample_count: 1,
3633            dimension: wgpu::TextureDimension::D2,
3634            format: wgpu::TextureFormat::R8Unorm,
3635            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3636            view_formats: &[],
3637        });
3638        self.atlas_mask.tex = tex;
3639        self.atlas_mask.view = self
3640            .atlas_mask
3641            .tex
3642            .create_view(&wgpu::TextureViewDescriptor::default());
3643        self.atlas_mask.size = new_size;
3644        self.atlas_mask.next_x = 1;
3645        self.atlas_mask.next_y = 1;
3646        self.atlas_mask.row_h = 0;
3647        let keys: Vec<(repose_text::GlyphKey, u32)> = self.atlas_mask.map.keys().copied().collect();
3648        self.atlas_mask.map.clear();
3649        for (k, px_bits) in keys {
3650            let _ = self.upload_glyph_mask(k, f32::from_bits(px_bits));
3651        }
3652    }
3653
3654    fn alloc_space_color(&mut self, w: u32, h: u32) -> bool {
3655        if self.atlas_color.next_x + w + 1 >= self.atlas_color.size {
3656            self.atlas_color.next_x = 1;
3657            self.atlas_color.next_y += self.atlas_color.row_h + 1;
3658            self.atlas_color.row_h = 0;
3659        }
3660        if self.atlas_color.next_y + h + 1 >= self.atlas_color.size {
3661            return false;
3662        }
3663        true
3664    }
3665
3666    fn grow_color_and_rebuild(&mut self) {
3667        let new_size = (self.atlas_color.size * 2).min(4096);
3668        if new_size == self.atlas_color.size {
3669            return;
3670        }
3671        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3672            label: Some("glyph atlas RGBA (grown)"),
3673            size: wgpu::Extent3d {
3674                width: new_size,
3675                height: new_size,
3676                depth_or_array_layers: 1,
3677            },
3678            mip_level_count: 1,
3679            sample_count: 1,
3680            dimension: wgpu::TextureDimension::D2,
3681            format: wgpu::TextureFormat::Rgba8UnormSrgb,
3682            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3683            view_formats: &[],
3684        });
3685        self.atlas_color.tex = tex;
3686        self.atlas_color.view = self
3687            .atlas_color
3688            .tex
3689            .create_view(&wgpu::TextureViewDescriptor::default());
3690        self.atlas_color.size = new_size;
3691        self.atlas_color.next_x = 1;
3692        self.atlas_color.next_y = 1;
3693        self.atlas_color.row_h = 0;
3694        let keys: Vec<(repose_text::GlyphKey, u32)> =
3695            self.atlas_color.map.keys().copied().collect();
3696        self.atlas_color.map.clear();
3697        for (k, px_bits) in keys {
3698            let _ = self.upload_glyph_color(k, f32::from_bits(px_bits));
3699        }
3700    }
3701}
3702
3703fn brush_to_instance_fields(brush: &Brush) -> (u32, [f32; 4], [f32; 4], [f32; 2], [f32; 2]) {
3704    match brush {
3705        Brush::Solid(c) => (
3706            0u32,
3707            c.to_linear(),
3708            [0.0, 0.0, 0.0, 0.0],
3709            [0.0, 0.0],
3710            [0.0, 1.0],
3711        ),
3712        Brush::Linear {
3713            start,
3714            end,
3715            start_color,
3716            end_color,
3717        } => (
3718            1u32,
3719            start_color.to_linear(),
3720            end_color.to_linear(),
3721            [start.x, start.y],
3722            [end.x, end.y],
3723        ),
3724        _ => (0u32, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2]),
3725    }
3726}
3727
3728fn brush_to_solid_color(brush: &Brush) -> [f32; 4] {
3729    match brush {
3730        Brush::Solid(c) => c.to_linear(),
3731        Brush::Linear { start_color, .. } => start_color.to_linear(),
3732        _ => [0.0; 4],
3733    }
3734}
3735
3736fn init_atlas_mask(device: &wgpu::Device) -> AtlasA8 {
3737    let size = 1024u32;
3738    let tex = device.create_texture(&wgpu::TextureDescriptor {
3739        label: Some("glyph atlas A8"),
3740        size: wgpu::Extent3d {
3741            width: size,
3742            height: size,
3743            depth_or_array_layers: 1,
3744        },
3745        mip_level_count: 1,
3746        sample_count: 1,
3747        dimension: wgpu::TextureDimension::D2,
3748        format: wgpu::TextureFormat::R8Unorm,
3749        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3750        view_formats: &[],
3751    });
3752    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3753    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
3754        label: Some("glyph atlas sampler A8"),
3755        address_mode_u: wgpu::AddressMode::ClampToEdge,
3756        address_mode_v: wgpu::AddressMode::ClampToEdge,
3757        address_mode_w: wgpu::AddressMode::ClampToEdge,
3758        mag_filter: wgpu::FilterMode::Linear,
3759        min_filter: wgpu::FilterMode::Linear,
3760        mipmap_filter: wgpu::MipmapFilterMode::Linear,
3761        ..Default::default()
3762    });
3763
3764    AtlasA8 {
3765        tex,
3766        view,
3767        sampler,
3768        size,
3769        next_x: 1,
3770        next_y: 1,
3771        row_h: 0,
3772        map: HashMap::new(),
3773    }
3774}
3775
3776fn init_atlas_color(device: &wgpu::Device) -> AtlasRGBA {
3777    let size = 1024u32;
3778    let tex = device.create_texture(&wgpu::TextureDescriptor {
3779        label: Some("glyph atlas RGBA"),
3780        size: wgpu::Extent3d {
3781            width: size,
3782            height: size,
3783            depth_or_array_layers: 1,
3784        },
3785        mip_level_count: 1,
3786        sample_count: 1,
3787        dimension: wgpu::TextureDimension::D2,
3788        format: wgpu::TextureFormat::Rgba8UnormSrgb,
3789        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3790        view_formats: &[],
3791    });
3792    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3793    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
3794        label: Some("glyph atlas sampler RGBA"),
3795        address_mode_u: wgpu::AddressMode::ClampToEdge,
3796        address_mode_v: wgpu::AddressMode::ClampToEdge,
3797        address_mode_w: wgpu::AddressMode::ClampToEdge,
3798        mag_filter: wgpu::FilterMode::Linear,
3799        min_filter: wgpu::FilterMode::Linear,
3800        mipmap_filter: wgpu::MipmapFilterMode::Linear,
3801        ..Default::default()
3802    });
3803    AtlasRGBA {
3804        tex,
3805        view,
3806        sampler,
3807        size,
3808        next_x: 1,
3809        next_y: 1,
3810        row_h: 0,
3811        map: HashMap::new(),
3812    }
3813}
3814
3815#[cfg(feature = "winit-surface")]
3816impl RenderBackend for WgpuSurfaceBackend {
3817    fn configure_surface(&mut self, width: u32, height: u32) {
3818        if width == 0 || height == 0 {
3819            return;
3820        }
3821        self.renderer.output_width = width;
3822        self.renderer.output_height = height;
3823        if let Some(ref mut config) = self.surface_config {
3824            config.width = width;
3825            config.height = height;
3826        }
3827        if let (Some(surface), Some(config)) = (self.surface.as_ref(), self.surface_config.as_ref())
3828        {
3829            surface.configure(&self.renderer.device, config);
3830        }
3831        self.renderer.recreate_msaa_and_depth_stencil();
3832        self.renderer.recreate_working_space_texture();
3833    }
3834
3835    fn frame(&mut self, scene: &Scene, _glyph_cfg: GlyphRasterConfig) {
3836        let surface = self.surface.as_ref().expect("WgpuSurfaceBackend::frame() requires a surface (use from_device + render_to_view instead)");
3837        let surface_config = self
3838            .surface_config
3839            .as_ref()
3840            .expect("surface_config required for frame()");
3841
3842        self.renderer.frame_index = self.renderer.frame_index.wrapping_add(1);
3843        self.renderer.slug_cache.next_frame();
3844
3845        if self.renderer.output_width == 0 || self.renderer.output_height == 0 {
3846            return;
3847        }
3848
3849        let mut retries = 0u32;
3850        const MAX_RETRIES: u32 = 4;
3851        let frame = loop {
3852            match surface.get_current_texture() {
3853                wgpu::CurrentSurfaceTexture::Success(f) => break f,
3854                wgpu::CurrentSurfaceTexture::Suboptimal(f) => {
3855                    log::warn!("suboptimal surface; reconfiguring");
3856                    surface.configure(&self.renderer.device, surface_config);
3857                    break f;
3858                }
3859                wgpu::CurrentSurfaceTexture::Outdated => {
3860                    retries += 1;
3861                    if retries >= MAX_RETRIES {
3862                        log::warn!(
3863                            "surface outdated persisted after {MAX_RETRIES} retries; skipping frame"
3864                        );
3865                        return;
3866                    }
3867                    log::warn!("surface outdated; reconfiguring");
3868                    surface.configure(&self.renderer.device, surface_config);
3869                }
3870                wgpu::CurrentSurfaceTexture::Lost => {
3871                    retries += 1;
3872                    if retries >= MAX_RETRIES {
3873                        log::warn!(
3874                            "surface lost persisted after {MAX_RETRIES} retries; skipping frame"
3875                        );
3876                        return;
3877                    }
3878                    log::warn!("surface lost; reconfiguring");
3879                    surface.configure(&self.renderer.device, surface_config);
3880                }
3881                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
3882                    request_frame();
3883                    return;
3884                }
3885                wgpu::CurrentSurfaceTexture::Validation => {
3886                    retries += 1;
3887                    if retries >= MAX_RETRIES {
3888                        log::warn!(
3889                            "surface validation persisted after {MAX_RETRIES} retries; skipping frame"
3890                        );
3891                        return;
3892                    }
3893                    surface.configure(&self.renderer.device, surface_config);
3894                }
3895            }
3896        };
3897
3898        let swap_view = frame
3899            .texture
3900            .create_view(&wgpu::TextureViewDescriptor::default());
3901        let mut encoder =
3902            self.renderer
3903                .device
3904                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3905                    label: Some("frame encoder"),
3906                });
3907
3908        let clear_color = Some([
3909            scene.clear_color.0 as f64 / 255.0,
3910            scene.clear_color.1 as f64 / 255.0,
3911            scene.clear_color.2 as f64 / 255.0,
3912            scene.clear_color.3 as f64 / 255.0,
3913        ]);
3914
3915        self.renderer
3916            .render_scene_to_encoder(scene, &mut encoder, &swap_view, clear_color);
3917
3918        //NOTE: The WebGL HAL present path (fullscreen triangle / blit) does not
3919        // restore gl.colorMask. Hence this is needed to prevent frames from going transparent.
3920        {
3921            let _reset = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3922                label: Some("webgl color_mask reset before present"),
3923                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3924                    view: &swap_view,
3925                    resolve_target: None,
3926                    ops: wgpu::Operations {
3927                        load: wgpu::LoadOp::Load,
3928                        store: wgpu::StoreOp::Store,
3929                    },
3930                    depth_slice: None,
3931                })],
3932                depth_stencil_attachment: None,
3933                timestamp_writes: None,
3934                occlusion_query_set: None,
3935                multiview_mask: None,
3936            });
3937        }
3938
3939        self.renderer
3940            .queue
3941            .submit(std::iter::once(encoder.finish()));
3942        if let Err(e) = catch_unwind(AssertUnwindSafe(|| self.renderer.queue.present(frame))) {
3943            log::warn!("queue.present panicked: {:?}", e);
3944        }
3945    }
3946}
3947
3948impl WgpuSceneRenderer {
3949    fn upload_mesh_geometry(&mut self, mesh: &repose_core::VectorMeshData) -> (u64, u32, u64, u32) {
3950        let verts: Vec<MeshVertex> = mesh
3951            .vertices
3952            .iter()
3953            .map(|v| MeshVertex {
3954                pos: v.pos,
3955                color: v.color,
3956                uv: v.uv,
3957            })
3958            .collect();
3959        let vbytes = bytemuck::cast_slice(&verts);
3960        self.mesh_verts
3961            .grow_to_fit(&self.device, vbytes.len() as u64);
3962        let (voff, _) = self.mesh_verts.alloc_write(&self.queue, vbytes);
3963        let ibytes = bytemuck::cast_slice(&mesh.indices);
3964        self.mesh_indices
3965            .grow_to_fit(&self.device, ibytes.len() as u64);
3966        let (ioff, _) = self.mesh_indices.alloc_write(&self.queue, ibytes);
3967        (voff, verts.len() as u32, ioff, mesh.indices.len() as u32)
3968    }
3969
3970    fn alloc_mesh_uniform(&mut self, u: MeshUniform) -> u64 {
3971        if self.mesh_uniform_head + MESH_UNIFORM_SLOT > MESH_UNIFORM_CAP {
3972            log::warn!("mesh uniform buffer overflow; regenerating");
3973            self.recreate_mesh_uniform_buffer();
3974        }
3975        let slot = self.mesh_uniform_head;
3976        self.queue
3977            .write_buffer(&self.mesh_uniform_buf, slot, bytemuck::bytes_of(&u));
3978        self.mesh_uniform_head = slot + MESH_UNIFORM_SLOT;
3979        slot
3980    }
3981
3982    fn recreate_mesh_uniform_buffer(&mut self) {
3983        let new_cap = self.mesh_uniform_head + MESH_UNIFORM_SLOT;
3984        self.mesh_uniform_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
3985            label: Some("mesh uniform buffer"),
3986            size: new_cap,
3987            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
3988            mapped_at_creation: false,
3989        });
3990        self.mesh_bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3991            label: Some("mesh uniform bind"),
3992            layout: &self.mesh_bind_layout,
3993            entries: &[wgpu::BindGroupEntry {
3994                binding: 0,
3995                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
3996                    buffer: &self.mesh_uniform_buf,
3997                    offset: 0,
3998                    size: NonZero::new(MESH_UNIFORM_SLOT),
3999                }),
4000            }],
4001        });
4002        self.mesh_uniform_head = 0;
4003    }
4004
4005    #[allow(clippy::too_many_arguments)]
4006    fn emit_vector_mesh(
4007        &mut self,
4008        current_transform: &Transform,
4009        mesh: &repose_core::VectorMeshData,
4010        transform: [f32; 6],
4011        paint: &repose_core::PaintDesc,
4012        cmds: &mut Vec<Cmd>,
4013    ) {
4014        let affine = combine_mesh_affine(current_transform, transform);
4015        let (voff, vcnt, ioff, icnt) = self.upload_mesh_geometry(mesh);
4016        let uoff = self.alloc_mesh_uniform(mesh_uniform_from_paint(affine, paint));
4017        cmds.push(Cmd::VectorMesh {
4018            voff,
4019            vcnt,
4020            ioff,
4021            icnt,
4022            uoff,
4023        });
4024    }
4025
4026    pub fn render_scene_to_encoder(
4027        &mut self,
4028        scene: &Scene,
4029        encoder: &mut wgpu::CommandEncoder,
4030        target_view: &wgpu::TextureView,
4031        clear_color_override: Option<[f64; 4]>,
4032    ) {
4033        fn to_ndc(x: f32, y: f32, w: f32, h: f32, fb_w: f32, fb_h: f32) -> [f32; 4] {
4034            let x0 = (x / fb_w) * 2.0 - 1.0;
4035            let y0 = 1.0 - (y / fb_h) * 2.0;
4036            let x1 = ((x + w) / fb_w) * 2.0 - 1.0;
4037            let y1 = 1.0 - ((y + h) / fb_h) * 2.0;
4038            let min_x = x0.min(x1);
4039            let min_y = y0.min(y1);
4040            let w_ndc = (x1 - x0).abs();
4041            let h_ndc = (y1 - y0).abs();
4042            [min_x, min_y, w_ndc, h_ndc]
4043        }
4044
4045        /// Convert a local-space rect + transform to NDC center-based position+size and rotation.
4046        fn rect_to_instance_ndc(
4047            rect: repose_core::Rect,
4048            transform: &Transform,
4049            fb_w: f32,
4050            fb_h: f32,
4051        ) -> ([f32; 4], [f32; 2]) {
4052            let cx = rect.x + rect.w * 0.5;
4053            let cy = rect.y + rect.h * 0.5;
4054
4055            // Apply full transform to center
4056            let sx = cx * transform.scale_x;
4057            let sy = cy * transform.scale_y;
4058            let cos_a = transform.rotate.cos();
4059            let sin_a = transform.rotate.sin();
4060            let tx = sx * cos_a - sy * sin_a + transform.translate_x;
4061            let ty = sx * sin_a + sy * cos_a + transform.translate_y;
4062
4063            // NDC center
4064            let ndc_cx = (tx / fb_w) * 2.0 - 1.0;
4065            let ndc_cy = 1.0 - (ty / fb_h) * 2.0;
4066            // NDC size (after scale only, no rotation - rotation is done in shader)
4067            let ndc_w = (rect.w * transform.scale_x / fb_w) * 2.0;
4068            let ndc_h = (rect.h * transform.scale_y / fb_h) * 2.0;
4069
4070            ([ndc_cx, ndc_cy, ndc_w, ndc_h], [cos_a, sin_a])
4071        }
4072
4073        fn to_scissor(r: &repose_core::Rect, fb_w: u32, fb_h: u32) -> (u32, u32, u32, u32) {
4074            let mut x = r.x.floor() as i64;
4075            let mut y = r.y.floor() as i64;
4076            let fb_wi = fb_w as i64;
4077            let fb_hi = fb_h as i64;
4078            x = x.clamp(0, fb_wi.saturating_sub(1));
4079            y = y.clamp(0, fb_hi.saturating_sub(1));
4080            let w_req = r.w.ceil().max(1.0) as i64;
4081            let h_req = r.h.ceil().max(1.0) as i64;
4082            let w = (w_req).min(fb_wi - x).max(1);
4083            let h = (h_req).min(fb_hi - y).max(1);
4084            (x as u32, y as u32, w as u32, h as u32)
4085        }
4086
4087        let fb_w = self.output_width as f32;
4088        let fb_h = self.output_height as f32;
4089
4090        let mut passes: Vec<Pass> = Vec::with_capacity(1);
4091        let clear_color = clear_color_override.unwrap_or_else(|| {
4092            [
4093                scene.clear_color.0 as f64 / 255.0,
4094                scene.clear_color.1 as f64 / 255.0,
4095                scene.clear_color.2 as f64 / 255.0,
4096                scene.clear_color.3 as f64 / 255.0,
4097            ]
4098        });
4099        let mut current_pass: Pass = Pass {
4100            target: PassTarget::Surface,
4101            initial_scissor: (0, 0, self.output_width, self.output_height),
4102            clear_color: Some([
4103                clear_color[0] as f32,
4104                clear_color[1] as f32,
4105                clear_color[2] as f32,
4106                clear_color[3] as f32,
4107            ]),
4108            cmds: Vec::with_capacity(scene.nodes.len()),
4109        };
4110        let mut target_stack: Vec<PassTarget> = Vec::new();
4111        let mut layer_alphas: Vec<(u32, f32, (u32, u32, u32, u32))> = Vec::new();
4112        let mut layer_blurs: Vec<(u32, f32, f32)> = Vec::new();
4113        let mut current_target_size: (f32, f32) = (fb_w, fb_h);
4114
4115        struct Batch {
4116            rects: Vec<RectInstance>,
4117            borders: Vec<BorderInstance>,
4118            ellipses: Vec<EllipseInstance>,
4119            e_borders: Vec<EllipseBorderInstance>,
4120            arcs: Vec<ArcInstance>,
4121            masks: Vec<GlyphInstance>,
4122            colors: Vec<GlyphInstance>,
4123            nv12s: Vec<Nv12Instance>,
4124        }
4125
4126        impl Batch {
4127            fn new() -> Self {
4128                Self {
4129                    rects: vec![],
4130                    borders: vec![],
4131                    ellipses: vec![],
4132                    e_borders: vec![],
4133                    arcs: vec![],
4134                    masks: vec![],
4135                    colors: vec![],
4136                    nv12s: vec![],
4137                }
4138            }
4139
4140            fn is_empty(&self) -> bool {
4141                self.rects.is_empty()
4142                    && self.borders.is_empty()
4143                    && self.ellipses.is_empty()
4144                    && self.e_borders.is_empty()
4145                    && self.arcs.is_empty()
4146                    && self.masks.is_empty()
4147                    && self.colors.is_empty()
4148                    && self.nv12s.is_empty()
4149            }
4150
4151            fn flush(
4152                &mut self,
4153                pipes: (
4154                    &mut InstancedPipe<RectInstance>,
4155                    &mut InstancedPipe<BorderInstance>,
4156                    &mut InstancedPipe<EllipseInstance>,
4157                    &mut InstancedPipe<EllipseBorderInstance>,
4158                    &mut InstancedPipe<ArcInstance>,
4159                ),
4160                glyph_pipes: (
4161                    &mut InstancedPipe<GlyphInstance>,
4162                    &mut InstancedPipe<GlyphInstance>,
4163                ),
4164                nv12_pipe: &mut InstancedPipe<Nv12Instance>,
4165                device: &wgpu::Device,
4166                queue: &wgpu::Queue,
4167                cmds: &mut Vec<Cmd>,
4168            ) {
4169                let (rects, borders, ellipses, e_borders, arcs) = pipes;
4170                let (masks, colors) = glyph_pipes;
4171
4172                macro_rules! flush_one {
4173                    ($buf:ident, $pipe:expr, $variant:ident) => {
4174                        if !self.$buf.is_empty() {
4175                            if let Some((off, cnt)) = $pipe.upload(device, queue, &self.$buf) {
4176                                cmds.push(Cmd::$variant { off, cnt });
4177                            }
4178                            self.$buf.clear();
4179                        }
4180                    };
4181                }
4182
4183                flush_one!(rects, rects, Rect);
4184                flush_one!(borders, borders, Border);
4185                flush_one!(ellipses, ellipses, Ellipse);
4186                flush_one!(e_borders, e_borders, EllipseBorder);
4187                flush_one!(arcs, arcs, Arc);
4188                flush_one!(masks, masks, GlyphsMask);
4189                flush_one!(colors, colors, GlyphsColor);
4190
4191                if !self.nv12s.is_empty() {
4192                    if let Some((off, cnt)) = nv12_pipe.upload(device, queue, &self.nv12s) {
4193                        let _ = (off, cnt);
4194                    }
4195                    self.nv12s.clear();
4196                }
4197            }
4198        }
4199
4200        self.rects.reset();
4201        self.borders.reset();
4202        self.ellipses.reset();
4203        self.ellipse_borders.reset();
4204        self.arcs.reset();
4205        self.glyph_mask.reset();
4206        self.glyph_color.reset();
4207        self.clip_ring.reset();
4208        self.blur_ring.reset();
4209        self.nv12.reset();
4210
4211        self.slug_ring.reset();
4212        self.mesh_verts.reset();
4213        self.mesh_indices.reset();
4214        self.mesh_uniform_head = 0;
4215        self.mesh_clip_stack.clear();
4216        let mut batch = Batch::new();
4217        let mut slug_verts_local: Vec<slug::TessVertex> = Vec::new();
4218        let mut transform_stack: Vec<Transform> = vec![Transform::identity()];
4219        let mut scissor_stack: Vec<repose_core::Rect> = Vec::with_capacity(8);
4220        // NOTE: Records the clip instance range + flags of each active rounded-rect clip
4221        // so PopClip can re-stamp the stencil with a decrement pass (mirroring
4222        // VectorClipPop). Keys: (off, cnt, difference, rounded).
4223        let mut clip_cmd_stack: Vec<(u64, u32, bool)> = Vec::with_capacity(8);
4224        let mut root_clip_rect = repose_core::Rect {
4225            x: 0.0,
4226            y: 0.0,
4227            w: fb_w,
4228            h: fb_h,
4229        };
4230        let mut saved_scissor_stack: Vec<repose_core::Rect> = Vec::new();
4231        let mut saved_root_clip_rect = root_clip_rect;
4232
4233        let mut current_prim: Option<&'static str> = None;
4234
4235        macro_rules! flush_if_prim_changed {
4236            ($prim:literal, $pipe:expr) => {
4237                if current_prim != Some($prim) {
4238                    flush_batch!();
4239                    current_prim = Some($prim);
4240                }
4241            };
4242        }
4243
4244        macro_rules! flush_batch {
4245            () => {
4246                if !batch.is_empty() {
4247                    batch.flush(
4248                        (
4249                            &mut self.rects,
4250                            &mut self.borders,
4251                            &mut self.ellipses,
4252                            &mut self.ellipse_borders,
4253                            &mut self.arcs,
4254                        ),
4255                        (&mut self.glyph_mask, &mut self.glyph_color),
4256                        &mut self.nv12,
4257                        &self.device,
4258                        &self.queue,
4259                        &mut current_pass.cmds,
4260                    )
4261                }
4262            };
4263        }
4264        for node in &scene.nodes {
4265            let t_identity = Transform::identity();
4266            let current_transform = transform_stack.last().unwrap_or(&t_identity);
4267
4268            match node {
4269                SceneNode::Rect {
4270                    rect,
4271                    brush,
4272                    radius,
4273                } => {
4274                    flush_if_prim_changed!("rect", &self.rects);
4275                    let (ndc, sin_cos) = rect_to_instance_ndc(
4276                        *rect,
4277                        current_transform,
4278                        current_target_size.0,
4279                        current_target_size.1,
4280                    );
4281                    let (brush_type, color0, color1, grad_start, grad_end) =
4282                        brush_to_instance_fields(brush);
4283                    batch.rects.push(RectInstance {
4284                        xywh: ndc,
4285                        radii: *radius,
4286                        brush_type,
4287                        _pad: [0.0; 3],
4288                        color0,
4289                        color1,
4290                        grad_start,
4291                        grad_end,
4292                        sin_cos,
4293                    });
4294                }
4295                SceneNode::Border {
4296                    rect,
4297                    color,
4298                    width,
4299                    radius,
4300                } => {
4301                    flush_if_prim_changed!("border", &self.borders);
4302                    let (ndc, sin_cos) = rect_to_instance_ndc(
4303                        *rect,
4304                        current_transform,
4305                        current_target_size.0,
4306                        current_target_size.1,
4307                    );
4308                    batch.borders.push(BorderInstance {
4309                        xywh: ndc,
4310                        radii: *radius,
4311                        stroke: *width,
4312                        color: color.to_linear(),
4313                        sin_cos,
4314                    });
4315                }
4316                SceneNode::Ellipse { rect, brush } => {
4317                    flush_if_prim_changed!("ellipse", &self.ellipses);
4318                    let (ndc, sin_cos) = rect_to_instance_ndc(
4319                        *rect,
4320                        current_transform,
4321                        current_target_size.0,
4322                        current_target_size.1,
4323                    );
4324                    let color = brush_to_solid_color(brush);
4325                    batch.ellipses.push(EllipseInstance {
4326                        xywh: ndc,
4327                        color,
4328                        sin_cos,
4329                    });
4330                }
4331                SceneNode::EllipseBorder { rect, color, width } => {
4332                    flush_if_prim_changed!("ellipse_border", &self.ellipse_borders);
4333                    let (ndc, sin_cos) = rect_to_instance_ndc(
4334                        *rect,
4335                        current_transform,
4336                        current_target_size.0,
4337                        current_target_size.1,
4338                    );
4339                    let pad_px = *width * 0.5 + 2.0;
4340                    let pad = (pad_px / current_target_size.0) * 2.0;
4341                    batch.e_borders.push(EllipseBorderInstance {
4342                        xywh: ndc,
4343                        stroke: *width,
4344                        pad,
4345                        color: color.to_linear(),
4346                        sin_cos,
4347                    });
4348                }
4349                SceneNode::Arc {
4350                    rect,
4351                    start_angle,
4352                    sweep_angle,
4353                    stroke_width,
4354                    color,
4355                    cap,
4356                } => {
4357                    flush_if_prim_changed!("arc", &self.arcs);
4358                    let (ndc, sin_cos) = rect_to_instance_ndc(
4359                        *rect,
4360                        current_transform,
4361                        current_target_size.0,
4362                        current_target_size.1,
4363                    );
4364                    let pad_px = *stroke_width * 0.5 + 2.0;
4365                    let pad = (pad_px / current_target_size.0) * 2.0;
4366                    let cap_val = match cap {
4367                        StrokeCap::Butt => 0.0,
4368                        StrokeCap::Round => 1.0,
4369                        StrokeCap::Square => 2.0,
4370                    };
4371                    batch.arcs.push(ArcInstance {
4372                        xywh: ndc,
4373                        start_angle: *start_angle,
4374                        sweep_angle: *sweep_angle,
4375                        stroke: *stroke_width,
4376                        pad,
4377                        color: color.to_linear(),
4378                        sin_cos,
4379                        cap: cap_val,
4380                    });
4381                }
4382                SceneNode::Text {
4383                    rect,
4384                    text,
4385                    color,
4386                    size,
4387                    font_family,
4388                    text_align: _,
4389                    font_weight,
4390                    font_style,
4391                    text_decoration,
4392                    letter_spacing,
4393                    line_height: _,
4394                    extra_style,
4395                    url: _,
4396                    font_variation_settings,
4397                } => {
4398                    flush_batch!(); // flush any prior primitives
4399
4400                    let px = *size;
4401                    let lh_ratio = rect.h / px;
4402                    let fw = font_weight.0;
4403                    let fs = if *font_style == FontStyle::Italic {
4404                        1
4405                    } else {
4406                        0
4407                    };
4408                    let shaped = repose_text::shape_line(
4409                        text.as_ref(),
4410                        px,
4411                        lh_ratio,
4412                        *font_family,
4413                        fw,
4414                        fs,
4415                        *letter_spacing,
4416                        font_variation_settings.as_deref(),
4417                    );
4418                    let baseline_y = shaped.first().map(|g| rect.y + g.y);
4419
4420                    let cos_a = current_transform.rotate.cos();
4421                    let sin_a = current_transform.rotate.sin();
4422                    let has_rotation = current_transform.rotate != 0.0;
4423
4424                    // For rotated text, the pivot is the center of the text rect.
4425                    let pivot_x = rect.x + rect.w * 0.5;
4426                    let pivot_y = rect.y + rect.h * 0.5;
4427
4428                    // Helper: compute NDC for a glyph rect, handling rotation correctly.
4429                    let make_glyph_instance =
4430                        |gx: f32, gy: f32, gw: f32, gh: f32| -> ([f32; 4], [f32; 2]) {
4431                            if has_rotation {
4432                                let corners =
4433                                    [(gx, gy), (gx + gw, gy), (gx + gw, gy + gh), (gx, gy + gh)];
4434                                let mut min_x = f32::MAX;
4435                                let mut max_x = f32::MIN;
4436                                let mut min_y = f32::MAX;
4437                                let mut max_y = f32::MIN;
4438                                for &(x, y) in &corners {
4439                                    let dx = x - pivot_x;
4440                                    let dy = y - pivot_y;
4441                                    let rx = pivot_x + dx * cos_a - dy * sin_a;
4442                                    let ry = pivot_y + dx * sin_a + dy * cos_a;
4443                                    min_x = min_x.min(rx);
4444                                    max_x = max_x.max(rx);
4445                                    min_y = min_y.min(ry);
4446                                    max_y = max_y.max(ry);
4447                                }
4448                                let bb_w = max_x - min_x;
4449                                let bb_h = max_y - min_y;
4450                                let ndc_tl = to_ndc(
4451                                    min_x,
4452                                    min_y,
4453                                    bb_w,
4454                                    bb_h,
4455                                    current_target_size.0,
4456                                    current_target_size.1,
4457                                );
4458                                let ndc = [
4459                                    ndc_tl[0] + ndc_tl[2] * 0.5,
4460                                    ndc_tl[1] + ndc_tl[3] * 0.5,
4461                                    ndc_tl[2],
4462                                    ndc_tl[3],
4463                                ];
4464                                (ndc, [cos_a, sin_a])
4465                            } else {
4466                                // Only safe at 1:1 scale (no zoom animations active).
4467                                let (sx, sy) = if current_transform.scale_x == 1.0
4468                                    && current_transform.scale_y == 1.0
4469                                {
4470                                    (gx.round(), gy.round())
4471                                } else {
4472                                    (gx, gy)
4473                                };
4474                                rect_to_instance_ndc(
4475                                    repose_core::Rect {
4476                                        x: sx,
4477                                        y: sy,
4478                                        w: gw,
4479                                        h: gh,
4480                                    },
4481                                    current_transform,
4482                                    current_target_size.0,
4483                                    current_target_size.1,
4484                                )
4485                            }
4486                        };
4487
4488                    let baseline_shift_y: f32 = px * extra_style.baseline_shift.0;
4489
4490                    let (
4491                        is_stroke,
4492                        stroke_width,
4493                        stroke_cap,
4494                        stroke_join,
4495                        stroke_miter,
4496                        stroke_path_effect,
4497                    ) = match &extra_style.draw_style {
4498                        repose_core::DrawStyle::Stroke {
4499                            width,
4500                            cap,
4501                            join,
4502                            miter,
4503                            path_effect,
4504                        } => (true, *width, *cap, *join, *miter, path_effect.clone()),
4505                        _ => (
4506                            false,
4507                            0.0,
4508                            repose_core::StrokeCap::Butt,
4509                            repose_core::StrokeJoin::Miter,
4510                            4.0,
4511                            None,
4512                        ),
4513                    };
4514                    let stroke_tess_key = if is_stroke {
4515                        Some(slug::StrokeTessKey::new(
4516                            stroke_width,
4517                            stroke_cap,
4518                            stroke_join,
4519                            stroke_miter,
4520                            &stroke_path_effect,
4521                        ))
4522                    } else {
4523                        None
4524                    };
4525
4526                    for sg in shaped {
4527                        let gx = rect.x + sg.x + sg.bearing_x;
4528                        let gy = rect.y + sg.y - sg.bearing_y + baseline_shift_y;
4529
4530                        // Vector glyph path: tessellated geometry with MSAA.
4531                        if self.slug_enabled {
4532                            let ck = repose_text::lookup_cache_key(sg.key, sg.px);
4533                            if let Some(ref ck) = ck {
4534                                // Check if cached.
4535                                let need_tessellate = self.slug_cache.get(ck).is_none_or(|g| {
4536                                    if is_stroke {
4537                                        let key = stroke_tess_key.as_ref().unwrap();
4538                                        !g.stroke_variants.contains_key(key)
4539                                    } else {
4540                                        g.fill_vertices.is_none()
4541                                    }
4542                                });
4543                                if need_tessellate {
4544                                    if let Some((ck2, commands)) =
4545                                        repose_text::lookup_and_extract_outline(sg.key, sg.px)
4546                                    {
4547                                        let font_size_px = f32::from_bits(ck2.font_size_bits);
4548                                        if is_stroke {
4549                                            self.slug_cache.get_or_insert_stroke(
4550                                                ck2,
4551                                                font_size_px,
4552                                                &commands,
4553                                                stroke_width,
4554                                                stroke_cap,
4555                                                stroke_join,
4556                                                stroke_miter,
4557                                                &stroke_path_effect,
4558                                            );
4559                                        } else {
4560                                            self.slug_cache.get_or_insert(
4561                                                ck2,
4562                                                font_size_px,
4563                                                &commands,
4564                                            );
4565                                        }
4566                                    }
4567                                } else {
4568                                    self.slug_cache.touch(ck);
4569                                }
4570                            }
4571                            if let Some(entry) = ck.as_ref().and_then(|ck| self.slug_cache.get(ck))
4572                            {
4573                                let ox = rect.x + sg.x;
4574                                let oy = rect.y + sg.y + baseline_shift_y;
4575                                let scx = current_transform.scale_x;
4576                                let scy = current_transform.scale_y;
4577                                let ttx = current_transform.translate_x;
4578                                let tty = current_transform.translate_y;
4579
4580                                let tf = |x: f32, y: f32| -> (f32, f32) {
4581                                    if has_rotation {
4582                                        let dx = x - pivot_x;
4583                                        let dy = y - pivot_y;
4584                                        let rx = pivot_x + dx * cos_a - dy * sin_a;
4585                                        let ry = pivot_y + dx * sin_a + dy * cos_a;
4586                                        (rx, ry)
4587                                    } else {
4588                                        (x * scx + ttx, y * scy + tty)
4589                                    }
4590                                };
4591
4592                                let tw = current_target_size.0;
4593                                let th = current_target_size.1;
4594
4595                                let verts = if is_stroke {
4596                                    let key = stroke_tess_key.as_ref().unwrap();
4597                                    entry
4598                                        .stroke_variants
4599                                        .get(key)
4600                                        .map(|v| v.as_slice())
4601                                        .unwrap_or(&[])
4602                                } else {
4603                                    entry.fill_vertices.as_deref().unwrap_or(&[])
4604                                };
4605
4606                                for &v in verts {
4607                                    let (sx, sy) = tf(ox + v[0] * px, oy - v[1] * px);
4608                                    let ndc_x = sx / tw * 2.0 - 1.0;
4609                                    let ndc_y = -(sy / th) * 2.0 + 1.0;
4610                                    slug_verts_local.push(slug::TessVertex {
4611                                        ndc_pos: [ndc_x, ndc_y],
4612                                        color: color.to_linear(),
4613                                    });
4614                                }
4615
4616                                if is_stroke {
4617                                    // Stroke glyphs cannot use atlas fallback...
4618                                    continue;
4619                                }
4620                                continue;
4621                            }
4622                        }
4623
4624                        // Don't use atlas fallback for strokes too
4625                        if is_stroke {
4626                            continue;
4627                        }
4628
4629                        // Atlas fallback: color emoji + failed slug extraction
4630                        if let Some(info) = self.upload_glyph_color(sg.key, sg.px) {
4631                            let (ndc, sin_cos) = make_glyph_instance(gx, gy, info.w, info.h);
4632                            batch.colors.push(GlyphInstance {
4633                                xywh: ndc,
4634                                uv: [info.u0, info.v1, info.u1, info.v0],
4635                                color: color.to_linear(),
4636                                sin_cos,
4637                            });
4638                        } else if let Some(info) = self.upload_glyph_mask(sg.key, sg.px) {
4639                            let (ndc, sin_cos) = make_glyph_instance(gx, gy, info.w, info.h);
4640                            batch.masks.push(GlyphInstance {
4641                                xywh: ndc,
4642                                uv: [info.u0, info.v1, info.u1, info.v0],
4643                                color: color.to_linear(),
4644                                sin_cos,
4645                            });
4646                        }
4647                    }
4648
4649                    // Upload slug vertices if any
4650                    if !slug_verts_local.is_empty() {
4651                        let bytes = bytemuck::cast_slice(&slug_verts_local);
4652                        self.slug_ring.grow_to_fit(&self.device, bytes.len() as u64);
4653                        let (off, _) = self.slug_ring.alloc_write(&self.queue, bytes);
4654                        current_pass.cmds.push(Cmd::GlyphsVector {
4655                            off,
4656                            cnt: slug_verts_local.len() as u32,
4657                        });
4658                        slug_verts_local.clear();
4659                    }
4660
4661                    // Text decoration: underline / strikethrough
4662                    if (text_decoration.underline || text_decoration.strikethrough)
4663                        && let Some(baseline_y) = baseline_y
4664                    {
4665                        flush_batch!();
4666                        current_prim = Some("rect");
4667                        let deco_color = text_decoration.color.unwrap_or(*color);
4668                        let thickness = (px * 0.07).max(1.0);
4669
4670                        if text_decoration.underline {
4671                            let dy = baseline_y + px * 0.1;
4672                            let (ndc, sin_cos) = rect_to_instance_ndc(
4673                                repose_core::Rect {
4674                                    x: rect.x,
4675                                    y: dy,
4676                                    w: rect.w,
4677                                    h: thickness,
4678                                },
4679                                current_transform,
4680                                current_target_size.0,
4681                                current_target_size.1,
4682                            );
4683                            batch.rects.push(RectInstance {
4684                                xywh: ndc,
4685                                radii: [0.0; 4],
4686                                brush_type: 0,
4687                                _pad: [0.0; 3],
4688                                color0: deco_color.to_linear(),
4689                                color1: [0.0; 4],
4690                                grad_start: [0.0; 2],
4691                                grad_end: [0.0; 2],
4692                                sin_cos,
4693                            });
4694                        }
4695                        if text_decoration.strikethrough {
4696                            let sy = baseline_y - px * 0.3;
4697                            let (ndc, sin_cos) = rect_to_instance_ndc(
4698                                repose_core::Rect {
4699                                    x: rect.x,
4700                                    y: sy,
4701                                    w: rect.w,
4702                                    h: thickness,
4703                                },
4704                                current_transform,
4705                                current_target_size.0,
4706                                current_target_size.1,
4707                            );
4708                            batch.rects.push(RectInstance {
4709                                xywh: ndc,
4710                                radii: [0.0; 4],
4711                                brush_type: 0,
4712                                _pad: [0.0; 3],
4713                                color0: deco_color.to_linear(),
4714                                color1: [0.0; 4],
4715                                grad_start: [0.0; 2],
4716                                grad_end: [0.0; 2],
4717                                sin_cos,
4718                            });
4719                        }
4720                    }
4721                }
4722                SceneNode::Image {
4723                    rect,
4724                    handle,
4725                    tint,
4726                    fit,
4727                } => {
4728                    flush_batch!();
4729
4730                    // Update usage timestamp for eviction, lazily re-uploading
4731                    // evicted RGBA images from their retained source.
4732                    let (img_w, img_h, is_nv12) = match self.resolve_image_for_draw(*handle) {
4733                        Some(wh) => wh,
4734                        None => {
4735                            log::warn!("Image handle {} not found", handle);
4736                            continue;
4737                        }
4738                    };
4739
4740                    let src_w = img_w as f32;
4741                    let src_h = img_h as f32;
4742
4743                    let dst_w = rect.w.max(0.0);
4744                    let dst_h = rect.h.max(0.0);
4745                    if dst_w <= 0.0 || dst_h <= 0.0 {
4746                        continue;
4747                    }
4748
4749                    let (draw_rect, uv_rect) = match fit {
4750                        repose_core::view::ImageFit::Contain => {
4751                            let scale = (dst_w / src_w).min(dst_h / src_h);
4752                            let w = src_w * scale;
4753                            let h = src_h * scale;
4754                            (
4755                                repose_core::Rect {
4756                                    x: rect.x + (dst_w - w) * 0.5,
4757                                    y: rect.y + (dst_h - h) * 0.5,
4758                                    w,
4759                                    h,
4760                                },
4761                                [0.0, 1.0, 1.0, 0.0],
4762                            )
4763                        }
4764                        repose_core::view::ImageFit::Cover => {
4765                            let scale = (dst_w / src_w).max(dst_h / src_h);
4766                            let content_w = src_w * scale;
4767                            let content_h = src_h * scale;
4768                            let overflow_x = (content_w - dst_w) * 0.5;
4769                            let overflow_y = (content_h - dst_h) * 0.5;
4770                            let u0 = (overflow_x / content_w).clamp(0.0, 1.0);
4771                            let v0 = (overflow_y / content_h).clamp(0.0, 1.0);
4772                            let u1 = ((overflow_x + dst_w) / content_w).clamp(0.0, 1.0);
4773                            let v1 = ((overflow_y + dst_h) / content_h).clamp(0.0, 1.0);
4774                            (*rect, [u0, 1.0 - v0, u1, 1.0 - v1])
4775                        }
4776                        repose_core::view::ImageFit::FitWidth => {
4777                            let scale = dst_w / src_w;
4778                            (
4779                                repose_core::Rect {
4780                                    x: rect.x,
4781                                    y: rect.y + (dst_h - src_h * scale) * 0.5,
4782                                    w: dst_w,
4783                                    h: src_h * scale,
4784                                },
4785                                [0.0, 1.0, 1.0, 0.0],
4786                            )
4787                        }
4788                        repose_core::view::ImageFit::FitHeight => {
4789                            let scale = dst_h / src_h;
4790                            (
4791                                repose_core::Rect {
4792                                    x: rect.x + (dst_w - src_w * scale) * 0.5,
4793                                    y: rect.y,
4794                                    w: src_w * scale,
4795                                    h: dst_h,
4796                                },
4797                                [0.0, 1.0, 1.0, 0.0],
4798                            )
4799                        }
4800                        repose_core::view::ImageFit::FillBounds => {
4801                            (*rect, [0.0, 1.0, 1.0, 0.0])
4802                        }
4803                        repose_core::view::ImageFit::Inside => {
4804                            let scale = (dst_w / src_w).min(dst_h / src_h).min(1.0);
4805                            let w = src_w * scale;
4806                            let h = src_h * scale;
4807                            (
4808                                repose_core::Rect {
4809                                    x: rect.x + (dst_w - w) * 0.5,
4810                                    y: rect.y + (dst_h - h) * 0.5,
4811                                    w,
4812                                    h,
4813                                },
4814                                [0.0, 1.0, 1.0, 0.0],
4815                            )
4816                        }
4817                        repose_core::view::ImageFit::None => {
4818                            (
4819                                repose_core::Rect {
4820                                    x: rect.x,
4821                                    y: rect.y,
4822                                    w: src_w.min(dst_w),
4823                                    h: src_h.min(dst_h),
4824                                },
4825                                // If larger than dst, crop top-left of source:
4826                                [
4827                                    0.0,
4828                                    1.0,
4829                                    (dst_w / src_w).min(1.0),
4830                                    1.0 - (dst_h / src_h).min(1.0),
4831                                ],
4832                            )
4833                        }
4834                        _ => continue,
4835                    };
4836
4837                    let (ndc_center, sin_cos) = rect_to_instance_ndc(
4838                        draw_rect,
4839                        current_transform,
4840                        current_target_size.0,
4841                        current_target_size.1,
4842                    );
4843
4844                    if is_nv12 {
4845                        let uv_x_offset = if let Some(ImageTex::Nv12 { w, color_info, .. }) =
4846                            self.images.get(handle)
4847                        {
4848                            match color_info.chroma_siting {
4849                                ChromaSiting::Center | ChromaSiting::TopLeft => 0.0,
4850                                ChromaSiting::Left => -1.0 / *w as f32,
4851                            }
4852                        } else {
4853                            0.0
4854                        };
4855
4856                        let inst = Nv12Instance {
4857                            xywh: ndc_center,
4858                            uv: uv_rect,
4859                            color: tint.to_linear(),
4860                            uv_x_offset,
4861                            sin_cos,
4862                            _pad: [0.0],
4863                        };
4864                        if let Some((off, _)) = self.nv12.upload(&self.device, &self.queue, &[inst])
4865                        {
4866                            current_pass.cmds.push(Cmd::ImageNv12 {
4867                                off,
4868                                cnt: 1,
4869                                handle: *handle,
4870                            });
4871                        }
4872                    } else {
4873                        // RGBA uses GlyphInstance struct (reused pipeline)
4874                        let inst = GlyphInstance {
4875                            xywh: ndc_center,
4876                            uv: uv_rect,
4877                            color: tint.to_linear(),
4878                            sin_cos,
4879                        };
4880                        if let Some((off, _)) =
4881                            self.glyph_color.upload(&self.device, &self.queue, &[inst])
4882                        {
4883                            current_pass.cmds.push(Cmd::ImageRgba {
4884                                off,
4885                                cnt: 1,
4886                                handle: *handle,
4887                            });
4888                        }
4889                    }
4890                }
4891                SceneNode::PushClip { rect, radius, op } => {
4892                    flush_batch!(); // flush content before entering clip
4893
4894                    let is_diff = matches!(op, repose_core::ClipOp::Difference);
4895
4896                    let t_identity = Transform::identity();
4897                    let current_transform = transform_stack.last().unwrap_or(&t_identity);
4898                    let transformed = current_transform.apply_to_rect(*rect);
4899
4900                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
4901                    let next_scissor = if is_diff {
4902                        top
4903                    } else {
4904                        intersect(top, transformed)
4905                    };
4906                    scissor_stack.push(next_scissor);
4907                    let scissor = to_scissor(
4908                        &next_scissor,
4909                        current_target_size.0 as u32,
4910                        current_target_size.1 as u32,
4911                    );
4912
4913                    let clip_ndc_tl = to_ndc(
4914                        transformed.x,
4915                        transformed.y,
4916                        transformed.w,
4917                        transformed.h,
4918                        current_target_size.0,
4919                        current_target_size.1,
4920                    );
4921                    let inst = ClipInstance {
4922                        xywh: [
4923                            clip_ndc_tl[0] + clip_ndc_tl[2] * 0.5,
4924                            clip_ndc_tl[1] + clip_ndc_tl[3] * 0.5,
4925                            clip_ndc_tl[2],
4926                            clip_ndc_tl[3],
4927                        ],
4928                        radii: *radius,
4929                        sin_cos: [1.0, 0.0],
4930                    };
4931                    let bytes = bytemuck::bytes_of(&inst);
4932                    self.clip_ring.grow_to_fit(&self.device, bytes.len() as u64);
4933                    let (off, _) = self.clip_ring.alloc_write(&self.queue, bytes);
4934
4935                    let rounded = radius.iter().any(|&r| r > 0.5);
4936
4937                    current_pass.cmds.push(Cmd::ClipPush {
4938                        off,
4939                        cnt: 1,
4940                        scissor,
4941                        difference: is_diff,
4942                        rounded,
4943                    });
4944                    clip_cmd_stack.push((off, 1, is_diff));
4945                }
4946                SceneNode::PopClip => {
4947                    flush_batch!();
4948
4949                    if !scissor_stack.is_empty() {
4950                        scissor_stack.pop();
4951                    } else {
4952                        log::warn!("PopClip with empty stack");
4953                    }
4954
4955                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
4956                    let scissor = to_scissor(
4957                        &top,
4958                        current_target_size.0 as u32,
4959                        current_target_size.1 as u32,
4960                    );
4961                    let (off, cnt, difference) = clip_cmd_stack.pop().unwrap_or((0, 0, false));
4962                    current_pass.cmds.push(Cmd::ClipPop {
4963                        off,
4964                        cnt,
4965                        scissor,
4966                        difference,
4967                    });
4968                }
4969                SceneNode::Shadow {
4970                    rect,
4971                    radius,
4972                    elevation: _,
4973                    color,
4974                } => {
4975                    flush_if_prim_changed!("rect", &self.rects);
4976                    let (ndc, sin_cos) = rect_to_instance_ndc(
4977                        *rect,
4978                        current_transform,
4979                        current_target_size.0,
4980                        current_target_size.1,
4981                    );
4982                    let (brush_type, color0, _color1, _grad_start, _grad_end) =
4983                        brush_to_instance_fields(&Brush::Solid(*color));
4984                    batch.rects.push(RectInstance {
4985                        xywh: ndc,
4986                        radii: *radius,
4987                        brush_type,
4988                        _pad: [0.0; 3],
4989                        color0,
4990                        color1: [0.0; 4],
4991                        grad_start: [0.0; 2],
4992                        grad_end: [0.0; 2],
4993                        sin_cos,
4994                    });
4995                }
4996                SceneNode::PushTransform { transform } => {
4997                    flush_batch!(); // flush before transform change
4998                    let combined = current_transform.combine(transform);
4999                    transform_stack.push(combined);
5000                }
5001                SceneNode::PopTransform => {
5002                    flush_batch!(); // flush before transform change
5003                    transform_stack.pop();
5004                }
5005                SceneNode::BeginLayer {
5006                    rect,
5007                    layer_id,
5008                    alpha,
5009                    blur_radius_x,
5010                    blur_radius_y,
5011                    rectangle_edge: _,
5012                } => {
5013                    flush_batch!();
5014                    // Layer rect is already snapped to whole pixels in layout;
5015                    // round() keeps any bypass of that snap consistent.
5016                    let w = (rect.w.round().max(1.0)) as u32;
5017                    let h = (rect.h.round().max(1.0)) as u32;
5018                    saved_scissor_stack =
5019                        std::mem::replace(&mut scissor_stack, Vec::with_capacity(8));
5020                    saved_root_clip_rect = std::mem::replace(
5021                        &mut root_clip_rect,
5022                        repose_core::Rect {
5023                            x: 0.0,
5024                            y: 0.0,
5025                            w: w as f32,
5026                            h: h as f32,
5027                        },
5028                    );
5029                    scissor_stack.push(root_clip_rect);
5030                    // Close out the current pass, start a new one for the layer.
5031                    let prev_target = current_pass.target;
5032                    let prev_scissor = current_pass.initial_scissor;
5033                    let saved = std::mem::replace(
5034                        &mut current_pass,
5035                        Pass {
5036                            target: PassTarget::Layer(*layer_id),
5037                            initial_scissor: (0, 0, w, h),
5038                            clear_color: Some([0.0, 0.0, 0.0, 0.0]),
5039                            cmds: Vec::new(),
5040                        },
5041                    );
5042                    passes.push(saved);
5043                    target_stack.push(prev_target);
5044                    let _ = prev_scissor; // initial_scissor of resumed pass is restored at EndLayer
5045                    // Get or create the layer's offscreen texture now so that
5046                    // subsequent scissor ops / draws have a valid target.
5047                    self.get_or_create_layer(*layer_id, w, h, *rect);
5048                    current_target_size = (w as f32, h as f32);
5049                    layer_alphas.push((*layer_id, *alpha, current_pass.initial_scissor));
5050                    // Store blur info for post-processing after EndLayer
5051                    if *blur_radius_x > 0.0 || *blur_radius_y > 0.0 {
5052                        layer_blurs.push((*layer_id, *blur_radius_x, *blur_radius_y));
5053                    }
5054                }
5055                SceneNode::EndLayer { layer_id } => {
5056                    flush_batch!();
5057                    scissor_stack = std::mem::replace(&mut saved_scissor_stack, Vec::new());
5058                    root_clip_rect = saved_root_clip_rect;
5059                    // Finish the layer's pass, start a new one on the previous target.
5060                    let saved = std::mem::replace(
5061                        &mut current_pass,
5062                        Pass {
5063                            target: target_stack.pop().unwrap_or(PassTarget::Surface),
5064                            initial_scissor: (0, 0, self.output_width, self.output_height),
5065                            clear_color: None, // LoadOp::Load - don't wipe earlier surface content
5066                            cmds: Vec::new(),
5067                        },
5068                    );
5069                    passes.push(saved);
5070                    current_target_size = (fb_w, fb_h);
5071                    // Issue a composite quad for the just-finished layer in the new pass.
5072                    if let Some((_, layer_alpha, _)) = layer_alphas
5073                        .iter()
5074                        .find(|(id, _, _)| id == layer_id)
5075                        .copied()
5076                    {
5077                        let layer = self.layer_pool.get(layer_id).expect("layer target");
5078                        let ndc_tl = to_ndc(
5079                            layer.rect_px.0,
5080                            layer.rect_px.1,
5081                            layer.rect_px.2,
5082                            layer.rect_px.3,
5083                            fb_w,
5084                            fb_h,
5085                        );
5086                        let uv_u1 = layer.rect_px.2 / layer.width.max(1) as f32;
5087                        let uv_v1 = layer.rect_px.3 / layer.height.max(1) as f32;
5088                        // Check if this layer needs content blur
5089                        let blur_px_val = layer_blurs
5090                            .iter()
5091                            .find(|(id, _, _)| id == layer_id)
5092                            .map(|(_, bx, by)| (*bx, *by));
5093                        if let Some((blur_x, blur_y)) =
5094                            blur_px_val.filter(|(bx, by)| *bx > 0.0 || *by > 0.0)
5095                        {
5096                            // Content blur: draw blurred version using the blur_content pipeline
5097                            let bw_uv = (blur_x * 1.5) / layer.width.max(1) as f32;
5098                            let bh_uv = (blur_y * 1.5) / layer.height.max(1) as f32;
5099                            let inst = BlurInstance {
5100                                xywh: [
5101                                    ndc_tl[0] + ndc_tl[2] * 0.5,
5102                                    ndc_tl[1] + ndc_tl[3] * 0.5,
5103                                    ndc_tl[2],
5104                                    ndc_tl[3],
5105                                ],
5106                                uv: [0.0, 0.0, uv_u1, uv_v1],
5107                                color: [1.0, 1.0, 1.0, layer_alpha],
5108                                blur_uv: [bw_uv, bh_uv],
5109                                sin_cos: [1.0, 0.0],
5110                            };
5111                            self.blur_ring.grow_to_fit(
5112                                &self.device,
5113                                std::mem::size_of::<BlurInstance>() as u64,
5114                            );
5115                            let bytes = bytemuck::bytes_of(&inst);
5116                            let (off, _) = self.blur_ring.alloc_write(&self.queue, bytes);
5117                            current_pass.cmds.push(Cmd::CompositeBlur {
5118                                off,
5119                                cnt: 1,
5120                                layer_id: *layer_id,
5121                            });
5122                        } else {
5123                            // Normal sharp composite
5124                            let inst = GlyphInstance {
5125                                xywh: [
5126                                    ndc_tl[0] + ndc_tl[2] * 0.5,
5127                                    ndc_tl[1] + ndc_tl[3] * 0.5,
5128                                    ndc_tl[2],
5129                                    ndc_tl[3],
5130                                ],
5131                                uv: [0.0, uv_v1, uv_u1, 0.0],
5132                                color: [1.0, 1.0, 1.0, layer_alpha],
5133                                sin_cos: [1.0, 0.0],
5134                            };
5135                            if let Some((off, cnt)) =
5136                                self.glyph_color.upload(&self.device, &self.queue, &[inst])
5137                            {
5138                                current_pass.cmds.push(Cmd::CompositeLayer {
5139                                    off,
5140                                    cnt,
5141                                    layer_id: *layer_id,
5142                                });
5143                            }
5144                        }
5145                    }
5146                }
5147                SceneNode::CompositeShadow {
5148                    layer_id,
5149                    blur_px,
5150                    offset_px,
5151                    color,
5152                } => {
5153                    flush_batch!();
5154                    if let Some(layer) = self.layer_pool.get(layer_id).cloned() {
5155                        // Shadow rect = layer rect + offset.
5156                        let sx = layer.rect_px.0 + offset_px.0;
5157                        let sy = layer.rect_px.1 + offset_px.1;
5158                        let sw = layer.rect_px.2;
5159                        let sh = layer.rect_px.3;
5160                        // The blur in UV space is 1.5 * blur_px / texture_size
5161                        // (the 1.5 matches the 3x3 Gaussian span).
5162                        let bw_uv = (blur_px * 1.5) / layer.width.max(1) as f32;
5163                        let bh_uv = (blur_px * 1.5) / layer.height.max(1) as f32;
5164                        let shadow_u1 = layer.rect_px.2 / layer.width.max(1) as f32;
5165                        let shadow_v1 = layer.rect_px.3 / layer.height.max(1) as f32;
5166                        let ndc_tl = to_ndc(sx, sy, sw, sh, fb_w, fb_h);
5167                        let inst = BlurInstance {
5168                            xywh: [
5169                                ndc_tl[0] + ndc_tl[2] * 0.5,
5170                                ndc_tl[1] + ndc_tl[3] * 0.5,
5171                                ndc_tl[2],
5172                                ndc_tl[3],
5173                            ],
5174                            uv: [0.0, 0.0, shadow_u1, shadow_v1],
5175                            color: [
5176                                color.0 as f32 / 255.0,
5177                                color.1 as f32 / 255.0,
5178                                color.2 as f32 / 255.0,
5179                                color.3 as f32 / 255.0,
5180                            ],
5181                            blur_uv: [bw_uv, bh_uv],
5182                            sin_cos: [1.0, 0.0],
5183                        };
5184                        self.blur_ring
5185                            .grow_to_fit(&self.device, std::mem::size_of::<BlurInstance>() as u64);
5186                        let bytes = bytemuck::bytes_of(&inst);
5187                        let (off, _) = self.blur_ring.alloc_write(&self.queue, bytes);
5188                        current_pass.cmds.push(Cmd::CompositeShadow {
5189                            off,
5190                            cnt: 1,
5191                            layer_id: *layer_id,
5192                        });
5193                    }
5194                }
5195                SceneNode::VectorMesh {
5196                    mesh,
5197                    transform,
5198                    paint,
5199                    clip: _,
5200                    blend: _,
5201                } => {
5202                    flush_batch!();
5203                    let t_identity = Transform::identity();
5204                    let current_transform = transform_stack.last().unwrap_or(&t_identity);
5205                    self.emit_vector_mesh(
5206                        current_transform,
5207                        mesh,
5208                        *transform,
5209                        paint,
5210                        &mut current_pass.cmds,
5211                    );
5212                }
5213                SceneNode::VectorOverlay { meshes } => {
5214                    flush_batch!();
5215                    for m in meshes.iter() {
5216                        let (voff, vcnt, ioff, icnt) = self.upload_mesh_geometry(m);
5217                        let uoff = self.alloc_mesh_uniform(MeshUniform::identity());
5218                        current_pass.cmds.push(Cmd::VectorOverlay {
5219                            voff,
5220                            vcnt,
5221                            ioff,
5222                            icnt,
5223                            uoff,
5224                        });
5225                    }
5226                }
5227                SceneNode::PushVectorClip { mesh } => {
5228                    flush_batch!();
5229                    let t_identity = Transform::identity();
5230                    let current_transform = transform_stack.last().unwrap_or(&t_identity);
5231                    let affine =
5232                        combine_mesh_affine(current_transform, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
5233                    let aabb = mesh_aabb(mesh, affine);
5234                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
5235                    let next = intersect(top, aabb);
5236                    scissor_stack.push(next);
5237                    let scissor = to_scissor(
5238                        &next,
5239                        current_target_size.0 as u32,
5240                        current_target_size.1 as u32,
5241                    );
5242                    let (voff, vcnt, ioff, icnt) = self.upload_mesh_geometry(mesh);
5243                    let uoff = self.alloc_mesh_uniform(mesh_uniform_from_paint(
5244                        affine,
5245                        &repose_core::PaintDesc::Solid,
5246                    ));
5247                    current_pass.cmds.push(Cmd::VectorClipPush {
5248                        voff,
5249                        vcnt,
5250                        ioff,
5251                        icnt,
5252                        uoff,
5253                        scissor,
5254                    });
5255                    self.mesh_clip_stack.push((voff, vcnt, ioff, icnt, uoff));
5256                }
5257                SceneNode::PopVectorClip => {
5258                    flush_batch!();
5259                    if !scissor_stack.is_empty() {
5260                        scissor_stack.pop();
5261                    } else {
5262                        log::warn!("PopVectorClip with empty scissor stack");
5263                    }
5264                    if let Some((voff, vcnt, ioff, icnt, uoff)) = self.mesh_clip_stack.pop() {
5265                        let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
5266                        let scissor = to_scissor(
5267                            &top,
5268                            current_target_size.0 as u32,
5269                            current_target_size.1 as u32,
5270                        );
5271                        current_pass.cmds.push(Cmd::VectorClipPop {
5272                            voff,
5273                            vcnt,
5274                            ioff,
5275                            icnt,
5276                            uoff,
5277                            scissor,
5278                        });
5279                    } else {
5280                        log::warn!("PopVectorClip with empty clip stack");
5281                    }
5282                }
5283                _ => {}
5284            }
5285        }
5286
5287        flush_batch!();
5288
5289        // Push the final pass.
5290        passes.push(current_pass);
5291
5292        let globals_bytes = std::mem::size_of::<Globals>() as u64;
5293        let globals_staging = self.device.create_buffer(&wgpu::BufferDescriptor {
5294            label: Some("globals staging"),
5295            size: (passes.len().max(1) as u64) * globals_bytes,
5296            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
5297            mapped_at_creation: false,
5298        });
5299        for (i, pass) in passes.iter().enumerate() {
5300            let (target_w, target_h) = match pass.target {
5301                PassTarget::Surface => (fb_w, fb_h),
5302                PassTarget::Layer(layer_id) => {
5303                    let lt = self.layer_pool.get(&layer_id);
5304                    (
5305                        lt.map_or(fb_w, |l| l.width as f32),
5306                        lt.map_or(fb_h, |l| l.height as f32),
5307                    )
5308                }
5309            };
5310            self.queue.write_buffer(
5311                &globals_staging,
5312                (i as u64) * globals_bytes,
5313                bytemuck::bytes_of(&make_globals(target_w, target_h)),
5314            );
5315        }
5316
5317        let bind_mask = self.atlas_bind_group_mask();
5318        let bind_color = self.atlas_bind_group_color();
5319        let mut clip_depth: u32 = 0;
5320
5321        for (pass_index, pass) in std::mem::take(&mut passes).into_iter().enumerate() {
5322            let (color_view, resolve_target, depth_stencil_view, is_layer) = match pass.target {
5323                PassTarget::Surface => {
5324                    let swap_view = target_view.clone();
5325                    let use_ws = self.working_space && self.ws_view.is_some();
5326                    let (color, resolve) = if use_ws {
5327                        let ws_view = self.ws_view.as_ref().unwrap();
5328                        if let Some(msaa_view) = &self.msaa_view {
5329                            // MSAA resolves to working-space texture
5330                            (msaa_view.clone(), Some(ws_view.clone()))
5331                        } else {
5332                            // Direct render to working-space texture
5333                            (ws_view.clone(), None)
5334                        }
5335                    } else if let Some(msaa_view) = &self.msaa_view {
5336                        (msaa_view.clone(), Some(swap_view))
5337                    } else {
5338                        (swap_view, None)
5339                    };
5340                    (color, resolve, self.depth_stencil_view.clone(), false)
5341                }
5342                PassTarget::Layer(layer_id) => {
5343                    if let Some(lt) = self.layer_pool.get(&layer_id) {
5344                        (lt.view.clone(), None, lt.depth_stencil_view.clone(), true)
5345                    } else {
5346                        log::warn!("missing layer target {layer_id}");
5347                        continue;
5348                    }
5349                }
5350            };
5351
5352            encoder.copy_buffer_to_buffer(
5353                &globals_staging,
5354                (pass_index as u64) * globals_bytes,
5355                &self.globals_buf,
5356                0,
5357                globals_bytes,
5358            );
5359
5360            if is_layer {
5361                clip_depth = 0;
5362            }
5363
5364            let (tw, th) = match pass.target {
5365                PassTarget::Surface => (self.output_width, self.output_height),
5366                PassTarget::Layer(layer_id) => self
5367                    .layer_pool
5368                    .get(&layer_id)
5369                    .map(|l| (l.width, l.height))
5370                    .unwrap_or((self.output_width, self.output_height)),
5371            };
5372            let initial_scissor = clamp_scissor(
5373                pass.initial_scissor.0,
5374                pass.initial_scissor.1,
5375                pass.initial_scissor.2,
5376                pass.initial_scissor.3,
5377                tw,
5378                th,
5379            );
5380
5381            let pipes: &Pipelines = if is_layer {
5382                &self.layer_pipes
5383            } else {
5384                &self.surface_pipes
5385            };
5386
5387            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5388                label: Some("pass"),
5389                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5390                    view: &color_view,
5391                    resolve_target: resolve_target.as_ref(),
5392                    ops: wgpu::Operations {
5393                        load: match pass.clear_color {
5394                            Some(c) => wgpu::LoadOp::Clear(wgpu::Color {
5395                                r: c[0] as f64,
5396                                g: c[1] as f64,
5397                                b: c[2] as f64,
5398                                a: c[3] as f64,
5399                            }),
5400                            None => wgpu::LoadOp::Load,
5401                        },
5402                        store: wgpu::StoreOp::Store,
5403                    },
5404                    depth_slice: None,
5405                })],
5406                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
5407                    view: &depth_stencil_view,
5408                    depth_ops: None,
5409                    stencil_ops: Some(wgpu::Operations {
5410                        load: if is_layer || pass.clear_color.is_some() {
5411                            wgpu::LoadOp::Clear(0)
5412                        } else {
5413                            wgpu::LoadOp::Load
5414                        },
5415                        store: wgpu::StoreOp::Store,
5416                    }),
5417                }),
5418                timestamp_writes: None,
5419                occlusion_query_set: None,
5420                multiview_mask: None,
5421            });
5422
5423            rpass.set_bind_group(0, &self.globals_bind, &[]);
5424            rpass.set_stencil_reference(clip_depth);
5425            rpass.set_scissor_rect(
5426                initial_scissor.0,
5427                initial_scissor.1,
5428                initial_scissor.2,
5429                initial_scissor.3,
5430            );
5431
5432            macro_rules! draw_simple {
5433                ($pipeline:expr, $ring:expr, $inst:ty, $off:ident, $n:ident) => {{
5434                    rpass.set_pipeline($pipeline);
5435                    let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
5436                    rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
5437                    rpass.draw(0..6, 0..$n);
5438                }};
5439            }
5440
5441            macro_rules! draw_with_bind {
5442                ($pipeline:expr, $ring:expr, $inst:ty, $bind:expr, $off:ident, $n:ident) => {{
5443                    rpass.set_pipeline($pipeline);
5444                    rpass.set_bind_group(1, $bind, &[]);
5445                    let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
5446                    rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
5447                    rpass.draw(0..6, 0..$n);
5448                }};
5449            }
5450
5451            macro_rules! draw_indexed_mesh {
5452                ($pipeline:expr, $uoff:ident, $voff:ident, $vcnt:ident, $ioff:ident, $icnt:ident) => {{
5453                    rpass.set_pipeline($pipeline);
5454                    rpass.set_bind_group(1, &self.mesh_bind, &[$uoff as u32]);
5455                    let vbytes = ($vcnt as u64) * std::mem::size_of::<MeshVertex>() as u64;
5456                    rpass.set_vertex_buffer(0, self.mesh_verts.buf.slice($voff..$voff + vbytes));
5457                    let ibytes = ($icnt as u64) * std::mem::size_of::<u32>() as u64;
5458                    rpass.set_index_buffer(
5459                        self.mesh_indices.buf.slice($ioff..$ioff + ibytes),
5460                        wgpu::IndexFormat::Uint32,
5461                    );
5462                    rpass.draw_indexed(0..$icnt, 0, 0..1);
5463                }};
5464            }
5465
5466            for cmd in pass.cmds {
5467                match cmd {
5468                    Cmd::ClipPush {
5469                        off,
5470                        cnt: n,
5471                        scissor,
5472                        difference,
5473                        rounded,
5474                    } => {
5475                        let scissor =
5476                            clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
5477                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
5478                        rpass.set_stencil_reference(clip_depth);
5479
5480                        if difference {
5481                            rpass.set_pipeline(&pipes.clip_dec);
5482                        } else if self.msaa_samples > 1 && !is_layer && rounded {
5483                            rpass.set_pipeline(&pipes.clip_a2c);
5484                        } else {
5485                            rpass.set_pipeline(&pipes.clip_bin);
5486                        }
5487
5488                        let bytes = (n as u64) * std::mem::size_of::<ClipInstance>() as u64;
5489                        rpass.set_vertex_buffer(0, self.clip_ring.buf.slice(off..off + bytes));
5490                        rpass.draw(0..6, 0..n);
5491
5492                        if !difference {
5493                            clip_depth = (clip_depth + 1).min(255);
5494                            rpass.set_stencil_reference(clip_depth);
5495                        }
5496                    }
5497
5498                    Cmd::ClipPop {
5499                        off,
5500                        cnt: n,
5501                        scissor,
5502                        difference,
5503                    } => {
5504                        let scissor =
5505                            clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
5506                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
5507
5508                        if !difference && n > 0 {
5509                            rpass.set_stencil_reference(clip_depth);
5510                            rpass.set_pipeline(&pipes.clip_dec);
5511                            let bytes = (n as u64) * std::mem::size_of::<ClipInstance>() as u64;
5512                            rpass.set_vertex_buffer(0, self.clip_ring.buf.slice(off..off + bytes));
5513                            rpass.draw(0..6, 0..n);
5514                            clip_depth = clip_depth.saturating_sub(1);
5515                        } else if !difference {
5516                            clip_depth = clip_depth.saturating_sub(1);
5517                        }
5518                        rpass.set_stencil_reference(clip_depth);
5519                    }
5520
5521                    Cmd::Rect { off, cnt: n } => {
5522                        draw_simple!(&pipes.rects, self.rects.ring, RectInstance, off, n);
5523                    }
5524
5525                    Cmd::Border { off, cnt: n } => {
5526                        draw_simple!(&pipes.borders, self.borders.ring, BorderInstance, off, n);
5527                    }
5528
5529                    Cmd::GlyphsMask { off, cnt: n } => {
5530                        draw_with_bind!(
5531                            &pipes.text_mask,
5532                            self.glyph_mask.ring,
5533                            GlyphInstance,
5534                            &bind_mask,
5535                            off,
5536                            n
5537                        );
5538                    }
5539
5540                    Cmd::GlyphsColor { off, cnt: n } => {
5541                        draw_with_bind!(
5542                            &pipes.text_color,
5543                            self.glyph_color.ring,
5544                            GlyphInstance,
5545                            &bind_color,
5546                            off,
5547                            n
5548                        );
5549                    }
5550
5551                    Cmd::GlyphsVector { off, cnt: n } => {
5552                        if let Some(slug_pipe) = pipes.slug.as_ref() {
5553                            rpass.set_pipeline(slug_pipe);
5554                            let bytes = (n as u64) * std::mem::size_of::<slug::TessVertex>() as u64;
5555                            rpass.set_vertex_buffer(0, self.slug_ring.buf.slice(off..off + bytes));
5556                            rpass.draw(0..n, 0..1);
5557                        }
5558                    }
5559
5560                    Cmd::ImageRgba {
5561                        off,
5562                        cnt: n,
5563                        handle,
5564                    } => {
5565                        if let Some(ImageTex::Rgba { bind, .. }) = self.images.get(&handle) {
5566                            draw_with_bind!(
5567                                &pipes.image_rgba,
5568                                self.glyph_color.ring,
5569                                GlyphInstance,
5570                                bind,
5571                                off,
5572                                n
5573                            );
5574                        }
5575                    }
5576
5577                    Cmd::ImageNv12 {
5578                        off,
5579                        cnt: n,
5580                        handle,
5581                    } => {
5582                        if let Some(ImageTex::Nv12 { bind, .. }) = self.images.get(&handle) {
5583                            draw_with_bind!(
5584                                &pipes.image_nv12,
5585                                self.nv12.ring,
5586                                Nv12Instance,
5587                                bind,
5588                                off,
5589                                n
5590                            );
5591                        }
5592                    }
5593
5594                    Cmd::Ellipse { off, cnt: n } => {
5595                        draw_simple!(&pipes.ellipses, self.ellipses.ring, EllipseInstance, off, n);
5596                    }
5597
5598                    Cmd::EllipseBorder { off, cnt: n } => {
5599                        draw_simple!(
5600                            &pipes.ellipse_borders,
5601                            self.ellipse_borders.ring,
5602                            EllipseBorderInstance,
5603                            off,
5604                            n
5605                        );
5606                    }
5607
5608                    Cmd::Arc { off, cnt: n } => {
5609                        draw_simple!(&pipes.arcs, self.arcs.ring, ArcInstance, off, n);
5610                    }
5611
5612                    Cmd::CompositeLayer {
5613                        off,
5614                        cnt: n,
5615                        layer_id,
5616                    } => {
5617                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
5618                            draw_with_bind!(
5619                                &pipes.image_rgba,
5620                                self.glyph_color.ring,
5621                                GlyphInstance,
5622                                &lt.bind,
5623                                off,
5624                                n
5625                            );
5626                        }
5627                    }
5628                    Cmd::CompositeShadow {
5629                        off,
5630                        cnt: n,
5631                        layer_id,
5632                    } => {
5633                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
5634                            draw_with_bind!(
5635                                &pipes.blur,
5636                                self.blur_ring,
5637                                BlurInstance,
5638                                &lt.bind_linear,
5639                                off,
5640                                n
5641                            );
5642                        }
5643                    }
5644                    Cmd::CompositeBlur {
5645                        off,
5646                        cnt: n,
5647                        layer_id,
5648                    } => {
5649                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
5650                            draw_with_bind!(
5651                                &pipes.blur_content,
5652                                self.blur_ring,
5653                                BlurInstance,
5654                                &lt.bind_linear,
5655                                off,
5656                                n
5657                            );
5658                        }
5659                    }
5660
5661                    Cmd::VectorMesh {
5662                        voff,
5663                        vcnt,
5664                        ioff,
5665                        icnt,
5666                        uoff,
5667                    } => {
5668                        draw_indexed_mesh!(&pipes.mesh, uoff, voff, vcnt, ioff, icnt);
5669                    }
5670
5671                    Cmd::VectorOverlay {
5672                        voff,
5673                        vcnt,
5674                        ioff,
5675                        icnt,
5676                        uoff,
5677                    } => {
5678                        draw_indexed_mesh!(&pipes.mesh_overlay, uoff, voff, vcnt, ioff, icnt);
5679                    }
5680
5681                    Cmd::VectorClipPush {
5682                        voff,
5683                        vcnt,
5684                        ioff,
5685                        icnt,
5686                        uoff,
5687                        scissor,
5688                    } => {
5689                        let scissor =
5690                            clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
5691                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
5692                        rpass.set_stencil_reference(clip_depth);
5693                        draw_indexed_mesh!(&pipes.mesh_clip_inc, uoff, voff, vcnt, ioff, icnt);
5694                        clip_depth = (clip_depth + 1).min(255);
5695                        rpass.set_stencil_reference(clip_depth);
5696                    }
5697
5698                    Cmd::VectorClipPop {
5699                        voff,
5700                        vcnt,
5701                        ioff,
5702                        icnt,
5703                        uoff,
5704                        scissor,
5705                    } => {
5706                        // Decrement the mask while the stencil reference is
5707                        // still at the depth it was incremented to, so the
5708                        // equal-compare fires; then step the clip depth down.
5709                        rpass.set_stencil_reference(clip_depth);
5710                        let scissor =
5711                            clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
5712                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
5713                        draw_indexed_mesh!(&pipes.mesh_clip_dec, uoff, voff, vcnt, ioff, icnt);
5714                        clip_depth = clip_depth.saturating_sub(1);
5715                        rpass.set_stencil_reference(clip_depth);
5716                    }
5717                }
5718            }
5719        }
5720
5721        // Display pass: linear working space -> sRGB OETF -> swapchain
5722        if self.working_space
5723            && let (Some(_ws_view), Some(ws_bind), Some(display_pipeline)) =
5724                (&self.ws_view, &self.ws_bind, &self.display_pipeline)
5725        {
5726            let swap_view = target_view.clone();
5727            let mut display_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5728                label: Some("display transform"),
5729                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5730                    view: &swap_view,
5731                    resolve_target: None,
5732                    ops: wgpu::Operations {
5733                        load: wgpu::LoadOp::Load,
5734                        store: wgpu::StoreOp::Store,
5735                    },
5736                    depth_slice: None,
5737                })],
5738                depth_stencil_attachment: None,
5739                timestamp_writes: None,
5740                occlusion_query_set: None,
5741                multiview_mask: None,
5742            });
5743            display_pass.set_pipeline(display_pipeline);
5744            display_pass.set_bind_group(1, ws_bind, &[]);
5745            display_pass.draw(0..3, 0..1);
5746        }
5747
5748        // Frame end maintenance: Evict unused images
5749        self.evict_unused_images();
5750    }
5751
5752    /// Render a scene into an externally-provided texture view.
5753    /// Use this when embedding Repose in a host that owns the GPU.
5754    /// The host is responsible for submitting the encoder and handling present.
5755    pub fn render_to_view(
5756        &mut self,
5757        scene: &Scene,
5758        encoder: &mut wgpu::CommandEncoder,
5759        target_view: &wgpu::TextureView,
5760        width: u32,
5761        height: u32,
5762        clear_color: Option<[f64; 4]>,
5763    ) {
5764        self.resize(width, height);
5765
5766        self.frame_index = self.frame_index.wrapping_add(1);
5767        self.slug_cache.next_frame();
5768
5769        if width == 0 || height == 0 {
5770            return;
5771        }
5772
5773        self.render_scene_to_encoder(scene, encoder, target_view, clear_color);
5774    }
5775}
5776
5777fn clamp_scissor(x: u32, y: u32, w: u32, h: u32, tw: u32, th: u32) -> (u32, u32, u32, u32) {
5778    let x = x.min(tw.saturating_sub(1));
5779    let y = y.min(th.saturating_sub(1));
5780    let w = w.min(tw.saturating_sub(x)).max(1);
5781    let h = h.min(th.saturating_sub(y)).max(1);
5782    (x, y, w, h)
5783}
5784
5785fn intersect(a: repose_core::Rect, b: repose_core::Rect) -> repose_core::Rect {
5786    let x0 = a.x.max(b.x);
5787    let y0 = a.y.max(b.y);
5788    let x1 = (a.x + a.w).min(b.x + b.w);
5789    let y1 = (a.y + a.h).min(b.y + b.h);
5790    repose_core::Rect {
5791        x: x0,
5792        y: y0,
5793        w: (x1 - x0).max(0.0),
5794        h: (y1 - y0).max(0.0),
5795    }
5796}