Skip to main content

strata_render/
gpu_pipeline.rs

1//! GPU Quad and Rounded Rectangle Presentation Pipeline.
2//!
3//! Provides instanced GPU memory representations (`GpuQuadInstance`, `GpuUniforms`, `GpuBatch`)
4//! and analytical Signed Distance Field (SDF) WGSL shaders for zero-CPU hardware rendering.
5
6use crate::compositor::{DisplayList, DrawCommand};
7use strata_layout::Rect;
8use strata_primitives::geom::EdgeInsets;
9use strata_style::types::{BorderRadius, Color};
10
11/// Embedded WGSL shader for instanced quad rendering with analytical SDF anti-aliased corners and borders.
12pub const WGSL_ANALYTICAL_QUAD_SHADER: &str = r#"
13struct VertexInput {
14    @location(0) position: vec2<f32>,
15};
16
17struct InstanceInput {
18    @location(1) bounds: vec4<f32>,
19    @location(2) color: vec4<f32>,
20    @location(3) border_radius: vec4<f32>,
21    @location(4) border_width: vec4<f32>,
22    @location(5) border_color: vec4<f32>,
23    @location(6) clip_rect: vec4<f32>,
24};
25
26struct VertexOutput {
27    @builtin(position) clip_position: vec4<f32>,
28    @location(0) pixel_pos: vec2<f32>,
29    @location(1) bounds: vec4<f32>,
30    @location(2) color: vec4<f32>,
31    @location(3) border_radius: vec4<f32>,
32    @location(4) border_width: vec4<f32>,
33    @location(5) border_color: vec4<f32>,
34    @location(6) clip_rect: vec4<f32>,
35};
36
37struct Uniforms {
38    viewport_size: vec2<f32>,
39    _padding: vec2<f32>,
40};
41
42@group(0) @binding(0) var<uniform> uniforms: Uniforms;
43
44@vertex
45fn vs_main(model: VertexInput, instance: InstanceInput) -> VertexOutput {
46    var out: VertexOutput;
47    let pixel_coords = instance.bounds.xy + model.position * instance.bounds.zw;
48    
49    let ndc_x = (pixel_coords.x / uniforms.viewport_size.x) * 2.0 - 1.0;
50    let ndc_y = 1.0 - (pixel_coords.y / uniforms.viewport_size.y) * 2.0;
51    
52    out.clip_position = vec4<f32>(ndc_x, ndc_y, 0.0, 1.0);
53    out.pixel_pos = pixel_coords;
54    out.bounds = instance.bounds;
55    out.color = instance.color;
56    out.border_radius = instance.border_radius;
57    out.border_width = instance.border_width;
58    out.border_color = instance.border_color;
59    out.clip_rect = instance.clip_rect;
60    return out;
61}
62
63fn sd_rounded_rect(p: vec2<f32>, b: vec2<f32>, r: f32) -> f32 {
64    let q = abs(p) - b + vec2<f32>(r, r);
65    return length(max(q, vec2<f32>(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - r;
66}
67
68@fragment
69fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
70    // Scissor clipping test
71    if (in.pixel_pos.x < in.clip_rect.x || in.pixel_pos.x > in.clip_rect.x + in.clip_rect.z ||
72        in.pixel_pos.y < in.clip_rect.y || in.pixel_pos.y > in.clip_rect.y + in.clip_rect.w) {
73        discard;
74    }
75
76    let center = in.bounds.xy + in.bounds.zw * 0.5;
77    let half_extents = in.bounds.zw * 0.5;
78    let p = in.pixel_pos - center;
79
80    // Corner radius selection per quadrant: [top_left, top_right, bottom_right, bottom_left]
81    var r: f32 = in.border_radius.x;
82    if (p.x >= 0.0 && p.y < 0.0) {
83        r = in.border_radius.y;
84    } else if (p.x >= 0.0 && p.y >= 0.0) {
85        r = in.border_radius.z;
86    } else if (p.x < 0.0 && p.y >= 0.0) {
87        r = in.border_radius.w;
88    }
89    r = min(r, min(half_extents.x, half_extents.y));
90
91    let dist = sd_rounded_rect(p, half_extents, r);
92    let coverage = clamp(0.5 - dist, 0.0, 1.0);
93
94    if (coverage <= 0.0) {
95        discard;
96    }
97
98    let bw = in.border_width.x;
99    if (bw > 0.0 && in.border_color.a > 0.0) {
100        let inner_dist = dist + bw;
101        let inner_cov = clamp(0.5 - inner_dist, 0.0, 1.0);
102        
103        let border_alpha = in.border_color.a * coverage * (1.0 - inner_cov);
104        let fill_alpha = in.color.a * inner_cov;
105        
106        let out_rgb = in.border_color.rgb * border_alpha + in.color.rgb * fill_alpha;
107        let out_a = border_alpha + fill_alpha;
108        return vec4<f32>(out_rgb, out_a);
109    }
110
111    let out_a = in.color.a * coverage;
112    return vec4<f32>(in.color.rgb * out_a, out_a);
113}
114"#;
115
116/// 2D Vertex coordinates for rendering unit instanced quads.
117#[repr(C)]
118#[derive(Debug, Clone, Copy, PartialEq)]
119pub struct GpuVertex {
120    pub position: [f32; 2],
121}
122
123impl GpuVertex {
124    pub const fn new(x: f32, y: f32) -> Self {
125        Self { position: [x, y] }
126    }
127}
128
129/// Six vertices composing two triangles for a unit rectangle [0, 0] to [1, 1].
130pub const QUAD_VERTICES: [GpuVertex; 6] = [
131    GpuVertex::new(0.0, 0.0),
132    GpuVertex::new(1.0, 0.0),
133    GpuVertex::new(0.0, 1.0),
134    GpuVertex::new(0.0, 1.0),
135    GpuVertex::new(1.0, 0.0),
136    GpuVertex::new(1.0, 1.0),
137];
138
139/// Six vertices composing two triangles for a signed unit quad `[-1, -1]` to `[1, 1]`,
140/// matching [`strata_gpu_path::WGSL_ANALYTICAL_PATH_RASTER_SHADER`].
141pub const SIGNED_QUAD_VERTICES: [GpuVertex; 6] = [
142    GpuVertex::new(-1.0, -1.0),
143    GpuVertex::new(1.0, -1.0),
144    GpuVertex::new(-1.0, 1.0),
145    GpuVertex::new(-1.0, 1.0),
146    GpuVertex::new(1.0, -1.0),
147    GpuVertex::new(1.0, 1.0),
148];
149
150/// Exact 96-byte GPU memory instance representation for an instanced quad or rounded rectangle.
151#[repr(C)]
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub struct GpuQuadInstance {
154    pub bounds: [f32; 4],        // [x, y, width, height]
155    pub color: [f32; 4],         // [r, g, b, a]
156    pub border_radius: [f32; 4], // [top_left, top_right, bottom_right, bottom_left]
157    pub border_width: [f32; 4],  // [top, right, bottom, left]
158    pub border_color: [f32; 4],  // [r, g, b, a]
159    pub clip_rect: [f32; 4],     // [clip_x, clip_y, clip_w, clip_h]
160}
161
162impl GpuQuadInstance {
163    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
164
165    /// Constructs a simple solid colored quad instance.
166    pub fn from_rect(bounds: Rect, color: Color, clip: Rect) -> Self {
167        let (r, g, b, a) = color.to_f32();
168        Self {
169            bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
170            color: [r, g, b, a],
171            border_radius: [0.0; 4],
172            border_width: [0.0; 4],
173            border_color: [0.0; 4],
174            clip_rect: [clip.x, clip.y, clip.width, clip.height],
175        }
176    }
177
178    /// Constructs a rounded rectangle with border widths and border colors.
179    pub fn from_rounded_rect(
180        bounds: Rect,
181        color: Color,
182        radius: BorderRadius,
183        widths: EdgeInsets<f32>,
184        border_color: Option<Color>,
185        clip: Rect,
186    ) -> Self {
187        let (r, g, b, a) = color.to_f32();
188        let (br, bg, bb, ba) = border_color
189            .map(|c| c.to_f32())
190            .unwrap_or((0.0, 0.0, 0.0, 0.0));
191
192        Self {
193            bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
194            color: [r, g, b, a],
195            border_radius: [
196                radius.top_left,
197                radius.top_right,
198                radius.bottom_right,
199                radius.bottom_left,
200            ],
201            border_width: [widths.top, widths.right, widths.bottom, widths.left],
202            border_color: [br, bg, bb, ba],
203            clip_rect: [clip.x, clip.y, clip.width, clip.height],
204        }
205    }
206
207    /// Safe zero-copy byte slice view of this quad instance.
208    #[inline]
209    pub fn as_bytes(&self) -> &[u8] {
210        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
211    }
212
213    /// Safe zero-copy byte slice view of a contiguous slice of quad instances.
214    #[inline]
215    pub fn slice_to_bytes(slice: &[Self]) -> &[u8] {
216        unsafe {
217            std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * Self::BYTE_SIZE)
218        }
219    }
220}
221
222/// 16-byte aligned Uniform Buffer object for viewport projection.
223#[repr(C)]
224#[derive(Debug, Clone, Copy, PartialEq)]
225pub struct GpuUniforms {
226    pub viewport_size: [f32; 2],
227    pub _padding: [f32; 2],
228}
229
230impl GpuUniforms {
231    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
232
233    pub fn new(width: f32, height: f32) -> Self {
234        Self {
235            viewport_size: [width, height],
236            _padding: [0.0, 0.0],
237        }
238    }
239
240    #[inline]
241    pub fn as_bytes(&self) -> &[u8] {
242        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
243    }
244}
245
246/// Embedded WGSL shader for non-rectangular polygonal clip stencil masks.
247pub const WGSL_STENCIL_CLIP_SHADER: &str = r#"
248struct VertexInput {
249    @location(0) position: vec2<f32>,
250};
251
252struct Uniforms {
253    viewport_size: vec2<f32>,
254    _padding: vec2<f32>,
255};
256
257@group(0) @binding(0) var<uniform> uniforms: Uniforms;
258
259@vertex
260fn vs_main(model: VertexInput) -> @builtin(position) vec4<f32> {
261    let ndc_x = (model.position.x / uniforms.viewport_size.x) * 2.0 - 1.0;
262    let ndc_y = 1.0 - (model.position.y / uniforms.viewport_size.y) * 2.0;
263    return vec4<f32>(ndc_x, ndc_y, 0.0, 1.0);
264}
265
266@fragment
267fn fs_main() -> @location(0) vec4<f32> {
268    // Stencil clip passes disable color writes and update the stencil attachment directly.
269    return vec4<f32>(0.0, 0.0, 0.0, 0.0);
270}
271"#;
272
273/// 2D vertex coordinate for triangulated GPU stencil clip mask geometry.
274#[repr(C)]
275#[derive(Debug, Clone, Copy, PartialEq)]
276pub struct GpuClipVertex {
277    pub position: [f32; 2],
278}
279
280impl GpuClipVertex {
281    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
282
283    #[inline]
284    pub const fn new(x: f32, y: f32) -> Self {
285        Self { position: [x, y] }
286    }
287
288    #[inline]
289    pub fn slice_to_bytes(slice: &[Self]) -> &[u8] {
290        unsafe {
291            std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * Self::BYTE_SIZE)
292        }
293    }
294}
295
296/// Spatial containment relation of a primitive or quad against an active polygonal clip stack.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298pub enum ClipContainment {
299    /// Primitive lies completely outside at least one clip layer (cullable).
300    Outside,
301    /// Primitive crosses a non-rectangular clip boundary (requires stencil masking).
302    Partial,
303    /// Primitive lies strictly inside every active clip layer (no stencil needed).
304    Inside,
305}
306
307/// Compiled polygonal/stencil clip mask for circular, rounded, or arbitrary CAD clip paths.
308#[derive(Debug, Clone, PartialEq)]
309pub struct GpuClipMask {
310    /// Conservative axis-aligned bounding box of the intersected clip region.
311    pub bounds: Rect,
312    /// Active non-rectangular clip layers; each layer contains closed/open subpaths evaluated even-odd.
313    pub layers: Vec<Vec<Vec<(f32, f32)>>>,
314    /// Triangulated vertex triplets per clip layer (3 vertices per triangle) for GPU stencil passes.
315    pub stencil_layers: Vec<Vec<GpuClipVertex>>,
316}
317
318impl GpuClipMask {
319    /// Constructs and triangulates a stencil clip mask from a stack of subpath layers.
320    pub fn from_layers(bounds: Rect, layers: Vec<Vec<Vec<(f32, f32)>>>) -> Self {
321        let stencil_layers = layers
322            .iter()
323            .map(|subpaths| {
324                let mut verts = Vec::new();
325                for sub in subpaths {
326                    verts.extend(triangulate_subpath_pts(sub));
327                }
328                verts
329            })
330            .collect();
331        Self {
332            bounds,
333            layers,
334            stencil_layers,
335        }
336    }
337
338    /// Returns `true` if `(x, y)` passes the intersected AABB and all even-odd polygon layers.
339    #[inline]
340    pub fn contains_point(&self, x: f32, y: f32) -> bool {
341        if x < self.bounds.x
342            || x >= self.bounds.max_x()
343            || y < self.bounds.y
344            || y >= self.bounds.max_y()
345        {
346            return false;
347        }
348        self.layers
349            .iter()
350            .all(|poly| crate::canvas2d::point_in_subpaths_even_odd(poly, x, y))
351    }
352
353    /// Evaluates containment of `rect` against all clip layers in this mask.
354    #[inline]
355    pub fn rect_containment(&self, rect: Rect) -> ClipContainment {
356        if self.bounds.intersect(rect).is_none() {
357            return ClipContainment::Outside;
358        }
359        rect_relation_to_clip_polys(rect, &self.layers)
360    }
361
362    /// Total number of stencil triangle vertices across all active clip layers.
363    #[inline]
364    pub fn total_stencil_vertices(&self) -> usize {
365        self.stencil_layers.iter().map(|v| v.len()).sum()
366    }
367}
368
369/// Maps a contiguous slice `[start..end)` of batched GPU primitives to an optional [`GpuClipMask`].
370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub struct GpuClipSpan {
372    pub start: usize,
373    pub end: usize,
374    pub clip_mask: Option<usize>,
375}
376
377#[inline]
378fn orient2d(a: (f32, f32), b: (f32, f32), c: (f32, f32)) -> f32 {
379    (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0)
380}
381
382#[inline]
383fn on_segment_bbox(a: (f32, f32), b: (f32, f32), p: (f32, f32)) -> bool {
384    p.0 >= a.0.min(b.0) - 1e-4
385        && p.0 <= a.0.max(b.0) + 1e-4
386        && p.1 >= a.1.min(b.1) - 1e-4
387        && p.1 <= a.1.max(b.1) + 1e-4
388}
389
390fn segments_intersect_2d(
391    a0: (f32, f32),
392    a1: (f32, f32),
393    b0: (f32, f32),
394    b1: (f32, f32),
395) -> bool {
396    let o1 = orient2d(a0, a1, b0);
397    let o2 = orient2d(a0, a1, b1);
398    let o3 = orient2d(b0, b1, a0);
399    let o4 = orient2d(b0, b1, a1);
400    if ((o1 > 1e-4 && o2 < -1e-4) || (o1 < -1e-4 && o2 > 1e-4))
401        && ((o3 > 1e-4 && o4 < -1e-4) || (o3 < -1e-4 && o4 > 1e-4))
402    {
403        return true;
404    }
405    (o1.abs() <= 1e-4 && on_segment_bbox(a0, a1, b0))
406        || (o2.abs() <= 1e-4 && on_segment_bbox(a0, a1, b1))
407        || (o3.abs() <= 1e-4 && on_segment_bbox(b0, b1, a0))
408        || (o4.abs() <= 1e-4 && on_segment_bbox(b0, b1, a1))
409}
410
411fn subpaths_are_axis_aligned_rect(subpaths: &[Vec<(f32, f32)>]) -> bool {
412    if subpaths.len() != 1 {
413        return false;
414    }
415    let raw = &subpaths[0];
416    let mut pts: Vec<(f32, f32)> = Vec::with_capacity(raw.len());
417    for &p in raw {
418        if pts
419            .last()
420            .is_none_or(|&prev| (p.0 - prev.0).hypot(p.1 - prev.1) > 1e-3)
421        {
422            pts.push(p);
423        }
424    }
425    if pts.len() >= 2 {
426        let first = pts[0];
427        let last = *pts.last().unwrap();
428        if (first.0 - last.0).hypot(first.1 - last.1) <= 1e-3 {
429            pts.pop();
430        }
431    }
432    if pts.len() != 4 {
433        return false;
434    }
435    let mut prev_horiz: Option<bool> = None;
436    for i in 0..4 {
437        let a = pts[i];
438        let b = pts[(i + 1) % 4];
439        let dx = (b.0 - a.0).abs();
440        let dy = (b.1 - a.1).abs();
441        let is_horiz = if dy <= 1e-3 && dx > 1e-3 {
442            true
443        } else if dx <= 1e-3 && dy > 1e-3 {
444            false
445        } else {
446            return false;
447        };
448        if prev_horiz == Some(is_horiz) {
449            return false;
450        }
451        prev_horiz = Some(is_horiz);
452    }
453    true
454}
455
456#[inline]
457fn point_in_triangle_ccw(p: (f32, f32), a: (f32, f32), b: (f32, f32), c: (f32, f32)) -> bool {
458    orient2d(a, b, p) >= -1e-4 && orient2d(b, c, p) >= -1e-4 && orient2d(c, a, p) >= -1e-4
459}
460
461fn triangulate_subpath_pts(raw_pts: &[(f32, f32)]) -> Vec<GpuClipVertex> {
462    let mut pts: Vec<(f32, f32)> = Vec::with_capacity(raw_pts.len());
463    for &p in raw_pts {
464        if pts
465            .last()
466            .is_none_or(|&prev| (p.0 - prev.0).hypot(p.1 - prev.1) > 1e-4)
467        {
468            pts.push(p);
469        }
470    }
471    if pts.len() >= 2 {
472        let first = pts[0];
473        let last = *pts.last().unwrap();
474        if (first.0 - last.0).hypot(first.1 - last.1) <= 1e-4 {
475            pts.pop();
476        }
477    }
478    let n = pts.len();
479    if n < 3 {
480        return Vec::new();
481    }
482
483    let mut area2 = 0.0_f32;
484    for i in 0..n {
485        let a = pts[i];
486        let b = pts[(i + 1) % n];
487        area2 += a.0 * b.1 - b.0 * a.1;
488    }
489    if area2.abs() <= 1e-4 {
490        return Vec::new();
491    }
492    if area2 < 0.0 {
493        pts.reverse();
494    }
495
496    let mut out = Vec::with_capacity((n - 2) * 3);
497    let mut indices: Vec<usize> = (0..n).collect();
498    let mut guard = 0usize;
499    let max_iters = n * n;
500
501    while indices.len() > 3 && guard < max_iters {
502        guard += 1;
503        let m = indices.len();
504        let mut clipped = false;
505        for i in 0..m {
506            let i_prev = indices[(i + m - 1) % m];
507            let i_curr = indices[i];
508            let i_next = indices[(i + 1) % m];
509            let a = pts[i_prev];
510            let b = pts[i_curr];
511            let c = pts[i_next];
512            if orient2d(a, b, c) <= 1e-5 {
513                continue;
514            }
515            let mut empty = true;
516            for (k_idx, &idx) in indices.iter().enumerate() {
517                if k_idx == (i + m - 1) % m || k_idx == i || k_idx == (i + 1) % m {
518                    continue;
519                }
520                if point_in_triangle_ccw(pts[idx], a, b, c) {
521                    empty = false;
522                    break;
523                }
524            }
525            if empty {
526                out.push(GpuClipVertex::new(a.0, a.1));
527                out.push(GpuClipVertex::new(b.0, b.1));
528                out.push(GpuClipVertex::new(c.0, c.1));
529                indices.remove(i);
530                clipped = true;
531                break;
532            }
533        }
534        if !clipped {
535            // Self-intersecting subpath fallback: centroid fan pairs cleanly with Invert even-odd stencil.
536            out.clear();
537            let inv = 1.0 / (n as f32);
538            let mut cx = 0.0_f32;
539            let mut cy = 0.0_f32;
540            for &(px, py) in &pts {
541                cx += px;
542                cy += py;
543            }
544            cx *= inv;
545            cy *= inv;
546            for i in 0..n {
547                let a = pts[i];
548                let b = pts[(i + 1) % n];
549                out.push(GpuClipVertex::new(cx, cy));
550                out.push(GpuClipVertex::new(a.0, a.1));
551                out.push(GpuClipVertex::new(b.0, b.1));
552            }
553            return out;
554        }
555    }
556
557    if indices.len() == 3 {
558        let a = pts[indices[0]];
559        let b = pts[indices[1]];
560        let c = pts[indices[2]];
561        out.push(GpuClipVertex::new(a.0, a.1));
562        out.push(GpuClipVertex::new(b.0, b.1));
563        out.push(GpuClipVertex::new(c.0, c.1));
564    }
565    out
566}
567
568/// Evaluates whether axis-aligned `r` is completely outside, partially clipped by, or strictly
569/// inside a stack of non-rectangular clip subpath layers (`even-odd` fill per layer).
570pub fn rect_relation_to_clip_polys(
571    r: Rect,
572    clip_polys: &[Vec<Vec<(f32, f32)>>],
573) -> ClipContainment {
574    if clip_polys.is_empty() {
575        return ClipContainment::Inside;
576    }
577    if r.width <= 0.0 || r.height <= 0.0 {
578        return ClipContainment::Outside;
579    }
580
581    let x0 = r.x;
582    let y0 = r.y;
583    let x1 = r.max_x();
584    let y1 = r.max_y();
585    let rect_edges = [
586        ((x0, y0), (x1, y0)),
587        ((x1, y0), (x1, y1)),
588        ((x1, y1), (x0, y1)),
589        ((x0, y1), (x0, y0)),
590    ];
591    let samples = [
592        (x0, y0),
593        (x1, y0),
594        (x1, y1),
595        (x0, y1),
596        ((x0 + x1) * 0.5, (y0 + y1) * 0.5),
597    ];
598
599    let mut all_inside = true;
600    for poly in clip_polys {
601        let mut any_vertex_in_rect = false;
602        let mut any_edge_cross = false;
603
604        'poly_scan: for sub in poly {
605            if sub.len() < 2 {
606                continue;
607            }
608            for &v in sub {
609                if v.0 > x0 + 1e-4 && v.0 < x1 - 1e-4 && v.1 > y0 + 1e-4 && v.1 < y1 - 1e-4 {
610                    any_vertex_in_rect = true;
611                    break 'poly_scan;
612                }
613            }
614            let closed_sub = sub.len() >= 3;
615            let edge_count = if closed_sub { sub.len() } else { sub.len() - 1 };
616            for i in 0..edge_count {
617                let a = sub[i];
618                let b = sub[(i + 1) % sub.len()];
619                for &(e0, e1) in &rect_edges {
620                    if segments_intersect_2d(a, b, e0, e1) {
621                        any_edge_cross = true;
622                        break 'poly_scan;
623                    }
624                }
625            }
626        }
627
628        if any_vertex_in_rect || any_edge_cross {
629            all_inside = false;
630            continue;
631        }
632
633        let mut inside_count = 0usize;
634        for &(sx, sy) in &samples {
635            if crate::canvas2d::point_in_subpaths_even_odd(poly, sx, sy) {
636                inside_count += 1;
637            }
638        }
639        if inside_count == 0 {
640            return ClipContainment::Outside;
641        }
642        if inside_count < samples.len() {
643            all_inside = false;
644        }
645    }
646
647    if all_inside {
648        ClipContainment::Inside
649    } else {
650        ClipContainment::Partial
651    }
652}
653
654fn push_clip_span(spans: &mut Vec<GpuClipSpan>, count: usize, index: usize, mask: Option<usize>) {
655    if let Some(last) = spans.last_mut() {
656        if last.end == index && last.clip_mask == mask {
657            last.end = index + count;
658            return;
659        }
660    }
661    spans.push(GpuClipSpan {
662        start: index,
663        end: index + count,
664        clip_mask: mask,
665    });
666}
667
668fn resolve_or_push_clip_mask(
669    masks: &mut Vec<GpuClipMask>,
670    active_clip: Option<Rect>,
671    clip_polys: &[Vec<Vec<(f32, f32)>>],
672) -> Option<usize> {
673    if clip_polys.is_empty() {
674        return None;
675    }
676    let bounds = active_clip?;
677    if let Some((idx, _)) = masks
678        .iter()
679        .enumerate()
680        .find(|(_, m)| m.bounds == bounds && m.layers == clip_polys)
681    {
682        Some(idx)
683    } else {
684        let idx = masks.len();
685        masks.push(GpuClipMask::from_layers(bounds, clip_polys.to_vec()));
686        Some(idx)
687    }
688}
689
690#[inline]
691fn apply_color_opacity(c: Color, alpha_mul: f32) -> Color {
692    if (alpha_mul - 1.0).abs() <= 1e-4 {
693        return c;
694    }
695    let (r, g, b, a) = c.to_f32();
696    Color::from_f32(r, g, b, (a * alpha_mul).clamp(0.0, 1.0))
697}
698
699fn rounded_rect_subpath(bounds: Rect, radius: BorderRadius) -> Vec<(f32, f32)> {
700    let hw = bounds.width * 0.5;
701    let hh = bounds.height * 0.5;
702    let max_r = hw.min(hh).max(0.0);
703    let r_tl = radius.top_left.clamp(0.0, max_r);
704    let r_tr = radius.top_right.clamp(0.0, max_r);
705    let r_br = radius.bottom_right.clamp(0.0, max_r);
706    let r_bl = radius.bottom_left.clamp(0.0, max_r);
707
708    let mut pts = Vec::with_capacity(32);
709    let corners = [
710        (
711            bounds.x + bounds.width - r_tr,
712            bounds.y + r_tr,
713            r_tr,
714            -std::f32::consts::FRAC_PI_2,
715            0.0,
716        ),
717        (
718            bounds.x + bounds.width - r_br,
719            bounds.y + bounds.height - r_br,
720            r_br,
721            0.0,
722            std::f32::consts::FRAC_PI_2,
723        ),
724        (
725            bounds.x + r_bl,
726            bounds.y + bounds.height - r_bl,
727            r_bl,
728            std::f32::consts::FRAC_PI_2,
729            std::f32::consts::PI,
730        ),
731        (
732            bounds.x + r_tl,
733            bounds.y + r_tl,
734            r_tl,
735            std::f32::consts::PI,
736            std::f32::consts::PI * 1.5,
737        ),
738    ];
739    for (cx, cy, r, a0, a1) in corners {
740        if r <= 0.25 {
741            pts.push((cx, cy));
742        } else {
743            let steps = 6usize;
744            for i in 0..=steps {
745                let a = a0 + (a1 - a0) * (i as f32 / steps as f32);
746                pts.push((cx + r * a.cos(), cy + r * a.sin()));
747            }
748        }
749    }
750    pts
751}
752
753fn compute_dashed_stroke_rect_segments(
754    r: Rect,
755    lw: f32,
756    line_dash: &[f32],
757    dash_offset: f32,
758) -> Vec<Rect> {
759    let mut out = Vec::new();
760    let period: f32 = line_dash.iter().copied().sum();
761    if line_dash.is_empty() || period <= 1e-4 || lw <= 0.0 || r.width <= 0.0 || r.height <= 0.0 {
762        return out;
763    }
764    let half = lw * 0.5;
765    let mut phase = dash_offset.rem_euclid(period);
766    let mut dash_idx = 0usize;
767    while dash_idx < line_dash.len() && phase >= line_dash[dash_idx] {
768        phase -= line_dash[dash_idx];
769        dash_idx = (dash_idx + 1) % line_dash.len();
770    }
771    let mut rem = (line_dash[dash_idx] - phase).max(0.0);
772
773    // Edges clockwise matching Cairo/framebuffer: Top, Right, Bottom, Left
774    let edges = [
775        (0u8, r.width),
776        (1u8, r.height),
777        (2u8, r.width),
778        (3u8, r.height),
779    ];
780    for (edge_id, edge_len) in edges {
781        if edge_len <= 1e-4 {
782            continue;
783        }
784        let mut cursor = 0.0_f32;
785        while cursor < edge_len {
786            if rem <= 1e-4 {
787                dash_idx = (dash_idx + 1) % line_dash.len();
788                rem = line_dash[dash_idx];
789                if rem <= 1e-4 {
790                    break;
791                }
792            }
793            let step = rem.min(edge_len - cursor);
794            if dash_idx.is_multiple_of(2) && step > 1e-4 {
795                let s0 = cursor;
796                let s1 = cursor + step;
797                let seg_rect = match edge_id {
798                    0 => Rect::new(r.x + s0, r.y - half, s1 - s0, lw),
799                    1 => Rect::new(r.x + r.width - half, r.y + s0, lw, s1 - s0),
800                    2 => Rect::new(r.x + r.width - s1, r.y + r.height - half, s1 - s0, lw),
801                    _ => Rect::new(r.x - half, r.y + r.height - s1, lw, s1 - s0),
802                };
803                out.push(seg_rect);
804            }
805            cursor += step;
806            rem -= step;
807        }
808    }
809    out
810}
811
812/// Batch collection of GPU instanced quads ready for upload to GPU buffers.
813#[derive(Debug, Default, Clone, PartialEq)]
814pub struct GpuBatch {
815    pub instances: Vec<GpuQuadInstance>,
816    /// Compiled non-rectangular/stencil clip masks referenced by [`Self::clip_spans`].
817    pub clip_masks: Vec<GpuClipMask>,
818    /// Contiguous instance ranges mapped to their active optional stencil clip mask index.
819    pub clip_spans: Vec<GpuClipSpan>,
820}
821
822impl GpuBatch {
823    pub fn new() -> Self {
824        Self::default()
825    }
826
827    pub fn with_capacity(capacity: usize) -> Self {
828        Self {
829            instances: Vec::with_capacity(capacity),
830            clip_masks: Vec::new(),
831            clip_spans: Vec::new(),
832        }
833    }
834
835    #[inline]
836    pub fn push(&mut self, instance: GpuQuadInstance) {
837        self.push_with_clip(instance, None);
838    }
839
840    /// Pushes a quad instance associated with an optional non-rectangular stencil clip mask index.
841    #[inline]
842    pub fn push_with_clip(&mut self, instance: GpuQuadInstance, clip_mask: Option<usize>) {
843        let idx = self.instances.len();
844        self.instances.push(instance);
845        if clip_mask.is_some() || !self.clip_spans.is_empty() {
846            push_clip_span(&mut self.clip_spans, 1, idx, clip_mask);
847        }
848    }
849
850    #[inline]
851    pub fn has_stencil_clips(&self) -> bool {
852        !self.clip_masks.is_empty()
853    }
854
855    /// Returns the stencil clip mask governing `instance_index`, if any.
856    pub fn clip_mask_for_instance(&self, instance_index: usize) -> Option<&GpuClipMask> {
857        let span = self
858            .clip_spans
859            .iter()
860            .find(|s| instance_index >= s.start && instance_index < s.end)?;
861        span.clip_mask.and_then(|id| self.clip_masks.get(id))
862    }
863
864    #[inline]
865    pub fn clear(&mut self) {
866        self.instances.clear();
867        self.clip_masks.clear();
868        self.clip_spans.clear();
869    }
870
871    #[inline]
872    pub fn len(&self) -> usize {
873        self.instances.len()
874    }
875
876    #[inline]
877    pub fn is_empty(&self) -> bool {
878        self.instances.is_empty()
879    }
880
881    #[inline]
882    pub fn as_bytes(&self) -> &[u8] {
883        GpuQuadInstance::slice_to_bytes(&self.instances)
884    }
885
886    /// Compiles a DisplayList into GPU quad instances for the given viewport.
887    pub fn from_display_list(
888        list: &DisplayList,
889        viewport_width: f32,
890        viewport_height: f32,
891    ) -> Self {
892        Self::from_display_list_damaged(list, None, viewport_width, viewport_height)
893    }
894
895    /// Compiles a DisplayList into GPU quad instances, scissoring to the optional damage rectangle.
896    pub fn from_display_list_damaged(
897        list: &DisplayList,
898        damage: Option<Rect>,
899        viewport_width: f32,
900        viewport_height: f32,
901    ) -> Self {
902        let mut batch = Self::with_capacity(list.len());
903        let mut clip_stack: Vec<Rect> = Vec::new();
904        let mut transform_stack: Vec<strata_primitives::geom::Matrix4x4> = Vec::new();
905        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
906
907        for cmd in list.commands() {
908            if let DrawCommand::PushClip { bounds, .. } = cmd {
909                let combined = match clip_stack.last() {
910                    Some(prev) => prev.intersect(*bounds).unwrap_or(Rect::zero()),
911                    None => *bounds,
912                };
913                clip_stack.push(combined);
914                continue;
915            } else if let DrawCommand::PopClip = cmd {
916                clip_stack.pop();
917                continue;
918            } else if let DrawCommand::PushTransform { matrix } = cmd {
919                let combined = match transform_stack.last() {
920                    Some(prev) => prev.multiply(matrix),
921                    None => *matrix,
922                };
923                transform_stack.push(combined);
924                continue;
925            } else if let DrawCommand::PopTransform = cmd {
926                transform_stack.pop();
927                continue;
928            }
929
930            let current_clip = match clip_stack.last() {
931                Some(prev) => match prev.intersect(default_clip) {
932                    Some(c) => c,
933                    None => continue, // Clipped away completely
934                },
935                None => default_clip,
936            };
937
938            let active_matrix = transform_stack.last();
939            let transform_rect_fn = |r: Rect| -> Rect {
940                if let Some(mat) = active_matrix {
941                    if !mat.is_identity() {
942                        let (x, y, w, h) = mat.transform_bounds(r.x, r.y, r.width, r.height);
943                        return Rect::new(x, y, w, h);
944                    }
945                }
946                r
947            };
948
949            // Fast AABB intersection check
950            let transformed_bounds = cmd.bounds().map(transform_rect_fn);
951            if let Some(cmd_bounds) = transformed_bounds {
952                if cmd_bounds.intersect(current_clip).is_none() {
953                    continue;
954                }
955            }
956
957            match cmd {
958                DrawCommand::DrawRect { bounds, color } => {
959                    batch.push(GpuQuadInstance::from_rect(
960                        transform_rect_fn(*bounds),
961                        *color,
962                        current_clip,
963                    ));
964                }
965                DrawCommand::DrawRoundedRect {
966                    bounds,
967                    color,
968                    border_radius,
969                    border_width,
970                    border_color,
971                } => {
972                    batch.push(GpuQuadInstance::from_rounded_rect(
973                        transform_rect_fn(*bounds),
974                        *color,
975                        *border_radius,
976                        *border_width,
977                        *border_color,
978                        current_clip,
979                    ));
980                }
981                DrawCommand::DrawBorder {
982                    bounds,
983                    widths,
984                    color,
985                    border_radius,
986                    ..
987                } => {
988                    batch.push(GpuQuadInstance::from_rounded_rect(
989                        transform_rect_fn(*bounds),
990                        Color::TRANSPARENT,
991                        *border_radius,
992                        *widths,
993                        Some(*color),
994                        current_clip,
995                    ));
996                }
997                DrawCommand::DrawCanvas2D { bounds, commands } => {
998                    if let Some(base_clip) = transform_rect_fn(*bounds).intersect(current_clip) {
999                        let mut active_clip = Some(base_clip);
1000                        let mut line_dash: Vec<f32> = Vec::new();
1001                        let mut dash_offset: f32 = 0.0;
1002                        let mut clip_polys: Vec<Vec<Vec<(f32, f32)>>> = Vec::new();
1003                        let mut clip_mask_id: Option<usize> = None;
1004                        #[allow(clippy::type_complexity)]
1005                        let mut state_stack: Vec<(
1006                            Option<Rect>,
1007                            Vec<f32>,
1008                            f32,
1009                            Vec<Vec<Vec<(f32, f32)>>>,
1010                            Option<usize>,
1011                        )> = Vec::new();
1012
1013                        let transform_subpaths = |subs: Vec<Vec<(f32, f32)>>| -> Vec<Vec<(f32, f32)>> {
1014                            if let Some(mat) = active_matrix {
1015                                if !mat.is_identity() {
1016                                    return subs
1017                                        .into_iter()
1018                                        .map(|sub| {
1019                                            sub.into_iter()
1020                                                .map(|(x, y)| mat.transform_point(x, y))
1021                                                .collect()
1022                                        })
1023                                        .collect();
1024                                }
1025                            }
1026                            subs
1027                        };
1028
1029                        for ccmd in commands {
1030                            match ccmd {
1031                                crate::canvas2d::CanvasCommand::Save => {
1032                                    state_stack.push((
1033                                        active_clip,
1034                                        line_dash.clone(),
1035                                        dash_offset,
1036                                        clip_polys.clone(),
1037                                        clip_mask_id,
1038                                    ));
1039                                }
1040                                crate::canvas2d::CanvasCommand::Restore => {
1041                                    if let Some((
1042                                        prev_clip,
1043                                        prev_dash,
1044                                        prev_offset,
1045                                        prev_polys,
1046                                        prev_mask,
1047                                    )) = state_stack.pop()
1048                                    {
1049                                        active_clip = prev_clip;
1050                                        line_dash = prev_dash;
1051                                        dash_offset = prev_offset;
1052                                        clip_polys = prev_polys;
1053                                        clip_mask_id = prev_mask;
1054                                    }
1055                                }
1056                                crate::canvas2d::CanvasCommand::SetLineDash {
1057                                    segments,
1058                                    offset,
1059                                } => {
1060                                    line_dash = segments
1061                                        .iter()
1062                                        .copied()
1063                                        .filter(|d| d.is_finite() && *d >= 0.0)
1064                                        .collect();
1065                                    if line_dash.len() % 2 == 1 {
1066                                        let dup = line_dash.clone();
1067                                        line_dash.extend(dup);
1068                                    }
1069                                    dash_offset = if offset.is_finite() { *offset } else { 0.0 };
1070                                }
1071                                crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
1072                                    let subpaths = transform_subpaths(
1073                                        crate::canvas2d::flatten_canvas_verbs(
1074                                            verbs, bounds.x, bounds.y,
1075                                        ),
1076                                    );
1077                                    if !subpaths.is_empty() {
1078                                        let mut min_x = f32::INFINITY;
1079                                        let mut min_y = f32::INFINITY;
1080                                        let mut max_x = f32::NEG_INFINITY;
1081                                        let mut max_y = f32::NEG_INFINITY;
1082                                        for sub in &subpaths {
1083                                            for &(x, y) in sub {
1084                                                min_x = min_x.min(x);
1085                                                min_y = min_y.min(y);
1086                                                max_x = max_x.max(x);
1087                                                max_y = max_y.max(y);
1088                                            }
1089                                        }
1090                                        if min_x.is_finite()
1091                                            && min_y.is_finite()
1092                                            && max_x >= min_x
1093                                            && max_y >= min_y
1094                                        {
1095                                            let tb = Rect::new(
1096                                                min_x,
1097                                                min_y,
1098                                                max_x - min_x,
1099                                                max_y - min_y,
1100                                            );
1101                                            active_clip =
1102                                                active_clip.and_then(|c| c.intersect(tb));
1103                                        }
1104                                        if !subpaths_are_axis_aligned_rect(&subpaths) {
1105                                            clip_polys.push(subpaths);
1106                                            clip_mask_id = resolve_or_push_clip_mask(
1107                                                &mut batch.clip_masks,
1108                                                active_clip,
1109                                                &clip_polys,
1110                                            );
1111                                        }
1112                                    }
1113                                }
1114                                crate::canvas2d::CanvasCommand::FillRect {
1115                                    bounds: rb,
1116                                    color,
1117                                } => {
1118                                    if let Some(canvas_clip) = active_clip {
1119                                        let r = transform_rect_fn(Rect::new(
1120                                            bounds.x + rb.x,
1121                                            bounds.y + rb.y,
1122                                            rb.width,
1123                                            rb.height,
1124                                        ));
1125                                        if r.intersect(canvas_clip).is_none() {
1126                                            continue;
1127                                        }
1128                                        let (emit, mask) = if clip_polys.is_empty() {
1129                                            (true, None)
1130                                        } else {
1131                                            match rect_relation_to_clip_polys(r, &clip_polys) {
1132                                                ClipContainment::Outside => (false, None),
1133                                                ClipContainment::Inside => (true, None),
1134                                                ClipContainment::Partial => (true, clip_mask_id),
1135                                            }
1136                                        };
1137                                        if emit {
1138                                            batch.push_with_clip(
1139                                                GpuQuadInstance::from_rect(r, *color, canvas_clip),
1140                                                mask,
1141                                            );
1142                                        }
1143                                    }
1144                                }
1145                                crate::canvas2d::CanvasCommand::StrokeRect {
1146                                    bounds: rb,
1147                                    color,
1148                                    line_width,
1149                                } => {
1150                                    if let Some(canvas_clip) = active_clip {
1151                                        let r = Rect::new(
1152                                            bounds.x + rb.x,
1153                                            bounds.y + rb.y,
1154                                            rb.width,
1155                                            rb.height,
1156                                        );
1157                                        let period: f32 = line_dash.iter().copied().sum();
1158                                        if line_dash.is_empty() || period <= 1e-4 {
1159                                            let tr = transform_rect_fn(r);
1160                                            let lw = *line_width;
1161                                            let (emit, mask) = if clip_polys.is_empty() {
1162                                                (tr.intersect(canvas_clip).is_some(), None)
1163                                            } else {
1164                                                let half = lw * 0.5;
1165                                                let edge_rects = [
1166                                                    Rect::new(tr.x, tr.y - half, tr.width, lw),
1167                                                    Rect::new(
1168                                                        tr.x + tr.width - half,
1169                                                        tr.y,
1170                                                        lw,
1171                                                        tr.height,
1172                                                    ),
1173                                                    Rect::new(
1174                                                        tr.x,
1175                                                        tr.y + tr.height - half,
1176                                                        tr.width,
1177                                                        lw,
1178                                                    ),
1179                                                    Rect::new(tr.x - half, tr.y, lw, tr.height),
1180                                                ];
1181                                                let mut any_in = false;
1182                                                let mut all_strictly_in = true;
1183                                                for er in edge_rects {
1184                                                    match rect_relation_to_clip_polys(
1185                                                        er,
1186                                                        &clip_polys,
1187                                                    ) {
1188                                                        ClipContainment::Outside => {
1189                                                            all_strictly_in = false;
1190                                                        }
1191                                                        ClipContainment::Inside => {
1192                                                            any_in = true;
1193                                                        }
1194                                                        ClipContainment::Partial => {
1195                                                            any_in = true;
1196                                                            all_strictly_in = false;
1197                                                        }
1198                                                    }
1199                                                }
1200                                                if !any_in {
1201                                                    (false, None)
1202                                                } else if all_strictly_in {
1203                                                    (true, None)
1204                                                } else {
1205                                                    (true, clip_mask_id)
1206                                                }
1207                                            };
1208                                            if emit {
1209                                                batch.push_with_clip(
1210                                                    GpuQuadInstance::from_rounded_rect(
1211                                                        tr,
1212                                                        Color::TRANSPARENT,
1213                                                        BorderRadius::default(),
1214                                                        EdgeInsets::all(lw),
1215                                                        Some(*color),
1216                                                        canvas_clip,
1217                                                    ),
1218                                                    mask,
1219                                                );
1220                                            }
1221                                        } else if *line_width > 0.0 && r.width > 0.0 && r.height > 0.0
1222                                        {
1223                                            for seg_rect in compute_dashed_stroke_rect_segments(
1224                                                r,
1225                                                *line_width,
1226                                                &line_dash,
1227                                                dash_offset,
1228                                            ) {
1229                                                let t_seg = transform_rect_fn(seg_rect);
1230                                                if t_seg.intersect(canvas_clip).is_some() {
1231                                                    let (emit, mask) = if clip_polys.is_empty() {
1232                                                        (true, None)
1233                                                    } else {
1234                                                        match rect_relation_to_clip_polys(
1235                                                            t_seg,
1236                                                            &clip_polys,
1237                                                        ) {
1238                                                            ClipContainment::Outside => {
1239                                                                (false, None)
1240                                                            }
1241                                                            ClipContainment::Inside => (true, None),
1242                                                            ClipContainment::Partial => {
1243                                                                (true, clip_mask_id)
1244                                                            }
1245                                                        }
1246                                                    };
1247                                                    if emit {
1248                                                        batch.push_with_clip(
1249                                                            GpuQuadInstance::from_rect(
1250                                                                t_seg,
1251                                                                *color,
1252                                                                canvas_clip,
1253                                                            ),
1254                                                            mask,
1255                                                        );
1256                                                    }
1257                                                }
1258                                            }
1259                                        }
1260                                    }
1261                                }
1262                                _ => {}
1263                            }
1264                        }
1265                    }
1266                }
1267                _ => {}
1268            }
1269        }
1270
1271        batch
1272    }
1273}
1274
1275/// Slug-tier analytical GPU text compilation pipeline.
1276///
1277/// Compiles DisplayList text commands (`DrawText`, `DrawTextFragments`) into analytical
1278/// quadratic Bézier glyph instances and curve contours for hardware shader evaluation.
1279#[derive(Debug, Clone)]
1280pub struct GpuSlugTextPipeline {
1281    pub glyph_cache: strata_gpu_path::AnalyticGlyphCache,
1282    pub buffer: strata_gpu_path::SlugGlyphBuffer,
1283    pub total_glyphs: usize,
1284    pub total_curves: usize,
1285}
1286
1287impl Default for GpuSlugTextPipeline {
1288    fn default() -> Self {
1289        Self::new()
1290    }
1291}
1292
1293impl GpuSlugTextPipeline {
1294    pub fn new() -> Self {
1295        Self {
1296            glyph_cache: strata_gpu_path::AnalyticGlyphCache::with_standard_ascii(),
1297            buffer: strata_gpu_path::SlugGlyphBuffer::new(),
1298            total_glyphs: 0,
1299            total_curves: 0,
1300        }
1301    }
1302
1303    pub fn clear(&mut self) {
1304        self.buffer.clear();
1305        self.total_glyphs = 0;
1306        self.total_curves = 0;
1307    }
1308
1309    /// Advances and returns the hardware synchronization fence.
1310    pub fn sync_barrier(&self) -> u64 {
1311        self.buffer.sync_barrier()
1312    }
1313
1314    /// Checks if a hardware synchronization fence has been signaled.
1315    pub fn is_fence_synchronized(&self, fence: u64) -> bool {
1316        self.buffer.is_fence_synchronized(fence)
1317    }
1318
1319    #[allow(clippy::too_many_arguments)]
1320    fn push_text_run(
1321        &mut self,
1322        text: &str,
1323        start_x: f32,
1324        start_y: f32,
1325        font_size: f32,
1326        x_squeeze: f32,
1327        color: Color,
1328        clip_rect: Rect,
1329    ) -> usize {
1330        let (r, g, b, a) = color.to_f32();
1331        let color_f32 = [r, g, b, a];
1332        let clip_r = strata_gpu_path::Rect2D::new(
1333            clip_rect.x,
1334            clip_rect.y,
1335            clip_rect.x + clip_rect.width,
1336            clip_rect.y + clip_rect.height,
1337        );
1338        let mut cursor_x = start_x;
1339        let cursor_y = start_y;
1340        let mut pushed = 0usize;
1341
1342        for ch in text.chars() {
1343            if let Some(glyph) = self.glyph_cache.get(ch) {
1344                let glyph_w = glyph.advance_width * font_size * x_squeeze;
1345                let glyph_h = font_size;
1346                let screen_bounds = strata_gpu_path::Rect2D::new(
1347                    cursor_x,
1348                    cursor_y,
1349                    cursor_x + glyph_w,
1350                    cursor_y + glyph_h,
1351                );
1352                if clip_rect
1353                    .intersect(Rect::new(cursor_x, cursor_y, glyph_w, glyph_h))
1354                    .is_some()
1355                    && self
1356                        .buffer
1357                        .push_glyph(glyph, screen_bounds, color_f32, clip_r)
1358                {
1359                    self.total_glyphs += 1;
1360                    pushed += 1;
1361                }
1362                cursor_x += glyph_w;
1363            } else {
1364                cursor_x += font_size * 0.5 * x_squeeze;
1365            }
1366        }
1367        pushed
1368    }
1369
1370    #[allow(clippy::too_many_arguments)]
1371    fn push_canvas_text(
1372        &mut self,
1373        bounds: Rect,
1374        text: &str,
1375        x: f32,
1376        y: f32,
1377        color: Color,
1378        font_size: f32,
1379        text_align: crate::canvas2d::CanvasTextAlign,
1380        text_baseline: crate::canvas2d::CanvasTextBaseline,
1381        max_width: Option<f32>,
1382        canvas_clip: Rect,
1383    ) -> (usize, Rect) {
1384        let scale = font_size;
1385        let raw_w: f32 = text
1386            .chars()
1387            .map(|ch| {
1388                self.glyph_cache
1389                    .get(ch)
1390                    .map(|g| g.advance_width * scale)
1391                    .unwrap_or(scale * 0.5)
1392            })
1393            .sum();
1394        let x_squeeze = match max_width {
1395            Some(mw) if mw > 0.0 && raw_w > mw => mw / raw_w,
1396            _ => 1.0,
1397        };
1398        let total_w = raw_w * x_squeeze;
1399        let cursor_x = bounds.x
1400            + match text_align {
1401                crate::canvas2d::CanvasTextAlign::Left | crate::canvas2d::CanvasTextAlign::Start => {
1402                    x
1403                }
1404                crate::canvas2d::CanvasTextAlign::Center => x - total_w * 0.5,
1405                crate::canvas2d::CanvasTextAlign::Right | crate::canvas2d::CanvasTextAlign::End => {
1406                    x - total_w
1407                }
1408            };
1409        let cursor_y = bounds.y
1410            + match text_baseline {
1411                crate::canvas2d::CanvasTextBaseline::Top
1412                | crate::canvas2d::CanvasTextBaseline::Hanging => y,
1413                crate::canvas2d::CanvasTextBaseline::Middle => y - scale * 0.5,
1414                crate::canvas2d::CanvasTextBaseline::Bottom
1415                | crate::canvas2d::CanvasTextBaseline::Ideographic => y - scale,
1416                crate::canvas2d::CanvasTextBaseline::Alphabetic => y - scale * 0.8,
1417            };
1418        let run_rect = Rect::new(cursor_x, cursor_y, total_w.max(1.0), scale.max(1.0));
1419        let pushed = self.push_text_run(
1420            text,
1421            cursor_x,
1422            cursor_y,
1423            scale,
1424            x_squeeze,
1425            color,
1426            canvas_clip,
1427        );
1428        (pushed, run_rect)
1429    }
1430
1431    /// Compiles all DrawText commands in a DisplayList into the Slug GPU buffer.
1432    pub fn compile_display_list(
1433        &mut self,
1434        list: &DisplayList,
1435        viewport_width: f32,
1436        viewport_height: f32,
1437        damage: Option<Rect>,
1438    ) -> usize {
1439        self.clear();
1440        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
1441
1442        for cmd in list.commands() {
1443            match cmd {
1444                DrawCommand::DrawText {
1445                    origin,
1446                    text,
1447                    font_size,
1448                    color,
1449                    ..
1450                } => {
1451                    self.push_text_run(
1452                        text,
1453                        origin.0,
1454                        origin.1,
1455                        *font_size,
1456                        1.0,
1457                        *color,
1458                        default_clip,
1459                    );
1460                }
1461                DrawCommand::DrawTextFragments { fragments } => {
1462                    for frag in fragments {
1463                        self.push_text_run(
1464                            &frag.text,
1465                            frag.bounds.x,
1466                            frag.bounds.y,
1467                            frag.style.font_size,
1468                            1.0,
1469                            frag.style.color,
1470                            default_clip,
1471                        );
1472                    }
1473                }
1474                DrawCommand::DrawCanvas2D { bounds, commands } => {
1475                    let Some(base_clip) = bounds.intersect(default_clip) else {
1476                        continue;
1477                    };
1478                    let mut active_clip = Some(base_clip);
1479                    let mut clip_stack: Vec<Option<Rect>> = Vec::new();
1480
1481                    for ccmd in commands {
1482                        match ccmd {
1483                            crate::canvas2d::CanvasCommand::Save => {
1484                                clip_stack.push(active_clip);
1485                            }
1486                            crate::canvas2d::CanvasCommand::Restore => {
1487                                if let Some(prev) = clip_stack.pop() {
1488                                    active_clip = prev;
1489                                }
1490                            }
1491                            crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
1492                                if let Some(vbbox) =
1493                                    crate::canvas2d::canvas_verbs_bounds(verbs, bounds.x, bounds.y)
1494                                {
1495                                    active_clip = active_clip.and_then(|c| c.intersect(vbbox));
1496                                }
1497                            }
1498                            crate::canvas2d::CanvasCommand::FillText {
1499                                text,
1500                                x,
1501                                y,
1502                                color,
1503                                font_size,
1504                                text_align,
1505                                text_baseline,
1506                                max_width,
1507                                ..
1508                            }
1509                            | crate::canvas2d::CanvasCommand::StrokeText {
1510                                text,
1511                                x,
1512                                y,
1513                                color,
1514                                font_size,
1515                                text_align,
1516                                text_baseline,
1517                                max_width,
1518                                ..
1519                            } => {
1520                                let Some(canvas_clip) = active_clip else {
1521                                    continue;
1522                                };
1523                                self.push_canvas_text(
1524                                    *bounds,
1525                                    text,
1526                                    *x,
1527                                    *y,
1528                                    *color,
1529                                    *font_size,
1530                                    *text_align,
1531                                    *text_baseline,
1532                                    *max_width,
1533                                    canvas_clip,
1534                                );
1535                            }
1536                            _ => {}
1537                        }
1538                    }
1539                }
1540                _ => {}
1541            }
1542        }
1543
1544        self.total_curves = self.buffer.curves.len();
1545        self.total_glyphs
1546    }
1547
1548    #[inline]
1549    pub fn instance_bytes(&self) -> &[u8] {
1550        self.buffer.instances_as_bytes()
1551    }
1552
1553    #[inline]
1554    pub fn curve_bytes(&self) -> &[u8] {
1555        self.buffer.curves_as_bytes()
1556    }
1557}
1558
1559/// High-level orchestration pipeline for compiling display lists into GPU instance buffers.
1560#[derive(Debug, Clone)]
1561pub struct GpuPresentationPipeline {
1562    pub viewport_width: f32,
1563    pub viewport_height: f32,
1564    pub uniforms: GpuUniforms,
1565    pub batch: GpuBatch,
1566    pub text_pipeline: GpuSlugTextPipeline,
1567    pub total_uploaded_bytes: usize,
1568    pub compiled_frames: u64,
1569}
1570
1571impl GpuPresentationPipeline {
1572    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
1573        Self {
1574            viewport_width,
1575            viewport_height,
1576            uniforms: GpuUniforms::new(viewport_width, viewport_height),
1577            batch: GpuBatch::new(),
1578            text_pipeline: GpuSlugTextPipeline::new(),
1579            total_uploaded_bytes: 0,
1580            compiled_frames: 0,
1581        }
1582    }
1583
1584    pub fn resize(&mut self, width: f32, height: f32) {
1585        self.viewport_width = width;
1586        self.viewport_height = height;
1587        self.uniforms = GpuUniforms::new(width, height);
1588    }
1589
1590    /// Compiles a frame from a DisplayList and optional damage rectangle into internal buffers.
1591    /// Returns the total number of primitives (quads + text glyphs) emitted.
1592    pub fn compile_frame(&mut self, list: &DisplayList, damage: Option<Rect>) -> usize {
1593        self.batch = GpuBatch::from_display_list_damaged(
1594            list,
1595            damage,
1596            self.viewport_width,
1597            self.viewport_height,
1598        );
1599
1600        let glyph_count = self.text_pipeline.compile_display_list(
1601            list,
1602            self.viewport_width,
1603            self.viewport_height,
1604            damage,
1605        );
1606
1607        let byte_count = self.batch.as_bytes().len()
1608            + self.uniforms.as_bytes().len()
1609            + self.text_pipeline.instance_bytes().len()
1610            + self.text_pipeline.curve_bytes().len();
1611        self.total_uploaded_bytes += byte_count;
1612        self.compiled_frames += 1;
1613
1614        self.batch.len() + glyph_count
1615    }
1616
1617    #[inline]
1618    pub fn instance_bytes(&self) -> &[u8] {
1619        self.batch.as_bytes()
1620    }
1621
1622    #[inline]
1623    pub fn uniform_bytes(&self) -> &[u8] {
1624        self.uniforms.as_bytes()
1625    }
1626}
1627
1628#[inline]
1629fn layout_cap_to_gpu(cap: strata_layout::StrokeLineCap) -> strata_gpu_path::LineCap {
1630    match cap {
1631        strata_layout::StrokeLineCap::Butt => strata_gpu_path::LineCap::Butt,
1632        strata_layout::StrokeLineCap::Round => strata_gpu_path::LineCap::Round,
1633        strata_layout::StrokeLineCap::Square => strata_gpu_path::LineCap::Square,
1634    }
1635}
1636
1637#[inline]
1638fn layout_join_to_gpu(join: strata_layout::StrokeLineJoin) -> strata_gpu_path::LineJoin {
1639    match join {
1640        strata_layout::StrokeLineJoin::Miter => strata_gpu_path::LineJoin::Miter,
1641        strata_layout::StrokeLineJoin::Round => strata_gpu_path::LineJoin::Round,
1642        strata_layout::StrokeLineJoin::Bevel => strata_gpu_path::LineJoin::Bevel,
1643    }
1644}
1645
1646#[inline]
1647fn quad_world_bounds(q: &strata_gpu_path::QuadraticBezier, pad: f32) -> Rect {
1648    let min_x = q.p0.x.min(q.p1.x).min(q.p2.x) - pad;
1649    let max_x = q.p0.x.max(q.p1.x).max(q.p2.x) + pad;
1650    let min_y = q.p0.y.min(q.p1.y).min(q.p2.y) - pad;
1651    let max_y = q.p0.y.max(q.p1.y).max(q.p2.y) + pad;
1652    Rect::new(
1653        min_x,
1654        min_y,
1655        (max_x - min_x).max(1.0),
1656        (max_y - min_y).max(1.0),
1657    )
1658}
1659
1660#[inline]
1661fn subpaths_from_path_verbs(
1662    verbs: &[strata_gpu_path::PathVerb],
1663    ox: f32,
1664    oy: f32,
1665    sx: f32,
1666    sy: f32,
1667    tolerance: f32,
1668) -> Vec<(Vec<strata_gpu_path::QuadraticBezier>, bool)> {
1669    let mut result = Vec::new();
1670    let mut cur_sub = Vec::new();
1671    let mut cur = strata_gpu_path::Point2D::new(ox, oy);
1672    let mut start = cur;
1673
1674    let map_pt = |p: strata_gpu_path::Point2D| {
1675        strata_gpu_path::Point2D::new(ox + p.x * sx, oy + p.y * sy)
1676    };
1677
1678    for &v in verbs {
1679        match v {
1680            strata_gpu_path::PathVerb::MoveTo(p) => {
1681                if !cur_sub.is_empty() {
1682                    result.push((std::mem::take(&mut cur_sub), false));
1683                }
1684                cur = map_pt(p);
1685                start = cur;
1686            }
1687            strata_gpu_path::PathVerb::LineTo(p) => {
1688                let next = map_pt(p);
1689                cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1690                    cur,
1691                    cur.lerp(next, 0.5),
1692                    next,
1693                ));
1694                cur = next;
1695            }
1696            strata_gpu_path::PathVerb::QuadTo(p1, p2) => {
1697                let cp = map_pt(p1);
1698                let next = map_pt(p2);
1699                cur_sub.push(strata_gpu_path::QuadraticBezier::new(cur, cp, next));
1700                cur = next;
1701            }
1702            strata_gpu_path::PathVerb::CubicTo(p1, p2, p3) => {
1703                let cubic =
1704                    strata_gpu_path::CubicBezier::new(cur, map_pt(p1), map_pt(p2), map_pt(p3));
1705                cur_sub.extend(cubic.to_quadratics(tolerance));
1706                cur = map_pt(p3);
1707            }
1708            strata_gpu_path::PathVerb::Close => {
1709                if cur.distance_squared(start) > 1e-4 {
1710                    cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1711                        cur,
1712                        cur.lerp(start, 0.5),
1713                        start,
1714                    ));
1715                    cur = start;
1716                }
1717                if !cur_sub.is_empty() {
1718                    result.push((std::mem::take(&mut cur_sub), true));
1719                }
1720            }
1721        }
1722    }
1723    if !cur_sub.is_empty() {
1724        result.push((cur_sub, false));
1725    }
1726    result
1727}
1728
1729fn circle_to_quads(cx: f32, cy: f32, r: f32) -> Vec<strata_gpu_path::QuadraticBezier> {
1730    let segs = 8usize;
1731    let mut circle_quads = Vec::with_capacity(segs);
1732    for i in 0..segs {
1733        let a0 = (i as f32 / segs as f32) * std::f32::consts::TAU;
1734        let a1 = ((i + 1) as f32 / segs as f32) * std::f32::consts::TAU;
1735        let am = (a0 + a1) * 0.5;
1736        let cos_half = ((a1 - a0) * 0.5).cos().max(0.1);
1737        let p0 = strata_gpu_path::Point2D::new(cx + r * a0.cos(), cy + r * a0.sin());
1738        let p2 = strata_gpu_path::Point2D::new(cx + r * a1.cos(), cy + r * a1.sin());
1739        let p1 = strata_gpu_path::Point2D::new(
1740            cx + (r / cos_half) * am.cos(),
1741            cy + (r / cos_half) * am.sin(),
1742        );
1743        circle_quads.push(strata_gpu_path::QuadraticBezier::new(p0, p1, p2));
1744    }
1745    circle_quads
1746}
1747
1748fn canvas_path_verbs_to_quad_subpaths(
1749    verbs: &[crate::canvas2d::CanvasPathVerb],
1750    ox: f32,
1751    oy: f32,
1752) -> Vec<(Vec<strata_gpu_path::QuadraticBezier>, bool)> {
1753    let mut subpaths: Vec<(Vec<strata_gpu_path::QuadraticBezier>, bool)> = Vec::new();
1754    let mut cur_sub = Vec::new();
1755    let mut start = strata_gpu_path::Point2D::new(ox, oy);
1756    let mut cur = start;
1757    let mut has_current = false;
1758    for v in verbs {
1759        match *v {
1760            crate::canvas2d::CanvasPathVerb::MoveTo(x, y) => {
1761                if !cur_sub.is_empty() {
1762                    subpaths.push((std::mem::take(&mut cur_sub), false));
1763                }
1764                cur = strata_gpu_path::Point2D::new(ox + x, oy + y);
1765                start = cur;
1766                has_current = true;
1767            }
1768            crate::canvas2d::CanvasPathVerb::LineTo(x, y) => {
1769                let next = strata_gpu_path::Point2D::new(ox + x, oy + y);
1770                cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1771                    cur,
1772                    cur.lerp(next, 0.5),
1773                    next,
1774                ));
1775                cur = next;
1776                has_current = true;
1777            }
1778            crate::canvas2d::CanvasPathVerb::QuadraticCurveTo { cpx, cpy, x, y } => {
1779                let cp = strata_gpu_path::Point2D::new(ox + cpx, oy + cpy);
1780                let next = strata_gpu_path::Point2D::new(ox + x, oy + y);
1781                cur_sub.push(strata_gpu_path::QuadraticBezier::new(cur, cp, next));
1782                cur = next;
1783                has_current = true;
1784            }
1785            crate::canvas2d::CanvasPathVerb::BezierCurveTo {
1786                cp1x,
1787                cp1y,
1788                cp2x,
1789                cp2y,
1790                x,
1791                y,
1792            } => {
1793                let cp1 = strata_gpu_path::Point2D::new(ox + cp1x, oy + cp1y);
1794                let cp2 = strata_gpu_path::Point2D::new(ox + cp2x, oy + cp2y);
1795                let next = strata_gpu_path::Point2D::new(ox + x, oy + y);
1796                let cubic = strata_gpu_path::CubicBezier::new(cur, cp1, cp2, next);
1797                cur_sub.extend(cubic.to_quadratics(0.25));
1798                cur = next;
1799                has_current = true;
1800            }
1801            crate::canvas2d::CanvasPathVerb::Arc {
1802                cx,
1803                cy,
1804                radius,
1805                start_angle,
1806                end_angle,
1807                counter_clockwise,
1808            } => {
1809                let acx = ox + cx;
1810                let acy = oy + cy;
1811                let mut sweep = end_angle - start_angle;
1812                if counter_clockwise && sweep > 0.0 {
1813                    sweep -= std::f32::consts::TAU;
1814                } else if !counter_clockwise && sweep < 0.0 {
1815                    sweep += std::f32::consts::TAU;
1816                }
1817                let arc_start = strata_gpu_path::Point2D::new(
1818                    acx + radius * start_angle.cos(),
1819                    acy + radius * start_angle.sin(),
1820                );
1821                if !has_current {
1822                    start = arc_start;
1823                    cur = arc_start;
1824                    has_current = true;
1825                } else if cur.distance_squared(arc_start) > 1e-4 {
1826                    cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1827                        cur,
1828                        cur.lerp(arc_start, 0.5),
1829                        arc_start,
1830                    ));
1831                    cur = arc_start;
1832                }
1833                let steps = ((sweep.abs() / std::f32::consts::FRAC_PI_4).ceil() as usize)
1834                    .clamp(4, 16);
1835                for i in 0..steps {
1836                    let t0 = start_angle + sweep * (i as f32 / steps as f32);
1837                    let t1 = start_angle + sweep * ((i + 1) as f32 / steps as f32);
1838                    let tm = (t0 + t1) * 0.5;
1839                    let cos_h = ((t1 - t0) * 0.5).cos().max(0.1);
1840                    let p0 = strata_gpu_path::Point2D::new(
1841                        acx + radius * t0.cos(),
1842                        acy + radius * t0.sin(),
1843                    );
1844                    let p2 = strata_gpu_path::Point2D::new(
1845                        acx + radius * t1.cos(),
1846                        acy + radius * t1.sin(),
1847                    );
1848                    let p1 = strata_gpu_path::Point2D::new(
1849                        acx + (radius / cos_h) * tm.cos(),
1850                        acy + (radius / cos_h) * tm.sin(),
1851                    );
1852                    cur_sub.push(strata_gpu_path::QuadraticBezier::new(p0, p1, p2));
1853                    cur = p2;
1854                }
1855            }
1856            crate::canvas2d::CanvasPathVerb::Close => {
1857                if has_current && cur.distance_squared(start) > 1e-4 {
1858                    cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1859                        cur,
1860                        cur.lerp(start, 0.5),
1861                        start,
1862                    ));
1863                    cur = start;
1864                }
1865                if !cur_sub.is_empty() {
1866                    subpaths.push((std::mem::take(&mut cur_sub), true));
1867                }
1868            }
1869        }
1870    }
1871    if !cur_sub.is_empty() {
1872        subpaths.push((cur_sub, false));
1873    }
1874    subpaths
1875}
1876
1877fn flatten_quad_subpaths(
1878    subpaths: &[(Vec<strata_gpu_path::QuadraticBezier>, bool)],
1879    steps_per_curve: usize,
1880) -> Vec<Vec<(f32, f32)>> {
1881    let steps = steps_per_curve.max(1);
1882    let mut polys = Vec::with_capacity(subpaths.len());
1883    for (quads, _) in subpaths {
1884        if quads.is_empty() {
1885            continue;
1886        }
1887        let mut pts = Vec::with_capacity(quads.len() * steps + 1);
1888        for (qi, q) in quads.iter().enumerate() {
1889            let a = (q.p0.x - 2.0 * q.p1.x + q.p2.x).hypot(q.p0.y - 2.0 * q.p1.y + q.p2.y);
1890            let seg_steps = if a <= 1e-3 { 1 } else { steps };
1891            let start_step = if qi == 0 { 0 } else { 1 };
1892            for s in start_step..=seg_steps {
1893                let t = s as f32 / seg_steps as f32;
1894                let u = 1.0 - t;
1895                let px = u * u * q.p0.x + 2.0 * u * t * q.p1.x + t * t * q.p2.x;
1896                let py = u * u * q.p0.y + 2.0 * u * t * q.p1.y + t * t * q.p2.y;
1897                pts.push((px, py));
1898            }
1899        }
1900        if pts.len() >= 3 {
1901            polys.push(pts);
1902        }
1903    }
1904    polys
1905}
1906
1907fn poly_layers_bbox(subpaths: &[Vec<(f32, f32)>]) -> Option<Rect> {
1908    let mut min_x = f32::INFINITY;
1909    let mut min_y = f32::INFINITY;
1910    let mut max_x = f32::NEG_INFINITY;
1911    let mut max_y = f32::NEG_INFINITY;
1912    for sub in subpaths {
1913        for &(x, y) in sub {
1914            min_x = min_x.min(x);
1915            min_y = min_y.min(y);
1916            max_x = max_x.max(x);
1917            max_y = max_y.max(y);
1918        }
1919    }
1920    if min_x.is_finite() && min_y.is_finite() && max_x > min_x && max_y > min_y {
1921        Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
1922    } else {
1923        None
1924    }
1925}
1926
1927/// Batch collection of GPU instanced path segments ready for upload to storage/vertex buffers.
1928#[derive(Debug, Default, Clone, PartialEq)]
1929pub struct GpuPathBatch {
1930    pub segments: Vec<strata_gpu_path::GpuPathSegment>,
1931    /// Compiled non-rectangular/stencil clip masks referenced by [`Self::clip_spans`].
1932    pub clip_masks: Vec<GpuClipMask>,
1933    /// Contiguous segment ranges mapped to their active optional stencil clip mask index.
1934    pub clip_spans: Vec<GpuClipSpan>,
1935}
1936
1937impl GpuPathBatch {
1938    pub fn new() -> Self {
1939        Self::default()
1940    }
1941
1942    pub fn with_capacity(capacity: usize) -> Self {
1943        Self {
1944            segments: Vec::with_capacity(capacity),
1945            clip_masks: Vec::new(),
1946            clip_spans: Vec::new(),
1947        }
1948    }
1949
1950    #[inline]
1951    pub fn push(&mut self, segment: strata_gpu_path::GpuPathSegment) {
1952        self.push_with_clip(segment, None);
1953    }
1954
1955    /// Pushes a path segment associated with an optional non-rectangular stencil clip mask index.
1956    #[inline]
1957    pub fn push_with_clip(
1958        &mut self,
1959        segment: strata_gpu_path::GpuPathSegment,
1960        clip_mask: Option<usize>,
1961    ) {
1962        let idx = self.segments.len();
1963        self.segments.push(segment);
1964        if clip_mask.is_some() || !self.clip_spans.is_empty() {
1965            push_clip_span(&mut self.clip_spans, 1, idx, clip_mask);
1966        }
1967    }
1968
1969    #[inline]
1970    pub fn has_stencil_clips(&self) -> bool {
1971        !self.clip_masks.is_empty()
1972    }
1973
1974    /// Returns the stencil clip mask governing `segment_index`, if any.
1975    pub fn clip_mask_for_segment(&self, segment_index: usize) -> Option<&GpuClipMask> {
1976        let span = self
1977            .clip_spans
1978            .iter()
1979            .find(|s| segment_index >= s.start && segment_index < s.end)?;
1980        span.clip_mask.and_then(|id| self.clip_masks.get(id))
1981    }
1982
1983    #[inline]
1984    pub fn clear(&mut self) {
1985        self.segments.clear();
1986        self.clip_masks.clear();
1987        self.clip_spans.clear();
1988    }
1989
1990    #[inline]
1991    pub fn len(&self) -> usize {
1992        self.segments.len()
1993    }
1994
1995    #[inline]
1996    pub fn is_empty(&self) -> bool {
1997        self.segments.is_empty()
1998    }
1999
2000    #[inline]
2001    pub fn as_bytes(&self) -> &[u8] {
2002        strata_gpu_path::GpuPathSegment::slice_to_bytes(&self.segments)
2003    }
2004
2005    fn emit_clipped_segment(
2006        &mut self,
2007        seg: strata_gpu_path::GpuPathSegment,
2008        q_bbox: Rect,
2009        clip: Rect,
2010        clip_polys: &[Vec<Vec<(f32, f32)>>],
2011        clip_mask_id: Option<usize>,
2012    ) {
2013        if q_bbox.intersect(clip).is_none() {
2014            return;
2015        }
2016        let (emit, mask) = if clip_polys.is_empty() {
2017            (true, None)
2018        } else {
2019            match rect_relation_to_clip_polys(q_bbox, clip_polys) {
2020                ClipContainment::Outside => (false, None),
2021                ClipContainment::Inside => (true, None),
2022                ClipContainment::Partial => (true, clip_mask_id),
2023            }
2024        };
2025        if emit {
2026            self.push_with_clip(seg, mask);
2027        }
2028    }
2029
2030    #[allow(clippy::too_many_arguments)]
2031    fn emit_corner_join(
2032        &mut self,
2033        q0: &strata_gpu_path::QuadraticBezier,
2034        q1: &strata_gpu_path::QuadraticBezier,
2035        sw: f32,
2036        c: [f32; 4],
2037        join: strata_gpu_path::LineJoin,
2038        miter_limit: f32,
2039        extra_flags: u32,
2040        clip: Rect,
2041        clip_polys: &[Vec<Vec<(f32, f32)>>],
2042        clip_mask_id: Option<usize>,
2043    ) {
2044        let j = q0.p2;
2045        let raw_t0 = q0.tangent(1.0);
2046        let raw_t0 = if raw_t0.x * raw_t0.x + raw_t0.y * raw_t0.y > 1e-6 {
2047            raw_t0
2048        } else {
2049            strata_gpu_path::Point2D::new(q0.p2.x - q0.p0.x, q0.p2.y - q0.p0.y)
2050        };
2051        let len0 = (raw_t0.x * raw_t0.x + raw_t0.y * raw_t0.y).sqrt();
2052        let raw_t1 = q1.tangent(0.0);
2053        let raw_t1 = if raw_t1.x * raw_t1.x + raw_t1.y * raw_t1.y > 1e-6 {
2054            raw_t1
2055        } else {
2056            strata_gpu_path::Point2D::new(q1.p2.x - q1.p0.x, q1.p2.y - q1.p0.y)
2057        };
2058        let len1 = (raw_t1.x * raw_t1.x + raw_t1.y * raw_t1.y).sqrt();
2059        if len0 <= 1e-5 || len1 <= 1e-5 {
2060            return;
2061        }
2062        let t0 = strata_gpu_path::Point2D::new(raw_t0.x / len0, raw_t0.y / len0);
2063        let t1 = strata_gpu_path::Point2D::new(raw_t1.x / len1, raw_t1.y / len1);
2064        let dot_t = t0.x * t1.x + t0.y * t1.y;
2065        if dot_t > 0.995 {
2066            return;
2067        }
2068
2069        let half_w = sw * 0.5;
2070        let join_bbox = Rect::new(
2071            j.x - half_w * miter_limit.max(1.0) - 2.0,
2072            j.y - half_w * miter_limit.max(1.0) - 2.0,
2073            (half_w * miter_limit.max(1.0) + 2.0) * 2.0,
2074            (half_w * miter_limit.max(1.0) + 2.0) * 2.0,
2075        );
2076
2077        let join_flag_bit = match join {
2078            strata_gpu_path::LineJoin::Miter => 0,
2079            strata_gpu_path::LineJoin::Round => strata_gpu_path::FLAG_JOIN_ROUND,
2080            strata_gpu_path::LineJoin::Bevel => strata_gpu_path::FLAG_JOIN_BEVEL,
2081        };
2082
2083        if join == strata_gpu_path::LineJoin::Round {
2084            let deg = strata_gpu_path::QuadraticBezier::new(j, j, j);
2085            let seg = strata_gpu_path::GpuPathSegment::from_quadratic(
2086                &deg,
2087                sw,
2088                strata_gpu_path::FLAG_STROKE
2089                    | strata_gpu_path::FLAG_CAP_ROUND
2090                    | strata_gpu_path::FLAG_START_OPEN
2091                    | strata_gpu_path::FLAG_END_OPEN
2092                    | join_flag_bit
2093                    | extra_flags,
2094                c,
2095                0.0,
2096            );
2097            self.emit_clipped_segment(seg, join_bbox, clip, clip_polys, clip_mask_id);
2098            return;
2099        }
2100
2101        let cross = t0.x * t1.y - t0.y * t1.x;
2102        if cross.abs() < 1e-4 {
2103            return;
2104        }
2105        let sign = if cross > 0.0 { -1.0 } else { 1.0 };
2106        let n0x = sign * (-t0.y);
2107        let n0y = sign * t0.x;
2108        let n1x = sign * (-t1.y);
2109        let n1y = sign * t1.x;
2110        let a = strata_gpu_path::Point2D::new(j.x + n0x * half_w, j.y + n0y * half_w);
2111        let b = strata_gpu_path::Point2D::new(j.x + n1x * half_w, j.y + n1y * half_w);
2112        if a.distance_squared(b) <= 0.04 {
2113            return;
2114        }
2115
2116        let sum_x = n0x + n1x;
2117        let sum_y = n0y + n1y;
2118        let sum_len = sum_x.hypot(sum_y);
2119        if sum_len <= 1e-5 {
2120            return;
2121        }
2122        let miter_ratio = 2.0 / sum_len;
2123        if join == strata_gpu_path::LineJoin::Miter && miter_ratio <= miter_limit.max(1.0) {
2124            let denom = 1.0 + n0x * n1x + n0y * n1y;
2125            if denom > 1e-4 {
2126                let m_scale = half_w / denom;
2127                let m = strata_gpu_path::Point2D::new(j.x + sum_x * m_scale, j.y + sum_y * m_scale);
2128                let q_a = strata_gpu_path::QuadraticBezier::new(j, a, m);
2129                let q_b = strata_gpu_path::QuadraticBezier::new(j, m, b);
2130                let flags = strata_gpu_path::FLAG_FILL | strata_gpu_path::FLAG_TRIANGLE | extra_flags;
2131                self.emit_clipped_segment(
2132                    strata_gpu_path::GpuPathSegment::from_quadratic(&q_a, sw, flags, c, 0.0),
2133                    quad_world_bounds(&q_a, 2.0),
2134                    clip,
2135                    clip_polys,
2136                    clip_mask_id,
2137                );
2138                self.emit_clipped_segment(
2139                    strata_gpu_path::GpuPathSegment::from_quadratic(&q_b, sw, flags, c, 0.0),
2140                    quad_world_bounds(&q_b, 2.0),
2141                    clip,
2142                    clip_polys,
2143                    clip_mask_id,
2144                );
2145                return;
2146            }
2147        }
2148
2149        let q_bev = strata_gpu_path::QuadraticBezier::new(j, a, b);
2150        let flags = strata_gpu_path::FLAG_FILL
2151            | strata_gpu_path::FLAG_JOIN_BEVEL
2152            | strata_gpu_path::FLAG_TRIANGLE
2153            | extra_flags;
2154        self.emit_clipped_segment(
2155            strata_gpu_path::GpuPathSegment::from_quadratic(&q_bev, sw, flags, c, 0.0),
2156            quad_world_bounds(&q_bev, 2.0),
2157            clip,
2158            clip_polys,
2159            clip_mask_id,
2160        );
2161    }
2162
2163    #[allow(clippy::too_many_arguments)]
2164    fn emit_subpath_strokes(
2165        &mut self,
2166        quads: &[strata_gpu_path::QuadraticBezier],
2167        closed: bool,
2168        sw: f32,
2169        col: Color,
2170        cap: strata_gpu_path::LineCap,
2171        join: strata_gpu_path::LineJoin,
2172        miter_limit: f32,
2173        dash: &[f32],
2174        dash_offset: f32,
2175        extra_flags: u32,
2176        clip_opt: Option<Rect>,
2177        clip_polys: &[Vec<Vec<(f32, f32)>>],
2178        clip_mask_id: Option<usize>,
2179    ) {
2180        let Some(clip) = clip_opt else {
2181            return;
2182        };
2183        if quads.is_empty() {
2184            return;
2185        }
2186        let (cr, cg, cb, ca) = col.to_f32();
2187        let c = [cr, cg, cb, ca];
2188        let pad = sw * 1.5 + 2.0;
2189
2190        let dash_period: f32 = dash.iter().copied().filter(|&d| d >= 0.0 && d.is_finite()).sum();
2191        if dash.iter().any(|&d| d > 0.0) && dash_period > 1e-4 {
2192            for dash_sub in strata_gpu_path::dash_quadratics_with_offset(quads, dash, dash_offset) {
2193                let n = dash_sub.len();
2194                if n == 0 {
2195                    continue;
2196                }
2197                for (i, q) in dash_sub.iter().enumerate() {
2198                    let flags = strata_gpu_path::stroke_style_flags(
2199                        cap,
2200                        join,
2201                        false,
2202                        i == 0,
2203                        i + 1 == n,
2204                    ) | extra_flags;
2205                    let seg = strata_gpu_path::GpuPathSegment::from_quadratic(q, sw, flags, c, 0.0);
2206                    self.emit_clipped_segment(
2207                        seg,
2208                        quad_world_bounds(q, pad),
2209                        clip,
2210                        clip_polys,
2211                        clip_mask_id,
2212                    );
2213                }
2214                for i in 0..n.saturating_sub(1) {
2215                    self.emit_corner_join(
2216                        &dash_sub[i],
2217                        &dash_sub[i + 1],
2218                        sw,
2219                        c,
2220                        join,
2221                        miter_limit,
2222                        extra_flags,
2223                        clip,
2224                        clip_polys,
2225                        clip_mask_id,
2226                    );
2227                }
2228            }
2229            return;
2230        }
2231
2232        // Split into connected runs cleanly in case `quads` holds multiple disconnected subpaths.
2233        let mut run_start = 0usize;
2234        for idx in 1..=quads.len() {
2235            let disconnected = idx == quads.len()
2236                || quads[idx - 1]
2237                    .p2
2238                    .distance_squared(quads[idx].p0)
2239                    > 1e-3;
2240            if disconnected {
2241                let run = &quads[run_start..idx];
2242                let n = run.len();
2243                let is_loop = closed
2244                    && n >= 2
2245                    && run.last().unwrap().p2.distance_squared(run[0].p0) <= 1e-3;
2246                for (i, q) in run.iter().enumerate() {
2247                    let start_open = !is_loop && i == 0;
2248                    let end_open = !is_loop && i + 1 == n;
2249                    let flags = strata_gpu_path::stroke_style_flags(
2250                        cap,
2251                        join,
2252                        is_loop,
2253                        start_open,
2254                        end_open,
2255                    ) | extra_flags;
2256                    let seg = strata_gpu_path::GpuPathSegment::from_quadratic(q, sw, flags, c, 0.0);
2257                    self.emit_clipped_segment(
2258                        seg,
2259                        quad_world_bounds(q, pad),
2260                        clip,
2261                        clip_polys,
2262                        clip_mask_id,
2263                    );
2264                }
2265                for i in 0..n.saturating_sub(1) {
2266                    self.emit_corner_join(
2267                        &run[i],
2268                        &run[i + 1],
2269                        sw,
2270                        c,
2271                        join,
2272                        miter_limit,
2273                        extra_flags,
2274                        clip,
2275                        clip_polys,
2276                        clip_mask_id,
2277                    );
2278                }
2279                if is_loop {
2280                    self.emit_corner_join(
2281                        &run[n - 1],
2282                        &run[0],
2283                        sw,
2284                        c,
2285                        join,
2286                        miter_limit,
2287                        extra_flags,
2288                        clip,
2289                        clip_polys,
2290                        clip_mask_id,
2291                    );
2292                }
2293                run_start = idx;
2294            }
2295        }
2296    }
2297
2298    #[allow(clippy::too_many_arguments)]
2299    fn emit_fill_quads(
2300        &mut self,
2301        quads: &[strata_gpu_path::QuadraticBezier],
2302        sw: f32,
2303        col: Color,
2304        extra_flags: u32,
2305        clip_opt: Option<Rect>,
2306        clip_polys: &[Vec<Vec<(f32, f32)>>],
2307        clip_mask_id: Option<usize>,
2308    ) {
2309        let Some(clip) = clip_opt else {
2310            return;
2311        };
2312        let (cr, cg, cb, ca) = col.to_f32();
2313        let c = [cr, cg, cb, ca];
2314        for q in quads {
2315            let seg = strata_gpu_path::GpuPathSegment::from_quadratic(
2316                q,
2317                sw,
2318                strata_gpu_path::FLAG_FILL | extra_flags,
2319                c,
2320                0.0,
2321            );
2322            self.emit_clipped_segment(seg, quad_world_bounds(q, 2.0), clip, clip_polys, clip_mask_id);
2323        }
2324    }
2325
2326    /// Compiles vector paths from a DisplayList into GPU path segments.
2327    pub fn from_display_list(
2328        list: &DisplayList,
2329        viewport_width: f32,
2330        viewport_height: f32,
2331    ) -> Self {
2332        Self::from_display_list_damaged(list, None, viewport_width, viewport_height)
2333    }
2334
2335    /// Compiles vector paths from a DisplayList into GPU path segments with optional damage scissoring.
2336    pub fn from_display_list_damaged(
2337        list: &DisplayList,
2338        damage: Option<Rect>,
2339        viewport_width: f32,
2340        viewport_height: f32,
2341    ) -> Self {
2342        let mut batch = Self::new();
2343        let mut clip_stack: Vec<Rect> = Vec::new();
2344        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
2345
2346        for cmd in list.commands() {
2347            if let DrawCommand::PushClip { bounds, .. } = cmd {
2348                let combined = match clip_stack.last() {
2349                    Some(prev) => prev.intersect(*bounds).unwrap_or(Rect::zero()),
2350                    None => *bounds,
2351                };
2352                clip_stack.push(combined);
2353                continue;
2354            } else if let DrawCommand::PopClip = cmd {
2355                clip_stack.pop();
2356                continue;
2357            }
2358
2359            let current_clip = match clip_stack.last() {
2360                Some(prev) => match prev.intersect(default_clip) {
2361                    Some(c) => c,
2362                    None => continue,
2363                },
2364                None => default_clip,
2365            };
2366
2367            match cmd {
2368                DrawCommand::DrawGpuPath {
2369                    bounds,
2370                    path,
2371                    stroke,
2372                    fill_color,
2373                    stroke_color,
2374                    transform: _,
2375                } => {
2376                    if bounds.intersect(current_clip).is_none() {
2377                        continue;
2378                    }
2379                    let even_odd = if path.fill_rule == Some(strata_gpu_path::FillRule::EvenOdd) {
2380                        strata_gpu_path::FLAG_EVEN_ODD
2381                    } else {
2382                        0
2383                    };
2384                    let subpaths = subpaths_from_path_verbs(&path.verbs, 0.0, 0.0, 1.0, 1.0, 0.25);
2385                    let stroke_w = stroke.map(|s| s.width).unwrap_or(1.0);
2386                    let cap = stroke.map(|s| s.cap).unwrap_or_default();
2387                    let join = stroke.map(|s| s.join).unwrap_or_default();
2388                    let miter_limit = stroke.map(|s| s.miter_limit).unwrap_or(4.0);
2389
2390                    if let Some(fc) = fill_color {
2391                        for (sub, closed) in &subpaths {
2392                            let closed_flag = if *closed {
2393                                strata_gpu_path::FLAG_CLOSED
2394                            } else {
2395                                0
2396                            };
2397                            batch.emit_fill_quads(
2398                                sub,
2399                                stroke_w,
2400                                *fc,
2401                                even_odd | closed_flag,
2402                                Some(current_clip),
2403                                &[],
2404                                None,
2405                            );
2406                        }
2407                    }
2408
2409                    if let Some(sc) = stroke_color {
2410                        for (sub, closed) in &subpaths {
2411                            batch.emit_subpath_strokes(
2412                                sub,
2413                                *closed,
2414                                stroke_w,
2415                                *sc,
2416                                cap,
2417                                join,
2418                                miter_limit,
2419                                &[],
2420                                0.0,
2421                                even_odd,
2422                                Some(current_clip),
2423                                &[],
2424                                None,
2425                            );
2426                        }
2427                    }
2428                }
2429                DrawCommand::DrawSvgPath {
2430                    bounds,
2431                    path_data,
2432                    stroke_color,
2433                    fill_color,
2434                    stroke_width,
2435                    stroke_linecap,
2436                    stroke_linejoin,
2437                    stroke_dasharray,
2438                    fill_rule,
2439                    view_box,
2440                } => {
2441                    if bounds.intersect(current_clip).is_none() {
2442                        continue;
2443                    }
2444                    let scale_x = if view_box.0 > 0.0 {
2445                        bounds.width / view_box.0
2446                    } else {
2447                        1.0
2448                    };
2449                    let scale_y = if view_box.1 > 0.0 {
2450                        bounds.height / view_box.1
2451                    } else {
2452                        1.0
2453                    };
2454                    let avg_scale = ((scale_x + scale_y) * 0.5).max(0.001);
2455                    let parsed = strata_gpu_path::PathBuilder::from_svg(path_data);
2456                    let subpaths = subpaths_from_path_verbs(
2457                        &parsed.verbs,
2458                        bounds.x,
2459                        bounds.y,
2460                        scale_x,
2461                        scale_y,
2462                        0.25,
2463                    );
2464
2465                    let even_odd = if *fill_rule == strata_layout::FillRule::EvenOdd {
2466                        strata_gpu_path::FLAG_EVEN_ODD
2467                    } else {
2468                        0
2469                    };
2470                    let sw = *stroke_width * avg_scale;
2471                    let cap = layout_cap_to_gpu(*stroke_linecap);
2472                    let join = layout_join_to_gpu(*stroke_linejoin);
2473
2474                    if let Some(fc) = fill_color {
2475                        for (sub, closed) in &subpaths {
2476                            let closed_flag = if *closed {
2477                                strata_gpu_path::FLAG_CLOSED
2478                            } else {
2479                                0
2480                            };
2481                            batch.emit_fill_quads(
2482                                sub,
2483                                sw,
2484                                *fc,
2485                                even_odd | closed_flag,
2486                                Some(current_clip),
2487                                &[],
2488                                None,
2489                            );
2490                        }
2491                    }
2492
2493                    if let Some(sc) = stroke_color {
2494                        let scaled_dashes: Vec<f32> =
2495                            stroke_dasharray.iter().map(|&d| d * avg_scale).collect();
2496                        for (sub, closed) in &subpaths {
2497                            batch.emit_subpath_strokes(
2498                                sub,
2499                                *closed,
2500                                sw,
2501                                *sc,
2502                                cap,
2503                                join,
2504                                4.0,
2505                                &scaled_dashes,
2506                                0.0,
2507                                even_odd,
2508                                Some(current_clip),
2509                                &[],
2510                                None,
2511                            );
2512                        }
2513                    }
2514                }
2515                DrawCommand::DrawCanvas2D { bounds, commands } => {
2516                    let Some(base_clip) = bounds.intersect(current_clip) else {
2517                        continue;
2518                    };
2519                    let ox = bounds.x;
2520                    let oy = bounds.y;
2521                    let mut active_clip = Some(base_clip);
2522                    let mut line_dash: Vec<f32> = Vec::new();
2523                    let mut dash_offset: f32 = 0.0;
2524                    let mut line_cap = strata_gpu_path::LineCap::Butt;
2525                    let mut line_join = strata_gpu_path::LineJoin::Miter;
2526                    let mut clip_polys: Vec<Vec<Vec<(f32, f32)>>> = Vec::new();
2527                    let mut clip_mask_id: Option<usize> = None;
2528                    #[allow(clippy::type_complexity)]
2529                    let mut state_stack: Vec<(
2530                        Option<Rect>,
2531                        Vec<f32>,
2532                        f32,
2533                        strata_gpu_path::LineCap,
2534                        strata_gpu_path::LineJoin,
2535                        Vec<Vec<Vec<(f32, f32)>>>,
2536                        Option<usize>,
2537                    )> = Vec::new();
2538
2539                    let rect_quads = |r: Rect| -> [strata_gpu_path::QuadraticBezier; 4] {
2540                        let p0 = strata_gpu_path::Point2D::new(ox + r.x, oy + r.y);
2541                        let p1 = strata_gpu_path::Point2D::new(ox + r.x + r.width, oy + r.y);
2542                        let p2 =
2543                            strata_gpu_path::Point2D::new(ox + r.x + r.width, oy + r.y + r.height);
2544                        let p3 = strata_gpu_path::Point2D::new(ox + r.x, oy + r.y + r.height);
2545                        [
2546                            strata_gpu_path::QuadraticBezier::new(p0, p0.lerp(p1, 0.5), p1),
2547                            strata_gpu_path::QuadraticBezier::new(p1, p1.lerp(p2, 0.5), p2),
2548                            strata_gpu_path::QuadraticBezier::new(p2, p2.lerp(p3, 0.5), p3),
2549                            strata_gpu_path::QuadraticBezier::new(p3, p3.lerp(p0, 0.5), p0),
2550                        ]
2551                    };
2552
2553                    for ccmd in commands {
2554                        match ccmd {
2555                            crate::canvas2d::CanvasCommand::Save => {
2556                                state_stack.push((
2557                                    active_clip,
2558                                    line_dash.clone(),
2559                                    dash_offset,
2560                                    line_cap,
2561                                    line_join,
2562                                    clip_polys.clone(),
2563                                    clip_mask_id,
2564                                ));
2565                            }
2566                            crate::canvas2d::CanvasCommand::Restore => {
2567                                if let Some((
2568                                    prev_clip,
2569                                    prev_dash,
2570                                    prev_offset,
2571                                    prev_cap,
2572                                    prev_join,
2573                                    prev_polys,
2574                                    prev_mask,
2575                                )) = state_stack.pop()
2576                                {
2577                                    active_clip = prev_clip;
2578                                    line_dash = prev_dash;
2579                                    dash_offset = prev_offset;
2580                                    line_cap = prev_cap;
2581                                    line_join = prev_join;
2582                                    clip_polys = prev_polys;
2583                                    clip_mask_id = prev_mask;
2584                                }
2585                            }
2586                            crate::canvas2d::CanvasCommand::SetLineDash { segments, offset } => {
2587                                line_dash = segments.clone();
2588                                dash_offset = *offset;
2589                            }
2590                            crate::canvas2d::CanvasCommand::SetLineCap(cap) => {
2591                                line_cap = layout_cap_to_gpu(*cap);
2592                            }
2593                            crate::canvas2d::CanvasCommand::SetLineJoin(join) => {
2594                                line_join = layout_join_to_gpu(*join);
2595                            }
2596                            crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
2597                                let subpaths = crate::canvas2d::flatten_canvas_verbs(verbs, ox, oy);
2598                                if !subpaths.is_empty() {
2599                                    if let Some(vbbox) =
2600                                        crate::canvas2d::canvas_verbs_bounds(verbs, ox, oy)
2601                                    {
2602                                        active_clip = active_clip.and_then(|c| c.intersect(vbbox));
2603                                    }
2604                                    if !subpaths_are_axis_aligned_rect(&subpaths) {
2605                                        clip_polys.push(subpaths);
2606                                        clip_mask_id = resolve_or_push_clip_mask(
2607                                            &mut batch.clip_masks,
2608                                            active_clip,
2609                                            &clip_polys,
2610                                        );
2611                                    }
2612                                }
2613                            }
2614                            crate::canvas2d::CanvasCommand::FillRect {
2615                                bounds: rb,
2616                                color,
2617                            } => {
2618                                let world_rect =
2619                                    Rect::new(ox + rb.x, oy + rb.y, rb.width, rb.height);
2620                                if active_clip
2621                                    .and_then(|c| c.intersect(world_rect))
2622                                    .is_some()
2623                                {
2624                                    let quads = rect_quads(*rb);
2625                                    batch.emit_fill_quads(
2626                                        &quads,
2627                                        1.0,
2628                                        *color,
2629                                        strata_gpu_path::FLAG_CLOSED,
2630                                        active_clip,
2631                                        &clip_polys,
2632                                        clip_mask_id,
2633                                    );
2634                                }
2635                            }
2636                            crate::canvas2d::CanvasCommand::StrokeRect {
2637                                bounds: rb,
2638                                color,
2639                                line_width,
2640                            } => {
2641                                let quads = rect_quads(*rb);
2642                                batch.emit_subpath_strokes(
2643                                    &quads,
2644                                    true,
2645                                    *line_width,
2646                                    *color,
2647                                    line_cap,
2648                                    line_join,
2649                                    10.0,
2650                                    &line_dash,
2651                                    dash_offset,
2652                                    0,
2653                                    active_clip,
2654                                    &clip_polys,
2655                                    clip_mask_id,
2656                                );
2657                            }
2658                            crate::canvas2d::CanvasCommand::DrawLine {
2659                                p0,
2660                                p1,
2661                                color,
2662                                line_width,
2663                            } => {
2664                                let a = strata_gpu_path::Point2D::new(ox + p0.0, oy + p0.1);
2665                                let b = strata_gpu_path::Point2D::new(ox + p1.0, oy + p1.1);
2666                                let q = strata_gpu_path::QuadraticBezier::new(a, a.lerp(b, 0.5), b);
2667                                batch.emit_subpath_strokes(
2668                                    &[q],
2669                                    false,
2670                                    *line_width,
2671                                    *color,
2672                                    line_cap,
2673                                    line_join,
2674                                    10.0,
2675                                    &line_dash,
2676                                    dash_offset,
2677                                    0,
2678                                    active_clip,
2679                                    &clip_polys,
2680                                    clip_mask_id,
2681                                );
2682                            }
2683                            crate::canvas2d::CanvasCommand::DrawCircle {
2684                                center,
2685                                radius,
2686                                fill_color,
2687                                stroke_color,
2688                                line_width,
2689                            } => {
2690                                let circle_quads =
2691                                    circle_to_quads(ox + center.0, oy + center.1, *radius);
2692                                if let Some(fc) = fill_color {
2693                                    batch.emit_fill_quads(
2694                                        &circle_quads,
2695                                        *line_width,
2696                                        *fc,
2697                                        strata_gpu_path::FLAG_CLOSED,
2698                                        active_clip,
2699                                        &clip_polys,
2700                                        clip_mask_id,
2701                                    );
2702                                }
2703                                if let Some(sc) = stroke_color {
2704                                    batch.emit_subpath_strokes(
2705                                        &circle_quads,
2706                                        true,
2707                                        *line_width,
2708                                        *sc,
2709                                        line_cap,
2710                                        line_join,
2711                                        10.0,
2712                                        &line_dash,
2713                                        dash_offset,
2714                                        0,
2715                                        active_clip,
2716                                        &clip_polys,
2717                                        clip_mask_id,
2718                                    );
2719                                }
2720                            }
2721                            crate::canvas2d::CanvasCommand::DrawPath {
2722                                verbs,
2723                                fill_color,
2724                                stroke_color,
2725                                line_width,
2726                            } => {
2727                                let subpaths = canvas_path_verbs_to_quad_subpaths(verbs, ox, oy);
2728
2729                                if let Some(fc) = fill_color {
2730                                    for (sub, closed) in &subpaths {
2731                                        let closed_flag = if *closed {
2732                                            strata_gpu_path::FLAG_CLOSED
2733                                        } else {
2734                                            0
2735                                        };
2736                                        batch.emit_fill_quads(
2737                                            sub,
2738                                            *line_width,
2739                                            *fc,
2740                                            closed_flag,
2741                                            active_clip,
2742                                            &clip_polys,
2743                                            clip_mask_id,
2744                                        );
2745                                    }
2746                                }
2747                                if let Some(sc) = stroke_color {
2748                                    for (sub, closed) in &subpaths {
2749                                        batch.emit_subpath_strokes(
2750                                            sub,
2751                                            *closed,
2752                                            *line_width,
2753                                            *sc,
2754                                            line_cap,
2755                                            line_join,
2756                                            10.0,
2757                                            &line_dash,
2758                                            dash_offset,
2759                                            0,
2760                                            active_clip,
2761                                            &clip_polys,
2762                                            clip_mask_id,
2763                                        );
2764                                    }
2765                                }
2766                            }
2767                            crate::canvas2d::CanvasCommand::ClearRect { .. }
2768                            | crate::canvas2d::CanvasCommand::FillText { .. }
2769                            | crate::canvas2d::CanvasCommand::StrokeText { .. } => {}
2770                        }
2771                    }
2772                }
2773                _ => {}
2774            }
2775        }
2776
2777        batch
2778    }
2779}
2780
2781/// High-level orchestration pipeline for compiling vector paths into GPU compute/render buffers.
2782#[derive(Debug, Clone)]
2783pub struct GpuPathPipeline {
2784    pub viewport_width: f32,
2785    pub viewport_height: f32,
2786    pub uniforms: strata_gpu_path::GpuPathUniforms,
2787    pub batch: GpuPathBatch,
2788    pub total_uploaded_bytes: usize,
2789    pub compiled_frames: u64,
2790}
2791
2792impl GpuPathPipeline {
2793    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
2794        Self {
2795            viewport_width,
2796            viewport_height,
2797            uniforms: strata_gpu_path::GpuPathUniforms::new(
2798                viewport_width,
2799                viewport_height,
2800                0.25,
2801                0,
2802            ),
2803            batch: GpuPathBatch::new(),
2804            total_uploaded_bytes: 0,
2805            compiled_frames: 0,
2806        }
2807    }
2808
2809    pub fn resize(&mut self, width: f32, height: f32) {
2810        self.viewport_width = width;
2811        self.viewport_height = height;
2812        self.uniforms =
2813            strata_gpu_path::GpuPathUniforms::new(width, height, 0.25, self.batch.len() as u32);
2814    }
2815
2816    /// Compiles a frame from a DisplayList and optional damage rectangle into the internal path batch buffer.
2817    pub fn compile_frame(&mut self, list: &DisplayList, damage: Option<Rect>) -> usize {
2818        // Most frames contain no vector paths; avoid walking clips and
2819        // rebuilding an empty batch when nothing needs compiling.
2820        let has_paths = list.commands().iter().any(|cmd| {
2821            matches!(
2822                cmd,
2823                DrawCommand::DrawGpuPath { .. }
2824                    | DrawCommand::DrawSvgPath { .. }
2825                    | DrawCommand::DrawCanvas2D { .. }
2826            )
2827        });
2828        if !has_paths {
2829            if !self.batch.is_empty() {
2830                self.batch.clear();
2831                self.uniforms.curve_count = 0;
2832            }
2833            return 0;
2834        }
2835        self.batch = GpuPathBatch::from_display_list_damaged(
2836            list,
2837            damage,
2838            self.viewport_width,
2839            self.viewport_height,
2840        );
2841
2842        self.uniforms.curve_count = self.batch.len() as u32;
2843        let byte_count = self.batch.as_bytes().len() + self.uniforms.as_bytes().len();
2844        self.total_uploaded_bytes += byte_count;
2845        self.compiled_frames += 1;
2846
2847        self.batch.len()
2848    }
2849
2850    #[inline]
2851    pub fn segment_bytes(&self) -> &[u8] {
2852        self.batch.as_bytes()
2853    }
2854
2855    #[inline]
2856    pub fn uniform_bytes(&self) -> &[u8] {
2857        self.uniforms.as_bytes()
2858    }
2859}
2860
2861/// Parsed and compiled WGSL shader module with verified reflection data.
2862#[derive(Debug, Clone, PartialEq)]
2863pub struct GpuShaderModule {
2864    pub source: String,
2865    pub has_vertex_entry: bool,
2866    pub has_fragment_entry: bool,
2867    pub vertex_entry: String,
2868    pub fragment_entry: String,
2869    pub uniforms_declared: Vec<String>,
2870    pub bind_groups_declared: usize,
2871}
2872
2873/// Compiler and validator for WGSL shaders ensuring runtime hardware compatibility.
2874#[derive(Debug, Default, Clone)]
2875pub struct GpuShaderCompiler;
2876
2877impl GpuShaderCompiler {
2878    pub fn new() -> Self {
2879        Self
2880    }
2881
2882    /// Compiles and validates a WGSL source string, returning a `GpuShaderModule` or an error.
2883    pub fn compile(&self, source: &str) -> Result<GpuShaderModule, String> {
2884        let has_vertex_entry = source.contains("@vertex");
2885        let has_fragment_entry = source.contains("@fragment");
2886
2887        if !has_vertex_entry && !has_fragment_entry && !source.contains("@compute") {
2888            return Err(
2889                "WGSL shader missing @vertex, @fragment, or @compute entry point".to_string(),
2890            );
2891        }
2892
2893        let mut vertex_entry = "vs_main".to_string();
2894        let mut fragment_entry = "fs_main".to_string();
2895
2896        for line in source.lines() {
2897            let trimmed = line.trim();
2898            if trimmed.starts_with("fn ") {
2899                let name = trimmed
2900                    .trim_start_matches("fn ")
2901                    .split('(')
2902                    .next()
2903                    .unwrap_or("")
2904                    .trim();
2905                if source.contains(&format!("@vertex\nfn {}", name))
2906                    || source.contains(&format!("@vertex fn {}", name))
2907                {
2908                    vertex_entry = name.to_string();
2909                }
2910                if source.contains(&format!("@fragment\nfn {}", name))
2911                    || source.contains(&format!("@fragment fn {}", name))
2912                {
2913                    fragment_entry = name.to_string();
2914                }
2915            }
2916        }
2917
2918        let mut uniforms = Vec::new();
2919        for line in source.lines() {
2920            if line.contains("var<uniform>") {
2921                if let Some(name) = line.split("var<uniform>").nth(1) {
2922                    let u_name = name.split(':').next().unwrap_or("").trim();
2923                    if !u_name.is_empty() {
2924                        uniforms.push(u_name.to_string());
2925                    }
2926                }
2927            }
2928        }
2929
2930        let bind_groups = source.matches("@group(").count();
2931
2932        Ok(GpuShaderModule {
2933            source: source.to_string(),
2934            has_vertex_entry,
2935            has_fragment_entry,
2936            vertex_entry,
2937            fragment_entry,
2938            uniforms_declared: uniforms,
2939            bind_groups_declared: bind_groups,
2940        })
2941    }
2942}
2943
2944/// Vertex attribute data format.
2945#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2946pub enum GpuVertexFormat {
2947    Float32x2,
2948    Float32x3,
2949    Float32x4,
2950    Uint32x2,
2951    Uint32x4,
2952}
2953
2954impl GpuVertexFormat {
2955    pub const fn byte_size(&self) -> usize {
2956        match self {
2957            Self::Float32x2 | Self::Uint32x2 => 8,
2958            Self::Float32x3 => 12,
2959            Self::Float32x4 | Self::Uint32x4 => 16,
2960        }
2961    }
2962}
2963
2964/// Individual vertex attribute descriptor.
2965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2966pub struct GpuVertexAttribute {
2967    pub format: GpuVertexFormat,
2968    pub offset: u64,
2969    pub shader_location: u32,
2970}
2971
2972/// Step mode for vertex buffer stepping.
2973#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2974pub enum GpuVertexStepMode {
2975    #[default]
2976    Vertex,
2977    Instance,
2978}
2979
2980/// Vertex buffer layout specifying stride and attributes.
2981#[derive(Debug, Clone, PartialEq)]
2982pub struct GpuVertexBufferLayout {
2983    pub array_stride: u64,
2984    pub step_mode: GpuVertexStepMode,
2985    pub attributes: Vec<GpuVertexAttribute>,
2986}
2987
2988/// Primitive topology for rasterization.
2989#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2990pub enum GpuPrimitiveTopology {
2991    PointList,
2992    LineList,
2993    LineStrip,
2994    #[default]
2995    TriangleList,
2996    TriangleStrip,
2997}
2998
2999/// Depth comparison function for early-Z culling and depth bounds testing.
3000#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3001pub enum GpuCompareFunction {
3002    Never,
3003    #[default]
3004    Less,
3005    Equal,
3006    LessEqual,
3007    Greater,
3008    NotEqual,
3009    GreaterEqual,
3010    Always,
3011}
3012
3013/// Depth/stencil state for hardware depth attachment.
3014#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3015pub struct GpuDepthStencilState {
3016    pub format: crate::swapchain::SwapchainFormat,
3017    pub depth_write_enabled: bool,
3018    pub depth_compare: GpuCompareFunction,
3019}
3020
3021impl Default for GpuDepthStencilState {
3022    fn default() -> Self {
3023        Self {
3024            format: crate::swapchain::SwapchainFormat::Depth32Float,
3025            depth_write_enabled: true,
3026            depth_compare: GpuCompareFunction::LessEqual,
3027        }
3028    }
3029}
3030
3031impl GpuDepthStencilState {
3032    /// Evaluates early-Z depth comparison between current depth buffer value and incoming fragment depth.
3033    pub fn passes_test(&self, current_depth: f32, new_depth: f32) -> bool {
3034        match self.depth_compare {
3035            GpuCompareFunction::Never => false,
3036            GpuCompareFunction::Less => new_depth < current_depth,
3037            GpuCompareFunction::Equal => (new_depth - current_depth).abs() < 1e-6,
3038            GpuCompareFunction::LessEqual => new_depth <= current_depth + 1e-6,
3039            GpuCompareFunction::Greater => new_depth > current_depth,
3040            GpuCompareFunction::NotEqual => (new_depth - current_depth).abs() >= 1e-6,
3041            GpuCompareFunction::GreaterEqual => new_depth >= current_depth - 1e-6,
3042            GpuCompareFunction::Always => true,
3043        }
3044    }
3045}
3046
3047/// Hardware-accelerated GPU render pipeline configuration.
3048#[derive(Debug, Clone)]
3049pub struct GpuRenderPipeline {
3050    pub shader_module: GpuShaderModule,
3051    pub vertex_layout: GpuVertexBufferLayout,
3052    pub instance_layout: Option<GpuVertexBufferLayout>,
3053    pub primitive_topology: GpuPrimitiveTopology,
3054    pub depth_stencil: Option<GpuDepthStencilState>,
3055}
3056
3057impl GpuRenderPipeline {
3058    /// Constructs an authentic instanced UI quad render pipeline binding WGSL_ANALYTICAL_QUAD_SHADER.
3059    pub fn new_instanced_quad_pipeline(
3060        viewport_width: f32,
3061        viewport_height: f32,
3062    ) -> Result<Self, String> {
3063        let _ = (viewport_width, viewport_height);
3064        let compiler = GpuShaderCompiler::new();
3065        let shader_module = compiler.compile(WGSL_ANALYTICAL_QUAD_SHADER)?;
3066
3067        let vertex_layout = GpuVertexBufferLayout {
3068            array_stride: 8,
3069            step_mode: GpuVertexStepMode::Vertex,
3070            attributes: vec![GpuVertexAttribute {
3071                format: GpuVertexFormat::Float32x2,
3072                offset: 0,
3073                shader_location: 0,
3074            }],
3075        };
3076
3077        let instance_layout = GpuVertexBufferLayout {
3078            array_stride: 96,
3079            step_mode: GpuVertexStepMode::Instance,
3080            attributes: vec![
3081                GpuVertexAttribute {
3082                    format: GpuVertexFormat::Float32x4,
3083                    offset: 0,
3084                    shader_location: 1,
3085                },
3086                GpuVertexAttribute {
3087                    format: GpuVertexFormat::Float32x4,
3088                    offset: 16,
3089                    shader_location: 2,
3090                },
3091                GpuVertexAttribute {
3092                    format: GpuVertexFormat::Float32x4,
3093                    offset: 32,
3094                    shader_location: 3,
3095                },
3096                GpuVertexAttribute {
3097                    format: GpuVertexFormat::Float32x4,
3098                    offset: 48,
3099                    shader_location: 4,
3100                },
3101                GpuVertexAttribute {
3102                    format: GpuVertexFormat::Float32x4,
3103                    offset: 64,
3104                    shader_location: 5,
3105                },
3106                GpuVertexAttribute {
3107                    format: GpuVertexFormat::Float32x4,
3108                    offset: 80,
3109                    shader_location: 6,
3110                },
3111            ],
3112        };
3113
3114        Ok(Self {
3115            shader_module,
3116            vertex_layout,
3117            instance_layout: Some(instance_layout),
3118            primitive_topology: GpuPrimitiveTopology::TriangleList,
3119            depth_stencil: Some(GpuDepthStencilState {
3120                format: crate::swapchain::SwapchainFormat::Depth32Float,
3121                depth_write_enabled: true,
3122                depth_compare: GpuCompareFunction::LessEqual,
3123            }),
3124        })
3125    }
3126
3127    /// Constructs a hardware stencil clip pipeline binding `WGSL_STENCIL_CLIP_SHADER`.
3128    pub fn new_stencil_clip_pipeline(
3129        viewport_width: f32,
3130        viewport_height: f32,
3131    ) -> Result<Self, String> {
3132        let _ = (viewport_width, viewport_height);
3133        let compiler = GpuShaderCompiler::new();
3134        let shader_module = compiler.compile(WGSL_STENCIL_CLIP_SHADER)?;
3135
3136        let vertex_layout = GpuVertexBufferLayout {
3137            array_stride: GpuClipVertex::BYTE_SIZE as u64,
3138            step_mode: GpuVertexStepMode::Vertex,
3139            attributes: vec![GpuVertexAttribute {
3140                format: GpuVertexFormat::Float32x2,
3141                offset: 0,
3142                shader_location: 0,
3143            }],
3144        };
3145
3146        Ok(Self {
3147            shader_module,
3148            vertex_layout,
3149            instance_layout: None,
3150            primitive_topology: GpuPrimitiveTopology::TriangleList,
3151            depth_stencil: Some(GpuDepthStencilState {
3152                format: crate::swapchain::SwapchainFormat::Depth32Float,
3153                depth_write_enabled: false,
3154                depth_compare: GpuCompareFunction::Always,
3155            }),
3156        })
3157    }
3158
3159    /// Records an instanced draw command onto a command encoder.
3160    pub fn draw_instanced(
3161        &self,
3162        encoder: &mut crate::gpu_context::GpuCommandEncoder,
3163        vertex_count: usize,
3164        instance_count: usize,
3165    ) {
3166        encoder.draw_instanced(vertex_count, instance_count);
3167    }
3168}
3169
3170/// Statistics and primitive breakdown for batched GPU dispatches.
3171#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3172pub struct GpuBatchSummary {
3173    pub total_commands: usize,
3174    pub quad_instances: usize,
3175    pub slug_glyphs: usize,
3176    pub path_segments: usize,
3177    pub total_draw_calls: usize,
3178}
3179
3180/// Instanced UI Draw Call Batch Collector for complex layouts (Goal 07).
3181///
3182/// Batches heterogeneous display lists with 10,000+ commands into <= 5 GPU draw calls.
3183#[derive(Debug, Clone)]
3184pub struct GpuBatchCollector {
3185    pub viewport_width: f32,
3186    pub viewport_height: f32,
3187    pub quad_batch: GpuBatch,
3188    pub text_pipeline: GpuSlugTextPipeline,
3189    pub path_batch: GpuPathBatch,
3190    pub summary: GpuBatchSummary,
3191}
3192
3193impl GpuBatchCollector {
3194    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
3195        Self {
3196            viewport_width,
3197            viewport_height,
3198            quad_batch: GpuBatch::new(),
3199            text_pipeline: GpuSlugTextPipeline::new(),
3200            path_batch: GpuPathBatch::new(),
3201            summary: GpuBatchSummary::default(),
3202        }
3203    }
3204
3205    fn count_span_draw_calls(
3206        total_items: usize,
3207        spans: &[GpuClipSpan],
3208        masks: &[GpuClipMask],
3209    ) -> usize {
3210        if total_items == 0 {
3211            return 0;
3212        }
3213        if spans.is_empty() || masks.is_empty() {
3214            return 1;
3215        }
3216        let mut calls = 0usize;
3217        for span in spans {
3218            if span.end <= span.start {
3219                continue;
3220            }
3221            if let Some(mask_id) = span.clip_mask {
3222                if let Some(mask) = masks.get(mask_id) {
3223                    calls += mask
3224                        .stencil_layers
3225                        .iter()
3226                        .filter(|layer| !layer.is_empty())
3227                        .count();
3228                }
3229            }
3230            calls += 1;
3231        }
3232        calls.max(1)
3233    }
3234
3235    /// Collects and batches all compatible primitives from a DisplayList.
3236    pub fn collect(&mut self, list: &DisplayList, damage: Option<Rect>) -> GpuBatchSummary {
3237        self.quad_batch = GpuBatch::from_display_list_damaged(
3238            list,
3239            damage,
3240            self.viewport_width,
3241            self.viewport_height,
3242        );
3243
3244        let glyph_count = self.text_pipeline.compile_display_list(
3245            list,
3246            self.viewport_width,
3247            self.viewport_height,
3248            damage,
3249        );
3250
3251        self.path_batch = GpuPathBatch::from_display_list_damaged(
3252            list,
3253            damage,
3254            self.viewport_width,
3255            self.viewport_height,
3256        );
3257
3258        let mut draw_calls = 0;
3259        draw_calls += Self::count_span_draw_calls(
3260            self.quad_batch.len(),
3261            &self.quad_batch.clip_spans,
3262            &self.quad_batch.clip_masks,
3263        );
3264        if glyph_count > 0 {
3265            draw_calls += 1;
3266        }
3267        draw_calls += Self::count_span_draw_calls(
3268            self.path_batch.len(),
3269            &self.path_batch.clip_spans,
3270            &self.path_batch.clip_masks,
3271        );
3272
3273        self.summary = GpuBatchSummary {
3274            total_commands: list.len(),
3275            quad_instances: self.quad_batch.len(),
3276            slug_glyphs: glyph_count,
3277            path_segments: self.path_batch.len(),
3278            total_draw_calls: draw_calls,
3279        };
3280
3281        self.summary
3282    }
3283
3284    fn dispatch_masked_spans(
3285        encoder: &mut crate::gpu_context::GpuCommandEncoder,
3286        total_items: usize,
3287        spans: &[GpuClipSpan],
3288        masks: &[GpuClipMask],
3289    ) {
3290        if total_items == 0 {
3291            return;
3292        }
3293        if spans.is_empty() || masks.is_empty() {
3294            encoder.draw_instanced(6, total_items);
3295            return;
3296        }
3297        for span in spans {
3298            let count = span.end.saturating_sub(span.start);
3299            if count == 0 {
3300                continue;
3301            }
3302            if let Some(mask_id) = span.clip_mask {
3303                if let Some(mask) = masks.get(mask_id) {
3304                    for layer in &mask.stencil_layers {
3305                        if !layer.is_empty() {
3306                            encoder.draw_instanced(layer.len(), 1);
3307                        }
3308                    }
3309                }
3310            }
3311            encoder.draw_instanced(6, count);
3312        }
3313    }
3314
3315    /// Dispatches all collected batches onto the GPU device in unified passes.
3316    pub fn dispatch(
3317        &self,
3318        device: &mut crate::gpu_context::GpuDevice,
3319        damage: Option<Rect>,
3320    ) -> Result<GpuBatchSummary, crate::swapchain::PresentError> {
3321        let mut encoder = device.create_command_encoder();
3322        let pass = crate::gpu_context::GpuRenderPassDescriptor {
3323            color_texture_id: device.swapchain_texture.id,
3324            depth_texture_id: Some(device.depth_texture.id),
3325            clear_color: Some([0.0, 0.0, 0.0, 1.0]),
3326            clear_depth: Some(1.0),
3327            scissor_rect: damage,
3328        };
3329        encoder.begin_render_pass(pass);
3330
3331        Self::dispatch_masked_spans(
3332            &mut encoder,
3333            self.quad_batch.len(),
3334            &self.quad_batch.clip_spans,
3335            &self.quad_batch.clip_masks,
3336        );
3337        if self.summary.slug_glyphs > 0 {
3338            encoder.draw_instanced(6, self.summary.slug_glyphs);
3339        }
3340        Self::dispatch_masked_spans(
3341            &mut encoder,
3342            self.path_batch.len(),
3343            &self.path_batch.clip_spans,
3344            &self.path_batch.clip_masks,
3345        );
3346
3347        encoder.end_render_pass();
3348        device.submit(encoder);
3349
3350        Ok(self.summary)
3351    }
3352
3353    /// Updates viewport dimensions for subsequent batch compilations.
3354    pub fn resize(&mut self, viewport_width: f32, viewport_height: f32) {
3355        self.viewport_width = viewport_width;
3356        self.viewport_height = viewport_height;
3357    }
3358
3359    /// Compiles a `DisplayList` into coalesced painter's-order hardware GPU batches
3360    /// (`GpuBatch`, `GpuPathBatch`, `GpuSlugTextPipeline`, `GpuClipMask`s, and `DrawViewport3D` split points),
3361    /// eliminating duplicate `FillRect`/`StrokeRect` emission and triangulating/stencil-filling closed vector shapes.
3362    pub fn collect_hardware_frame(
3363        &mut self,
3364        list: &DisplayList,
3365        damage: Option<Rect>,
3366    ) -> Hardware2DFrame {
3367        self.quad_batch.clear();
3368        self.path_batch.clear();
3369        self.text_pipeline.clear();
3370
3371        let glyph_cache = std::mem::take(&mut self.text_pipeline.glyph_cache);
3372        let text = GpuSlugTextPipeline {
3373            glyph_cache,
3374            buffer: strata_gpu_path::SlugGlyphBuffer::new(),
3375            total_glyphs: 0,
3376            total_curves: 0,
3377        };
3378        let mut frame = Hardware2DFrame {
3379            quads: GpuBatch::with_capacity(list.len()),
3380            paths: GpuPathBatch::new(),
3381            text,
3382            items: Vec::with_capacity(list.len().min(64)),
3383            clip_masks: Vec::new(),
3384            summary: GpuBatchSummary::default(),
3385        };
3386
3387        let viewport_rect = Rect::new(0.0, 0.0, self.viewport_width, self.viewport_height);
3388        let default_clip = damage.unwrap_or(viewport_rect);
3389        let mut builder = HardwareFrameBuilder {
3390            frame: &mut frame,
3391            viewport_rect,
3392            default_clip,
3393            clip_stack: Vec::new(),
3394            poly_clip_stack: Vec::new(),
3395            poly_mask_id: None,
3396            transform_stack: Vec::new(),
3397            opacity_stack: Vec::new(),
3398            cur_alpha: 1.0,
3399        };
3400        builder.compile_list(list);
3401
3402        frame.text.total_curves = frame.text.buffer.curves.len();
3403        let draw_calls = frame.count_draw_calls();
3404        frame.summary = GpuBatchSummary {
3405            total_commands: list.len(),
3406            quad_instances: frame.quads.len(),
3407            slug_glyphs: frame.text.total_glyphs,
3408            path_segments: frame.paths.len(),
3409            total_draw_calls: draw_calls,
3410        };
3411
3412        // Keep legacy collector state in sync without cloning large vector buffers.
3413        self.text_pipeline.glyph_cache = frame.text.glyph_cache.clone();
3414        self.summary = frame.summary;
3415        frame
3416    }
3417}
3418
3419/// Alias matching hardware swapchain batch collection across `strata_render` and `strata_platform`.
3420pub type UnifiedGpuCollector = GpuBatchCollector;
3421
3422/// GPU primitive kind for a coalesced hardware draw call inside [`Hardware2DFrame`].
3423#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3424pub enum HardwareDrawOpKind {
3425    Quads,
3426    Paths,
3427    Text,
3428}
3429
3430/// Contiguous range `[start..end)` of batched GPU instances/segments sharing clip mask and scissor.
3431#[derive(Debug, Clone, Copy, PartialEq)]
3432pub struct HardwareDrawOp {
3433    pub kind: HardwareDrawOpKind,
3434    pub start: usize,
3435    pub end: usize,
3436    pub clip_mask: Option<usize>,
3437    pub scissor_rect: Option<Rect>,
3438}
3439
3440/// Ordered hardware render step preserving exact Z-order across 2D GPU batches and 3D viewports.
3441#[derive(Debug, Clone)]
3442pub enum HardwareRenderItem {
3443    Batch(HardwareDrawOp),
3444    Viewport3D {
3445        bounds: Rect,
3446        scene: std::sync::Arc<crate::scene3d::Scene3D>,
3447    },
3448}
3449
3450/// Complete compiled hardware 2D/3D frame ready for live `wgpu` swapchain or offscreen execution.
3451#[derive(Debug, Clone, Default)]
3452pub struct Hardware2DFrame {
3453    pub quads: GpuBatch,
3454    pub paths: GpuPathBatch,
3455    pub text: GpuSlugTextPipeline,
3456    pub items: Vec<HardwareRenderItem>,
3457    pub clip_masks: Vec<GpuClipMask>,
3458    pub summary: GpuBatchSummary,
3459}
3460
3461impl Hardware2DFrame {
3462    /// Counts hardware draw calls including stencil clip mask passes and batched content spans.
3463    pub fn count_draw_calls(&self) -> usize {
3464        let mut calls = 0usize;
3465        let mut active_mask: Option<usize> = None;
3466        for item in &self.items {
3467            match item {
3468                HardwareRenderItem::Batch(op) => {
3469                    if let Some(mask_id) = op.clip_mask {
3470                        if active_mask != Some(mask_id) {
3471                            if let Some(mask) = self.clip_masks.get(mask_id) {
3472                                calls += mask
3473                                    .stencil_layers
3474                                    .iter()
3475                                    .filter(|l| !l.is_empty())
3476                                    .count();
3477                            }
3478                            active_mask = Some(mask_id);
3479                        }
3480                    }
3481                    calls += 1;
3482                }
3483                HardwareRenderItem::Viewport3D { .. } => {
3484                    calls += 1;
3485                    active_mask = None;
3486                }
3487            }
3488        }
3489        calls
3490    }
3491}
3492
3493struct HardwareFrameBuilder<'a> {
3494    frame: &'a mut Hardware2DFrame,
3495    viewport_rect: Rect,
3496    default_clip: Rect,
3497    clip_stack: Vec<(Rect, bool)>,
3498    poly_clip_stack: Vec<Vec<Vec<(f32, f32)>>>,
3499    poly_mask_id: Option<usize>,
3500    transform_stack: Vec<strata_primitives::geom::Matrix4x4>,
3501    opacity_stack: Vec<f32>,
3502    cur_alpha: f32,
3503}
3504
3505impl<'a> HardwareFrameBuilder<'a> {
3506    #[inline]
3507    fn current_clip(&self) -> Option<Rect> {
3508        match self.clip_stack.last() {
3509            Some((r, _)) => r.intersect(self.default_clip),
3510            None => Some(self.default_clip),
3511        }
3512    }
3513
3514    #[inline]
3515    fn transform_rect(&self, r: Rect) -> Rect {
3516        if let Some(mat) = self.transform_stack.last() {
3517            if !mat.is_identity() {
3518                let (x, y, w, h) = mat.transform_bounds(r.x, r.y, r.width, r.height);
3519                return Rect::new(x, y, w, h);
3520            }
3521        }
3522        r
3523    }
3524
3525    fn transform_subpaths(&self, subs: Vec<Vec<(f32, f32)>>) -> Vec<Vec<(f32, f32)>> {
3526        if let Some(mat) = self.transform_stack.last() {
3527            if !mat.is_identity() {
3528                return subs
3529                    .into_iter()
3530                    .map(|sub| {
3531                        sub.into_iter()
3532                            .map(|(x, y)| mat.transform_point(x, y))
3533                            .collect()
3534                    })
3535                    .collect();
3536            }
3537        }
3538        subs
3539    }
3540
3541    fn record_op(
3542        &mut self,
3543        kind: HardwareDrawOpKind,
3544        start: usize,
3545        end: usize,
3546        clip_mask: Option<usize>,
3547        scissor_rect: Option<Rect>,
3548    ) {
3549        if end <= start {
3550            return;
3551        }
3552        if let Some(HardwareRenderItem::Batch(prev)) = self.frame.items.last_mut() {
3553            if prev.kind == kind
3554                && prev.clip_mask == clip_mask
3555                && prev.scissor_rect == scissor_rect
3556                && prev.end == start
3557            {
3558                prev.end = end;
3559                return;
3560            }
3561        }
3562        self.frame.items.push(HardwareRenderItem::Batch(HardwareDrawOp {
3563            kind,
3564            start,
3565            end,
3566            clip_mask,
3567            scissor_rect,
3568        }));
3569    }
3570
3571    #[inline]
3572    fn scissor_for(&self, clip: Rect) -> Option<Rect> {
3573        if clip == self.viewport_rect {
3574            None
3575        } else {
3576            Some(clip)
3577        }
3578    }
3579
3580    fn push_clipped_quad(
3581        &mut self,
3582        instance: GpuQuadInstance,
3583        rect: Rect,
3584        clip_polys: &[Vec<Vec<(f32, f32)>>],
3585        clip_mask_id: Option<usize>,
3586    ) {
3587        let mask = if clip_polys.is_empty() {
3588            None
3589        } else {
3590            match rect_relation_to_clip_polys(rect, clip_polys) {
3591                ClipContainment::Outside => return,
3592                ClipContainment::Inside => None,
3593                ClipContainment::Partial => clip_mask_id,
3594            }
3595        };
3596        let start = self.frame.quads.len();
3597        self.frame.quads.push_with_clip(instance, mask);
3598        let end = self.frame.quads.len();
3599        self.record_op(HardwareDrawOpKind::Quads, start, end, mask, None);
3600    }
3601
3602    fn emit_stencil_fill(
3603        &mut self,
3604        fill_polys: Vec<Vec<(f32, f32)>>,
3605        fill_color: Color,
3606        active_clip: Rect,
3607        parent_clip_polys: &[Vec<Vec<(f32, f32)>>],
3608    ) {
3609        let Some(poly_bbox) = poly_layers_bbox(&fill_polys) else {
3610            return;
3611        };
3612        let Some(clipped_bbox) = poly_bbox.intersect(active_clip) else {
3613            return;
3614        };
3615        if !parent_clip_polys.is_empty()
3616            && rect_relation_to_clip_polys(clipped_bbox, parent_clip_polys)
3617                == ClipContainment::Outside
3618        {
3619            return;
3620        }
3621        let mut layers = Vec::with_capacity(parent_clip_polys.len() + 1);
3622        layers.extend_from_slice(parent_clip_polys);
3623        layers.push(fill_polys);
3624        let Some(mask_id) =
3625            resolve_or_push_clip_mask(&mut self.frame.clip_masks, Some(clipped_bbox), &layers)
3626        else {
3627            return;
3628        };
3629        let col = apply_color_opacity(fill_color, self.cur_alpha);
3630        let start = self.frame.quads.len();
3631        self.frame
3632            .quads
3633            .push_with_clip(GpuQuadInstance::from_rect(clipped_bbox, col, active_clip), Some(mask_id));
3634        let end = self.frame.quads.len();
3635        self.record_op(HardwareDrawOpKind::Quads, start, end, Some(mask_id), None);
3636    }
3637
3638    #[allow(clippy::too_many_arguments)]
3639    fn emit_paths_with_op(
3640        &mut self,
3641        quads: &[strata_gpu_path::QuadraticBezier],
3642        closed: bool,
3643        sw: f32,
3644        color: Color,
3645        cap: strata_gpu_path::LineCap,
3646        join: strata_gpu_path::LineJoin,
3647        miter_limit: f32,
3648        dashes: &[f32],
3649        dash_offset: f32,
3650        extra_flags: u32,
3651        active_clip: Rect,
3652        clip_polys: &[Vec<Vec<(f32, f32)>>],
3653        clip_mask_id: Option<usize>,
3654    ) {
3655        let start = self.frame.paths.len();
3656        let before_spans = self.frame.paths.clip_spans.len();
3657        let col = apply_color_opacity(color, self.cur_alpha);
3658        self.frame.paths.emit_subpath_strokes(
3659            quads,
3660            closed,
3661            sw,
3662            col,
3663            cap,
3664            join,
3665            miter_limit,
3666            dashes,
3667            dash_offset,
3668            extra_flags,
3669            Some(active_clip),
3670            clip_polys,
3671            clip_mask_id,
3672        );
3673        let end = self.frame.paths.len();
3674        if end <= start {
3675            return;
3676        }
3677        let scissor = self.scissor_for(active_clip);
3678        let spans = &self.frame.paths.clip_spans;
3679        if !spans.is_empty() {
3680            let scan_from = before_spans.saturating_sub(1);
3681            let mut local_ops: Vec<(usize, usize, Option<usize>)> = Vec::new();
3682            for span in &spans[scan_from..] {
3683                if span.end <= start || span.start >= end {
3684                    continue;
3685                }
3686                local_ops.push((span.start.max(start), span.end.min(end), span.clip_mask));
3687            }
3688            for (s0, s1, mask) in local_ops {
3689                self.record_op(HardwareDrawOpKind::Paths, s0, s1, mask, scissor);
3690            }
3691        } else {
3692            self.record_op(HardwareDrawOpKind::Paths, start, end, None, scissor);
3693        }
3694    }
3695
3696    fn emit_text_with_clip(
3697        &mut self,
3698        start: usize,
3699        end: usize,
3700        run_bounds: Rect,
3701        active_clip: Rect,
3702        clip_polys: &[Vec<Vec<(f32, f32)>>],
3703        clip_mask_id: Option<usize>,
3704    ) {
3705        if end <= start {
3706            return;
3707        }
3708        let mask = if clip_polys.is_empty() {
3709            None
3710        } else {
3711            match rect_relation_to_clip_polys(run_bounds, clip_polys) {
3712                ClipContainment::Outside => {
3713                    self.frame.text.buffer.instances.truncate(start);
3714                    self.frame.text.total_glyphs = self.frame.text.buffer.instances.len();
3715                    return;
3716                }
3717                ClipContainment::Inside => None,
3718                ClipContainment::Partial => clip_mask_id,
3719            }
3720        };
3721        let scissor = self.scissor_for(active_clip);
3722        self.record_op(HardwareDrawOpKind::Text, start, end, mask, scissor);
3723    }
3724
3725    fn compile_list(&mut self, list: &DisplayList) {
3726        for cmd in list.commands() {
3727            match cmd {
3728                DrawCommand::PushClip { bounds, radius } => {
3729                    let tb = self.transform_rect(*bounds);
3730                    let combined = match self.clip_stack.last() {
3731                        Some((prev, _)) => prev.intersect(tb).unwrap_or(Rect::zero()),
3732                        None => tb,
3733                    };
3734                    let has_radius = radius.top_left > 0.5
3735                        || radius.top_right > 0.5
3736                        || radius.bottom_right > 0.5
3737                        || radius.bottom_left > 0.5;
3738                    if has_radius && tb.width > 0.0 && tb.height > 0.0 {
3739                        self.poly_clip_stack.push(vec![rounded_rect_subpath(tb, *radius)]);
3740                        self.poly_mask_id = resolve_or_push_clip_mask(
3741                            &mut self.frame.clip_masks,
3742                            combined.intersect(self.default_clip),
3743                            &self.poly_clip_stack,
3744                        );
3745                    }
3746                    self.clip_stack.push((combined, has_radius));
3747                    continue;
3748                }
3749                DrawCommand::PopClip => {
3750                    if let Some((_, had_poly)) = self.clip_stack.pop() {
3751                        if had_poly {
3752                            self.poly_clip_stack.pop();
3753                            let active = self.current_clip();
3754                            self.poly_mask_id = resolve_or_push_clip_mask(
3755                                &mut self.frame.clip_masks,
3756                                active,
3757                                &self.poly_clip_stack,
3758                            );
3759                        }
3760                    }
3761                    continue;
3762                }
3763                DrawCommand::PushTransform { matrix } => {
3764                    let combined = match self.transform_stack.last() {
3765                        Some(prev) => prev.multiply(matrix),
3766                        None => *matrix,
3767                    };
3768                    self.transform_stack.push(combined);
3769                    continue;
3770                }
3771                DrawCommand::PopTransform => {
3772                    self.transform_stack.pop();
3773                    continue;
3774                }
3775                DrawCommand::PushOpacity { alpha } => {
3776                    self.opacity_stack.push(self.cur_alpha);
3777                    self.cur_alpha = (self.cur_alpha * alpha).clamp(0.0, 1.0);
3778                    continue;
3779                }
3780                DrawCommand::PopOpacity => {
3781                    if let Some(prev) = self.opacity_stack.pop() {
3782                        self.cur_alpha = prev;
3783                    }
3784                    continue;
3785                }
3786                DrawCommand::DrawViewport3D { bounds, scene } => {
3787                    if bounds.width > 0.0 && bounds.height > 0.0 {
3788                        self.frame.items.push(HardwareRenderItem::Viewport3D {
3789                            bounds: self.transform_rect(*bounds),
3790                            scene: std::sync::Arc::clone(scene),
3791                        });
3792                    }
3793                    continue;
3794                }
3795                _ => {}
3796            }
3797
3798            let Some(current_clip) = self.current_clip() else {
3799                continue;
3800            };
3801            if let Some(b) = cmd.bounds() {
3802                if self.transform_rect(b).intersect(current_clip).is_none() {
3803                    continue;
3804                }
3805            }
3806
3807            let root_polys = self.poly_clip_stack.clone();
3808            let root_mask = self.poly_mask_id;
3809            match cmd {
3810                DrawCommand::DrawRect { bounds, color } => {
3811                    let tr = self.transform_rect(*bounds);
3812                    let col = apply_color_opacity(*color, self.cur_alpha);
3813                    self.push_clipped_quad(
3814                        GpuQuadInstance::from_rect(tr, col, current_clip),
3815                        tr,
3816                        &root_polys,
3817                        root_mask,
3818                    );
3819                }
3820                DrawCommand::DrawRoundedRect {
3821                    bounds,
3822                    color,
3823                    border_radius,
3824                    border_width,
3825                    border_color,
3826                } => {
3827                    let tr = self.transform_rect(*bounds);
3828                    let col = apply_color_opacity(*color, self.cur_alpha);
3829                    let bcol = border_color.map(|c| apply_color_opacity(c, self.cur_alpha));
3830                    self.push_clipped_quad(
3831                        GpuQuadInstance::from_rounded_rect(
3832                            tr,
3833                            col,
3834                            *border_radius,
3835                            *border_width,
3836                            bcol,
3837                            current_clip,
3838                        ),
3839                        tr,
3840                        &root_polys,
3841                        root_mask,
3842                    );
3843                }
3844                DrawCommand::DrawBorder {
3845                    bounds,
3846                    widths,
3847                    color,
3848                    border_radius,
3849                    ..
3850                } => {
3851                    let tr = self.transform_rect(*bounds);
3852                    let bcol = apply_color_opacity(*color, self.cur_alpha);
3853                    self.push_clipped_quad(
3854                        GpuQuadInstance::from_rounded_rect(
3855                            tr,
3856                            Color::TRANSPARENT,
3857                            *border_radius,
3858                            *widths,
3859                            Some(bcol),
3860                            current_clip,
3861                        ),
3862                        tr,
3863                        &root_polys,
3864                        root_mask,
3865                    );
3866                }
3867                DrawCommand::DrawText {
3868                    origin,
3869                    text,
3870                    font_size,
3871                    color,
3872                    ..
3873                } => {
3874                    let col = apply_color_opacity(*color, self.cur_alpha);
3875                    let start = self.frame.text.buffer.instances.len();
3876                    self.frame.text.push_text_run(
3877                        text,
3878                        origin.0,
3879                        origin.1,
3880                        *font_size,
3881                        1.0,
3882                        col,
3883                        current_clip,
3884                    );
3885                    let end = self.frame.text.buffer.instances.len();
3886                    let run_rect = Rect::new(
3887                        origin.0,
3888                        origin.1,
3889                        (text.len() as f32 * font_size).max(1.0),
3890                        font_size.max(1.0),
3891                    );
3892                    self.emit_text_with_clip(
3893                        start,
3894                        end,
3895                        run_rect,
3896                        current_clip,
3897                        &root_polys,
3898                        root_mask,
3899                    );
3900                }
3901                DrawCommand::DrawTextFragments { fragments } => {
3902                    for frag in fragments {
3903                        let col = apply_color_opacity(frag.style.color, self.cur_alpha);
3904                        let start = self.frame.text.buffer.instances.len();
3905                        self.frame.text.push_text_run(
3906                            &frag.text,
3907                            frag.bounds.x,
3908                            frag.bounds.y,
3909                            frag.style.font_size,
3910                            1.0,
3911                            col,
3912                            current_clip,
3913                        );
3914                        let end = self.frame.text.buffer.instances.len();
3915                        self.emit_text_with_clip(
3916                            start,
3917                            end,
3918                            frag.bounds,
3919                            current_clip,
3920                            &root_polys,
3921                            root_mask,
3922                        );
3923                    }
3924                }
3925                DrawCommand::DrawGpuPath {
3926                    path,
3927                    stroke,
3928                    fill_color,
3929                    stroke_color,
3930                    ..
3931                } => {
3932                    let subpaths = subpaths_from_path_verbs(&path.verbs, 0.0, 0.0, 1.0, 1.0, 0.25);
3933                    if let Some(fc) = fill_color {
3934                        let polys = flatten_quad_subpaths(&subpaths, 6);
3935                        self.emit_stencil_fill(polys, *fc, current_clip, &root_polys);
3936                    }
3937                    if let Some(sc) = stroke_color {
3938                        let sw = stroke.map(|s| s.width).unwrap_or(1.0);
3939                        let cap = stroke.map(|s| s.cap).unwrap_or_default();
3940                        let join = stroke.map(|s| s.join).unwrap_or_default();
3941                        let miter = stroke.map(|s| s.miter_limit).unwrap_or(4.0);
3942                        let even_odd =
3943                            if path.fill_rule == Some(strata_gpu_path::FillRule::EvenOdd) {
3944                                strata_gpu_path::FLAG_EVEN_ODD
3945                            } else {
3946                                0
3947                            };
3948                        for (sub, closed) in &subpaths {
3949                            self.emit_paths_with_op(
3950                                sub,
3951                                *closed,
3952                                sw,
3953                                *sc,
3954                                cap,
3955                                join,
3956                                miter,
3957                                &[],
3958                                0.0,
3959                                even_odd,
3960                                current_clip,
3961                                &root_polys,
3962                                root_mask,
3963                            );
3964                        }
3965                    }
3966                }
3967                DrawCommand::DrawSvgPath {
3968                    bounds,
3969                    path_data,
3970                    stroke_color,
3971                    fill_color,
3972                    stroke_width,
3973                    stroke_linecap,
3974                    stroke_linejoin,
3975                    stroke_dasharray,
3976                    fill_rule,
3977                    view_box,
3978                } => {
3979                    let sx = if view_box.0 > 0.0 {
3980                        bounds.width / view_box.0
3981                    } else {
3982                        1.0
3983                    };
3984                    let sy = if view_box.1 > 0.0 {
3985                        bounds.height / view_box.1
3986                    } else {
3987                        1.0
3988                    };
3989                    let avg_scale = ((sx + sy) * 0.5).max(0.001);
3990                    let parsed = strata_gpu_path::PathBuilder::from_svg(path_data);
3991                    let subpaths = subpaths_from_path_verbs(
3992                        &parsed.verbs,
3993                        bounds.x,
3994                        bounds.y,
3995                        sx,
3996                        sy,
3997                        0.25,
3998                    );
3999                    if let Some(fc) = fill_color {
4000                        let polys = flatten_quad_subpaths(&subpaths, 6);
4001                        self.emit_stencil_fill(polys, *fc, current_clip, &root_polys);
4002                    }
4003                    if let Some(sc) = stroke_color {
4004                        let sw = *stroke_width * avg_scale;
4005                        let cap = layout_cap_to_gpu(*stroke_linecap);
4006                        let join = layout_join_to_gpu(*stroke_linejoin);
4007                        let even_odd = if *fill_rule == strata_layout::FillRule::EvenOdd {
4008                            strata_gpu_path::FLAG_EVEN_ODD
4009                        } else {
4010                            0
4011                        };
4012                        let scaled_dashes: Vec<f32> =
4013                            stroke_dasharray.iter().map(|&d| d * avg_scale).collect();
4014                        for (sub, closed) in &subpaths {
4015                            self.emit_paths_with_op(
4016                                sub,
4017                                *closed,
4018                                sw,
4019                                *sc,
4020                                cap,
4021                                join,
4022                                4.0,
4023                                &scaled_dashes,
4024                                0.0,
4025                                even_odd,
4026                                current_clip,
4027                                &root_polys,
4028                                root_mask,
4029                            );
4030                        }
4031                    }
4032                }
4033                DrawCommand::DrawCanvas2D { bounds, commands } => {
4034                    if let Some(base_clip) = self.transform_rect(*bounds).intersect(current_clip) {
4035                        self.compile_canvas_commands(bounds, commands, base_clip);
4036                    }
4037                }
4038                _ => {}
4039            }
4040        }
4041    }
4042
4043    fn compile_canvas_commands(
4044        &mut self,
4045        bounds: &Rect,
4046        commands: &[crate::canvas2d::CanvasCommand],
4047        base_clip: Rect,
4048    ) {
4049        let ox = bounds.x;
4050        let oy = bounds.y;
4051        let mut active_clip = Some(base_clip);
4052        let mut line_dash: Vec<f32> = Vec::new();
4053        let mut dash_offset: f32 = 0.0;
4054        let mut line_cap = strata_gpu_path::LineCap::Butt;
4055        let mut line_join = strata_gpu_path::LineJoin::Miter;
4056        let mut clip_polys = self.poly_clip_stack.clone();
4057        let mut clip_mask_id = resolve_or_push_clip_mask(
4058            &mut self.frame.clip_masks,
4059            active_clip,
4060            &clip_polys,
4061        );
4062        #[allow(clippy::type_complexity)]
4063        let mut state_stack: Vec<(
4064            Option<Rect>,
4065            Vec<f32>,
4066            f32,
4067            strata_gpu_path::LineCap,
4068            strata_gpu_path::LineJoin,
4069            Vec<Vec<Vec<(f32, f32)>>>,
4070            Option<usize>,
4071        )> = Vec::new();
4072
4073        for ccmd in commands {
4074            match ccmd {
4075                crate::canvas2d::CanvasCommand::Save => {
4076                    state_stack.push((
4077                        active_clip,
4078                        line_dash.clone(),
4079                        dash_offset,
4080                        line_cap,
4081                        line_join,
4082                        clip_polys.clone(),
4083                        clip_mask_id,
4084                    ));
4085                }
4086                crate::canvas2d::CanvasCommand::Restore => {
4087                    if let Some((
4088                        prev_clip,
4089                        prev_dash,
4090                        prev_offset,
4091                        prev_cap,
4092                        prev_join,
4093                        prev_polys,
4094                        prev_mask,
4095                    )) = state_stack.pop()
4096                    {
4097                        active_clip = prev_clip;
4098                        line_dash = prev_dash;
4099                        dash_offset = prev_offset;
4100                        line_cap = prev_cap;
4101                        line_join = prev_join;
4102                        clip_polys = prev_polys;
4103                        clip_mask_id = prev_mask;
4104                    }
4105                }
4106                crate::canvas2d::CanvasCommand::SetLineDash { segments, offset } => {
4107                    line_dash = segments
4108                        .iter()
4109                        .copied()
4110                        .filter(|d| d.is_finite() && *d >= 0.0)
4111                        .collect();
4112                    if line_dash.len() % 2 == 1 {
4113                        let dup = line_dash.clone();
4114                        line_dash.extend(dup);
4115                    }
4116                    dash_offset = if offset.is_finite() { *offset } else { 0.0 };
4117                }
4118                crate::canvas2d::CanvasCommand::SetLineCap(cap) => {
4119                    line_cap = layout_cap_to_gpu(*cap);
4120                }
4121                crate::canvas2d::CanvasCommand::SetLineJoin(join) => {
4122                    line_join = layout_join_to_gpu(*join);
4123                }
4124                crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
4125                    let subpaths = self.transform_subpaths(
4126                        crate::canvas2d::flatten_canvas_verbs(verbs, ox, oy),
4127                    );
4128                    if !subpaths.is_empty() {
4129                        if let Some(tb) = poly_layers_bbox(&subpaths) {
4130                            active_clip = active_clip.and_then(|c| c.intersect(tb));
4131                        }
4132                        if !subpaths_are_axis_aligned_rect(&subpaths) {
4133                            clip_polys.push(subpaths);
4134                            clip_mask_id = resolve_or_push_clip_mask(
4135                                &mut self.frame.clip_masks,
4136                                active_clip,
4137                                &clip_polys,
4138                            );
4139                        }
4140                    }
4141                }
4142                crate::canvas2d::CanvasCommand::FillRect { bounds: rb, color } => {
4143                    let Some(canvas_clip) = active_clip else {
4144                        continue;
4145                    };
4146                    let tr = self.transform_rect(Rect::new(
4147                        ox + rb.x,
4148                        oy + rb.y,
4149                        rb.width,
4150                        rb.height,
4151                    ));
4152                    if tr.intersect(canvas_clip).is_none() {
4153                        continue;
4154                    }
4155                    let col = apply_color_opacity(*color, self.cur_alpha);
4156                    self.push_clipped_quad(
4157                        GpuQuadInstance::from_rect(tr, col, canvas_clip),
4158                        tr,
4159                        &clip_polys,
4160                        clip_mask_id,
4161                    );
4162                }
4163                crate::canvas2d::CanvasCommand::StrokeRect {
4164                    bounds: rb,
4165                    color,
4166                    line_width,
4167                } => {
4168                    let Some(canvas_clip) = active_clip else {
4169                        continue;
4170                    };
4171                    let r = Rect::new(ox + rb.x, oy + rb.y, rb.width, rb.height);
4172                    let period: f32 = line_dash.iter().copied().sum();
4173                    if line_cap == strata_gpu_path::LineCap::Butt
4174                        && line_join == strata_gpu_path::LineJoin::Miter
4175                    {
4176                        if line_dash.is_empty() || period <= 1e-4 {
4177                            let tr = self.transform_rect(r);
4178                            if tr.intersect(canvas_clip).is_some() {
4179                                let col = apply_color_opacity(*color, self.cur_alpha);
4180                                self.push_clipped_quad(
4181                                    GpuQuadInstance::from_rounded_rect(
4182                                        tr,
4183                                        Color::TRANSPARENT,
4184                                        BorderRadius::default(),
4185                                        EdgeInsets::all(*line_width),
4186                                        Some(col),
4187                                        canvas_clip,
4188                                    ),
4189                                    tr,
4190                                    &clip_polys,
4191                                    clip_mask_id,
4192                                );
4193                            }
4194                        } else {
4195                            let col = apply_color_opacity(*color, self.cur_alpha);
4196                            for seg_rect in compute_dashed_stroke_rect_segments(
4197                                r,
4198                                *line_width,
4199                                &line_dash,
4200                                dash_offset,
4201                            ) {
4202                                let t_seg = self.transform_rect(seg_rect);
4203                                if t_seg.intersect(canvas_clip).is_some() {
4204                                    self.push_clipped_quad(
4205                                        GpuQuadInstance::from_rect(t_seg, col, canvas_clip),
4206                                        t_seg,
4207                                        &clip_polys,
4208                                        clip_mask_id,
4209                                    );
4210                                }
4211                            }
4212                        }
4213                    } else {
4214                        let p0 = strata_gpu_path::Point2D::new(r.x, r.y);
4215                        let p1 = strata_gpu_path::Point2D::new(r.x + r.width, r.y);
4216                        let p2 = strata_gpu_path::Point2D::new(r.x + r.width, r.y + r.height);
4217                        let p3 = strata_gpu_path::Point2D::new(r.x, r.y + r.height);
4218                        let rect_quads = [
4219                            strata_gpu_path::QuadraticBezier::new(p0, p0.lerp(p1, 0.5), p1),
4220                            strata_gpu_path::QuadraticBezier::new(p1, p1.lerp(p2, 0.5), p2),
4221                            strata_gpu_path::QuadraticBezier::new(p2, p2.lerp(p3, 0.5), p3),
4222                            strata_gpu_path::QuadraticBezier::new(p3, p3.lerp(p0, 0.5), p0),
4223                        ];
4224                        self.emit_paths_with_op(
4225                            &rect_quads,
4226                            true,
4227                            *line_width,
4228                            *color,
4229                            line_cap,
4230                            line_join,
4231                            10.0,
4232                            &line_dash,
4233                            dash_offset,
4234                            0,
4235                            canvas_clip,
4236                            &clip_polys,
4237                            clip_mask_id,
4238                        );
4239                    }
4240                }
4241                crate::canvas2d::CanvasCommand::DrawLine {
4242                    p0,
4243                    p1,
4244                    color,
4245                    line_width,
4246                } => {
4247                    let Some(canvas_clip) = active_clip else {
4248                        continue;
4249                    };
4250                    let a = strata_gpu_path::Point2D::new(ox + p0.0, oy + p0.1);
4251                    let b = strata_gpu_path::Point2D::new(ox + p1.0, oy + p1.1);
4252                    let q = strata_gpu_path::QuadraticBezier::new(a, a.lerp(b, 0.5), b);
4253                    self.emit_paths_with_op(
4254                        &[q],
4255                        false,
4256                        *line_width,
4257                        *color,
4258                        line_cap,
4259                        line_join,
4260                        10.0,
4261                        &line_dash,
4262                        dash_offset,
4263                        0,
4264                        canvas_clip,
4265                        &clip_polys,
4266                        clip_mask_id,
4267                    );
4268                }
4269                crate::canvas2d::CanvasCommand::DrawCircle {
4270                    center,
4271                    radius,
4272                    fill_color,
4273                    stroke_color,
4274                    line_width,
4275                } => {
4276                    let Some(canvas_clip) = active_clip else {
4277                        continue;
4278                    };
4279                    let circle_quads = circle_to_quads(ox + center.0, oy + center.1, *radius);
4280                    if let Some(fc) = fill_color {
4281                        let polys = flatten_quad_subpaths(&[(circle_quads.clone(), true)], 4);
4282                        self.emit_stencil_fill(polys, *fc, canvas_clip, &clip_polys);
4283                    }
4284                    if let Some(sc) = stroke_color {
4285                        self.emit_paths_with_op(
4286                            &circle_quads,
4287                            true,
4288                            *line_width,
4289                            *sc,
4290                            line_cap,
4291                            line_join,
4292                            10.0,
4293                            &line_dash,
4294                            dash_offset,
4295                            0,
4296                            canvas_clip,
4297                            &clip_polys,
4298                            clip_mask_id,
4299                        );
4300                    }
4301                }
4302                crate::canvas2d::CanvasCommand::DrawPath {
4303                    verbs,
4304                    fill_color,
4305                    stroke_color,
4306                    line_width,
4307                } => {
4308                    let Some(canvas_clip) = active_clip else {
4309                        continue;
4310                    };
4311                    let subpaths = canvas_path_verbs_to_quad_subpaths(verbs, ox, oy);
4312                    if let Some(fc) = fill_color {
4313                        let polys = flatten_quad_subpaths(&subpaths, 6);
4314                        self.emit_stencil_fill(polys, *fc, canvas_clip, &clip_polys);
4315                    }
4316                    if let Some(sc) = stroke_color {
4317                        for (sub, closed) in &subpaths {
4318                            self.emit_paths_with_op(
4319                                sub,
4320                                *closed,
4321                                *line_width,
4322                                *sc,
4323                                line_cap,
4324                                line_join,
4325                                10.0,
4326                                &line_dash,
4327                                dash_offset,
4328                                0,
4329                                canvas_clip,
4330                                &clip_polys,
4331                                clip_mask_id,
4332                            );
4333                        }
4334                    }
4335                }
4336                crate::canvas2d::CanvasCommand::FillText {
4337                    text,
4338                    x,
4339                    y,
4340                    color,
4341                    font_size,
4342                    text_align,
4343                    text_baseline,
4344                    max_width,
4345                    ..
4346                }
4347                | crate::canvas2d::CanvasCommand::StrokeText {
4348                    text,
4349                    x,
4350                    y,
4351                    color,
4352                    font_size,
4353                    text_align,
4354                    text_baseline,
4355                    max_width,
4356                    ..
4357                } => {
4358                    let Some(canvas_clip) = active_clip else {
4359                        continue;
4360                    };
4361                    let col = apply_color_opacity(*color, self.cur_alpha);
4362                    let start = self.frame.text.buffer.instances.len();
4363                    let (_, run_rect) = self.frame.text.push_canvas_text(
4364                        *bounds,
4365                        text,
4366                        *x,
4367                        *y,
4368                        col,
4369                        *font_size,
4370                        *text_align,
4371                        *text_baseline,
4372                        *max_width,
4373                        canvas_clip,
4374                    );
4375                    let end = self.frame.text.buffer.instances.len();
4376                    self.emit_text_with_clip(
4377                        start,
4378                        end,
4379                        run_rect,
4380                        canvas_clip,
4381                        &clip_polys,
4382                        clip_mask_id,
4383                    );
4384                }
4385                crate::canvas2d::CanvasCommand::ClearRect { .. } => {}
4386            }
4387        }
4388    }
4389}
4390
4391#[cfg(feature = "wgpu-backend")]
4392pub use crate::wgpu_2d::{GpuStencilClipPipeline, Wgpu2DRenderer};
4393
4394#[cfg(test)]
4395mod tests {
4396    use super::*;
4397
4398    #[test]
4399    fn test_gpu_quad_memory_layout() {
4400        assert_eq!(GpuQuadInstance::BYTE_SIZE, 96);
4401        assert_eq!(GpuUniforms::BYTE_SIZE, 16);
4402        assert_eq!(QUAD_VERTICES.len(), 6);
4403
4404        let quad = GpuQuadInstance::from_rect(
4405            Rect::new(10.0, 20.0, 100.0, 50.0),
4406            Color::rgb(255, 0, 0),
4407            Rect::new(0.0, 0.0, 1920.0, 1080.0),
4408        );
4409
4410        let bytes = quad.as_bytes();
4411        assert_eq!(bytes.len(), 96);
4412
4413        // Verify bounds at byte offset 0: 10.0, 20.0, 100.0, 50.0
4414        let b0 = f32::from_ne_bytes(bytes[0..4].try_into().unwrap());
4415        let b1 = f32::from_ne_bytes(bytes[4..8].try_into().unwrap());
4416        let b2 = f32::from_ne_bytes(bytes[8..12].try_into().unwrap());
4417        let b3 = f32::from_ne_bytes(bytes[12..16].try_into().unwrap());
4418        assert_eq!(b0, 10.0);
4419        assert_eq!(b1, 20.0);
4420        assert_eq!(b2, 100.0);
4421        assert_eq!(b3, 50.0);
4422    }
4423
4424    #[test]
4425    fn test_gpu_batch_compilation_and_scissoring() {
4426        let mut dl = DisplayList::new();
4427
4428        // 1. Root background (1920x1080)
4429        dl.push(DrawCommand::DrawRect {
4430            bounds: Rect::new(0.0, 0.0, 1920.0, 1080.0),
4431            color: Color::rgb(10, 10, 15),
4432        });
4433
4434        // 2. Button in top-left (20, 20, 120, 36)
4435        dl.push(DrawCommand::DrawRoundedRect {
4436            bounds: Rect::new(20.0, 20.0, 120.0, 36.0),
4437            color: Color::rgb(59, 130, 246),
4438            border_radius: BorderRadius::all(6.0),
4439            border_width: EdgeInsets::ZERO,
4440            border_color: None,
4441        });
4442
4443        // 3. Card in bottom-right (1500, 800, 300, 200)
4444        dl.push(DrawCommand::DrawRect {
4445            bounds: Rect::new(1500.0, 800.0, 300.0, 200.0),
4446            color: Color::rgb(30, 41, 59),
4447        });
4448
4449        // Full compilation
4450        let full_batch = GpuBatch::from_display_list(&dl, 1920.0, 1080.0);
4451        assert_eq!(full_batch.len(), 3);
4452        assert_eq!(full_batch.as_bytes().len(), 3 * 96);
4453
4454        // Damaged compilation targeting only the button in top-left
4455        let damage = Rect::new(10.0, 10.0, 140.0, 60.0);
4456        let damaged_batch = GpuBatch::from_display_list_damaged(&dl, Some(damage), 1920.0, 1080.0);
4457
4458        // Background (intersects damage) and Button (intersects damage) are included.
4459        // Card (at 1500, 800) does not intersect damage and is skipped!
4460        assert_eq!(damaged_batch.len(), 2);
4461    }
4462
4463    #[test]
4464    fn test_presentation_pipeline_compilation() {
4465        let mut pipeline = GpuPresentationPipeline::new(1920.0, 1080.0);
4466
4467        let mut dl = DisplayList::new();
4468        dl.push(DrawCommand::DrawRect {
4469            bounds: Rect::new(50.0, 50.0, 200.0, 100.0),
4470            color: Color::rgb(255, 255, 255),
4471        });
4472
4473        let count = pipeline.compile_frame(&dl, None);
4474        assert_eq!(count, 1);
4475        assert_eq!(pipeline.compiled_frames, 1);
4476        assert_eq!(pipeline.instance_bytes().len(), 96);
4477        assert_eq!(pipeline.uniform_bytes().len(), 16);
4478    }
4479
4480    #[test]
4481    fn test_gpu_path_batch_and_pipeline() {
4482        let mut path_pipeline = GpuPathPipeline::new(1920.0, 1080.0);
4483
4484        let mut dl = DisplayList::new();
4485        // Add DrawGpuPath
4486        let path = strata_gpu_path::PathBuilder::from_svg("M 0 0 L 100 100 Q 150 50 200 0 Z")
4487            .with_fill(strata_gpu_path::FillRule::NonZero);
4488
4489        dl.push(DrawCommand::DrawGpuPath {
4490            bounds: Rect::new(0.0, 0.0, 200.0, 100.0),
4491            path,
4492            stroke: Some(strata_gpu_path::StrokeOptions::new(2.0)),
4493            fill_color: Some(Color::rgb(16, 185, 129)),
4494            stroke_color: Some(Color::rgb(5, 150, 105)),
4495            transform: None,
4496        });
4497
4498        // Add DrawSvgPath
4499        dl.push(DrawCommand::DrawSvgPath {
4500            bounds: Rect::new(300.0, 300.0, 50.0, 50.0),
4501            path_data: "M 0 0 L 50 50 Z".to_string(),
4502            stroke_color: Some(Color::rgb(255, 255, 255)),
4503            fill_color: None,
4504            stroke_width: 1.5,
4505            stroke_linecap: strata_layout::StrokeLineCap::Round,
4506            stroke_linejoin: strata_layout::StrokeLineJoin::Round,
4507            stroke_dasharray: Vec::new(),
4508            fill_rule: strata_layout::FillRule::NonZero,
4509            view_box: (50.0, 50.0),
4510        });
4511
4512        let seg_count = path_pipeline.compile_frame(&dl, None);
4513        assert!(
4514            seg_count >= 4,
4515            "Should emit multiple quadratic segments for path + svg"
4516        );
4517        assert_eq!(path_pipeline.compiled_frames, 1);
4518        assert_eq!(path_pipeline.segment_bytes().len(), seg_count * 64);
4519        assert_eq!(path_pipeline.uniform_bytes().len(), 16);
4520
4521        // Test damage scissoring: scissoring away the second path
4522        let damage = Rect::new(0.0, 0.0, 220.0, 120.0);
4523        let damaged_count = path_pipeline.compile_frame(&dl, Some(damage));
4524        assert!(
4525            damaged_count < seg_count,
4526            "Damaged compilation should skip path outside damage rect"
4527        );
4528    }
4529
4530    #[test]
4531    fn test_gpu_batch_dashed_stroke_rect() {
4532        let mut ctx = crate::canvas2d::Canvas2DContext::new(200.0, 200.0);
4533        ctx.set_stroke_style(Color::rgb(255, 255, 255));
4534        ctx.set_line_width(2.0);
4535        ctx.save();
4536        ctx.set_line_dash(&[10.0, 10.0]);
4537        // 100x40 perimeter = 280 -> should emit multiple dash quads
4538        ctx.stroke_rect(10.0, 10.0, 100.0, 40.0);
4539        ctx.restore();
4540        // After restore, dash is cleared -> single solid bordered StrokeRect quad
4541        ctx.stroke_rect(10.0, 70.0, 100.0, 40.0);
4542
4543        let mut dl = DisplayList::new();
4544        dl.push(DrawCommand::DrawCanvas2D {
4545            bounds: Rect::new(0.0, 0.0, 200.0, 200.0),
4546            commands: ctx.commands().to_vec(),
4547        });
4548
4549        let batch = GpuBatch::from_display_list(&dl, 200.0, 200.0);
4550        // Perimeter 280 with 10 on / 10 off produces 14 dash instances, plus 1 solid instance after restore = 15
4551        assert_eq!(batch.instances.len(), 15);
4552        // Solid last instance carries non-zero border_width
4553        let last = batch.instances.last().unwrap();
4554        assert!(last.border_width[0] > 1.5);
4555        // Dash instances are solid fill rects with border_width == 0
4556        assert_eq!(batch.instances[0].border_width, [0.0; 4]);
4557    }
4558
4559    #[test]
4560    fn test_gpu_path_pipeline_set_line_cap_and_set_line_join() {
4561        let build_corner = |cap: crate::canvas2d::CanvasLineCap, join: crate::canvas2d::CanvasLineJoin| {
4562            let mut ctx = crate::canvas2d::Canvas2DContext::new(200.0, 200.0);
4563            ctx.set_stroke_style(Color::rgb(0, 255, 128));
4564            ctx.set_line_width(10.0);
4565            ctx.save();
4566            ctx.set_line_cap(cap);
4567            ctx.set_line_join(join);
4568            ctx.begin_path();
4569            ctx.move_to(10.0, 30.0);
4570            ctx.line_to(50.0, 30.0);
4571            ctx.line_to(50.0, 70.0);
4572            ctx.stroke();
4573            ctx.restore();
4574            // After restore, caps/joins revert to Butt / Miter
4575            ctx.begin_path();
4576            ctx.move_to(10.0, 100.0);
4577            ctx.line_to(80.0, 100.0);
4578            ctx.stroke();
4579
4580            let mut dl = DisplayList::new();
4581            dl.push(DrawCommand::DrawCanvas2D {
4582                bounds: Rect::new(0.0, 0.0, 200.0, 200.0),
4583                commands: ctx.commands().to_vec(),
4584            });
4585            let mut pipe = GpuPathPipeline::new(200.0, 200.0);
4586            pipe.compile_frame(&dl, None);
4587            pipe.batch.segments
4588        };
4589
4590        let segs_butt_miter =
4591            build_corner(crate::canvas2d::CanvasLineCap::Butt, crate::canvas2d::CanvasLineJoin::Miter);
4592        let segs_round_bevel =
4593            build_corner(crate::canvas2d::CanvasLineCap::Round, crate::canvas2d::CanvasLineJoin::Bevel);
4594        let segs_square_round =
4595            build_corner(crate::canvas2d::CanvasLineCap::Square, crate::canvas2d::CanvasLineJoin::Round);
4596
4597        // Butt vs Round vs Square open cap flags on first segment of the polyline
4598        assert_eq!(segs_butt_miter[0].flags & strata_gpu_path::FLAG_CAP_ROUND, 0);
4599        assert_eq!(segs_butt_miter[0].flags & strata_gpu_path::FLAG_CAP_SQUARE, 0);
4600        assert_ne!(segs_butt_miter[0].flags & strata_gpu_path::FLAG_START_OPEN, 0);
4601
4602        assert_ne!(segs_round_bevel[0].flags & strata_gpu_path::FLAG_CAP_ROUND, 0);
4603        assert_ne!(segs_round_bevel[0].flags & strata_gpu_path::FLAG_JOIN_BEVEL, 0);
4604        assert_ne!(segs_square_round[0].flags & strata_gpu_path::FLAG_CAP_SQUARE, 0);
4605        assert_ne!(segs_square_round[0].flags & strata_gpu_path::FLAG_JOIN_ROUND, 0);
4606
4607        // Miter emits 2 FLAG_TRIANGLE corner wedges reaching apex (55, 25); Bevel emits 1 triangle; Round emits 1 disk
4608        let miter_tris: Vec<_> = segs_butt_miter
4609            .iter()
4610            .filter(|s| (s.flags & strata_gpu_path::FLAG_TRIANGLE) != 0)
4611            .collect();
4612        assert_eq!(miter_tris.len(), 2);
4613        assert!(miter_tris.iter().any(|s| s.p2 == [55.0, 25.0] || s.p1 == [55.0, 25.0]));
4614
4615        let bevel_tris: Vec<_> = segs_round_bevel
4616            .iter()
4617            .filter(|s| (s.flags & strata_gpu_path::FLAG_TRIANGLE) != 0)
4618            .collect();
4619        assert_eq!(bevel_tris.len(), 1);
4620        assert_ne!(bevel_tris[0].flags & strata_gpu_path::FLAG_JOIN_BEVEL, 0);
4621
4622        let round_joins: Vec<_> = segs_square_round
4623            .iter()
4624            .filter(|s| s.p0 == [50.0, 30.0] && s.p2 == [50.0, 30.0])
4625            .collect();
4626        assert_eq!(round_joins.len(), 1);
4627        assert_ne!(round_joins[0].flags & strata_gpu_path::FLAG_CAP_ROUND, 0);
4628
4629        // Restored final line segment must revert to Butt (no Round/Square cap flags)
4630        let last_line_round_ctx = segs_round_bevel.last().unwrap();
4631        assert_eq!(last_line_round_ctx.flags & strata_gpu_path::FLAG_CAP_ROUND, 0);
4632        assert_eq!(last_line_round_ctx.flags & strata_gpu_path::FLAG_CAP_SQUARE, 0);
4633    }
4634
4635    #[test]
4636    fn test_gpu_non_rectangular_clip_path_parity_for_quads_and_paths() {
4637        // 1. Diagonal triangle clip (0,0) -> (100,0) -> (0,100)
4638        // AABB is [0,0,100,100], yet any rect with x+y > 100 lies outside the diagonal clip!
4639        let mut ctx = crate::canvas2d::Canvas2DContext::new(200.0, 200.0);
4640        ctx.save();
4641        ctx.begin_path();
4642        ctx.move_to(0.0, 0.0);
4643        ctx.line_to(100.0, 0.0);
4644        ctx.line_to(0.0, 100.0);
4645        ctx.close_path();
4646        ctx.clip();
4647
4648        // Inside AABB [0..100, 0..100], strictly OUTSIDE diagonal triangle -> must be culled!
4649        ctx.set_fill_style(Color::rgb(255, 0, 0));
4650        ctx.fill_rect(60.0, 60.0, 30.0, 30.0);
4651
4652        // Strictly INSIDE diagonal triangle ((5..25) -> max x+y = 50 < 100) -> no stencil mask needed
4653        ctx.set_fill_style(Color::rgb(0, 255, 0));
4654        ctx.fill_rect(5.0, 5.0, 20.0, 20.0);
4655
4656        // Crosses diagonal boundary -> requires triangulated stencil mask
4657        ctx.set_fill_style(Color::rgb(0, 0, 255));
4658        ctx.fill_rect(0.0, 0.0, 100.0, 100.0);
4659
4660        // Line strictly outside triangle -> culled by GpuPathBatch too
4661        ctx.set_stroke_style(Color::rgb(255, 255, 0));
4662        ctx.set_line_width(2.0);
4663        ctx.begin_path();
4664        ctx.move_to(65.0, 65.0);
4665        ctx.line_to(90.0, 90.0);
4666        ctx.stroke();
4667
4668        // Line inside/crossing triangle -> emitted with clip mask on partial span
4669        ctx.begin_path();
4670        ctx.move_to(10.0, 10.0);
4671        ctx.line_to(80.0, 80.0);
4672        ctx.stroke();
4673        ctx.restore();
4674
4675        // Rectangular clip must NOT allocate stencil masks
4676        ctx.save();
4677        ctx.begin_path();
4678        ctx.rect(110.0, 10.0, 50.0, 50.0);
4679        ctx.clip();
4680        ctx.fill_rect(115.0, 15.0, 20.0, 20.0);
4681        ctx.restore();
4682
4683        // Circular aperture clip
4684        ctx.save();
4685        ctx.begin_path();
4686        ctx.arc(150.0, 150.0, 30.0, 0.0, std::f32::consts::TAU, false);
4687        ctx.clip();
4688        // Corner of circle's AABB [120..180, 120..180] outside radius 30: dist from (150,150) to (122..126) is > 33!
4689        ctx.fill_rect(121.0, 121.0, 4.0, 4.0);
4690        // Crossing circle center
4691        ctx.fill_rect(120.0, 120.0, 60.0, 60.0);
4692        ctx.restore();
4693
4694        let mut dl = DisplayList::new();
4695        dl.push(DrawCommand::DrawCanvas2D {
4696            bounds: Rect::new(0.0, 0.0, 200.0, 200.0),
4697            commands: ctx.commands().to_vec(),
4698        });
4699
4700        let batch = GpuBatch::from_display_list(&dl, 200.0, 200.0);
4701        assert!(batch.has_stencil_clips());
4702        // Red (60,60) and corner-outside-circle (121,121) were culled -> 4 quads remain!
4703        assert_eq!(batch.instances.len(), 4);
4704        // Green (5,5) is strictly inside triangle -> no stencil mask
4705        assert!(batch.clip_mask_for_instance(0).is_none());
4706        // Blue (0,0,100,100) crosses diagonal -> stencil mask has vertices and accurate point test
4707        let diag_mask = batch
4708            .clip_mask_for_instance(1)
4709            .expect("crossing quad should have diagonal stencil clip mask");
4710        assert!(diag_mask.total_stencil_vertices() >= 3);
4711        assert_eq!(diag_mask.total_stencil_vertices() % 3, 0);
4712        assert!(diag_mask.contains_point(20.0, 20.0));
4713        assert!(!diag_mask.contains_point(75.0, 75.0));
4714
4715        // Rect clip (instance 2) must be unmasked after restore()
4716        assert!(batch.clip_mask_for_instance(2).is_none());
4717
4718        // Circular clip (instance 3)
4719        let circle_mask = batch
4720            .clip_mask_for_instance(3)
4721            .expect("circle aperture should bind stencil mask");
4722        assert!(circle_mask.contains_point(150.0, 150.0));
4723        assert!(!circle_mask.contains_point(122.0, 122.0));
4724
4725        // GpuPathBatch also culls outside diagonal & circle clips and compiles stencil shader
4726        let mut collector = GpuBatchCollector::new(200.0, 200.0);
4727        let summary = collector.collect(&dl, None);
4728        assert!(collector.path_batch.has_stencil_clips());
4729        let mut dev = crate::gpu_context::GpuDevice::new(
4730            200,
4731            200,
4732            crate::swapchain::SwapchainFormat::Rgba8Unorm,
4733        );
4734        let dispatched = collector.dispatch(&mut dev, None).expect("dispatch");
4735        assert_eq!(dispatched.total_draw_calls, summary.total_draw_calls);
4736        assert!(GpuRenderPipeline::new_stencil_clip_pipeline(200.0, 200.0).is_ok());
4737    }
4738
4739    #[test]
4740    fn test_unified_gpu_collector_hardware_frame_ordering_and_stencil_masks() {
4741        let mut collector = UnifiedGpuCollector::new(240.0, 240.0);
4742
4743        let mut canvas = crate::canvas2d::Canvas2DContext::new(240.0, 240.0);
4744        canvas.set_fill_style(Color::rgb(20, 40, 80));
4745        canvas.fill_rect(0.0, 0.0, 240.0, 240.0);
4746        canvas.save();
4747        canvas.set_stroke_style(Color::rgb(255, 200, 0));
4748        canvas.set_line_width(6.0);
4749        canvas.set_line_cap(crate::canvas2d::CanvasLineCap::Round);
4750        canvas.set_line_join(crate::canvas2d::CanvasLineJoin::Bevel);
4751        canvas.begin_path();
4752        canvas.move_to(20.0, 40.0);
4753        canvas.line_to(100.0, 40.0);
4754        canvas.line_to(100.0, 120.0);
4755        canvas.stroke();
4756        canvas.restore();
4757        canvas.set_fill_style(Color::rgb(12, 12, 16));
4758        canvas.fill_rect(60.0, 30.0, 60.0, 24.0);
4759        canvas.set_fill_style(Color::WHITE);
4760        canvas.fill_text("A", 70.0, 46.0);
4761
4762        let scene = crate::scene3d::Scene3D::new();
4763        let mut dl = DisplayList::new();
4764        dl.push(DrawCommand::DrawRect {
4765            bounds: Rect::new(0.0, 0.0, 240.0, 240.0),
4766            color: Color::rgb(10, 12, 18),
4767        });
4768        dl.push(DrawCommand::DrawViewport3D {
4769            bounds: Rect::new(120.0, 20.0, 100.0, 100.0),
4770            scene: std::sync::Arc::new(scene),
4771        });
4772        dl.push(DrawCommand::DrawCanvas2D {
4773            bounds: Rect::new(0.0, 0.0, 240.0, 240.0),
4774            commands: canvas.commands().to_vec(),
4775        });
4776
4777        let frame = collector.collect_hardware_frame(&dl, None);
4778        // Order: bg DrawRect (Quads) -> Viewport3D -> FillRect (Quads) -> Path stroke (Paths) -> badge FillRect (Quads) -> FillText (Text)
4779        assert!(frame.items.len() >= 6);
4780        assert!(matches!(
4781            frame.items[0],
4782            HardwareRenderItem::Batch(HardwareDrawOp {
4783                kind: HardwareDrawOpKind::Quads,
4784                ..
4785            })
4786        ));
4787        assert!(matches!(
4788            frame.items[1],
4789            HardwareRenderItem::Viewport3D { .. }
4790        ));
4791        // Capped path stroke is preserved strictly between FillRect #1 and badge FillRect #2!
4792        let path_pos = frame
4793            .items
4794            .iter()
4795            .position(|it| {
4796                matches!(
4797                    it,
4798                    HardwareRenderItem::Batch(HardwareDrawOp {
4799                        kind: HardwareDrawOpKind::Paths,
4800                        ..
4801                    })
4802                )
4803            })
4804            .expect("path stroke op");
4805        let text_pos = frame
4806            .items
4807            .iter()
4808            .position(|it| {
4809                matches!(
4810                    it,
4811                    HardwareRenderItem::Batch(HardwareDrawOp {
4812                        kind: HardwareDrawOpKind::Text,
4813                        ..
4814                    })
4815                )
4816            })
4817            .expect("slug text op");
4818        assert!(path_pos < text_pos);
4819        // Canvas FillRect must NOT emit duplicate segments in paths batch
4820        assert!(!frame.paths.segments.is_empty());
4821        assert_eq!(
4822            frame.quads.len(),
4823            3,
4824            "bg rect + canvas FillRect + badge FillRect"
4825        );
4826    }
4827
4828    #[cfg(feature = "wgpu-backend")]
4829    #[test]
4830    fn test_wgpu_2d_renderer_stencil_clip_dashed_stroke_caps_joins_and_slug_pixels() {
4831        let instance = wgpu::Instance::default();
4832        let Ok((_adapter, device, queue)) = crate::gpu_wgpu::request_working_adapter_and_device(
4833            &instance,
4834            None,
4835            "strata_render_2d_test_device",
4836        ) else {
4837            return;
4838        };
4839
4840        let mut renderer = Wgpu2DRenderer::from_device(
4841            std::sync::Arc::new(device),
4842            std::sync::Arc::new(queue),
4843            wgpu::TextureFormat::Rgba8Unorm,
4844        );
4845        let mut collector = UnifiedGpuCollector::new(240.0, 240.0);
4846
4847        let mut ctx = crate::canvas2d::Canvas2DContext::new(240.0, 240.0);
4848        // 1. Diagonal triangle clip (0,0)-(100,0)-(0,100) + crossing blue FillRect
4849        ctx.save();
4850        ctx.begin_path();
4851        ctx.move_to(0.0, 0.0);
4852        ctx.line_to(100.0, 0.0);
4853        ctx.line_to(0.0, 100.0);
4854        ctx.close_path();
4855        ctx.clip();
4856        ctx.set_fill_style(Color::rgb(0, 120, 255));
4857        ctx.fill_rect(0.0, 0.0, 100.0, 100.0);
4858        ctx.restore();
4859
4860        // 2. Circular clip aperture at (170, 55), radius 30 + full AABB green FillRect
4861        ctx.save();
4862        ctx.begin_path();
4863        ctx.arc(170.0, 55.0, 30.0, 0.0, std::f32::consts::TAU, false);
4864        ctx.clip();
4865        ctx.set_fill_style(Color::rgb(0, 220, 80));
4866        ctx.fill_rect(140.0, 25.0, 60.0, 60.0);
4867        ctx.restore();
4868
4869        // 3. Dashed StrokeRect [12, 12] from x=20..120 at y=140, width=4 (dash on [20..32], gap on [36..42])
4870        ctx.save();
4871        ctx.set_stroke_style(Color::rgb(255, 60, 60));
4872        ctx.set_line_width(4.0);
4873        ctx.set_line_dash(&[12.0, 12.0]);
4874        ctx.stroke_rect(20.0, 140.0, 100.0, 30.0);
4875        ctx.restore();
4876
4877        // 4. Straight horizontal+vertical stroke with Round cap + Miter join
4878        ctx.save();
4879        ctx.set_stroke_style(Color::rgb(255, 220, 0));
4880        ctx.set_line_width(10.0);
4881        ctx.set_line_cap(crate::canvas2d::CanvasLineCap::Round);
4882        ctx.set_line_join(crate::canvas2d::CanvasLineJoin::Miter);
4883        ctx.begin_path();
4884        ctx.move_to(150.0, 150.0);
4885        ctx.line_to(200.0, 150.0);
4886        ctx.line_to(200.0, 200.0);
4887        ctx.stroke();
4888        ctx.restore();
4889
4890        // 5. Slug glyph "H" rendered in bright cyan
4891        let mut dl = DisplayList::new();
4892        dl.push(DrawCommand::DrawCanvas2D {
4893            bounds: Rect::new(0.0, 0.0, 240.0, 240.0),
4894            commands: ctx.commands().to_vec(),
4895        });
4896        dl.push(DrawCommand::DrawText {
4897            origin: (20.0, 195.0),
4898            bounds_width: None,
4899            bounds_height: None,
4900            text_align: strata_style::TextAlign::Left,
4901            text: "H".to_string(),
4902            font_size: 24.0,
4903            line_height: 1.2,
4904            font_weight: strata_style::FontWeight::Bold,
4905            color: Color::rgb(0, 240, 240),
4906            is_monospace: false,
4907            font_family: strata_primitives::atom::AtomId::NULL,
4908        });
4909
4910        let (summary, pixels) = renderer
4911            .render_display_list_offscreen(
4912                &mut collector,
4913                &dl,
4914                240,
4915                240,
4916                1.0,
4917                [0.0, 0.0, 0.0, 1.0],
4918                None,
4919                true,
4920            )
4921            .expect("wgpu 2D offscreen render");
4922        assert!(summary.quad_instances >= 10);
4923        assert!(summary.path_segments > 0);
4924        assert!(summary.slug_glyphs > 0);
4925
4926        let px = |x: usize, y: usize| -> [u8; 4] {
4927            let idx = (y * 240 + x) * 4;
4928            [pixels[idx], pixels[idx + 1], pixels[idx + 2], pixels[idx + 3]]
4929        };
4930
4931        // Diagonal triangle clip: (20,20) inside (blue), (75,75) inside AABB but outside diagonal (black!)
4932        let diag_in = px(20, 20);
4933        assert!(
4934            diag_in[2] > 200 && diag_in[0] < 20,
4935            "inside diagonal clip should be blue: {:?}",
4936            diag_in
4937        );
4938        let diag_out = px(75, 75);
4939        assert_eq!(
4940            diag_out,
4941            [0, 0, 0, 255],
4942            "outside diagonal clip must remain cleared background via stencil"
4943        );
4944
4945        // Circular clip: (170,55) inside (green), (143,28) in circle AABB corner outside radius 30 (black!)
4946        let circ_in = px(170, 55);
4947        assert!(
4948            circ_in[1] > 180 && circ_in[0] < 20,
4949            "inside circular clip should be green: {:?}",
4950            circ_in
4951        );
4952        let circ_corner = px(143, 28);
4953        assert_eq!(
4954            circ_corner,
4955            [0, 0, 0, 255],
4956            "outside circular clip must remain black via stencil"
4957        );
4958
4959        // Dashed StrokeRect: dash on [20..32] at (25, 140) is red; gap [32..44] at (38, 140) is black
4960        let dash_on = px(25, 140);
4961        assert!(
4962            dash_on[0] > 200 && dash_on[1] < 80,
4963            "dash segment should be red: {:?}",
4964            dash_on
4965        );
4966        assert_eq!(px(38, 140), [0, 0, 0, 255], "dash gap must stay background");
4967
4968        // Round cap + Miter join stroke: midpoint (175, 150) & miter apex (203, 147) & round cap tail (147, 150)
4969        assert!(
4970            px(175, 150)[0] > 200 && px(175, 150)[1] > 180,
4971            "straight segment midpoint must be filled"
4972        );
4973        assert!(
4974            px(147, 150)[0] > 150,
4975            "Round cap extends past x=150: {:?}",
4976            px(147, 150)
4977        );
4978        assert!(
4979            px(203, 147)[0] > 150,
4980            "Miter outer corner reaches outside corner apex: {:?}",
4981            px(203, 147)
4982        );
4983
4984        // Slug glyph "H" should light up at least one cyan pixel inside [20..44, 195..220]
4985        let mut lit_glyph = false;
4986        for y in 195..220 {
4987            for x in 20..44 {
4988                let p = px(x, y);
4989                if p[1] > 150 && p[2] > 150 {
4990                    lit_glyph = true;
4991                    break;
4992                }
4993            }
4994        }
4995        assert!(lit_glyph, "Slug font shader should rasterize visible glyph pixels");
4996    }
4997}