euv-core 0.52.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
use super::*;

/// Sparse-effect hybrid partitioning, tight-tile CPU rasterization, and GPU batch compositing for `HybridRenderer`.
impl HybridRenderer {
    /// Creates a sparse-effect hybrid renderer targeting `gpu_backend` for direct GPU primitives and tight-tile compositing.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - GPU backend used for direct primitive batches and sparse-tile compositing.
    /// - `u32` - Initial physical width.
    /// - `u32` - Initial physical height.
    /// - `RenderConfig` - Rendering configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized sparse-effect hybrid renderer.
    #[must_use]
    pub fn with_backend(
        gpu_backend: GraphicsBackend,
        width: u32,
        height: u32,
        config: RenderConfig,
    ) -> Self {
        Self::with_backend_and_font(
            gpu_backend,
            width,
            height,
            config,
            NativeSystemFont::deterministic(),
        )
    }

    /// Creates a sparse-effect hybrid renderer targeting `gpu_backend` with an explicit font provider.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - GPU backend used for direct primitive batches and sparse-tile compositing.
    /// - `u32` - Initial physical width.
    /// - `u32` - Initial physical height.
    /// - `RenderConfig` - Rendering configuration.
    /// - `NativeSystemFont` - Font provider used only when sparse CPU effect regions require rasterization.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized sparse-effect hybrid renderer.
    #[must_use]
    pub fn with_backend_and_font(
        gpu_backend: GraphicsBackend,
        width: u32,
        height: u32,
        config: RenderConfig,
        font_provider: NativeSystemFont,
    ) -> Self {
        let driver: NativeGpuDriver = NativeGpuDriver::probe(gpu_backend);
        Self {
            software: SoftwareRenderer::with_font_provider(width, height, config, font_provider),
            driver,
            gpu_glyph_atlas: IncrementalGpuGlyphAtlas::default(),
            last_cpu_effect_regions: Vec::new(),
            last_gpu_native_commands: 0,
            last_cpu_tile_count: 0,
            last_cpu_upload_bytes: 0,
            last_cpu_rasterized_pixels: 0,
            last_batches: Vec::new(),
        }
    }

    /// Partitions `display_list` into GPU-native primitives versus sparse CPU-only effect regions without rasterizing the full frame.
    ///
    /// # Arguments
    ///
    /// - `&DisplayList` - Frame display list to inspect.
    ///
    /// # Returns
    ///
    /// - `HybridCommandPartition` - Partition counts and tight physical bounds of sparse CPU-only effect regions.
    #[must_use]
    pub fn partition_commands(display_list: &DisplayList) -> HybridCommandPartition {
        let scale: f32 = display_list.get_scale_factor().max(0.5);
        let mut gpu_native_count: usize = 0;
        let mut gpu_covered_pixels: usize = 0;
        let mut cpu_effect_regions: Vec<Rect> = Vec::new();
        for cmd in display_list.get_commands().iter() {
            match cmd {
                DrawCommand::BackdropBlur { rect, .. } => {
                    let phys: Rect = Rect::new(
                        rect.get_x() * scale,
                        rect.get_y() * scale,
                        (rect.get_width() * scale).max(1.0),
                        (rect.get_height() * scale).max(1.0),
                    );
                    cpu_effect_regions.push(phys);
                }
                DrawCommand::FillRoundedRect { rect, .. }
                | DrawCommand::LinearGradientRect { rect, .. }
                | DrawCommand::BoxShadow { rect, .. }
                | DrawCommand::TextRun { rect, .. }
                | DrawCommand::Image { rect, .. }
                | DrawCommand::SharedImage { rect, .. }
                | DrawCommand::SpriteRegion { rect, .. }
                | DrawCommand::ExternalSurface { rect, .. } => {
                    gpu_native_count = gpu_native_count.saturating_add(1);
                    let pw: usize = ((rect.get_width() * scale).ceil() as usize).max(1);
                    let ph: usize = ((rect.get_height() * scale).ceil() as usize).max(1);
                    gpu_covered_pixels = gpu_covered_pixels.saturating_add(pw.saturating_mul(ph));
                }
                DrawCommand::Circle { radius, .. } => {
                    gpu_native_count = gpu_native_count.saturating_add(1);
                    let delta_val: usize = (((*radius) * 2.0 * scale).ceil() as usize).max(1);
                    gpu_covered_pixels =
                        gpu_covered_pixels.saturating_add(delta_val.saturating_mul(delta_val));
                }
                DrawCommand::Line {
                    from, to, width, ..
                } => {
                    gpu_native_count = gpu_native_count.saturating_add(1);
                    let lw: usize = (((to.get_x() - from.get_x()).abs().max(*width) * scale).ceil()
                        as usize)
                        .max(1);
                    let lh: usize = (((to.get_y() - from.get_y()).abs().max(*width) * scale).ceil()
                        as usize)
                        .max(1);
                    gpu_covered_pixels = gpu_covered_pixels.saturating_add(lw.saturating_mul(lh));
                }
                DrawCommand::Triangle { p0, p1, p2, .. } => {
                    gpu_native_count = gpu_native_count.saturating_add(1);
                    let width_val: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x())
                        - p0.get_x().min(p1.get_x()).min(p2.get_x());
                    let height_val: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y())
                        - p0.get_y().min(p1.get_y()).min(p2.get_y());
                    let pw: usize = ((width_val * scale).ceil() as usize).max(1);
                    let ph: usize = ((height_val * scale).ceil() as usize).max(1);
                    gpu_covered_pixels = gpu_covered_pixels.saturating_add(pw.saturating_mul(ph));
                }
                DrawCommand::Clear(_)
                | DrawCommand::TextCaret { .. }
                | DrawCommand::PushClip(_)
                | DrawCommand::PushRoundedClip { .. }
                | DrawCommand::PopClip => {
                    gpu_native_count = gpu_native_count.saturating_add(1);
                }
            }
        }
        HybridCommandPartition {
            gpu_native_count,
            cpu_effect_regions,
            gpu_covered_pixels,
        }
    }

    /// Evaluates whether the sparse CPU-only effect regions from the most recent frame justify `Hybrid` over pure GPU or pure CPU.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Hybrid renderer reference.
    /// - `f64` - Pure GPU frame time in milliseconds.
    /// - `f64` - Pure CPU frame time in milliseconds.
    /// - `f64` - Sparse CPU tile raster time in milliseconds.
    /// - `f64` - GPU composite + native primitive time in milliseconds.
    ///
    /// # Returns
    ///
    /// - `HybridNetGainEstimate` - Net gain verdict for `AdaptiveRenderRouter`.
    #[must_use]
    pub fn evaluate_last_frame_net_gain(
        &self,
        gpu_full_ms: f64,
        cpu_full_ms: f64,
        cpu_tile_ms: f64,
        gpu_composite_ms: f64,
    ) -> HybridNetGainEstimate {
        let target_framebuffer: &Framebuffer = self.get_software().get_framebuffer();
        estimate_hybrid_net_gain(
            target_framebuffer.get_width(),
            target_framebuffer.get_height(),
            self.get_last_cpu_effect_regions().as_slice(),
            gpu_full_ms,
            cpu_full_ms,
            cpu_tile_ms,
            gpu_composite_ms,
        )
    }

    /// Compiles GPU-native primitives directly into 64-byte GPU batches on `NativeGpuDriver` and rasterizes ONLY sparse CPU-only effect regions into tight tiles.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable hybrid renderer.
    /// - `&DisplayList` - Frame display list.
    /// - `DamageRegion` - Dirty damage bounds.
    ///
    /// # Returns
    ///
    /// - `Result<(usize, usize), PlatformError>` - Tuple of `(batches_submitted, pixels_shaded)`.
    pub fn render(
        &mut self,
        display_list: &DisplayList,
        damage: DamageRegion,
    ) -> Result<(usize, usize), PlatformError> {
        self.render_with_physical_size(display_list, damage, None)
    }

    /// Compiles GPU-native primitives directly into 64-byte batches with authoritative physical backing dimensions when provided.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable hybrid renderer.
    /// - `&DisplayList` - Frame display list.
    /// - `DamageRegion` - Dirty damage bounds.
    /// - `Option<(u32, u32)>` - Authoritative `(physical_width, physical_height)` preventing `(logical * scale).round()` drift.
    ///
    /// # Returns
    ///
    /// - `Result<(usize, usize), PlatformError>` - Tuple of `(batches_submitted, pixels_shaded)`.
    pub fn render_with_physical_size(
        &mut self,
        display_list: &DisplayList,
        damage: DamageRegion,
        physical_size: Option<(u32, u32)>,
    ) -> Result<(usize, usize), PlatformError> {
        let scale: f32 = display_list.get_scale_factor().clamp(0.25, 16.0);
        let box_size: Size = display_list.get_viewport();
        let (phys_w, phys_h): (u32, u32) = match physical_size {
            Some((width_px, height_px)) if width_px > 0 && height_px > 0 => (width_px, height_px),
            _ => {
                let width_px: u32 = if box_size.get_width() > 0.0 {
                    ((box_size.get_width() * scale).round() as u32).max(1)
                } else {
                    self.get_software().get_framebuffer().get_width().max(1)
                };
                let height_px: u32 = if box_size.get_height() > 0.0 {
                    ((box_size.get_height() * scale).round() as u32).max(1)
                } else {
                    self.get_software().get_framebuffer().get_height().max(1)
                };
                (width_px, height_px)
            }
        };
        if self.get_software().get_framebuffer().get_width() != phys_w
            || self.get_software().get_framebuffer().get_height() != phys_h
        {
            let software_ref: &mut SoftwareRenderer = self.get_mut_software();
            if let Some(frame_pixels) = software_ref.framebuffer.as_mut() {
                frame_pixels.resize(phys_w, phys_h);
            }
        }
        let full_rect: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
        let partition: HybridCommandPartition = Self::partition_commands(display_list);
        let mut clip_stack: Vec<(Rect, u16)> = Vec::with_capacity(16);
        clip_stack.push((full_rect, 0));
        let mut batches: Vec<GpuBatch> = Vec::with_capacity(8);
        let mut clear_color: Color = COLOR_TRANSPARENT;
        let max_blur_px: f32 = (64.0 * scale).clamp(64.0, 512.0);
        for cmd in display_list.get_commands().iter() {
            let (active_clip, active_rounded_bits): (Rect, u16) =
                clip_stack.last().copied().unwrap_or((full_rect, 0));
            let clip_arr: [f32; 4] = [
                active_clip.get_x(),
                active_clip.get_y(),
                active_clip.right(),
                active_clip.bottom(),
            ];
            match cmd {
                DrawCommand::Clear(clear_col) => {
                    clear_color = *clear_col;
                }
                DrawCommand::PushClip(rect) => {
                    let phys: Rect = Rect::new(
                        (rect.get_x() * scale).round(),
                        (rect.get_y() * scale).round(),
                        (rect.get_width() * scale).round().max(0.0),
                        (rect.get_height() * scale).round().max(0.0),
                    );
                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
                    let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
                        active_clip,
                        active_rounded_bits,
                        next_scissor,
                        phys,
                        None,
                    );
                    clip_stack.push((next_scissor, next_bits));
                }
                DrawCommand::PushRoundedClip { rect, radius } => {
                    let phys: Rect = Rect::new(
                        (rect.get_x() * scale).round(),
                        (rect.get_y() * scale).round(),
                        (rect.get_width() * scale).round().max(0.0),
                        (rect.get_height() * scale).round().max(0.0),
                    );
                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
                    let phys_rad: CornerRadius = CornerRadius::new(
                        radius.get_top_left() * scale,
                        radius.get_top_right() * scale,
                        radius.get_bottom_right() * scale,
                        radius.get_bottom_left() * scale,
                    );
                    let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
                        active_clip,
                        active_rounded_bits,
                        next_scissor,
                        phys,
                        Some(phys_rad),
                    );
                    clip_stack.push((next_scissor, next_bits));
                }
                DrawCommand::PopClip => {
                    if clip_stack.len() > 1 {
                        let _: Option<(Rect, u16)> = clip_stack.pop();
                    }
                }
                DrawCommand::FillRoundedRect {
                    rect,
                    color,
                    radius,
                    border,
                } => {
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            rect.get_x() * scale,
                            rect.get_y() * scale,
                            rect.get_width() * scale,
                            rect.get_height() * scale,
                        ],
                        clip: clip_arr,
                        color: color.to_f32_array(),
                        secondary_color: border.get_color().to_f32_array(),
                        radii: [
                            radius.get_top_left() * scale,
                            radius.get_top_right() * scale,
                            radius.get_bottom_right() * scale,
                            radius.get_bottom_left() * scale,
                        ],
                        stroke_or_blur: border.get_width() * scale,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::RoundedRect as u32,
                        reserved: 0,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0),
                    );
                }
                DrawCommand::LinearGradientRect {
                    rect,
                    gradient,
                    radius,
                } => {
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            rect.get_x() * scale,
                            rect.get_y() * scale,
                            rect.get_width() * scale,
                            rect.get_height() * scale,
                        ],
                        clip: clip_arr,
                        color: gradient.get_start_color().to_f32_array(),
                        secondary_color: gradient.get_end_color().to_f32_array(),
                        radii: [
                            radius.get_top_left() * scale,
                            radius.get_top_right() * scale,
                            radius.get_bottom_right() * scale,
                            radius.get_bottom_left() * scale,
                        ],
                        stroke_or_blur: 0.0,
                        angle_rad: gradient.get_angle_deg().to_radians(),
                        kind: GpuPrimitiveKind::Gradient as u32,
                        reserved: 0,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0),
                    );
                }
                DrawCommand::BoxShadow {
                    rect,
                    radius,
                    shadow,
                } => {
                    let blur_px: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(max_blur_px);
                    let spread_px: f32 = shadow.get_spread_radius() * scale;
                    let pad: f32 = (blur_px * 1.5 + spread_px).max(1.0);
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            (rect.get_x() + shadow.get_offset_x()) * scale - pad,
                            (rect.get_y() + shadow.get_offset_y()) * scale - pad,
                            rect.get_width() * scale + pad * 2.0,
                            rect.get_height() * scale + pad * 2.0,
                        ],
                        clip: clip_arr,
                        color: shadow.get_color().to_f32_array(),
                        secondary_color: [0.0; 4],
                        radii: [
                            radius.get_top_left() * scale,
                            radius.get_top_right() * scale,
                            radius.get_bottom_right() * scale,
                            radius.get_bottom_left() * scale,
                        ],
                        stroke_or_blur: (blur_px * 0.5).max(0.75),
                        angle_rad: pad,
                        kind: GpuPrimitiveKind::Shadow as u32,
                        reserved: 0,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0),
                    );
                }
                DrawCommand::TextRun { rect, text, style } => {
                    let wrap_w: Option<f32> = if style.get_overflow() == TextOverflow::Wrap {
                        Some(rect.get_width().max(1.0))
                    } else {
                        None
                    };
                    let layout_res: TextLayoutResult =
                        DeterministicTextMeasurer.measure(text, *style, wrap_w);
                    let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
                    let letter_sp: f32 = style.get_letter_spacing() * scale;
                    let line_h_phys: f32 = layout_res.get_line_height_px() * scale;
                    let run_w_phys: f32 = rect.get_width() * scale;
                    let text_color_u32: u32 =
                        GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
                    let Self {
                        software,
                        gpu_glyph_atlas,
                        ..
                    } = self;
                    let font_provider: NativeSystemFont = software.get_font_provider().clone();
                    let cpu_atlas: &mut GlyphAtlas = software.get_mut_glyph_atlas();
                    let base_x_phys: f32 = (rect.get_x() * scale).round();
                    let mut line_glyphs: Vec<(Option<GpuGlyphPlacement>, f32)> =
                        Vec::with_capacity(32);
                    for (line_idx, line) in layout_res.get_lines().iter().enumerate() {
                        let line_y: f32 =
                            (rect.get_y() * scale + (line_idx as f32) * line_h_phys).round();
                        line_glyphs.clear();
                        let mut actual_line_w: f32 = 0.0;
                        for ch in line.get_text().chars() {
                            if ch == ' ' || ch == '\t' {
                                let space_adv: f32 =
                                    measure_char_advance(ch, *style) * scale + letter_sp;
                                actual_line_w += space_adv;
                                line_glyphs.push((None, space_adv));
                            } else {
                                let key: GlyphKey =
                                    GlyphKey::from_text_style(ch, phys_font_px, *style);
                                let raster: &RasterizedGlyph =
                                    cpu_atlas.get_or_rasterize_with(key, &font_provider);
                                let adv_phys: f32 =
                                    (raster.get_advance() as f32).max(1.0) + letter_sp;
                                let placement: GpuGlyphPlacement =
                                    gpu_glyph_atlas.insert_or_get(key, raster);
                                actual_line_w += adv_phys;
                                line_glyphs.push((Some(placement), adv_phys));
                            }
                        }
                        let fit_scale: f32 = if run_w_phys > 1.0 && actual_line_w > run_w_phys + 1.0
                        {
                            (run_w_phys / actual_line_w).clamp(0.72, 1.0)
                        } else {
                            1.0
                        };
                        let fitted_w: f32 = actual_line_w * fit_scale;
                        let align_x: f32 = match style.get_align() {
                            TextAlign::Left => 0.0,
                            TextAlign::Center => ((run_w_phys - fitted_w) * 0.5).max(0.0),
                            TextAlign::Right => (run_w_phys - fitted_w).max(0.0),
                        };
                        let mut pen_x: f32 = base_x_phys + align_x.round();
                        for &(placement_opt, adv_phys) in line_glyphs.iter() {
                            if let Some(placement) = placement_opt
                                && placement.get_width() > 0
                                && placement.get_height() > 0
                            {
                                let gw: f32 = placement.get_width() as f32;
                                let gh: f32 = placement.get_height() as f32;
                                let glyph_y: f32 = line_y + ((line_h_phys - gh) * 0.5).round();
                                let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
                                    PrimKind::GlyphAlpha8,
                                    0,
                                    0,
                                    0,
                                );
                                let prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
                                    rect: [pen_x.round(), glyph_y, gw, gh],
                                    clip_rect: clip_arr,
                                    color_rgba: text_color_u32,
                                    aux_color_rgba: 0,
                                    uv_rect: placement.get_uv_rect(),
                                    radii_border: [0; 4],
                                    kind_flags,
                                    extra_param: 0,
                                };
                                Self::push_hybrid_primitive(
                                    &mut batches,
                                    active_clip,
                                    active_rounded_bits,
                                    prim,
                                );
                            }
                            pen_x += adv_phys * fit_scale;
                        }
                    }
                }
                DrawCommand::TextCaret {
                    text_rect,
                    content_rect,
                    caret_height,
                    color,
                    ..
                } => {
                    let caret_y: f32 = content_rect.get_y()
                        + ((content_rect.get_height() - caret_height) * 0.5).max(0.0);
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            (text_rect.get_x() * scale).round(),
                            (caret_y * scale).round(),
                            (1.5 * scale).max(1.0),
                            (caret_height * scale).max(2.0),
                        ],
                        clip: clip_arr,
                        color: color.to_f32_array(),
                        secondary_color: [0.0; 4],
                        radii: [0.5 * scale; 4],
                        stroke_or_blur: 0.0,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::RoundedRect as u32,
                        reserved: 0,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0),
                    );
                }
                DrawCommand::Image { rect, radius, .. }
                | DrawCommand::SharedImage { rect, radius, .. } => {
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            rect.get_x() * scale,
                            rect.get_y() * scale,
                            rect.get_width() * scale,
                            rect.get_height() * scale,
                        ],
                        clip: clip_arr,
                        color: [1.0, 1.0, 1.0, 1.0],
                        secondary_color: [0.0; 4],
                        radii: [
                            radius.get_top_left() * scale,
                            radius.get_top_right() * scale,
                            radius.get_bottom_right() * scale,
                            radius.get_bottom_left() * scale,
                        ],
                        stroke_or_blur: 0.0,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::TexturedQuad as u32,
                        reserved: 0,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 2, 0),
                    );
                }
                DrawCommand::SpriteRegion { rect, tint, .. } => {
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            rect.get_x() * scale,
                            rect.get_y() * scale,
                            rect.get_width() * scale,
                            rect.get_height() * scale,
                        ],
                        clip: clip_arr,
                        color: tint.to_f32_array(),
                        secondary_color: [0.0; 4],
                        radii: [0.0; 4],
                        stroke_or_blur: 0.0,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::TexturedQuad as u32,
                        reserved: 1,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 2, 0),
                    );
                }
                DrawCommand::ExternalSurface { rect, radius } => {
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            rect.get_x() * scale,
                            rect.get_y() * scale,
                            rect.get_width() * scale,
                            rect.get_height() * scale,
                        ],
                        clip: clip_arr,
                        color: [1.0, 1.0, 1.0, 1.0],
                        secondary_color: [0.0; 4],
                        radii: [
                            radius.get_top_left() * scale,
                            radius.get_top_right() * scale,
                            radius.get_bottom_right() * scale,
                            radius.get_bottom_left() * scale,
                        ],
                        stroke_or_blur: 0.0,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::ExternalSurface as u32,
                        reserved: 0,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 3, 0),
                    );
                }
                DrawCommand::Circle {
                    center,
                    radius,
                    color,
                } => {
                    let rad_px: f32 = radius * scale;
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            center.get_x() * scale - rad_px,
                            center.get_y() * scale - rad_px,
                            rad_px * 2.0,
                            rad_px * 2.0,
                        ],
                        clip: clip_arr,
                        color: color.to_f32_array(),
                        secondary_color: [0.0; 4],
                        radii: [rad_px; 4],
                        stroke_or_blur: rad_px,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::Circle as u32,
                        reserved: 0,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0),
                    );
                }
                DrawCommand::Line {
                    from,
                    to,
                    color,
                    width,
                } => {
                    let fx0: f32 = from.get_x() * scale;
                    let fy0: f32 = from.get_y() * scale;
                    let fx1: f32 = to.get_x() * scale;
                    let fy1: f32 = to.get_y() * scale;
                    let stroke_px: f32 = (width * scale).max(1.0);
                    let pad: f32 = stroke_px * 0.5 + 1.5;
                    let min_x: f32 = fx0.min(fx1) - pad;
                    let min_y: f32 = fy0.min(fy1) - pad;
                    let max_x: f32 = fx0.max(fx1) + pad;
                    let max_y: f32 = fy0.max(fy1) + pad;
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            min_x,
                            min_y,
                            (max_x - min_x).max(2.0),
                            (max_y - min_y).max(2.0),
                        ],
                        clip: clip_arr,
                        color: color.to_f32_array(),
                        secondary_color: [0.0; 4],
                        radii: [fx0, fy0, fx1, fy1],
                        stroke_or_blur: stroke_px,
                        angle_rad: (fy1 - fy0).atan2(fx1 - fx0),
                        kind: GpuPrimitiveKind::Line as u32,
                        reserved: 0,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0),
                    );
                }
                DrawCommand::Triangle { p0, p1, p2, color } => {
                    let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
                    let quad: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            min_x,
                            min_y,
                            (max_x - min_x).max(2.0),
                            (max_y - min_y).max(2.0),
                        ],
                        clip: clip_arr,
                        color: color.to_f32_array(),
                        secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
                        radii: [
                            p1.get_x() * scale,
                            p1.get_y() * scale,
                            p2.get_x() * scale,
                            p2.get_y() * scale,
                        ],
                        stroke_or_blur: 0.0,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::Triangle as u32,
                        reserved: 3,
                    };
                    Self::push_hybrid_primitive(
                        &mut batches,
                        active_clip,
                        active_rounded_bits,
                        GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0),
                    );
                }
                DrawCommand::BackdropBlur { .. } => {}
            }
        }
        let mut cpu_tiles: usize = 0;
        let mut cpu_pixels: usize = 0;
        let mut cpu_upload_bytes: usize = 0;
        let mut upload_regions: Vec<(u32, u32, u32, u32)> = Vec::new();
        if !partition.get_cpu_effect_regions().is_empty() {
            let mut sparse_damage: DamageRegion = DamageRegion::default();
            for region in partition.get_cpu_effect_regions().iter() {
                let clipped_x: f32 = region.get_x().clamp(0.0, phys_w as f32);
                let clipped_y: f32 = region.get_y().clamp(0.0, phys_h as f32);
                let clipped_w: f32 = region
                    .get_width()
                    .min((phys_w as f32 - clipped_x).max(0.0))
                    .max(0.0);
                let clipped_h: f32 = region
                    .get_height()
                    .min((phys_h as f32 - clipped_y).max(0.0))
                    .max(0.0);
                if clipped_w <= 0.0 || clipped_h <= 0.0 {
                    continue;
                }
                let tight_rect: Rect = Rect::new(clipped_x, clipped_y, clipped_w, clipped_h);
                if !damage.get_full_damage()
                    && let Some(dmg_rect) = damage.bounds_rect()
                    && tight_rect.intersect(dmg_rect).is_none()
                {
                    continue;
                }
                sparse_damage.add_rect(tight_rect);
                let tx: u32 = (clipped_x.floor() as u32).min(phys_w.saturating_sub(1));
                let ty: u32 = (clipped_y.floor() as u32).min(phys_h.saturating_sub(1));
                let tw: u32 = (clipped_w.ceil() as u32)
                    .min(phys_w.saturating_sub(tx))
                    .max(1);
                let th: u32 = (clipped_h.ceil() as u32)
                    .min(phys_h.saturating_sub(ty))
                    .max(1);
                let tile_bytes: usize = (tw as usize)
                    .saturating_mul(th as usize)
                    .saturating_mul(HYBRID_RGBA8_BYTES_PER_PIXEL);
                cpu_upload_bytes = cpu_upload_bytes.saturating_add(tile_bytes);
                upload_regions.push((tx, ty, tw, th));
                let tile_uv: [u16; 4] = encode_glyph_atlas_uv(tx, ty, tw, th, phys_w, phys_h);
                let tile_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
                    rect: [clipped_x, clipped_y, clipped_w, clipped_h],
                    clip_rect: [0.0, 0.0, phys_w as f32, phys_h as f32],
                    color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
                    aux_color_rgba: 0,
                    uv_rect: tile_uv,
                    radii_border: [0; 4],
                    kind_flags: GpuPrimitiveInstance::pack_kind_flags(
                        PrimKind::ImageTexture,
                        0,
                        2,
                        0,
                    ),
                    extra_param: 0,
                };
                Self::push_hybrid_primitive(&mut batches, full_rect, 0, tile_prim);
            }
            if sparse_damage.bounds_rect().is_some() {
                let (tiles, pixels): (usize, usize) =
                    self.get_mut_software().render(display_list, sparse_damage);
                cpu_tiles = tiles;
                cpu_pixels = pixels;
                let Self {
                    software, driver, ..
                } = self;
                let fb_pixels: &[u8] = software.get_framebuffer().get_pixels();
                let stride: usize = (phys_w as usize).saturating_mul(HYBRID_RGBA8_BYTES_PER_PIXEL);
                for (tx, ty, tw, th) in upload_regions {
                    let offset: usize = (ty as usize)
                        .saturating_mul(stride)
                        .saturating_add((tx as usize).saturating_mul(HYBRID_RGBA8_BYTES_PER_PIXEL));
                    if offset < fb_pixels.len() {
                        let _: bool = driver.upload_texture_dirty_rect(
                            GpuAtlasPixelFormat::Rgba8Unorm,
                            2,
                            (phys_w, phys_h),
                            (tx, ty, tw, th),
                            &fb_pixels[offset..],
                            stride,
                        );
                    }
                }
            }
        }
        if batches.is_empty() {
            let mut empty_batch: GpuBatch = GpuBatch::default();
            empty_batch.set_scissor(full_rect);
            batches.push(empty_batch);
        }
        let Self {
            driver,
            gpu_glyph_atlas,
            last_cpu_effect_regions,
            last_gpu_native_commands,
            last_cpu_tile_count,
            last_cpu_upload_bytes,
            last_cpu_rasterized_pixels,
            last_batches,
            ..
        } = self;
        let _: usize = gpu_glyph_atlas.flush_to_driver(driver);
        *last_cpu_effect_regions = partition.get_cpu_effect_regions().clone();
        *last_gpu_native_commands = partition.get_gpu_native_count();
        *last_cpu_tile_count = cpu_tiles;
        *last_cpu_upload_bytes = cpu_upload_bytes;
        *last_cpu_rasterized_pixels = cpu_pixels;
        let submitted: usize =
            driver.submit_batches(phys_w, phys_h, clear_color, batches.as_slice())?;
        *last_batches = batches;
        let total_pixels: usize = if cpu_pixels > 0 {
            partition
                .get_gpu_covered_pixels()
                .saturating_add(cpu_pixels)
        } else {
            partition.get_gpu_covered_pixels().max(1)
        };
        Ok((submitted.max(1), total_pixels))
    }

    /// Appends `prim` with `rounded_bits` into the active `GpuBatch` tail matching `scissor`, opening a new batch when scissor or capacity changes.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<GpuBatch>` - Output batch stream.
    /// - `Rect` - Active physical scissor rectangle.
    /// - `u16` - Packed 6-bit rounded-clip metadata bits.
    /// - `GpuPrimitiveInstance` - Compiled 64-byte GPU primitive instance.
    fn push_hybrid_primitive(
        batches: &mut Vec<GpuBatch>,
        scissor: Rect,
        rounded_bits: u16,
        prim: GpuPrimitiveInstance,
    ) {
        let clipped: GpuPrimitiveInstance = prim.with_rounded_clip_bits(rounded_bits);
        if let Some(tail) = batches.last_mut()
            && tail.get_scissor() == scissor
            && tail.get_primitives().len() < MAX_QUADS_PER_BATCH
        {
            tail.get_mut_primitives().push(clipped);
            return;
        }
        let mut next_batch: GpuBatch = GpuBatch::default();
        next_batch.set_scissor(scissor);
        next_batch.get_mut_primitives().push(clipped);
        batches.push(next_batch);
    }
}