Skip to main content

euv_core/render/hardware/
impl.rs

1use super::*;
2
3/// `GpuDriver` implementation for `RecordingGpuDriver`.
4impl GpuDriver for RecordingGpuDriver {
5    /// Returns the configured backend tag.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Driver reference.
10    ///
11    /// # Returns
12    ///
13    /// - `GraphicsBackend` - Active backend tag.
14    fn backend(&self) -> GraphicsBackend {
15        self.get_backend_kind()
16    }
17
18    /// Selects the canonical native shader source for this backend.
19    ///
20    /// # Arguments
21    ///
22    /// - `&Self` - Driver reference.
23    ///
24    /// # Returns
25    ///
26    /// - `&'static str` - Native shader source string.
27    fn shader_source(&self) -> &'static str {
28        match self.get_backend_kind() {
29            GraphicsBackend::Metal => MSL_UI_SHADER,
30            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => HLSL_UI_SHADER,
31            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => GLSL_ES3_UI_FRAGMENT_SHADER,
32            GraphicsBackend::WebGpu
33            | GraphicsBackend::Vulkan
34            | GraphicsBackend::SoftwareCpu
35            | GraphicsBackend::Canvas2d
36            | GraphicsBackend::Headless => WGSL_UI_SHADER,
37        }
38    }
39
40    /// Records submitted GPU batches and returns draw-call count.
41    ///
42    /// # Arguments
43    ///
44    /// - `&Self` - Mutable driver.
45    /// - `u32` - Surface width.
46    /// - `u32` - Surface height.
47    /// - `Color` - Clear color.
48    /// - `&[GpuBatch]` - Ordered batches.
49    ///
50    /// # Returns
51    ///
52    /// - `Result<usize, PlatformError>` - Submitted batch count.
53    fn submit_batches(
54        &mut self,
55        _width: u32,
56        _height: u32,
57        clear_color: Color,
58        batches: &[GpuBatch],
59    ) -> Result<usize, PlatformError> {
60        let count: usize = batches.len();
61        let instances: usize = batches.iter().fold(0_usize, |acc: usize, b: &GpuBatch| {
62            acc + b.get_instances().len()
63        });
64        self.set_last_clear(clear_color);
65        self.set_last_instance_count(instances);
66        self.set_total_draw_calls(self.get_total_draw_calls().saturating_add(count));
67        Ok(count)
68    }
69}
70
71/// Instanced batch builder and execution methods for `HardwareRenderer`.
72impl HardwareRenderer {
73    /// Creates a hardware renderer bound to `backend` with optional deterministic pixel readback.
74    ///
75    /// # Arguments
76    ///
77    /// - `GraphicsBackend` - Selected GPU backend.
78    /// - `u32` - Initial physical width.
79    /// - `u32` - Initial physical height.
80    /// - `RenderConfig` - Rendering configuration.
81    /// - `bool` - Whether software readback mirror is enabled.
82    ///
83    /// # Returns
84    ///
85    /// - `Self` - Configured hardware renderer.
86    #[must_use]
87    pub fn with_backend(
88        backend: GraphicsBackend,
89        width: u32,
90        height: u32,
91        config: RenderConfig,
92        enable_readback: bool,
93    ) -> Self {
94        Self::with_backend_and_font(
95            backend,
96            width,
97            height,
98            config,
99            enable_readback,
100            NativeSystemFont::deterministic(),
101        )
102    }
103
104    /// Creates a hardware renderer bound to `backend` with an explicit font provider for readback.
105    ///
106    /// # Arguments
107    ///
108    /// - `GraphicsBackend` - Selected GPU backend.
109    /// - `u32` - Initial physical width.
110    /// - `u32` - Initial physical height.
111    /// - `RenderConfig` - Rendering configuration.
112    /// - `bool` - Whether software readback mirror is enabled.
113    /// - `NativeSystemFont` - Font provider used by the software readback mirror.
114    ///
115    /// # Returns
116    ///
117    /// - `Self` - Configured hardware renderer.
118    #[must_use]
119    pub fn with_backend_and_font(
120        backend: GraphicsBackend,
121        width: u32,
122        height: u32,
123        config: RenderConfig,
124        enable_readback: bool,
125        font_provider: NativeSystemFont,
126    ) -> Self {
127        let driver: NativeGpuDriver = NativeGpuDriver::probe(backend);
128        Self {
129            driver,
130            batches: Vec::with_capacity(16),
131            readback: SoftwareRenderer::with_font_provider(width, height, config, font_provider),
132            enable_readback,
133        }
134    }
135
136    /// Computes a deterministic 64-bit FNV-1a hash over all compiled GPU batch instances.
137    ///
138    /// # Arguments
139    ///
140    /// - `&Self` - Hardware renderer reference.
141    ///
142    /// # Returns
143    ///
144    /// - `u64` - Deterministic batch geometry hash.
145    #[must_use]
146    pub fn batch_hash(&self) -> u64 {
147        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
148        for batch in self.get_batches().iter() {
149            for inst in batch.get_instances().iter() {
150                for v in inst
151                    .get_rect()
152                    .iter()
153                    .chain(inst.get_color().iter())
154                    .chain(inst.get_radii().iter())
155                {
156                    hash ^= v.to_bits() as u64;
157                    hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
158                }
159            }
160        }
161        hash
162    }
163
164    /// Compiles `display_list` into coalesced GPU instanced batches and submits them to the GPU driver.
165    ///
166    /// # Arguments
167    ///
168    /// - `&Self` - Mutable hardware renderer.
169    /// - `&DisplayList` - Backend-agnostic draw command stream.
170    /// - `DamageRegion` - Active damage region for readback mirroring.
171    ///
172    /// # Returns
173    ///
174    /// - `Result<(usize, usize), PlatformError>` - Tuple of `(draw_batches, pixels_shaded)`.
175    pub fn render(
176        &mut self,
177        display_list: &DisplayList,
178        damage: DamageRegion,
179    ) -> Result<(usize, usize), PlatformError> {
180        let scale: f32 = display_list.get_scale_factor().max(0.5);
181        let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
182        let phys_h: u32 =
183            ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
184        let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
185        let mut clip_stack: Vec<Rect> = vec![full_clip];
186        let mut clear_color: Color = COLOR_WHITE;
187        self.get_mut_batches().clear();
188        for cmd in display_list.get_commands().iter() {
189            let active_clip: Rect = clip_stack.last().copied().unwrap_or(full_clip);
190            match cmd {
191                DrawCommand::Clear(c) => {
192                    clear_color = *c;
193                }
194                DrawCommand::PushClip(rect) => {
195                    let phys: Rect = snap_physical_rect(*rect, scale);
196                    clip_stack.push(active_clip.intersect(phys).unwrap_or_default());
197                }
198                DrawCommand::PopClip => {
199                    if clip_stack.len() > 1 {
200                        clip_stack.pop();
201                    }
202                }
203                DrawCommand::FillRoundedRect {
204                    rect,
205                    color,
206                    radius,
207                    border,
208                } => {
209                    let snapped: Rect = snap_physical_rect(*rect, scale);
210                    let bw: f32 = if border.get_width() > 0.0 {
211                        (border.get_width() * scale).max(1.0)
212                    } else {
213                        0.0
214                    };
215                    let inst: GpuQuadInstance = GpuQuadInstance {
216                        rect: [
217                            snapped.get_x(),
218                            snapped.get_y(),
219                            snapped.get_width(),
220                            snapped.get_height(),
221                        ],
222                        clip: [
223                            active_clip.get_x(),
224                            active_clip.get_y(),
225                            active_clip.right(),
226                            active_clip.bottom(),
227                        ],
228                        color: color.to_f32_array(),
229                        secondary_color: border.get_color().to_f32_array(),
230                        radii: [
231                            radius.get_top_left() * scale,
232                            radius.get_top_right() * scale,
233                            radius.get_bottom_right() * scale,
234                            radius.get_bottom_left() * scale,
235                        ],
236                        stroke_or_blur: bw,
237                        angle_rad: 0.0,
238                        kind: GpuPrimitiveKind::RoundedRect as u32,
239                        reserved: 0,
240                    };
241                    self.push_instance(active_clip, inst);
242                }
243                DrawCommand::LinearGradientRect {
244                    rect,
245                    gradient,
246                    radius,
247                } => {
248                    let snapped: Rect = snap_physical_rect(*rect, scale);
249                    let inst: GpuQuadInstance = GpuQuadInstance {
250                        rect: [
251                            snapped.get_x(),
252                            snapped.get_y(),
253                            snapped.get_width(),
254                            snapped.get_height(),
255                        ],
256                        clip: [
257                            active_clip.get_x(),
258                            active_clip.get_y(),
259                            active_clip.right(),
260                            active_clip.bottom(),
261                        ],
262                        color: gradient.get_start_color().to_f32_array(),
263                        secondary_color: gradient.get_end_color().to_f32_array(),
264                        radii: [
265                            radius.get_top_left() * scale,
266                            radius.get_top_right() * scale,
267                            radius.get_bottom_right() * scale,
268                            radius.get_bottom_left() * scale,
269                        ],
270                        stroke_or_blur: 0.0,
271                        angle_rad: gradient.get_angle_deg().to_radians(),
272                        kind: GpuPrimitiveKind::Gradient as u32,
273                        reserved: 0,
274                    };
275                    self.push_instance(active_clip, inst);
276                }
277                DrawCommand::BoxShadow {
278                    rect,
279                    radius,
280                    shadow,
281                } => {
282                    let spread: f32 = shadow.get_spread_radius() * scale;
283                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
284                    let sigma: f32 = (blur * 0.5).max(0.75);
285                    let pad: f32 = (sigma * 3.0).ceil();
286                    let base_rect: Rect = snap_physical_rect(*rect, scale);
287                    let caster_x: f32 =
288                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
289                    let caster_y: f32 =
290                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
291                    let caster_w: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
292                    let caster_h: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
293                    let inst: GpuQuadInstance = GpuQuadInstance {
294                        rect: [
295                            caster_x - pad,
296                            caster_y - pad,
297                            caster_w + pad * 2.0,
298                            caster_h + pad * 2.0,
299                        ],
300                        clip: [
301                            active_clip.get_x(),
302                            active_clip.get_y(),
303                            active_clip.right(),
304                            active_clip.bottom(),
305                        ],
306                        color: shadow.get_color().to_f32_array(),
307                        secondary_color: [0.0; 4],
308                        radii: [
309                            (radius.get_top_left() * scale + spread).max(0.0),
310                            (radius.get_top_right() * scale + spread).max(0.0),
311                            (radius.get_bottom_right() * scale + spread).max(0.0),
312                            (radius.get_bottom_left() * scale + spread).max(0.0),
313                        ],
314                        stroke_or_blur: sigma,
315                        angle_rad: pad,
316                        kind: GpuPrimitiveKind::Shadow as u32,
317                        reserved: 0,
318                    };
319                    self.push_instance(active_clip, inst);
320                }
321                DrawCommand::TextRun { rect, text, style } => {
322                    let glyph_count: usize =
323                        text.chars().filter(|c: &char| *c != ' ').count().max(1);
324                    let inst: GpuQuadInstance = GpuQuadInstance {
325                        rect: [
326                            rect.get_x() * scale,
327                            rect.get_y() * scale,
328                            rect.get_width() * scale,
329                            rect.get_height() * scale,
330                        ],
331                        clip: [
332                            active_clip.get_x(),
333                            active_clip.get_y(),
334                            active_clip.right(),
335                            active_clip.bottom(),
336                        ],
337                        color: style.get_color().to_f32_array(),
338                        secondary_color: [0.0; 4],
339                        radii: [0.0; 4],
340                        stroke_or_blur: style.get_font_size() * scale,
341                        angle_rad: 0.0,
342                        kind: GpuPrimitiveKind::Glyph as u32,
343                        reserved: glyph_count as u32,
344                    };
345                    self.push_instance(active_clip, inst);
346                }
347                DrawCommand::Image { rect, radius, .. } => {
348                    let snapped: Rect = snap_physical_rect(*rect, scale);
349                    let inst: GpuQuadInstance = GpuQuadInstance {
350                        rect: [
351                            snapped.get_x(),
352                            snapped.get_y(),
353                            snapped.get_width(),
354                            snapped.get_height(),
355                        ],
356                        clip: [
357                            active_clip.get_x(),
358                            active_clip.get_y(),
359                            active_clip.right(),
360                            active_clip.bottom(),
361                        ],
362                        color: [1.0, 1.0, 1.0, 1.0],
363                        secondary_color: [0.0; 4],
364                        radii: [
365                            radius.get_top_left() * scale,
366                            radius.get_top_right() * scale,
367                            radius.get_bottom_right() * scale,
368                            radius.get_bottom_left() * scale,
369                        ],
370                        stroke_or_blur: 0.0,
371                        angle_rad: 0.0,
372                        kind: GpuPrimitiveKind::TexturedQuad as u32,
373                        reserved: 0,
374                    };
375                    self.push_instance(active_clip, inst);
376                }
377                DrawCommand::Circle {
378                    center,
379                    radius,
380                    color,
381                } => {
382                    let r: f32 = radius * scale;
383                    let inst: GpuQuadInstance = GpuQuadInstance {
384                        rect: [
385                            center.get_x() * scale - r,
386                            center.get_y() * scale - r,
387                            r * 2.0,
388                            r * 2.0,
389                        ],
390                        clip: [
391                            active_clip.get_x(),
392                            active_clip.get_y(),
393                            active_clip.right(),
394                            active_clip.bottom(),
395                        ],
396                        color: color.to_f32_array(),
397                        secondary_color: [0.0; 4],
398                        radii: [r; 4],
399                        stroke_or_blur: 0.0,
400                        angle_rad: 0.0,
401                        kind: GpuPrimitiveKind::Circle as u32,
402                        reserved: 0,
403                    };
404                    self.push_instance(active_clip, inst);
405                }
406                DrawCommand::Line {
407                    from,
408                    to,
409                    color,
410                    width,
411                } => {
412                    let dx: f32 = (to.get_x() - from.get_x()) * scale;
413                    let dy: f32 = (to.get_y() - from.get_y()) * scale;
414                    let x0: f32 = from.get_x().min(to.get_x()) * scale;
415                    let y0: f32 = from.get_y().min(to.get_y()) * scale;
416                    let w: f32 = dx.abs().max(width * scale);
417                    let h: f32 = dy.abs().max(width * scale);
418                    let inst: GpuQuadInstance = GpuQuadInstance {
419                        rect: [x0, y0, w, h],
420                        clip: [
421                            active_clip.get_x(),
422                            active_clip.get_y(),
423                            active_clip.right(),
424                            active_clip.bottom(),
425                        ],
426                        color: color.to_f32_array(),
427                        secondary_color: [0.0; 4],
428                        radii: [
429                            from.get_x() * scale,
430                            from.get_y() * scale,
431                            to.get_x() * scale,
432                            to.get_y() * scale,
433                        ],
434                        stroke_or_blur: width * scale,
435                        angle_rad: dy.atan2(dx),
436                        kind: GpuPrimitiveKind::Line as u32,
437                        reserved: 0,
438                    };
439                    self.push_instance(active_clip, inst);
440                }
441                DrawCommand::Triangle { p0, p1, p2, color } => {
442                    let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale;
443                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale;
444                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale;
445                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale;
446                    let inst: GpuQuadInstance = GpuQuadInstance {
447                        rect: [
448                            min_x,
449                            min_y,
450                            (max_x - min_x).max(1.0),
451                            (max_y - min_y).max(1.0),
452                        ],
453                        clip: [
454                            active_clip.get_x(),
455                            active_clip.get_y(),
456                            active_clip.right(),
457                            active_clip.bottom(),
458                        ],
459                        color: color.to_f32_array(),
460                        secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
461                        radii: [
462                            p1.get_x() * scale,
463                            p1.get_y() * scale,
464                            p2.get_x() * scale,
465                            p2.get_y() * scale,
466                        ],
467                        stroke_or_blur: 0.0,
468                        angle_rad: 0.0,
469                        kind: GpuPrimitiveKind::Triangle as u32,
470                        reserved: 3,
471                    };
472                    self.push_instance(active_clip, inst);
473                }
474                DrawCommand::SpriteRegion { rect, tint, .. } => {
475                    let snapped: Rect = snap_physical_rect(*rect, scale);
476                    let inst: GpuQuadInstance = GpuQuadInstance {
477                        rect: [
478                            snapped.get_x(),
479                            snapped.get_y(),
480                            snapped.get_width(),
481                            snapped.get_height(),
482                        ],
483                        clip: [
484                            active_clip.get_x(),
485                            active_clip.get_y(),
486                            active_clip.right(),
487                            active_clip.bottom(),
488                        ],
489                        color: tint.to_f32_array(),
490                        secondary_color: [0.0; 4],
491                        radii: [0.0; 4],
492                        stroke_or_blur: 0.0,
493                        angle_rad: 0.0,
494                        kind: GpuPrimitiveKind::TexturedQuad as u32,
495                        reserved: 1,
496                    };
497                    self.push_instance(active_clip, inst);
498                }
499            }
500        }
501        let Self {
502            driver,
503            batches,
504            readback,
505            enable_readback,
506        } = self;
507        let submitted: usize = driver.submit_batches(phys_w, phys_h, clear_color, batches)?;
508        let pixels: usize = if *enable_readback {
509            let (_, px): (usize, usize) = readback.render(display_list, damage);
510            px
511        } else {
512            (phys_w as usize) * (phys_h as usize)
513        };
514        Ok((submitted, pixels))
515    }
516
517    /// Appends `instance` to the tail `GpuBatch` if scissor matches and batch is below capacity.
518    ///
519    /// # Arguments
520    ///
521    /// - `&Self` - Mutable hardware renderer.
522    /// - `Rect` - Active scissor rectangle.
523    /// - `GpuQuadInstance` - Instance data to batch.
524    fn push_instance(&mut self, scissor: Rect, instance: GpuQuadInstance) {
525        if let Some(last) = self.get_mut_batches().last_mut()
526            && last.get_scissor() == scissor
527            && last.get_instances().len() < MAX_QUADS_PER_BATCH
528        {
529            last.get_mut_instances().push(instance);
530            return;
531        }
532        let mut batch: GpuBatch = GpuBatch::default();
533        batch.set_scissor(scissor);
534        batch.get_mut_instances().push(instance);
535        self.get_mut_batches().push(batch);
536    }
537}