Skip to main content

euv_core/render/hardware/
impl.rs

1use super::*;
2
3/// Packing, conversion, and compile-time ABI stride verification helpers for `GpuPrimitiveInstance`.
4impl GpuPrimitiveInstance {
5    /// Packs normalized `[r, g, b, a]` floating-point channels into little-endian RGBA8 `u32`.
6    ///
7    /// # Arguments
8    ///
9    /// - `[f32; 4]` - Normalized RGBA channels in `[0.0..=1.0]`.
10    ///
11    /// # Returns
12    ///
13    /// - `u32` - Packed RGBA8 color word (`R` in low byte, `A` in high byte).
14    #[must_use]
15    pub fn pack_rgba8_f32(rgba: [f32; 4]) -> u32 {
16        let r: u32 = (rgba[0].clamp(0.0, 1.0) * 255.0).round() as u32;
17        let g: u32 = (rgba[1].clamp(0.0, 1.0) * 255.0).round() as u32;
18        let b: u32 = (rgba[2].clamp(0.0, 1.0) * 255.0).round() as u32;
19        let a: u32 = (rgba[3].clamp(0.0, 1.0) * 255.0).round() as u32;
20        r | (g << 8) | (b << 16) | (a << 24)
21    }
22
23    /// Packs a `Color` into little-endian RGBA8 `u32`.
24    ///
25    /// # Arguments
26    ///
27    /// - `Color` - Source sRGB color with alpha.
28    ///
29    /// # Returns
30    ///
31    /// - `u32` - Packed RGBA8 color word.
32    #[must_use]
33    pub fn pack_color_rgba8(color: Color) -> u32 {
34        (color.get_r() as u32)
35            | ((color.get_g() as u32) << 8)
36            | ((color.get_b() as u32) << 16)
37            | ((color.get_a() as u32) << 24)
38    }
39
40    /// Packs a non-negative physical pixel radius into Q12.4 unsigned fixed-point (`1/16` px).
41    ///
42    /// # Arguments
43    ///
44    /// - `f32` - Physical pixel measurement (`>= 0.0`).
45    ///
46    /// # Returns
47    ///
48    /// - `u16` - Q12.4 quantized fixed-point value.
49    #[must_use]
50    pub fn pack_u16_q4(value: f32) -> u16 {
51        (value.clamp(0.0, 4095.9375) * 16.0).round() as u16
52    }
53
54    /// Returns the geometric corner-radius ceiling (half the shortest side) for a quad so oversized
55    /// full-pill radii (e.g. `999.0` logical px at high DPR) encode losslessly within Q12.4 range.
56    ///
57    /// # Arguments
58    ///
59    /// - `[f32; 4]` - Physical quad rectangle `[x, y, w, h]` (shadow quads include blur padding).
60    /// - `u32` - Primitive kind discriminant (`2` = shadow).
61    /// - `f32` - Shadow blur padding stored in the angle slot for shadow quads.
62    ///
63    /// # Returns
64    ///
65    /// - `f32` - Maximum meaningful corner radius in physical pixels.
66    #[must_use]
67    pub fn corner_radius_cap(rect: [f32; 4], kind: u32, shadow_pad: f32) -> f32 {
68        let shortest: f32 = rect[2].min(rect[3]);
69        let inner: f32 = if kind == GpuPrimitiveKind::Shadow as u32 {
70            shortest - shadow_pad * 2.0
71        } else {
72            shortest
73        };
74        (inner * 0.5).max(0.0)
75    }
76
77    /// Converts a finite `f32` into IEEE-754 binary16 (`f16`) raw bit representation.
78    ///
79    /// # Arguments
80    ///
81    /// - `f32` - Single-precision floating-point value.
82    ///
83    /// # Returns
84    ///
85    /// - `u16` - IEEE-754 binary16 encoded bits.
86    #[must_use]
87    pub fn f32_to_f16_bits(value: f32) -> u16 {
88        let bits: u32 = value.to_bits();
89        let sign: u32 = (bits >> 16) & 0x8000;
90        let exp: i32 = ((bits >> 23) & 0xFF) as i32 - 127 + 15;
91        let frac: u32 = bits & 0x007F_FFFF;
92        if exp <= 0 {
93            if exp < -10 {
94                return sign as u16;
95            }
96            let mant: u32 = (frac | 0x0080_0000) >> (1 - exp);
97            return (sign | ((mant + 0x1000) >> 13)) as u16;
98        }
99        if exp >= 31 {
100            return (sign | 0x7C00) as u16;
101        }
102        let rounded: u32 = frac + 0x1000;
103        if (rounded & 0x0080_0000) != 0 {
104            (sign | (((exp + 1) as u32) << 10)) as u16
105        } else {
106            (sign | ((exp as u32) << 10) | (rounded >> 13)) as u16
107        }
108    }
109
110    /// Packs two `f32` values into an IEEE-754 `f16x2` `u32` matching GPU `unpack2x16float` / `half2`.
111    ///
112    /// # Arguments
113    ///
114    /// - `f32` - Low-lane parameter (`stroke_or_blur`).
115    /// - `f32` - High-lane parameter (`angle_or_pad`).
116    ///
117    /// # Returns
118    ///
119    /// - `u32` - Packed `f16x2` parameter word.
120    #[must_use]
121    pub fn pack_f16x2(lo: f32, hi: f32) -> u32 {
122        (Self::f32_to_f16_bits(lo) as u32) | ((Self::f32_to_f16_bits(hi) as u32) << 16)
123    }
124
125    /// Encodes `PrimKind`, `clip_mask_or_sub`, `tex_slot`, and `layer_id` into `kind_flags`.
126    ///
127    /// # Arguments
128    ///
129    /// - `PrimKind` - Unified 8-variant primitive discriminant (`bits[0..4]`).
130    /// - `u16` - Clip-mask identifier or `VectorSubKind` (`bits[4..16]`).
131    /// - `u8` - Bound texture slot index (`bits[16..24]`).
132    /// - `u8` - Owning retained layer identifier (`bits[24..32]`).
133    ///
134    /// # Returns
135    ///
136    /// - `u32` - Packed `kind_flags` bitfield.
137    #[must_use]
138    pub const fn pack_kind_flags(
139        kind: PrimKind,
140        clip_mask_or_sub: u16,
141        tex_slot: u8,
142        layer_id: u8,
143    ) -> u32 {
144        ((kind as u32) & 0xF)
145            | (((clip_mask_or_sub as u32) & 0xFFF) << 4)
146            | ((tex_slot as u32) << 16)
147            | ((layer_id as u32) << 24)
148    }
149
150    /// Decodes the `PrimKind` variant stored in `kind_flags` bits `[0..4]`.
151    ///
152    /// # Returns
153    ///
154    /// - `PrimKind` - Decoded primitive variant.
155    #[must_use]
156    pub fn prim_kind(&self) -> PrimKind {
157        match self.get_kind_flags() & 0xF {
158            1 => PrimKind::LinearGradientRect,
159            2 => PrimKind::Shadow,
160            3 => PrimKind::GlyphAlpha8,
161            4 => PrimKind::GlyphColorRgba8,
162            5 => PrimKind::ImageTexture,
163            6 => PrimKind::VectorShape,
164            7 => PrimKind::ExternalGpuSurface,
165            _ => PrimKind::RoundedRect,
166        }
167    }
168
169    /// Returns the `clip_mask_id` / `VectorSubKind` stored in `kind_flags` bits `[4..16]`.
170    ///
171    /// # Returns
172    ///
173    /// - `u16` - Encoded clip-mask ID or vector sub-kind.
174    #[must_use]
175    pub fn clip_or_sub_kind(&self) -> u16 {
176        ((self.get_kind_flags() >> 4) & 0xFFF) as u16
177    }
178
179    /// Returns the texture slot index stored in `kind_flags` bits `[16..24]`.
180    ///
181    /// # Returns
182    ///
183    /// - `u8` - Bound texture slot.
184    #[must_use]
185    pub fn texture_slot(&self) -> u8 {
186        ((self.get_kind_flags() >> 16) & 0xFF) as u8
187    }
188
189    /// Returns the retained layer identifier stored in `kind_flags` bits `[24..32]`.
190    ///
191    /// # Returns
192    ///
193    /// - `u8` - Owning layer identifier.
194    #[must_use]
195    pub fn layer_id(&self) -> u8 {
196        ((self.get_kind_flags() >> 24) & 0xFF) as u8
197    }
198
199    /// Compiles a 64-byte `GpuPrimitiveInstance` from a legacy 96-byte `GpuQuadInstance`.
200    ///
201    /// # Arguments
202    ///
203    /// - `&GpuQuadInstance` - Source quad descriptor.
204    /// - `u8` - Active texture slot index.
205    /// - `u8` - Active retained layer identifier.
206    ///
207    /// # Returns
208    ///
209    /// - `Self` - Tightly packed 64-byte GPU primitive instance.
210    #[must_use]
211    pub fn from_quad_instance(quad: &GpuQuadInstance, tex_slot: u8, layer_id: u8) -> Self {
212        const {
213            assert!(size_of::<GpuPrimitiveInstance>() == GPU_PRIMITIVE_INSTANCE_BYTES);
214        }
215        let rect: [f32; 4] = quad.get_rect();
216        let clip_rect: [f32; 4] = quad.get_clip();
217        let color_rgba: u32 = Self::pack_rgba8_f32(quad.get_color());
218        let mut aux_color_rgba: u32 = Self::pack_rgba8_f32(quad.get_secondary_color());
219        let mut uv_rect: [u16; 4] = [0, 0, u16::MAX, u16::MAX];
220        let src_radii: [f32; 4] = quad.get_radii();
221        let radius_cap: f32 = Self::corner_radius_cap(rect, quad.get_kind(), quad.get_angle_rad());
222        let mut radii_border: [u16; 4] = [
223            Self::pack_u16_q4(src_radii[0].min(radius_cap)),
224            Self::pack_u16_q4(src_radii[1].min(radius_cap)),
225            Self::pack_u16_q4(src_radii[2].min(radius_cap)),
226            Self::pack_u16_q4(src_radii[3].min(radius_cap)),
227        ];
228        let (prim_kind, sub_kind): (PrimKind, u16) = match quad.get_kind() {
229            1 => (PrimKind::LinearGradientRect, 0),
230            2 => (PrimKind::Shadow, 0),
231            3 => {
232                let is_color_glyph: bool = (quad.get_reserved() & 0x8000_0000) != 0;
233                if is_color_glyph {
234                    (PrimKind::GlyphColorRgba8, 0)
235                } else {
236                    (PrimKind::GlyphAlpha8, 0)
237                }
238            }
239            4 => (PrimKind::ImageTexture, 0),
240            5 => (PrimKind::VectorShape, VectorSubKind::Circle as u16),
241            6 => {
242                let inv_w: f32 = 1.0 / rect[2].max(1.0);
243                let inv_h: f32 = 1.0 / rect[3].max(1.0);
244                let r: [f32; 4] = quad.get_radii();
245                uv_rect = [
246                    (((r[0] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
247                    (((r[1] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
248                    (((r[2] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
249                    (((r[3] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
250                ];
251                radii_border = [0; 4];
252                (PrimKind::VectorShape, VectorSubKind::Line as u16)
253            }
254            7 => {
255                let inv_w: f32 = 1.0 / rect[2].max(1.0);
256                let inv_h: f32 = 1.0 / rect[3].max(1.0);
257                let p0: [f32; 4] = quad.get_secondary_color();
258                let r: [f32; 4] = quad.get_radii();
259                aux_color_rgba = Self::pack_rgba8_f32([
260                    ((p0[0] - rect[0]) * inv_w).clamp(0.0, 1.0),
261                    ((p0[1] - rect[1]) * inv_h).clamp(0.0, 1.0),
262                    0.0,
263                    1.0,
264                ]);
265                uv_rect = [
266                    (((r[0] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
267                    (((r[1] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
268                    (((r[2] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
269                    (((r[3] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
270                ];
271                radii_border = [0; 4];
272                (PrimKind::VectorShape, VectorSubKind::Triangle as u16)
273            }
274            8 => (PrimKind::ExternalGpuSurface, 0),
275            _ => (PrimKind::RoundedRect, 0),
276        };
277        let kind_flags: u32 = Self::pack_kind_flags(prim_kind, sub_kind, tex_slot, layer_id);
278        let extra_param: u32 = Self::pack_f16x2(quad.get_stroke_or_blur(), quad.get_angle_rad());
279        Self {
280            rect,
281            clip_rect,
282            color_rgba,
283            aux_color_rgba,
284            uv_rect,
285            radii_border,
286            kind_flags,
287            extra_param,
288        }
289    }
290
291    /// Constructs a 64-byte `PrimKind::ExternalGpuSurface` instance for shared-device 3D game or video textures.
292    ///
293    /// # Arguments
294    ///
295    /// - `Rect` - Destination physical bounds.
296    /// - `Rect` - Active physical scissor clip rectangle.
297    /// - `[f32; 4]` - Per-corner physical clip radii `[tl, tr, br, bl]`.
298    /// - `[u16; 4]` - Normalized texture UV rectangle `[u0, v0, u1, v1]`.
299    /// - `u8` - External GPU texture slot.
300    /// - `u8` - Retained layer identifier.
301    ///
302    /// # Returns
303    ///
304    /// - `Self` - Packed 64-byte external GPU surface primitive instance.
305    #[must_use]
306    pub fn external_surface(
307        bounds: Rect,
308        clip: Rect,
309        radii: [f32; 4],
310        uv_rect: [u16; 4],
311        tex_slot: u8,
312        layer_id: u8,
313    ) -> Self {
314        Self {
315            rect: [
316                bounds.get_x(),
317                bounds.get_y(),
318                bounds.get_width(),
319                bounds.get_height(),
320            ],
321            clip_rect: [clip.get_x(), clip.get_y(), clip.right(), clip.bottom()],
322            color_rgba: 0xFFFF_FFFF,
323            aux_color_rgba: 0,
324            uv_rect,
325            radii_border: [
326                Self::pack_u16_q4(radii[0]),
327                Self::pack_u16_q4(radii[1]),
328                Self::pack_u16_q4(radii[2]),
329                Self::pack_u16_q4(radii[3]),
330            ],
331            kind_flags: Self::pack_kind_flags(PrimKind::ExternalGpuSurface, 0, tex_slot, layer_id),
332            extra_param: 0,
333        }
334    }
335}
336
337/// Construction helper for `GpuLayerUniform`.
338impl GpuLayerUniform {
339    /// Creates a 16-byte layer uniform carrying physical viewport dimensions and scroll translation.
340    ///
341    /// # Arguments
342    ///
343    /// - `f32` - Physical viewport width in pixels.
344    /// - `f32` - Physical viewport height in pixels.
345    /// - `[f32; 2]` - Retained layer scroll offset `[scroll_x, scroll_y]` in physical pixels.
346    ///
347    /// # Returns
348    ///
349    /// - `Self` - Packed 16-byte GPU layer uniform.
350    #[must_use]
351    pub fn new(viewport_w: f32, viewport_h: f32, scroll_offset: [f32; 2]) -> Self {
352        const {
353            assert!(size_of::<GpuLayerUniform>() == GPU_LAYER_UNIFORM_BYTES);
354        }
355        Self {
356            viewport_size: [viewport_w.max(1.0), viewport_h.max(1.0)],
357            scroll_offset,
358        }
359    }
360}
361
362/// `GpuDriver` implementation for `RecordingGpuDriver`.
363impl GpuDriver for RecordingGpuDriver {
364    /// Returns the configured backend tag.
365    ///
366    /// # Arguments
367    ///
368    /// - `&Self` - Driver reference.
369    ///
370    /// # Returns
371    ///
372    /// - `GraphicsBackend` - Active backend tag.
373    fn backend(&self) -> GraphicsBackend {
374        self.get_backend_kind()
375    }
376
377    /// Selects the canonical native shader source for this backend.
378    ///
379    /// # Arguments
380    ///
381    /// - `&Self` - Driver reference.
382    ///
383    /// # Returns
384    ///
385    /// - `&'static str` - Native shader source string.
386    fn shader_source(&self) -> &'static str {
387        match self.get_backend_kind() {
388            GraphicsBackend::Metal => MSL_UI_SHADER,
389            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => HLSL_UI_SHADER,
390            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => GLSL_ES3_UI_FRAGMENT_SHADER,
391            GraphicsBackend::WebGpu
392            | GraphicsBackend::Vulkan
393            | GraphicsBackend::SoftwareCpu
394            | GraphicsBackend::Canvas2d
395            | GraphicsBackend::Headless => WGSL_UI_SHADER,
396        }
397    }
398
399    /// Records submitted GPU batches and returns draw-call count.
400    ///
401    /// # Arguments
402    ///
403    /// - `&Self` - Mutable driver.
404    /// - `u32` - Surface width.
405    /// - `u32` - Surface height.
406    /// - `Color` - Clear color.
407    /// - `&[GpuBatch]` - Ordered batches.
408    ///
409    /// # Returns
410    ///
411    /// - `Result<usize, PlatformError>` - Submitted batch count.
412    fn submit_batches(
413        &mut self,
414        _width: u32,
415        _height: u32,
416        clear_color: Color,
417        batches: &[GpuBatch],
418    ) -> Result<usize, PlatformError> {
419        let count: usize = batches.len();
420        let instances: usize = batches.iter().fold(0_usize, |acc: usize, b: &GpuBatch| {
421            acc + b.get_instances().len()
422        });
423        self.set_last_clear(clear_color);
424        self.set_last_instance_count(instances);
425        self.set_total_draw_calls(self.get_total_draw_calls().saturating_add(count));
426        Ok(count)
427    }
428}
429
430/// Instanced batch builder, order-preserving coalescer, and telemetry methods for `HardwareRenderer`.
431impl HardwareRenderer {
432    /// Creates a hardware renderer bound to `backend` with optional deterministic pixel readback.
433    ///
434    /// # Arguments
435    ///
436    /// - `GraphicsBackend` - Selected GPU backend.
437    /// - `u32` - Initial physical width.
438    /// - `u32` - Initial physical height.
439    /// - `RenderConfig` - Rendering configuration.
440    /// - `bool` - Whether software readback mirror is enabled.
441    ///
442    /// # Returns
443    ///
444    /// - `Self` - Configured hardware renderer.
445    #[must_use]
446    pub fn with_backend(
447        backend: GraphicsBackend,
448        width: u32,
449        height: u32,
450        config: RenderConfig,
451        enable_readback: bool,
452    ) -> Self {
453        Self::with_backend_and_font(
454            backend,
455            width,
456            height,
457            config,
458            enable_readback,
459            NativeSystemFont::deterministic(),
460        )
461    }
462
463    /// Creates a hardware renderer bound to `backend` with an explicit font provider for readback.
464    ///
465    /// # Arguments
466    ///
467    /// - `GraphicsBackend` - Selected GPU backend.
468    /// - `u32` - Initial physical width.
469    /// - `u32` - Initial physical height.
470    /// - `RenderConfig` - Rendering configuration.
471    /// - `bool` - Whether software readback mirror is enabled.
472    /// - `NativeSystemFont` - Font provider used by the software readback mirror.
473    ///
474    /// # Returns
475    ///
476    /// - `Self` - Configured hardware renderer.
477    #[must_use]
478    pub fn with_backend_and_font(
479        backend: GraphicsBackend,
480        width: u32,
481        height: u32,
482        config: RenderConfig,
483        enable_readback: bool,
484        font_provider: NativeSystemFont,
485    ) -> Self {
486        let driver: NativeGpuDriver = NativeGpuDriver::probe(backend);
487        let mut batches: Vec<GpuBatch> = Vec::with_capacity(16);
488        for _ in 0..8usize {
489            let mut batch: GpuBatch = GpuBatch::default();
490            batch.get_mut_instances().reserve(256);
491            batch.get_mut_primitives().reserve(256);
492            batches.push(batch);
493        }
494        Self {
495            driver,
496            batches,
497            active_batches: 0,
498            clip_stack: Vec::with_capacity(16),
499            last_submitted_batches: 0,
500            last_coalesced_merges: 0,
501            last_culled_instances: 0,
502            last_uploaded_instances: 0,
503            last_uploaded_bytes: 0,
504            readback: SoftwareRenderer::with_font_provider(width, height, config, font_provider),
505            enable_readback,
506            resource_ring: GpuResourceRing::default(),
507            direct_gpu_frames: 0,
508            cpu_readback_frames: 0,
509            last_cpu_rgba_upload_bytes: 0,
510            has_unsupported_effect: false,
511            last_fence_id: 0,
512            blur_passes: Vec::with_capacity(8),
513            active_scroll_offset: [0.0, 0.0],
514            active_layer_id: 0,
515            last_uploaded_primitive_bytes: 0,
516        }
517    }
518
519    /// Captures an on-demand CPU reference framebuffer readback without enabling steady-state CPU mirroring.
520    ///
521    /// # Arguments
522    ///
523    /// - `&Self` - Mutable hardware renderer.
524    /// - `&DisplayList` - Display list to rasterize through the CPU reference backend.
525    /// - `DamageRegion` - Damage region to rasterize.
526    ///
527    /// # Returns
528    ///
529    /// - `&Framebuffer` - Rendered reference RGBA8 framebuffer.
530    pub fn capture_reference_readback(
531        &mut self,
532        display_list: &DisplayList,
533        damage: DamageRegion,
534    ) -> &Framebuffer {
535        let (_, _): (usize, usize) = self.get_mut_readback().render(display_list, damage);
536        self.get_readback().get_framebuffer()
537    }
538
539    /// Signals completion of GPU submission `fence_id` to release staging ring slots and reclaim deferred resources.
540    ///
541    /// # Arguments
542    ///
543    /// - `&Self` - Mutable hardware renderer.
544    /// - `u64` - Completed monotonic GPU fence identifier.
545    ///
546    /// # Returns
547    ///
548    /// - `usize` - Number of deferred GPU resources reclaimed.
549    pub fn complete_gpu_fence(&mut self, fence_id: u64) -> usize {
550        self.get_mut_resource_ring().complete_fence(fence_id)
551    }
552
553    /// Trims invisible persistent GPU scroll tile caches under memory pressure according to `retain_ratio`.
554    ///
555    /// # Arguments
556    ///
557    /// - `&Self` - Mutable hardware renderer.
558    /// - `f32` - Retained budget fraction in `(0.0..=1.0]`.
559    ///
560    /// # Returns
561    ///
562    /// - `usize` - Number of cold scroll tiles evicted to fence-deferred reclamation.
563    pub fn trim_gpu_caches(&mut self, retain_ratio: f32) -> usize {
564        self.get_mut_resource_ring()
565            .apply_retention_ratio(retain_ratio)
566    }
567
568    /// Returns latest-frame GPU batching and upload telemetry `(batches, coalesced_merges, culled_instances, uploaded_instances, uploaded_bytes)`.
569    ///
570    /// # Arguments
571    ///
572    /// - `&Self` - Hardware renderer reference.
573    ///
574    /// # Returns
575    ///
576    /// - `(usize, usize, usize, usize, usize)` - Latest frame batching and upload telemetry tuple.
577    #[must_use]
578    pub fn last_frame_telemetry(&self) -> (usize, usize, usize, usize, usize) {
579        (
580            self.get_last_submitted_batches(),
581            self.get_last_coalesced_merges(),
582            self.get_last_culled_instances(),
583            self.get_last_uploaded_instances(),
584            self.get_last_uploaded_bytes(),
585        )
586    }
587
588    /// Returns the slice of active `GpuBatch` submissions populated for the latest rendered frame.
589    ///
590    /// # Arguments
591    ///
592    /// - `&Self` - Hardware renderer reference.
593    ///
594    /// # Returns
595    ///
596    /// - `&[GpuBatch]` - Active order-preserving GPU draw batches.
597    #[must_use]
598    pub fn active_batches_slice(&self) -> &[GpuBatch] {
599        let active: usize = self.get_active_batches().min(self.get_batches().len());
600        &self.get_batches()[..active]
601    }
602
603    /// Computes a deterministic 64-bit FNV-1a hash over all compiled GPU batch instances.
604    ///
605    /// # Arguments
606    ///
607    /// - `&Self` - Hardware renderer reference.
608    ///
609    /// # Returns
610    ///
611    /// - `u64` - Deterministic batch geometry hash.
612    #[must_use]
613    pub fn batch_hash(&self) -> u64 {
614        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
615        let active: usize = self.get_active_batches().min(self.get_batches().len());
616        for batch in self.get_batches()[..active].iter() {
617            for inst in batch.get_instances().iter() {
618                for v in inst
619                    .get_rect()
620                    .iter()
621                    .chain(inst.get_color().iter())
622                    .chain(inst.get_radii().iter())
623                {
624                    hash ^= v.to_bits() as u64;
625                    hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
626                }
627            }
628        }
629        hash
630    }
631
632    /// Returns `true` when physical quad `quad = [x, y, w, h]` lies completely inside `container`.
633    ///
634    /// # Arguments
635    ///
636    /// - `[f32; 4]` - Physical quad bounds `[x, y, width, height]`.
637    /// - `Rect` - Enclosing physical clip rectangle.
638    ///
639    /// # Returns
640    ///
641    /// - `bool` - True when no fragment of `quad` extends outside `container`.
642    #[inline(always)]
643    #[must_use]
644    fn quad_inside_rect(quad: [f32; 4], container: Rect) -> bool {
645        let qx0: f32 = quad[0];
646        let qy0: f32 = quad[1];
647        let qx1: f32 = qx0 + quad[2];
648        let qy1: f32 = qy0 + quad[3];
649        let x_in: bool = qx0 >= container.get_x() && qx1 <= container.right();
650        let y_in: bool = qy0 >= container.get_y() && qy1 <= container.bottom();
651        container.get_width() > 0.0 && container.get_height() > 0.0 && x_in && y_in
652    }
653
654    /// Returns `true` when `quad` intersects `clip` with strictly positive area.
655    ///
656    /// # Arguments
657    ///
658    /// - `[f32; 4]` - Physical quad bounds `[x, y, width, height]`.
659    /// - `Rect` - Active physical scissor clip.
660    ///
661    /// # Returns
662    ///
663    /// - `bool` - True when at least part of `quad` falls inside `clip`.
664    #[inline(always)]
665    #[must_use]
666    fn quad_intersects_clip(quad: [f32; 4], clip: Rect) -> bool {
667        let qw: f32 = quad[2];
668        let qh: f32 = quad[3];
669        let quad_empty: bool = qw <= 0.0 || qh <= 0.0;
670        let clip_empty: bool = clip.get_width() <= 0.0 || clip.get_height() <= 0.0;
671        if quad_empty || clip_empty {
672            return false;
673        }
674        let qx0: f32 = quad[0];
675        let qy0: f32 = quad[1];
676        let qx1: f32 = qx0 + qw;
677        let qy1: f32 = qy0 + qh;
678        let x_hit: bool = qx1 > clip.get_x() && qx0 < clip.right();
679        let y_hit: bool = qy1 > clip.get_y() && qy0 < clip.bottom();
680        x_hit && y_hit
681    }
682
683    /// Returns `true` when `inner` lies completely inside `outer`.
684    ///
685    /// # Arguments
686    ///
687    /// - `Rect` - Candidate inner rectangle.
688    /// - `Rect` - Candidate outer enclosing rectangle.
689    ///
690    /// # Returns
691    ///
692    /// - `bool` - True when `inner` is contained inside `outer`.
693    #[inline(always)]
694    #[must_use]
695    fn rect_inside_rect(inner: Rect, outer: Rect) -> bool {
696        let x_in: bool = inner.get_x() >= outer.get_x() && inner.right() <= outer.right();
697        let y_in: bool = inner.get_y() >= outer.get_y() && inner.bottom() <= outer.bottom();
698        x_in && y_in
699    }
700
701    /// Returns the union bounding box of `existing` and physical quad `quad = [x, y, w, h]`.
702    ///
703    /// # Arguments
704    ///
705    /// - `Rect` - Existing bounding box.
706    /// - `[f32; 4]` - Newly appended quad bounds `[x, y, width, height]`.
707    ///
708    /// # Returns
709    ///
710    /// - `Rect` - Enclosing union rectangle.
711    #[inline(always)]
712    #[must_use]
713    fn union_rect_quad(existing: Rect, quad: [f32; 4]) -> Rect {
714        let x0: f32 = existing.get_x().min(quad[0]);
715        let y0: f32 = existing.get_y().min(quad[1]);
716        let x1: f32 = existing.right().max(quad[0] + quad[2]);
717        let y1: f32 = existing.bottom().max(quad[1] + quad[3]);
718        Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
719    }
720
721    /// Compiles `display_list` into order-preserving coalesced GPU instanced batches and submits them to the GPU driver.
722    ///
723    /// # Arguments
724    ///
725    /// - `&Self` - Mutable hardware renderer.
726    /// - `&DisplayList` - Backend-agnostic draw command stream.
727    /// - `DamageRegion` - Active damage region for readback mirroring.
728    ///
729    /// # Returns
730    ///
731    /// - `Result<(usize, usize), PlatformError>` - Tuple of `(draw_batches, pixels_shaded)`.
732    pub fn render(
733        &mut self,
734        display_list: &DisplayList,
735        damage: DamageRegion,
736    ) -> Result<(usize, usize), PlatformError> {
737        let scale: f32 = display_list.get_scale_factor().max(0.5);
738        let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
739        let phys_h: u32 =
740            ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
741        let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
742        let full_entry: GpuClipEntry = GpuClipEntry {
743            scissor: full_clip,
744            safe_inner: full_clip,
745        };
746        let Self {
747            driver,
748            batches,
749            active_batches,
750            clip_stack,
751            last_submitted_batches,
752            last_coalesced_merges,
753            last_culled_instances,
754            last_uploaded_instances,
755            last_uploaded_bytes,
756            readback,
757            enable_readback,
758            resource_ring,
759            direct_gpu_frames,
760            cpu_readback_frames,
761            last_cpu_rgba_upload_bytes,
762            has_unsupported_effect,
763            last_fence_id,
764            blur_passes,
765            active_scroll_offset,
766            active_layer_id,
767            last_uploaded_primitive_bytes,
768        } = self;
769        clip_stack.clear();
770        clip_stack.push(full_entry);
771        blur_passes.clear();
772        *active_batches = 0;
773        *has_unsupported_effect = false;
774        let layer_scroll: [f32; 2] = *active_scroll_offset;
775        let layer_id: u8 = *active_layer_id;
776        let gpu_supports_blur: bool = driver.supports_backdrop_blur_pass();
777        let mut tail_state: GpuBatchCoalesceState = GpuBatchCoalesceState {
778            scroll_offset: layer_scroll,
779            layer_id,
780            ..GpuBatchCoalesceState::default()
781        };
782        let mut coalesced_merges: usize = 0;
783        let mut culled_instances: usize = 0;
784        let mut uploaded_instances: usize = 0;
785        let mut clear_color: Color = COLOR_WHITE;
786        for cmd in display_list.get_commands().iter() {
787            let clip_entry: GpuClipEntry = clip_stack.last().copied().unwrap_or(full_entry);
788            let active_clip: Rect = clip_entry.scissor;
789            match cmd {
790                DrawCommand::Clear(c) => {
791                    clear_color = *c;
792                }
793                DrawCommand::PushClip(rect) => {
794                    let phys: Rect = snap_physical_rect(*rect, scale);
795                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
796                    let next_safe: Rect = clip_entry.safe_inner.intersect(phys).unwrap_or_default();
797                    clip_stack.push(GpuClipEntry {
798                        scissor: next_scissor,
799                        safe_inner: next_safe,
800                    });
801                }
802                DrawCommand::PushRoundedClip { rect, radius } => {
803                    let phys: Rect = snap_physical_rect(*rect, scale);
804                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
805                    let max_r: f32 = (radius.max_radius() * scale).ceil();
806                    let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
807                    let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
808                    let rounded_safe: Rect =
809                        Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
810                    let next_safe: Rect = clip_entry
811                        .safe_inner
812                        .intersect(rounded_safe)
813                        .unwrap_or_default();
814                    clip_stack.push(GpuClipEntry {
815                        scissor: next_scissor,
816                        safe_inner: next_safe,
817                    });
818                }
819                DrawCommand::PopClip => {
820                    if clip_stack.len() > 1 {
821                        let _: Option<GpuClipEntry> = clip_stack.pop();
822                    }
823                }
824                DrawCommand::FillRoundedRect {
825                    rect,
826                    color,
827                    radius,
828                    border,
829                } => {
830                    let snapped: Rect = snap_physical_rect(*rect, scale);
831                    let quad: [f32; 4] = [
832                        snapped.get_x(),
833                        snapped.get_y(),
834                        snapped.get_width(),
835                        snapped.get_height(),
836                    ];
837                    if !Self::quad_intersects_clip(quad, active_clip) {
838                        culled_instances += 1;
839                        continue;
840                    }
841                    let bw: f32 = if border.get_width() > 0.0 {
842                        (border.get_width() * scale).max(1.0)
843                    } else {
844                        0.0
845                    };
846                    let inst: GpuQuadInstance = GpuQuadInstance {
847                        rect: quad,
848                        clip: [
849                            active_clip.get_x(),
850                            active_clip.get_y(),
851                            active_clip.right(),
852                            active_clip.bottom(),
853                        ],
854                        color: color.to_f32_array(),
855                        secondary_color: border.get_color().to_f32_array(),
856                        radii: [
857                            radius.get_top_left() * scale,
858                            radius.get_top_right() * scale,
859                            radius.get_bottom_right() * scale,
860                            radius.get_bottom_left() * scale,
861                        ],
862                        stroke_or_blur: bw,
863                        angle_rad: 0.0,
864                        kind: GpuPrimitiveKind::RoundedRect as u32,
865                        reserved: 0,
866                    };
867                    Self::push_instance_coalesced(
868                        batches,
869                        active_batches,
870                        &mut tail_state,
871                        clip_entry,
872                        inst,
873                        &mut coalesced_merges,
874                    );
875                    uploaded_instances += 1;
876                }
877                DrawCommand::LinearGradientRect {
878                    rect,
879                    gradient,
880                    radius,
881                } => {
882                    let snapped: Rect = snap_physical_rect(*rect, scale);
883                    let quad: [f32; 4] = [
884                        snapped.get_x(),
885                        snapped.get_y(),
886                        snapped.get_width(),
887                        snapped.get_height(),
888                    ];
889                    if !Self::quad_intersects_clip(quad, active_clip) {
890                        culled_instances += 1;
891                        continue;
892                    }
893                    let inst: GpuQuadInstance = GpuQuadInstance {
894                        rect: quad,
895                        clip: [
896                            active_clip.get_x(),
897                            active_clip.get_y(),
898                            active_clip.right(),
899                            active_clip.bottom(),
900                        ],
901                        color: gradient.get_start_color().to_f32_array(),
902                        secondary_color: gradient.get_end_color().to_f32_array(),
903                        radii: [
904                            radius.get_top_left() * scale,
905                            radius.get_top_right() * scale,
906                            radius.get_bottom_right() * scale,
907                            radius.get_bottom_left() * scale,
908                        ],
909                        stroke_or_blur: 0.0,
910                        angle_rad: gradient.get_angle_deg().to_radians(),
911                        kind: GpuPrimitiveKind::Gradient as u32,
912                        reserved: 0,
913                    };
914                    Self::push_instance_coalesced(
915                        batches,
916                        active_batches,
917                        &mut tail_state,
918                        clip_entry,
919                        inst,
920                        &mut coalesced_merges,
921                    );
922                    uploaded_instances += 1;
923                }
924                DrawCommand::BoxShadow {
925                    rect,
926                    radius,
927                    shadow,
928                } => {
929                    let spread: f32 = shadow.get_spread_radius() * scale;
930                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
931                    let sigma: f32 = (blur * 0.5).max(0.75);
932                    let pad: f32 = (sigma * 3.0).ceil();
933                    let base_rect: Rect = snap_physical_rect(*rect, scale);
934                    let caster_x: f32 =
935                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
936                    let caster_y: f32 =
937                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
938                    let caster_w: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
939                    let caster_h: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
940                    let quad: [f32; 4] = [
941                        caster_x - pad,
942                        caster_y - pad,
943                        caster_w + pad * 2.0,
944                        caster_h + pad * 2.0,
945                    ];
946                    if !Self::quad_intersects_clip(quad, active_clip) {
947                        culled_instances += 1;
948                        continue;
949                    }
950                    let inst: GpuQuadInstance = GpuQuadInstance {
951                        rect: quad,
952                        clip: [
953                            active_clip.get_x(),
954                            active_clip.get_y(),
955                            active_clip.right(),
956                            active_clip.bottom(),
957                        ],
958                        color: shadow.get_color().to_f32_array(),
959                        secondary_color: [0.0; 4],
960                        radii: [
961                            (radius.get_top_left() * scale + spread).max(0.0),
962                            (radius.get_top_right() * scale + spread).max(0.0),
963                            (radius.get_bottom_right() * scale + spread).max(0.0),
964                            (radius.get_bottom_left() * scale + spread).max(0.0),
965                        ],
966                        stroke_or_blur: sigma,
967                        angle_rad: pad,
968                        kind: GpuPrimitiveKind::Shadow as u32,
969                        reserved: 0,
970                    };
971                    Self::push_instance_coalesced(
972                        batches,
973                        active_batches,
974                        &mut tail_state,
975                        clip_entry,
976                        inst,
977                        &mut coalesced_merges,
978                    );
979                    uploaded_instances += 1;
980                }
981                DrawCommand::BackdropBlur {
982                    rect,
983                    radius,
984                    blur_radius,
985                } => {
986                    if !gpu_supports_blur {
987                        *has_unsupported_effect = true;
988                    }
989                    let snapped: Rect = snap_physical_rect(*rect, scale);
990                    let quad: [f32; 4] = [
991                        snapped.get_x(),
992                        snapped.get_y(),
993                        snapped.get_width(),
994                        snapped.get_height(),
995                    ];
996                    if !Self::quad_intersects_clip(quad, active_clip) {
997                        culled_instances += 1;
998                        continue;
999                    }
1000                    let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 96.0);
1001                    let radii_px: [f32; 4] = [
1002                        radius.get_top_left() * scale,
1003                        radius.get_top_right() * scale,
1004                        radius.get_bottom_right() * scale,
1005                        radius.get_bottom_left() * scale,
1006                    ];
1007                    let halo: Rect = Rect::new(
1008                        (snapped.get_x() - phys_blur).max(0.0),
1009                        (snapped.get_y() - phys_blur).max(0.0),
1010                        (snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
1011                        (snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
1012                    );
1013                    blur_passes.push(GpuBackdropBlurPass {
1014                        bounds: snapped,
1015                        input_bounds: halo,
1016                        clip_rect: active_clip,
1017                        radii: radii_px,
1018                        blur_radius: phys_blur,
1019                        layer_id,
1020                    });
1021                    let inst: GpuQuadInstance = GpuQuadInstance {
1022                        rect: quad,
1023                        clip: [
1024                            active_clip.get_x(),
1025                            active_clip.get_y(),
1026                            active_clip.right(),
1027                            active_clip.bottom(),
1028                        ],
1029                        color: [1.0, 1.0, 1.0, 1.0],
1030                        secondary_color: [0.0; 4],
1031                        radii: radii_px,
1032                        stroke_or_blur: phys_blur,
1033                        angle_rad: 0.0,
1034                        kind: GpuPrimitiveKind::BackdropBlur as u32,
1035                        reserved: 0,
1036                    };
1037                    Self::push_instance_coalesced(
1038                        batches,
1039                        active_batches,
1040                        &mut tail_state,
1041                        clip_entry,
1042                        inst,
1043                        &mut coalesced_merges,
1044                    );
1045                    uploaded_instances += 1;
1046                }
1047                DrawCommand::TextRun { rect, text, style } => {
1048                    let quad: [f32; 4] = [
1049                        rect.get_x() * scale,
1050                        rect.get_y() * scale,
1051                        rect.get_width() * scale,
1052                        rect.get_height() * scale,
1053                    ];
1054                    if !Self::quad_intersects_clip(quad, active_clip) {
1055                        culled_instances += 1;
1056                        continue;
1057                    }
1058                    let glyph_count: usize = if text.is_ascii() {
1059                        text.as_bytes()
1060                            .iter()
1061                            .filter(|b: &&u8| **b != b' ')
1062                            .count()
1063                            .max(1)
1064                    } else {
1065                        text.chars().filter(|c: &char| *c != ' ').count().max(1)
1066                    };
1067                    let inst: GpuQuadInstance = GpuQuadInstance {
1068                        rect: quad,
1069                        clip: [
1070                            active_clip.get_x(),
1071                            active_clip.get_y(),
1072                            active_clip.right(),
1073                            active_clip.bottom(),
1074                        ],
1075                        color: style.get_color().to_f32_array(),
1076                        secondary_color: [0.0; 4],
1077                        radii: [0.0; 4],
1078                        stroke_or_blur: style.get_font_size() * scale,
1079                        angle_rad: 0.0,
1080                        kind: GpuPrimitiveKind::Glyph as u32,
1081                        reserved: glyph_count as u32,
1082                    };
1083                    Self::push_instance_coalesced(
1084                        batches,
1085                        active_batches,
1086                        &mut tail_state,
1087                        clip_entry,
1088                        inst,
1089                        &mut coalesced_merges,
1090                    );
1091                    uploaded_instances += 1;
1092                }
1093                DrawCommand::TextCaret {
1094                    text_rect,
1095                    content_rect,
1096                    text,
1097                    style,
1098                    caret_height,
1099                    color,
1100                    multiline,
1101                } => {
1102                    if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
1103                        culled_instances += 1;
1104                        continue;
1105                    }
1106                    let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
1107                        text,
1108                        *style,
1109                        if *multiline {
1110                            Some(content_rect.get_width().max(1.0))
1111                        } else {
1112                            None
1113                        },
1114                    );
1115                    let last_w: f32 = meas
1116                        .get_lines()
1117                        .last()
1118                        .map(TextLine::get_width)
1119                        .unwrap_or(0.0);
1120                    let line_idx: usize = meas.get_lines().len().saturating_sub(1);
1121                    let trailing_gap: f32 = if last_w > 0.0 { 1.5 } else { 0.0 };
1122                    let min_x: f32 = content_rect.get_x();
1123                    let max_x: f32 = (content_rect.right() - 2.0).max(min_x);
1124                    let caret_x: f32 = (text_rect.get_x() + last_w + trailing_gap)
1125                        .min(max_x)
1126                        .max(min_x);
1127                    let caret_y: f32 = if *multiline {
1128                        (content_rect.get_y()
1129                            + (line_idx as f32) * meas.get_line_height_px()
1130                            + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
1131                        .min(content_rect.bottom() - caret_height)
1132                        .max(content_rect.get_y())
1133                    } else {
1134                        content_rect.get_y()
1135                            + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
1136                    };
1137                    let quad: [f32; 4] = [
1138                        caret_x * scale,
1139                        caret_y * scale,
1140                        (1.5 * scale).max(1.0),
1141                        (caret_height * scale).max(2.0),
1142                    ];
1143                    if !Self::quad_intersects_clip(quad, active_clip) {
1144                        culled_instances += 1;
1145                        continue;
1146                    }
1147                    let inst: GpuQuadInstance = GpuQuadInstance {
1148                        rect: quad,
1149                        clip: [
1150                            active_clip.get_x(),
1151                            active_clip.get_y(),
1152                            active_clip.right(),
1153                            active_clip.bottom(),
1154                        ],
1155                        color: color.to_f32_array(),
1156                        secondary_color: [0.0; 4],
1157                        radii: [0.5 * scale; 4],
1158                        stroke_or_blur: 0.0,
1159                        angle_rad: 0.0,
1160                        kind: GpuPrimitiveKind::RoundedRect as u32,
1161                        reserved: 0,
1162                    };
1163                    Self::push_instance_coalesced(
1164                        batches,
1165                        active_batches,
1166                        &mut tail_state,
1167                        clip_entry,
1168                        inst,
1169                        &mut coalesced_merges,
1170                    );
1171                    uploaded_instances += 1;
1172                }
1173                DrawCommand::Image { rect, radius, .. }
1174                | DrawCommand::SharedImage { rect, radius, .. } => {
1175                    let snapped: Rect = snap_physical_rect(*rect, scale);
1176                    let quad: [f32; 4] = [
1177                        snapped.get_x(),
1178                        snapped.get_y(),
1179                        snapped.get_width(),
1180                        snapped.get_height(),
1181                    ];
1182                    if !Self::quad_intersects_clip(quad, active_clip) {
1183                        culled_instances += 1;
1184                        continue;
1185                    }
1186                    let inst: GpuQuadInstance = GpuQuadInstance {
1187                        rect: quad,
1188                        clip: [
1189                            active_clip.get_x(),
1190                            active_clip.get_y(),
1191                            active_clip.right(),
1192                            active_clip.bottom(),
1193                        ],
1194                        color: [1.0, 1.0, 1.0, 1.0],
1195                        secondary_color: [0.0; 4],
1196                        radii: [
1197                            radius.get_top_left() * scale,
1198                            radius.get_top_right() * scale,
1199                            radius.get_bottom_right() * scale,
1200                            radius.get_bottom_left() * scale,
1201                        ],
1202                        stroke_or_blur: 0.0,
1203                        angle_rad: 0.0,
1204                        kind: GpuPrimitiveKind::TexturedQuad as u32,
1205                        reserved: 0,
1206                    };
1207                    Self::push_instance_coalesced(
1208                        batches,
1209                        active_batches,
1210                        &mut tail_state,
1211                        clip_entry,
1212                        inst,
1213                        &mut coalesced_merges,
1214                    );
1215                    uploaded_instances += 1;
1216                }
1217                DrawCommand::Circle {
1218                    center,
1219                    radius,
1220                    color,
1221                } => {
1222                    let r: f32 = radius * scale;
1223                    let pad: f32 = 1.5;
1224                    let extent: f32 = r + pad;
1225                    let quad: [f32; 4] = [
1226                        center.get_x() * scale - extent,
1227                        center.get_y() * scale - extent,
1228                        extent * 2.0,
1229                        extent * 2.0,
1230                    ];
1231                    if !Self::quad_intersects_clip(quad, active_clip) {
1232                        culled_instances += 1;
1233                        continue;
1234                    }
1235                    let inst: GpuQuadInstance = GpuQuadInstance {
1236                        rect: quad,
1237                        clip: [
1238                            active_clip.get_x(),
1239                            active_clip.get_y(),
1240                            active_clip.right(),
1241                            active_clip.bottom(),
1242                        ],
1243                        color: color.to_f32_array(),
1244                        secondary_color: [0.0; 4],
1245                        radii: [r; 4],
1246                        stroke_or_blur: r,
1247                        angle_rad: 0.0,
1248                        kind: GpuPrimitiveKind::Circle as u32,
1249                        reserved: 0,
1250                    };
1251                    Self::push_instance_coalesced(
1252                        batches,
1253                        active_batches,
1254                        &mut tail_state,
1255                        clip_entry,
1256                        inst,
1257                        &mut coalesced_merges,
1258                    );
1259                    uploaded_instances += 1;
1260                }
1261                DrawCommand::Line {
1262                    from,
1263                    to,
1264                    color,
1265                    width,
1266                } => {
1267                    let fx0: f32 = from.get_x() * scale;
1268                    let fy0: f32 = from.get_y() * scale;
1269                    let fx1: f32 = to.get_x() * scale;
1270                    let fy1: f32 = to.get_y() * scale;
1271                    let dx: f32 = fx1 - fx0;
1272                    let dy: f32 = fy1 - fy0;
1273                    let stroke_px: f32 = (width * scale).max(1.0);
1274                    let pad: f32 = stroke_px * 0.5 + 1.5;
1275                    let min_x: f32 = fx0.min(fx1) - pad;
1276                    let min_y: f32 = fy0.min(fy1) - pad;
1277                    let max_x: f32 = fx0.max(fx1) + pad;
1278                    let max_y: f32 = fy0.max(fy1) + pad;
1279                    let quad: [f32; 4] = [
1280                        min_x,
1281                        min_y,
1282                        (max_x - min_x).max(2.0),
1283                        (max_y - min_y).max(2.0),
1284                    ];
1285                    if !Self::quad_intersects_clip(quad, active_clip) {
1286                        culled_instances += 1;
1287                        continue;
1288                    }
1289                    let inst: GpuQuadInstance = GpuQuadInstance {
1290                        rect: quad,
1291                        clip: [
1292                            active_clip.get_x(),
1293                            active_clip.get_y(),
1294                            active_clip.right(),
1295                            active_clip.bottom(),
1296                        ],
1297                        color: color.to_f32_array(),
1298                        secondary_color: [0.0; 4],
1299                        radii: [fx0, fy0, fx1, fy1],
1300                        stroke_or_blur: stroke_px,
1301                        angle_rad: dy.atan2(dx),
1302                        kind: GpuPrimitiveKind::Line as u32,
1303                        reserved: 0,
1304                    };
1305                    Self::push_instance_coalesced(
1306                        batches,
1307                        active_batches,
1308                        &mut tail_state,
1309                        clip_entry,
1310                        inst,
1311                        &mut coalesced_merges,
1312                    );
1313                    uploaded_instances += 1;
1314                }
1315                DrawCommand::Triangle { p0, p1, p2, color } => {
1316                    let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
1317                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
1318                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
1319                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
1320                    let quad: [f32; 4] = [
1321                        min_x,
1322                        min_y,
1323                        (max_x - min_x).max(2.0),
1324                        (max_y - min_y).max(2.0),
1325                    ];
1326                    if !Self::quad_intersects_clip(quad, active_clip) {
1327                        culled_instances += 1;
1328                        continue;
1329                    }
1330                    let inst: GpuQuadInstance = GpuQuadInstance {
1331                        rect: quad,
1332                        clip: [
1333                            active_clip.get_x(),
1334                            active_clip.get_y(),
1335                            active_clip.right(),
1336                            active_clip.bottom(),
1337                        ],
1338                        color: color.to_f32_array(),
1339                        secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
1340                        radii: [
1341                            p1.get_x() * scale,
1342                            p1.get_y() * scale,
1343                            p2.get_x() * scale,
1344                            p2.get_y() * scale,
1345                        ],
1346                        stroke_or_blur: 0.0,
1347                        angle_rad: 0.0,
1348                        kind: GpuPrimitiveKind::Triangle as u32,
1349                        reserved: 3,
1350                    };
1351                    Self::push_instance_coalesced(
1352                        batches,
1353                        active_batches,
1354                        &mut tail_state,
1355                        clip_entry,
1356                        inst,
1357                        &mut coalesced_merges,
1358                    );
1359                    uploaded_instances += 1;
1360                }
1361                DrawCommand::SpriteRegion { rect, tint, .. } => {
1362                    let snapped: Rect = snap_physical_rect(*rect, scale);
1363                    let quad: [f32; 4] = [
1364                        snapped.get_x(),
1365                        snapped.get_y(),
1366                        snapped.get_width(),
1367                        snapped.get_height(),
1368                    ];
1369                    if !Self::quad_intersects_clip(quad, active_clip) {
1370                        culled_instances += 1;
1371                        continue;
1372                    }
1373                    let inst: GpuQuadInstance = GpuQuadInstance {
1374                        rect: quad,
1375                        clip: [
1376                            active_clip.get_x(),
1377                            active_clip.get_y(),
1378                            active_clip.right(),
1379                            active_clip.bottom(),
1380                        ],
1381                        color: tint.to_f32_array(),
1382                        secondary_color: [0.0; 4],
1383                        radii: [0.0; 4],
1384                        stroke_or_blur: 0.0,
1385                        angle_rad: 0.0,
1386                        kind: GpuPrimitiveKind::TexturedQuad as u32,
1387                        reserved: 1,
1388                    };
1389                    Self::push_instance_coalesced(
1390                        batches,
1391                        active_batches,
1392                        &mut tail_state,
1393                        clip_entry,
1394                        inst,
1395                        &mut coalesced_merges,
1396                    );
1397                    uploaded_instances += 1;
1398                }
1399            }
1400        }
1401        let prim_upload_bytes: usize =
1402            uploaded_instances.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
1403        let upload_bytes: usize = prim_upload_bytes;
1404        let acquired_fence: u64 = match resource_ring
1405            .acquire_staging(prim_upload_bytes, GpuUploadPriority::RequiredFrame)
1406        {
1407            GpuRingAcquireResult::Acquired { fence_id, .. } => fence_id,
1408            GpuRingAcquireResult::DeferredFrameRingFull
1409            | GpuRingAcquireResult::DroppedPrefetchRingFull => {
1410                let prev: u64 =
1411                    GpuResourceRing::next_monotonic_fence(resource_ring.get_completed_fence_id());
1412                let _: usize = resource_ring.complete_fence(prev);
1413                match resource_ring
1414                    .acquire_staging(prim_upload_bytes, GpuUploadPriority::RequiredFrame)
1415                {
1416                    GpuRingAcquireResult::Acquired { fence_id, .. } => fence_id,
1417                    GpuRingAcquireResult::DeferredFrameRingFull
1418                    | GpuRingAcquireResult::DroppedPrefetchRingFull => {
1419                        resource_ring.get_next_fence_id()
1420                    }
1421                }
1422            }
1423        };
1424        let active_slice: &[GpuBatch] = &batches[..(*active_batches).min(batches.len())];
1425        let submitted: usize = driver.submit_batches(phys_w, phys_h, clear_color, active_slice)?;
1426        *last_fence_id = acquired_fence;
1427        let retire_window: u64 = acquired_fence.saturating_sub(2);
1428        if retire_window > 0 {
1429            let _: usize = resource_ring.complete_fence(retire_window);
1430        }
1431        *last_submitted_batches = submitted;
1432        *last_coalesced_merges = coalesced_merges;
1433        *last_culled_instances = culled_instances;
1434        *last_uploaded_instances = uploaded_instances;
1435        *last_uploaded_bytes = upload_bytes;
1436        *last_uploaded_primitive_bytes = prim_upload_bytes;
1437        let pixels: usize = if *enable_readback {
1438            let (_, px): (usize, usize) = readback.render(display_list, damage);
1439            *cpu_readback_frames = cpu_readback_frames.saturating_add(1);
1440            *last_cpu_rgba_upload_bytes = (phys_w as usize)
1441                .saturating_mul(phys_h as usize)
1442                .saturating_mul(4);
1443            px
1444        } else {
1445            *direct_gpu_frames = direct_gpu_frames.saturating_add(1);
1446            *last_cpu_rgba_upload_bytes = 0;
1447            (phys_w as usize).saturating_mul(phys_h as usize)
1448        };
1449        Ok((submitted, pixels))
1450    }
1451
1452    /// Appends `instance` in strict draw order into the tail `GpuBatch` when clip-compatible, or opens the next reusable batch slot.
1453    ///
1454    /// # Arguments
1455    ///
1456    /// - `&mut Vec<GpuBatch>` - Persistent batch pool vector.
1457    /// - `&mut usize` - Active batch watermark for the current frame.
1458    /// - `&mut GpuBatchCoalesceState` - Unclipped containment and layer metadata for the active tail batch.
1459    /// - `GpuClipEntry` - Active physical scissor and corner-free interior safe clip rectangle.
1460    /// - `GpuQuadInstance` - Instance data to batch in exact back-to-front order.
1461    /// - `&mut usize` - Running counter of cross-clip batch splits avoided by coalescing.
1462    fn push_instance_coalesced(
1463        batches: &mut Vec<GpuBatch>,
1464        active_batches: &mut usize,
1465        tail_state: &mut GpuBatchCoalesceState,
1466        clip_entry: GpuClipEntry,
1467        instance: GpuQuadInstance,
1468        coalesced_merges: &mut usize,
1469    ) {
1470        let scissor: Rect = clip_entry.scissor;
1471        let is_blur: bool = instance.kind == GpuPrimitiveKind::BackdropBlur as u32;
1472        let inst_unclipped: bool =
1473            !is_blur && Self::quad_inside_rect(instance.rect, clip_entry.safe_inner);
1474        let prim: GpuPrimitiveInstance =
1475            GpuPrimitiveInstance::from_quad_instance(&instance, 0, tail_state.layer_id);
1476        let count: usize = *active_batches;
1477        if count > 0 {
1478            let last: &mut GpuBatch = &mut batches[count - 1];
1479            if last.get_instances().len() < MAX_QUADS_PER_BATCH
1480                && last.get_layer_id() == tail_state.layer_id
1481                && last.get_scroll_offset() == tail_state.scroll_offset
1482            {
1483                let last_scissor: Rect = last.get_scissor();
1484                let blur_boundary: bool = tail_state.has_backdrop_blur || is_blur;
1485                if last_scissor == scissor && !blur_boundary {
1486                    last.get_mut_instances().push(instance);
1487                    last.get_mut_primitives().push(prim);
1488                    tail_state.all_unclipped = tail_state.all_unclipped && inst_unclipped;
1489                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, instance.rect);
1490                    return;
1491                }
1492                if !blur_boundary
1493                    && inst_unclipped
1494                    && Self::quad_inside_rect(instance.rect, last_scissor)
1495                {
1496                    last.get_mut_instances().push(instance);
1497                    last.get_mut_primitives().push(prim);
1498                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, instance.rect);
1499                    *coalesced_merges += 1;
1500                    return;
1501                }
1502                if !blur_boundary
1503                    && tail_state.all_unclipped
1504                    && Self::rect_inside_rect(tail_state.bounds, scissor)
1505                {
1506                    last.set_scissor(scissor);
1507                    last.get_mut_instances().push(instance);
1508                    last.get_mut_primitives().push(prim);
1509                    tail_state.all_unclipped = inst_unclipped;
1510                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, instance.rect);
1511                    *coalesced_merges += 1;
1512                    return;
1513                }
1514            }
1515        }
1516        if count < batches.len() {
1517            let slot: &mut GpuBatch = &mut batches[count];
1518            slot.set_scissor(scissor);
1519            slot.set_scroll_offset(tail_state.scroll_offset);
1520            slot.set_layer_id(tail_state.layer_id);
1521            slot.get_mut_instances().clear();
1522            slot.get_mut_instances().push(instance);
1523            slot.get_mut_primitives().clear();
1524            slot.get_mut_primitives().push(prim);
1525        } else {
1526            let mut batch: GpuBatch = GpuBatch::default();
1527            batch.set_scissor(scissor);
1528            batch.set_scroll_offset(tail_state.scroll_offset);
1529            batch.set_layer_id(tail_state.layer_id);
1530            batch.get_mut_instances().reserve(512);
1531            batch.get_mut_primitives().reserve(512);
1532            batch.get_mut_instances().push(instance);
1533            batch.get_mut_primitives().push(prim);
1534            batches.push(batch);
1535        }
1536        *active_batches = count + 1;
1537        tail_state.all_unclipped = inst_unclipped;
1538        tail_state.has_backdrop_blur = is_blur;
1539        tail_state.bounds = Rect::new(
1540            instance.rect[0],
1541            instance.rect[1],
1542            instance.rect[2],
1543            instance.rect[3],
1544        );
1545    }
1546}