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    return vec4<f32>(in.color.rgb, in.color.a * coverage);
112}
113"#;
114
115/// 2D Vertex coordinates for rendering unit instanced quads.
116#[repr(C)]
117#[derive(Debug, Clone, Copy, PartialEq)]
118pub struct GpuVertex {
119    pub position: [f32; 2],
120}
121
122impl GpuVertex {
123    pub const fn new(x: f32, y: f32) -> Self {
124        Self { position: [x, y] }
125    }
126}
127
128/// Six vertices composing two triangles for a unit rectangle [0, 0] to [1, 1].
129pub const QUAD_VERTICES: [GpuVertex; 6] = [
130    GpuVertex::new(0.0, 0.0),
131    GpuVertex::new(1.0, 0.0),
132    GpuVertex::new(0.0, 1.0),
133    GpuVertex::new(0.0, 1.0),
134    GpuVertex::new(1.0, 0.0),
135    GpuVertex::new(1.0, 1.0),
136];
137
138/// Exact 96-byte GPU memory instance representation for an instanced quad or rounded rectangle.
139#[repr(C)]
140#[derive(Debug, Clone, Copy, PartialEq)]
141pub struct GpuQuadInstance {
142    pub bounds: [f32; 4],        // [x, y, width, height]
143    pub color: [f32; 4],         // [r, g, b, a]
144    pub border_radius: [f32; 4], // [top_left, top_right, bottom_right, bottom_left]
145    pub border_width: [f32; 4],  // [top, right, bottom, left]
146    pub border_color: [f32; 4],  // [r, g, b, a]
147    pub clip_rect: [f32; 4],     // [clip_x, clip_y, clip_w, clip_h]
148}
149
150impl GpuQuadInstance {
151    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
152
153    /// Constructs a simple solid colored quad instance.
154    pub fn from_rect(bounds: Rect, color: Color, clip: Rect) -> Self {
155        let (r, g, b, a) = color.to_f32();
156        Self {
157            bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
158            color: [r, g, b, a],
159            border_radius: [0.0; 4],
160            border_width: [0.0; 4],
161            border_color: [0.0; 4],
162            clip_rect: [clip.x, clip.y, clip.width, clip.height],
163        }
164    }
165
166    /// Constructs a rounded rectangle with border widths and border colors.
167    pub fn from_rounded_rect(
168        bounds: Rect,
169        color: Color,
170        radius: BorderRadius,
171        widths: EdgeInsets<f32>,
172        border_color: Option<Color>,
173        clip: Rect,
174    ) -> Self {
175        let (r, g, b, a) = color.to_f32();
176        let (br, bg, bb, ba) = border_color
177            .map(|c| c.to_f32())
178            .unwrap_or((0.0, 0.0, 0.0, 0.0));
179
180        Self {
181            bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
182            color: [r, g, b, a],
183            border_radius: [
184                radius.top_left,
185                radius.top_right,
186                radius.bottom_right,
187                radius.bottom_left,
188            ],
189            border_width: [widths.top, widths.right, widths.bottom, widths.left],
190            border_color: [br, bg, bb, ba],
191            clip_rect: [clip.x, clip.y, clip.width, clip.height],
192        }
193    }
194
195    /// Safe zero-copy byte slice view of this quad instance.
196    #[inline]
197    pub fn as_bytes(&self) -> &[u8] {
198        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
199    }
200
201    /// Safe zero-copy byte slice view of a contiguous slice of quad instances.
202    #[inline]
203    pub fn slice_to_bytes(slice: &[Self]) -> &[u8] {
204        unsafe {
205            std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * Self::BYTE_SIZE)
206        }
207    }
208}
209
210/// 16-byte aligned Uniform Buffer object for viewport projection.
211#[repr(C)]
212#[derive(Debug, Clone, Copy, PartialEq)]
213pub struct GpuUniforms {
214    pub viewport_size: [f32; 2],
215    pub _padding: [f32; 2],
216}
217
218impl GpuUniforms {
219    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
220
221    pub fn new(width: f32, height: f32) -> Self {
222        Self {
223            viewport_size: [width, height],
224            _padding: [0.0, 0.0],
225        }
226    }
227
228    #[inline]
229    pub fn as_bytes(&self) -> &[u8] {
230        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
231    }
232}
233
234/// Batch collection of GPU instanced quads ready for upload to GPU buffers.
235#[derive(Debug, Default, Clone, PartialEq)]
236pub struct GpuBatch {
237    pub instances: Vec<GpuQuadInstance>,
238}
239
240impl GpuBatch {
241    pub fn new() -> Self {
242        Self::default()
243    }
244
245    pub fn with_capacity(capacity: usize) -> Self {
246        Self {
247            instances: Vec::with_capacity(capacity),
248        }
249    }
250
251    #[inline]
252    pub fn push(&mut self, instance: GpuQuadInstance) {
253        self.instances.push(instance);
254    }
255
256    #[inline]
257    pub fn clear(&mut self) {
258        self.instances.clear();
259    }
260
261    #[inline]
262    pub fn len(&self) -> usize {
263        self.instances.len()
264    }
265
266    #[inline]
267    pub fn is_empty(&self) -> bool {
268        self.instances.is_empty()
269    }
270
271    #[inline]
272    pub fn as_bytes(&self) -> &[u8] {
273        GpuQuadInstance::slice_to_bytes(&self.instances)
274    }
275
276    /// Compiles a DisplayList into GPU quad instances for the given viewport.
277    pub fn from_display_list(
278        list: &DisplayList,
279        viewport_width: f32,
280        viewport_height: f32,
281    ) -> Self {
282        Self::from_display_list_damaged(list, None, viewport_width, viewport_height)
283    }
284
285    /// Compiles a DisplayList into GPU quad instances, scissoring to the optional damage rectangle.
286    pub fn from_display_list_damaged(
287        list: &DisplayList,
288        damage: Option<Rect>,
289        viewport_width: f32,
290        viewport_height: f32,
291    ) -> Self {
292        let mut batch = Self::with_capacity(list.len());
293        let mut clip_stack: Vec<Rect> = Vec::new();
294        let mut transform_stack: Vec<strata_primitives::geom::Matrix4x4> = Vec::new();
295        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
296
297        for cmd in list.commands() {
298            if let DrawCommand::PushClip { bounds, .. } = cmd {
299                let combined = match clip_stack.last() {
300                    Some(prev) => prev.intersect(*bounds).unwrap_or(Rect::zero()),
301                    None => *bounds,
302                };
303                clip_stack.push(combined);
304                continue;
305            } else if let DrawCommand::PopClip = cmd {
306                clip_stack.pop();
307                continue;
308            } else if let DrawCommand::PushTransform { matrix } = cmd {
309                let combined = match transform_stack.last() {
310                    Some(prev) => prev.multiply(matrix),
311                    None => *matrix,
312                };
313                transform_stack.push(combined);
314                continue;
315            } else if let DrawCommand::PopTransform = cmd {
316                transform_stack.pop();
317                continue;
318            }
319
320            let current_clip = match clip_stack.last() {
321                Some(prev) => match prev.intersect(default_clip) {
322                    Some(c) => c,
323                    None => continue, // Clipped away completely
324                },
325                None => default_clip,
326            };
327
328            let active_matrix = transform_stack.last();
329            let transform_rect_fn = |r: Rect| -> Rect {
330                if let Some(mat) = active_matrix {
331                    if !mat.is_identity() {
332                        let (x, y, w, h) = mat.transform_bounds(r.x, r.y, r.width, r.height);
333                        return Rect::new(x, y, w, h);
334                    }
335                }
336                r
337            };
338
339            // Fast AABB intersection check
340            let transformed_bounds = cmd.bounds().map(transform_rect_fn);
341            if let Some(cmd_bounds) = transformed_bounds {
342                if cmd_bounds.intersect(current_clip).is_none() {
343                    continue;
344                }
345            }
346
347            match cmd {
348                DrawCommand::DrawRect { bounds, color } => {
349                    batch.push(GpuQuadInstance::from_rect(
350                        transform_rect_fn(*bounds),
351                        *color,
352                        current_clip,
353                    ));
354                }
355                DrawCommand::DrawRoundedRect {
356                    bounds,
357                    color,
358                    border_radius,
359                    border_width,
360                    border_color,
361                } => {
362                    batch.push(GpuQuadInstance::from_rounded_rect(
363                        transform_rect_fn(*bounds),
364                        *color,
365                        *border_radius,
366                        *border_width,
367                        *border_color,
368                        current_clip,
369                    ));
370                }
371                DrawCommand::DrawBorder {
372                    bounds,
373                    widths,
374                    color,
375                    border_radius,
376                    ..
377                } => {
378                    batch.push(GpuQuadInstance::from_rounded_rect(
379                        transform_rect_fn(*bounds),
380                        Color::TRANSPARENT,
381                        *border_radius,
382                        *widths,
383                        Some(*color),
384                        current_clip,
385                    ));
386                }
387                DrawCommand::DrawCanvas2D { bounds, commands } => {
388                    if let Some(canvas_clip) = transform_rect_fn(*bounds).intersect(current_clip) {
389                        for ccmd in commands {
390                            match ccmd {
391                                crate::canvas2d::CanvasCommand::FillRect {
392                                    bounds: rb,
393                                    color,
394                                } => {
395                                    let r = Rect::new(
396                                        bounds.x + rb.x,
397                                        bounds.y + rb.y,
398                                        rb.width,
399                                        rb.height,
400                                    );
401                                    batch.push(GpuQuadInstance::from_rect(
402                                        transform_rect_fn(r),
403                                        *color,
404                                        canvas_clip,
405                                    ));
406                                }
407                                crate::canvas2d::CanvasCommand::StrokeRect {
408                                    bounds: rb,
409                                    color,
410                                    line_width,
411                                } => {
412                                    let r = Rect::new(
413                                        bounds.x + rb.x,
414                                        bounds.y + rb.y,
415                                        rb.width,
416                                        rb.height,
417                                    );
418                                    batch.push(GpuQuadInstance::from_rounded_rect(
419                                        transform_rect_fn(r),
420                                        Color::TRANSPARENT,
421                                        BorderRadius::default(),
422                                        EdgeInsets::all(*line_width),
423                                        Some(*color),
424                                        canvas_clip,
425                                    ));
426                                }
427                                _ => {}
428                            }
429                        }
430                    }
431                }
432                _ => {}
433            }
434        }
435
436        batch
437    }
438}
439
440/// Slug-tier analytical GPU text compilation pipeline.
441///
442/// Compiles DisplayList text commands (`DrawText`, `DrawTextFragments`) into analytical
443/// quadratic Bézier glyph instances and curve contours for hardware shader evaluation.
444#[derive(Debug, Clone)]
445pub struct GpuSlugTextPipeline {
446    pub glyph_cache: strata_gpu_path::AnalyticGlyphCache,
447    pub buffer: strata_gpu_path::SlugGlyphBuffer,
448    pub total_glyphs: usize,
449    pub total_curves: usize,
450}
451
452impl Default for GpuSlugTextPipeline {
453    fn default() -> Self {
454        Self::new()
455    }
456}
457
458impl GpuSlugTextPipeline {
459    pub fn new() -> Self {
460        Self {
461            glyph_cache: strata_gpu_path::AnalyticGlyphCache::with_standard_ascii(),
462            buffer: strata_gpu_path::SlugGlyphBuffer::new(),
463            total_glyphs: 0,
464            total_curves: 0,
465        }
466    }
467
468    pub fn clear(&mut self) {
469        self.buffer.clear();
470        self.total_glyphs = 0;
471        self.total_curves = 0;
472    }
473
474    /// Advances and returns the hardware synchronization fence.
475    pub fn sync_barrier(&self) -> u64 {
476        self.buffer.sync_barrier()
477    }
478
479    /// Checks if a hardware synchronization fence has been signaled.
480    pub fn is_fence_synchronized(&self, fence: u64) -> bool {
481        self.buffer.is_fence_synchronized(fence)
482    }
483
484    /// Compiles all DrawText commands in a DisplayList into the Slug GPU buffer.
485    pub fn compile_display_list(
486        &mut self,
487        list: &DisplayList,
488        viewport_width: f32,
489        viewport_height: f32,
490        damage: Option<Rect>,
491    ) -> usize {
492        self.clear();
493        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
494
495        for cmd in list.commands() {
496            match cmd {
497                DrawCommand::DrawText {
498                    origin,
499                    text,
500                    font_size,
501                    color,
502                    ..
503                } => {
504                    let (r, g, b, a) = color.to_f32();
505                    let color_f32 = [r, g, b, a];
506                    let mut cursor_x = origin.0;
507                    let cursor_y = origin.1;
508
509                    for ch in text.chars() {
510                        if let Some(glyph) = self.glyph_cache.get(ch) {
511                            let scale = *font_size;
512                            let glyph_w = glyph.advance_width * scale;
513                            let glyph_h = scale;
514                            let screen_bounds = strata_gpu_path::Rect2D::new(
515                                cursor_x,
516                                cursor_y,
517                                cursor_x + glyph_w,
518                                cursor_y + glyph_h,
519                            );
520
521                            let clip_r = strata_gpu_path::Rect2D::new(
522                                default_clip.x,
523                                default_clip.y,
524                                default_clip.x + default_clip.width,
525                                default_clip.y + default_clip.height,
526                            );
527
528                            if default_clip
529                                .intersect(Rect::new(cursor_x, cursor_y, glyph_w, glyph_h))
530                                .is_some()
531                            {
532                                self.buffer
533                                    .push_glyph(glyph, screen_bounds, color_f32, clip_r);
534                                self.total_glyphs += 1;
535                            }
536                            cursor_x += glyph_w;
537                        } else {
538                            cursor_x += *font_size * 0.5;
539                        }
540                    }
541                }
542                DrawCommand::DrawTextFragments { fragments } => {
543                    for frag in fragments {
544                        let (r, g, b, a) = frag.style.color.to_f32();
545                        let color_f32 = [r, g, b, a];
546                        let mut cursor_x = frag.bounds.x;
547                        let cursor_y = frag.bounds.y;
548
549                        for ch in frag.text.chars() {
550                            if let Some(glyph) = self.glyph_cache.get(ch) {
551                                let scale = frag.style.font_size;
552                                let glyph_w = glyph.advance_width * scale;
553                                let glyph_h = scale;
554                                let screen_bounds = strata_gpu_path::Rect2D::new(
555                                    cursor_x,
556                                    cursor_y,
557                                    cursor_x + glyph_w,
558                                    cursor_y + glyph_h,
559                                );
560
561                                let clip_r = strata_gpu_path::Rect2D::new(
562                                    default_clip.x,
563                                    default_clip.y,
564                                    default_clip.x + default_clip.width,
565                                    default_clip.y + default_clip.height,
566                                );
567
568                                if default_clip
569                                    .intersect(Rect::new(cursor_x, cursor_y, glyph_w, glyph_h))
570                                    .is_some()
571                                {
572                                    self.buffer
573                                        .push_glyph(glyph, screen_bounds, color_f32, clip_r);
574                                    self.total_glyphs += 1;
575                                }
576                                cursor_x += glyph_w;
577                            } else {
578                                cursor_x += frag.style.font_size * 0.5;
579                            }
580                        }
581                    }
582                }
583                _ => {}
584            }
585        }
586
587        self.total_curves = self.buffer.curves.len();
588        self.total_glyphs
589    }
590
591    #[inline]
592    pub fn instance_bytes(&self) -> &[u8] {
593        self.buffer.instances_as_bytes()
594    }
595
596    #[inline]
597    pub fn curve_bytes(&self) -> &[u8] {
598        self.buffer.curves_as_bytes()
599    }
600}
601
602/// High-level orchestration pipeline for compiling display lists into GPU instance buffers.
603#[derive(Debug, Clone)]
604pub struct GpuPresentationPipeline {
605    pub viewport_width: f32,
606    pub viewport_height: f32,
607    pub uniforms: GpuUniforms,
608    pub batch: GpuBatch,
609    pub text_pipeline: GpuSlugTextPipeline,
610    pub total_uploaded_bytes: usize,
611    pub compiled_frames: u64,
612}
613
614impl GpuPresentationPipeline {
615    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
616        Self {
617            viewport_width,
618            viewport_height,
619            uniforms: GpuUniforms::new(viewport_width, viewport_height),
620            batch: GpuBatch::new(),
621            text_pipeline: GpuSlugTextPipeline::new(),
622            total_uploaded_bytes: 0,
623            compiled_frames: 0,
624        }
625    }
626
627    pub fn resize(&mut self, width: f32, height: f32) {
628        self.viewport_width = width;
629        self.viewport_height = height;
630        self.uniforms = GpuUniforms::new(width, height);
631    }
632
633    /// Compiles a frame from a DisplayList and optional damage rectangle into internal buffers.
634    /// Returns the total number of primitives (quads + text glyphs) emitted.
635    pub fn compile_frame(&mut self, list: &DisplayList, damage: Option<Rect>) -> usize {
636        self.batch = GpuBatch::from_display_list_damaged(
637            list,
638            damage,
639            self.viewport_width,
640            self.viewport_height,
641        );
642
643        let glyph_count = self.text_pipeline.compile_display_list(
644            list,
645            self.viewport_width,
646            self.viewport_height,
647            damage,
648        );
649
650        let byte_count = self.batch.as_bytes().len()
651            + self.uniforms.as_bytes().len()
652            + self.text_pipeline.instance_bytes().len()
653            + self.text_pipeline.curve_bytes().len();
654        self.total_uploaded_bytes += byte_count;
655        self.compiled_frames += 1;
656
657        self.batch.len() + glyph_count
658    }
659
660    #[inline]
661    pub fn instance_bytes(&self) -> &[u8] {
662        self.batch.as_bytes()
663    }
664
665    #[inline]
666    pub fn uniform_bytes(&self) -> &[u8] {
667        self.uniforms.as_bytes()
668    }
669}
670
671/// Batch collection of GPU instanced path segments ready for upload to storage/vertex buffers.
672#[derive(Debug, Default, Clone, PartialEq)]
673pub struct GpuPathBatch {
674    pub segments: Vec<strata_gpu_path::GpuPathSegment>,
675}
676
677impl GpuPathBatch {
678    pub fn new() -> Self {
679        Self::default()
680    }
681
682    pub fn with_capacity(capacity: usize) -> Self {
683        Self {
684            segments: Vec::with_capacity(capacity),
685        }
686    }
687
688    #[inline]
689    pub fn push(&mut self, segment: strata_gpu_path::GpuPathSegment) {
690        self.segments.push(segment);
691    }
692
693    #[inline]
694    pub fn clear(&mut self) {
695        self.segments.clear();
696    }
697
698    #[inline]
699    pub fn len(&self) -> usize {
700        self.segments.len()
701    }
702
703    #[inline]
704    pub fn is_empty(&self) -> bool {
705        self.segments.is_empty()
706    }
707
708    #[inline]
709    pub fn as_bytes(&self) -> &[u8] {
710        strata_gpu_path::GpuPathSegment::slice_to_bytes(&self.segments)
711    }
712
713    /// Compiles vector paths from a DisplayList into GPU path segments.
714    pub fn from_display_list(
715        list: &DisplayList,
716        viewport_width: f32,
717        viewport_height: f32,
718    ) -> Self {
719        Self::from_display_list_damaged(list, None, viewport_width, viewport_height)
720    }
721
722    /// Compiles vector paths from a DisplayList into GPU path segments with optional damage scissoring.
723    pub fn from_display_list_damaged(
724        list: &DisplayList,
725        damage: Option<Rect>,
726        viewport_width: f32,
727        viewport_height: f32,
728    ) -> Self {
729        let mut batch = Self::new();
730        let mut clip_stack: Vec<Rect> = Vec::new();
731        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
732
733        for cmd in list.commands() {
734            if let DrawCommand::PushClip { bounds, .. } = cmd {
735                let combined = match clip_stack.last() {
736                    Some(prev) => prev.intersect(*bounds).unwrap_or(Rect::zero()),
737                    None => *bounds,
738                };
739                clip_stack.push(combined);
740                continue;
741            } else if let DrawCommand::PopClip = cmd {
742                clip_stack.pop();
743                continue;
744            }
745
746            let current_clip = match clip_stack.last() {
747                Some(prev) => match prev.intersect(default_clip) {
748                    Some(c) => c,
749                    None => continue,
750                },
751                None => default_clip,
752            };
753
754            match cmd {
755                DrawCommand::DrawGpuPath {
756                    bounds,
757                    path,
758                    stroke,
759                    fill_color,
760                    stroke_color,
761                    transform: _,
762                } => {
763                    if bounds.intersect(current_clip).is_none() {
764                        continue;
765                    }
766
767                    let quads = path.to_quadratics(0.25);
768                    let mut flags = 0;
769                    if fill_color.is_some() {
770                        flags |= strata_gpu_path::FLAG_FILL;
771                    }
772                    if stroke_color.is_some() {
773                        flags |= strata_gpu_path::FLAG_STROKE;
774                    }
775                    if path.fill_rule == Some(strata_gpu_path::FillRule::EvenOdd) {
776                        flags |= strata_gpu_path::FLAG_EVEN_ODD;
777                    }
778
779                    let color_f32 = if let Some(fc) = fill_color {
780                        let (r, g, b, a) = fc.to_f32();
781                        [r, g, b, a]
782                    } else if let Some(sc) = stroke_color {
783                        let (r, g, b, a) = sc.to_f32();
784                        [r, g, b, a]
785                    } else {
786                        [1.0, 1.0, 1.0, 1.0]
787                    };
788
789                    let stroke_w = stroke.map(|s| s.width).unwrap_or(1.0);
790
791                    for q in quads {
792                        batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
793                            &q, stroke_w, flags, color_f32, 0.0,
794                        ));
795                    }
796                }
797                DrawCommand::DrawSvgPath {
798                    bounds,
799                    path_data,
800                    stroke_color,
801                    fill_color,
802                    stroke_width,
803                    stroke_dasharray,
804                    fill_rule,
805                    view_box,
806                    ..
807                } => {
808                    if bounds.intersect(current_clip).is_none() {
809                        continue;
810                    }
811                    let scale_x = if view_box.0 > 0.0 {
812                        bounds.width / view_box.0
813                    } else {
814                        1.0
815                    };
816                    let scale_y = if view_box.1 > 0.0 {
817                        bounds.height / view_box.1
818                    } else {
819                        1.0
820                    };
821                    let avg_scale = ((scale_x + scale_y) * 0.5).max(0.001);
822                    let parsed = strata_gpu_path::PathBuilder::from_svg(path_data);
823                    let quads: Vec<strata_gpu_path::QuadraticBezier> = parsed
824                        .to_quadratics(0.25)
825                        .into_iter()
826                        .map(|q| {
827                            strata_gpu_path::QuadraticBezier::new(
828                                strata_gpu_path::Point2D::new(
829                                    bounds.x + q.p0.x * scale_x,
830                                    bounds.y + q.p0.y * scale_y,
831                                ),
832                                strata_gpu_path::Point2D::new(
833                                    bounds.x + q.p1.x * scale_x,
834                                    bounds.y + q.p1.y * scale_y,
835                                ),
836                                strata_gpu_path::Point2D::new(
837                                    bounds.x + q.p2.x * scale_x,
838                                    bounds.y + q.p2.y * scale_y,
839                                ),
840                            )
841                        })
842                        .collect();
843
844                    let even_odd = if *fill_rule == strata_layout::FillRule::EvenOdd {
845                        strata_gpu_path::FLAG_EVEN_ODD
846                    } else {
847                        0
848                    };
849
850                    if let Some(fc) = fill_color {
851                        let (r, g, b, a) = fc.to_f32();
852                        let flags = strata_gpu_path::FLAG_FILL | even_odd;
853                        for q in &quads {
854                            batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
855                                q,
856                                *stroke_width * avg_scale,
857                                flags,
858                                [r, g, b, a],
859                                0.0,
860                            ));
861                        }
862                    }
863
864                    if let Some(sc) = stroke_color {
865                        let (r, g, b, a) = sc.to_f32();
866                        let flags = strata_gpu_path::FLAG_STROKE | even_odd;
867                        let sw = *stroke_width * avg_scale;
868                        let has_dashes = stroke_dasharray.iter().any(|&d| d > 0.0);
869                        if has_dashes {
870                            let scaled_dashes: Vec<f32> =
871                                stroke_dasharray.iter().map(|&d| d * avg_scale).collect();
872                            for dash_sub in
873                                strata_gpu_path::dash_quadratics(&quads, &scaled_dashes)
874                            {
875                                for q in &dash_sub {
876                                    batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
877                                        q,
878                                        sw,
879                                        flags,
880                                        [r, g, b, a],
881                                        0.0,
882                                    ));
883                                }
884                            }
885                        } else {
886                            for q in &quads {
887                                batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
888                                    q,
889                                    sw,
890                                    flags,
891                                    [r, g, b, a],
892                                    0.0,
893                                ));
894                            }
895                        }
896                    }
897                }
898                DrawCommand::DrawCanvas2D { bounds, commands } => {
899                    if bounds.intersect(current_clip).is_none() {
900                        continue;
901                    }
902                    let ox = bounds.x;
903                    let oy = bounds.y;
904                    let push_rect_quads =
905                        |batch: &mut Self, r: Rect, flags: u32, sw: f32, col: Color| {
906                            let (cr, cg, cb, ca) = col.to_f32();
907                            let c = [cr, cg, cb, ca];
908                            let p0 = strata_gpu_path::Point2D::new(ox + r.x, oy + r.y);
909                            let p1 = strata_gpu_path::Point2D::new(ox + r.x + r.width, oy + r.y);
910                            let p2 = strata_gpu_path::Point2D::new(
911                                ox + r.x + r.width,
912                                oy + r.y + r.height,
913                            );
914                            let p3 =
915                                strata_gpu_path::Point2D::new(ox + r.x, oy + r.y + r.height);
916                            for (a, b) in [(p0, p1), (p1, p2), (p2, p3), (p3, p0)] {
917                                let q = strata_gpu_path::QuadraticBezier::new(a, a.lerp(b, 0.5), b);
918                                batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
919                                    &q, sw, flags, c, 0.0,
920                                ));
921                            }
922                        };
923                    for ccmd in commands {
924                        match ccmd {
925                            crate::canvas2d::CanvasCommand::FillRect {
926                                bounds: rb,
927                                color,
928                            } => {
929                                push_rect_quads(
930                                    &mut batch,
931                                    *rb,
932                                    strata_gpu_path::FLAG_FILL,
933                                    1.0,
934                                    *color,
935                                );
936                            }
937                            crate::canvas2d::CanvasCommand::StrokeRect {
938                                bounds: rb,
939                                color,
940                                line_width,
941                            } => {
942                                push_rect_quads(
943                                    &mut batch,
944                                    *rb,
945                                    strata_gpu_path::FLAG_STROKE,
946                                    *line_width,
947                                    *color,
948                                );
949                            }
950                            crate::canvas2d::CanvasCommand::DrawLine {
951                                p0,
952                                p1,
953                                color,
954                                line_width,
955                            } => {
956                                let a = strata_gpu_path::Point2D::new(ox + p0.0, oy + p0.1);
957                                let b = strata_gpu_path::Point2D::new(ox + p1.0, oy + p1.1);
958                                let q = strata_gpu_path::QuadraticBezier::new(a, a.lerp(b, 0.5), b);
959                                let (r, g, bl, al) = color.to_f32();
960                                batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
961                                    &q,
962                                    *line_width,
963                                    strata_gpu_path::FLAG_STROKE,
964                                    [r, g, bl, al],
965                                    0.0,
966                                ));
967                            }
968                            crate::canvas2d::CanvasCommand::DrawCircle {
969                                center,
970                                radius,
971                                fill_color,
972                                stroke_color,
973                                line_width,
974                            } => {
975                                let cx = ox + center.0;
976                                let cy = oy + center.1;
977                                let r = *radius;
978                                let segs = 8usize;
979                                let mut circle_quads = Vec::with_capacity(segs);
980                                for i in 0..segs {
981                                    let a0 = (i as f32 / segs as f32) * std::f32::consts::TAU;
982                                    let a1 =
983                                        ((i + 1) as f32 / segs as f32) * std::f32::consts::TAU;
984                                    let am = (a0 + a1) * 0.5;
985                                    let cos_half = ((a1 - a0) * 0.5).cos().max(0.1);
986                                    let p0 = strata_gpu_path::Point2D::new(
987                                        cx + r * a0.cos(),
988                                        cy + r * a0.sin(),
989                                    );
990                                    let p2 = strata_gpu_path::Point2D::new(
991                                        cx + r * a1.cos(),
992                                        cy + r * a1.sin(),
993                                    );
994                                    let p1 = strata_gpu_path::Point2D::new(
995                                        cx + (r / cos_half) * am.cos(),
996                                        cy + (r / cos_half) * am.sin(),
997                                    );
998                                    circle_quads
999                                        .push(strata_gpu_path::QuadraticBezier::new(p0, p1, p2));
1000                                }
1001                                if let Some(fc) = fill_color {
1002                                    let (cr, cg, cb, ca) = fc.to_f32();
1003                                    for q in &circle_quads {
1004                                        batch.push(
1005                                            strata_gpu_path::GpuPathSegment::from_quadratic(
1006                                                q,
1007                                                *line_width,
1008                                                strata_gpu_path::FLAG_FILL,
1009                                                [cr, cg, cb, ca],
1010                                                0.0,
1011                                            ),
1012                                        );
1013                                    }
1014                                }
1015                                if let Some(sc) = stroke_color {
1016                                    let (cr, cg, cb, ca) = sc.to_f32();
1017                                    for q in &circle_quads {
1018                                        batch.push(
1019                                            strata_gpu_path::GpuPathSegment::from_quadratic(
1020                                                q,
1021                                                *line_width,
1022                                                strata_gpu_path::FLAG_STROKE,
1023                                                [cr, cg, cb, ca],
1024                                                0.0,
1025                                            ),
1026                                        );
1027                                    }
1028                                }
1029                            }
1030                            crate::canvas2d::CanvasCommand::DrawPath {
1031                                verbs,
1032                                fill_color,
1033                                stroke_color,
1034                                line_width,
1035                            } => {
1036                                let mut start = strata_gpu_path::Point2D::new(ox, oy);
1037                                let mut cur = start;
1038                                let mut path_quads = Vec::new();
1039                                for v in verbs {
1040                                    match *v {
1041                                        crate::canvas2d::CanvasPathVerb::MoveTo(x, y) => {
1042                                            cur = strata_gpu_path::Point2D::new(ox + x, oy + y);
1043                                            start = cur;
1044                                        }
1045                                        crate::canvas2d::CanvasPathVerb::LineTo(x, y) => {
1046                                            let next =
1047                                                strata_gpu_path::Point2D::new(ox + x, oy + y);
1048                                            path_quads.push(strata_gpu_path::QuadraticBezier::new(
1049                                                cur,
1050                                                cur.lerp(next, 0.5),
1051                                                next,
1052                                            ));
1053                                            cur = next;
1054                                        }
1055                                        crate::canvas2d::CanvasPathVerb::Arc {
1056                                            cx,
1057                                            cy,
1058                                            radius,
1059                                            start_angle,
1060                                            end_angle,
1061                                            counter_clockwise,
1062                                        } => {
1063                                            let acx = ox + cx;
1064                                            let acy = oy + cy;
1065                                            let mut sweep = end_angle - start_angle;
1066                                            if counter_clockwise && sweep > 0.0 {
1067                                                sweep -= std::f32::consts::TAU;
1068                                            } else if !counter_clockwise && sweep < 0.0 {
1069                                                sweep += std::f32::consts::TAU;
1070                                            }
1071                                            let steps = 8usize;
1072                                            for i in 0..steps {
1073                                                let t0 =
1074                                                    start_angle + sweep * (i as f32 / steps as f32);
1075                                                let t1 = start_angle
1076                                                    + sweep * ((i + 1) as f32 / steps as f32);
1077                                                let p0 = strata_gpu_path::Point2D::new(
1078                                                    acx + radius * t0.cos(),
1079                                                    acy + radius * t0.sin(),
1080                                                );
1081                                                let p2 = strata_gpu_path::Point2D::new(
1082                                                    acx + radius * t1.cos(),
1083                                                    acy + radius * t1.sin(),
1084                                                );
1085                                                path_quads.push(
1086                                                    strata_gpu_path::QuadraticBezier::new(
1087                                                        p0,
1088                                                        p0.lerp(p2, 0.5),
1089                                                        p2,
1090                                                    ),
1091                                                );
1092                                                cur = p2;
1093                                            }
1094                                        }
1095                                        crate::canvas2d::CanvasPathVerb::Close => {
1096                                            if cur.distance_squared(start) > 1e-4 {
1097                                                path_quads.push(
1098                                                    strata_gpu_path::QuadraticBezier::new(
1099                                                        cur,
1100                                                        cur.lerp(start, 0.5),
1101                                                        start,
1102                                                    ),
1103                                                );
1104                                                cur = start;
1105                                            }
1106                                        }
1107                                    }
1108                                }
1109                                if let Some(fc) = fill_color {
1110                                    let (cr, cg, cb, ca) = fc.to_f32();
1111                                    for q in &path_quads {
1112                                        batch.push(
1113                                            strata_gpu_path::GpuPathSegment::from_quadratic(
1114                                                q,
1115                                                *line_width,
1116                                                strata_gpu_path::FLAG_FILL,
1117                                                [cr, cg, cb, ca],
1118                                                0.0,
1119                                            ),
1120                                        );
1121                                    }
1122                                }
1123                                if let Some(sc) = stroke_color {
1124                                    let (cr, cg, cb, ca) = sc.to_f32();
1125                                    for q in &path_quads {
1126                                        batch.push(
1127                                            strata_gpu_path::GpuPathSegment::from_quadratic(
1128                                                q,
1129                                                *line_width,
1130                                                strata_gpu_path::FLAG_STROKE,
1131                                                [cr, cg, cb, ca],
1132                                                0.0,
1133                                            ),
1134                                        );
1135                                    }
1136                                }
1137                            }
1138                            crate::canvas2d::CanvasCommand::ClearRect { .. } => {}
1139                        }
1140                    }
1141                }
1142                _ => {}
1143            }
1144        }
1145
1146        batch
1147    }
1148}
1149
1150/// High-level orchestration pipeline for compiling vector paths into GPU compute/render buffers.
1151#[derive(Debug, Clone)]
1152pub struct GpuPathPipeline {
1153    pub viewport_width: f32,
1154    pub viewport_height: f32,
1155    pub uniforms: strata_gpu_path::GpuPathUniforms,
1156    pub batch: GpuPathBatch,
1157    pub total_uploaded_bytes: usize,
1158    pub compiled_frames: u64,
1159}
1160
1161impl GpuPathPipeline {
1162    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
1163        Self {
1164            viewport_width,
1165            viewport_height,
1166            uniforms: strata_gpu_path::GpuPathUniforms::new(
1167                viewport_width,
1168                viewport_height,
1169                0.25,
1170                0,
1171            ),
1172            batch: GpuPathBatch::new(),
1173            total_uploaded_bytes: 0,
1174            compiled_frames: 0,
1175        }
1176    }
1177
1178    pub fn resize(&mut self, width: f32, height: f32) {
1179        self.viewport_width = width;
1180        self.viewport_height = height;
1181        self.uniforms =
1182            strata_gpu_path::GpuPathUniforms::new(width, height, 0.25, self.batch.len() as u32);
1183    }
1184
1185    /// Compiles a frame from a DisplayList and optional damage rectangle into the internal path batch buffer.
1186    pub fn compile_frame(&mut self, list: &DisplayList, damage: Option<Rect>) -> usize {
1187        // Most frames contain no vector paths; avoid walking clips and
1188        // rebuilding an empty batch when nothing needs compiling.
1189        let has_paths = list.commands().iter().any(|cmd| {
1190            matches!(
1191                cmd,
1192                DrawCommand::DrawGpuPath { .. }
1193                    | DrawCommand::DrawSvgPath { .. }
1194                    | DrawCommand::DrawCanvas2D { .. }
1195            )
1196        });
1197        if !has_paths {
1198            if !self.batch.is_empty() {
1199                self.batch.clear();
1200                self.uniforms.curve_count = 0;
1201            }
1202            return 0;
1203        }
1204        self.batch = GpuPathBatch::from_display_list_damaged(
1205            list,
1206            damage,
1207            self.viewport_width,
1208            self.viewport_height,
1209        );
1210
1211        self.uniforms.curve_count = self.batch.len() as u32;
1212        let byte_count = self.batch.as_bytes().len() + self.uniforms.as_bytes().len();
1213        self.total_uploaded_bytes += byte_count;
1214        self.compiled_frames += 1;
1215
1216        self.batch.len()
1217    }
1218
1219    #[inline]
1220    pub fn segment_bytes(&self) -> &[u8] {
1221        self.batch.as_bytes()
1222    }
1223
1224    #[inline]
1225    pub fn uniform_bytes(&self) -> &[u8] {
1226        self.uniforms.as_bytes()
1227    }
1228}
1229
1230/// Parsed and compiled WGSL shader module with verified reflection data.
1231#[derive(Debug, Clone, PartialEq)]
1232pub struct GpuShaderModule {
1233    pub source: String,
1234    pub has_vertex_entry: bool,
1235    pub has_fragment_entry: bool,
1236    pub vertex_entry: String,
1237    pub fragment_entry: String,
1238    pub uniforms_declared: Vec<String>,
1239    pub bind_groups_declared: usize,
1240}
1241
1242/// Compiler and validator for WGSL shaders ensuring runtime hardware compatibility.
1243#[derive(Debug, Default, Clone)]
1244pub struct GpuShaderCompiler;
1245
1246impl GpuShaderCompiler {
1247    pub fn new() -> Self {
1248        Self
1249    }
1250
1251    /// Compiles and validates a WGSL source string, returning a `GpuShaderModule` or an error.
1252    pub fn compile(&self, source: &str) -> Result<GpuShaderModule, String> {
1253        let has_vertex_entry = source.contains("@vertex");
1254        let has_fragment_entry = source.contains("@fragment");
1255
1256        if !has_vertex_entry && !has_fragment_entry && !source.contains("@compute") {
1257            return Err(
1258                "WGSL shader missing @vertex, @fragment, or @compute entry point".to_string(),
1259            );
1260        }
1261
1262        let mut vertex_entry = "vs_main".to_string();
1263        let mut fragment_entry = "fs_main".to_string();
1264
1265        for line in source.lines() {
1266            let trimmed = line.trim();
1267            if trimmed.starts_with("fn ") {
1268                let name = trimmed
1269                    .trim_start_matches("fn ")
1270                    .split('(')
1271                    .next()
1272                    .unwrap_or("")
1273                    .trim();
1274                if source.contains(&format!("@vertex\nfn {}", name))
1275                    || source.contains(&format!("@vertex fn {}", name))
1276                {
1277                    vertex_entry = name.to_string();
1278                }
1279                if source.contains(&format!("@fragment\nfn {}", name))
1280                    || source.contains(&format!("@fragment fn {}", name))
1281                {
1282                    fragment_entry = name.to_string();
1283                }
1284            }
1285        }
1286
1287        let mut uniforms = Vec::new();
1288        for line in source.lines() {
1289            if line.contains("var<uniform>") {
1290                if let Some(name) = line.split("var<uniform>").nth(1) {
1291                    let u_name = name.split(':').next().unwrap_or("").trim();
1292                    if !u_name.is_empty() {
1293                        uniforms.push(u_name.to_string());
1294                    }
1295                }
1296            }
1297        }
1298
1299        let bind_groups = source.matches("@group(").count();
1300
1301        Ok(GpuShaderModule {
1302            source: source.to_string(),
1303            has_vertex_entry,
1304            has_fragment_entry,
1305            vertex_entry,
1306            fragment_entry,
1307            uniforms_declared: uniforms,
1308            bind_groups_declared: bind_groups,
1309        })
1310    }
1311}
1312
1313/// Vertex attribute data format.
1314#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1315pub enum GpuVertexFormat {
1316    Float32x2,
1317    Float32x3,
1318    Float32x4,
1319    Uint32x2,
1320    Uint32x4,
1321}
1322
1323impl GpuVertexFormat {
1324    pub const fn byte_size(&self) -> usize {
1325        match self {
1326            Self::Float32x2 | Self::Uint32x2 => 8,
1327            Self::Float32x3 => 12,
1328            Self::Float32x4 | Self::Uint32x4 => 16,
1329        }
1330    }
1331}
1332
1333/// Individual vertex attribute descriptor.
1334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1335pub struct GpuVertexAttribute {
1336    pub format: GpuVertexFormat,
1337    pub offset: u64,
1338    pub shader_location: u32,
1339}
1340
1341/// Step mode for vertex buffer stepping.
1342#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1343pub enum GpuVertexStepMode {
1344    #[default]
1345    Vertex,
1346    Instance,
1347}
1348
1349/// Vertex buffer layout specifying stride and attributes.
1350#[derive(Debug, Clone, PartialEq)]
1351pub struct GpuVertexBufferLayout {
1352    pub array_stride: u64,
1353    pub step_mode: GpuVertexStepMode,
1354    pub attributes: Vec<GpuVertexAttribute>,
1355}
1356
1357/// Primitive topology for rasterization.
1358#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1359pub enum GpuPrimitiveTopology {
1360    PointList,
1361    LineList,
1362    LineStrip,
1363    #[default]
1364    TriangleList,
1365    TriangleStrip,
1366}
1367
1368/// Depth comparison function for early-Z culling and depth bounds testing.
1369#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1370pub enum GpuCompareFunction {
1371    Never,
1372    #[default]
1373    Less,
1374    Equal,
1375    LessEqual,
1376    Greater,
1377    NotEqual,
1378    GreaterEqual,
1379    Always,
1380}
1381
1382/// Depth/stencil state for hardware depth attachment.
1383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1384pub struct GpuDepthStencilState {
1385    pub format: crate::swapchain::SwapchainFormat,
1386    pub depth_write_enabled: bool,
1387    pub depth_compare: GpuCompareFunction,
1388}
1389
1390impl Default for GpuDepthStencilState {
1391    fn default() -> Self {
1392        Self {
1393            format: crate::swapchain::SwapchainFormat::Depth32Float,
1394            depth_write_enabled: true,
1395            depth_compare: GpuCompareFunction::LessEqual,
1396        }
1397    }
1398}
1399
1400impl GpuDepthStencilState {
1401    /// Evaluates early-Z depth comparison between current depth buffer value and incoming fragment depth.
1402    pub fn passes_test(&self, current_depth: f32, new_depth: f32) -> bool {
1403        match self.depth_compare {
1404            GpuCompareFunction::Never => false,
1405            GpuCompareFunction::Less => new_depth < current_depth,
1406            GpuCompareFunction::Equal => (new_depth - current_depth).abs() < 1e-6,
1407            GpuCompareFunction::LessEqual => new_depth <= current_depth + 1e-6,
1408            GpuCompareFunction::Greater => new_depth > current_depth,
1409            GpuCompareFunction::NotEqual => (new_depth - current_depth).abs() >= 1e-6,
1410            GpuCompareFunction::GreaterEqual => new_depth >= current_depth - 1e-6,
1411            GpuCompareFunction::Always => true,
1412        }
1413    }
1414}
1415
1416/// Hardware-accelerated GPU render pipeline configuration.
1417#[derive(Debug, Clone)]
1418pub struct GpuRenderPipeline {
1419    pub shader_module: GpuShaderModule,
1420    pub vertex_layout: GpuVertexBufferLayout,
1421    pub instance_layout: Option<GpuVertexBufferLayout>,
1422    pub primitive_topology: GpuPrimitiveTopology,
1423    pub depth_stencil: Option<GpuDepthStencilState>,
1424}
1425
1426impl GpuRenderPipeline {
1427    /// Constructs an authentic instanced UI quad render pipeline binding WGSL_ANALYTICAL_QUAD_SHADER.
1428    pub fn new_instanced_quad_pipeline(
1429        viewport_width: f32,
1430        viewport_height: f32,
1431    ) -> Result<Self, String> {
1432        let _ = (viewport_width, viewport_height);
1433        let compiler = GpuShaderCompiler::new();
1434        let shader_module = compiler.compile(WGSL_ANALYTICAL_QUAD_SHADER)?;
1435
1436        let vertex_layout = GpuVertexBufferLayout {
1437            array_stride: 8,
1438            step_mode: GpuVertexStepMode::Vertex,
1439            attributes: vec![GpuVertexAttribute {
1440                format: GpuVertexFormat::Float32x2,
1441                offset: 0,
1442                shader_location: 0,
1443            }],
1444        };
1445
1446        let instance_layout = GpuVertexBufferLayout {
1447            array_stride: 96,
1448            step_mode: GpuVertexStepMode::Instance,
1449            attributes: vec![
1450                GpuVertexAttribute {
1451                    format: GpuVertexFormat::Float32x4,
1452                    offset: 0,
1453                    shader_location: 1,
1454                },
1455                GpuVertexAttribute {
1456                    format: GpuVertexFormat::Float32x4,
1457                    offset: 16,
1458                    shader_location: 2,
1459                },
1460                GpuVertexAttribute {
1461                    format: GpuVertexFormat::Float32x4,
1462                    offset: 32,
1463                    shader_location: 3,
1464                },
1465                GpuVertexAttribute {
1466                    format: GpuVertexFormat::Float32x4,
1467                    offset: 48,
1468                    shader_location: 4,
1469                },
1470                GpuVertexAttribute {
1471                    format: GpuVertexFormat::Float32x4,
1472                    offset: 64,
1473                    shader_location: 5,
1474                },
1475                GpuVertexAttribute {
1476                    format: GpuVertexFormat::Float32x4,
1477                    offset: 80,
1478                    shader_location: 6,
1479                },
1480            ],
1481        };
1482
1483        Ok(Self {
1484            shader_module,
1485            vertex_layout,
1486            instance_layout: Some(instance_layout),
1487            primitive_topology: GpuPrimitiveTopology::TriangleList,
1488            depth_stencil: Some(GpuDepthStencilState {
1489                format: crate::swapchain::SwapchainFormat::Depth32Float,
1490                depth_write_enabled: true,
1491                depth_compare: GpuCompareFunction::LessEqual,
1492            }),
1493        })
1494    }
1495
1496    /// Records an instanced draw command onto a command encoder.
1497    pub fn draw_instanced(
1498        &self,
1499        encoder: &mut crate::gpu_context::GpuCommandEncoder,
1500        vertex_count: usize,
1501        instance_count: usize,
1502    ) {
1503        encoder.draw_instanced(vertex_count, instance_count);
1504    }
1505}
1506
1507/// Statistics and primitive breakdown for batched GPU dispatches.
1508#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1509pub struct GpuBatchSummary {
1510    pub total_commands: usize,
1511    pub quad_instances: usize,
1512    pub slug_glyphs: usize,
1513    pub path_segments: usize,
1514    pub total_draw_calls: usize,
1515}
1516
1517/// Instanced UI Draw Call Batch Collector for complex layouts (Goal 07).
1518///
1519/// Batches heterogeneous display lists with 10,000+ commands into <= 5 GPU draw calls.
1520#[derive(Debug, Clone)]
1521pub struct GpuBatchCollector {
1522    pub viewport_width: f32,
1523    pub viewport_height: f32,
1524    pub quad_batch: GpuBatch,
1525    pub text_pipeline: GpuSlugTextPipeline,
1526    pub path_batch: GpuPathBatch,
1527    pub summary: GpuBatchSummary,
1528}
1529
1530impl GpuBatchCollector {
1531    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
1532        Self {
1533            viewport_width,
1534            viewport_height,
1535            quad_batch: GpuBatch::new(),
1536            text_pipeline: GpuSlugTextPipeline::new(),
1537            path_batch: GpuPathBatch::new(),
1538            summary: GpuBatchSummary::default(),
1539        }
1540    }
1541
1542    /// Collects and batches all compatible primitives from a DisplayList.
1543    pub fn collect(&mut self, list: &DisplayList, damage: Option<Rect>) -> GpuBatchSummary {
1544        self.quad_batch = GpuBatch::from_display_list_damaged(
1545            list,
1546            damage,
1547            self.viewport_width,
1548            self.viewport_height,
1549        );
1550
1551        let glyph_count = self.text_pipeline.compile_display_list(
1552            list,
1553            self.viewport_width,
1554            self.viewport_height,
1555            damage,
1556        );
1557
1558        self.path_batch = GpuPathBatch::from_display_list_damaged(
1559            list,
1560            damage,
1561            self.viewport_width,
1562            self.viewport_height,
1563        );
1564
1565        let mut draw_calls = 0;
1566        if !self.quad_batch.is_empty() {
1567            draw_calls += 1;
1568        }
1569        if glyph_count > 0 {
1570            draw_calls += 1;
1571        }
1572        if !self.path_batch.is_empty() {
1573            draw_calls += 1;
1574        }
1575
1576        self.summary = GpuBatchSummary {
1577            total_commands: list.len(),
1578            quad_instances: self.quad_batch.len(),
1579            slug_glyphs: glyph_count,
1580            path_segments: self.path_batch.len(),
1581            total_draw_calls: draw_calls,
1582        };
1583
1584        self.summary
1585    }
1586
1587    /// Dispatches all collected batches onto the GPU device in unified passes.
1588    pub fn dispatch(
1589        &self,
1590        device: &mut crate::gpu_context::GpuDevice,
1591        damage: Option<Rect>,
1592    ) -> Result<GpuBatchSummary, crate::swapchain::PresentError> {
1593        let mut encoder = device.create_command_encoder();
1594        let pass = crate::gpu_context::GpuRenderPassDescriptor {
1595            color_texture_id: device.swapchain_texture.id,
1596            depth_texture_id: Some(device.depth_texture.id),
1597            clear_color: Some([0.0, 0.0, 0.0, 1.0]),
1598            clear_depth: Some(1.0),
1599            scissor_rect: damage,
1600        };
1601        encoder.begin_render_pass(pass);
1602
1603        if !self.quad_batch.is_empty() {
1604            encoder.draw_instanced(6, self.quad_batch.len());
1605        }
1606        if self.summary.slug_glyphs > 0 {
1607            encoder.draw_instanced(6, self.summary.slug_glyphs);
1608        }
1609        if !self.path_batch.is_empty() {
1610            encoder.draw_instanced(6, self.path_batch.len());
1611        }
1612
1613        encoder.end_render_pass();
1614        device.submit(encoder);
1615
1616        Ok(self.summary)
1617    }
1618}
1619
1620#[cfg(test)]
1621mod tests {
1622    use super::*;
1623
1624    #[test]
1625    fn test_gpu_quad_memory_layout() {
1626        assert_eq!(GpuQuadInstance::BYTE_SIZE, 96);
1627        assert_eq!(GpuUniforms::BYTE_SIZE, 16);
1628        assert_eq!(QUAD_VERTICES.len(), 6);
1629
1630        let quad = GpuQuadInstance::from_rect(
1631            Rect::new(10.0, 20.0, 100.0, 50.0),
1632            Color::rgb(255, 0, 0),
1633            Rect::new(0.0, 0.0, 1920.0, 1080.0),
1634        );
1635
1636        let bytes = quad.as_bytes();
1637        assert_eq!(bytes.len(), 96);
1638
1639        // Verify bounds at byte offset 0: 10.0, 20.0, 100.0, 50.0
1640        let b0 = f32::from_ne_bytes(bytes[0..4].try_into().unwrap());
1641        let b1 = f32::from_ne_bytes(bytes[4..8].try_into().unwrap());
1642        let b2 = f32::from_ne_bytes(bytes[8..12].try_into().unwrap());
1643        let b3 = f32::from_ne_bytes(bytes[12..16].try_into().unwrap());
1644        assert_eq!(b0, 10.0);
1645        assert_eq!(b1, 20.0);
1646        assert_eq!(b2, 100.0);
1647        assert_eq!(b3, 50.0);
1648    }
1649
1650    #[test]
1651    fn test_gpu_batch_compilation_and_scissoring() {
1652        let mut dl = DisplayList::new();
1653
1654        // 1. Root background (1920x1080)
1655        dl.push(DrawCommand::DrawRect {
1656            bounds: Rect::new(0.0, 0.0, 1920.0, 1080.0),
1657            color: Color::rgb(10, 10, 15),
1658        });
1659
1660        // 2. Button in top-left (20, 20, 120, 36)
1661        dl.push(DrawCommand::DrawRoundedRect {
1662            bounds: Rect::new(20.0, 20.0, 120.0, 36.0),
1663            color: Color::rgb(59, 130, 246),
1664            border_radius: BorderRadius::all(6.0),
1665            border_width: EdgeInsets::ZERO,
1666            border_color: None,
1667        });
1668
1669        // 3. Card in bottom-right (1500, 800, 300, 200)
1670        dl.push(DrawCommand::DrawRect {
1671            bounds: Rect::new(1500.0, 800.0, 300.0, 200.0),
1672            color: Color::rgb(30, 41, 59),
1673        });
1674
1675        // Full compilation
1676        let full_batch = GpuBatch::from_display_list(&dl, 1920.0, 1080.0);
1677        assert_eq!(full_batch.len(), 3);
1678        assert_eq!(full_batch.as_bytes().len(), 3 * 96);
1679
1680        // Damaged compilation targeting only the button in top-left
1681        let damage = Rect::new(10.0, 10.0, 140.0, 60.0);
1682        let damaged_batch = GpuBatch::from_display_list_damaged(&dl, Some(damage), 1920.0, 1080.0);
1683
1684        // Background (intersects damage) and Button (intersects damage) are included.
1685        // Card (at 1500, 800) does not intersect damage and is skipped!
1686        assert_eq!(damaged_batch.len(), 2);
1687    }
1688
1689    #[test]
1690    fn test_presentation_pipeline_compilation() {
1691        let mut pipeline = GpuPresentationPipeline::new(1920.0, 1080.0);
1692
1693        let mut dl = DisplayList::new();
1694        dl.push(DrawCommand::DrawRect {
1695            bounds: Rect::new(50.0, 50.0, 200.0, 100.0),
1696            color: Color::rgb(255, 255, 255),
1697        });
1698
1699        let count = pipeline.compile_frame(&dl, None);
1700        assert_eq!(count, 1);
1701        assert_eq!(pipeline.compiled_frames, 1);
1702        assert_eq!(pipeline.instance_bytes().len(), 96);
1703        assert_eq!(pipeline.uniform_bytes().len(), 16);
1704    }
1705
1706    #[test]
1707    fn test_gpu_path_batch_and_pipeline() {
1708        let mut path_pipeline = GpuPathPipeline::new(1920.0, 1080.0);
1709
1710        let mut dl = DisplayList::new();
1711        // Add DrawGpuPath
1712        let path = strata_gpu_path::PathBuilder::from_svg("M 0 0 L 100 100 Q 150 50 200 0 Z")
1713            .with_fill(strata_gpu_path::FillRule::NonZero);
1714
1715        dl.push(DrawCommand::DrawGpuPath {
1716            bounds: Rect::new(0.0, 0.0, 200.0, 100.0),
1717            path,
1718            stroke: Some(strata_gpu_path::StrokeOptions::new(2.0)),
1719            fill_color: Some(Color::rgb(16, 185, 129)),
1720            stroke_color: Some(Color::rgb(5, 150, 105)),
1721            transform: None,
1722        });
1723
1724        // Add DrawSvgPath
1725        dl.push(DrawCommand::DrawSvgPath {
1726            bounds: Rect::new(300.0, 300.0, 50.0, 50.0),
1727            path_data: "M 0 0 L 50 50 Z".to_string(),
1728            stroke_color: Some(Color::rgb(255, 255, 255)),
1729            fill_color: None,
1730            stroke_width: 1.5,
1731            stroke_linecap: strata_layout::StrokeLineCap::Round,
1732            stroke_linejoin: strata_layout::StrokeLineJoin::Round,
1733            stroke_dasharray: Vec::new(),
1734            fill_rule: strata_layout::FillRule::NonZero,
1735            view_box: (50.0, 50.0),
1736        });
1737
1738        let seg_count = path_pipeline.compile_frame(&dl, None);
1739        assert!(
1740            seg_count >= 4,
1741            "Should emit multiple quadratic segments for path + svg"
1742        );
1743        assert_eq!(path_pipeline.compiled_frames, 1);
1744        assert_eq!(path_pipeline.segment_bytes().len(), seg_count * 64);
1745        assert_eq!(path_pipeline.uniform_bytes().len(), 16);
1746
1747        // Test damage scissoring: scissoring away the second path
1748        let damage = Rect::new(0.0, 0.0, 220.0, 120.0);
1749        let damaged_count = path_pipeline.compile_frame(&dl, Some(damage));
1750        assert!(
1751            damaged_count < seg_count,
1752            "Damaged compilation should skip path outside damage rect"
1753        );
1754    }
1755}