Skip to main content

repose_render_wgpu/
lib.rs

1use std::borrow::Cow;
2use std::collections::HashMap;
3#[cfg(feature = "winit-surface")]
4use std::sync::Arc;
5#[cfg(feature = "winit-surface")]
6use std::panic::{AssertUnwindSafe, catch_unwind};
7use std::ops::{Deref, DerefMut};
8
9use repose_core::color::{ChromaSiting, ColorInfo, PixelFormat};
10use repose_core::request_frame;
11use repose_core::{
12    Brush, FontStyle, GlyphRasterConfig, RenderBackend, Scene, SceneNode, StrokeCap, Transform,
13};
14use wgpu::Instance;
15
16mod slug;
17
18#[derive(Clone)]
19struct UploadRing {
20    buf: wgpu::Buffer,
21    cap: u64,
22    head: u64,
23}
24
25impl UploadRing {
26    fn new(device: &wgpu::Device, label: &str, cap: u64) -> Self {
27        let buf = device.create_buffer(&wgpu::BufferDescriptor {
28            label: Some(label),
29            size: cap,
30            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
31            mapped_at_creation: false,
32        });
33        Self { buf, cap, head: 0 }
34    }
35
36    fn reset(&mut self) {
37        self.head = 0;
38    }
39
40    fn grow_to_fit(&mut self, device: &wgpu::Device, needed: u64) {
41        let start = (self.head + 3) & !3;
42        if start + needed <= self.cap {
43            return;
44        }
45        let new_cap = (start + needed).next_power_of_two();
46        self.buf = device.create_buffer(&wgpu::BufferDescriptor {
47            label: Some("upload ring (grown)"),
48            size: new_cap,
49            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
50            mapped_at_creation: false,
51        });
52        self.cap = new_cap;
53    }
54
55    fn alloc_write(&mut self, queue: &wgpu::Queue, bytes: &[u8]) -> (u64, u64) {
56        let len = bytes.len() as u64;
57        let start = (self.head + 3) & !3; // align to 4
58        let end = start + len;
59        assert!(end <= self.cap, "ring overflow - call grow_to_fit first");
60        queue.write_buffer(&self.buf, start, bytes);
61        self.head = end;
62        (start, len)
63    }
64}
65
66struct InstancedPipe<I: bytemuck::Pod> {
67    ring: UploadRing,
68    _marker: std::marker::PhantomData<I>,
69}
70
71impl<I: bytemuck::Pod> InstancedPipe<I> {
72    fn new(ring: UploadRing) -> Self {
73        Self {
74            ring,
75            _marker: std::marker::PhantomData,
76        }
77    }
78
79    fn upload(
80        &mut self,
81        device: &wgpu::Device,
82        queue: &wgpu::Queue,
83        data: &[I],
84    ) -> Option<(u64, u32)> {
85        if data.is_empty() {
86            return None;
87        }
88        let bytes = bytemuck::cast_slice(data);
89        self.ring.grow_to_fit(device, bytes.len() as u64);
90        let (off, wrote) = self.ring.alloc_write(queue, bytes);
91        debug_assert_eq!(wrote as usize, bytes.len());
92        Some((off, data.len() as u32))
93    }
94
95    fn reset(&mut self) {
96        self.ring.reset();
97    }
98}
99
100#[repr(C)]
101#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
102struct Globals {
103    ndc_to_px: [f32; 2],
104    _pad: [f32; 2],
105}
106
107pub struct WgpuSceneRenderer {
108    pub device: wgpu::Device,
109    pub queue: wgpu::Queue,
110    pub output_format: wgpu::TextureFormat,
111    pub output_width: u32,
112    pub output_height: u32,
113
114    // Render pipelines. Two sets: one for the MSAA surface pass, one for
115    // graphics-layer render-to-texture passes (sample_count = 1).
116    surface_pipes: Pipelines,
117    layer_pipes: Pipelines,
118
119    // Instanced draw rings
120    rects: InstancedPipe<RectInstance>,
121    borders: InstancedPipe<BorderInstance>,
122    ellipses: InstancedPipe<EllipseInstance>,
123    ellipse_borders: InstancedPipe<EllipseBorderInstance>,
124    arcs: InstancedPipe<ArcInstance>,
125    glyph_mask: InstancedPipe<GlyphInstance>,
126    glyph_color: InstancedPipe<GlyphInstance>,
127
128    // Image bind layouts and shared sampler
129    image_bind_layout_rgba: wgpu::BindGroupLayout,
130    image_bind_layout_nv12: wgpu::BindGroupLayout,
131    image_sampler: wgpu::Sampler,
132
133    // Blur composite ring (for graphics-layer drop shadows)
134    blur_ring: UploadRing,
135
136    text_bind_layout: wgpu::BindGroupLayout,
137
138    // Stencil clip ring
139    clip_ring: UploadRing,
140
141    // Tessellated vector glyph pipeline (always enabled)
142    slug_enabled: bool,
143    slug_ring: UploadRing,
144    slug_cache: slug::GlyphSlugCache,
145
146    // Instanced NV12 ring
147    nv12: InstancedPipe<Nv12Instance>,
148
149    msaa_samples: u32,
150
151    // Depth-stencil target
152    depth_stencil_tex: wgpu::Texture,
153    depth_stencil_view: wgpu::TextureView,
154
155    // Optional MSAA color target
156    msaa_tex: Option<wgpu::Texture>,
157    msaa_view: Option<wgpu::TextureView>,
158
159    globals_layout: wgpu::BindGroupLayout,
160    globals_buf: wgpu::Buffer,
161    globals_bind: wgpu::BindGroup,
162
163    // Glyph atlas
164    atlas_mask: AtlasA8,
165    atlas_color: AtlasRGBA,
166
167    // Image management
168    next_image_handle: u64,
169    images: HashMap<u64, ImageTex>,
170
171    // Eviction stats
172    frame_index: u64,
173    image_bytes_total: u64,
174    image_evict_after_frames: u64,
175    image_budget_bytes: u64,
176
177    // Graphics layer pool. Maps `SceneNode::BeginLayer::layer_id` to a
178    // cached offscreen render target.
179    layer_pool: HashMap<u32, LayerTarget>,
180
181    // Linear working-space mode (default off -> fast playback path).
182    // When enabled, the scene is rendered into an Rgba16Float intermediate
183    // texture, then a final full-screen pass applies the display OETF.
184    working_space: bool,
185    ws_tex: Option<wgpu::Texture>,
186    ws_view: Option<wgpu::TextureView>,
187    ws_bind: Option<wgpu::BindGroup>,
188    display_pipeline: Option<wgpu::RenderPipeline>,
189    display_layout: Option<wgpu::BindGroupLayout>,
190}
191
192pub struct WgpuSurfaceBackend {
193    pub surface: Option<wgpu::Surface<'static>>,
194    pub surface_config: Option<wgpu::SurfaceConfiguration>,
195    pub renderer: WgpuSceneRenderer,
196}
197
198impl std::ops::Deref for WgpuSurfaceBackend {
199    type Target = WgpuSceneRenderer;
200    fn deref(&self) -> &Self::Target { &self.renderer }
201}
202impl std::ops::DerefMut for WgpuSurfaceBackend {
203    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.renderer }
204}
205
206#[cfg(feature = "winit-surface")]
207pub type WgpuBackend = WgpuSurfaceBackend;
208
209impl Drop for WgpuSceneRenderer {
210    fn drop(&mut self) {
211        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
212    }
213}
214
215#[derive(Clone)]
216struct LayerTarget {
217    texture: wgpu::Texture,
218    view: wgpu::TextureView,
219    bind: wgpu::BindGroup,
220    depth_stencil_tex: wgpu::Texture,
221    depth_stencil_view: wgpu::TextureView,
222    width: u32,
223    height: u32,
224    rect_px: (f32, f32, f32, f32),
225}
226
227/// Identifies which render target a `Pass` draws into.
228#[derive(Clone, Copy)]
229enum PassTarget {
230    Surface,
231    Layer(u32),
232}
233
234/// A bundle of render pipelines for a single sample-count target. Created
235/// twice: once with `sample_count = msaa_samples` for the surface pass, and
236/// once with `sample_count = 1` for graphics-layer render-to-texture passes
237/// (where MSAA is wasted).
238struct Pipelines {
239    rects: wgpu::RenderPipeline,
240    borders: wgpu::RenderPipeline,
241    ellipses: wgpu::RenderPipeline,
242    ellipse_borders: wgpu::RenderPipeline,
243    arcs: wgpu::RenderPipeline,
244    text_mask: wgpu::RenderPipeline,
245    text_color: wgpu::RenderPipeline,
246    image_rgba: wgpu::RenderPipeline,
247    image_nv12: wgpu::RenderPipeline,
248    blur: wgpu::RenderPipeline,
249    blur_content: wgpu::RenderPipeline,
250    clip_a2c: wgpu::RenderPipeline,
251    clip_bin: wgpu::RenderPipeline,
252    clip_dec: wgpu::RenderPipeline,
253    slug: Option<wgpu::RenderPipeline>,
254}
255
256impl Pipelines {
257    fn create(
258        device: &wgpu::Device,
259        format: wgpu::TextureFormat,
260        sample_count: u32,
261        globals_layout: &wgpu::BindGroupLayout,
262        text_bind_layout: &wgpu::BindGroupLayout,
263        image_bind_layout_nv12: &wgpu::BindGroupLayout,
264        clip_pipeline_layout: &wgpu::PipelineLayout,
265        stencil_for_content: &wgpu::DepthStencilState,
266        stencil_for_clip_inc: &wgpu::DepthStencilState,
267        stencil_for_clip_dec: &wgpu::DepthStencilState,
268        clip_color_target: &wgpu::ColorTargetState,
269        clip_vertex_layout: &wgpu::VertexBufferLayout,
270    ) -> Self {
271        let msaa_state = wgpu::MultisampleState {
272            count: sample_count,
273            mask: !0,
274            alpha_to_coverage_enabled: false,
275        };
276
277        macro_rules! make_content_pipeline {
278            ($name:ident, $shader:literal, $inst_type:ty, $attrs:expr) => {
279                let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
280                    label: Some(concat!($shader, ".wgsl")),
281                    source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(concat!(
282                        "shaders/", $shader, ".wgsl"
283                    )))),
284                });
285                let pipeline_layout =
286                    device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
287                        label: Some(concat!($shader, " pipeline layout")),
288                        bind_group_layouts: &[Some(globals_layout)],
289                        immediate_size: 0,
290                    });
291                let $name = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
292                    label: Some(concat!($shader, " pipeline")),
293                    layout: Some(&pipeline_layout),
294                    vertex: wgpu::VertexState {
295                        module: &shader_module,
296                        entry_point: Some("vs_main"),
297                        buffers: &[Some(wgpu::VertexBufferLayout {
298                            array_stride: std::mem::size_of::<$inst_type>() as u64,
299                            step_mode: wgpu::VertexStepMode::Instance,
300                            attributes: $attrs,
301                        })],
302                        compilation_options: wgpu::PipelineCompilationOptions::default(),
303                    },
304                    fragment: Some(wgpu::FragmentState {
305                        module: &shader_module,
306                        entry_point: Some("fs_main"),
307                        targets: &[Some(wgpu::ColorTargetState {
308                            format,
309                            blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
310                            write_mask: wgpu::ColorWrites::ALL,
311                        })],
312                        compilation_options: wgpu::PipelineCompilationOptions::default(),
313                    }),
314                    primitive: wgpu::PrimitiveState::default(),
315                    depth_stencil: Some(stencil_for_content.clone()),
316                    multisample: msaa_state,
317                    multiview_mask: None,
318                    cache: None,
319                });
320            };
321        }
322
323        let rect_attrs: &[wgpu::VertexAttribute] = &[
324            wgpu::VertexAttribute {
325                shader_location: 0,
326                offset: 0,
327                format: wgpu::VertexFormat::Float32x4,
328            },
329            wgpu::VertexAttribute {
330                shader_location: 1,
331                offset: 16,
332                format: wgpu::VertexFormat::Float32x4,
333            },
334            wgpu::VertexAttribute {
335                shader_location: 2,
336                offset: 32,
337                format: wgpu::VertexFormat::Uint32,
338            },
339            wgpu::VertexAttribute {
340                shader_location: 3,
341                offset: 48,
342                format: wgpu::VertexFormat::Float32x4,
343            },
344            wgpu::VertexAttribute {
345                shader_location: 4,
346                offset: 64,
347                format: wgpu::VertexFormat::Float32x4,
348            },
349            wgpu::VertexAttribute {
350                shader_location: 5,
351                offset: 80,
352                format: wgpu::VertexFormat::Float32x2,
353            },
354            wgpu::VertexAttribute {
355                shader_location: 6,
356                offset: 88,
357                format: wgpu::VertexFormat::Float32x2,
358            },
359            wgpu::VertexAttribute {
360                shader_location: 7,
361                offset: 96,
362                format: wgpu::VertexFormat::Float32x2,
363            },
364        ];
365        let border_attrs: &[wgpu::VertexAttribute] = &[
366            wgpu::VertexAttribute {
367                shader_location: 0,
368                offset: 0,
369                format: wgpu::VertexFormat::Float32x4,
370            },
371            wgpu::VertexAttribute {
372                shader_location: 1,
373                offset: 16,
374                format: wgpu::VertexFormat::Float32x4,
375            },
376            wgpu::VertexAttribute {
377                shader_location: 2,
378                offset: 32,
379                format: wgpu::VertexFormat::Float32,
380            },
381            wgpu::VertexAttribute {
382                shader_location: 3,
383                offset: 36,
384                format: wgpu::VertexFormat::Float32x4,
385            },
386            wgpu::VertexAttribute {
387                shader_location: 4,
388                offset: 52,
389                format: wgpu::VertexFormat::Float32x2,
390            },
391        ];
392        let ellipse_attrs: &[wgpu::VertexAttribute] = &[
393            wgpu::VertexAttribute {
394                shader_location: 0,
395                offset: 0,
396                format: wgpu::VertexFormat::Float32x4,
397            },
398            wgpu::VertexAttribute {
399                shader_location: 1,
400                offset: 16,
401                format: wgpu::VertexFormat::Float32x4,
402            },
403            wgpu::VertexAttribute {
404                shader_location: 2,
405                offset: 32,
406                format: wgpu::VertexFormat::Float32x2,
407            },
408        ];
409        let ellipse_border_attrs: &[wgpu::VertexAttribute] = &[
410            wgpu::VertexAttribute {
411                shader_location: 0,
412                offset: 0,
413                format: wgpu::VertexFormat::Float32x4,
414            },
415            wgpu::VertexAttribute {
416                shader_location: 1,
417                offset: 16,
418                format: wgpu::VertexFormat::Float32,
419            },
420            wgpu::VertexAttribute {
421                shader_location: 2,
422                offset: 20,
423                format: wgpu::VertexFormat::Float32,
424            },
425            wgpu::VertexAttribute {
426                shader_location: 3,
427                offset: 24,
428                format: wgpu::VertexFormat::Float32x4,
429            },
430            wgpu::VertexAttribute {
431                shader_location: 4,
432                offset: 40,
433                format: wgpu::VertexFormat::Float32x2,
434            },
435        ];
436
437        make_content_pipeline!(rects, "rect", RectInstance, rect_attrs);
438        make_content_pipeline!(borders, "border", BorderInstance, border_attrs);
439        make_content_pipeline!(ellipses, "ellipse", EllipseInstance, ellipse_attrs);
440        make_content_pipeline!(
441            ellipse_borders,
442            "ellipse_border",
443            EllipseBorderInstance,
444            ellipse_border_attrs
445        );
446
447        let arc_attrs: &[wgpu::VertexAttribute] = &[
448            wgpu::VertexAttribute {
449                shader_location: 0,
450                offset: 0,
451                format: wgpu::VertexFormat::Float32x4,
452            },
453            wgpu::VertexAttribute {
454                shader_location: 1,
455                offset: 16,
456                format: wgpu::VertexFormat::Float32,
457            },
458            wgpu::VertexAttribute {
459                shader_location: 2,
460                offset: 20,
461                format: wgpu::VertexFormat::Float32,
462            },
463            wgpu::VertexAttribute {
464                shader_location: 3,
465                offset: 24,
466                format: wgpu::VertexFormat::Float32,
467            },
468            wgpu::VertexAttribute {
469                shader_location: 4,
470                offset: 28,
471                format: wgpu::VertexFormat::Float32,
472            },
473            wgpu::VertexAttribute {
474                shader_location: 5,
475                offset: 32,
476                format: wgpu::VertexFormat::Float32x4,
477            },
478            wgpu::VertexAttribute {
479                shader_location: 6,
480                offset: 48,
481                format: wgpu::VertexFormat::Float32x2,
482            },
483            wgpu::VertexAttribute {
484                shader_location: 7,
485                offset: 56,
486                format: wgpu::VertexFormat::Float32,
487            },
488        ];
489
490        make_content_pipeline!(arcs, "arc", ArcInstance, arc_attrs);
491
492        // Text (mask)
493        let text_mask_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
494            label: Some("text.wgsl"),
495            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shaders/text.wgsl"))),
496        });
497        // Text (color)
498        let text_color_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
499            label: Some("text_color.wgsl"),
500            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
501                "shaders/text_color.wgsl"
502            ))),
503        });
504        let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
505            label: Some("text pipeline layout"),
506            bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
507            immediate_size: 0,
508        });
509        let glyph_vertex = wgpu::VertexBufferLayout {
510            array_stride: std::mem::size_of::<GlyphInstance>() as u64,
511            step_mode: wgpu::VertexStepMode::Instance,
512            attributes: &[
513                wgpu::VertexAttribute {
514                    shader_location: 0,
515                    offset: 0,
516                    format: wgpu::VertexFormat::Float32x4,
517                },
518                wgpu::VertexAttribute {
519                    shader_location: 1,
520                    offset: 16,
521                    format: wgpu::VertexFormat::Float32x4,
522                },
523                wgpu::VertexAttribute {
524                    shader_location: 2,
525                    offset: 32,
526                    format: wgpu::VertexFormat::Float32x4,
527                },
528                wgpu::VertexAttribute {
529                    shader_location: 3,
530                    offset: 48,
531                    format: wgpu::VertexFormat::Float32x2,
532                },
533            ],
534        };
535        let text_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
536            label: Some("text pipeline (mask)"),
537            layout: Some(&text_pipeline_layout),
538            vertex: wgpu::VertexState {
539                module: &text_mask_shader,
540                entry_point: Some("vs_main"),
541                buffers: &[Some(glyph_vertex.clone())],
542                compilation_options: wgpu::PipelineCompilationOptions::default(),
543            },
544            fragment: Some(wgpu::FragmentState {
545                module: &text_mask_shader,
546                entry_point: Some("fs_main"),
547                targets: &[Some(wgpu::ColorTargetState {
548                    format,
549                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
550                    write_mask: wgpu::ColorWrites::ALL,
551                })],
552                compilation_options: wgpu::PipelineCompilationOptions::default(),
553            }),
554            primitive: wgpu::PrimitiveState::default(),
555            depth_stencil: Some(stencil_for_content.clone()),
556            multisample: msaa_state,
557            multiview_mask: None,
558            cache: None,
559        });
560        let text_color = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
561            label: Some("text pipeline (color)"),
562            layout: Some(&text_pipeline_layout),
563            vertex: wgpu::VertexState {
564                module: &text_color_shader,
565                entry_point: Some("vs_main"),
566                buffers: &[Some(glyph_vertex)],
567                compilation_options: wgpu::PipelineCompilationOptions::default(),
568            },
569            fragment: Some(wgpu::FragmentState {
570                module: &text_color_shader,
571                entry_point: Some("fs_main"),
572                targets: &[Some(wgpu::ColorTargetState {
573                    format,
574                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
575                    write_mask: wgpu::ColorWrites::ALL,
576                })],
577                compilation_options: wgpu::PipelineCompilationOptions::default(),
578            }),
579            primitive: wgpu::PrimitiveState::default(),
580            depth_stencil: Some(stencil_for_content.clone()),
581            multisample: msaa_state,
582            multiview_mask: None,
583            cache: None,
584        });
585        // image_rgba reuses the text color pipeline (same vertex/bindings).
586        let image_rgba = text_color.clone();
587
588        // Blur composite pipeline (graphics-layer drop shadow)
589        let blur_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
590            label: Some("blur_shadow.wgsl"),
591            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
592                "shaders/blur_shadow.wgsl"
593            ))),
594        });
595        let blur_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
596            label: Some("blur pipeline layout"),
597            bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
598            immediate_size: 0,
599        });
600        let blur = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
601            label: Some("blur pipeline"),
602            layout: Some(&blur_pipeline_layout),
603            vertex: wgpu::VertexState {
604                module: &blur_shader,
605                entry_point: Some("vs_main"),
606                buffers: &[Some(wgpu::VertexBufferLayout {
607                    array_stride: std::mem::size_of::<BlurInstance>() as u64,
608                    step_mode: wgpu::VertexStepMode::Instance,
609                    attributes: &[
610                        wgpu::VertexAttribute {
611                            shader_location: 0,
612                            offset: 0,
613                            format: wgpu::VertexFormat::Float32x4,
614                        },
615                        wgpu::VertexAttribute {
616                            shader_location: 1,
617                            offset: 16,
618                            format: wgpu::VertexFormat::Float32x4,
619                        },
620                        wgpu::VertexAttribute {
621                            shader_location: 2,
622                            offset: 32,
623                            format: wgpu::VertexFormat::Float32x4,
624                        },
625                        wgpu::VertexAttribute {
626                            shader_location: 3,
627                            offset: 48,
628                            format: wgpu::VertexFormat::Float32x2,
629                        },
630                        wgpu::VertexAttribute {
631                            shader_location: 4,
632                            offset: 56,
633                            format: wgpu::VertexFormat::Float32x2,
634                        },
635                    ],
636                })],
637                compilation_options: wgpu::PipelineCompilationOptions::default(),
638            },
639            fragment: Some(wgpu::FragmentState {
640                module: &blur_shader,
641                entry_point: Some("fs_main"),
642                targets: &[Some(wgpu::ColorTargetState {
643                    format,
644                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
645                    write_mask: wgpu::ColorWrites::ALL,
646                })],
647                compilation_options: wgpu::PipelineCompilationOptions::default(),
648            }),
649            primitive: wgpu::PrimitiveState::default(),
650            depth_stencil: Some(stencil_for_content.clone()),
651            multisample: msaa_state,
652            multiview_mask: None,
653            cache: None,
654        });
655
656        // Content blur pipeline (full RGBA gaussian blur)
657        let blur_content_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
658            label: Some("blur_content.wgsl"),
659            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
660                "shaders/blur_content.wgsl"
661            ))),
662        });
663        let blur_content = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
664            label: Some("blur content pipeline"),
665            layout: Some(&blur_pipeline_layout),
666            vertex: wgpu::VertexState {
667                module: &blur_content_shader,
668                entry_point: Some("vs_main"),
669                buffers: &[Some(wgpu::VertexBufferLayout {
670                    array_stride: std::mem::size_of::<BlurInstance>() as u64,
671                    step_mode: wgpu::VertexStepMode::Instance,
672                    attributes: &[
673                        wgpu::VertexAttribute {
674                            shader_location: 0,
675                            offset: 0,
676                            format: wgpu::VertexFormat::Float32x4,
677                        },
678                        wgpu::VertexAttribute {
679                            shader_location: 1,
680                            offset: 16,
681                            format: wgpu::VertexFormat::Float32x4,
682                        },
683                        wgpu::VertexAttribute {
684                            shader_location: 2,
685                            offset: 32,
686                            format: wgpu::VertexFormat::Float32x4,
687                        },
688                        wgpu::VertexAttribute {
689                            shader_location: 3,
690                            offset: 48,
691                            format: wgpu::VertexFormat::Float32x2,
692                        },
693                        wgpu::VertexAttribute {
694                            shader_location: 4,
695                            offset: 56,
696                            format: wgpu::VertexFormat::Float32x2,
697                        },
698                    ],
699                })],
700                compilation_options: wgpu::PipelineCompilationOptions::default(),
701            },
702            fragment: Some(wgpu::FragmentState {
703                module: &blur_content_shader,
704                entry_point: Some("fs_main"),
705                targets: &[Some(wgpu::ColorTargetState {
706                    format,
707                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
708                    write_mask: wgpu::ColorWrites::ALL,
709                })],
710                compilation_options: wgpu::PipelineCompilationOptions::default(),
711            }),
712            primitive: wgpu::PrimitiveState::default(),
713            depth_stencil: Some(stencil_for_content.clone()),
714            multisample: msaa_state,
715            multiview_mask: None,
716            cache: None,
717        });
718
719        // NV12 Image Pipeline
720        let image_nv12_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
721            label: Some("image_nv12.wgsl"),
722            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
723                "shaders/image_nv12.wgsl"
724            ))),
725        });
726        let image_nv12_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
727            label: Some("image nv12 pipeline layout"),
728            bind_group_layouts: &[Some(globals_layout), Some(image_bind_layout_nv12)],
729            immediate_size: 0,
730        });
731        let image_nv12 = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
732            label: Some("image nv12 pipeline"),
733            layout: Some(&image_nv12_layout),
734            vertex: wgpu::VertexState {
735                module: &image_nv12_shader,
736                entry_point: Some("vs_main"),
737                buffers: &[Some(wgpu::VertexBufferLayout {
738                    array_stride: std::mem::size_of::<Nv12Instance>() as u64,
739                    step_mode: wgpu::VertexStepMode::Instance,
740                    attributes: &[
741                        wgpu::VertexAttribute {
742                            shader_location: 0,
743                            offset: 0,
744                            format: wgpu::VertexFormat::Float32x4,
745                        },
746                        wgpu::VertexAttribute {
747                            shader_location: 1,
748                            offset: 16,
749                            format: wgpu::VertexFormat::Float32x4,
750                        },
751                        wgpu::VertexAttribute {
752                            shader_location: 2,
753                            offset: 32,
754                            format: wgpu::VertexFormat::Float32x4,
755                        },
756                        wgpu::VertexAttribute {
757                            shader_location: 3,
758                            offset: 48,
759                            format: wgpu::VertexFormat::Float32,
760                        },
761                        wgpu::VertexAttribute {
762                            shader_location: 4,
763                            offset: 52,
764                            format: wgpu::VertexFormat::Float32x2,
765                        },
766                    ],
767                })],
768                compilation_options: wgpu::PipelineCompilationOptions::default(),
769            },
770            fragment: Some(wgpu::FragmentState {
771                module: &image_nv12_shader,
772                entry_point: Some("fs_main"),
773                targets: &[Some(wgpu::ColorTargetState {
774                    format,
775                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
776                    write_mask: wgpu::ColorWrites::ALL,
777                })],
778                compilation_options: wgpu::PipelineCompilationOptions::default(),
779            }),
780            primitive: wgpu::PrimitiveState::default(),
781            depth_stencil: Some(stencil_for_content.clone()),
782            multisample: msaa_state,
783            multiview_mask: None,
784            cache: None,
785        });
786
787        // Clipping
788        let clip_shader_a2c = device.create_shader_module(wgpu::ShaderModuleDescriptor {
789            label: Some("clip_round_rect_a2c.wgsl"),
790            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
791                "shaders/clip_round_rect_a2c.wgsl"
792            ))),
793        });
794        let clip_shader_bin = device.create_shader_module(wgpu::ShaderModuleDescriptor {
795            label: Some("clip_round_rect_bin.wgsl"),
796            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
797                "shaders/clip_round_rect_bin.wgsl"
798            ))),
799        });
800        let clip_a2c = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
801            label: Some("clip pipeline (a2c)"),
802            layout: Some(clip_pipeline_layout),
803            vertex: wgpu::VertexState {
804                module: &clip_shader_a2c,
805                entry_point: Some("vs_main"),
806                buffers: &[Some(clip_vertex_layout.clone())],
807                compilation_options: wgpu::PipelineCompilationOptions::default(),
808            },
809            fragment: Some(wgpu::FragmentState {
810                module: &clip_shader_a2c,
811                entry_point: Some("fs_main"),
812                targets: &[Some(clip_color_target.clone())],
813                compilation_options: wgpu::PipelineCompilationOptions::default(),
814            }),
815            primitive: wgpu::PrimitiveState::default(),
816            depth_stencil: Some(stencil_for_clip_inc.clone()),
817            multisample: wgpu::MultisampleState {
818                count: sample_count,
819                mask: !0,
820                alpha_to_coverage_enabled: sample_count > 1,
821            },
822            multiview_mask: None,
823            cache: None,
824        });
825        let clip_bin = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
826            label: Some("clip pipeline (bin)"),
827            layout: Some(clip_pipeline_layout),
828            vertex: wgpu::VertexState {
829                module: &clip_shader_bin,
830                entry_point: Some("vs_main"),
831                buffers: &[Some(clip_vertex_layout.clone())],
832                compilation_options: wgpu::PipelineCompilationOptions::default(),
833            },
834            fragment: Some(wgpu::FragmentState {
835                module: &clip_shader_bin,
836                entry_point: Some("fs_main"),
837                targets: &[Some(clip_color_target.clone())],
838                compilation_options: wgpu::PipelineCompilationOptions::default(),
839            }),
840            primitive: wgpu::PrimitiveState::default(),
841            depth_stencil: Some(stencil_for_clip_inc.clone()),
842            multisample: wgpu::MultisampleState {
843                count: sample_count,
844                mask: !0,
845                alpha_to_coverage_enabled: false,
846            },
847            multiview_mask: None,
848            cache: None,
849        });
850        let clip_dec = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
851            label: Some("clip pipeline (dec)"),
852            layout: Some(clip_pipeline_layout),
853            vertex: wgpu::VertexState {
854                module: &clip_shader_bin,
855                entry_point: Some("vs_main"),
856                buffers: &[Some(clip_vertex_layout.clone())],
857                compilation_options: wgpu::PipelineCompilationOptions::default(),
858            },
859            fragment: Some(wgpu::FragmentState {
860                module: &clip_shader_bin,
861                entry_point: Some("fs_main"),
862                targets: &[Some(clip_color_target.clone())],
863                compilation_options: wgpu::PipelineCompilationOptions::default(),
864            }),
865            primitive: wgpu::PrimitiveState::default(),
866            depth_stencil: Some(stencil_for_clip_dec.clone()),
867            multisample: wgpu::MultisampleState {
868                count: sample_count,
869                mask: !0,
870                alpha_to_coverage_enabled: false,
871            },
872            multiview_mask: None,
873            cache: None,
874        });
875
876        let slug = Some(slug::create_pipeline(
877            device,
878            format,
879            sample_count,
880            stencil_for_content,
881        ));
882
883        Self {
884            rects,
885            borders,
886            ellipses,
887            ellipse_borders,
888            arcs,
889            text_mask,
890            text_color,
891            image_rgba,
892            image_nv12,
893            blur,
894            blur_content,
895            clip_a2c,
896            clip_bin,
897            clip_dec,
898            slug,
899        }
900    }
901}
902
903/// A segment of the frame that draws into a single render target.
904struct Pass {
905    target: PassTarget,
906    /// The initial scissor to apply to the rpass when it is opened.
907    initial_scissor: (u32, u32, u32, u32),
908    /// `None` means `LoadOp::Load` (resume existing content);
909    /// `Some(c)` means `LoadOp::Clear(c)`.
910    clear_color: Option<[f32; 4]>,
911    cmds: Vec<Cmd>,
912}
913
914#[allow(non_snake_case)]
915enum Cmd {
916    ClipPush {
917        off: u64,
918        cnt: u32,
919        scissor: (u32, u32, u32, u32),
920        difference: bool,
921        rounded: bool,
922    },
923    ClipPop {
924        scissor: (u32, u32, u32, u32),
925    },
926    Rect {
927        off: u64,
928        cnt: u32,
929    },
930    Border {
931        off: u64,
932        cnt: u32,
933    },
934    Ellipse {
935        off: u64,
936        cnt: u32,
937    },
938    EllipseBorder {
939        off: u64,
940        cnt: u32,
941    },
942    Arc {
943        off: u64,
944        cnt: u32,
945    },
946    GlyphsMask {
947        off: u64,
948        cnt: u32,
949    },
950    GlyphsColor {
951        off: u64,
952        cnt: u32,
953    },
954    GlyphsVector {
955        off: u64,
956        cnt: u32,
957    },
958    ImageRgba {
959        off: u64,
960        cnt: u32,
961        handle: u64,
962    },
963    ImageNv12 {
964        off: u64,
965        cnt: u32,
966        handle: u64,
967    },
968    PushTransform(Transform),
969    PopTransform,
970    /// Composite a previously-rendered graphics layer back into the
971    /// current target as a textured quad. The quad's vertex buffer
972    /// lives in `self.glyph_color.ring` (a `GlyphInstance`).
973    CompositeLayer {
974        off: u64,
975        cnt: u32,
976        layer_id: u32,
977        alpha: f32,
978    },
979    /// Composite a blurred drop shadow of a previously-rendered graphics
980    /// layer. The quad's vertex buffer lives in `self.blur_ring` (a
981    /// `BlurInstance`).
982    CompositeShadow {
983        off: u64,
984        cnt: u32,
985        layer_id: u32,
986    },
987    /// Apply gaussian blur to a layer and composite the blurred result.
988    /// Uses the `blur_content` pipeline (full RGBA blur).
989    CompositeBlur {
990        off: u64,
991        cnt: u32,
992        layer_id: u32,
993    },
994}
995
996enum ImageTex {
997    Rgba {
998        tex: wgpu::Texture,
999        view: wgpu::TextureView,
1000        bind: wgpu::BindGroup,
1001        w: u32,
1002        h: u32,
1003        format: wgpu::TextureFormat,
1004        last_used_frame: u64,
1005        bytes: u64,
1006    },
1007    Nv12 {
1008        tex_y: wgpu::Texture,
1009        view_y: wgpu::TextureView,
1010        tex_uv: wgpu::Texture,
1011        view_uv: wgpu::TextureView,
1012        bind: wgpu::BindGroup,
1013        yuv_buf: wgpu::Buffer,
1014        w: u32,
1015        h: u32,
1016        color_info: ColorInfo,
1017        last_used_frame: u64,
1018        bytes: u64,
1019    },
1020}
1021
1022struct AtlasA8 {
1023    tex: wgpu::Texture,
1024    view: wgpu::TextureView,
1025    sampler: wgpu::Sampler,
1026    size: u32,
1027    next_x: u32,
1028    next_y: u32,
1029    row_h: u32,
1030    map: HashMap<(repose_text::GlyphKey, u32), GlyphInfo>,
1031}
1032
1033struct AtlasRGBA {
1034    tex: wgpu::Texture,
1035    view: wgpu::TextureView,
1036    sampler: wgpu::Sampler,
1037    size: u32,
1038    next_x: u32,
1039    next_y: u32,
1040    row_h: u32,
1041    map: HashMap<(repose_text::GlyphKey, u32), GlyphInfo>,
1042}
1043
1044#[derive(Clone, Copy)]
1045struct GlyphInfo {
1046    u0: f32,
1047    v0: f32,
1048    u1: f32,
1049    v1: f32,
1050    w: f32,
1051    h: f32,
1052    bearing_x: f32,
1053    bearing_y: f32,
1054    advance: f32,
1055}
1056
1057#[repr(C)]
1058#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1059struct RectInstance {
1060    xywh: [f32; 4],
1061    radii: [f32; 4],
1062    brush_type: u32,
1063    _pad: [f32; 3],
1064    color0: [f32; 4],
1065    color1: [f32; 4],
1066    grad_start: [f32; 2],
1067    grad_end: [f32; 2],
1068    sin_cos: [f32; 2],
1069}
1070
1071#[repr(C)]
1072#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1073struct BorderInstance {
1074    xywh: [f32; 4],
1075    radii: [f32; 4],
1076    stroke: f32,
1077    color: [f32; 4],
1078    sin_cos: [f32; 2],
1079}
1080
1081#[repr(C)]
1082#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1083struct EllipseInstance {
1084    xywh: [f32; 4],
1085    color: [f32; 4],
1086    sin_cos: [f32; 2],
1087}
1088
1089#[repr(C)]
1090#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1091struct EllipseBorderInstance {
1092    xywh: [f32; 4],
1093    stroke: f32,
1094    pad: f32,
1095    color: [f32; 4],
1096    sin_cos: [f32; 2],
1097}
1098
1099#[repr(C)]
1100#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1101struct ArcInstance {
1102    xywh: [f32; 4],
1103    start_angle: f32,
1104    sweep_angle: f32,
1105    stroke: f32,
1106    pad: f32,
1107    color: [f32; 4],
1108    sin_cos: [f32; 2],
1109    cap: f32, // 0=Butt, 1=Round, 2=Square
1110}
1111
1112#[repr(C)]
1113#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1114struct GlyphInstance {
1115    xywh: [f32; 4],
1116    uv: [f32; 4],
1117    color: [f32; 4],
1118    sin_cos: [f32; 2],
1119}
1120
1121#[repr(C)]
1122#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1123struct BlurInstance {
1124    xywh: [f32; 4],
1125    uv: [f32; 4],
1126    color: [f32; 4],
1127    blur_uv: [f32; 2],
1128    sin_cos: [f32; 2],
1129}
1130
1131/// CPU-computed Y′CbCr → R′G′B′ transform uploaded as a uniform buffer.
1132/// Layout matches the WGSL `YuvTransform` struct (4 × vec4<f32>).
1133#[repr(C)]
1134#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1135struct YuvTransformRaw {
1136    row0: [f32; 4],
1137    row1: [f32; 4],
1138    row2: [f32; 4],
1139    b: [f32; 4],
1140}
1141
1142#[repr(C)]
1143#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1144struct Nv12Instance {
1145    xywh: [f32; 4],
1146    uv: [f32; 4],
1147    color: [f32; 4], // tint
1148    uv_x_offset: f32,
1149    sin_cos: [f32; 2],
1150    _pad: [f32; 1],
1151}
1152
1153#[repr(C)]
1154#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
1155struct ClipInstance {
1156    xywh: [f32; 4],
1157    radii: [f32; 4],
1158    sin_cos: [f32; 2],
1159}
1160
1161fn swash_to_a8_coverage(content: repose_text::SwashContent, data: &[u8]) -> Option<Vec<u8>> {
1162    match content {
1163        repose_text::SwashContent::Mask => Some(data.to_vec()),
1164        repose_text::SwashContent::SubpixelMask => {
1165            let mut out = Vec::with_capacity(data.len() / 4);
1166            for px in data.chunks_exact(4) {
1167                let r = px[0];
1168                let g = px[1];
1169                let b = px[2];
1170                out.push(r.max(g).max(b));
1171            }
1172            Some(out)
1173        }
1174        repose_text::SwashContent::Color => None,
1175    }
1176}
1177
1178impl WgpuSceneRenderer {
1179    pub fn from_device(
1180        device: wgpu::Device,
1181        queue: wgpu::Queue,
1182        output_format: wgpu::TextureFormat,
1183        msaa_samples: u32,
1184    ) -> Self {
1185        let globals_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1186            label: Some("globals layout"),
1187            entries: &[wgpu::BindGroupLayoutEntry {
1188                binding: 0,
1189                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
1190                ty: wgpu::BindingType::Buffer {
1191                    ty: wgpu::BufferBindingType::Uniform,
1192                    has_dynamic_offset: false,
1193                    min_binding_size: None,
1194                },
1195                count: None,
1196            }],
1197        });
1198
1199        let globals_buf = device.create_buffer(&wgpu::BufferDescriptor {
1200            label: Some("globals buf"),
1201            size: std::mem::size_of::<Globals>() as u64,
1202            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1203            mapped_at_creation: false,
1204        });
1205
1206        let globals_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
1207            label: Some("globals bind"),
1208            layout: &globals_layout,
1209            entries: &[wgpu::BindGroupEntry {
1210                binding: 0,
1211                resource: globals_buf.as_entire_binding(),
1212            }],
1213        });
1214
1215
1216        let ds_format = wgpu::TextureFormat::Depth24PlusStencil8;
1217
1218        let stencil_for_content = wgpu::DepthStencilState {
1219            format: ds_format,
1220            depth_write_enabled: Some(false),
1221            depth_compare: Some(wgpu::CompareFunction::Always),
1222            stencil: wgpu::StencilState {
1223                front: wgpu::StencilFaceState {
1224                    compare: wgpu::CompareFunction::LessEqual,
1225                    fail_op: wgpu::StencilOperation::Keep,
1226                    depth_fail_op: wgpu::StencilOperation::Keep,
1227                    pass_op: wgpu::StencilOperation::Keep,
1228                },
1229                back: wgpu::StencilFaceState {
1230                    compare: wgpu::CompareFunction::LessEqual,
1231                    fail_op: wgpu::StencilOperation::Keep,
1232                    depth_fail_op: wgpu::StencilOperation::Keep,
1233                    pass_op: wgpu::StencilOperation::Keep,
1234                },
1235                read_mask: 0xFF,
1236                write_mask: 0x00,
1237            },
1238            bias: wgpu::DepthBiasState::default(),
1239        };
1240
1241        let stencil_for_clip_inc = wgpu::DepthStencilState {
1242            format: ds_format,
1243            depth_write_enabled: Some(false),
1244            depth_compare: Some(wgpu::CompareFunction::Always),
1245            stencil: wgpu::StencilState {
1246                front: wgpu::StencilFaceState {
1247                    compare: wgpu::CompareFunction::Equal,
1248                    fail_op: wgpu::StencilOperation::Keep,
1249                    depth_fail_op: wgpu::StencilOperation::Keep,
1250                    pass_op: wgpu::StencilOperation::IncrementClamp,
1251                },
1252                back: wgpu::StencilFaceState {
1253                    compare: wgpu::CompareFunction::Equal,
1254                    fail_op: wgpu::StencilOperation::Keep,
1255                    depth_fail_op: wgpu::StencilOperation::Keep,
1256                    pass_op: wgpu::StencilOperation::IncrementClamp,
1257                },
1258                read_mask: 0xFF,
1259                write_mask: 0xFF,
1260            },
1261            bias: wgpu::DepthBiasState::default(),
1262        };
1263
1264        let stencil_for_clip_dec = wgpu::DepthStencilState {
1265            format: ds_format,
1266            depth_write_enabled: Some(false),
1267            depth_compare: Some(wgpu::CompareFunction::Always),
1268            stencil: wgpu::StencilState {
1269                front: wgpu::StencilFaceState {
1270                    compare: wgpu::CompareFunction::Equal,
1271                    fail_op: wgpu::StencilOperation::Keep,
1272                    depth_fail_op: wgpu::StencilOperation::Keep,
1273                    pass_op: wgpu::StencilOperation::DecrementClamp,
1274                },
1275                back: wgpu::StencilFaceState {
1276                    compare: wgpu::CompareFunction::Equal,
1277                    fail_op: wgpu::StencilOperation::Keep,
1278                    depth_fail_op: wgpu::StencilOperation::Keep,
1279                    pass_op: wgpu::StencilOperation::DecrementClamp,
1280                },
1281                read_mask: 0xFF,
1282                write_mask: 0xFF,
1283            },
1284            bias: wgpu::DepthBiasState::default(),
1285        };
1286
1287        let _multisample_state = wgpu::MultisampleState {
1288            count: msaa_samples,
1289            mask: !0,
1290            alpha_to_coverage_enabled: false,
1291        };
1292
1293        // PIPELINES
1294
1295        // Single shared sampler for images/text
1296        let image_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
1297            label: Some("image/text sampler"),
1298            address_mode_u: wgpu::AddressMode::ClampToEdge,
1299            address_mode_v: wgpu::AddressMode::ClampToEdge,
1300            mag_filter: wgpu::FilterMode::Linear,
1301            min_filter: wgpu::FilterMode::Linear,
1302            mipmap_filter: wgpu::MipmapFilterMode::Linear,
1303            ..Default::default()
1304        });
1305
1306        // Layout for Text / RGBA Images (Texture + Sampler)
1307        let text_bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1308            label: Some("text/rgba bind layout"),
1309            entries: &[
1310                wgpu::BindGroupLayoutEntry {
1311                    binding: 0,
1312                    visibility: wgpu::ShaderStages::FRAGMENT,
1313                    ty: wgpu::BindingType::Texture {
1314                        multisampled: false,
1315                        view_dimension: wgpu::TextureViewDimension::D2,
1316                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
1317                    },
1318                    count: None,
1319                },
1320                wgpu::BindGroupLayoutEntry {
1321                    binding: 1,
1322                    visibility: wgpu::ShaderStages::FRAGMENT,
1323                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1324                    count: None,
1325                },
1326            ],
1327        });
1328        // We reuse this for RGBA images for simplicity, or create a distinct one
1329        let image_bind_layout_rgba = text_bind_layout.clone();
1330
1331        // Layout for NV12 Images (TextureY + TextureUV + Sampler + YuvTransform uniform)
1332        let image_bind_layout_nv12 =
1333            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1334                label: Some("image bind layout nv12"),
1335                entries: &[
1336                    // Y plane
1337                    wgpu::BindGroupLayoutEntry {
1338                        binding: 0,
1339                        visibility: wgpu::ShaderStages::FRAGMENT,
1340                        ty: wgpu::BindingType::Texture {
1341                            multisampled: false,
1342                            view_dimension: wgpu::TextureViewDimension::D2,
1343                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
1344                        },
1345                        count: None,
1346                    },
1347                    // UV plane
1348                    wgpu::BindGroupLayoutEntry {
1349                        binding: 1,
1350                        visibility: wgpu::ShaderStages::FRAGMENT,
1351                        ty: wgpu::BindingType::Texture {
1352                            multisampled: false,
1353                            view_dimension: wgpu::TextureViewDimension::D2,
1354                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
1355                        },
1356                        count: None,
1357                    },
1358                    // Sampler
1359                    wgpu::BindGroupLayoutEntry {
1360                        binding: 2,
1361                        visibility: wgpu::ShaderStages::FRAGMENT,
1362                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1363                        count: None,
1364                    },
1365                    // YUV transform uniform buffer
1366                    wgpu::BindGroupLayoutEntry {
1367                        binding: 3,
1368                        visibility: wgpu::ShaderStages::FRAGMENT,
1369                        ty: wgpu::BindingType::Buffer {
1370                            ty: wgpu::BufferBindingType::Uniform,
1371                            has_dynamic_offset: false,
1372                            min_binding_size: None,
1373                        },
1374                        count: None,
1375                    },
1376                ],
1377            });
1378
1379        // Clipping layout
1380        let clip_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1381            label: Some("clip pipeline layout"),
1382            bind_group_layouts: &[Some(&globals_layout)],
1383            immediate_size: 0,
1384        });
1385        let clip_vertex_layout = wgpu::VertexBufferLayout {
1386            array_stride: std::mem::size_of::<ClipInstance>() as u64,
1387            step_mode: wgpu::VertexStepMode::Instance,
1388            attributes: &[
1389                wgpu::VertexAttribute {
1390                    shader_location: 0,
1391                    offset: 0,
1392                    format: wgpu::VertexFormat::Float32x4,
1393                },
1394                wgpu::VertexAttribute {
1395                    shader_location: 1,
1396                    offset: 16,
1397                    format: wgpu::VertexFormat::Float32x4,
1398                },
1399                wgpu::VertexAttribute {
1400                    shader_location: 2,
1401                    offset: 32,
1402                    format: wgpu::VertexFormat::Float32x2,
1403                },
1404            ],
1405        };
1406        let clip_color_target = wgpu::ColorTargetState {
1407            format: output_format,
1408            blend: None,
1409            write_mask: wgpu::ColorWrites::empty(),
1410        };
1411
1412        // Two sets of pipelines: one for the MSAA surface pass, one for layer
1413        // render-to-texture passes (sample_count = 1).
1414        let surface_pipes = Pipelines::create(
1415            &device,
1416            output_format,
1417            msaa_samples,
1418            &globals_layout,
1419            &text_bind_layout,
1420            &image_bind_layout_nv12,
1421            &clip_pipeline_layout,
1422            &stencil_for_content,
1423            &stencil_for_clip_inc,
1424            &stencil_for_clip_dec,
1425            &clip_color_target,
1426            &clip_vertex_layout,
1427        );
1428        let layer_pipes = Pipelines::create(
1429            &device,
1430            output_format,
1431            1,
1432            &globals_layout,
1433            &text_bind_layout,
1434            &image_bind_layout_nv12,
1435            &clip_pipeline_layout,
1436            &stencil_for_content,
1437            &stencil_for_clip_inc,
1438            &stencil_for_clip_dec,
1439            &clip_color_target,
1440            &clip_vertex_layout,
1441        );
1442
1443        // Vector glyph rendering always available with tessellation+MSAA approach.
1444        let slug_enabled = true;
1445
1446        // Blur composite ring (for graphics-layer drop shadows)
1447        let blur_ring = UploadRing::new(&device, "blur ring", 1024 * 1024);
1448
1449        // Atlases
1450        let atlas_mask = init_atlas_mask(&device);
1451        let atlas_color = init_atlas_color(&device);
1452
1453        // Upload rings
1454        let ring_rect = UploadRing::new(&device, "ring rect", 1 << 20);
1455        let ring_border = UploadRing::new(&device, "ring border", 1 << 20);
1456        let ring_ellipse = UploadRing::new(&device, "ring ellipse", 1 << 20);
1457        let ring_ellipse_border = UploadRing::new(&device, "ring ellipse border", 1 << 20);
1458        let ring_arc = UploadRing::new(&device, "ring arc", 1 << 20);
1459        let ring_glyph_mask = UploadRing::new(&device, "ring glyph mask", 1 << 20);
1460        let ring_glyph_color = UploadRing::new(&device, "ring glyph color", 1 << 20);
1461        let ring_slug = UploadRing::new(&device, "ring slug", 1 << 22);
1462        let ring_clip = UploadRing::new(&device, "ring clip", 1 << 16);
1463        let ring_nv12 = UploadRing::new(&device, "ring nv12", 1 << 20);
1464
1465        // Placeholder textures
1466        let depth_stencil_tex = device.create_texture(&wgpu::TextureDescriptor {
1467            label: Some("temp ds"),
1468            size: wgpu::Extent3d {
1469                width: 1,
1470                height: 1,
1471                depth_or_array_layers: 1,
1472            },
1473            mip_level_count: 1,
1474            sample_count: 1,
1475            dimension: wgpu::TextureDimension::D2,
1476            format: wgpu::TextureFormat::Depth24PlusStencil8,
1477            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1478            view_formats: &[],
1479        });
1480        let depth_stencil_view =
1481            depth_stencil_tex.create_view(&wgpu::TextureViewDescriptor::default());
1482
1483        let mut renderer = WgpuSceneRenderer {
1484            device,
1485            queue,
1486            output_format,
1487            output_width: 0,
1488            output_height: 0,
1489
1490            surface_pipes,
1491            layer_pipes,
1492
1493            rects: InstancedPipe::new(ring_rect),
1494            borders: InstancedPipe::new(ring_border),
1495            ellipses: InstancedPipe::new(ring_ellipse),
1496            ellipse_borders: InstancedPipe::new(ring_ellipse_border),
1497            arcs: InstancedPipe::new(ring_arc),
1498            glyph_mask: InstancedPipe::new(ring_glyph_mask),
1499            glyph_color: InstancedPipe::new(ring_glyph_color),
1500
1501            text_bind_layout,
1502
1503            image_bind_layout_rgba,
1504            image_bind_layout_nv12,
1505            image_sampler,
1506
1507            blur_ring,
1508
1509            slug_enabled,
1510            slug_ring: ring_slug,
1511            slug_cache: slug::GlyphSlugCache::new(),
1512
1513            clip_ring: ring_clip,
1514
1515            nv12: InstancedPipe::new(ring_nv12),
1516
1517            msaa_samples,
1518            depth_stencil_tex,
1519            depth_stencil_view,
1520            msaa_tex: None,
1521            msaa_view: None,
1522            globals_bind,
1523            globals_buf,
1524            globals_layout,
1525
1526            atlas_mask,
1527            atlas_color,
1528
1529            next_image_handle: 1,
1530            images: HashMap::new(),
1531
1532            frame_index: 0,
1533            image_bytes_total: 0,
1534            image_evict_after_frames: 600,         // ~10s @ 60fps
1535            image_budget_bytes: 512 * 1024 * 1024, // 512 MB
1536            layer_pool: HashMap::new(),
1537
1538            working_space: false,
1539            ws_tex: None,
1540            ws_view: None,
1541            ws_bind: None,
1542            display_pipeline: None,
1543            display_layout: None,
1544        };
1545
1546        renderer.recreate_msaa_and_depth_stencil();
1547        renderer
1548    }
1549}
1550
1551impl WgpuSurfaceBackend {
1552    #[cfg(feature = "winit-surface")]
1553    pub async fn new_async(window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
1554        let instance: Instance;
1555
1556        if cfg!(target_arch = "wasm32") {
1557            let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
1558            desc.backends = wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL;
1559            instance = wgpu::util::new_instance_with_webgpu_detection(desc).await;
1560        } else {
1561            instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
1562        };
1563
1564        let surface = instance.create_surface(window.clone())?;
1565
1566        let adapter = instance
1567            .request_adapter(&wgpu::RequestAdapterOptions {
1568                power_preference: wgpu::PowerPreference::HighPerformance,
1569                compatible_surface: Some(&surface),
1570                force_fallback_adapter: false,
1571                apply_limit_buckets: false,
1572            })
1573            .await
1574            .map_err(|e| anyhow::anyhow!("No suitable adapter: {e:?}"))?;
1575
1576        let limits = adapter.limits();
1577
1578        let (device, queue) = adapter
1579            .request_device(&wgpu::DeviceDescriptor {
1580                label: Some("repose-rs device"),
1581                required_features: wgpu::Features::empty(),
1582                required_limits: limits,
1583                experimental_features: wgpu::ExperimentalFeatures::disabled(),
1584                memory_hints: wgpu::MemoryHints::default(),
1585                trace: wgpu::Trace::Off,
1586            })
1587            .await
1588            .map_err(|e| anyhow::anyhow!("request_device failed: {e:?}"))?;
1589
1590        let size = window.inner_size();
1591
1592        let caps = surface.get_capabilities(&adapter);
1593        let format = caps
1594            .formats
1595            .iter()
1596            .copied()
1597            .find(|f| f.is_srgb())
1598            .unwrap_or(caps.formats[0]);
1599        let present_mode = caps
1600            .present_modes
1601            .iter()
1602            .copied()
1603            .find(|m| *m == wgpu::PresentMode::Mailbox || *m == wgpu::PresentMode::Immediate)
1604            .unwrap_or(wgpu::PresentMode::Fifo);
1605        let alpha_mode = caps.alpha_modes[0];
1606
1607        // Pick MSAA sample count
1608        let fmt_features = adapter.get_texture_format_features(format);
1609        let msaa_samples = if fmt_features.flags.sample_count_supported(4)
1610            && fmt_features
1611                .flags
1612                .contains(wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE)
1613        {
1614            4
1615        } else {
1616            1
1617        };
1618
1619        let renderer = WgpuSceneRenderer::from_device(device, queue, format, msaa_samples);
1620
1621        let config = wgpu::SurfaceConfiguration {
1622            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1623            format,
1624            width: size.width.max(1),
1625            height: size.height.max(1),
1626            present_mode,
1627            alpha_mode,
1628            color_space: wgpu::SurfaceColorSpace::Auto,
1629            view_formats: vec![],
1630            desired_maximum_frame_latency: 2,
1631        };
1632        surface.configure(&renderer.device, &config);
1633
1634        Ok(WgpuSurfaceBackend { surface: Some(surface), surface_config: Some(config), renderer })
1635    }
1636
1637    #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
1638    pub fn new(window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
1639        pollster::block_on(Self::new_async(window))
1640    }
1641
1642    #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
1643    pub fn new(_window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
1644        anyhow::bail!("Use WgpuSurfaceBackend::new_async(window).await on wasm32")
1645    }
1646}
1647
1648impl WgpuSceneRenderer {
1649    // Image API
1650
1651    pub fn set_image_from_bytes(
1652        &mut self,
1653        handle: u64,
1654        data: &[u8],
1655        srgb: bool,
1656    ) -> anyhow::Result<()> {
1657        let img = image::load_from_memory(data)?;
1658        let rgba = img.to_rgba8();
1659        let (w, h) = rgba.dimensions();
1660        self.set_image_rgba8(handle, w, h, &rgba, srgb)
1661    }
1662
1663    pub fn set_image_rgba8(
1664        &mut self,
1665        handle: u64,
1666        w: u32,
1667        h: u32,
1668        rgba: &[u8],
1669        srgb: bool,
1670    ) -> anyhow::Result<()> {
1671        let expected = (w as usize) * (h as usize) * 4;
1672        if rgba.len() < expected {
1673            return Err(anyhow::anyhow!(
1674                "RGBA buffer too small: {} < {}",
1675                rgba.len(),
1676                expected
1677            ));
1678        }
1679
1680        let format = if srgb {
1681            wgpu::TextureFormat::Rgba8UnormSrgb
1682        } else {
1683            wgpu::TextureFormat::Rgba8Unorm
1684        };
1685
1686        let needs_recreate = match self.images.get(&handle) {
1687            Some(ImageTex::Rgba {
1688                w: cw,
1689                h: ch,
1690                format: cf,
1691                ..
1692            }) => *cw != w || *ch != h || *cf != format,
1693            _ => true,
1694        };
1695
1696        if needs_recreate {
1697            // Remove old to track budget correctly
1698            self.remove_image(handle);
1699
1700            let tex = self.device.create_texture(&wgpu::TextureDescriptor {
1701                label: Some("user image rgba"),
1702                size: wgpu::Extent3d {
1703                    width: w,
1704                    height: h,
1705                    depth_or_array_layers: 1,
1706                },
1707                mip_level_count: 1,
1708                sample_count: 1,
1709                dimension: wgpu::TextureDimension::D2,
1710                format,
1711                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1712                view_formats: &[],
1713            });
1714            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1715
1716            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
1717                label: Some("image bind rgba"),
1718                layout: &self.image_bind_layout_rgba,
1719                entries: &[
1720                    wgpu::BindGroupEntry {
1721                        binding: 0,
1722                        resource: wgpu::BindingResource::TextureView(&view),
1723                    },
1724                    wgpu::BindGroupEntry {
1725                        binding: 1,
1726                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
1727                    },
1728                ],
1729            });
1730
1731            let bytes = (w as u64) * (h as u64) * 4;
1732            self.image_bytes_total += bytes;
1733
1734            self.images.insert(
1735                handle,
1736                ImageTex::Rgba {
1737                    tex,
1738                    view,
1739                    bind,
1740                    w,
1741                    h,
1742                    format,
1743                    last_used_frame: self.frame_index,
1744                    bytes,
1745                },
1746            );
1747        }
1748
1749        let tex = match self.images.get(&handle) {
1750            Some(ImageTex::Rgba { tex, .. }) => tex,
1751            _ => unreachable!(),
1752        };
1753
1754        self.queue.write_texture(
1755            wgpu::TexelCopyTextureInfo {
1756                texture: tex,
1757                mip_level: 0,
1758                origin: wgpu::Origin3d::ZERO,
1759                aspect: wgpu::TextureAspect::All,
1760            },
1761            &rgba[..expected],
1762            wgpu::TexelCopyBufferLayout {
1763                offset: 0,
1764                bytes_per_row: Some(4 * w),
1765                rows_per_image: Some(h),
1766            },
1767            wgpu::Extent3d {
1768                width: w,
1769                height: h,
1770                depth_or_array_layers: 1,
1771            },
1772        );
1773
1774        // Ensure budget limits
1775        self.evict_budget_excess();
1776
1777        Ok(())
1778    }
1779
1780    pub fn set_image_nv12(
1781        &mut self,
1782        handle: u64,
1783        w: u32,
1784        h: u32,
1785        y: &[u8],
1786        uv: &[u8],
1787        color_info: ColorInfo,
1788    ) -> anyhow::Result<()> {
1789        let y_expected = (w as usize) * (h as usize);
1790        let uv_w = (w / 2).max(1);
1791        let uv_h = (h / 2).max(1);
1792        let uv_expected = (uv_w as usize) * (uv_h as usize) * 2;
1793
1794        if y.len() < y_expected {
1795            return Err(anyhow::anyhow!("Y plane too small"));
1796        }
1797        if uv.len() < uv_expected {
1798            return Err(anyhow::anyhow!("UV plane too small"));
1799        }
1800
1801        let needs_recreate = match self.images.get(&handle) {
1802            Some(ImageTex::Nv12 { w: ww, h: hh, .. }) => *ww != w || *hh != h,
1803            _ => true,
1804        };
1805
1806        // Compute the YUV→RGB transform on the CPU.
1807        let yuv = color_info.to_yuv_transform();
1808        let yuv_raw = YuvTransformRaw {
1809            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
1810            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
1811            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
1812            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
1813        };
1814
1815        if needs_recreate {
1816            self.remove_image(handle);
1817
1818            let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
1819                label: Some("nv12 Y"),
1820                size: wgpu::Extent3d {
1821                    width: w,
1822                    height: h,
1823                    depth_or_array_layers: 1,
1824                },
1825                mip_level_count: 1,
1826                sample_count: 1,
1827                dimension: wgpu::TextureDimension::D2,
1828                format: wgpu::TextureFormat::R8Unorm,
1829                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1830                view_formats: &[],
1831            });
1832            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
1833
1834            let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
1835                label: Some("nv12 UV"),
1836                size: wgpu::Extent3d {
1837                    width: uv_w,
1838                    height: uv_h,
1839                    depth_or_array_layers: 1,
1840                },
1841                mip_level_count: 1,
1842                sample_count: 1,
1843                dimension: wgpu::TextureDimension::D2,
1844                format: wgpu::TextureFormat::Rg8Unorm,
1845                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1846                view_formats: &[],
1847            });
1848            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
1849
1850            // Create a uniform buffer for the YUV transform (per-image).
1851            let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
1852                label: Some("nv12 yuv transform"),
1853                size: std::mem::size_of::<YuvTransformRaw>() as u64,
1854                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1855                mapped_at_creation: false,
1856            });
1857
1858            // Write initial transform.
1859            self.queue
1860                .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
1861
1862            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
1863                label: Some("nv12 bind"),
1864                layout: &self.image_bind_layout_nv12,
1865                entries: &[
1866                    wgpu::BindGroupEntry {
1867                        binding: 0,
1868                        resource: wgpu::BindingResource::TextureView(&view_y),
1869                    },
1870                    wgpu::BindGroupEntry {
1871                        binding: 1,
1872                        resource: wgpu::BindingResource::TextureView(&view_uv),
1873                    },
1874                    wgpu::BindGroupEntry {
1875                        binding: 2,
1876                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
1877                    },
1878                    wgpu::BindGroupEntry {
1879                        binding: 3,
1880                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1881                            buffer: &yuv_buf,
1882                            offset: 0,
1883                            size: None,
1884                        }),
1885                    },
1886                ],
1887            });
1888
1889            let bytes = (w as u64) * (h as u64)
1890                + (uv_w as u64) * (uv_h as u64) * 2
1891                + std::mem::size_of::<YuvTransformRaw>() as u64;
1892            self.image_bytes_total += bytes;
1893
1894            self.images.insert(
1895                handle,
1896                ImageTex::Nv12 {
1897                    tex_y,
1898                    view_y,
1899                    tex_uv,
1900                    view_uv,
1901                    bind,
1902                    yuv_buf,
1903                    w,
1904                    h,
1905                    color_info,
1906                    last_used_frame: self.frame_index,
1907                    bytes,
1908                },
1909            );
1910        } else {
1911            // Re-use existing textures; just update the YUV transform if needed.
1912            if let Some(ImageTex::Nv12 { yuv_buf, .. }) = self.images.get(&handle) {
1913                self.queue
1914                    .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
1915            }
1916        }
1917
1918        let (tex_y, tex_uv, _bind) = match self.images.get(&handle) {
1919            Some(ImageTex::Nv12 {
1920                tex_y,
1921                tex_uv,
1922                bind,
1923                ..
1924            }) => (tex_y, tex_uv, bind),
1925            _ => return Err(anyhow::anyhow!("Handle is not NV12")),
1926        };
1927
1928        self.queue.write_texture(
1929            wgpu::TexelCopyTextureInfo {
1930                texture: tex_y,
1931                mip_level: 0,
1932                origin: wgpu::Origin3d::ZERO,
1933                aspect: wgpu::TextureAspect::All,
1934            },
1935            &y[..y_expected],
1936            wgpu::TexelCopyBufferLayout {
1937                offset: 0,
1938                bytes_per_row: Some(w),
1939                rows_per_image: Some(h),
1940            },
1941            wgpu::Extent3d {
1942                width: w,
1943                height: h,
1944                depth_or_array_layers: 1,
1945            },
1946        );
1947
1948        self.queue.write_texture(
1949            wgpu::TexelCopyTextureInfo {
1950                texture: tex_uv,
1951                mip_level: 0,
1952                origin: wgpu::Origin3d::ZERO,
1953                aspect: wgpu::TextureAspect::All,
1954            },
1955            &uv[..uv_expected],
1956            wgpu::TexelCopyBufferLayout {
1957                offset: 0,
1958                bytes_per_row: Some(2 * uv_w),
1959                rows_per_image: Some(uv_h),
1960            },
1961            wgpu::Extent3d {
1962                width: uv_w,
1963                height: uv_h,
1964                depth_or_array_layers: 1,
1965            },
1966        );
1967
1968        self.evict_budget_excess();
1969        Ok(())
1970    }
1971
1972    pub fn set_image_planes(
1973        &mut self,
1974        handle: u64,
1975        w: u32,
1976        h: u32,
1977        pixel_format: PixelFormat,
1978        planes: &[Vec<u8>],
1979        color_info: ColorInfo,
1980    ) -> anyhow::Result<()> {
1981        match pixel_format {
1982            PixelFormat::Nv12 => {
1983                let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
1984                let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
1985                self.set_image_nv12(handle, w, h, y, uv, color_info)
1986            }
1987            PixelFormat::P010 => {
1988                let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
1989                let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
1990                self.set_image_p010(handle, w, h, y, uv, color_info)
1991            }
1992            PixelFormat::I420 | PixelFormat::I444 => Err(anyhow::anyhow!(
1993                "I420/I444 not implemented and unlikely -> cheap to convert to NV12 (better for the GPU too)"
1994            )),
1995            PixelFormat::Rgba => {
1996                let rgba = planes
1997                    .first()
1998                    .ok_or(anyhow::anyhow!("missing RGBA plane"))?;
1999                self.set_image_rgba8(handle, w, h, rgba, false)
2000            }
2001        }
2002    }
2003
2004    fn set_image_p010(
2005        &mut self,
2006        handle: u64,
2007        w: u32,
2008        h: u32,
2009        y: &[u8],
2010        uv: &[u8],
2011        color_info: ColorInfo,
2012    ) -> anyhow::Result<()> {
2013        let uv_w = (w / 2).max(1);
2014        let uv_h = (h / 2).max(1);
2015
2016        let y_expected = (w as usize) * 2;
2017        let uv_expected = (uv_w as usize) * (uv_h as usize) * 4;
2018
2019        if y.len() < y_expected {
2020            return Err(anyhow::anyhow!("P010 Y plane too small"));
2021        }
2022        if uv.len() < uv_expected {
2023            return Err(anyhow::anyhow!("P010 UV plane too small"));
2024        }
2025
2026        // P010 reuses the NV12 pipeline (same bind group layout -> wgpu
2027        // abstracts the storage format so R16Unorm/Rg16Unorm are
2028        // filterable float textures just like R8Unorm/Rg8Unorm).
2029        let needs_recreate = match self.images.get(&handle) {
2030            Some(ImageTex::Nv12 { w: ww, h: hh, .. }) => *ww != w || *hh != h,
2031            _ => true,
2032        };
2033
2034        let yuv = color_info.to_yuv_transform();
2035        let yuv_raw = YuvTransformRaw {
2036            row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2037            row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2038            row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2039            b: [yuv.b[0], yuv.b[1], yuv.b[2], 0.0],
2040        };
2041
2042        if needs_recreate {
2043            self.remove_image(handle);
2044
2045            let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
2046                label: Some("p010 Y"),
2047                size: wgpu::Extent3d {
2048                    width: w,
2049                    height: h,
2050                    depth_or_array_layers: 1,
2051                },
2052                mip_level_count: 1,
2053                sample_count: 1,
2054                dimension: wgpu::TextureDimension::D2,
2055                format: wgpu::TextureFormat::R16Unorm,
2056                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2057                view_formats: &[],
2058            });
2059            let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
2060
2061            let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
2062                label: Some("p010 UV"),
2063                size: wgpu::Extent3d {
2064                    width: uv_w,
2065                    height: uv_h,
2066                    depth_or_array_layers: 1,
2067                },
2068                mip_level_count: 1,
2069                sample_count: 1,
2070                dimension: wgpu::TextureDimension::D2,
2071                format: wgpu::TextureFormat::Rg16Unorm,
2072                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2073                view_formats: &[],
2074            });
2075            let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
2076
2077            let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
2078                label: Some("p010 yuv transform"),
2079                size: std::mem::size_of::<YuvTransformRaw>() as u64,
2080                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
2081                mapped_at_creation: false,
2082            });
2083            self.queue
2084                .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2085
2086            let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2087                label: Some("p010 bind"),
2088                layout: &self.image_bind_layout_nv12,
2089                entries: &[
2090                    wgpu::BindGroupEntry {
2091                        binding: 0,
2092                        resource: wgpu::BindingResource::TextureView(&view_y),
2093                    },
2094                    wgpu::BindGroupEntry {
2095                        binding: 1,
2096                        resource: wgpu::BindingResource::TextureView(&view_uv),
2097                    },
2098                    wgpu::BindGroupEntry {
2099                        binding: 2,
2100                        resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2101                    },
2102                    wgpu::BindGroupEntry {
2103                        binding: 3,
2104                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
2105                            buffer: &yuv_buf,
2106                            offset: 0,
2107                            size: None,
2108                        }),
2109                    },
2110                ],
2111            });
2112
2113            let bytes = (w as u64) * 2
2114                + (uv_w as u64) * (uv_h as u64) * 4
2115                + std::mem::size_of::<YuvTransformRaw>() as u64;
2116            self.image_bytes_total += bytes;
2117
2118            self.images.insert(
2119                handle,
2120                ImageTex::Nv12 {
2121                    tex_y,
2122                    view_y,
2123                    tex_uv,
2124                    view_uv,
2125                    bind,
2126                    yuv_buf,
2127                    w,
2128                    h,
2129                    color_info,
2130                    last_used_frame: self.frame_index,
2131                    bytes,
2132                },
2133            );
2134        } else {
2135            if let Some(ImageTex::Nv12 { yuv_buf, .. }) = self.images.get(&handle) {
2136                self.queue
2137                    .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
2138            }
2139        }
2140
2141        let (tex_y, tex_uv, _bind) = match self.images.get(&handle) {
2142            Some(ImageTex::Nv12 {
2143                tex_y,
2144                tex_uv,
2145                bind,
2146                ..
2147            }) => (tex_y, tex_uv, bind),
2148            _ => return Err(anyhow::anyhow!("Handle is not P010/NV12")),
2149        };
2150
2151        self.queue.write_texture(
2152            wgpu::TexelCopyTextureInfo {
2153                texture: tex_y,
2154                mip_level: 0,
2155                origin: wgpu::Origin3d::ZERO,
2156                aspect: wgpu::TextureAspect::All,
2157            },
2158            &y[..y_expected],
2159            wgpu::TexelCopyBufferLayout {
2160                offset: 0,
2161                bytes_per_row: Some(w * 2),
2162                rows_per_image: Some(h),
2163            },
2164            wgpu::Extent3d {
2165                width: w,
2166                height: h,
2167                depth_or_array_layers: 1,
2168            },
2169        );
2170        self.queue.write_texture(
2171            wgpu::TexelCopyTextureInfo {
2172                texture: tex_uv,
2173                mip_level: 0,
2174                origin: wgpu::Origin3d::ZERO,
2175                aspect: wgpu::TextureAspect::All,
2176            },
2177            &uv[..uv_expected],
2178            wgpu::TexelCopyBufferLayout {
2179                offset: 0,
2180                bytes_per_row: Some(uv_w * 4),
2181                rows_per_image: Some(uv_h),
2182            },
2183            wgpu::Extent3d {
2184                width: uv_w,
2185                height: uv_h,
2186                depth_or_array_layers: 1,
2187            },
2188        );
2189
2190        self.evict_budget_excess();
2191        Ok(())
2192    }
2193
2194    pub fn remove_image(&mut self, handle: u64) {
2195        if let Some(img) = self.images.remove(&handle) {
2196            let b = match &img {
2197                ImageTex::Rgba { bytes, .. } => *bytes,
2198                ImageTex::Nv12 { bytes, .. } => *bytes,
2199            };
2200            self.image_bytes_total = self.image_bytes_total.saturating_sub(b);
2201        }
2202    }
2203
2204    // Legacy support from Step 1 instructions (temporary until platform render logic is fully swapped)
2205    pub fn register_image_from_bytes(&mut self, data: &[u8], srgb: bool) -> u64 {
2206        let handle = self.next_image_handle;
2207        self.next_image_handle += 1;
2208        if let Err(e) = self.set_image_from_bytes(handle, data, srgb) {
2209            log::error!("Failed to register image: {e}");
2210        }
2211        handle
2212    }
2213
2214    fn evict_unused_images(&mut self) {
2215        let now = self.frame_index;
2216        let evict_after = self.image_evict_after_frames;
2217
2218        // Time based eviction
2219        let mut to_remove = Vec::new();
2220        for (h, t) in self.images.iter() {
2221            let last = match t {
2222                ImageTex::Rgba {
2223                    last_used_frame, ..
2224                } => *last_used_frame,
2225                ImageTex::Nv12 {
2226                    last_used_frame, ..
2227                } => *last_used_frame,
2228            };
2229            if now.saturating_sub(last) > evict_after {
2230                to_remove.push(*h);
2231            }
2232        }
2233        for h in to_remove {
2234            self.remove_image(h);
2235        }
2236
2237        self.evict_budget_excess();
2238    }
2239
2240    fn evict_budget_excess(&mut self) {
2241        if self.image_bytes_total <= self.image_budget_bytes {
2242            return;
2243        }
2244        // Collect (handle, last_used, bytes)
2245        let mut candidates: Vec<(u64, u64, u64)> = self
2246            .images
2247            .iter()
2248            .map(|(h, t)| {
2249                let (last, bytes) = match t {
2250                    ImageTex::Rgba {
2251                        last_used_frame,
2252                        bytes,
2253                        ..
2254                    } => (*last_used_frame, *bytes),
2255                    ImageTex::Nv12 {
2256                        last_used_frame,
2257                        bytes,
2258                        ..
2259                    } => (*last_used_frame, *bytes),
2260                };
2261                (*h, last, bytes)
2262            })
2263            .collect();
2264
2265        // Sort by last_used ascending (LRU first)
2266        candidates.sort_by_key(|k| k.1);
2267
2268        let now = self.frame_index;
2269        for (h, last, _bytes) in candidates {
2270            if self.image_bytes_total <= self.image_budget_bytes {
2271                break;
2272            }
2273            // Don't evict something used this frame
2274            if last == now {
2275                continue;
2276            }
2277            self.remove_image(h);
2278        }
2279    }
2280
2281    /// Enable or disable linear working-space rendering.
2282    /// When enabled, the scene is rendered into an Rgba16Float intermediate
2283    /// and a final full-screen pass applies the display OETF.
2284    pub fn set_working_space(&mut self, enabled: bool) {
2285        if enabled == self.working_space {
2286            return;
2287        }
2288        self.working_space = enabled;
2289        if enabled {
2290            self.ensure_display_pipeline();
2291            self.recreate_working_space_texture();
2292        } else {
2293            self.ws_tex = None;
2294            self.ws_view = None;
2295            self.ws_bind = None;
2296        }
2297    }
2298
2299    fn ensure_display_pipeline(&mut self) {
2300        if self.display_pipeline.is_some() {
2301            return;
2302        }
2303
2304        let layout = self
2305            .device
2306            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2307                label: Some("display transform layout"),
2308                entries: &[
2309                    wgpu::BindGroupLayoutEntry {
2310                        binding: 0,
2311                        visibility: wgpu::ShaderStages::FRAGMENT,
2312                        ty: wgpu::BindingType::Texture {
2313                            multisampled: false,
2314                            view_dimension: wgpu::TextureViewDimension::D2,
2315                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
2316                        },
2317                        count: None,
2318                    },
2319                    wgpu::BindGroupLayoutEntry {
2320                        binding: 1,
2321                        visibility: wgpu::ShaderStages::FRAGMENT,
2322                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
2323                        count: None,
2324                    },
2325                ],
2326            });
2327        self.display_layout = Some(layout);
2328
2329        let shader = self
2330            .device
2331            .create_shader_module(wgpu::ShaderModuleDescriptor {
2332                label: Some("display_transform.wgsl"),
2333                source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
2334                    "shaders/display_transform.wgsl"
2335                ))),
2336            });
2337
2338        let pipeline_layout = self
2339            .device
2340            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
2341                label: Some("display transform pipeline layout"),
2342                bind_group_layouts: &[None, self.display_layout.as_ref()],
2343                immediate_size: 0,
2344            });
2345
2346        let pipeline = self
2347            .device
2348            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
2349                label: Some("display transform pipeline"),
2350                layout: Some(&pipeline_layout),
2351                vertex: wgpu::VertexState {
2352                    module: &shader,
2353                    entry_point: Some("vs_main"),
2354                    buffers: &[],
2355                    compilation_options: wgpu::PipelineCompilationOptions::default(),
2356                },
2357                fragment: Some(wgpu::FragmentState {
2358                    module: &shader,
2359                    entry_point: Some("fs_main"),
2360                    targets: &[Some(wgpu::ColorTargetState {
2361                        format: self.output_format,
2362                        blend: None,
2363                        write_mask: wgpu::ColorWrites::ALL,
2364                    })],
2365                    compilation_options: wgpu::PipelineCompilationOptions::default(),
2366                }),
2367                primitive: wgpu::PrimitiveState::default(),
2368                depth_stencil: None,
2369                multisample: wgpu::MultisampleState::default(),
2370                multiview_mask: None,
2371                cache: None,
2372            });
2373        self.display_pipeline = Some(pipeline);
2374    }
2375
2376    /// Resize the render target dimensions.
2377    ///
2378    /// Recreates MSAA, depth-stencil, and working-space textures to match the
2379    /// new size..
2380    pub fn resize(&mut self, width: u32, height: u32) {
2381        self.output_width = width;
2382        self.output_height = height;
2383        self.recreate_msaa_and_depth_stencil();
2384        self.recreate_working_space_texture();
2385    }
2386
2387    fn recreate_working_space_texture(&mut self) {
2388        if !self.working_space {
2389            return;
2390        }
2391        let w = self.output_width.max(1);
2392        let h = self.output_height.max(1);
2393
2394        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2395            label: Some("working space"),
2396            size: wgpu::Extent3d {
2397                width: w,
2398                height: h,
2399                depth_or_array_layers: 1,
2400            },
2401            mip_level_count: 1,
2402            sample_count: 1,
2403            dimension: wgpu::TextureDimension::D2,
2404            format: wgpu::TextureFormat::Rgba16Float,
2405            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
2406            view_formats: &[],
2407        });
2408        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2409
2410        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2411            label: Some("working space bind"),
2412            layout: self.display_layout.as_ref().unwrap(),
2413            entries: &[
2414                wgpu::BindGroupEntry {
2415                    binding: 0,
2416                    resource: wgpu::BindingResource::TextureView(&view),
2417                },
2418                wgpu::BindGroupEntry {
2419                    binding: 1,
2420                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2421                },
2422            ],
2423        });
2424
2425        self.ws_tex = Some(tex);
2426        self.ws_view = Some(view);
2427        self.ws_bind = Some(bind);
2428    }
2429
2430    fn recreate_msaa_and_depth_stencil(&mut self) {
2431        if self.msaa_samples > 1 {
2432            let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2433                label: Some("msaa color"),
2434                size: wgpu::Extent3d {
2435                    width: self.output_width.max(1),
2436                    height: self.output_height.max(1),
2437                    depth_or_array_layers: 1,
2438                },
2439                mip_level_count: 1,
2440                sample_count: self.msaa_samples,
2441                dimension: wgpu::TextureDimension::D2,
2442                format: self.output_format,
2443                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
2444                view_formats: &[],
2445            });
2446            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2447            self.msaa_tex = Some(tex);
2448            self.msaa_view = Some(view);
2449        } else {
2450            self.msaa_tex = None;
2451            self.msaa_view = None;
2452        }
2453
2454        self.depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
2455            label: Some("depth-stencil (stencil clips)"),
2456            size: wgpu::Extent3d {
2457                width: self.output_width.max(1),
2458                height: self.output_height.max(1),
2459                depth_or_array_layers: 1,
2460            },
2461            mip_level_count: 1,
2462            sample_count: self.msaa_samples,
2463            dimension: wgpu::TextureDimension::D2,
2464            format: wgpu::TextureFormat::Depth24PlusStencil8,
2465            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
2466            view_formats: &[],
2467        });
2468        self.depth_stencil_view = self
2469            .depth_stencil_tex
2470            .create_view(&wgpu::TextureViewDescriptor::default());
2471    }
2472
2473
2474
2475    fn get_or_create_layer(
2476        &mut self,
2477        layer_id: u32,
2478        width: u32,
2479        height: u32,
2480        rect: repose_core::Rect,
2481    ) {
2482        let needs_alloc = match self.layer_pool.get(&layer_id) {
2483            Some(lt) => lt.width != width || lt.height != height,
2484            None => true,
2485        };
2486        if !needs_alloc {
2487            return;
2488        }
2489        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2490            label: Some("graphics layer"),
2491            size: wgpu::Extent3d {
2492                width: width.max(1),
2493                height: height.max(1),
2494                depth_or_array_layers: 1,
2495            },
2496            mip_level_count: 1,
2497            sample_count: 1,
2498            dimension: wgpu::TextureDimension::D2,
2499            format: self.output_format,
2500            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
2501            view_formats: &[],
2502        });
2503        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2504        let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2505            label: Some("layer bind"),
2506            layout: &self.image_bind_layout_rgba,
2507            entries: &[
2508                wgpu::BindGroupEntry {
2509                    binding: 0,
2510                    resource: wgpu::BindingResource::TextureView(&view),
2511                },
2512                wgpu::BindGroupEntry {
2513                    binding: 1,
2514                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
2515                },
2516            ],
2517        });
2518        let depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
2519            label: Some("graphics layer depth-stencil"),
2520            size: wgpu::Extent3d {
2521                width: width.max(1),
2522                height: height.max(1),
2523                depth_or_array_layers: 1,
2524            },
2525            mip_level_count: 1,
2526            sample_count: 1,
2527            dimension: wgpu::TextureDimension::D2,
2528            format: wgpu::TextureFormat::Depth24PlusStencil8,
2529            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
2530            view_formats: &[],
2531        });
2532        let depth_stencil_view =
2533            depth_stencil_tex.create_view(&wgpu::TextureViewDescriptor::default());
2534        self.layer_pool.insert(
2535            layer_id,
2536            LayerTarget {
2537                texture: tex,
2538                view,
2539                bind,
2540                depth_stencil_tex,
2541                depth_stencil_view,
2542                width,
2543                height,
2544                rect_px: (rect.x, rect.y, rect.w, rect.h),
2545            },
2546        );
2547    }
2548
2549    fn atlas_bind_group_mask(&self) -> wgpu::BindGroup {
2550        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2551            label: Some("atlas bind"),
2552            layout: &self.text_bind_layout,
2553            entries: &[
2554                wgpu::BindGroupEntry {
2555                    binding: 0,
2556                    resource: wgpu::BindingResource::TextureView(&self.atlas_mask.view),
2557                },
2558                wgpu::BindGroupEntry {
2559                    binding: 1,
2560                    resource: wgpu::BindingResource::Sampler(&self.atlas_mask.sampler),
2561                },
2562            ],
2563        })
2564    }
2565
2566    fn atlas_bind_group_color(&self) -> wgpu::BindGroup {
2567        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2568            label: Some("atlas bind color"),
2569            layout: &self.text_bind_layout,
2570            entries: &[
2571                wgpu::BindGroupEntry {
2572                    binding: 0,
2573                    resource: wgpu::BindingResource::TextureView(&self.atlas_color.view),
2574                },
2575                wgpu::BindGroupEntry {
2576                    binding: 1,
2577                    resource: wgpu::BindingResource::Sampler(&self.atlas_color.sampler),
2578                },
2579            ],
2580        })
2581    }
2582
2583    fn upload_glyph_mask(&mut self, key: repose_text::GlyphKey, px: f32) -> Option<GlyphInfo> {
2584        let keyp = (key, px.to_bits());
2585        if let Some(info) = self.atlas_mask.map.get(&keyp) {
2586            return Some(*info);
2587        }
2588
2589        let gb = repose_text::rasterize(key, px)?;
2590        if gb.w == 0 || gb.h == 0 || gb.data.is_empty() {
2591            return None;
2592        }
2593
2594        let coverage = swash_to_a8_coverage(gb.content, &gb.data)?;
2595
2596        let w = gb.w.max(1);
2597        let h = gb.h.max(1);
2598
2599        if !self.alloc_space_mask(w, h) {
2600            self.grow_mask_and_rebuild();
2601        }
2602        if !self.alloc_space_mask(w, h) {
2603            return None;
2604        }
2605        let x = self.atlas_mask.next_x;
2606        let y = self.atlas_mask.next_y;
2607        self.atlas_mask.next_x += w + 1;
2608        self.atlas_mask.row_h = self.atlas_mask.row_h.max(h + 1);
2609
2610        let layout = wgpu::TexelCopyBufferLayout {
2611            offset: 0,
2612            bytes_per_row: Some(w),
2613            rows_per_image: Some(h),
2614        };
2615        let size = wgpu::Extent3d {
2616            width: w,
2617            height: h,
2618            depth_or_array_layers: 1,
2619        };
2620        self.queue.write_texture(
2621            wgpu::TexelCopyTextureInfoBase {
2622                texture: &self.atlas_mask.tex,
2623                mip_level: 0,
2624                origin: wgpu::Origin3d { x, y, z: 0 },
2625                aspect: wgpu::TextureAspect::All,
2626            },
2627            &coverage,
2628            layout,
2629            size,
2630        );
2631
2632        let info = GlyphInfo {
2633            u0: x as f32 / self.atlas_mask.size as f32,
2634            v0: y as f32 / self.atlas_mask.size as f32,
2635            u1: (x + w) as f32 / self.atlas_mask.size as f32,
2636            v1: (y + h) as f32 / self.atlas_mask.size as f32,
2637            w: w as f32,
2638            h: h as f32,
2639            bearing_x: 0.0,
2640            bearing_y: 0.0,
2641            advance: 0.0,
2642        };
2643        self.atlas_mask.map.insert(keyp, info);
2644        Some(info)
2645    }
2646
2647    fn upload_glyph_color(&mut self, key: repose_text::GlyphKey, px: f32) -> Option<GlyphInfo> {
2648        let keyp = (key, px.to_bits());
2649        if let Some(info) = self.atlas_color.map.get(&keyp) {
2650            return Some(*info);
2651        }
2652        let gb = repose_text::rasterize(key, px)?;
2653        if !matches!(gb.content, repose_text::SwashContent::Color) {
2654            return None;
2655        }
2656        let w = gb.w.max(1);
2657        let h = gb.h.max(1);
2658        if !self.alloc_space_color(w, h) {
2659            self.grow_color_and_rebuild();
2660        }
2661        if !self.alloc_space_color(w, h) {
2662            return None;
2663        }
2664        let x = self.atlas_color.next_x;
2665        let y = self.atlas_color.next_y;
2666        self.atlas_color.next_x += w + 1;
2667        self.atlas_color.row_h = self.atlas_color.row_h.max(h + 1);
2668
2669        let layout = wgpu::TexelCopyBufferLayout {
2670            offset: 0,
2671            bytes_per_row: Some(w * 4),
2672            rows_per_image: Some(h),
2673        };
2674        let size = wgpu::Extent3d {
2675            width: w,
2676            height: h,
2677            depth_or_array_layers: 1,
2678        };
2679        self.queue.write_texture(
2680            wgpu::TexelCopyTextureInfoBase {
2681                texture: &self.atlas_color.tex,
2682                mip_level: 0,
2683                origin: wgpu::Origin3d { x, y, z: 0 },
2684                aspect: wgpu::TextureAspect::All,
2685            },
2686            &gb.data,
2687            layout,
2688            size,
2689        );
2690        let info = GlyphInfo {
2691            u0: x as f32 / self.atlas_color.size as f32,
2692            v0: y as f32 / self.atlas_color.size as f32,
2693            u1: (x + w) as f32 / self.atlas_color.size as f32,
2694            v1: (y + h) as f32 / self.atlas_color.size as f32,
2695            w: w as f32,
2696            h: h as f32,
2697            bearing_x: 0.0,
2698            bearing_y: 0.0,
2699            advance: 0.0,
2700        };
2701        self.atlas_color.map.insert(keyp, info);
2702        Some(info)
2703    }
2704
2705    fn alloc_space_mask(&mut self, w: u32, h: u32) -> bool {
2706        if self.atlas_mask.next_x + w + 1 >= self.atlas_mask.size {
2707            self.atlas_mask.next_x = 1;
2708            self.atlas_mask.next_y += self.atlas_mask.row_h + 1;
2709            self.atlas_mask.row_h = 0;
2710        }
2711        if self.atlas_mask.next_y + h + 1 >= self.atlas_mask.size {
2712            return false;
2713        }
2714        true
2715    }
2716
2717    fn grow_mask_and_rebuild(&mut self) {
2718        let new_size = (self.atlas_mask.size * 2).min(4096);
2719        if new_size == self.atlas_mask.size {
2720            return;
2721        }
2722        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2723            label: Some("glyph atlas A8 (grown)"),
2724            size: wgpu::Extent3d {
2725                width: new_size,
2726                height: new_size,
2727                depth_or_array_layers: 1,
2728            },
2729            mip_level_count: 1,
2730            sample_count: 1,
2731            dimension: wgpu::TextureDimension::D2,
2732            format: wgpu::TextureFormat::R8Unorm,
2733            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2734            view_formats: &[],
2735        });
2736        self.atlas_mask.tex = tex;
2737        self.atlas_mask.view = self
2738            .atlas_mask
2739            .tex
2740            .create_view(&wgpu::TextureViewDescriptor::default());
2741        self.atlas_mask.size = new_size;
2742        self.atlas_mask.next_x = 1;
2743        self.atlas_mask.next_y = 1;
2744        self.atlas_mask.row_h = 0;
2745        let keys: Vec<(repose_text::GlyphKey, u32)> = self.atlas_mask.map.keys().copied().collect();
2746        self.atlas_mask.map.clear();
2747        for (k, px_bits) in keys {
2748            let _ = self.upload_glyph_mask(k, f32::from_bits(px_bits));
2749        }
2750    }
2751
2752    fn alloc_space_color(&mut self, w: u32, h: u32) -> bool {
2753        if self.atlas_color.next_x + w + 1 >= self.atlas_color.size {
2754            self.atlas_color.next_x = 1;
2755            self.atlas_color.next_y += self.atlas_color.row_h + 1;
2756            self.atlas_color.row_h = 0;
2757        }
2758        if self.atlas_color.next_y + h + 1 >= self.atlas_color.size {
2759            return false;
2760        }
2761        true
2762    }
2763
2764    fn grow_color_and_rebuild(&mut self) {
2765        let new_size = (self.atlas_color.size * 2).min(4096);
2766        if new_size == self.atlas_color.size {
2767            return;
2768        }
2769        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
2770            label: Some("glyph atlas RGBA (grown)"),
2771            size: wgpu::Extent3d {
2772                width: new_size,
2773                height: new_size,
2774                depth_or_array_layers: 1,
2775            },
2776            mip_level_count: 1,
2777            sample_count: 1,
2778            dimension: wgpu::TextureDimension::D2,
2779            format: wgpu::TextureFormat::Rgba8UnormSrgb,
2780            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2781            view_formats: &[],
2782        });
2783        self.atlas_color.tex = tex;
2784        self.atlas_color.view = self
2785            .atlas_color
2786            .tex
2787            .create_view(&wgpu::TextureViewDescriptor::default());
2788        self.atlas_color.size = new_size;
2789        self.atlas_color.next_x = 1;
2790        self.atlas_color.next_y = 1;
2791        self.atlas_color.row_h = 0;
2792        let keys: Vec<(repose_text::GlyphKey, u32)> =
2793            self.atlas_color.map.keys().copied().collect();
2794        self.atlas_color.map.clear();
2795        for (k, px_bits) in keys {
2796            let _ = self.upload_glyph_color(k, f32::from_bits(px_bits));
2797        }
2798    }
2799}
2800
2801fn brush_to_instance_fields(brush: &Brush) -> (u32, [f32; 4], [f32; 4], [f32; 2], [f32; 2]) {
2802    match brush {
2803        Brush::Solid(c) => (
2804            0u32,
2805            c.to_linear(),
2806            [0.0, 0.0, 0.0, 0.0],
2807            [0.0, 0.0],
2808            [0.0, 1.0],
2809        ),
2810        Brush::Linear {
2811            start,
2812            end,
2813            start_color,
2814            end_color,
2815        } => (
2816            1u32,
2817            start_color.to_linear(),
2818            end_color.to_linear(),
2819            [start.x, start.y],
2820            [end.x, end.y],
2821        ),
2822        _ => (0u32, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2]),
2823    }
2824}
2825
2826fn brush_to_solid_color(brush: &Brush) -> [f32; 4] {
2827    match brush {
2828        Brush::Solid(c) => c.to_linear(),
2829        Brush::Linear { start_color, .. } => start_color.to_linear(),
2830        _ => [0.0; 4],
2831    }
2832}
2833
2834fn init_atlas_mask(device: &wgpu::Device) -> AtlasA8 {
2835    let size = 1024u32;
2836    let tex = device.create_texture(&wgpu::TextureDescriptor {
2837        label: Some("glyph atlas A8"),
2838        size: wgpu::Extent3d {
2839            width: size,
2840            height: size,
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::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2848        view_formats: &[],
2849    });
2850    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2851    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2852        label: Some("glyph atlas sampler A8"),
2853        address_mode_u: wgpu::AddressMode::ClampToEdge,
2854        address_mode_v: wgpu::AddressMode::ClampToEdge,
2855        address_mode_w: wgpu::AddressMode::ClampToEdge,
2856        mag_filter: wgpu::FilterMode::Linear,
2857        min_filter: wgpu::FilterMode::Linear,
2858        mipmap_filter: wgpu::MipmapFilterMode::Linear,
2859        ..Default::default()
2860    });
2861
2862    AtlasA8 {
2863        tex,
2864        view,
2865        sampler,
2866        size,
2867        next_x: 1,
2868        next_y: 1,
2869        row_h: 0,
2870        map: HashMap::new(),
2871    }
2872}
2873
2874fn init_atlas_color(device: &wgpu::Device) -> AtlasRGBA {
2875    let size = 1024u32;
2876    let tex = device.create_texture(&wgpu::TextureDescriptor {
2877        label: Some("glyph atlas RGBA"),
2878        size: wgpu::Extent3d {
2879            width: size,
2880            height: size,
2881            depth_or_array_layers: 1,
2882        },
2883        mip_level_count: 1,
2884        sample_count: 1,
2885        dimension: wgpu::TextureDimension::D2,
2886        format: wgpu::TextureFormat::Rgba8UnormSrgb,
2887        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2888        view_formats: &[],
2889    });
2890    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
2891    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2892        label: Some("glyph atlas sampler RGBA"),
2893        address_mode_u: wgpu::AddressMode::ClampToEdge,
2894        address_mode_v: wgpu::AddressMode::ClampToEdge,
2895        address_mode_w: wgpu::AddressMode::ClampToEdge,
2896        mag_filter: wgpu::FilterMode::Linear,
2897        min_filter: wgpu::FilterMode::Linear,
2898        mipmap_filter: wgpu::MipmapFilterMode::Linear,
2899        ..Default::default()
2900    });
2901    AtlasRGBA {
2902        tex,
2903        view,
2904        sampler,
2905        size,
2906        next_x: 1,
2907        next_y: 1,
2908        row_h: 0,
2909        map: HashMap::new(),
2910    }
2911}
2912
2913#[cfg(feature = "winit-surface")]
2914impl RenderBackend for WgpuSurfaceBackend {
2915    fn configure_surface(&mut self, width: u32, height: u32) {
2916        if width == 0 || height == 0 {
2917            return;
2918        }
2919        self.renderer.output_width = width;
2920        self.renderer.output_height = height;
2921        if let Some(ref mut config) = self.surface_config {
2922            config.width = width;
2923            config.height = height;
2924        }
2925        if let (Some(surface), Some(config)) = (self.surface.as_ref(), self.surface_config.as_ref()) {
2926            surface.configure(&self.renderer.device, config);
2927        }
2928        self.renderer.recreate_msaa_and_depth_stencil();
2929        self.renderer.recreate_working_space_texture();
2930    }
2931
2932    fn frame(&mut self, scene: &Scene, _glyph_cfg: GlyphRasterConfig) {
2933        let surface = self.surface.as_ref().expect("WgpuSurfaceBackend::frame() requires a surface (use from_device + render_to_view instead)");
2934        let surface_config = self.surface_config.as_ref().expect("surface_config required for frame()");
2935
2936        self.renderer.frame_index = self.renderer.frame_index.wrapping_add(1);
2937        self.renderer.slug_cache.next_frame();
2938
2939        if self.renderer.output_width == 0 || self.renderer.output_height == 0 {
2940            return;
2941        }
2942
2943        let mut retries = 0u32;
2944        const MAX_RETRIES: u32 = 4;
2945        let frame = loop {
2946            match surface.get_current_texture() {
2947                wgpu::CurrentSurfaceTexture::Success(f) => break f,
2948                wgpu::CurrentSurfaceTexture::Suboptimal(f) => {
2949                    log::warn!("suboptimal surface; reconfiguring");
2950                    surface.configure(&self.renderer.device, surface_config);
2951                    break f;
2952                }
2953                wgpu::CurrentSurfaceTexture::Outdated => {
2954                    retries += 1;
2955                    if retries >= MAX_RETRIES {
2956                        log::warn!("surface outdated persisted after {MAX_RETRIES} retries; skipping frame");
2957                        return;
2958                    }
2959                    log::warn!("surface outdated; reconfiguring");
2960                    surface.configure(&self.renderer.device, surface_config);
2961                }
2962                wgpu::CurrentSurfaceTexture::Lost => {
2963                    retries += 1;
2964                    if retries >= MAX_RETRIES {
2965                        log::warn!("surface lost persisted after {MAX_RETRIES} retries; skipping frame");
2966                        return;
2967                    }
2968                    log::warn!("surface lost; reconfiguring");
2969                    surface.configure(&self.renderer.device, surface_config);
2970                }
2971                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
2972                    request_frame();
2973                    return;
2974                }
2975                wgpu::CurrentSurfaceTexture::Validation => {
2976                    retries += 1;
2977                    if retries >= MAX_RETRIES {
2978                        log::warn!("surface validation persisted after {MAX_RETRIES} retries; skipping frame");
2979                        return;
2980                    }
2981                    surface.configure(&self.renderer.device, surface_config);
2982                }
2983            }
2984        };
2985
2986        let swap_view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());
2987        let mut encoder = self.renderer.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
2988            label: Some("frame encoder"),
2989        });
2990
2991        let clear_color = Some([
2992            scene.clear_color.0 as f64 / 255.0,
2993            scene.clear_color.1 as f64 / 255.0,
2994            scene.clear_color.2 as f64 / 255.0,
2995            scene.clear_color.3 as f64 / 255.0,
2996        ]);
2997
2998        self.renderer.render_scene_to_encoder(scene, &mut encoder, &swap_view, clear_color);
2999
3000        self.renderer.queue.submit(std::iter::once(encoder.finish()));
3001        if let Err(e) = catch_unwind(AssertUnwindSafe(|| self.renderer.queue.present(frame))) {
3002            log::warn!("queue.present panicked: {:?}", e);
3003        }
3004    }
3005}
3006
3007impl WgpuSceneRenderer {
3008    pub fn render_scene_to_encoder(
3009        &mut self,
3010        scene: &Scene,
3011        encoder: &mut wgpu::CommandEncoder,
3012        target_view: &wgpu::TextureView,
3013        clear_color_override: Option<[f64; 4]>,
3014    ) {
3015        fn to_ndc(x: f32, y: f32, w: f32, h: f32, fb_w: f32, fb_h: f32) -> [f32; 4] {
3016            let x0 = (x / fb_w) * 2.0 - 1.0;
3017            let y0 = 1.0 - (y / fb_h) * 2.0;
3018            let x1 = ((x + w) / fb_w) * 2.0 - 1.0;
3019            let y1 = 1.0 - ((y + h) / fb_h) * 2.0;
3020            let min_x = x0.min(x1);
3021            let min_y = y0.min(y1);
3022            let w_ndc = (x1 - x0).abs();
3023            let h_ndc = (y1 - y0).abs();
3024            [min_x, min_y, w_ndc, h_ndc]
3025        }
3026
3027        /// Convert a local-space rect + transform to NDC center-based position+size and rotation.
3028        fn rect_to_instance_ndc(
3029            rect: repose_core::Rect,
3030            transform: &Transform,
3031            fb_w: f32,
3032            fb_h: f32,
3033        ) -> ([f32; 4], [f32; 2]) {
3034            let cx = rect.x + rect.w * 0.5;
3035            let cy = rect.y + rect.h * 0.5;
3036
3037            // Apply full transform to center
3038            let sx = cx * transform.scale_x;
3039            let sy = cy * transform.scale_y;
3040            let cos_a = transform.rotate.cos();
3041            let sin_a = transform.rotate.sin();
3042            let tx = sx * cos_a - sy * sin_a + transform.translate_x;
3043            let ty = sx * sin_a + sy * cos_a + transform.translate_y;
3044
3045            // NDC center
3046            let ndc_cx = (tx / fb_w) * 2.0 - 1.0;
3047            let ndc_cy = 1.0 - (ty / fb_h) * 2.0;
3048            // NDC size (after scale only, no rotation - rotation is done in shader)
3049            let ndc_w = (rect.w * transform.scale_x / fb_w) * 2.0;
3050            let ndc_h = (rect.h * transform.scale_y / fb_h) * 2.0;
3051
3052            ([ndc_cx, ndc_cy, ndc_w, ndc_h], [cos_a, sin_a])
3053        }
3054
3055        fn to_scissor(r: &repose_core::Rect, fb_w: u32, fb_h: u32) -> (u32, u32, u32, u32) {
3056            let mut x = r.x.floor() as i64;
3057            let mut y = r.y.floor() as i64;
3058            let fb_wi = fb_w as i64;
3059            let fb_hi = fb_h as i64;
3060            x = x.clamp(0, fb_wi.saturating_sub(1));
3061            y = y.clamp(0, fb_hi.saturating_sub(1));
3062            let w_req = r.w.ceil().max(1.0) as i64;
3063            let h_req = r.h.ceil().max(1.0) as i64;
3064            let w = (w_req).min(fb_wi - x).max(1);
3065            let h = (h_req).min(fb_hi - y).max(1);
3066            (x as u32, y as u32, w as u32, h as u32)
3067        }
3068
3069        let fb_w = self.output_width as f32;
3070        let fb_h = self.output_height as f32;
3071
3072        let globals = Globals {
3073            ndc_to_px: [fb_w * 0.5, fb_h * 0.5],
3074            _pad: [0.0, 0.0],
3075        };
3076        self.queue
3077            .write_buffer(&self.globals_buf, 0, bytemuck::bytes_of(&globals));
3078
3079        let mut passes: Vec<Pass> = Vec::with_capacity(1);
3080        let clear_color = clear_color_override.unwrap_or_else(|| {
3081            [
3082                scene.clear_color.0 as f64 / 255.0,
3083                scene.clear_color.1 as f64 / 255.0,
3084                scene.clear_color.2 as f64 / 255.0,
3085                scene.clear_color.3 as f64 / 255.0,
3086            ]
3087        });
3088        let mut current_pass: Pass = Pass {
3089            target: PassTarget::Surface,
3090            initial_scissor: (0, 0, self.output_width, self.output_height),
3091            clear_color: Some([
3092                clear_color[0] as f32,
3093                clear_color[1] as f32,
3094                clear_color[2] as f32,
3095                clear_color[3] as f32,
3096            ]),
3097            cmds: Vec::with_capacity(scene.nodes.len()),
3098        };
3099        let mut target_stack: Vec<PassTarget> = Vec::new();
3100        let mut layer_alphas: Vec<(u32, f32, (u32, u32, u32, u32))> = Vec::new();
3101        let mut layer_blurs: Vec<(u32, f32, f32)> = Vec::new();
3102        let mut current_target_size: (f32, f32) = (fb_w, fb_h);
3103
3104        struct Batch {
3105            rects: Vec<RectInstance>,
3106            borders: Vec<BorderInstance>,
3107            ellipses: Vec<EllipseInstance>,
3108            e_borders: Vec<EllipseBorderInstance>,
3109            arcs: Vec<ArcInstance>,
3110            masks: Vec<GlyphInstance>,
3111            colors: Vec<GlyphInstance>,
3112            nv12s: Vec<Nv12Instance>,
3113        }
3114
3115        impl Batch {
3116            fn new() -> Self {
3117                Self {
3118                    rects: vec![],
3119                    borders: vec![],
3120                    ellipses: vec![],
3121                    e_borders: vec![],
3122                    arcs: vec![],
3123                    masks: vec![],
3124                    colors: vec![],
3125                    nv12s: vec![],
3126                }
3127            }
3128
3129            fn is_empty(&self) -> bool {
3130                self.rects.is_empty()
3131                    && self.borders.is_empty()
3132                    && self.ellipses.is_empty()
3133                    && self.e_borders.is_empty()
3134                    && self.arcs.is_empty()
3135                    && self.masks.is_empty()
3136                    && self.colors.is_empty()
3137                    && self.nv12s.is_empty()
3138            }
3139
3140            fn flush(
3141                &mut self,
3142                pipes: (
3143                    &mut InstancedPipe<RectInstance>,
3144                    &mut InstancedPipe<BorderInstance>,
3145                    &mut InstancedPipe<EllipseInstance>,
3146                    &mut InstancedPipe<EllipseBorderInstance>,
3147                    &mut InstancedPipe<ArcInstance>,
3148                ),
3149                glyph_pipes: (
3150                    &mut InstancedPipe<GlyphInstance>,
3151                    &mut InstancedPipe<GlyphInstance>,
3152                ),
3153                nv12_pipe: &mut InstancedPipe<Nv12Instance>,
3154                device: &wgpu::Device,
3155                queue: &wgpu::Queue,
3156                cmds: &mut Vec<Cmd>,
3157            ) {
3158                let (rects, borders, ellipses, e_borders, arcs) = pipes;
3159                let (masks, colors) = glyph_pipes;
3160
3161                macro_rules! flush_one {
3162                    ($buf:ident, $pipe:expr, $variant:ident) => {
3163                        if !self.$buf.is_empty() {
3164                            if let Some((off, cnt)) = $pipe.upload(device, queue, &self.$buf) {
3165                                cmds.push(Cmd::$variant { off, cnt });
3166                            }
3167                            self.$buf.clear();
3168                        }
3169                    };
3170                }
3171
3172                flush_one!(rects, rects, Rect);
3173                flush_one!(borders, borders, Border);
3174                flush_one!(ellipses, ellipses, Ellipse);
3175                flush_one!(e_borders, e_borders, EllipseBorder);
3176                flush_one!(arcs, arcs, Arc);
3177                flush_one!(masks, masks, GlyphsMask);
3178                flush_one!(colors, colors, GlyphsColor);
3179
3180                if !self.nv12s.is_empty() {
3181                    if let Some((off, cnt)) = nv12_pipe.upload(device, queue, &self.nv12s) {
3182                        let _ = (off, cnt);
3183                    }
3184                    self.nv12s.clear();
3185                }
3186            }
3187        }
3188
3189        self.rects.reset();
3190        self.borders.reset();
3191        self.ellipses.reset();
3192        self.ellipse_borders.reset();
3193        self.arcs.reset();
3194        self.glyph_mask.reset();
3195        self.glyph_color.reset();
3196        self.clip_ring.reset();
3197        self.blur_ring.reset();
3198        self.nv12.reset();
3199
3200        self.slug_ring.reset();
3201        let mut batch = Batch::new();
3202        let mut slug_verts_local: Vec<slug::TessVertex> = Vec::new();
3203        let mut transform_stack: Vec<Transform> = vec![Transform::identity()];
3204        let mut scissor_stack: Vec<repose_core::Rect> = Vec::with_capacity(8);
3205        let root_clip_rect = repose_core::Rect {
3206            x: 0.0,
3207            y: 0.0,
3208            w: fb_w,
3209            h: fb_h,
3210        };
3211
3212        let mut current_prim: Option<&'static str> = None;
3213
3214        macro_rules! flush_if_prim_changed {
3215            ($prim:literal, $pipe:expr) => {
3216                if current_prim != Some($prim) {
3217                    flush_batch!();
3218                    current_prim = Some($prim);
3219                }
3220            };
3221        }
3222
3223        macro_rules! flush_batch {
3224            () => {
3225                if !batch.is_empty() {
3226                    batch.flush(
3227                        (
3228                            &mut self.rects,
3229                            &mut self.borders,
3230                            &mut self.ellipses,
3231                            &mut self.ellipse_borders,
3232                            &mut self.arcs,
3233                        ),
3234                        (&mut self.glyph_mask, &mut self.glyph_color),
3235                        &mut self.nv12,
3236                        &self.device,
3237                        &self.queue,
3238                        &mut current_pass.cmds,
3239                    )
3240                }
3241            };
3242        }
3243        for node in &scene.nodes {
3244            let t_identity = Transform::identity();
3245            let current_transform = transform_stack.last().unwrap_or(&t_identity);
3246
3247            match node {
3248                SceneNode::Rect {
3249                    rect,
3250                    brush,
3251                    radius,
3252                } => {
3253                    flush_if_prim_changed!("rect", &self.rects);
3254                    let (ndc, sin_cos) = rect_to_instance_ndc(
3255                        *rect,
3256                        current_transform,
3257                        current_target_size.0,
3258                        current_target_size.1,
3259                    );
3260                    let (brush_type, color0, color1, grad_start, grad_end) =
3261                        brush_to_instance_fields(brush);
3262                    batch.rects.push(RectInstance {
3263                        xywh: ndc,
3264                        radii: *radius,
3265                        brush_type,
3266                        _pad: [0.0; 3],
3267                        color0,
3268                        color1,
3269                        grad_start,
3270                        grad_end,
3271                        sin_cos,
3272                    });
3273                }
3274                SceneNode::Border {
3275                    rect,
3276                    color,
3277                    width,
3278                    radius,
3279                } => {
3280                    flush_if_prim_changed!("border", &self.borders);
3281                    let (ndc, sin_cos) = rect_to_instance_ndc(
3282                        *rect,
3283                        current_transform,
3284                        current_target_size.0,
3285                        current_target_size.1,
3286                    );
3287                    batch.borders.push(BorderInstance {
3288                        xywh: ndc,
3289                        radii: *radius,
3290                        stroke: *width,
3291                        color: color.to_linear(),
3292                        sin_cos,
3293                    });
3294                }
3295                SceneNode::Ellipse { rect, brush } => {
3296                    flush_if_prim_changed!("ellipse", &self.ellipses);
3297                    let (ndc, sin_cos) = rect_to_instance_ndc(
3298                        *rect,
3299                        current_transform,
3300                        current_target_size.0,
3301                        current_target_size.1,
3302                    );
3303                    let color = brush_to_solid_color(brush);
3304                    batch.ellipses.push(EllipseInstance {
3305                        xywh: ndc,
3306                        color,
3307                        sin_cos,
3308                    });
3309                }
3310                SceneNode::EllipseBorder { rect, color, width } => {
3311                    flush_if_prim_changed!("ellipse_border", &self.ellipse_borders);
3312                    let (ndc, sin_cos) = rect_to_instance_ndc(
3313                        *rect,
3314                        current_transform,
3315                        current_target_size.0,
3316                        current_target_size.1,
3317                    );
3318                    let pad_px = *width * 0.5 + 2.0;
3319                    let pad = (pad_px / current_target_size.0) * 2.0;
3320                    batch.e_borders.push(EllipseBorderInstance {
3321                        xywh: ndc,
3322                        stroke: *width,
3323                        pad,
3324                        color: color.to_linear(),
3325                        sin_cos,
3326                    });
3327                }
3328                SceneNode::Arc {
3329                    rect,
3330                    start_angle,
3331                    sweep_angle,
3332                    stroke_width,
3333                    color,
3334                    cap,
3335                } => {
3336                    flush_if_prim_changed!("arc", &self.arcs);
3337                    let (ndc, sin_cos) = rect_to_instance_ndc(
3338                        *rect,
3339                        current_transform,
3340                        current_target_size.0,
3341                        current_target_size.1,
3342                    );
3343                    let pad_px = *stroke_width * 0.5 + 2.0;
3344                    let pad = (pad_px / current_target_size.0) * 2.0;
3345                    let cap_val = match cap {
3346                        StrokeCap::Butt => 0.0,
3347                        StrokeCap::Round => 1.0,
3348                        StrokeCap::Square => 2.0,
3349                    };
3350                    batch.arcs.push(ArcInstance {
3351                        xywh: ndc,
3352                        start_angle: *start_angle,
3353                        sweep_angle: *sweep_angle,
3354                        stroke: *stroke_width,
3355                        pad,
3356                        color: color.to_linear(),
3357                        sin_cos,
3358                        cap: cap_val,
3359                    });
3360                }
3361                SceneNode::Text {
3362                    rect,
3363                    text,
3364                    color,
3365                    size,
3366                    font_family,
3367                    text_align: _,
3368                    font_weight,
3369                    font_style,
3370                    text_decoration,
3371                    letter_spacing,
3372                    line_height: _,
3373                    extra_style,
3374                    url: _,
3375                    font_variation_settings,
3376                } => {
3377                    flush_batch!(); // flush any prior primitives
3378
3379                    let px = *size;
3380                    let lh_ratio = rect.h / px;
3381                    let fw = font_weight.0;
3382                    let fs = if *font_style == FontStyle::Italic {
3383                        1
3384                    } else {
3385                        0
3386                    };
3387                    let shaped = repose_text::shape_line(
3388                        text.as_ref(),
3389                        px,
3390                        lh_ratio,
3391                        *font_family,
3392                        fw,
3393                        fs,
3394                        *letter_spacing,
3395                        font_variation_settings.as_deref(),
3396                    );
3397                    let baseline_y = shaped.first().map(|g| rect.y + g.y);
3398
3399                    let cos_a = current_transform.rotate.cos();
3400                    let sin_a = current_transform.rotate.sin();
3401                    let has_rotation = current_transform.rotate != 0.0;
3402
3403                    // For rotated text, the pivot is the center of the text rect.
3404                    let pivot_x = rect.x + rect.w * 0.5;
3405                    let pivot_y = rect.y + rect.h * 0.5;
3406
3407                    // Helper: compute NDC for a glyph rect, handling rotation correctly.
3408                    let make_glyph_instance =
3409                        |gx: f32, gy: f32, gw: f32, gh: f32| -> ([f32; 4], [f32; 2]) {
3410                            if has_rotation {
3411                                let corners =
3412                                    [(gx, gy), (gx + gw, gy), (gx + gw, gy + gh), (gx, gy + gh)];
3413                                let mut min_x = f32::MAX;
3414                                let mut max_x = f32::MIN;
3415                                let mut min_y = f32::MAX;
3416                                let mut max_y = f32::MIN;
3417                                for &(x, y) in &corners {
3418                                    let dx = x - pivot_x;
3419                                    let dy = y - pivot_y;
3420                                    let rx = pivot_x + dx * cos_a - dy * sin_a;
3421                                    let ry = pivot_y + dx * sin_a + dy * cos_a;
3422                                    min_x = min_x.min(rx);
3423                                    max_x = max_x.max(rx);
3424                                    min_y = min_y.min(ry);
3425                                    max_y = max_y.max(ry);
3426                                }
3427                                let bb_w = max_x - min_x;
3428                                let bb_h = max_y - min_y;
3429                                let ndc_tl = to_ndc(
3430                                    min_x,
3431                                    min_y,
3432                                    bb_w,
3433                                    bb_h,
3434                                    current_target_size.0,
3435                                    current_target_size.1,
3436                                );
3437                                let ndc = [
3438                                    ndc_tl[0] + ndc_tl[2] * 0.5,
3439                                    ndc_tl[1] + ndc_tl[3] * 0.5,
3440                                    ndc_tl[2],
3441                                    ndc_tl[3],
3442                                ];
3443                                (ndc, [cos_a, sin_a])
3444                            } else {
3445                                rect_to_instance_ndc(
3446                                    repose_core::Rect {
3447                                        x: gx,
3448                                        y: gy,
3449                                        w: gw,
3450                                        h: gh,
3451                                    },
3452                                    current_transform,
3453                                    current_target_size.0,
3454                                    current_target_size.1,
3455                                )
3456                            }
3457                        };
3458
3459                    let baseline_shift_y: f32 = px * extra_style.baseline_shift.0;
3460
3461                    let (
3462                        is_stroke,
3463                        stroke_width,
3464                        stroke_cap,
3465                        stroke_join,
3466                        stroke_miter,
3467                        stroke_path_effect,
3468                    ) = match &extra_style.draw_style {
3469                        repose_core::DrawStyle::Stroke {
3470                            width,
3471                            cap,
3472                            join,
3473                            miter,
3474                            path_effect,
3475                        } => (true, *width, *cap, *join, *miter, path_effect.clone()),
3476                        _ => (
3477                            false,
3478                            0.0,
3479                            repose_core::StrokeCap::Butt,
3480                            repose_core::StrokeJoin::Miter,
3481                            4.0,
3482                            None,
3483                        ),
3484                    };
3485                    let stroke_tess_key = if is_stroke {
3486                        Some(slug::StrokeTessKey::new(
3487                            stroke_width,
3488                            stroke_cap,
3489                            stroke_join,
3490                            stroke_miter,
3491                            &stroke_path_effect,
3492                        ))
3493                    } else {
3494                        None
3495                    };
3496
3497                    for sg in shaped {
3498                        let gx = rect.x + sg.x + sg.bearing_x;
3499                        let gy = rect.y + sg.y - sg.bearing_y + baseline_shift_y;
3500
3501                        // Vector glyph path: tessellated geometry with MSAA.
3502                        if self.slug_enabled {
3503                            let ck = repose_text::lookup_cache_key(sg.key, sg.px);
3504                            if let Some(ref ck) = ck {
3505                                // Check if cached.
3506                                let need_tessellate = self.slug_cache.get(ck).map_or(true, |g| {
3507                                    if is_stroke {
3508                                        let key = stroke_tess_key.as_ref().unwrap();
3509                                        !g.stroke_variants.contains_key(key)
3510                                    } else {
3511                                        g.fill_vertices.is_none()
3512                                    }
3513                                });
3514                                if need_tessellate {
3515                                    if let Some((ck2, commands)) =
3516                                        repose_text::lookup_and_extract_outline(sg.key, sg.px)
3517                                    {
3518                                        let font_size_px = f32::from_bits(ck2.font_size_bits);
3519                                        if is_stroke {
3520                                            self.slug_cache.get_or_insert_stroke(
3521                                                ck2,
3522                                                font_size_px,
3523                                                &commands,
3524                                                stroke_width,
3525                                                stroke_cap,
3526                                                stroke_join,
3527                                                stroke_miter,
3528                                                &stroke_path_effect,
3529                                            );
3530                                        } else {
3531                                            self.slug_cache.get_or_insert(
3532                                                ck2,
3533                                                font_size_px,
3534                                                &commands,
3535                                            );
3536                                        }
3537                                    }
3538                                } else {
3539                                    self.slug_cache.touch(ck);
3540                                }
3541                            }
3542                            if let Some(entry) = ck.as_ref().and_then(|ck| self.slug_cache.get(ck))
3543                            {
3544                                let ox = rect.x + sg.x;
3545                                let oy = rect.y + sg.y + baseline_shift_y;
3546                                let scx = current_transform.scale_x;
3547                                let scy = current_transform.scale_y;
3548                                let ttx = current_transform.translate_x;
3549                                let tty = current_transform.translate_y;
3550
3551                                let tf = |x: f32, y: f32| -> (f32, f32) {
3552                                    if has_rotation {
3553                                        let dx = x - pivot_x;
3554                                        let dy = y - pivot_y;
3555                                        let rx = pivot_x + dx * cos_a - dy * sin_a;
3556                                        let ry = pivot_y + dx * sin_a + dy * cos_a;
3557                                        (rx, ry)
3558                                    } else {
3559                                        (x * scx + ttx, y * scy + tty)
3560                                    }
3561                                };
3562
3563                                let tw = current_target_size.0;
3564                                let th = current_target_size.1;
3565
3566                                let verts = if is_stroke {
3567                                    let key = stroke_tess_key.as_ref().unwrap();
3568                                    entry
3569                                        .stroke_variants
3570                                        .get(key)
3571                                        .map(|v| v.as_slice())
3572                                        .unwrap_or(&[])
3573                                } else {
3574                                    entry.fill_vertices.as_deref().unwrap_or(&[])
3575                                };
3576
3577                                for &v in verts {
3578                                    let (sx, sy) = tf(ox + v[0] * px, oy - v[1] * px);
3579                                    let ndc_x = sx / tw * 2.0 - 1.0;
3580                                    let ndc_y = -(sy / th) * 2.0 + 1.0;
3581                                    slug_verts_local.push(slug::TessVertex {
3582                                        ndc_pos: [ndc_x, ndc_y],
3583                                        color: color.to_linear(),
3584                                    });
3585                                }
3586
3587                                if is_stroke {
3588                                    // Stroke glyphs cannot use atlas fallback...
3589                                    continue;
3590                                }
3591                                continue;
3592                            }
3593                        }
3594
3595                        // Don't use atlas fallback for strokes too
3596                        if is_stroke {
3597                            continue;
3598                        }
3599
3600                        // Atlas fallback: color emoji + failed slug extraction
3601                        if let Some(info) = self.upload_glyph_color(sg.key, sg.px) {
3602                            let (ndc, sin_cos) = make_glyph_instance(gx, gy, info.w, info.h);
3603                            batch.colors.push(GlyphInstance {
3604                                xywh: ndc,
3605                                uv: [info.u0, info.v1, info.u1, info.v0],
3606                                color: color.to_linear(),
3607                                sin_cos,
3608                            });
3609                        } else if let Some(info) = self.upload_glyph_mask(sg.key, sg.px) {
3610                            let (ndc, sin_cos) = make_glyph_instance(gx, gy, info.w, info.h);
3611                            batch.masks.push(GlyphInstance {
3612                                xywh: ndc,
3613                                uv: [info.u0, info.v1, info.u1, info.v0],
3614                                color: color.to_linear(),
3615                                sin_cos,
3616                            });
3617                        }
3618                    }
3619
3620                    // Upload slug vertices if any
3621                    if !slug_verts_local.is_empty() {
3622                        let bytes = bytemuck::cast_slice(&slug_verts_local);
3623                        self.slug_ring.grow_to_fit(&self.device, bytes.len() as u64);
3624                        let (off, _) = self.slug_ring.alloc_write(&self.queue, bytes);
3625                        current_pass.cmds.push(Cmd::GlyphsVector {
3626                            off,
3627                            cnt: slug_verts_local.len() as u32,
3628                        });
3629                        slug_verts_local.clear();
3630                    }
3631
3632                    // Text decoration: underline / strikethrough
3633                    if (text_decoration.underline || text_decoration.strikethrough)
3634                        && let Some(baseline_y) = baseline_y
3635                    {
3636                        flush_batch!();
3637                        current_prim = Some("rect");
3638                        let deco_color = text_decoration.color.unwrap_or(*color);
3639                        let thickness = (px * 0.07).max(1.0);
3640
3641                        if text_decoration.underline {
3642                            let dy = baseline_y + px * 0.1;
3643                            let (ndc, sin_cos) = rect_to_instance_ndc(
3644                                repose_core::Rect {
3645                                    x: rect.x,
3646                                    y: dy,
3647                                    w: rect.w,
3648                                    h: thickness,
3649                                },
3650                                current_transform,
3651                                current_target_size.0,
3652                                current_target_size.1,
3653                            );
3654                            batch.rects.push(RectInstance {
3655                                xywh: ndc,
3656                                radii: [0.0; 4],
3657                                brush_type: 0,
3658                                _pad: [0.0; 3],
3659                                color0: deco_color.to_linear(),
3660                                color1: [0.0; 4],
3661                                grad_start: [0.0; 2],
3662                                grad_end: [0.0; 2],
3663                                sin_cos,
3664                            });
3665                        }
3666                        if text_decoration.strikethrough {
3667                            let sy = baseline_y - px * 0.3;
3668                            let (ndc, sin_cos) = rect_to_instance_ndc(
3669                                repose_core::Rect {
3670                                    x: rect.x,
3671                                    y: sy,
3672                                    w: rect.w,
3673                                    h: thickness,
3674                                },
3675                                current_transform,
3676                                current_target_size.0,
3677                                current_target_size.1,
3678                            );
3679                            batch.rects.push(RectInstance {
3680                                xywh: ndc,
3681                                radii: [0.0; 4],
3682                                brush_type: 0,
3683                                _pad: [0.0; 3],
3684                                color0: deco_color.to_linear(),
3685                                color1: [0.0; 4],
3686                                grad_start: [0.0; 2],
3687                                grad_end: [0.0; 2],
3688                                sin_cos,
3689                            });
3690                        }
3691                    }
3692                }
3693                SceneNode::Image {
3694                    rect,
3695                    handle,
3696                    tint,
3697                    fit,
3698                } => {
3699                    flush_batch!();
3700
3701                    // Update usage timestamp for eviction
3702                    let (img_w, img_h, is_nv12) = if let Some(t) = self.images.get_mut(handle) {
3703                        match t {
3704                            ImageTex::Rgba {
3705                                w,
3706                                h,
3707                                last_used_frame,
3708                                ..
3709                            } => {
3710                                *last_used_frame = self.frame_index;
3711                                (*w, *h, false)
3712                            }
3713                            ImageTex::Nv12 {
3714                                w,
3715                                h,
3716                                last_used_frame,
3717                                ..
3718                            } => {
3719                                *last_used_frame = self.frame_index;
3720                                (*w, *h, true)
3721                            }
3722                        }
3723                    } else {
3724                        log::warn!("Image handle {} not found", handle);
3725                        continue;
3726                    };
3727
3728                    let src_w = img_w as f32;
3729                    let src_h = img_h as f32;
3730                    let transformed = current_transform.apply_to_rect(*rect);
3731                    let dst_w = transformed.w.max(0.0);
3732                    let dst_h = transformed.h.max(0.0);
3733                    if dst_w <= 0.0 || dst_h <= 0.0 {
3734                        continue;
3735                    }
3736
3737                    let (xywh_ndc, uv_rect) = match fit {
3738                        repose_core::view::ImageFit::Contain => {
3739                            let scale = (dst_w / src_w).min(dst_h / src_h);
3740                            let w = src_w * scale;
3741                            let h = src_h * scale;
3742                            let x = transformed.x + (dst_w - w) * 0.5;
3743                            let y = transformed.y + (dst_h - h) * 0.5;
3744                            (
3745                                to_ndc(x, y, w, h, current_target_size.0, current_target_size.1),
3746                                [0.0, 1.0, 1.0, 0.0],
3747                            )
3748                        }
3749                        repose_core::view::ImageFit::Cover => {
3750                            let scale = (dst_w / src_w).max(dst_h / src_h);
3751                            let content_w = src_w * scale;
3752                            let content_h = src_h * scale;
3753                            let overflow_x = (content_w - dst_w) * 0.5;
3754                            let overflow_y = (content_h - dst_h) * 0.5;
3755                            let u0 = (overflow_x / content_w).clamp(0.0, 1.0);
3756                            let v0 = (overflow_y / content_h).clamp(0.0, 1.0);
3757                            let u1 = ((overflow_x + dst_w) / content_w).clamp(0.0, 1.0);
3758                            let v1 = ((overflow_y + dst_h) / content_h).clamp(0.0, 1.0);
3759                            (
3760                                to_ndc(
3761                                    transformed.x,
3762                                    transformed.y,
3763                                    dst_w,
3764                                    dst_h,
3765                                    current_target_size.0,
3766                                    current_target_size.1,
3767                                ),
3768                                [u0, 1.0 - v1, u1, 1.0 - v0],
3769                            )
3770                        }
3771                        repose_core::view::ImageFit::FitWidth => {
3772                            let scale = dst_w / src_w;
3773                            let w = dst_w;
3774                            let h = src_h * scale;
3775                            let y = transformed.y + (dst_h - h) * 0.5;
3776                            (
3777                                to_ndc(
3778                                    transformed.x,
3779                                    y,
3780                                    w,
3781                                    h,
3782                                    current_target_size.0,
3783                                    current_target_size.1,
3784                                ),
3785                                [0.0, 1.0, 1.0, 0.0],
3786                            )
3787                        }
3788                        repose_core::view::ImageFit::FitHeight => {
3789                            let scale = dst_h / src_h;
3790                            let w = src_w * scale;
3791                            let h = dst_h;
3792                            let x = transformed.x + (dst_w - w) * 0.5;
3793                            (
3794                                to_ndc(
3795                                    x,
3796                                    transformed.y,
3797                                    w,
3798                                    h,
3799                                    current_target_size.0,
3800                                    current_target_size.1,
3801                                ),
3802                                [0.0, 1.0, 1.0, 0.0],
3803                            )
3804                        }
3805                        _ => ([0.0; 4], [0.0; 4]),
3806                    };
3807
3808                    // Convert top-left based NDC to center-based for shader
3809                    let ndc_center = [
3810                        xywh_ndc[0] + xywh_ndc[2] * 0.5,
3811                        xywh_ndc[1] + xywh_ndc[3] * 0.5,
3812                        xywh_ndc[2],
3813                        xywh_ndc[3],
3814                    ];
3815
3816                    if is_nv12 {
3817                        let uv_x_offset = if let Some(ImageTex::Nv12 { w, color_info, .. }) =
3818                            self.images.get(handle)
3819                        {
3820                            match color_info.chroma_siting {
3821                                ChromaSiting::Center | ChromaSiting::TopLeft => 0.0,
3822                                ChromaSiting::Left => -1.0 / *w as f32,
3823                            }
3824                        } else {
3825                            0.0
3826                        };
3827
3828                        let inst = Nv12Instance {
3829                            xywh: ndc_center,
3830                            uv: uv_rect,
3831                            color: tint.to_linear(),
3832                            uv_x_offset,
3833                            sin_cos: [1.0, 0.0],
3834                            _pad: [0.0],
3835                        };
3836                        if let Some((off, _)) = self.nv12.upload(&self.device, &self.queue, &[inst])
3837                        {
3838                            current_pass.cmds.push(Cmd::ImageNv12 {
3839                                off,
3840                                cnt: 1,
3841                                handle: *handle,
3842                            });
3843                        }
3844                    } else {
3845                        // RGBA uses GlyphInstance struct (reused pipeline)
3846                        let inst = GlyphInstance {
3847                            xywh: ndc_center,
3848                            uv: uv_rect,
3849                            color: tint.to_linear(),
3850                            sin_cos: [1.0, 0.0],
3851                        };
3852                        if let Some((off, _)) =
3853                            self.glyph_color.upload(&self.device, &self.queue, &[inst])
3854                        {
3855                            current_pass.cmds.push(Cmd::ImageRgba {
3856                                off,
3857                                cnt: 1,
3858                                handle: *handle,
3859                            });
3860                        }
3861                    }
3862                }
3863                SceneNode::PushClip { rect, radius, op } => {
3864                    flush_batch!(); // flush content before entering clip
3865
3866                    let is_diff = matches!(op, repose_core::ClipOp::Difference);
3867
3868                    let t_identity = Transform::identity();
3869                    let current_transform = transform_stack.last().unwrap_or(&t_identity);
3870                    let transformed = current_transform.apply_to_rect(*rect);
3871
3872                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
3873                    let next_scissor = if is_diff {
3874                        top
3875                    } else {
3876                        intersect(top, transformed)
3877                    };
3878                    scissor_stack.push(next_scissor);
3879                    let scissor = to_scissor(
3880                        &next_scissor,
3881                        current_target_size.0 as u32,
3882                        current_target_size.1 as u32,
3883                    );
3884
3885                    let clip_ndc_tl = to_ndc(
3886                        transformed.x,
3887                        transformed.y,
3888                        transformed.w,
3889                        transformed.h,
3890                        current_target_size.0,
3891                        current_target_size.1,
3892                    );
3893                    let inst = ClipInstance {
3894                        xywh: [
3895                            clip_ndc_tl[0] + clip_ndc_tl[2] * 0.5,
3896                            clip_ndc_tl[1] + clip_ndc_tl[3] * 0.5,
3897                            clip_ndc_tl[2],
3898                            clip_ndc_tl[3],
3899                        ],
3900                        radii: *radius,
3901                        sin_cos: [1.0, 0.0],
3902                    };
3903                    let bytes = bytemuck::bytes_of(&inst);
3904                    self.clip_ring.grow_to_fit(&self.device, bytes.len() as u64);
3905                    let (off, _) = self.clip_ring.alloc_write(&self.queue, bytes);
3906
3907                    let rounded = radius.iter().any(|&r| r > 0.5);
3908
3909                    current_pass.cmds.push(Cmd::ClipPush {
3910                        off,
3911                        cnt: 1,
3912                        scissor,
3913                        difference: is_diff,
3914                        rounded,
3915                    });
3916                }
3917                SceneNode::PopClip => {
3918                    flush_batch!();
3919
3920                    if !scissor_stack.is_empty() {
3921                        scissor_stack.pop();
3922                    } else {
3923                        log::warn!("PopClip with empty stack");
3924                    }
3925
3926                    let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
3927                    let scissor = to_scissor(
3928                        &top,
3929                        current_target_size.0 as u32,
3930                        current_target_size.1 as u32,
3931                    );
3932                    current_pass.cmds.push(Cmd::ClipPop { scissor });
3933                }
3934                SceneNode::Shadow {
3935                    rect,
3936                    radius,
3937                    elevation: _,
3938                    color,
3939                } => {
3940                    flush_if_prim_changed!("rect", &self.rects);
3941                    let (ndc, sin_cos) = rect_to_instance_ndc(
3942                        *rect,
3943                        current_transform,
3944                        current_target_size.0,
3945                        current_target_size.1,
3946                    );
3947                    let (brush_type, color0, _color1, _grad_start, _grad_end) =
3948                        brush_to_instance_fields(&Brush::Solid(*color));
3949                    batch.rects.push(RectInstance {
3950                        xywh: ndc,
3951                        radii: *radius,
3952                        brush_type,
3953                        _pad: [0.0; 3],
3954                        color0,
3955                        color1: [0.0; 4],
3956                        grad_start: [0.0; 2],
3957                        grad_end: [0.0; 2],
3958                        sin_cos,
3959                    });
3960                }
3961                SceneNode::PushTransform { transform } => {
3962                    flush_batch!(); // flush before transform change
3963                    let combined = current_transform.combine(transform);
3964                    transform_stack.push(combined);
3965                }
3966                SceneNode::PopTransform => {
3967                    flush_batch!(); // flush before transform change
3968                    transform_stack.pop();
3969                }
3970                SceneNode::BeginLayer {
3971                    rect,
3972                    layer_id,
3973                    alpha,
3974                    blur_radius_x,
3975                    blur_radius_y,
3976                    rectangle_edge: _,
3977                } => {
3978                    flush_batch!();
3979                    let w = (rect.w.max(1.0)).ceil() as u32;
3980                    let h = (rect.h.max(1.0)).ceil() as u32;
3981                    // Close out the current pass, start a new one for the layer.
3982                    let prev_target = current_pass.target;
3983                    let prev_scissor = current_pass.initial_scissor;
3984                    let saved = std::mem::replace(
3985                        &mut current_pass,
3986                        Pass {
3987                            target: PassTarget::Layer(*layer_id),
3988                            initial_scissor: (0, 0, w, h),
3989                            clear_color: Some([0.0, 0.0, 0.0, 0.0]),
3990                            cmds: Vec::new(),
3991                        },
3992                    );
3993                    passes.push(saved);
3994                    target_stack.push(prev_target);
3995                    let _ = prev_scissor; // initial_scissor of resumed pass is restored at EndLayer
3996                    // Get or create the layer's offscreen texture now so that
3997                    // subsequent scissor ops / draws have a valid target.
3998                    self.get_or_create_layer(*layer_id, w, h, *rect);
3999                    current_target_size = (w as f32, h as f32);
4000                    layer_alphas.push((*layer_id, *alpha, current_pass.initial_scissor));
4001                    // Store blur info for post-processing after EndLayer
4002                    if *blur_radius_x > 0.0 || *blur_radius_y > 0.0 {
4003                        layer_blurs.push((*layer_id, *blur_radius_x, *blur_radius_y));
4004                    }
4005                }
4006                SceneNode::EndLayer { layer_id } => {
4007                    flush_batch!();
4008                    // Finish the layer's pass, start a new one on the previous target.
4009                    let saved = std::mem::replace(
4010                        &mut current_pass,
4011                        Pass {
4012                            target: target_stack.pop().unwrap_or(PassTarget::Surface),
4013                            initial_scissor: (0, 0, self.output_width, self.output_height),
4014                            clear_color: None, // LoadOp::Load - don't wipe earlier surface content
4015                            cmds: Vec::new(),
4016                        },
4017                    );
4018                    passes.push(saved);
4019                    current_target_size = (fb_w, fb_h);
4020                    // Issue a composite quad for the just-finished layer in the new pass.
4021                    if let Some((_, layer_alpha, _)) = layer_alphas
4022                        .iter()
4023                        .find(|(id, _, _)| id == layer_id)
4024                        .copied()
4025                    {
4026                        let layer = self.layer_pool.get(layer_id).expect("layer target");
4027                        let ndc_tl = to_ndc(
4028                            layer.rect_px.0,
4029                            layer.rect_px.1,
4030                            layer.rect_px.2,
4031                            layer.rect_px.3,
4032                            fb_w,
4033                            fb_h,
4034                        );
4035                        // Check if this layer needs content blur
4036                        let blur_px_val = layer_blurs
4037                            .iter()
4038                            .find(|(id, _, _)| id == layer_id)
4039                            .map(|(_, bx, by)| (*bx, *by));
4040                        if let Some((blur_x, blur_y)) =
4041                            blur_px_val.filter(|(bx, by)| *bx > 0.0 || *by > 0.0)
4042                        {
4043                            // Content blur: draw blurred version using the blur_content pipeline
4044                            let bw_uv = (blur_x * 1.5) / layer.width.max(1) as f32;
4045                            let bh_uv = (blur_y * 1.5) / layer.height.max(1) as f32;
4046                            let inst = BlurInstance {
4047                                xywh: [
4048                                    ndc_tl[0] + ndc_tl[2] * 0.5,
4049                                    ndc_tl[1] + ndc_tl[3] * 0.5,
4050                                    ndc_tl[2],
4051                                    ndc_tl[3],
4052                                ],
4053                                uv: [0.0, 0.0, 1.0, 1.0],
4054                                color: [1.0, 1.0, 1.0, layer_alpha],
4055                                blur_uv: [bw_uv, bh_uv],
4056                                sin_cos: [1.0, 0.0],
4057                            };
4058                            self.blur_ring.grow_to_fit(
4059                                &self.device,
4060                                std::mem::size_of::<BlurInstance>() as u64,
4061                            );
4062                            let bytes = bytemuck::bytes_of(&inst);
4063                            let (off, _) = self.blur_ring.alloc_write(&self.queue, bytes);
4064                            current_pass.cmds.push(Cmd::CompositeBlur {
4065                                off,
4066                                cnt: 1,
4067                                layer_id: *layer_id,
4068                            });
4069                        } else {
4070                            // Normal sharp composite
4071                            let inst = GlyphInstance {
4072                                xywh: [
4073                                    ndc_tl[0] + ndc_tl[2] * 0.5,
4074                                    ndc_tl[1] + ndc_tl[3] * 0.5,
4075                                    ndc_tl[2],
4076                                    ndc_tl[3],
4077                                ],
4078                                uv: [0.0, 1.0, 1.0, 0.0],
4079                                color: [1.0, 1.0, 1.0, layer_alpha],
4080                                sin_cos: [1.0, 0.0],
4081                            };
4082                            if let Some((off, cnt)) =
4083                                self.glyph_color.upload(&self.device, &self.queue, &[inst])
4084                            {
4085                                current_pass.cmds.push(Cmd::CompositeLayer {
4086                                    off,
4087                                    cnt,
4088                                    layer_id: *layer_id,
4089                                    alpha: layer_alpha,
4090                                });
4091                            }
4092                        }
4093                    }
4094                }
4095                SceneNode::CompositeShadow {
4096                    layer_id,
4097                    blur_px,
4098                    offset_px,
4099                    color,
4100                } => {
4101                    flush_batch!();
4102                    if let Some(layer) = self.layer_pool.get(layer_id).cloned() {
4103                        // Shadow rect = layer rect + offset.
4104                        let sx = layer.rect_px.0 + offset_px.0;
4105                        let sy = layer.rect_px.1 + offset_px.1;
4106                        let sw = layer.rect_px.2;
4107                        let sh = layer.rect_px.3;
4108                        // The blur in UV space is 1.5 * blur_px / texture_size
4109                        // (the 1.5 matches the 3x3 Gaussian span).
4110                        let bw_uv = (blur_px * 1.5) / layer.width.max(1) as f32;
4111                        let bh_uv = (blur_px * 1.5) / layer.height.max(1) as f32;
4112                        let ndc_tl = to_ndc(sx, sy, sw, sh, fb_w, fb_h);
4113                        let inst = BlurInstance {
4114                            xywh: [
4115                                ndc_tl[0] + ndc_tl[2] * 0.5,
4116                                ndc_tl[1] + ndc_tl[3] * 0.5,
4117                                ndc_tl[2],
4118                                ndc_tl[3],
4119                            ],
4120                            uv: [0.0, 0.0, 1.0, 1.0],
4121                            color: [
4122                                color.0 as f32 / 255.0,
4123                                color.1 as f32 / 255.0,
4124                                color.2 as f32 / 255.0,
4125                                color.3 as f32 / 255.0,
4126                            ],
4127                            blur_uv: [bw_uv, bh_uv],
4128                            sin_cos: [1.0, 0.0],
4129                        };
4130                        self.blur_ring
4131                            .grow_to_fit(&self.device, std::mem::size_of::<BlurInstance>() as u64);
4132                        let bytes = bytemuck::bytes_of(&inst);
4133                        let (off, _) = self.blur_ring.alloc_write(&self.queue, bytes);
4134                        current_pass.cmds.push(Cmd::CompositeShadow {
4135                            off,
4136                            cnt: 1,
4137                            layer_id: *layer_id,
4138                        });
4139                    }
4140                }
4141                _ => {}
4142            }
4143        }
4144
4145        flush_batch!();
4146
4147        // Push the final pass.
4148        passes.push(current_pass);
4149
4150        let bind_mask = self.atlas_bind_group_mask();
4151        let bind_color = self.atlas_bind_group_color();
4152        let mut clip_depth: u32 = 0;
4153
4154        for pass in std::mem::take(&mut passes) {
4155            let (color_view, resolve_target, depth_stencil_view, is_layer) = match pass.target {
4156                PassTarget::Surface => {
4157                    let swap_view = target_view.clone();
4158                    let use_ws = self.working_space && self.ws_view.is_some();
4159                    let (color, resolve) = if use_ws {
4160                        let ws_view = self.ws_view.as_ref().unwrap();
4161                        if let Some(msaa_view) = &self.msaa_view {
4162                            // MSAA resolves to working-space texture
4163                            (msaa_view.clone(), Some(ws_view.clone()))
4164                        } else {
4165                            // Direct render to working-space texture
4166                            (ws_view.clone(), None)
4167                        }
4168                    } else if let Some(msaa_view) = &self.msaa_view {
4169                        (msaa_view.clone(), Some(swap_view))
4170                    } else {
4171                        (swap_view, None)
4172                    };
4173                    (color, resolve, self.depth_stencil_view.clone(), false)
4174                }
4175                PassTarget::Layer(layer_id) => {
4176                    if let Some(lt) = self.layer_pool.get(&layer_id) {
4177                        (lt.view.clone(), None, lt.depth_stencil_view.clone(), true)
4178                    } else {
4179                        log::warn!("missing layer target {layer_id}");
4180                        continue;
4181                    }
4182                }
4183            };
4184
4185            if is_layer {
4186                clip_depth = 0;
4187            }
4188
4189            let pipes: &Pipelines = if is_layer {
4190                &self.layer_pipes
4191            } else {
4192                &self.surface_pipes
4193            };
4194
4195            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4196                label: Some("pass"),
4197                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
4198                    view: &color_view,
4199                    resolve_target: resolve_target.as_ref(),
4200                    ops: wgpu::Operations {
4201                        load: match pass.clear_color {
4202                            Some(c) => wgpu::LoadOp::Clear(wgpu::Color {
4203                                r: c[0] as f64,
4204                                g: c[1] as f64,
4205                                b: c[2] as f64,
4206                                a: c[3] as f64,
4207                            }),
4208                            None => wgpu::LoadOp::Load,
4209                        },
4210                        store: wgpu::StoreOp::Store,
4211                    },
4212                    depth_slice: None,
4213                })],
4214                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
4215                    view: &depth_stencil_view,
4216                    depth_ops: None,
4217                    stencil_ops: Some(wgpu::Operations {
4218                        load: if is_layer || pass.clear_color.is_some() {
4219                            wgpu::LoadOp::Clear(0)
4220                        } else {
4221                            wgpu::LoadOp::Load
4222                        },
4223                        store: wgpu::StoreOp::Store,
4224                    }),
4225                }),
4226                timestamp_writes: None,
4227                occlusion_query_set: None,
4228                multiview_mask: None,
4229            });
4230
4231            rpass.set_bind_group(0, &self.globals_bind, &[]);
4232            rpass.set_stencil_reference(clip_depth);
4233            rpass.set_scissor_rect(
4234                pass.initial_scissor.0,
4235                pass.initial_scissor.1,
4236                pass.initial_scissor.2,
4237                pass.initial_scissor.3,
4238            );
4239
4240            macro_rules! draw_simple {
4241                ($pipeline:expr, $ring:expr, $inst:ty, $off:ident, $n:ident) => {{
4242                    rpass.set_pipeline($pipeline);
4243                    let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
4244                    rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
4245                    rpass.draw(0..6, 0..$n);
4246                }};
4247            }
4248
4249            macro_rules! draw_with_bind {
4250                ($pipeline:expr, $ring:expr, $inst:ty, $bind:expr, $off:ident, $n:ident) => {{
4251                    rpass.set_pipeline($pipeline);
4252                    rpass.set_bind_group(1, $bind, &[]);
4253                    let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
4254                    rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
4255                    rpass.draw(0..6, 0..$n);
4256                }};
4257            }
4258
4259            for cmd in pass.cmds {
4260                match cmd {
4261                    Cmd::ClipPush {
4262                        off,
4263                        cnt: n,
4264                        scissor,
4265                        difference,
4266                        rounded,
4267                    } => {
4268                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
4269                        rpass.set_stencil_reference(clip_depth);
4270
4271                        if difference {
4272                            rpass.set_pipeline(&pipes.clip_dec);
4273                        } else if self.msaa_samples > 1 && !is_layer && rounded {
4274                            rpass.set_pipeline(&pipes.clip_a2c);
4275                        } else {
4276                            rpass.set_pipeline(&pipes.clip_bin);
4277                        }
4278
4279                        let bytes = (n as u64) * std::mem::size_of::<ClipInstance>() as u64;
4280                        rpass.set_vertex_buffer(0, self.clip_ring.buf.slice(off..off + bytes));
4281                        rpass.draw(0..6, 0..n);
4282
4283                        if !difference {
4284                            clip_depth = (clip_depth + 1).min(255);
4285                            rpass.set_stencil_reference(clip_depth);
4286                        }
4287                    }
4288
4289                    Cmd::ClipPop { scissor } => {
4290                        clip_depth = clip_depth.saturating_sub(1);
4291                        rpass.set_stencil_reference(clip_depth);
4292                        rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
4293                    }
4294
4295                    Cmd::Rect { off, cnt: n } => {
4296                        draw_simple!(&pipes.rects, self.rects.ring, RectInstance, off, n);
4297                    }
4298
4299                    Cmd::Border { off, cnt: n } => {
4300                        draw_simple!(&pipes.borders, self.borders.ring, BorderInstance, off, n);
4301                    }
4302
4303                    Cmd::GlyphsMask { off, cnt: n } => {
4304                        draw_with_bind!(
4305                            &pipes.text_mask,
4306                            self.glyph_mask.ring,
4307                            GlyphInstance,
4308                            &bind_mask,
4309                            off,
4310                            n
4311                        );
4312                    }
4313
4314                    Cmd::GlyphsColor { off, cnt: n } => {
4315                        draw_with_bind!(
4316                            &pipes.text_color,
4317                            self.glyph_color.ring,
4318                            GlyphInstance,
4319                            &bind_color,
4320                            off,
4321                            n
4322                        );
4323                    }
4324
4325                    Cmd::GlyphsVector { off, cnt: n } => {
4326                        if let Some(ref slug_pipe) = pipes.slug.as_ref() {
4327                            rpass.set_pipeline(slug_pipe);
4328                            let bytes = (n as u64) * std::mem::size_of::<slug::TessVertex>() as u64;
4329                            rpass.set_vertex_buffer(0, self.slug_ring.buf.slice(off..off + bytes));
4330                            rpass.draw(0..n, 0..1);
4331                        }
4332                    }
4333
4334                    Cmd::ImageRgba {
4335                        off,
4336                        cnt: n,
4337                        handle,
4338                    } => {
4339                        if let Some(ImageTex::Rgba { bind, .. }) = self.images.get(&handle) {
4340                            draw_with_bind!(
4341                                &pipes.image_rgba,
4342                                self.glyph_color.ring,
4343                                GlyphInstance,
4344                                bind,
4345                                off,
4346                                n
4347                            );
4348                        }
4349                    }
4350
4351                    Cmd::ImageNv12 {
4352                        off,
4353                        cnt: n,
4354                        handle,
4355                    } => {
4356                        if let Some(ImageTex::Nv12 { bind, .. }) = self.images.get(&handle) {
4357                            draw_with_bind!(
4358                                &pipes.image_nv12,
4359                                self.nv12.ring,
4360                                Nv12Instance,
4361                                bind,
4362                                off,
4363                                n
4364                            );
4365                        }
4366                    }
4367
4368                    Cmd::Ellipse { off, cnt: n } => {
4369                        draw_simple!(&pipes.ellipses, self.ellipses.ring, EllipseInstance, off, n);
4370                    }
4371
4372                    Cmd::EllipseBorder { off, cnt: n } => {
4373                        draw_simple!(
4374                            &pipes.ellipse_borders,
4375                            self.ellipse_borders.ring,
4376                            EllipseBorderInstance,
4377                            off,
4378                            n
4379                        );
4380                    }
4381
4382                    Cmd::Arc { off, cnt: n } => {
4383                        draw_simple!(&pipes.arcs, self.arcs.ring, ArcInstance, off, n);
4384                    }
4385
4386                    Cmd::PushTransform(_) => {}
4387                    Cmd::PopTransform => {}
4388                    Cmd::CompositeLayer {
4389                        off,
4390                        cnt: n,
4391                        layer_id,
4392                        alpha: _,
4393                    } => {
4394                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
4395                            draw_with_bind!(
4396                                &pipes.image_rgba,
4397                                self.glyph_color.ring,
4398                                GlyphInstance,
4399                                &lt.bind,
4400                                off,
4401                                n
4402                            );
4403                        }
4404                    }
4405                    Cmd::CompositeShadow {
4406                        off,
4407                        cnt: n,
4408                        layer_id,
4409                    } => {
4410                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
4411                            draw_with_bind!(
4412                                &pipes.blur,
4413                                self.blur_ring,
4414                                BlurInstance,
4415                                &lt.bind,
4416                                off,
4417                                n
4418                            );
4419                        }
4420                    }
4421                    Cmd::CompositeBlur {
4422                        off,
4423                        cnt: n,
4424                        layer_id,
4425                    } => {
4426                        if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
4427                            draw_with_bind!(
4428                                &pipes.blur_content,
4429                                self.blur_ring,
4430                                BlurInstance,
4431                                &lt.bind,
4432                                off,
4433                                n
4434                            );
4435                        }
4436                    }
4437                }
4438            }
4439        }
4440
4441        // Display pass: linear working space → sRGB OETF → swapchain
4442        if self.working_space {
4443            if let (Some(_ws_view), Some(ws_bind), Some(display_pipeline)) =
4444                (&self.ws_view, &self.ws_bind, &self.display_pipeline)
4445            {
4446                let swap_view = target_view.clone();
4447                let mut display_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4448                    label: Some("display transform"),
4449                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
4450                        view: &swap_view,
4451                        resolve_target: None,
4452                        ops: wgpu::Operations {
4453                            load: wgpu::LoadOp::Load,
4454                            store: wgpu::StoreOp::Store,
4455                        },
4456                        depth_slice: None,
4457                    })],
4458                    depth_stencil_attachment: None,
4459                    timestamp_writes: None,
4460                    occlusion_query_set: None,
4461                    multiview_mask: None,
4462                });
4463                display_pass.set_pipeline(display_pipeline);
4464                display_pass.set_bind_group(1, ws_bind, &[]);
4465                display_pass.draw(0..3, 0..1);
4466            }
4467        }
4468
4469
4470        // Frame end maintenance: Evict unused images
4471        self.evict_unused_images();
4472    }
4473
4474    /// Render a scene into an externally-provided texture view.
4475    /// Use this when embedding Repose in a host that owns the GPU.
4476    /// The host is responsible for submitting the encoder and handling present.
4477    pub fn render_to_view(
4478        &mut self,
4479        scene: &Scene,
4480        encoder: &mut wgpu::CommandEncoder,
4481        target_view: &wgpu::TextureView,
4482        width: u32,
4483        height: u32,
4484        clear_color: Option<[f64; 4]>,
4485    ) {
4486        self.resize(width, height);
4487
4488        self.frame_index = self.frame_index.wrapping_add(1);
4489        self.slug_cache.next_frame();
4490
4491        if width == 0 || height == 0 {
4492            return;
4493        }
4494
4495        self.render_scene_to_encoder(scene, encoder, target_view, clear_color);
4496    }
4497}
4498
4499
4500fn intersect(a: repose_core::Rect, b: repose_core::Rect) -> repose_core::Rect {
4501    let x0 = a.x.max(b.x);
4502    let y0 = a.y.max(b.y);
4503    let x1 = (a.x + a.w).min(b.x + b.w);
4504    let y1 = (a.y + a.h).min(b.y + b.h);
4505    repose_core::Rect {
4506        x: x0,
4507        y: y0,
4508        w: (x1 - x0).max(0.0),
4509        h: (y1 - y0).max(0.0),
4510    }
4511}