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
2065        let (format, view_format) = if cfg!(target_arch = "wasm32")
2066            && adapter
2067                .get_downlevel_capabilities()
2068                .flags
2069                .contains(wgpu::DownlevelFlags::SURFACE_VIEW_FORMATS)
2070        {
2071            let non_srgb = caps
2072                .formats
2073                .iter()
2074                .copied()
2075                .find(|f| !f.is_srgb())
2076                .unwrap_or(caps.formats[0]);
2077            (non_srgb, Some(non_srgb.add_srgb_suffix()))
2078        } else if cfg!(target_arch = "wasm32") {
2079            let fmt = caps
2080                .formats
2081                .iter()
2082                .copied()
2083                .find(|f| f.is_srgb())
2084                .unwrap_or(caps.formats[0]);
2085            (fmt, None)
2086        } else {
2087            let fmt = caps
2088                .formats
2089                .iter()
2090                .copied()
2091                .find(|f| f.is_srgb())
2092                .unwrap_or(caps.formats[0]);
2093            (fmt, None)
2094        };
2095
2096        let present_mode = pick_present_mode(&caps, present_mode);
2097        let alpha_mode = caps.alpha_modes[0];
2098
2099        let render_format = view_format.unwrap_or(format);
2100        let msaa_samples = pick_surface_msaa(&adapter, format, msaa_samples);
2101        let renderer = WgpuSceneRenderer::from_device(device, queue, render_format, msaa_samples);
2102
2103        let view_formats = view_format.into_iter().collect::<Vec<_>>();
2104
2105        let config = wgpu::SurfaceConfiguration {
2106            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
2107            format,
2108            width: size.width.max(1),
2109            height: size.height.max(1),
2110            present_mode,
2111            alpha_mode,
2112            color_space: wgpu::SurfaceColorSpace::Auto,
2113            view_formats,
2114            desired_maximum_frame_latency: 1,
2115        };
2116        surface.configure(&renderer.device, &config);
2117
2118        Ok(WgpuSurfaceBackend {
2119            surface: Some(surface),
2120            surface_config: Some(config),
2121            renderer,
2122        })
2123    }
2124
2125    #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
2126    pub fn new(window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
2127        pollster::block_on(Self::new_async(window))
2128    }
2129
2130    #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
2131    pub fn new_with_msaa(
2132        window: Arc<winit::window::Window>,
2133        msaa_samples: u32,
2134    ) -> anyhow::Result<WgpuSurfaceBackend> {
2135        pollster::block_on(Self::new_async_with_msaa(window, msaa_samples))
2136    }
2137
2138    #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
2139    pub fn new_with_options(
2140        window: Arc<winit::window::Window>,
2141        msaa_samples: u32,
2142        present_mode: PresentModePref,
2143    ) -> anyhow::Result<WgpuSurfaceBackend> {
2144        pollster::block_on(Self::new_async_with_options(
2145            window,
2146            msaa_samples,
2147            present_mode,
2148        ))
2149    }
2150
2151    #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
2152    pub fn new(_window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
2153        anyhow::bail!("Use WgpuSurfaceBackend::new_async(window).await on wasm32")
2154    }
2155
2156    #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
2157    pub fn new_with_msaa(
2158        _window: Arc<winit::window::Window>,
2159        _msaa_samples: u32,
2160    ) -> anyhow::Result<WgpuSurfaceBackend> {
2161        anyhow::bail!("Use WgpuSurfaceBackend::new_async_with_msaa(window, msaa).await on wasm32")
2162    }
2163
2164    #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
2165    pub fn new_with_options(
2166        _window: Arc<winit::window::Window>,
2167        _msaa_samples: u32,
2168        _present_mode: PresentModePref,
2169    ) -> anyhow::Result<WgpuSurfaceBackend> {
2170        anyhow::bail!(
2171            "Use WgpuSurfaceBackend::new_async_with_options(window, msaa, mode).await on wasm32"
2172        )
2173    }
2174}
2175
2176/// Pick the swapchain present mode honoring `pref`, falling back to an "auto"
2177/// Fifo-first selection when the preferred mode is unavailable.
2178fn pick_present_mode(caps: &wgpu::SurfaceCapabilities, pref: PresentModePref) -> wgpu::PresentMode {
2179    let auto = || {
2180        caps.present_modes
2181            .iter()
2182            .copied()
2183            .find(|m| *m == wgpu::PresentMode::Fifo)
2184            .or_else(|| {
2185                caps.present_modes
2186                    .iter()
2187                    .copied()
2188                    .find(|m| *m == wgpu::PresentMode::Mailbox)
2189            })
2190            .unwrap_or(wgpu::PresentMode::Immediate)
2191    };
2192    match pref {
2193        PresentModePref::Auto => auto(),
2194        PresentModePref::Fifo if caps.present_modes.contains(&wgpu::PresentMode::Fifo) => {
2195            wgpu::PresentMode::Fifo
2196        }
2197        PresentModePref::Mailbox if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) => {
2198            wgpu::PresentMode::Mailbox
2199        }
2200        PresentModePref::Immediate
2201            if caps.present_modes.contains(&wgpu::PresentMode::Immediate) =>
2202        {
2203            wgpu::PresentMode::Immediate
2204        }
2205        _ => auto(),
2206    }
2207}
2208
2209/// Pick the MSAA sample count for the surface pass, honoring `requested` and
2210/// falling back to the largest supported count <= it.
2211fn pick_surface_msaa(adapter: &wgpu::Adapter, format: wgpu::TextureFormat, requested: u32) -> u32 {
2212    let requested = requested.max(1);
2213    let color_feat = adapter.get_texture_format_features(format);
2214    let depth_feat = adapter.get_texture_format_features(wgpu::TextureFormat::Depth24PlusStencil8);
2215    let supported = |n: u32| {
2216        color_feat.flags.sample_count_supported(n)
2217            && color_feat
2218                .flags
2219                .contains(wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE)
2220            && depth_feat.flags.sample_count_supported(n)
2221    };
2222    let mut candidates = vec![requested];
2223    for n in [8, 4, 2, 1] {
2224        if n < requested {
2225            candidates.push(n);
2226        }
2227    }
2228    let chosen = candidates.into_iter().find(|&n| supported(n)).unwrap_or(1);
2229    if chosen != requested {
2230        log::info!("requested MSAA x{requested}, using x{chosen}");
2231    }
2232    chosen
2233}
2234
2235impl WgpuSceneRenderer {
2236    // Image API
2237
2238    pub fn set_image_from_bytes(
2239        &mut self,
2240        handle: u64,
2241        data: &[u8],
2242        srgb: bool,
2243    ) -> anyhow::Result<()> {
2244        let img = image::load_from_memory(data)?;
2245        let rgba = img.to_rgba8();
2246        let (w, h) = rgba.dimensions();
2247        self.set_image_rgba8(handle, w, h, &rgba, srgb)
2248    }
2249
2250    pub fn set_image_rgba8(
2251        &mut self,
2252        handle: u64,
2253        w: u32,
2254        h: u32,
2255        rgba: &[u8],
2256        srgb: bool,
2257    ) -> anyhow::Result<()> {
2258        let expected = (w as usize) * (h as usize) * 4;
2259        if rgba.len() < expected {
2260            return Err(anyhow::anyhow!(
2261                "RGBA buffer too small: {} < {}",
2262                rgba.len(),
2263                expected
2264            ));
2265        }
2266
2267        let format = if srgb {
2268            wgpu::TextureFormat::Rgba8UnormSrgb
2269        } else {
2270            wgpu::TextureFormat::Rgba8Unorm
2271        };
2272
2273        let needs_recreate = match self.images.get(&handle) {
2274            Some(ImageTex::Rgba {
2275                w: cw,
2276                h: ch,
2277                format: cf,
2278                ..
2279            }) => *cw != w || *ch != h || *cf != format,
2280            _ => true,
2281        };
2282
2283        if needs_recreate {
2284            self.remove_image(handle);
2285
2286            let (tex, bind) = self.create_rgba_tex(w, h, format);
2287            let bytes = (w as u64) * (h as u64) * 4;
2288            self.image_bytes_total += bytes;
2289
2290            self.images.insert(
2291                handle,
2292                ImageTex::Rgba {
2293                    tex,
2294                    bind,
2295                    w,
2296                    h,
2297                    format,
2298                    last_used_frame: self.frame_index,
2299                    bytes,
2300                },
2301            );
2302        }
2303
2304        self.retained.insert(
2305            handle,
2306            RetainedImage {
2307                w,
2308                h,
2309                format,
2310                rgba: rgba[..expected].to_vec(),
2311            },
2312        );
2313
2314        let tex = match self.images.get(&handle) {
2315            Some(ImageTex::Rgba { tex, .. }) => tex,
2316            _ => unreachable!(),
2317        };
2318
2319        self.queue.write_texture(
2320            wgpu::TexelCopyTextureInfo {
2321                texture: tex,
2322                mip_level: 0,
2323                origin: wgpu::Origin3d::ZERO,
2324                aspect: wgpu::TextureAspect::All,
2325            },
2326            &rgba[..expected],
2327            wgpu::TexelCopyBufferLayout {
2328                offset: 0,
2329                bytes_per_row: Some(4 * w),
2330                rows_per_image: Some(h),
2331            },
2332            wgpu::Extent3d {
2333                width: w,
2334                height: h,
2335                depth_or_array_layers: 1,
2336            },
2337        );
2338
2339        // Ensure budget limits
2340        self.evict_budget_excess();
2341
2342        Ok(())
2343    }
2344
2345    /// Create (but do not populate) the GPU texture, view and bind group for an
2346    /// RGBA image. Pixels are written separately via `write_texture`.
2347    fn create_rgba_tex(
2348        &self,
2349        w: u32,
2350        h: u32,
2351        format: wgpu::TextureFormat,
2352    ) -> (wgpu::Texture, wgpu::BindGroup) {
2353        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2354            label: Some("user image rgba"),
2355            size: wgpu::Extent3d {
2356                width: w,
2357                height: h,
2358                depth_or_array_layers: 1,
2359            },
2360            mip_level_count: 1,
2361            sample_count: 1,
2362            dimension: wgpu::TextureDimension::D2,
2363            format,
2364            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2365            view_formats: &[],
2366        });
2367        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2368
2369        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2370            label: Some("image bind rgba"),
2371            layout: &self.image_bind_layout_rgba,
2372            entries: &[
2373                wgpu::BindGroupEntry {
2374                    binding: 0,
2375                    resource: wgpu::BindingResource::TextureView(&view),
2376                },
2377                wgpu::BindGroupEntry {
2378                    binding: 1,
2379                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2380                },
2381            ],
2382        });
2383
2384        (tex, bind)
2385    }
2386
2387    pub fn set_image_nv12(
2388        &mut self,
2389        handle: u64,
2390        w: u32,
2391        h: u32,
2392        y: &[u8],
2393        uv: &[u8],
2394        color_info: ColorInfo,
2395    ) -> anyhow::Result<()> {
2396        let y_expected = (w as usize) * (h as usize);
2397        let uv_w = w.div_ceil(2);
2398        let uv_h = h.div_ceil(2);
2399        let uv_expected = (uv_w as usize) * (uv_h as usize) * 2;
2400
2401        if y.len() < y_expected {
2402            return Err(anyhow::anyhow!("Y plane too small"));
2403        }
2404        if uv.len() < uv_expected {
2405            return Err(anyhow::anyhow!("UV plane too small"));
2406        }
2407
2408        let needs_recreate = match self.images.get(&handle) {
2409            Some(ImageTex::Nv12 { w: ww, h: hh, .. }) => *ww != w || *hh != h,
2410            _ => true,
2411        };
2412
2413        // Compute the YUV->RGB transform on the CPU.
2414        let yuv = color_info.to_yuv_transform();
2415        let yuv_raw = YuvTransformRaw {
2416            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2417            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2418            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2419            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
2420        };
2421
2422        if needs_recreate {
2423            self.remove_image(handle);
2424
2425            let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
2426                label: Some("nv12 Y"),
2427                size: wgpu::Extent3d {
2428                    width: w,
2429                    height: h,
2430                    depth_or_array_layers: 1,
2431                },
2432                mip_level_count: 1,
2433                sample_count: 1,
2434                dimension: wgpu::TextureDimension::D2,
2435                format: wgpu::TextureFormat::R8Unorm,
2436                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2437                view_formats: &[],
2438            });
2439            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
2440
2441            let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
2442                label: Some("nv12 UV"),
2443                size: wgpu::Extent3d {
2444                    width: uv_w,
2445                    height: uv_h,
2446                    depth_or_array_layers: 1,
2447                },
2448                mip_level_count: 1,
2449                sample_count: 1,
2450                dimension: wgpu::TextureDimension::D2,
2451                format: wgpu::TextureFormat::Rg8Unorm,
2452                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2453                view_formats: &[],
2454            });
2455            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
2456
2457            // Create a uniform buffer for the YUV transform (per-image).
2458            let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
2459                label: Some("nv12 yuv transform"),
2460                size: std::mem::size_of::<YuvTransformRaw>() as u64,
2461                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2462                mapped_at_creation: false,
2463            });
2464
2465            // Write initial transform.
2466            self.queue
2467                .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2468
2469            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2470                label: Some("nv12 bind"),
2471                layout: &self.image_bind_layout_nv12,
2472                entries: &[
2473                    wgpu::BindGroupEntry {
2474                        binding: 0,
2475                        resource: wgpu::BindingResource::TextureView(&view_y),
2476                    },
2477                    wgpu::BindGroupEntry {
2478                        binding: 1,
2479                        resource: wgpu::BindingResource::TextureView(&view_uv),
2480                    },
2481                    wgpu::BindGroupEntry {
2482                        binding: 2,
2483                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2484                    },
2485                    wgpu::BindGroupEntry {
2486                        binding: 3,
2487                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
2488                            buffer: &yuv_buf,
2489                            offset: 0,
2490                            size: None,
2491                        }),
2492                    },
2493                ],
2494            });
2495
2496            let bytes = (w as u64) * (h as u64)
2497                + (uv_w as u64) * (uv_h as u64) * 2
2498                + std::mem::size_of::<YuvTransformRaw>() as u64;
2499            self.image_bytes_total += bytes;
2500
2501            self.images.insert(
2502                handle,
2503                ImageTex::Nv12 {
2504                    tex_y,
2505                    tex_uv,
2506                    bind,
2507                    yuv_buf,
2508                    w,
2509                    h,
2510                    color_info,
2511                    last_used_frame: self.frame_index,
2512                    bytes,
2513                },
2514            );
2515        } else {
2516            // Re-use existing textures; just update the YUV transform if needed.
2517            if let Some(ImageTex::Nv12 { yuv_buf, .. }) = self.images.get(&handle) {
2518                self.queue
2519                    .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2520            }
2521        }
2522
2523        let (tex_y, tex_uv, _bind) = match self.images.get(&handle) {
2524            Some(ImageTex::Nv12 {
2525                tex_y,
2526                tex_uv,
2527                bind,
2528                ..
2529            }) => (tex_y, tex_uv, bind),
2530            _ => return Err(anyhow::anyhow!("Handle is not NV12")),
2531        };
2532
2533        self.queue.write_texture(
2534            wgpu::TexelCopyTextureInfo {
2535                texture: tex_y,
2536                mip_level: 0,
2537                origin: wgpu::Origin3d::ZERO,
2538                aspect: wgpu::TextureAspect::All,
2539            },
2540            &y[..y_expected],
2541            wgpu::TexelCopyBufferLayout {
2542                offset: 0,
2543                bytes_per_row: Some(w),
2544                rows_per_image: Some(h),
2545            },
2546            wgpu::Extent3d {
2547                width: w,
2548                height: h,
2549                depth_or_array_layers: 1,
2550            },
2551        );
2552
2553        self.queue.write_texture(
2554            wgpu::TexelCopyTextureInfo {
2555                texture: tex_uv,
2556                mip_level: 0,
2557                origin: wgpu::Origin3d::ZERO,
2558                aspect: wgpu::TextureAspect::All,
2559            },
2560            &uv[..uv_expected],
2561            wgpu::TexelCopyBufferLayout {
2562                offset: 0,
2563                bytes_per_row: Some(2 * uv_w),
2564                rows_per_image: Some(uv_h),
2565            },
2566            wgpu::Extent3d {
2567                width: uv_w,
2568                height: uv_h,
2569                depth_or_array_layers: 1,
2570            },
2571        );
2572
2573        self.evict_budget_excess();
2574        Ok(())
2575    }
2576
2577    pub fn set_image_planes(
2578        &mut self,
2579        handle: u64,
2580        w: u32,
2581        h: u32,
2582        pixel_format: PixelFormat,
2583        planes: &[&[u8]],
2584        color_info: ColorInfo,
2585    ) -> anyhow::Result<()> {
2586        match pixel_format {
2587            PixelFormat::Nv12 => {
2588                let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
2589                let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
2590                self.set_image_nv12(handle, w, h, y, uv, color_info)
2591            }
2592            PixelFormat::P010 => {
2593                let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
2594                let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
2595                self.set_image_p010(handle, w, h, y, uv, color_info)
2596            }
2597            PixelFormat::I420 | PixelFormat::I444 => Err(anyhow::anyhow!(
2598                "I420/I444 not implemented and unlikely -> cheap to convert to NV12 (better for the GPU too)"
2599            )),
2600            PixelFormat::Rgba => {
2601                let rgba = planes
2602                    .first()
2603                    .ok_or(anyhow::anyhow!("missing RGBA plane"))?;
2604                self.set_image_rgba8(handle, w, h, rgba, false)
2605            }
2606        }
2607    }
2608
2609    fn set_image_p010(
2610        &mut self,
2611        handle: u64,
2612        w: u32,
2613        h: u32,
2614        y: &[u8],
2615        uv: &[u8],
2616        color_info: ColorInfo,
2617    ) -> anyhow::Result<()> {
2618        let uv_w = w.div_ceil(2);
2619        let uv_h = h.div_ceil(2);
2620
2621        let y_expected = (w as usize) * 2;
2622        let uv_expected = (uv_w as usize) * (uv_h as usize) * 4;
2623
2624        if y.len() < y_expected {
2625            return Err(anyhow::anyhow!("P010 Y plane too small"));
2626        }
2627        if uv.len() < uv_expected {
2628            return Err(anyhow::anyhow!("P010 UV plane too small"));
2629        }
2630
2631        // P010 reuses the NV12 pipeline (same bind group layout -> wgpu
2632        // abstracts the storage format so R16Unorm/Rg16Unorm are
2633        // filterable float textures just like R8Unorm/Rg8Unorm).
2634        let needs_recreate = match self.images.get(&handle) {
2635            Some(ImageTex::Nv12 { w: ww, h: hh, .. }) => *ww != w || *hh != h,
2636            _ => true,
2637        };
2638
2639        let yuv = color_info.to_yuv_transform();
2640        let yuv_raw = YuvTransformRaw {
2641            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2642            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2643            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2644            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
2645        };
2646
2647        if needs_recreate {
2648            self.remove_image(handle);
2649
2650            let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
2651                label: Some("p010 Y"),
2652                size: wgpu::Extent3d {
2653                    width: w,
2654                    height: h,
2655                    depth_or_array_layers: 1,
2656                },
2657                mip_level_count: 1,
2658                sample_count: 1,
2659                dimension: wgpu::TextureDimension::D2,
2660                format: wgpu::TextureFormat::R16Unorm,
2661                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2662                view_formats: &[],
2663            });
2664            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
2665
2666            let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
2667                label: Some("p010 UV"),
2668                size: wgpu::Extent3d {
2669                    width: uv_w,
2670                    height: uv_h,
2671                    depth_or_array_layers: 1,
2672                },
2673                mip_level_count: 1,
2674                sample_count: 1,
2675                dimension: wgpu::TextureDimension::D2,
2676                format: wgpu::TextureFormat::Rg16Unorm,
2677                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2678                view_formats: &[],
2679            });
2680            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
2681
2682            let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
2683                label: Some("p010 yuv transform"),
2684                size: std::mem::size_of::<YuvTransformRaw>() as u64,
2685                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2686                mapped_at_creation: false,
2687            });
2688            self.queue
2689                .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2690
2691            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2692                label: Some("p010 bind"),
2693                layout: &self.image_bind_layout_nv12,
2694                entries: &[
2695                    wgpu::BindGroupEntry {
2696                        binding: 0,
2697                        resource: wgpu::BindingResource::TextureView(&view_y),
2698                    },
2699                    wgpu::BindGroupEntry {
2700                        binding: 1,
2701                        resource: wgpu::BindingResource::TextureView(&view_uv),
2702                    },
2703                    wgpu::BindGroupEntry {
2704                        binding: 2,
2705                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2706                    },
2707                    wgpu::BindGroupEntry {
2708                        binding: 3,
2709                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
2710                            buffer: &yuv_buf,
2711                            offset: 0,
2712                            size: None,
2713                        }),
2714                    },
2715                ],
2716            });
2717
2718            let bytes = (w as u64) * 2
2719                + (uv_w as u64) * (uv_h as u64) * 4
2720                + std::mem::size_of::<YuvTransformRaw>() as u64;
2721            self.image_bytes_total += bytes;
2722
2723            self.images.insert(
2724                handle,
2725                ImageTex::Nv12 {
2726                    tex_y,
2727                    tex_uv,
2728                    bind,
2729                    yuv_buf,
2730                    w,
2731                    h,
2732                    color_info,
2733                    last_used_frame: self.frame_index,
2734                    bytes,
2735                },
2736            );
2737        } else {
2738            if let Some(ImageTex::Nv12 { yuv_buf, .. }) = self.images.get(&handle) {
2739                self.queue
2740                    .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2741            }
2742        }
2743
2744        let (tex_y, tex_uv, _bind) = match self.images.get(&handle) {
2745            Some(ImageTex::Nv12 {
2746                tex_y,
2747                tex_uv,
2748                bind,
2749                ..
2750            }) => (tex_y, tex_uv, bind),
2751            _ => return Err(anyhow::anyhow!("Handle is not P010/NV12")),
2752        };
2753
2754        self.queue.write_texture(
2755            wgpu::TexelCopyTextureInfo {
2756                texture: tex_y,
2757                mip_level: 0,
2758                origin: wgpu::Origin3d::ZERO,
2759                aspect: wgpu::TextureAspect::All,
2760            },
2761            &y[..y_expected],
2762            wgpu::TexelCopyBufferLayout {
2763                offset: 0,
2764                bytes_per_row: Some(w * 2),
2765                rows_per_image: Some(h),
2766            },
2767            wgpu::Extent3d {
2768                width: w,
2769                height: h,
2770                depth_or_array_layers: 1,
2771            },
2772        );
2773        self.queue.write_texture(
2774            wgpu::TexelCopyTextureInfo {
2775                texture: tex_uv,
2776                mip_level: 0,
2777                origin: wgpu::Origin3d::ZERO,
2778                aspect: wgpu::TextureAspect::All,
2779            },
2780            &uv[..uv_expected],
2781            wgpu::TexelCopyBufferLayout {
2782                offset: 0,
2783                bytes_per_row: Some(uv_w * 4),
2784                rows_per_image: Some(uv_h),
2785            },
2786            wgpu::Extent3d {
2787                width: uv_w,
2788                height: uv_h,
2789                depth_or_array_layers: 1,
2790            },
2791        );
2792
2793        self.evict_budget_excess();
2794        Ok(())
2795    }
2796
2797    #[cfg(target_os = "linux")]
2798    pub fn set_image_dmabuf(
2799        &mut self,
2800        handle: u64,
2801        w: u32,
2802        h: u32,
2803        fds: Vec<std::os::unix::io::OwnedFd>,
2804        modifier: u64,
2805        strides: Vec<u32>,
2806        offsets: Vec<u64>,
2807        color_info: ColorInfo,
2808    ) -> anyhow::Result<()> {
2809        log::info!(
2810            "set_image_dmabuf handle={handle} {}x{} fds={} modifier=0x{modifier:x}",
2811            w,
2812            h,
2813            fds.len()
2814        );
2815
2816        self.remove_image(handle);
2817
2818        let yuv = color_info.to_yuv_transform();
2819        let yuv_raw = YuvTransformRaw {
2820            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2821            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2822            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2823            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
2824        };
2825
2826        if fds.len() != 2 {
2827            return Err(anyhow::anyhow!(
2828                "unsupported fd count {} - need exactly 2 for separate Y/UV planes",
2829                fds.len()
2830            ));
2831        }
2832
2833        let uv_w = w.div_ceil(2);
2834        let uv_h = h.div_ceil(2);
2835
2836        let hal_y_desc = wgpu::hal::TextureDescriptor {
2837            label: Some("dmabuf y"),
2838            size: wgpu::Extent3d {
2839                width: w,
2840                height: h,
2841                depth_or_array_layers: 1,
2842            },
2843            mip_level_count: 1,
2844            sample_count: 1,
2845            dimension: wgpu::TextureDimension::D2,
2846            format: wgpu::TextureFormat::R8Unorm,
2847            usage: wgpu::wgt::TextureUses::RESOURCE,
2848            memory_flags: wgpu::hal::MemoryFlags::empty(),
2849            view_formats: vec![],
2850        };
2851        let hal_uv_desc = wgpu::hal::TextureDescriptor {
2852            label: Some("dmabuf uv"),
2853            size: wgpu::Extent3d {
2854                width: uv_w,
2855                height: uv_h,
2856                depth_or_array_layers: 1,
2857            },
2858            mip_level_count: 1,
2859            sample_count: 1,
2860            dimension: wgpu::TextureDimension::D2,
2861            format: wgpu::TextureFormat::Rg8Unorm,
2862            usage: wgpu::wgt::TextureUses::RESOURCE,
2863            memory_flags: wgpu::hal::MemoryFlags::empty(),
2864            view_formats: vec![],
2865        };
2866
2867        let wgpu_y_desc = wgpu::TextureDescriptor {
2868            label: Some("dmabuf y"),
2869            size: wgpu::Extent3d {
2870                width: w,
2871                height: h,
2872                depth_or_array_layers: 1,
2873            },
2874            mip_level_count: 1,
2875            sample_count: 1,
2876            dimension: wgpu::TextureDimension::D2,
2877            format: wgpu::TextureFormat::R8Unorm,
2878            usage: wgpu::TextureUsages::TEXTURE_BINDING,
2879            view_formats: &[],
2880        };
2881        let wgpu_uv_desc = wgpu::TextureDescriptor {
2882            label: Some("dmabuf uv"),
2883            size: wgpu::Extent3d {
2884                width: uv_w,
2885                height: uv_h,
2886                depth_or_array_layers: 1,
2887            },
2888            mip_level_count: 1,
2889            sample_count: 1,
2890            dimension: wgpu::TextureDimension::D2,
2891            format: wgpu::TextureFormat::Rg8Unorm,
2892            usage: wgpu::TextureUsages::TEXTURE_BINDING,
2893            view_formats: &[],
2894        };
2895
2896        let (tex_y, view_y, tex_uv, view_uv) = unsafe {
2897            let hal_guard = self
2898                .device
2899                .as_hal::<wgpu::hal::vulkan::Api>()
2900                .ok_or_else(|| {
2901                    log::warn!("as_hal::<vulkan::Api> returned None");
2902                    anyhow::anyhow!("Device is not Vulkan")
2903                })?;
2904
2905            let mut fds = fds;
2906            let uv_fd = fds.remove(1);
2907            let y_fd = fds.remove(0);
2908
2909            let yt = hal_guard
2910                .texture_from_dmabuf_fd(y_fd, &hal_y_desc, modifier, strides[0] as u64, offsets[0])
2911                .map_err(|e| anyhow::anyhow!("import Y dmabuf: {e:?}"))?;
2912            log::info!("imported Y dmabuf OK");
2913
2914            let uvt = hal_guard
2915                .texture_from_dmabuf_fd(
2916                    uv_fd,
2917                    &hal_uv_desc,
2918                    modifier,
2919                    strides[1] as u64,
2920                    offsets[1],
2921                )
2922                .map_err(|e| anyhow::anyhow!("import UV dmabuf: {e:?}"))?;
2923            log::info!("imported UV dmabuf OK");
2924
2925            drop(hal_guard);
2926
2927            let tex_y = self
2928                .device
2929                .create_texture_from_hal::<wgpu::hal::vulkan::Api>(
2930                    yt,
2931                    &wgpu_y_desc,
2932                    wgpu::wgt::TextureUses::UNINITIALIZED,
2933                );
2934            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
2935
2936            let tex_uv = self
2937                .device
2938                .create_texture_from_hal::<wgpu::hal::vulkan::Api>(
2939                    uvt,
2940                    &wgpu_uv_desc,
2941                    wgpu::wgt::TextureUses::UNINITIALIZED,
2942                );
2943            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
2944
2945            (tex_y, view_y, tex_uv, view_uv)
2946        };
2947
2948        let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
2949            label: Some("dmabuf yuv transform"),
2950            size: std::mem::size_of::<YuvTransformRaw>() as u64,
2951            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2952            mapped_at_creation: false,
2953        });
2954        self.queue
2955            .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2956
2957        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2958            label: Some("dmabuf nv12 bind"),
2959            layout: &self.image_bind_layout_nv12,
2960            entries: &[
2961                wgpu::BindGroupEntry {
2962                    binding: 0,
2963                    resource: wgpu::BindingResource::TextureView(&view_y),
2964                },
2965                wgpu::BindGroupEntry {
2966                    binding: 1,
2967                    resource: wgpu::BindingResource::TextureView(&view_uv),
2968                },
2969                wgpu::BindGroupEntry {
2970                    binding: 2,
2971                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2972                },
2973                wgpu::BindGroupEntry {
2974                    binding: 3,
2975                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
2976                        buffer: &yuv_buf,
2977                        offset: 0,
2978                        size: None,
2979                    }),
2980                },
2981            ],
2982        });
2983
2984        let bytes = (w as u64) * (h as u64)
2985            + (uv_w as u64) * (uv_h as u64) * 2
2986            + std::mem::size_of::<YuvTransformRaw>() as u64;
2987
2988        self.images.insert(
2989            handle,
2990            ImageTex::Nv12 {
2991                tex_y,
2992                tex_uv,
2993                bind,
2994                yuv_buf,
2995                w,
2996                h,
2997                color_info,
2998                last_used_frame: self.frame_index,
2999                bytes,
3000            },
3001        );
3002
3003        self.evict_budget_excess();
3004        Ok(())
3005    }
3006
3007    pub fn remove_image(&mut self, handle: u64) {
3008        if let Some(img) = self.images.remove(&handle) {
3009            let b = match &img {
3010                ImageTex::Rgba { bytes, .. } => *bytes,
3011                ImageTex::Nv12 { bytes, .. } => *bytes,
3012            };
3013            self.image_bytes_total = self.image_bytes_total.saturating_sub(b);
3014        }
3015        self.retained.remove(&handle);
3016    }
3017
3018    fn evict_image_gpu(&mut self, handle: u64) -> u64 {
3019        let Some(img) = self.images.remove(&handle) else {
3020            return 0;
3021        };
3022        let b = match &img {
3023            ImageTex::Rgba { bytes, .. } => *bytes,
3024            ImageTex::Nv12 { bytes, .. } => *bytes,
3025        };
3026        self.image_bytes_total = self.image_bytes_total.saturating_sub(b);
3027        b
3028    }
3029
3030    fn revive_retained_image(&mut self, handle: u64) -> bool {
3031        if self.images.contains_key(&handle) {
3032            return true;
3033        }
3034        let Some(r) = self.retained.get(&handle).cloned() else {
3035            return false;
3036        };
3037        let (tex, bind) = self.create_rgba_tex(r.w, r.h, r.format);
3038
3039        self.queue.write_texture(
3040            wgpu::TexelCopyTextureInfo {
3041                texture: &tex,
3042                mip_level: 0,
3043                origin: wgpu::Origin3d::ZERO,
3044                aspect: wgpu::TextureAspect::All,
3045            },
3046            &r.rgba,
3047            wgpu::TexelCopyBufferLayout {
3048                offset: 0,
3049                bytes_per_row: Some(4 * r.w),
3050                rows_per_image: Some(r.h),
3051            },
3052            wgpu::Extent3d {
3053                width: r.w,
3054                height: r.h,
3055                depth_or_array_layers: 1,
3056            },
3057        );
3058
3059        let bytes = (r.w as u64) * (r.h as u64) * 4;
3060        self.image_bytes_total += bytes;
3061        self.images.insert(
3062            handle,
3063            ImageTex::Rgba {
3064                tex,
3065                bind,
3066                w: r.w,
3067                h: r.h,
3068                format: r.format,
3069                last_used_frame: self.frame_index,
3070                bytes,
3071            },
3072        );
3073        true
3074    }
3075
3076    fn resolve_image_for_draw(&mut self, handle: u64) -> Option<(u32, u32, bool)> {
3077        if let Some(t) = self.images.get_mut(&handle) {
3078            return match t {
3079                ImageTex::Rgba {
3080                    w,
3081                    h,
3082                    last_used_frame,
3083                    ..
3084                } => {
3085                    *last_used_frame = self.frame_index;
3086                    Some((*w, *h, false))
3087                }
3088                ImageTex::Nv12 {
3089                    w,
3090                    h,
3091                    last_used_frame,
3092                    ..
3093                } => {
3094                    *last_used_frame = self.frame_index;
3095                    Some((*w, *h, true))
3096                }
3097            };
3098        }
3099        if self.revive_retained_image(handle)
3100            && let Some(ImageTex::Rgba {
3101                w,
3102                h,
3103                last_used_frame,
3104                ..
3105            }) = self.images.get_mut(&handle)
3106        {
3107            *last_used_frame = self.frame_index;
3108            return Some((*w, *h, false));
3109        }
3110        None
3111    }
3112
3113    // Legacy support from Step 1 instructions (temporary until platform render logic is fully swapped)
3114    pub fn register_image_from_bytes(&mut self, data: &[u8], srgb: bool) -> u64 {
3115        let handle = self.next_image_handle;
3116        self.next_image_handle += 1;
3117        if let Err(e) = self.set_image_from_bytes(handle, data, srgb) {
3118            log::error!("Failed to register image: {e}");
3119        }
3120        handle
3121    }
3122
3123    fn evict_unused_images(&mut self) {
3124        let now = self.frame_index;
3125        let evict_after = self.image_evict_after_frames;
3126
3127        // Time based eviction. Eviction only frees GPU memory: retained RGBA
3128        // sources stay so the image can be lazily re-uploaded when drawn again.
3129        let mut to_evict = Vec::new();
3130        for (h, t) in self.images.iter() {
3131            let last = match t {
3132                ImageTex::Rgba {
3133                    last_used_frame, ..
3134                } => *last_used_frame,
3135                ImageTex::Nv12 {
3136                    last_used_frame, ..
3137                } => *last_used_frame,
3138            };
3139            if now.saturating_sub(last) > evict_after {
3140                to_evict.push(*h);
3141            }
3142        }
3143        for h in to_evict {
3144            if self.retained.contains_key(&h) {
3145                self.evict_image_gpu(h);
3146            } else {
3147                self.remove_image(h);
3148            }
3149        }
3150
3151        self.evict_budget_excess();
3152    }
3153
3154    fn evict_budget_excess(&mut self) {
3155        if self.image_bytes_total <= self.image_budget_bytes {
3156            return;
3157        }
3158        // Collect (handle, last_used, bytes)
3159        let mut candidates: Vec<(u64, u64, u64)> = self
3160            .images
3161            .iter()
3162            .map(|(h, t)| {
3163                let (last, bytes) = match t {
3164                    ImageTex::Rgba {
3165                        last_used_frame,
3166                        bytes,
3167                        ..
3168                    } => (*last_used_frame, *bytes),
3169                    ImageTex::Nv12 {
3170                        last_used_frame,
3171                        bytes,
3172                        ..
3173                    } => (*last_used_frame, *bytes),
3174                };
3175                (*h, last, bytes)
3176            })
3177            .collect();
3178
3179        // Sort by last_used ascending (LRU first)
3180        candidates.sort_by_key(|k| k.1);
3181
3182        let now = self.frame_index;
3183        for (h, last, _bytes) in candidates {
3184            if self.image_bytes_total <= self.image_budget_bytes {
3185                break;
3186            }
3187            // Don't evict something used this frame
3188            if last == now {
3189                continue;
3190            }
3191            if self.retained.contains_key(&h) {
3192                self.evict_image_gpu(h);
3193            } else {
3194                self.remove_image(h);
3195            }
3196        }
3197    }
3198
3199    /// Enable or disable linear working-space rendering.
3200    /// When enabled, the scene is rendered into an Rgba16Float intermediate
3201    /// and a final full-screen pass applies the display OETF.
3202    pub fn set_working_space(&mut self, enabled: bool) {
3203        if enabled == self.working_space {
3204            return;
3205        }
3206        self.working_space = enabled;
3207        if enabled {
3208            self.ensure_display_pipeline();
3209            self.recreate_working_space_texture();
3210        } else {
3211            self.ws_tex = None;
3212            self.ws_view = None;
3213            self.ws_bind = None;
3214        }
3215    }
3216
3217    fn ensure_display_pipeline(&mut self) {
3218        if self.display_pipeline.is_some() {
3219            return;
3220        }
3221
3222        let layout = self
3223            .device
3224            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3225                label: Some("display transform layout"),
3226                entries: &[
3227                    wgpu::BindGroupLayoutEntry {
3228                        binding: 0,
3229                        visibility: wgpu::ShaderStages::FRAGMENT,
3230                        ty: wgpu::BindingType::Texture {
3231                            multisampled: false,
3232                            view_dimension: wgpu::TextureViewDimension::D2,
3233                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
3234                        },
3235                        count: None,
3236                    },
3237                    wgpu::BindGroupLayoutEntry {
3238                        binding: 1,
3239                        visibility: wgpu::ShaderStages::FRAGMENT,
3240                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3241                        count: None,
3242                    },
3243                ],
3244            });
3245        self.display_layout = Some(layout);
3246
3247        let shader = self
3248            .device
3249            .create_shader_module(wgpu::ShaderModuleDescriptor {
3250                label: Some("display_transform.wgsl"),
3251                source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
3252                    "shaders/display_transform.wgsl"
3253                ))),
3254            });
3255
3256        let pipeline_layout = self
3257            .device
3258            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
3259                label: Some("display transform pipeline layout"),
3260                bind_group_layouts: &[None, self.display_layout.as_ref()],
3261                immediate_size: 0,
3262            });
3263
3264        let pipeline = self
3265            .device
3266            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
3267                label: Some("display transform pipeline"),
3268                layout: Some(&pipeline_layout),
3269                vertex: wgpu::VertexState {
3270                    module: &shader,
3271                    entry_point: Some("vs_main"),
3272                    buffers: &[],
3273                    compilation_options: wgpu::PipelineCompilationOptions::default(),
3274                },
3275                fragment: Some(wgpu::FragmentState {
3276                    module: &shader,
3277                    entry_point: Some("fs_main"),
3278                    targets: &[Some(wgpu::ColorTargetState {
3279                        format: self.output_format,
3280                        blend: None,
3281                        write_mask: wgpu::ColorWrites::ALL,
3282                    })],
3283                    compilation_options: wgpu::PipelineCompilationOptions::default(),
3284                }),
3285                primitive: wgpu::PrimitiveState::default(),
3286                depth_stencil: None,
3287                multisample: wgpu::MultisampleState::default(),
3288                multiview_mask: None,
3289                cache: None,
3290            });
3291        self.display_pipeline = Some(pipeline);
3292    }
3293
3294    /// Resize the render target dimensions.
3295    ///
3296    /// Recreates MSAA, depth-stencil, and working-space textures to match the
3297    /// new size..
3298    pub fn resize(&mut self, width: u32, height: u32) {
3299        self.output_width = width;
3300        self.output_height = height;
3301        self.recreate_msaa_and_depth_stencil();
3302        self.recreate_working_space_texture();
3303    }
3304
3305    fn recreate_working_space_texture(&mut self) {
3306        if !self.working_space {
3307            return;
3308        }
3309        let w = self.output_width.max(1);
3310        let h = self.output_height.max(1);
3311
3312        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3313            label: Some("working space"),
3314            size: wgpu::Extent3d {
3315                width: w,
3316                height: h,
3317                depth_or_array_layers: 1,
3318            },
3319            mip_level_count: 1,
3320            sample_count: 1,
3321            dimension: wgpu::TextureDimension::D2,
3322            format: wgpu::TextureFormat::Rgba16Float,
3323            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
3324            view_formats: &[],
3325        });
3326        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3327
3328        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3329            label: Some("working space bind"),
3330            layout: self.display_layout.as_ref().unwrap(),
3331            entries: &[
3332                wgpu::BindGroupEntry {
3333                    binding: 0,
3334                    resource: wgpu::BindingResource::TextureView(&view),
3335                },
3336                wgpu::BindGroupEntry {
3337                    binding: 1,
3338                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
3339                },
3340            ],
3341        });
3342
3343        self.ws_tex = Some(tex);
3344        self.ws_view = Some(view);
3345        self.ws_bind = Some(bind);
3346    }
3347
3348    fn recreate_msaa_and_depth_stencil(&mut self) {
3349        if self.msaa_samples > 1 {
3350            let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3351                label: Some("msaa color"),
3352                size: wgpu::Extent3d {
3353                    width: self.output_width.max(1),
3354                    height: self.output_height.max(1),
3355                    depth_or_array_layers: 1,
3356                },
3357                mip_level_count: 1,
3358                sample_count: self.msaa_samples,
3359                dimension: wgpu::TextureDimension::D2,
3360                format: self.output_format,
3361                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
3362                view_formats: &[],
3363            });
3364            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3365            self.msaa_tex = Some(tex);
3366            self.msaa_view = Some(view);
3367        } else {
3368            self.msaa_tex = None;
3369            self.msaa_view = None;
3370        }
3371
3372        self.depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
3373            label: Some("depth-stencil (stencil clips)"),
3374            size: wgpu::Extent3d {
3375                width: self.output_width.max(1),
3376                height: self.output_height.max(1),
3377                depth_or_array_layers: 1,
3378            },
3379            mip_level_count: 1,
3380            sample_count: self.msaa_samples,
3381            dimension: wgpu::TextureDimension::D2,
3382            format: wgpu::TextureFormat::Depth24PlusStencil8,
3383            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
3384            view_formats: &[],
3385        });
3386        self.depth_stencil_view = self
3387            .depth_stencil_tex
3388            .create_view(&wgpu::TextureViewDescriptor::default());
3389    }
3390
3391    fn get_or_create_layer(
3392        &mut self,
3393        layer_id: u32,
3394        width: u32,
3395        height: u32,
3396        rect: repose_core::Rect,
3397    ) {
3398        let needs_alloc = match self.layer_pool.get(&layer_id) {
3399            Some(lt) => lt.width != width || lt.height != height,
3400            None => true,
3401        };
3402        if !needs_alloc {
3403            if let Some(lt) = self.layer_pool.get_mut(&layer_id) {
3404                lt.rect_px = (rect.x, rect.y, rect.w, rect.h);
3405            }
3406            return;
3407        }
3408        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3409            label: Some("graphics layer"),
3410            size: wgpu::Extent3d {
3411                width: width.max(1),
3412                height: height.max(1),
3413                depth_or_array_layers: 1,
3414            },
3415            mip_level_count: 1,
3416            sample_count: 1,
3417            dimension: wgpu::TextureDimension::D2,
3418            format: self.output_format,
3419            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
3420            view_formats: &[],
3421        });
3422        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3423        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3424            label: Some("layer bind"),
3425            layout: &self.image_bind_layout_rgba,
3426            entries: &[
3427                wgpu::BindGroupEntry {
3428                    binding: 0,
3429                    resource: wgpu::BindingResource::TextureView(&view),
3430                },
3431                wgpu::BindGroupEntry {
3432                    binding: 1,
3433                    resource: wgpu::BindingResource::Sampler(&self.layer_sampler),
3434                },
3435            ],
3436        });
3437        let bind_linear = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3438            label: Some("layer bind linear"),
3439            layout: &self.image_bind_layout_rgba,
3440            entries: &[
3441                wgpu::BindGroupEntry {
3442                    binding: 0,
3443                    resource: wgpu::BindingResource::TextureView(&view),
3444                },
3445                wgpu::BindGroupEntry {
3446                    binding: 1,
3447                    resource: wgpu::BindingResource::Sampler(&self.layer_sampler_linear),
3448                },
3449            ],
3450        });
3451        let depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
3452            label: Some("graphics layer depth-stencil"),
3453            size: wgpu::Extent3d {
3454                width: width.max(1),
3455                height: height.max(1),
3456                depth_or_array_layers: 1,
3457            },
3458            mip_level_count: 1,
3459            sample_count: 1,
3460            dimension: wgpu::TextureDimension::D2,
3461            format: wgpu::TextureFormat::Depth24PlusStencil8,
3462            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
3463            view_formats: &[],
3464        });
3465        let depth_stencil_view =
3466            depth_stencil_tex.create_view(&wgpu::TextureViewDescriptor::default());
3467        self.layer_pool.insert(
3468            layer_id,
3469            LayerTarget {
3470                view,
3471                bind,
3472                bind_linear,
3473                depth_stencil_view,
3474                width,
3475                height,
3476                rect_px: (rect.x, rect.y, rect.w, rect.h),
3477            },
3478        );
3479    }
3480
3481    fn atlas_bind_group_mask(&self) -> wgpu::BindGroup {
3482        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3483            label: Some("atlas bind"),
3484            layout: &self.text_bind_layout,
3485            entries: &[
3486                wgpu::BindGroupEntry {
3487                    binding: 0,
3488                    resource: wgpu::BindingResource::TextureView(&self.atlas_mask.view),
3489                },
3490                wgpu::BindGroupEntry {
3491                    binding: 1,
3492                    resource: wgpu::BindingResource::Sampler(&self.atlas_mask.sampler),
3493                },
3494            ],
3495        })
3496    }
3497
3498    fn atlas_bind_group_color(&self) -> wgpu::BindGroup {
3499        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3500            label: Some("atlas bind color"),
3501            layout: &self.text_bind_layout,
3502            entries: &[
3503                wgpu::BindGroupEntry {
3504                    binding: 0,
3505                    resource: wgpu::BindingResource::TextureView(&self.atlas_color.view),
3506                },
3507                wgpu::BindGroupEntry {
3508                    binding: 1,
3509                    resource: wgpu::BindingResource::Sampler(&self.atlas_color.sampler),
3510                },
3511            ],
3512        })
3513    }
3514
3515    fn upload_glyph_mask(&mut self, key: repose_text::GlyphKey, px: f32) -> Option<GlyphInfo> {
3516        let keyp = (key, px.to_bits());
3517        if let Some(info) = self.atlas_mask.map.get(&keyp) {
3518            return Some(*info);
3519        }
3520
3521        let gb = repose_text::rasterize(key, px)?;
3522        if gb.w == 0 || gb.h == 0 || gb.data.is_empty() {
3523            return None;
3524        }
3525
3526        let coverage = swash_to_a8_coverage(gb.content, &gb.data)?;
3527
3528        let w = gb.w.max(1);
3529        let h = gb.h.max(1);
3530
3531        if !self.alloc_space_mask(w, h) {
3532            self.grow_mask_and_rebuild();
3533        }
3534        if !self.alloc_space_mask(w, h) {
3535            return None;
3536        }
3537        let x = self.atlas_mask.next_x;
3538        let y = self.atlas_mask.next_y;
3539        self.atlas_mask.next_x += w + 1;
3540        self.atlas_mask.row_h = self.atlas_mask.row_h.max(h + 1);
3541
3542        let layout = wgpu::TexelCopyBufferLayout {
3543            offset: 0,
3544            bytes_per_row: Some(w),
3545            rows_per_image: Some(h),
3546        };
3547        let size = wgpu::Extent3d {
3548            width: w,
3549            height: h,
3550            depth_or_array_layers: 1,
3551        };
3552        self.queue.write_texture(
3553            wgpu::TexelCopyTextureInfoBase {
3554                texture: &self.atlas_mask.tex,
3555                mip_level: 0,
3556                origin: wgpu::Origin3d { x, y, z: 0 },
3557                aspect: wgpu::TextureAspect::All,
3558            },
3559            &coverage,
3560            layout,
3561            size,
3562        );
3563
3564        let info = GlyphInfo {
3565            u0: x as f32 / self.atlas_mask.size as f32,
3566            v0: y as f32 / self.atlas_mask.size as f32,
3567            u1: (x + w) as f32 / self.atlas_mask.size as f32,
3568            v1: (y + h) as f32 / self.atlas_mask.size as f32,
3569            w: w as f32,
3570            h: h as f32,
3571        };
3572        self.atlas_mask.map.insert(keyp, info);
3573        Some(info)
3574    }
3575
3576    fn upload_glyph_color(&mut self, key: repose_text::GlyphKey, px: f32) -> Option<GlyphInfo> {
3577        let keyp = (key, px.to_bits());
3578        if let Some(info) = self.atlas_color.map.get(&keyp) {
3579            return Some(*info);
3580        }
3581        let gb = repose_text::rasterize(key, px)?;
3582        if !matches!(gb.content, repose_text::SwashContent::Color) {
3583            return None;
3584        }
3585        let w = gb.w.max(1);
3586        let h = gb.h.max(1);
3587        if !self.alloc_space_color(w, h) {
3588            self.grow_color_and_rebuild();
3589        }
3590        if !self.alloc_space_color(w, h) {
3591            return None;
3592        }
3593        let x = self.atlas_color.next_x;
3594        let y = self.atlas_color.next_y;
3595        self.atlas_color.next_x += w + 1;
3596        self.atlas_color.row_h = self.atlas_color.row_h.max(h + 1);
3597
3598        let layout = wgpu::TexelCopyBufferLayout {
3599            offset: 0,
3600            bytes_per_row: Some(w * 4),
3601            rows_per_image: Some(h),
3602        };
3603        let size = wgpu::Extent3d {
3604            width: w,
3605            height: h,
3606            depth_or_array_layers: 1,
3607        };
3608        self.queue.write_texture(
3609            wgpu::TexelCopyTextureInfoBase {
3610                texture: &self.atlas_color.tex,
3611                mip_level: 0,
3612                origin: wgpu::Origin3d { x, y, z: 0 },
3613                aspect: wgpu::TextureAspect::All,
3614            },
3615            &gb.data,
3616            layout,
3617            size,
3618        );
3619        let info = GlyphInfo {
3620            u0: x as f32 / self.atlas_color.size as f32,
3621            v0: y as f32 / self.atlas_color.size as f32,
3622            u1: (x + w) as f32 / self.atlas_color.size as f32,
3623            v1: (y + h) as f32 / self.atlas_color.size as f32,
3624            w: w as f32,
3625            h: h as f32,
3626        };
3627        self.atlas_color.map.insert(keyp, info);
3628        Some(info)
3629    }
3630
3631    fn alloc_space_mask(&mut self, w: u32, h: u32) -> bool {
3632        if self.atlas_mask.next_x + w + 1 >= self.atlas_mask.size {
3633            self.atlas_mask.next_x = 1;
3634            self.atlas_mask.next_y += self.atlas_mask.row_h + 1;
3635            self.atlas_mask.row_h = 0;
3636        }
3637        if self.atlas_mask.next_y + h + 1 >= self.atlas_mask.size {
3638            return false;
3639        }
3640        true
3641    }
3642
3643    fn grow_mask_and_rebuild(&mut self) {
3644        let new_size = (self.atlas_mask.size * 2).min(4096);
3645        if new_size == self.atlas_mask.size {
3646            return;
3647        }
3648        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3649            label: Some("glyph atlas A8 (grown)"),
3650            size: wgpu::Extent3d {
3651                width: new_size,
3652                height: new_size,
3653                depth_or_array_layers: 1,
3654            },
3655            mip_level_count: 1,
3656            sample_count: 1,
3657            dimension: wgpu::TextureDimension::D2,
3658            format: wgpu::TextureFormat::R8Unorm,
3659            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3660            view_formats: &[],
3661        });
3662        self.atlas_mask.tex = tex;
3663        self.atlas_mask.view = self
3664            .atlas_mask
3665            .tex
3666            .create_view(&wgpu::TextureViewDescriptor::default());
3667        self.atlas_mask.size = new_size;
3668        self.atlas_mask.next_x = 1;
3669        self.atlas_mask.next_y = 1;
3670        self.atlas_mask.row_h = 0;
3671        let keys: Vec<(repose_text::GlyphKey, u32)> = self.atlas_mask.map.keys().copied().collect();
3672        self.atlas_mask.map.clear();
3673        for (k, px_bits) in keys {
3674            let _ = self.upload_glyph_mask(k, f32::from_bits(px_bits));
3675        }
3676    }
3677
3678    fn alloc_space_color(&mut self, w: u32, h: u32) -> bool {
3679        if self.atlas_color.next_x + w + 1 >= self.atlas_color.size {
3680            self.atlas_color.next_x = 1;
3681            self.atlas_color.next_y += self.atlas_color.row_h + 1;
3682            self.atlas_color.row_h = 0;
3683        }
3684        if self.atlas_color.next_y + h + 1 >= self.atlas_color.size {
3685            return false;
3686        }
3687        true
3688    }
3689
3690    fn grow_color_and_rebuild(&mut self) {
3691        let new_size = (self.atlas_color.size * 2).min(4096);
3692        if new_size == self.atlas_color.size {
3693            return;
3694        }
3695        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
3696            label: Some("glyph atlas RGBA (grown)"),
3697            size: wgpu::Extent3d {
3698                width: new_size,
3699                height: new_size,
3700                depth_or_array_layers: 1,
3701            },
3702            mip_level_count: 1,
3703            sample_count: 1,
3704            dimension: wgpu::TextureDimension::D2,
3705            format: wgpu::TextureFormat::Rgba8UnormSrgb,
3706            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3707            view_formats: &[],
3708        });
3709        self.atlas_color.tex = tex;
3710        self.atlas_color.view = self
3711            .atlas_color
3712            .tex
3713            .create_view(&wgpu::TextureViewDescriptor::default());
3714        self.atlas_color.size = new_size;
3715        self.atlas_color.next_x = 1;
3716        self.atlas_color.next_y = 1;
3717        self.atlas_color.row_h = 0;
3718        let keys: Vec<(repose_text::GlyphKey, u32)> =
3719            self.atlas_color.map.keys().copied().collect();
3720        self.atlas_color.map.clear();
3721        for (k, px_bits) in keys {
3722            let _ = self.upload_glyph_color(k, f32::from_bits(px_bits));
3723        }
3724    }
3725}
3726
3727fn brush_to_instance_fields(brush: &Brush) -> (u32, [f32; 4], [f32; 4], [f32; 2], [f32; 2]) {
3728    match brush {
3729        Brush::Solid(c) => (
3730            0u32,
3731            c.to_linear(),
3732            [0.0, 0.0, 0.0, 0.0],
3733            [0.0, 0.0],
3734            [0.0, 1.0],
3735        ),
3736        Brush::Linear {
3737            start,
3738            end,
3739            start_color,
3740            end_color,
3741        } => (
3742            1u32,
3743            start_color.to_linear(),
3744            end_color.to_linear(),
3745            [start.x, start.y],
3746            [end.x, end.y],
3747        ),
3748        _ => (0u32, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2]),
3749    }
3750}
3751
3752fn brush_to_solid_color(brush: &Brush) -> [f32; 4] {
3753    match brush {
3754        Brush::Solid(c) => c.to_linear(),
3755        Brush::Linear { start_color, .. } => start_color.to_linear(),
3756        _ => [0.0; 4],
3757    }
3758}
3759
3760fn init_atlas_mask(device: &wgpu::Device) -> AtlasA8 {
3761    let size = 1024u32;
3762    let tex = device.create_texture(&wgpu::TextureDescriptor {
3763        label: Some("glyph atlas A8"),
3764        size: wgpu::Extent3d {
3765            width: size,
3766            height: size,
3767            depth_or_array_layers: 1,
3768        },
3769        mip_level_count: 1,
3770        sample_count: 1,
3771        dimension: wgpu::TextureDimension::D2,
3772        format: wgpu::TextureFormat::R8Unorm,
3773        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3774        view_formats: &[],
3775    });
3776    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3777    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
3778        label: Some("glyph atlas sampler A8"),
3779        address_mode_u: wgpu::AddressMode::ClampToEdge,
3780        address_mode_v: wgpu::AddressMode::ClampToEdge,
3781        address_mode_w: wgpu::AddressMode::ClampToEdge,
3782        mag_filter: wgpu::FilterMode::Linear,
3783        min_filter: wgpu::FilterMode::Linear,
3784        mipmap_filter: wgpu::MipmapFilterMode::Linear,
3785        ..Default::default()
3786    });
3787
3788    AtlasA8 {
3789        tex,
3790        view,
3791        sampler,
3792        size,
3793        next_x: 1,
3794        next_y: 1,
3795        row_h: 0,
3796        map: HashMap::new(),
3797    }
3798}
3799
3800fn init_atlas_color(device: &wgpu::Device) -> AtlasRGBA {
3801    let size = 1024u32;
3802    let tex = device.create_texture(&wgpu::TextureDescriptor {
3803        label: Some("glyph atlas RGBA"),
3804        size: wgpu::Extent3d {
3805            width: size,
3806            height: size,
3807            depth_or_array_layers: 1,
3808        },
3809        mip_level_count: 1,
3810        sample_count: 1,
3811        dimension: wgpu::TextureDimension::D2,
3812        format: wgpu::TextureFormat::Rgba8UnormSrgb,
3813        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3814        view_formats: &[],
3815    });
3816    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
3817    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
3818        label: Some("glyph atlas sampler RGBA"),
3819        address_mode_u: wgpu::AddressMode::ClampToEdge,
3820        address_mode_v: wgpu::AddressMode::ClampToEdge,
3821        address_mode_w: wgpu::AddressMode::ClampToEdge,
3822        mag_filter: wgpu::FilterMode::Linear,
3823        min_filter: wgpu::FilterMode::Linear,
3824        mipmap_filter: wgpu::MipmapFilterMode::Linear,
3825        ..Default::default()
3826    });
3827    AtlasRGBA {
3828        tex,
3829        view,
3830        sampler,
3831        size,
3832        next_x: 1,
3833        next_y: 1,
3834        row_h: 0,
3835        map: HashMap::new(),
3836    }
3837}
3838
3839#[cfg(feature = "winit-surface")]
3840impl RenderBackend for WgpuSurfaceBackend {
3841    fn configure_surface(&mut self, width: u32, height: u32) {
3842        if width == 0 || height == 0 {
3843            return;
3844        }
3845        self.renderer.output_width = width;
3846        self.renderer.output_height = height;
3847        if let Some(ref mut config) = self.surface_config {
3848            config.width = width;
3849            config.height = height;
3850        }
3851        if let (Some(surface), Some(config)) = (self.surface.as_ref(), self.surface_config.as_ref())
3852        {
3853            surface.configure(&self.renderer.device, config);
3854        }
3855        self.renderer.recreate_msaa_and_depth_stencil();
3856        self.renderer.recreate_working_space_texture();
3857    }
3858
3859    fn frame(&mut self, scene: &Scene, _glyph_cfg: GlyphRasterConfig) {
3860        let surface = self.surface.as_ref().expect("WgpuSurfaceBackend::frame() requires a surface (use from_device + render_to_view instead)");
3861        let surface_config = self
3862            .surface_config
3863            .as_ref()
3864            .expect("surface_config required for frame()");
3865
3866        self.renderer.frame_index = self.renderer.frame_index.wrapping_add(1);
3867        self.renderer.slug_cache.next_frame();
3868
3869        if self.renderer.output_width == 0 || self.renderer.output_height == 0 {
3870            return;
3871        }
3872
3873        let mut retries = 0u32;
3874        const MAX_RETRIES: u32 = 4;
3875        let frame = loop {
3876            match surface.get_current_texture() {
3877                wgpu::CurrentSurfaceTexture::Success(f) => break f,
3878                wgpu::CurrentSurfaceTexture::Suboptimal(f) => {
3879                    log::warn!("suboptimal surface; reconfiguring");
3880                    surface.configure(&self.renderer.device, surface_config);
3881                    break f;
3882                }
3883                wgpu::CurrentSurfaceTexture::Outdated => {
3884                    retries += 1;
3885                    if retries >= MAX_RETRIES {
3886                        log::warn!(
3887                            "surface outdated persisted after {MAX_RETRIES} retries; skipping frame"
3888                        );
3889                        return;
3890                    }
3891                    log::warn!("surface outdated; reconfiguring");
3892                    surface.configure(&self.renderer.device, surface_config);
3893                }
3894                wgpu::CurrentSurfaceTexture::Lost => {
3895                    retries += 1;
3896                    if retries >= MAX_RETRIES {
3897                        log::warn!(
3898                            "surface lost persisted after {MAX_RETRIES} retries; skipping frame"
3899                        );
3900                        return;
3901                    }
3902                    log::warn!("surface lost; reconfiguring");
3903                    surface.configure(&self.renderer.device, surface_config);
3904                }
3905                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
3906                    request_frame();
3907                    return;
3908                }
3909                wgpu::CurrentSurfaceTexture::Validation => {
3910                    retries += 1;
3911                    if retries >= MAX_RETRIES {
3912                        log::warn!(
3913                            "surface validation persisted after {MAX_RETRIES} retries; skipping frame"
3914                        );
3915                        return;
3916                    }
3917                    surface.configure(&self.renderer.device, surface_config);
3918                }
3919            }
3920        };
3921
3922        let swap_view = if let Some(view_format) = self
3923            .surface_config
3924            .as_ref()
3925            .and_then(|c| c.view_formats.iter().find(|f| f.is_srgb()).copied())
3926        {
3927            frame.texture.create_view(&wgpu::TextureViewDescriptor {
3928                format: Some(view_format),
3929                ..Default::default()
3930            })
3931        } else {
3932            frame
3933                .texture
3934                .create_view(&wgpu::TextureViewDescriptor::default())
3935        };
3936        let mut encoder =
3937            self.renderer
3938                .device
3939                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3940                    label: Some("frame encoder"),
3941                });
3942
3943        let clear_color = Some([
3944            scene.clear_color.0 as f64 / 255.0,
3945            scene.clear_color.1 as f64 / 255.0,
3946            scene.clear_color.2 as f64 / 255.0,
3947            scene.clear_color.3 as f64 / 255.0,
3948        ]);
3949
3950        self.renderer
3951            .render_scene_to_encoder(scene, &mut encoder, &swap_view, clear_color);
3952
3953        //NOTE: The WebGL HAL present path (fullscreen triangle / blit) does not
3954        // restore gl.colorMask. Hence this is needed to prevent frames from going transparent.
3955        {
3956            let _reset = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3957                label: Some("webgl color_mask reset before present"),
3958                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3959                    view: &swap_view,
3960                    resolve_target: None,
3961                    ops: wgpu::Operations {
3962                        load: wgpu::LoadOp::Load,
3963                        store: wgpu::StoreOp::Store,
3964                    },
3965                    depth_slice: None,
3966                })],
3967                depth_stencil_attachment: None,
3968                timestamp_writes: None,
3969                occlusion_query_set: None,
3970                multiview_mask: None,
3971            });
3972        }
3973
3974        self.renderer
3975            .queue
3976            .submit(std::iter::once(encoder.finish()));
3977        if let Err(e) = catch_unwind(AssertUnwindSafe(|| self.renderer.queue.present(frame))) {
3978            log::warn!("queue.present panicked: {:?}", e);
3979        }
3980    }
3981}
3982
3983impl WgpuSceneRenderer {
3984    fn upload_mesh_geometry(&mut self, mesh: &repose_core::VectorMeshData) -> (u64, u32, u64, u32) {
3985        let verts: Vec<MeshVertex> = mesh
3986            .vertices
3987            .iter()
3988            .map(|v| MeshVertex {
3989                pos: v.pos,
3990                color: v.color,
3991                uv: v.uv,
3992            })
3993            .collect();
3994        let vbytes = bytemuck::cast_slice(&verts);
3995        self.mesh_verts
3996            .grow_to_fit(&self.device, vbytes.len() as u64);
3997        let (voff, _) = self.mesh_verts.alloc_write(&self.queue, vbytes);
3998        let ibytes = bytemuck::cast_slice(&mesh.indices);
3999        self.mesh_indices
4000            .grow_to_fit(&self.device, ibytes.len() as u64);
4001        let (ioff, _) = self.mesh_indices.alloc_write(&self.queue, ibytes);
4002        (voff, verts.len() as u32, ioff, mesh.indices.len() as u32)
4003    }
4004
4005    fn alloc_mesh_uniform(&mut self, u: MeshUniform) -> u64 {
4006        if self.mesh_uniform_head + MESH_UNIFORM_SLOT > MESH_UNIFORM_CAP {
4007            log::warn!("mesh uniform buffer overflow; regenerating");
4008            self.recreate_mesh_uniform_buffer();
4009        }
4010        let slot = self.mesh_uniform_head;
4011        self.queue
4012            .write_buffer(&self.mesh_uniform_buf, slot, bytemuck::bytes_of(&u));
4013        self.mesh_uniform_head = slot + MESH_UNIFORM_SLOT;
4014        slot
4015    }
4016
4017    fn recreate_mesh_uniform_buffer(&mut self) {
4018        let new_cap = self.mesh_uniform_head + MESH_UNIFORM_SLOT;
4019        self.mesh_uniform_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
4020            label: Some("mesh uniform buffer"),
4021            size: new_cap,
4022            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
4023            mapped_at_creation: false,
4024        });
4025        self.mesh_bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
4026            label: Some("mesh uniform bind"),
4027            layout: &self.mesh_bind_layout,
4028            entries: &[wgpu::BindGroupEntry {
4029                binding: 0,
4030                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
4031                    buffer: &self.mesh_uniform_buf,
4032                    offset: 0,
4033                    size: NonZero::new(MESH_UNIFORM_SLOT),
4034                }),
4035            }],
4036        });
4037        self.mesh_uniform_head = 0;
4038    }
4039
4040    #[allow(clippy::too_many_arguments)]
4041    fn emit_vector_mesh(
4042        &mut self,
4043        current_transform: &Transform,
4044        mesh: &repose_core::VectorMeshData,
4045        transform: [f32; 6],
4046        paint: &repose_core::PaintDesc,
4047        cmds: &mut Vec<Cmd>,
4048    ) {
4049        let affine = combine_mesh_affine(current_transform, transform);
4050        let (voff, vcnt, ioff, icnt) = self.upload_mesh_geometry(mesh);
4051        let uoff = self.alloc_mesh_uniform(mesh_uniform_from_paint(affine, paint));
4052        cmds.push(Cmd::VectorMesh {
4053            voff,
4054            vcnt,
4055            ioff,
4056            icnt,
4057            uoff,
4058        });
4059    }
4060
4061    pub fn render_scene_to_encoder(
4062        &mut self,
4063        scene: &Scene,
4064        encoder: &mut wgpu::CommandEncoder,
4065        target_view: &wgpu::TextureView,
4066        clear_color_override: Option<[f64; 4]>,
4067    ) {
4068        fn to_ndc(x: f32, y: f32, w: f32, h: f32, fb_w: f32, fb_h: f32) -> [f32; 4] {
4069            let x0 = (x / fb_w) * 2.0 - 1.0;
4070            let y0 = 1.0 - (y / fb_h) * 2.0;
4071            let x1 = ((x + w) / fb_w) * 2.0 - 1.0;
4072            let y1 = 1.0 - ((y + h) / fb_h) * 2.0;
4073            let min_x = x0.min(x1);
4074            let min_y = y0.min(y1);
4075            let w_ndc = (x1 - x0).abs();
4076            let h_ndc = (y1 - y0).abs();
4077            [min_x, min_y, w_ndc, h_ndc]
4078        }
4079
4080        /// Convert a local-space rect + transform to NDC center-based position+size and rotation.
4081        fn rect_to_instance_ndc(
4082            rect: repose_core::Rect,
4083            transform: &Transform,
4084            fb_w: f32,
4085            fb_h: f32,
4086        ) -> ([f32; 4], [f32; 2]) {
4087            let cx = rect.x + rect.w * 0.5;
4088            let cy = rect.y + rect.h * 0.5;
4089
4090            let sx = cx * transform.scale_x;
4091            let sy = cy * transform.scale_y;
4092            let cos_a = transform.rotate.cos();
4093            let sin_a = transform.rotate.sin();
4094            let tx = sx * cos_a - sy * sin_a + transform.translate_x;
4095            let ty = sx * sin_a + sy * cos_a + transform.translate_y;
4096
4097            // NDC center
4098            let ndc_cx = (tx / fb_w) * 2.0 - 1.0;
4099            let ndc_cy = 1.0 - (ty / fb_h) * 2.0;
4100            // NDC size (after scale only, no rotation - rotation is done in shader)
4101            let ndc_w = (rect.w * transform.scale_x / fb_w) * 2.0;
4102            let ndc_h = (rect.h * transform.scale_y / fb_h) * 2.0;
4103
4104            ([ndc_cx, ndc_cy, ndc_w, ndc_h], [cos_a, sin_a])
4105        }
4106
4107        fn to_scissor(r: &repose_core::Rect, fb_w: u32, fb_h: u32) -> (u32, u32, u32, u32) {
4108            let mut x = r.x.floor() as i64;
4109            let mut y = r.y.floor() as i64;
4110            let fb_wi = fb_w as i64;
4111            let fb_hi = fb_h as i64;
4112            x = x.clamp(0, fb_wi.saturating_sub(1));
4113            y = y.clamp(0, fb_hi.saturating_sub(1));
4114            let w_req = r.w.ceil().max(1.0) as i64;
4115            let h_req = r.h.ceil().max(1.0) as i64;
4116            let w = (w_req).min(fb_wi - x).max(1);
4117            let h = (h_req).min(fb_hi - y).max(1);
4118            (x as u32, y as u32, w as u32, h as u32)
4119        }
4120
4121        let fb_w = self.output_width as f32;
4122        let fb_h = self.output_height as f32;
4123
4124        let mut passes: Vec<Pass> = Vec::with_capacity(1);
4125        let clear_color = clear_color_override.unwrap_or_else(|| {
4126            [
4127                scene.clear_color.0 as f64 / 255.0,
4128                scene.clear_color.1 as f64 / 255.0,
4129                scene.clear_color.2 as f64 / 255.0,
4130                scene.clear_color.3 as f64 / 255.0,
4131            ]
4132        });
4133        let mut current_pass: Pass = Pass {
4134            target: PassTarget::Surface,
4135            initial_scissor: (0, 0, self.output_width, self.output_height),
4136            clear_color: Some([
4137                clear_color[0] as f32,
4138                clear_color[1] as f32,
4139                clear_color[2] as f32,
4140                clear_color[3] as f32,
4141            ]),
4142            cmds: Vec::with_capacity(scene.nodes.len()),
4143        };
4144        let mut target_stack: Vec<PassTarget> = Vec::new();
4145        let mut layer_alphas: Vec<(u32, f32, (u32, u32, u32, u32))> = Vec::new();
4146        let mut layer_blurs: Vec<(u32, f32, f32)> = Vec::new();
4147        let mut current_target_size: (f32, f32) = (fb_w, fb_h);
4148
4149        struct Batch {
4150            rects: Vec<RectInstance>,
4151            borders: Vec<BorderInstance>,
4152            ellipses: Vec<EllipseInstance>,
4153            e_borders: Vec<EllipseBorderInstance>,
4154            arcs: Vec<ArcInstance>,
4155            masks: Vec<GlyphInstance>,
4156            colors: Vec<GlyphInstance>,
4157            nv12s: Vec<Nv12Instance>,
4158        }
4159
4160        impl Batch {
4161            fn new() -> Self {
4162                Self {
4163                    rects: vec![],
4164                    borders: vec![],
4165                    ellipses: vec![],
4166                    e_borders: vec![],
4167                    arcs: vec![],
4168                    masks: vec![],
4169                    colors: vec![],
4170                    nv12s: vec![],
4171                }
4172            }
4173
4174            fn is_empty(&self) -> bool {
4175                self.rects.is_empty()
4176                    && self.borders.is_empty()
4177                    && self.ellipses.is_empty()
4178                    && self.e_borders.is_empty()
4179                    && self.arcs.is_empty()
4180                    && self.masks.is_empty()
4181                    && self.colors.is_empty()
4182                    && self.nv12s.is_empty()
4183            }
4184
4185            fn flush(
4186                &mut self,
4187                pipes: (
4188                    &mut InstancedPipe<RectInstance>,
4189                    &mut InstancedPipe<BorderInstance>,
4190                    &mut InstancedPipe<EllipseInstance>,
4191                    &mut InstancedPipe<EllipseBorderInstance>,
4192                    &mut InstancedPipe<ArcInstance>,
4193                ),
4194                glyph_pipes: (
4195                    &mut InstancedPipe<GlyphInstance>,
4196                    &mut InstancedPipe<GlyphInstance>,
4197                ),
4198                nv12_pipe: &mut InstancedPipe<Nv12Instance>,
4199                device: &wgpu::Device,
4200                queue: &wgpu::Queue,
4201                cmds: &mut Vec<Cmd>,
4202            ) {
4203                let (rects, borders, ellipses, e_borders, arcs) = pipes;
4204                let (masks, colors) = glyph_pipes;
4205
4206                macro_rules! flush_one {
4207                    ($buf:ident, $pipe:expr, $variant:ident) => {
4208                        if !self.$buf.is_empty() {
4209                            if let Some((off, cnt)) = $pipe.upload(device, queue, &self.$buf) {
4210                                cmds.push(Cmd::$variant { off, cnt });
4211                            }
4212                            self.$buf.clear();
4213                        }
4214                    };
4215                }
4216
4217                flush_one!(rects, rects, Rect);
4218                flush_one!(borders, borders, Border);
4219                flush_one!(ellipses, ellipses, Ellipse);
4220                flush_one!(e_borders, e_borders, EllipseBorder);
4221                flush_one!(arcs, arcs, Arc);
4222                flush_one!(masks, masks, GlyphsMask);
4223                flush_one!(colors, colors, GlyphsColor);
4224
4225                if !self.nv12s.is_empty() {
4226                    if let Some((off, cnt)) = nv12_pipe.upload(device, queue, &self.nv12s) {
4227                        let _ = (off, cnt);
4228                    }
4229                    self.nv12s.clear();
4230                }
4231            }
4232        }
4233
4234        self.rects.reset();
4235        self.borders.reset();
4236        self.ellipses.reset();
4237        self.ellipse_borders.reset();
4238        self.arcs.reset();
4239        self.glyph_mask.reset();
4240        self.glyph_color.reset();
4241        self.clip_ring.reset();
4242        self.blur_ring.reset();
4243        self.nv12.reset();
4244
4245        self.slug_ring.reset();
4246        self.mesh_verts.reset();
4247        self.mesh_indices.reset();
4248        self.mesh_uniform_head = 0;
4249        self.mesh_clip_stack.clear();
4250        let mut batch = Batch::new();
4251        let mut slug_verts_local: Vec<slug::TessVertex> = Vec::new();
4252        let mut transform_stack: Vec<Transform> = vec![Transform::identity()];
4253        let mut scissor_stack: Vec<repose_core::Rect> = Vec::with_capacity(8);
4254        // NOTE: Records the clip instance range + flags of each active rounded-rect clip
4255        // so PopClip can re-stamp the stencil with a decrement pass (mirroring
4256        // VectorClipPop). Keys: (off, cnt, difference, rounded).
4257        let mut clip_cmd_stack: Vec<(u64, u32, bool)> = Vec::with_capacity(8);
4258        let mut root_clip_rect = repose_core::Rect {
4259            x: 0.0,
4260            y: 0.0,
4261            w: fb_w,
4262            h: fb_h,
4263        };
4264        let mut saved_scissor_stack: Vec<repose_core::Rect> = Vec::new();
4265        let mut saved_root_clip_rect = root_clip_rect;
4266
4267        let mut current_prim: Option<&'static str> = None;
4268
4269        macro_rules! flush_if_prim_changed {
4270            ($prim:literal, $pipe:expr) => {
4271                if current_prim != Some($prim) {
4272                    flush_batch!();
4273                    current_prim = Some($prim);
4274                }
4275            };
4276        }
4277
4278        macro_rules! flush_batch {
4279            () => {
4280                if !batch.is_empty() {
4281                    batch.flush(
4282                        (
4283                            &mut self.rects,
4284                            &mut self.borders,
4285                            &mut self.ellipses,
4286                            &mut self.ellipse_borders,
4287                            &mut self.arcs,
4288                        ),
4289                        (&mut self.glyph_mask, &mut self.glyph_color),
4290                        &mut self.nv12,
4291                        &self.device,
4292                        &self.queue,
4293                        &mut current_pass.cmds,
4294                    )
4295                }
4296            };
4297        }
4298        for node in &scene.nodes {
4299            let t_identity = Transform::identity();
4300            let current_transform = transform_stack.last().unwrap_or(&t_identity);
4301
4302            match node {
4303                SceneNode::Rect {
4304                    rect,
4305                    brush,
4306                    radius,
4307                } => {
4308                    flush_if_prim_changed!("rect", &self.rects);
4309                    let (ndc, sin_cos) = rect_to_instance_ndc(
4310                        *rect,
4311                        current_transform,
4312                        current_target_size.0,
4313                        current_target_size.1,
4314                    );
4315                    let (brush_type, color0, color1, grad_start, grad_end) =
4316                        brush_to_instance_fields(brush);
4317                    batch.rects.push(RectInstance {
4318                        xywh: ndc,
4319                        radii: *radius,
4320                        brush_type,
4321                        _pad: [0.0; 3],
4322                        color0,
4323                        color1,
4324                        grad_start,
4325                        grad_end,
4326                        sin_cos,
4327                    });
4328                }
4329                SceneNode::Border {
4330                    rect,
4331                    color,
4332                    width,
4333                    radius,
4334                } => {
4335                    flush_if_prim_changed!("border", &self.borders);
4336                    let (ndc, sin_cos) = rect_to_instance_ndc(
4337                        *rect,
4338                        current_transform,
4339                        current_target_size.0,
4340                        current_target_size.1,
4341                    );
4342                    batch.borders.push(BorderInstance {
4343                        xywh: ndc,
4344                        radii: *radius,
4345                        stroke: *width,
4346                        color: color.to_linear(),
4347                        sin_cos,
4348                    });
4349                }
4350                SceneNode::Ellipse { rect, brush } => {
4351                    flush_if_prim_changed!("ellipse", &self.ellipses);
4352                    let (ndc, sin_cos) = rect_to_instance_ndc(
4353                        *rect,
4354                        current_transform,
4355                        current_target_size.0,
4356                        current_target_size.1,
4357                    );
4358                    let color = brush_to_solid_color(brush);
4359                    batch.ellipses.push(EllipseInstance {
4360                        xywh: ndc,
4361                        color,
4362                        sin_cos,
4363                    });
4364                }
4365                SceneNode::EllipseBorder { rect, color, width } => {
4366                    flush_if_prim_changed!("ellipse_border", &self.ellipse_borders);
4367                    let (ndc, sin_cos) = rect_to_instance_ndc(
4368                        *rect,
4369                        current_transform,
4370                        current_target_size.0,
4371                        current_target_size.1,
4372                    );
4373                    let pad_px = *width * 0.5 + 2.0;
4374                    let pad = (pad_px / current_target_size.0) * 2.0;
4375                    batch.e_borders.push(EllipseBorderInstance {
4376                        xywh: ndc,
4377                        stroke: *width,
4378                        pad,
4379                        color: color.to_linear(),
4380                        sin_cos,
4381                    });
4382                }
4383                SceneNode::Arc {
4384                    rect,
4385                    start_angle,
4386                    sweep_angle,
4387                    stroke_width,
4388                    color,
4389                    cap,
4390                } => {
4391                    flush_if_prim_changed!("arc", &self.arcs);
4392                    let (ndc, sin_cos) = rect_to_instance_ndc(
4393                        *rect,
4394                        current_transform,
4395                        current_target_size.0,
4396                        current_target_size.1,
4397                    );
4398                    let pad_px = *stroke_width * 0.5 + 2.0;
4399                    let pad = (pad_px / current_target_size.0) * 2.0;
4400                    let cap_val = match cap {
4401                        StrokeCap::Butt => 0.0,
4402                        StrokeCap::Round => 1.0,
4403                        StrokeCap::Square => 2.0,
4404                    };
4405                    batch.arcs.push(ArcInstance {
4406                        xywh: ndc,
4407                        start_angle: *start_angle,
4408                        sweep_angle: *sweep_angle,
4409                        stroke: *stroke_width,
4410                        pad,
4411                        color: color.to_linear(),
4412                        sin_cos,
4413                        cap: cap_val,
4414                    });
4415                }
4416                SceneNode::Text {
4417                    rect,
4418                    text,
4419                    color,
4420                    size,
4421                    font_family,
4422                    text_align: _,
4423                    font_weight,
4424                    font_style,
4425                    text_decoration,
4426                    letter_spacing,
4427                    line_height: _,
4428                    extra_style,
4429                    url: _,
4430                    font_variation_settings,
4431                } => {
4432                    flush_batch!(); // flush any prior primitives
4433
4434                    let px = *size;
4435                    let lh_ratio = rect.h / px;
4436                    let fw = font_weight.0;
4437                    let fs = if *font_style == FontStyle::Italic {
4438                        1
4439                    } else {
4440                        0
4441                    };
4442                    let shaped = repose_text::shape_line(
4443                        text.as_ref(),
4444                        px,
4445                        lh_ratio,
4446                        *font_family,
4447                        fw,
4448                        fs,
4449                        *letter_spacing,
4450                        font_variation_settings.as_deref(),
4451                    );
4452                    let baseline_y = shaped.first().map(|g| rect.y + g.y);
4453
4454                    let cos_a = current_transform.rotate.cos();
4455                    let sin_a = current_transform.rotate.sin();
4456                    let has_rotation = current_transform.rotate != 0.0;
4457
4458                    // For rotated text, the pivot is the center of the text rect.
4459                    let pivot_x = rect.x + rect.w * 0.5;
4460                    let pivot_y = rect.y + rect.h * 0.5;
4461
4462                    // Helper: compute NDC for a glyph rect, handling rotation correctly.
4463                    let make_glyph_instance =
4464                        |gx: f32, gy: f32, gw: f32, gh: f32| -> ([f32; 4], [f32; 2]) {
4465                            if has_rotation {
4466                                let corners =
4467                                    [(gx, gy), (gx + gw, gy), (gx + gw, gy + gh), (gx, gy + gh)];
4468                                let mut min_x = f32::MAX;
4469                                let mut max_x = f32::MIN;
4470                                let mut min_y = f32::MAX;
4471                                let mut max_y = f32::MIN;
4472                                for &(x, y) in &corners {
4473                                    let dx = x - pivot_x;
4474                                    let dy = y - pivot_y;
4475                                    let rx = pivot_x + dx * cos_a - dy * sin_a;
4476                                    let ry = pivot_y + dx * sin_a + dy * cos_a;
4477                                    min_x = min_x.min(rx);
4478                                    max_x = max_x.max(rx);
4479                                    min_y = min_y.min(ry);
4480                                    max_y = max_y.max(ry);
4481                                }
4482                                let bb_w = max_x - min_x;
4483                                let bb_h = max_y - min_y;
4484                                let ndc_tl = to_ndc(
4485                                    min_x,
4486                                    min_y,
4487                                    bb_w,
4488                                    bb_h,
4489                                    current_target_size.0,
4490                                    current_target_size.1,
4491                                );
4492                                let ndc = [
4493                                    ndc_tl[0] + ndc_tl[2] * 0.5,
4494                                    ndc_tl[1] + ndc_tl[3] * 0.5,
4495                                    ndc_tl[2],
4496                                    ndc_tl[3],
4497                                ];
4498                                (ndc, [cos_a, sin_a])
4499                            } else {
4500                                // Only safe at 1:1 scale (no zoom animations active).
4501                                let (sx, sy) = if current_transform.scale_x == 1.0
4502                                    && current_transform.scale_y == 1.0
4503                                {
4504                                    (gx.round(), gy.round())
4505                                } else {
4506                                    (gx, gy)
4507                                };
4508                                rect_to_instance_ndc(
4509                                    repose_core::Rect {
4510                                        x: sx,
4511                                        y: sy,
4512                                        w: gw,
4513                                        h: gh,
4514                                    },
4515                                    current_transform,
4516                                    current_target_size.0,
4517                                    current_target_size.1,
4518                                )
4519                            }
4520                        };
4521
4522                    let baseline_shift_y: f32 = px * extra_style.baseline_shift.0;
4523
4524                    let (
4525                        is_stroke,
4526                        stroke_width,
4527                        stroke_cap,
4528                        stroke_join,
4529                        stroke_miter,
4530                        stroke_path_effect,
4531                    ) = match &extra_style.draw_style {
4532                        repose_core::DrawStyle::Stroke {
4533                            width,
4534                            cap,
4535                            join,
4536                            miter,
4537                            path_effect,
4538                        } => (true, *width, *cap, *join, *miter, path_effect.clone()),
4539                        _ => (
4540                            false,
4541                            0.0,
4542                            repose_core::StrokeCap::Butt,
4543                            repose_core::StrokeJoin::Miter,
4544                            4.0,
4545                            None,
4546                        ),
4547                    };
4548                    let stroke_tess_key = if is_stroke {
4549                        Some(slug::StrokeTessKey::new(
4550                            stroke_width,
4551                            stroke_cap,
4552                            stroke_join,
4553                            stroke_miter,
4554                            &stroke_path_effect,
4555                        ))
4556                    } else {
4557                        None
4558                    };
4559
4560                    for sg in shaped {
4561                        let gx = rect.x + sg.x + sg.bearing_x;
4562                        let gy = rect.y + sg.y - sg.bearing_y + baseline_shift_y;
4563
4564                        // Vector glyph path: tessellated geometry with MSAA.
4565                        if self.slug_enabled {
4566                            let ck = repose_text::lookup_cache_key(sg.key, sg.px);
4567                            if let Some(ref ck) = ck {
4568                                // Check if cached.
4569                                let need_tessellate = self.slug_cache.get(ck).is_none_or(|g| {
4570                                    if is_stroke {
4571                                        let key = stroke_tess_key.as_ref().unwrap();
4572                                        !g.stroke_variants.contains_key(key)
4573                                    } else {
4574                                        g.fill_vertices.is_none()
4575                                    }
4576                                });
4577                                if need_tessellate {
4578                                    if let Some((ck2, commands)) =
4579                                        repose_text::lookup_and_extract_outline(sg.key, sg.px)
4580                                    {
4581                                        let font_size_px = f32::from_bits(ck2.font_size_bits);
4582                                        if is_stroke {
4583                                            self.slug_cache.get_or_insert_stroke(
4584                                                ck2,
4585                                                font_size_px,
4586                                                &commands,
4587                                                stroke_width,
4588                                                stroke_cap,
4589                                                stroke_join,
4590                                                stroke_miter,
4591                                                &stroke_path_effect,
4592                                            );
4593                                        } else {
4594                                            self.slug_cache.get_or_insert(
4595                                                ck2,
4596                                                font_size_px,
4597                                                &commands,
4598                                            );
4599                                        }
4600                                    }
4601                                } else {
4602                                    self.slug_cache.touch(ck);
4603                                }
4604                            }
4605                            if let Some(entry) = ck.as_ref().and_then(|ck| self.slug_cache.get(ck))
4606                            {
4607                                let ox = rect.x + sg.x;
4608                                let oy = rect.y + sg.y + baseline_shift_y;
4609                                let scx = current_transform.scale_x;
4610                                let scy = current_transform.scale_y;
4611                                let ttx = current_transform.translate_x;
4612                                let tty = current_transform.translate_y;
4613
4614                                let tf = |x: f32, y: f32| -> (f32, f32) {
4615                                    if has_rotation {
4616                                        let dx = x - pivot_x;
4617                                        let dy = y - pivot_y;
4618                                        let rx = pivot_x + dx * cos_a - dy * sin_a;
4619                                        let ry = pivot_y + dx * sin_a + dy * cos_a;
4620                                        (rx, ry)
4621                                    } else {
4622                                        (x * scx + ttx, y * scy + tty)
4623                                    }
4624                                };
4625
4626                                let tw = current_target_size.0;
4627                                let th = current_target_size.1;
4628
4629                                let verts = if is_stroke {
4630                                    let key = stroke_tess_key.as_ref().unwrap();
4631                                    entry
4632                                        .stroke_variants
4633                                        .get(key)
4634                                        .map(|v| v.as_slice())
4635                                        .unwrap_or(&[])
4636                                } else {
4637                                    entry.fill_vertices.as_deref().unwrap_or(&[])
4638                                };
4639
4640                                for &v in verts {
4641                                    let (sx, sy) = tf(ox + v[0] * px, oy - v[1] * px);
4642                                    let ndc_x = sx / tw * 2.0 - 1.0;
4643                                    let ndc_y = -(sy / th) * 2.0 + 1.0;
4644                                    slug_verts_local.push(slug::TessVertex {
4645                                        ndc_pos: [ndc_x, ndc_y],
4646                                        color: color.to_linear(),
4647                                    });
4648                                }
4649
4650                                if is_stroke {
4651                                    // Stroke glyphs cannot use atlas fallback...
4652                                    continue;
4653                                }
4654                                continue;
4655                            }
4656                        }
4657
4658                        // Don't use atlas fallback for strokes too
4659                        if is_stroke {
4660                            continue;
4661                        }
4662
4663                        // Atlas fallback: color emoji + failed slug extraction
4664                        if let Some(info) = self.upload_glyph_color(sg.key, sg.px) {
4665                            let (ndc, sin_cos) = make_glyph_instance(gx, gy, info.w, info.h);
4666                            batch.colors.push(GlyphInstance {
4667                                xywh: ndc,
4668                                uv: [info.u0, info.v1, info.u1, info.v0],
4669                                color: color.to_linear(),
4670                                sin_cos,
4671                            });
4672                        } else if let Some(info) = self.upload_glyph_mask(sg.key, sg.px) {
4673                            let (ndc, sin_cos) = make_glyph_instance(gx, gy, info.w, info.h);
4674                            batch.masks.push(GlyphInstance {
4675                                xywh: ndc,
4676                                uv: [info.u0, info.v1, info.u1, info.v0],
4677                                color: color.to_linear(),
4678                                sin_cos,
4679                            });
4680                        }
4681                    }
4682
4683                    // Upload slug vertices if any
4684                    if !slug_verts_local.is_empty() {
4685                        let bytes = bytemuck::cast_slice(&slug_verts_local);
4686                        self.slug_ring.grow_to_fit(&self.device, bytes.len() as u64);
4687                        let (off, _) = self.slug_ring.alloc_write(&self.queue, bytes);
4688                        current_pass.cmds.push(Cmd::GlyphsVector {
4689                            off,
4690                            cnt: slug_verts_local.len() as u32,
4691                        });
4692                        slug_verts_local.clear();
4693                    }
4694
4695                    // Text decoration: underline / strikethrough
4696                    if (text_decoration.underline || text_decoration.strikethrough)
4697                        && let Some(baseline_y) = baseline_y
4698                    {
4699                        flush_batch!();
4700                        current_prim = Some("rect");
4701                        let deco_color = text_decoration.color.unwrap_or(*color);
4702                        let thickness = (px * 0.07).max(1.0);
4703
4704                        if text_decoration.underline {
4705                            let dy = baseline_y + px * 0.1;
4706                            let (ndc, sin_cos) = rect_to_instance_ndc(
4707                                repose_core::Rect {
4708                                    x: rect.x,
4709                                    y: dy,
4710                                    w: rect.w,
4711                                    h: thickness,
4712                                },
4713                                current_transform,
4714                                current_target_size.0,
4715                                current_target_size.1,
4716                            );
4717                            batch.rects.push(RectInstance {
4718                                xywh: ndc,
4719                                radii: [0.0; 4],
4720                                brush_type: 0,
4721                                _pad: [0.0; 3],
4722                                color0: deco_color.to_linear(),
4723                                color1: [0.0; 4],
4724                                grad_start: [0.0; 2],
4725                                grad_end: [0.0; 2],
4726                                sin_cos,
4727                            });
4728                        }
4729                        if text_decoration.strikethrough {
4730                            let sy = baseline_y - px * 0.3;
4731                            let (ndc, sin_cos) = rect_to_instance_ndc(
4732                                repose_core::Rect {
4733                                    x: rect.x,
4734                                    y: sy,
4735                                    w: rect.w,
4736                                    h: thickness,
4737                                },
4738                                current_transform,
4739                                current_target_size.0,
4740                                current_target_size.1,
4741                            );
4742                            batch.rects.push(RectInstance {
4743                                xywh: ndc,
4744                                radii: [0.0; 4],
4745                                brush_type: 0,
4746                                _pad: [0.0; 3],
4747                                color0: deco_color.to_linear(),
4748                                color1: [0.0; 4],
4749                                grad_start: [0.0; 2],
4750                                grad_end: [0.0; 2],
4751                                sin_cos,
4752                            });
4753                        }
4754                    }
4755                }
4756                SceneNode::Image {
4757                    rect,
4758                    handle,
4759                    tint,
4760                    fit,
4761                } => {
4762                    flush_batch!();
4763
4764                    // Update usage timestamp for eviction, lazily re-uploading
4765                    // evicted RGBA images from their retained source.
4766                    let (img_w, img_h, is_nv12) = match self.resolve_image_for_draw(*handle) {
4767                        Some(wh) => wh,
4768                        None => {
4769                            log::warn!("Image handle {} not found", handle);
4770                            continue;
4771                        }
4772                    };
4773
4774                    let src_w = img_w as f32;
4775                    let src_h = img_h as f32;
4776
4777                    let dst_w = rect.w.max(0.0);
4778                    let dst_h = rect.h.max(0.0);
4779                    if dst_w <= 0.0 || dst_h <= 0.0 {
4780                        continue;
4781                    }
4782
4783                    let (draw_rect, uv_rect) = match fit {
4784                        repose_core::view::ImageFit::Contain => {
4785                            let scale = (dst_w / src_w).min(dst_h / src_h);
4786                            let w = src_w * scale;
4787                            let h = src_h * scale;
4788                            (
4789                                repose_core::Rect {
4790                                    x: rect.x + (dst_w - w) * 0.5,
4791                                    y: rect.y + (dst_h - h) * 0.5,
4792                                    w,
4793                                    h,
4794                                },
4795                                [0.0, 1.0, 1.0, 0.0],
4796                            )
4797                        }
4798                        repose_core::view::ImageFit::Cover => {
4799                            let scale = (dst_w / src_w).max(dst_h / src_h);
4800                            let content_w = src_w * scale;
4801                            let content_h = src_h * scale;
4802                            let overflow_x = (content_w - dst_w) * 0.5;
4803                            let overflow_y = (content_h - dst_h) * 0.5;
4804                            let u0 = (overflow_x / content_w).clamp(0.0, 1.0);
4805                            let v0 = (overflow_y / content_h).clamp(0.0, 1.0);
4806                            let u1 = ((overflow_x + dst_w) / content_w).clamp(0.0, 1.0);
4807                            let v1 = ((overflow_y + dst_h) / content_h).clamp(0.0, 1.0);
4808                            (*rect, [u0, 1.0 - v0, u1, 1.0 - v1])
4809                        }
4810                        repose_core::view::ImageFit::FitWidth => {
4811                            let scale = dst_w / src_w;
4812                            (
4813                                repose_core::Rect {
4814                                    x: rect.x,
4815                                    y: rect.y + (dst_h - src_h * scale) * 0.5,
4816                                    w: dst_w,
4817                                    h: src_h * scale,
4818                                },
4819                                [0.0, 1.0, 1.0, 0.0],
4820                            )
4821                        }
4822                        repose_core::view::ImageFit::FitHeight => {
4823                            let scale = dst_h / src_h;
4824                            (
4825                                repose_core::Rect {
4826                                    x: rect.x + (dst_w - src_w * scale) * 0.5,
4827                                    y: rect.y,
4828                                    w: src_w * scale,
4829                                    h: dst_h,
4830                                },
4831                                [0.0, 1.0, 1.0, 0.0],
4832                            )
4833                        }
4834                        repose_core::view::ImageFit::FillBounds => (*rect, [0.0, 1.0, 1.0, 0.0]),
4835                        repose_core::view::ImageFit::Inside => {
4836                            let scale = (dst_w / src_w).min(dst_h / src_h).min(1.0);
4837                            let w = src_w * scale;
4838                            let h = src_h * scale;
4839                            (
4840                                repose_core::Rect {
4841                                    x: rect.x + (dst_w - w) * 0.5,
4842                                    y: rect.y + (dst_h - h) * 0.5,
4843                                    w,
4844                                    h,
4845                                },
4846                                [0.0, 1.0, 1.0, 0.0],
4847                            )
4848                        }
4849                        repose_core::view::ImageFit::None => {
4850                            (
4851                                repose_core::Rect {
4852                                    x: rect.x,
4853                                    y: rect.y,
4854                                    w: src_w.min(dst_w),
4855                                    h: src_h.min(dst_h),
4856                                },
4857                                // If larger than dst, crop top-left of source:
4858                                [
4859                                    0.0,
4860                                    1.0,
4861                                    (dst_w / src_w).min(1.0),
4862                                    1.0 - (dst_h / src_h).min(1.0),
4863                                ],
4864                            )
4865                        }
4866                        _ => continue,
4867                    };
4868
4869                    let (ndc_center, sin_cos) = rect_to_instance_ndc(
4870                        draw_rect,
4871                        current_transform,
4872                        current_target_size.0,
4873                        current_target_size.1,
4874                    );
4875
4876                    if is_nv12 {
4877                        let uv_x_offset = if let Some(ImageTex::Nv12 { w, color_info, .. }) =
4878                            self.images.get(handle)
4879                        {
4880                            match color_info.chroma_siting {
4881                                ChromaSiting::Center | ChromaSiting::TopLeft => 0.0,
4882                                ChromaSiting::Left => -1.0 / *w as f32,
4883                            }
4884                        } else {
4885                            0.0
4886                        };
4887
4888                        let inst = Nv12Instance {
4889                            xywh: ndc_center,
4890                            uv: uv_rect,
4891                            color: tint.to_linear(),
4892                            uv_x_offset,
4893                            sin_cos,
4894                            _pad: [0.0],
4895                        };
4896                        if let Some((off, _)) = self.nv12.upload(&self.device, &self.queue, &[inst])
4897                        {
4898                            current_pass.cmds.push(Cmd::ImageNv12 {
4899                                off,
4900                                cnt: 1,
4901                                handle: *handle,
4902                            });
4903                        }
4904                    } else {
4905                        // RGBA uses GlyphInstance struct (reused pipeline)
4906                        let inst = GlyphInstance {
4907                            xywh: ndc_center,
4908                            uv: uv_rect,
4909                            color: tint.to_linear(),
4910                            sin_cos,
4911                        };
4912                        if let Some((off, _)) =
4913                            self.glyph_color.upload(&self.device, &self.queue, &[inst])
4914                        {
4915                            current_pass.cmds.push(Cmd::ImageRgba {
4916                                off,
4917                                cnt: 1,
4918                                handle: *handle,
4919                            });
4920                        }
4921                    }
4922                }
4923                SceneNode::PushClip { rect, radius, op } => {
4924                    flush_batch!(); // flush content before entering clip
4925
4926                    let is_diff = matches!(op, repose_core::ClipOp::Difference);
4927
4928                    let t_identity = Transform::identity();
4929                    let current_transform = transform_stack.last().unwrap_or(&t_identity);
4930                    let transformed = current_transform.apply_to_rect(*rect);
4931
4932                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
4933                    let next_scissor = if is_diff {
4934                        top
4935                    } else {
4936                        intersect(top, transformed)
4937                    };
4938                    scissor_stack.push(next_scissor);
4939                    let scissor = to_scissor(
4940                        &next_scissor,
4941                        current_target_size.0 as u32,
4942                        current_target_size.1 as u32,
4943                    );
4944
4945                    let clip_ndc_tl = to_ndc(
4946                        transformed.x,
4947                        transformed.y,
4948                        transformed.w,
4949                        transformed.h,
4950                        current_target_size.0,
4951                        current_target_size.1,
4952                    );
4953                    let inst = ClipInstance {
4954                        xywh: [
4955                            clip_ndc_tl[0] + clip_ndc_tl[2] * 0.5,
4956                            clip_ndc_tl[1] + clip_ndc_tl[3] * 0.5,
4957                            clip_ndc_tl[2],
4958                            clip_ndc_tl[3],
4959                        ],
4960                        radii: *radius,
4961                        sin_cos: [1.0, 0.0],
4962                    };
4963                    let bytes = bytemuck::bytes_of(&inst);
4964                    self.clip_ring.grow_to_fit(&self.device, bytes.len() as u64);
4965                    let (off, _) = self.clip_ring.alloc_write(&self.queue, bytes);
4966
4967                    let rounded = radius.iter().any(|&r| r > 0.5);
4968
4969                    current_pass.cmds.push(Cmd::ClipPush {
4970                        off,
4971                        cnt: 1,
4972                        scissor,
4973                        difference: is_diff,
4974                        rounded,
4975                    });
4976                    clip_cmd_stack.push((off, 1, is_diff));
4977                }
4978                SceneNode::PopClip => {
4979                    flush_batch!();
4980
4981                    if !scissor_stack.is_empty() {
4982                        scissor_stack.pop();
4983                    } else {
4984                        log::warn!("PopClip with empty stack");
4985                    }
4986
4987                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
4988                    let scissor = to_scissor(
4989                        &top,
4990                        current_target_size.0 as u32,
4991                        current_target_size.1 as u32,
4992                    );
4993                    let (off, cnt, difference) = clip_cmd_stack.pop().unwrap_or((0, 0, false));
4994                    current_pass.cmds.push(Cmd::ClipPop {
4995                        off,
4996                        cnt,
4997                        scissor,
4998                        difference,
4999                    });
5000                }
5001                SceneNode::Shadow {
5002                    rect,
5003                    radius,
5004                    elevation: _,
5005                    color,
5006                } => {
5007                    flush_if_prim_changed!("rect", &self.rects);
5008                    let (ndc, sin_cos) = rect_to_instance_ndc(
5009                        *rect,
5010                        current_transform,
5011                        current_target_size.0,
5012                        current_target_size.1,
5013                    );
5014                    let (brush_type, color0, _color1, _grad_start, _grad_end) =
5015                        brush_to_instance_fields(&Brush::Solid(*color));
5016                    batch.rects.push(RectInstance {
5017                        xywh: ndc,
5018                        radii: *radius,
5019                        brush_type,
5020                        _pad: [0.0; 3],
5021                        color0,
5022                        color1: [0.0; 4],
5023                        grad_start: [0.0; 2],
5024                        grad_end: [0.0; 2],
5025                        sin_cos,
5026                    });
5027                }
5028                SceneNode::PushTransform { transform } => {
5029                    flush_batch!(); // flush before transform change
5030                    let combined = current_transform.combine(transform);
5031                    transform_stack.push(combined);
5032                }
5033                SceneNode::PopTransform => {
5034                    flush_batch!(); // flush before transform change
5035                    transform_stack.pop();
5036                }
5037                SceneNode::BeginLayer {
5038                    rect,
5039                    layer_id,
5040                    alpha,
5041                    blur_radius_x,
5042                    blur_radius_y,
5043                    rectangle_edge: _,
5044                } => {
5045                    flush_batch!();
5046                    // Layer rect is already snapped to whole pixels in layout;
5047                    // round() keeps any bypass of that snap consistent.
5048                    let w = (rect.w.round().max(1.0)) as u32;
5049                    let h = (rect.h.round().max(1.0)) as u32;
5050                    saved_scissor_stack =
5051                        std::mem::replace(&mut scissor_stack, Vec::with_capacity(8));
5052                    saved_root_clip_rect = std::mem::replace(
5053                        &mut root_clip_rect,
5054                        repose_core::Rect {
5055                            x: 0.0,
5056                            y: 0.0,
5057                            w: w as f32,
5058                            h: h as f32,
5059                        },
5060                    );
5061                    scissor_stack.push(root_clip_rect);
5062                    // Close out the current pass, start a new one for the layer.
5063                    let prev_target = current_pass.target;
5064                    let prev_scissor = current_pass.initial_scissor;
5065                    let saved = std::mem::replace(
5066                        &mut current_pass,
5067                        Pass {
5068                            target: PassTarget::Layer(*layer_id),
5069                            initial_scissor: (0, 0, w, h),
5070                            clear_color: Some([0.0, 0.0, 0.0, 0.0]),
5071                            cmds: Vec::new(),
5072                        },
5073                    );
5074                    passes.push(saved);
5075                    target_stack.push(prev_target);
5076                    let _ = prev_scissor; // initial_scissor of resumed pass is restored at EndLayer
5077                    // Get or create the layer's offscreen texture now so that
5078                    // subsequent scissor ops / draws have a valid target.
5079                    self.get_or_create_layer(*layer_id, w, h, *rect);
5080                    current_target_size = (w as f32, h as f32);
5081                    layer_alphas.push((*layer_id, *alpha, current_pass.initial_scissor));
5082                    // Store blur info for post-processing after EndLayer
5083                    if *blur_radius_x > 0.0 || *blur_radius_y > 0.0 {
5084                        layer_blurs.push((*layer_id, *blur_radius_x, *blur_radius_y));
5085                    }
5086                }
5087                SceneNode::EndLayer { layer_id } => {
5088                    flush_batch!();
5089                    scissor_stack = std::mem::replace(&mut saved_scissor_stack, Vec::new());
5090                    root_clip_rect = saved_root_clip_rect;
5091                    // Finish the layer's pass, start a new one on the previous target.
5092                    let saved = std::mem::replace(
5093                        &mut current_pass,
5094                        Pass {
5095                            target: target_stack.pop().unwrap_or(PassTarget::Surface),
5096                            initial_scissor: (0, 0, self.output_width, self.output_height),
5097                            clear_color: None, // LoadOp::Load - don't wipe earlier surface content
5098                            cmds: Vec::new(),
5099                        },
5100                    );
5101                    passes.push(saved);
5102                    current_target_size = (fb_w, fb_h);
5103                    // Issue a composite quad for the just-finished layer in the new pass.
5104                    if let Some((_, layer_alpha, _)) = layer_alphas
5105                        .iter()
5106                        .find(|(id, _, _)| id == layer_id)
5107                        .copied()
5108                    {
5109                        let layer = self.layer_pool.get(layer_id).expect("layer target");
5110                        let ndc_tl = to_ndc(
5111                            layer.rect_px.0,
5112                            layer.rect_px.1,
5113                            layer.rect_px.2,
5114                            layer.rect_px.3,
5115                            fb_w,
5116                            fb_h,
5117                        );
5118                        let uv_u1 = layer.rect_px.2 / layer.width.max(1) as f32;
5119                        let uv_v1 = layer.rect_px.3 / layer.height.max(1) as f32;
5120                        // Check if this layer needs content blur
5121                        let blur_px_val = layer_blurs
5122                            .iter()
5123                            .find(|(id, _, _)| id == layer_id)
5124                            .map(|(_, bx, by)| (*bx, *by));
5125                        if let Some((blur_x, blur_y)) =
5126                            blur_px_val.filter(|(bx, by)| *bx > 0.0 || *by > 0.0)
5127                        {
5128                            // Content blur: draw blurred version using the blur_content pipeline
5129                            let bw_uv = (blur_x * 1.5) / layer.width.max(1) as f32;
5130                            let bh_uv = (blur_y * 1.5) / layer.height.max(1) as f32;
5131                            let inst = BlurInstance {
5132                                xywh: [
5133                                    ndc_tl[0] + ndc_tl[2] * 0.5,
5134                                    ndc_tl[1] + ndc_tl[3] * 0.5,
5135                                    ndc_tl[2],
5136                                    ndc_tl[3],
5137                                ],
5138                                uv: [0.0, 0.0, uv_u1, uv_v1],
5139                                color: [1.0, 1.0, 1.0, layer_alpha],
5140                                blur_uv: [bw_uv, bh_uv],
5141                                sin_cos: [1.0, 0.0],
5142                            };
5143                            self.blur_ring.grow_to_fit(
5144                                &self.device,
5145                                std::mem::size_of::<BlurInstance>() as u64,
5146                            );
5147                            let bytes = bytemuck::bytes_of(&inst);
5148                            let (off, _) = self.blur_ring.alloc_write(&self.queue, bytes);
5149                            current_pass.cmds.push(Cmd::CompositeBlur {
5150                                off,
5151                                cnt: 1,
5152                                layer_id: *layer_id,
5153                            });
5154                        } else {
5155                            // Normal sharp composite
5156                            let inst = GlyphInstance {
5157                                xywh: [
5158                                    ndc_tl[0] + ndc_tl[2] * 0.5,
5159                                    ndc_tl[1] + ndc_tl[3] * 0.5,
5160                                    ndc_tl[2],
5161                                    ndc_tl[3],
5162                                ],
5163                                uv: [0.0, uv_v1, uv_u1, 0.0],
5164                                color: [1.0, 1.0, 1.0, layer_alpha],
5165                                sin_cos: [1.0, 0.0],
5166                            };
5167                            if let Some((off, cnt)) =
5168                                self.glyph_color.upload(&self.device, &self.queue, &[inst])
5169                            {
5170                                current_pass.cmds.push(Cmd::CompositeLayer {
5171                                    off,
5172                                    cnt,
5173                                    layer_id: *layer_id,
5174                                });
5175                            }
5176                        }
5177                    }
5178                }
5179                SceneNode::CompositeShadow {
5180                    layer_id,
5181                    blur_px,
5182                    offset_px,
5183                    color,
5184                } => {
5185                    flush_batch!();
5186                    if let Some(layer) = self.layer_pool.get(layer_id).cloned() {
5187                        // Shadow rect = layer rect + offset.
5188                        let sx = layer.rect_px.0 + offset_px.0;
5189                        let sy = layer.rect_px.1 + offset_px.1;
5190                        let sw = layer.rect_px.2;
5191                        let sh = layer.rect_px.3;
5192                        // The blur in UV space is 1.5 * blur_px / texture_size
5193                        // (the 1.5 matches the 3x3 Gaussian span).
5194                        let bw_uv = (blur_px * 1.5) / layer.width.max(1) as f32;
5195                        let bh_uv = (blur_px * 1.5) / layer.height.max(1) as f32;
5196                        let shadow_u1 = layer.rect_px.2 / layer.width.max(1) as f32;
5197                        let shadow_v1 = layer.rect_px.3 / layer.height.max(1) as f32;
5198                        let ndc_tl = to_ndc(sx, sy, sw, sh, fb_w, fb_h);
5199                        let inst = BlurInstance {
5200                            xywh: [
5201                                ndc_tl[0] + ndc_tl[2] * 0.5,
5202                                ndc_tl[1] + ndc_tl[3] * 0.5,
5203                                ndc_tl[2],
5204                                ndc_tl[3],
5205                            ],
5206                            uv: [0.0, 0.0, shadow_u1, shadow_v1],
5207                            color: [
5208                                color.0 as f32 / 255.0,
5209                                color.1 as f32 / 255.0,
5210                                color.2 as f32 / 255.0,
5211                                color.3 as f32 / 255.0,
5212                            ],
5213                            blur_uv: [bw_uv, bh_uv],
5214                            sin_cos: [1.0, 0.0],
5215                        };
5216                        self.blur_ring
5217                            .grow_to_fit(&self.device, std::mem::size_of::<BlurInstance>() as u64);
5218                        let bytes = bytemuck::bytes_of(&inst);
5219                        let (off, _) = self.blur_ring.alloc_write(&self.queue, bytes);
5220                        current_pass.cmds.push(Cmd::CompositeShadow {
5221                            off,
5222                            cnt: 1,
5223                            layer_id: *layer_id,
5224                        });
5225                    }
5226                }
5227                SceneNode::VectorMesh {
5228                    mesh,
5229                    transform,
5230                    paint,
5231                    clip: _,
5232                    blend: _,
5233                } => {
5234                    flush_batch!();
5235                    let t_identity = Transform::identity();
5236                    let current_transform = transform_stack.last().unwrap_or(&t_identity);
5237                    self.emit_vector_mesh(
5238                        current_transform,
5239                        mesh,
5240                        *transform,
5241                        paint,
5242                        &mut current_pass.cmds,
5243                    );
5244                }
5245                SceneNode::VectorOverlay { meshes } => {
5246                    flush_batch!();
5247                    for m in meshes.iter() {
5248                        let (voff, vcnt, ioff, icnt) = self.upload_mesh_geometry(m);
5249                        let uoff = self.alloc_mesh_uniform(MeshUniform::identity());
5250                        current_pass.cmds.push(Cmd::VectorOverlay {
5251                            voff,
5252                            vcnt,
5253                            ioff,
5254                            icnt,
5255                            uoff,
5256                        });
5257                    }
5258                }
5259                SceneNode::PushVectorClip { mesh } => {
5260                    flush_batch!();
5261                    let t_identity = Transform::identity();
5262                    let current_transform = transform_stack.last().unwrap_or(&t_identity);
5263                    let affine =
5264                        combine_mesh_affine(current_transform, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
5265                    let aabb = mesh_aabb(mesh, affine);
5266                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
5267                    let next = intersect(top, aabb);
5268                    scissor_stack.push(next);
5269                    let scissor = to_scissor(
5270                        &next,
5271                        current_target_size.0 as u32,
5272                        current_target_size.1 as u32,
5273                    );
5274                    let (voff, vcnt, ioff, icnt) = self.upload_mesh_geometry(mesh);
5275                    let uoff = self.alloc_mesh_uniform(mesh_uniform_from_paint(
5276                        affine,
5277                        &repose_core::PaintDesc::Solid,
5278                    ));
5279                    current_pass.cmds.push(Cmd::VectorClipPush {
5280                        voff,
5281                        vcnt,
5282                        ioff,
5283                        icnt,
5284                        uoff,
5285                        scissor,
5286                    });
5287                    self.mesh_clip_stack.push((voff, vcnt, ioff, icnt, uoff));
5288                }
5289                SceneNode::PopVectorClip => {
5290                    flush_batch!();
5291                    if !scissor_stack.is_empty() {
5292                        scissor_stack.pop();
5293                    } else {
5294                        log::warn!("PopVectorClip with empty scissor stack");
5295                    }
5296                    if let Some((voff, vcnt, ioff, icnt, uoff)) = self.mesh_clip_stack.pop() {
5297                        let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
5298                        let scissor = to_scissor(
5299                            &top,
5300                            current_target_size.0 as u32,
5301                            current_target_size.1 as u32,
5302                        );
5303                        current_pass.cmds.push(Cmd::VectorClipPop {
5304                            voff,
5305                            vcnt,
5306                            ioff,
5307                            icnt,
5308                            uoff,
5309                            scissor,
5310                        });
5311                    } else {
5312                        log::warn!("PopVectorClip with empty clip stack");
5313                    }
5314                }
5315                _ => {}
5316            }
5317        }
5318
5319        flush_batch!();
5320
5321        // Push the final pass.
5322        passes.push(current_pass);
5323
5324        let globals_bytes = std::mem::size_of::<Globals>() as u64;
5325        let globals_staging = self.device.create_buffer(&wgpu::BufferDescriptor {
5326            label: Some("globals staging"),
5327            size: (passes.len().max(1) as u64) * globals_bytes,
5328            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
5329            mapped_at_creation: false,
5330        });
5331        for (i, pass) in passes.iter().enumerate() {
5332            let (target_w, target_h) = match pass.target {
5333                PassTarget::Surface => (fb_w, fb_h),
5334                PassTarget::Layer(layer_id) => {
5335                    let lt = self.layer_pool.get(&layer_id);
5336                    (
5337                        lt.map_or(fb_w, |l| l.width as f32),
5338                        lt.map_or(fb_h, |l| l.height as f32),
5339                    )
5340                }
5341            };
5342            self.queue.write_buffer(
5343                &globals_staging,
5344                (i as u64) * globals_bytes,
5345                bytemuck::bytes_of(&make_globals(target_w, target_h)),
5346            );
5347        }
5348
5349        let bind_mask = self.atlas_bind_group_mask();
5350        let bind_color = self.atlas_bind_group_color();
5351        let mut clip_depth: u32 = 0;
5352
5353        for (pass_index, pass) in std::mem::take(&mut passes).into_iter().enumerate() {
5354            let (color_view, resolve_target, depth_stencil_view, is_layer) = match pass.target {
5355                PassTarget::Surface => {
5356                    let swap_view = target_view.clone();
5357                    let use_ws = self.working_space && self.ws_view.is_some();
5358                    let (color, resolve) = if use_ws {
5359                        let ws_view = self.ws_view.as_ref().unwrap();
5360                        if let Some(msaa_view) = &self.msaa_view {
5361                            // MSAA resolves to working-space texture
5362                            (msaa_view.clone(), Some(ws_view.clone()))
5363                        } else {
5364                            // Direct render to working-space texture
5365                            (ws_view.clone(), None)
5366                        }
5367                    } else if let Some(msaa_view) = &self.msaa_view {
5368                        (msaa_view.clone(), Some(swap_view))
5369                    } else {
5370                        (swap_view, None)
5371                    };
5372                    (color, resolve, self.depth_stencil_view.clone(), false)
5373                }
5374                PassTarget::Layer(layer_id) => {
5375                    if let Some(lt) = self.layer_pool.get(&layer_id) {
5376                        (lt.view.clone(), None, lt.depth_stencil_view.clone(), true)
5377                    } else {
5378                        log::warn!("missing layer target {layer_id}");
5379                        continue;
5380                    }
5381                }
5382            };
5383
5384            encoder.copy_buffer_to_buffer(
5385                &globals_staging,
5386                (pass_index as u64) * globals_bytes,
5387                &self.globals_buf,
5388                0,
5389                globals_bytes,
5390            );
5391
5392            if is_layer {
5393                clip_depth = 0;
5394            }
5395
5396            let (tw, th) = match pass.target {
5397                PassTarget::Surface => (self.output_width, self.output_height),
5398                PassTarget::Layer(layer_id) => self
5399                    .layer_pool
5400                    .get(&layer_id)
5401                    .map(|l| (l.width, l.height))
5402                    .unwrap_or((self.output_width, self.output_height)),
5403            };
5404            let initial_scissor = clamp_scissor(
5405                pass.initial_scissor.0,
5406                pass.initial_scissor.1,
5407                pass.initial_scissor.2,
5408                pass.initial_scissor.3,
5409                tw,
5410                th,
5411            );
5412
5413            let pipes: &Pipelines = if is_layer {
5414                &self.layer_pipes
5415            } else {
5416                &self.surface_pipes
5417            };
5418
5419            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5420                label: Some("pass"),
5421                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5422                    view: &color_view,
5423                    resolve_target: resolve_target.as_ref(),
5424                    ops: wgpu::Operations {
5425                        load: match pass.clear_color {
5426                            Some(c) => wgpu::LoadOp::Clear(wgpu::Color {
5427                                r: c[0] as f64,
5428                                g: c[1] as f64,
5429                                b: c[2] as f64,
5430                                a: c[3] as f64,
5431                            }),
5432                            None => wgpu::LoadOp::Load,
5433                        },
5434                        store: wgpu::StoreOp::Store,
5435                    },
5436                    depth_slice: None,
5437                })],
5438                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
5439                    view: &depth_stencil_view,
5440                    depth_ops: None,
5441                    stencil_ops: Some(wgpu::Operations {
5442                        load: if is_layer || pass.clear_color.is_some() {
5443                            wgpu::LoadOp::Clear(0)
5444                        } else {
5445                            wgpu::LoadOp::Load
5446                        },
5447                        store: wgpu::StoreOp::Store,
5448                    }),
5449                }),
5450                timestamp_writes: None,
5451                occlusion_query_set: None,
5452                multiview_mask: None,
5453            });
5454
5455            rpass.set_bind_group(0, &self.globals_bind, &[]);
5456            rpass.set_stencil_reference(clip_depth);
5457            rpass.set_scissor_rect(
5458                initial_scissor.0,
5459                initial_scissor.1,
5460                initial_scissor.2,
5461                initial_scissor.3,
5462            );
5463
5464            macro_rules! draw_simple {
5465                ($pipeline:expr, $ring:expr, $inst:ty, $off:ident, $n:ident) => {{
5466                    rpass.set_pipeline($pipeline);
5467                    let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
5468                    rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
5469                    rpass.draw(0..6, 0..$n);
5470                }};
5471            }
5472
5473            macro_rules! draw_with_bind {
5474                ($pipeline:expr, $ring:expr, $inst:ty, $bind:expr, $off:ident, $n:ident) => {{
5475                    rpass.set_pipeline($pipeline);
5476                    rpass.set_bind_group(1, $bind, &[]);
5477                    let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
5478                    rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
5479                    rpass.draw(0..6, 0..$n);
5480                }};
5481            }
5482
5483            macro_rules! draw_indexed_mesh {
5484                ($pipeline:expr, $uoff:ident, $voff:ident, $vcnt:ident, $ioff:ident, $icnt:ident) => {{
5485                    rpass.set_pipeline($pipeline);
5486                    rpass.set_bind_group(1, &self.mesh_bind, &[$uoff as u32]);
5487                    let vbytes = ($vcnt as u64) * std::mem::size_of::<MeshVertex>() as u64;
5488                    rpass.set_vertex_buffer(0, self.mesh_verts.buf.slice($voff..$voff + vbytes));
5489                    let ibytes = ($icnt as u64) * std::mem::size_of::<u32>() as u64;
5490                    rpass.set_index_buffer(
5491                        self.mesh_indices.buf.slice($ioff..$ioff + ibytes),
5492                        wgpu::IndexFormat::Uint32,
5493                    );
5494                    rpass.draw_indexed(0..$icnt, 0, 0..1);
5495                }};
5496            }
5497
5498            for cmd in pass.cmds {
5499                match cmd {
5500                    Cmd::ClipPush {
5501                        off,
5502                        cnt: n,
5503                        scissor,
5504                        difference,
5505                        rounded,
5506                    } => {
5507                        let scissor =
5508                            clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
5509                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
5510                        rpass.set_stencil_reference(clip_depth);
5511
5512                        if difference {
5513                            rpass.set_pipeline(&pipes.clip_dec);
5514                        } else if self.msaa_samples > 1 && !is_layer && rounded {
5515                            rpass.set_pipeline(&pipes.clip_a2c);
5516                        } else {
5517                            rpass.set_pipeline(&pipes.clip_bin);
5518                        }
5519
5520                        let bytes = (n as u64) * std::mem::size_of::<ClipInstance>() as u64;
5521                        rpass.set_vertex_buffer(0, self.clip_ring.buf.slice(off..off + bytes));
5522                        rpass.draw(0..6, 0..n);
5523
5524                        if !difference {
5525                            clip_depth = (clip_depth + 1).min(255);
5526                            rpass.set_stencil_reference(clip_depth);
5527                        }
5528                    }
5529
5530                    Cmd::ClipPop {
5531                        off,
5532                        cnt: n,
5533                        scissor,
5534                        difference,
5535                    } => {
5536                        let scissor =
5537                            clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
5538                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
5539
5540                        if !difference && n > 0 {
5541                            rpass.set_stencil_reference(clip_depth);
5542                            rpass.set_pipeline(&pipes.clip_dec);
5543                            let bytes = (n as u64) * std::mem::size_of::<ClipInstance>() as u64;
5544                            rpass.set_vertex_buffer(0, self.clip_ring.buf.slice(off..off + bytes));
5545                            rpass.draw(0..6, 0..n);
5546                            clip_depth = clip_depth.saturating_sub(1);
5547                        } else if !difference {
5548                            clip_depth = clip_depth.saturating_sub(1);
5549                        }
5550                        rpass.set_stencil_reference(clip_depth);
5551                    }
5552
5553                    Cmd::Rect { off, cnt: n } => {
5554                        draw_simple!(&pipes.rects, self.rects.ring, RectInstance, off, n);
5555                    }
5556
5557                    Cmd::Border { off, cnt: n } => {
5558                        draw_simple!(&pipes.borders, self.borders.ring, BorderInstance, off, n);
5559                    }
5560
5561                    Cmd::GlyphsMask { off, cnt: n } => {
5562                        draw_with_bind!(
5563                            &pipes.text_mask,
5564                            self.glyph_mask.ring,
5565                            GlyphInstance,
5566                            &bind_mask,
5567                            off,
5568                            n
5569                        );
5570                    }
5571
5572                    Cmd::GlyphsColor { off, cnt: n } => {
5573                        draw_with_bind!(
5574                            &pipes.text_color,
5575                            self.glyph_color.ring,
5576                            GlyphInstance,
5577                            &bind_color,
5578                            off,
5579                            n
5580                        );
5581                    }
5582
5583                    Cmd::GlyphsVector { off, cnt: n } => {
5584                        if let Some(slug_pipe) = pipes.slug.as_ref() {
5585                            rpass.set_pipeline(slug_pipe);
5586                            let bytes = (n as u64) * std::mem::size_of::<slug::TessVertex>() as u64;
5587                            rpass.set_vertex_buffer(0, self.slug_ring.buf.slice(off..off + bytes));
5588                            rpass.draw(0..n, 0..1);
5589                        }
5590                    }
5591
5592                    Cmd::ImageRgba {
5593                        off,
5594                        cnt: n,
5595                        handle,
5596                    } => {
5597                        if let Some(ImageTex::Rgba { bind, .. }) = self.images.get(&handle) {
5598                            draw_with_bind!(
5599                                &pipes.image_rgba,
5600                                self.glyph_color.ring,
5601                                GlyphInstance,
5602                                bind,
5603                                off,
5604                                n
5605                            );
5606                        }
5607                    }
5608
5609                    Cmd::ImageNv12 {
5610                        off,
5611                        cnt: n,
5612                        handle,
5613                    } => {
5614                        if let Some(ImageTex::Nv12 { bind, .. }) = self.images.get(&handle) {
5615                            draw_with_bind!(
5616                                &pipes.image_nv12,
5617                                self.nv12.ring,
5618                                Nv12Instance,
5619                                bind,
5620                                off,
5621                                n
5622                            );
5623                        }
5624                    }
5625
5626                    Cmd::Ellipse { off, cnt: n } => {
5627                        draw_simple!(&pipes.ellipses, self.ellipses.ring, EllipseInstance, off, n);
5628                    }
5629
5630                    Cmd::EllipseBorder { off, cnt: n } => {
5631                        draw_simple!(
5632                            &pipes.ellipse_borders,
5633                            self.ellipse_borders.ring,
5634                            EllipseBorderInstance,
5635                            off,
5636                            n
5637                        );
5638                    }
5639
5640                    Cmd::Arc { off, cnt: n } => {
5641                        draw_simple!(&pipes.arcs, self.arcs.ring, ArcInstance, off, n);
5642                    }
5643
5644                    Cmd::CompositeLayer {
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.image_rgba,
5652                                self.glyph_color.ring,
5653                                GlyphInstance,
5654                                &lt.bind,
5655                                off,
5656                                n
5657                            );
5658                        }
5659                    }
5660                    Cmd::CompositeShadow {
5661                        off,
5662                        cnt: n,
5663                        layer_id,
5664                    } => {
5665                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
5666                            draw_with_bind!(
5667                                &pipes.blur,
5668                                self.blur_ring,
5669                                BlurInstance,
5670                                &lt.bind_linear,
5671                                off,
5672                                n
5673                            );
5674                        }
5675                    }
5676                    Cmd::CompositeBlur {
5677                        off,
5678                        cnt: n,
5679                        layer_id,
5680                    } => {
5681                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
5682                            draw_with_bind!(
5683                                &pipes.blur_content,
5684                                self.blur_ring,
5685                                BlurInstance,
5686                                &lt.bind_linear,
5687                                off,
5688                                n
5689                            );
5690                        }
5691                    }
5692
5693                    Cmd::VectorMesh {
5694                        voff,
5695                        vcnt,
5696                        ioff,
5697                        icnt,
5698                        uoff,
5699                    } => {
5700                        draw_indexed_mesh!(&pipes.mesh, uoff, voff, vcnt, ioff, icnt);
5701                    }
5702
5703                    Cmd::VectorOverlay {
5704                        voff,
5705                        vcnt,
5706                        ioff,
5707                        icnt,
5708                        uoff,
5709                    } => {
5710                        draw_indexed_mesh!(&pipes.mesh_overlay, uoff, voff, vcnt, ioff, icnt);
5711                    }
5712
5713                    Cmd::VectorClipPush {
5714                        voff,
5715                        vcnt,
5716                        ioff,
5717                        icnt,
5718                        uoff,
5719                        scissor,
5720                    } => {
5721                        let scissor =
5722                            clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
5723                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
5724                        rpass.set_stencil_reference(clip_depth);
5725                        draw_indexed_mesh!(&pipes.mesh_clip_inc, uoff, voff, vcnt, ioff, icnt);
5726                        clip_depth = (clip_depth + 1).min(255);
5727                        rpass.set_stencil_reference(clip_depth);
5728                    }
5729
5730                    Cmd::VectorClipPop {
5731                        voff,
5732                        vcnt,
5733                        ioff,
5734                        icnt,
5735                        uoff,
5736                        scissor,
5737                    } => {
5738                        // Decrement the mask while the stencil reference is
5739                        // still at the depth it was incremented to, so the
5740                        // equal-compare fires; then step the clip depth down.
5741                        rpass.set_stencil_reference(clip_depth);
5742                        let scissor =
5743                            clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
5744                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
5745                        draw_indexed_mesh!(&pipes.mesh_clip_dec, uoff, voff, vcnt, ioff, icnt);
5746                        clip_depth = clip_depth.saturating_sub(1);
5747                        rpass.set_stencil_reference(clip_depth);
5748                    }
5749                }
5750            }
5751        }
5752
5753        // Display pass: linear working space -> sRGB OETF -> swapchain
5754        if self.working_space
5755            && let (Some(_ws_view), Some(ws_bind), Some(display_pipeline)) =
5756                (&self.ws_view, &self.ws_bind, &self.display_pipeline)
5757        {
5758            let swap_view = target_view.clone();
5759            let mut display_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5760                label: Some("display transform"),
5761                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5762                    view: &swap_view,
5763                    resolve_target: None,
5764                    ops: wgpu::Operations {
5765                        load: wgpu::LoadOp::Load,
5766                        store: wgpu::StoreOp::Store,
5767                    },
5768                    depth_slice: None,
5769                })],
5770                depth_stencil_attachment: None,
5771                timestamp_writes: None,
5772                occlusion_query_set: None,
5773                multiview_mask: None,
5774            });
5775            display_pass.set_pipeline(display_pipeline);
5776            display_pass.set_bind_group(1, ws_bind, &[]);
5777            display_pass.draw(0..3, 0..1);
5778        }
5779
5780        // Frame end maintenance: Evict unused images
5781        self.evict_unused_images();
5782    }
5783
5784    /// Render a scene into an externally-provided texture view.
5785    /// Use this when embedding Repose in a host that owns the GPU.
5786    /// The host is responsible for submitting the encoder and handling present.
5787    pub fn render_to_view(
5788        &mut self,
5789        scene: &Scene,
5790        encoder: &mut wgpu::CommandEncoder,
5791        target_view: &wgpu::TextureView,
5792        width: u32,
5793        height: u32,
5794        clear_color: Option<[f64; 4]>,
5795    ) {
5796        self.resize(width, height);
5797
5798        self.frame_index = self.frame_index.wrapping_add(1);
5799        self.slug_cache.next_frame();
5800
5801        if width == 0 || height == 0 {
5802            return;
5803        }
5804
5805        self.render_scene_to_encoder(scene, encoder, target_view, clear_color);
5806    }
5807}
5808
5809fn clamp_scissor(x: u32, y: u32, w: u32, h: u32, tw: u32, th: u32) -> (u32, u32, u32, u32) {
5810    let x = x.min(tw.saturating_sub(1));
5811    let y = y.min(th.saturating_sub(1));
5812    let w = w.min(tw.saturating_sub(x)).max(1);
5813    let h = h.min(th.saturating_sub(y)).max(1);
5814    (x, y, w, h)
5815}
5816
5817fn intersect(a: repose_core::Rect, b: repose_core::Rect) -> repose_core::Rect {
5818    let x0 = a.x.max(b.x);
5819    let y0 = a.y.max(b.y);
5820    let x1 = (a.x + a.w).min(b.x + b.w);
5821    let y1 = (a.y + a.h).min(b.y + b.h);
5822    repose_core::Rect {
5823        x: x0,
5824        y: y0,
5825        w: (x1 - x0).max(0.0),
5826        h: (y1 - y0).max(0.0),
5827    }
5828}