Skip to main content

euv_core/render/command/
impl.rs

1use super::*;
2
3/// Command emission helpers for `DisplayList`.
4impl DisplayList {
5    /// Clears all commands while preserving allocated backing capacity.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable display list.
10    /// - `Size` - Target logical viewport size.
11    /// - `f32` - Active DPI scale factor.
12    pub fn reset(&mut self, viewport: Size, scale_factor: f32) {
13        self.get_mut_commands().clear();
14        self.set_viewport(viewport);
15        self.set_scale_factor(scale_factor.max(0.5));
16        self.set_portal_split_index(0);
17    }
18
19    /// Appends a single `DrawCommand` to the list.
20    ///
21    /// # Arguments
22    ///
23    /// - `&Self` - Mutable display list.
24    /// - `DrawCommand` - Command to push.
25    pub fn push(&mut self, command: DrawCommand) {
26        self.get_mut_commands().push(command);
27    }
28
29    /// Returns total emitted command count.
30    ///
31    /// # Arguments
32    ///
33    /// - `&Self` - Display list reference.
34    ///
35    /// # Returns
36    ///
37    /// - `usize` - Number of commands.
38    #[must_use]
39    pub fn len(&self) -> usize {
40        self.get_commands().len()
41    }
42
43    /// Returns true when the display list contains zero commands.
44    ///
45    /// # Arguments
46    ///
47    /// - `&Self` - Display list reference.
48    ///
49    /// # Returns
50    ///
51    /// - `bool` - True if empty.
52    #[must_use]
53    pub fn is_empty(&self) -> bool {
54        self.get_commands().is_empty()
55    }
56
57    /// Folds a 64-bit value into an FNV-1a accumulator.
58    ///
59    /// # Arguments
60    ///
61    /// - `&mut u64` - Mutable hash accumulator.
62    /// - `u64` - Value to fold into the digest.
63    fn mix_hash(hash: &mut u64, value: u64) {
64        *hash ^= value;
65        *hash = hash.wrapping_mul(FNV1A_PRIME);
66    }
67
68    /// Computes a fast O(commands) 64-bit FNV-1a digest over the display list without scanning framebuffer pixels.
69    ///
70    /// # Arguments
71    ///
72    /// - `&Self` - Display list reference.
73    ///
74    /// # Returns
75    ///
76    /// - `u64` - Deterministic command-stream digest.
77    #[must_use]
78    pub fn fast_hash(&self) -> u64 {
79        let mut hash: u64 = FNV1A_OFFSET_BASIS;
80        Self::mix_hash(&mut hash, self.get_commands().len() as u64);
81        Self::mix_hash(&mut hash, self.get_viewport().get_width().to_bits() as u64);
82        Self::mix_hash(&mut hash, self.get_viewport().get_height().to_bits() as u64);
83        Self::mix_hash(&mut hash, self.get_scale_factor().to_bits() as u64);
84        for cmd in self.get_commands().iter() {
85            match cmd {
86                DrawCommand::Clear(c) => {
87                    Self::mix_hash(&mut hash, 1);
88                    Self::mix_hash(&mut hash, u32::from_le_bytes(c.to_rgba_bytes()) as u64);
89                }
90                DrawCommand::FillRoundedRect {
91                    rect,
92                    color,
93                    border,
94                    ..
95                } => {
96                    Self::mix_hash(&mut hash, 2);
97                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
98                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
99                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
100                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
101                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
102                    Self::mix_hash(&mut hash, border.get_width().to_bits() as u64);
103                }
104                DrawCommand::LinearGradientRect { rect, gradient, .. } => {
105                    Self::mix_hash(&mut hash, 3);
106                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
107                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
108                    Self::mix_hash(
109                        &mut hash,
110                        u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64,
111                    );
112                }
113                DrawCommand::BoxShadow { rect, shadow, .. } => {
114                    Self::mix_hash(&mut hash, 4);
115                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
116                    Self::mix_hash(&mut hash, shadow.get_blur_radius().to_bits() as u64);
117                }
118                DrawCommand::TextRun { rect, text, style } => {
119                    Self::mix_hash(&mut hash, 5);
120                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
121                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
122                    Self::mix_hash(&mut hash, text.len() as u64);
123                    for byte in text.as_bytes().iter().take(16).copied() {
124                        Self::mix_hash(&mut hash, byte as u64);
125                    }
126                    Self::mix_hash(
127                        &mut hash,
128                        u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64,
129                    );
130                }
131                DrawCommand::Image { rect, buffer, .. } => {
132                    Self::mix_hash(&mut hash, 6);
133                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
134                    Self::mix_hash(&mut hash, buffer.get_width() as u64);
135                    Self::mix_hash(&mut hash, buffer.get_height() as u64);
136                }
137                DrawCommand::Line {
138                    from,
139                    to,
140                    color,
141                    width,
142                } => {
143                    Self::mix_hash(&mut hash, 7);
144                    Self::mix_hash(&mut hash, from.get_x().to_bits() as u64);
145                    Self::mix_hash(&mut hash, to.get_y().to_bits() as u64);
146                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
147                    Self::mix_hash(&mut hash, width.to_bits() as u64);
148                }
149                DrawCommand::Circle {
150                    center,
151                    radius,
152                    color,
153                } => {
154                    Self::mix_hash(&mut hash, 8);
155                    Self::mix_hash(&mut hash, center.get_x().to_bits() as u64);
156                    Self::mix_hash(&mut hash, center.get_y().to_bits() as u64);
157                    Self::mix_hash(&mut hash, radius.to_bits() as u64);
158                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
159                }
160                DrawCommand::Triangle { p0, p1, p2, color } => {
161                    Self::mix_hash(&mut hash, 9);
162                    Self::mix_hash(&mut hash, p0.get_x().to_bits() as u64);
163                    Self::mix_hash(&mut hash, p1.get_y().to_bits() as u64);
164                    Self::mix_hash(&mut hash, p2.get_x().to_bits() as u64);
165                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
166                }
167                DrawCommand::SpriteRegion {
168                    rect,
169                    src_rect,
170                    tint,
171                    ..
172                } => {
173                    Self::mix_hash(&mut hash, 10);
174                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
175                    Self::mix_hash(&mut hash, src_rect.get_x().to_bits() as u64);
176                    Self::mix_hash(&mut hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
177                }
178                DrawCommand::PushClip(r) => {
179                    Self::mix_hash(&mut hash, 11);
180                    Self::mix_hash(&mut hash, r.get_x().to_bits() as u64);
181                    Self::mix_hash(&mut hash, r.get_y().to_bits() as u64);
182                }
183                DrawCommand::PopClip => {
184                    Self::mix_hash(&mut hash, 12);
185                }
186            }
187        }
188        hash
189    }
190
191    /// Computes a full collision-resistant 64-bit FNV-1a digest over the base-scene slice `commands[..portal_split_index]` for lossless portal backdrop caching.
192    ///
193    /// # Arguments
194    ///
195    /// - `&Self` - Display list reference.
196    ///
197    /// # Returns
198    ///
199    /// - `u64` - Complete base-scene digest (guaranteed non-zero when commands are present).
200    #[must_use]
201    pub fn base_layer_hash(&self) -> u64 {
202        let split: usize = self.get_portal_split_index().min(self.get_commands().len());
203        let mut hash: u64 = FNV1A_OFFSET_BASIS;
204        Self::mix_hash(&mut hash, split as u64);
205        Self::mix_hash(&mut hash, self.get_viewport().get_width().to_bits() as u64);
206        Self::mix_hash(&mut hash, self.get_viewport().get_height().to_bits() as u64);
207        Self::mix_hash(&mut hash, self.get_scale_factor().to_bits() as u64);
208        for cmd in self.get_commands()[..split].iter() {
209            match cmd {
210                DrawCommand::Clear(c) => {
211                    Self::mix_hash(&mut hash, 1);
212                    Self::mix_hash(&mut hash, u32::from_le_bytes(c.to_rgba_bytes()) as u64);
213                }
214                DrawCommand::FillRoundedRect {
215                    rect,
216                    color,
217                    radius,
218                    border,
219                } => {
220                    Self::mix_hash(&mut hash, 2);
221                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
222                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
223                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
224                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
225                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
226                    Self::mix_hash(&mut hash, radius.get_top_left().to_bits() as u64);
227                    Self::mix_hash(&mut hash, radius.get_top_right().to_bits() as u64);
228                    Self::mix_hash(&mut hash, radius.get_bottom_right().to_bits() as u64);
229                    Self::mix_hash(&mut hash, radius.get_bottom_left().to_bits() as u64);
230                    Self::mix_hash(&mut hash, border.get_width().to_bits() as u64);
231                    Self::mix_hash(
232                        &mut hash,
233                        u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64,
234                    );
235                }
236                DrawCommand::LinearGradientRect {
237                    rect,
238                    gradient,
239                    radius,
240                } => {
241                    Self::mix_hash(&mut hash, 3);
242                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
243                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
244                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
245                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
246                    Self::mix_hash(&mut hash, gradient.get_angle_deg().to_bits() as u64);
247                    Self::mix_hash(
248                        &mut hash,
249                        u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64,
250                    );
251                    Self::mix_hash(
252                        &mut hash,
253                        u32::from_le_bytes(gradient.get_end_color().to_rgba_bytes()) as u64,
254                    );
255                    Self::mix_hash(&mut hash, radius.max_radius().to_bits() as u64);
256                }
257                DrawCommand::BoxShadow {
258                    rect,
259                    radius,
260                    shadow,
261                } => {
262                    Self::mix_hash(&mut hash, 4);
263                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
264                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
265                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
266                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
267                    Self::mix_hash(&mut hash, radius.max_radius().to_bits() as u64);
268                    Self::mix_hash(&mut hash, shadow.get_offset_x().to_bits() as u64);
269                    Self::mix_hash(&mut hash, shadow.get_offset_y().to_bits() as u64);
270                    Self::mix_hash(&mut hash, shadow.get_blur_radius().to_bits() as u64);
271                    Self::mix_hash(&mut hash, shadow.get_spread_radius().to_bits() as u64);
272                    Self::mix_hash(
273                        &mut hash,
274                        u32::from_le_bytes(shadow.get_color().to_rgba_bytes()) as u64,
275                    );
276                }
277                DrawCommand::TextRun { rect, text, style } => {
278                    Self::mix_hash(&mut hash, 5);
279                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
280                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
281                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
282                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
283                    Self::mix_hash(&mut hash, style.get_font_size().to_bits() as u64);
284                    Self::mix_hash(&mut hash, style.get_weight() as u64);
285                    Self::mix_hash(&mut hash, style.get_align() as u64);
286                    Self::mix_hash(
287                        &mut hash,
288                        u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64,
289                    );
290                    Self::mix_hash(&mut hash, text.len() as u64);
291                    for byte in text.as_bytes().iter().copied() {
292                        Self::mix_hash(&mut hash, byte as u64);
293                    }
294                }
295                DrawCommand::Image {
296                    rect,
297                    buffer,
298                    radius,
299                } => {
300                    Self::mix_hash(&mut hash, 6);
301                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
302                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
303                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
304                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
305                    Self::mix_hash(&mut hash, buffer.get_width() as u64);
306                    Self::mix_hash(&mut hash, buffer.get_height() as u64);
307                    Self::mix_hash(&mut hash, buffer.get_pixels().as_ptr() as usize as u64);
308                    Self::mix_hash(&mut hash, radius.max_radius().to_bits() as u64);
309                }
310                DrawCommand::Line {
311                    from,
312                    to,
313                    color,
314                    width,
315                } => {
316                    Self::mix_hash(&mut hash, 7);
317                    Self::mix_hash(&mut hash, from.get_x().to_bits() as u64);
318                    Self::mix_hash(&mut hash, from.get_y().to_bits() as u64);
319                    Self::mix_hash(&mut hash, to.get_x().to_bits() as u64);
320                    Self::mix_hash(&mut hash, to.get_y().to_bits() as u64);
321                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
322                    Self::mix_hash(&mut hash, width.to_bits() as u64);
323                }
324                DrawCommand::Circle {
325                    center,
326                    radius,
327                    color,
328                } => {
329                    Self::mix_hash(&mut hash, 8);
330                    Self::mix_hash(&mut hash, center.get_x().to_bits() as u64);
331                    Self::mix_hash(&mut hash, center.get_y().to_bits() as u64);
332                    Self::mix_hash(&mut hash, radius.to_bits() as u64);
333                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
334                }
335                DrawCommand::Triangle { p0, p1, p2, color } => {
336                    Self::mix_hash(&mut hash, 9);
337                    Self::mix_hash(&mut hash, p0.get_x().to_bits() as u64);
338                    Self::mix_hash(&mut hash, p0.get_y().to_bits() as u64);
339                    Self::mix_hash(&mut hash, p1.get_x().to_bits() as u64);
340                    Self::mix_hash(&mut hash, p1.get_y().to_bits() as u64);
341                    Self::mix_hash(&mut hash, p2.get_x().to_bits() as u64);
342                    Self::mix_hash(&mut hash, p2.get_y().to_bits() as u64);
343                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
344                }
345                DrawCommand::SpriteRegion {
346                    rect,
347                    buffer,
348                    src_rect,
349                    tint,
350                } => {
351                    Self::mix_hash(&mut hash, 10);
352                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
353                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
354                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
355                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
356                    Self::mix_hash(&mut hash, buffer.get_pixels().as_ptr() as usize as u64);
357                    Self::mix_hash(&mut hash, src_rect.get_x().to_bits() as u64);
358                    Self::mix_hash(&mut hash, src_rect.get_y().to_bits() as u64);
359                    Self::mix_hash(&mut hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
360                }
361                DrawCommand::PushClip(r) => {
362                    Self::mix_hash(&mut hash, 11);
363                    Self::mix_hash(&mut hash, r.get_x().to_bits() as u64);
364                    Self::mix_hash(&mut hash, r.get_y().to_bits() as u64);
365                    Self::mix_hash(&mut hash, r.get_width().to_bits() as u64);
366                    Self::mix_hash(&mut hash, r.get_height().to_bits() as u64);
367                }
368                DrawCommand::PopClip => {
369                    Self::mix_hash(&mut hash, 12);
370                }
371            }
372        }
373        if hash == 0 { 1 } else { hash }
374    }
375}
376
377/// Scene-to-display-list compilation pass.
378impl PaintPass {
379    /// Compiles `tree` into `display_list`, culling offscreen nodes and honoring z-index stacking.
380    ///
381    /// # Arguments
382    ///
383    /// - `&SceneTree` - Laid-out scene tree.
384    /// - `Size` - Logical viewport size.
385    /// - `f32` - DPI scale factor.
386    /// - `Color` - Surface clear background color.
387    /// - `&mut DisplayList` - Output reusable display list.
388    pub fn build(
389        tree: &SceneTree,
390        viewport: Size,
391        scale_factor: f32,
392        clear_color: Color,
393        display_list: &mut DisplayList,
394    ) {
395        display_list.reset(viewport, scale_factor);
396        display_list.push(DrawCommand::Clear(clear_color));
397        let viewport_rect: Rect = Rect::new(0.0, 0.0, viewport.get_width(), viewport.get_height());
398        let active_hover_target: Option<NodeId> = Self::resolve_active_hover_target(tree);
399        let mut portals: Vec<(i32, usize, NodeId)> = Vec::new();
400        Self::emit_node(
401            tree,
402            tree.get_root(),
403            (Point::new(0.0, 0.0), 1.0),
404            viewport_rect,
405            active_hover_target,
406            Some(&mut portals),
407            display_list,
408        );
409        display_list.set_portal_split_index(display_list.len());
410        portals.sort_by(|a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
411            a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
412        });
413        for (_, _, portal_id) in portals.into_iter() {
414            Self::emit_node(
415                tree,
416                portal_id,
417                (Point::new(0.0, 0.0), 1.0),
418                viewport_rect,
419                active_hover_target,
420                None,
421                display_list,
422            );
423        }
424    }
425
426    /// Resolves the single innermost interactive non-scrim node along the active hover chain so nested controls never stack duplicate hover fills.
427    ///
428    /// # Arguments
429    ///
430    /// - `&SceneTree` - Retained scene tree.
431    ///
432    /// # Returns
433    ///
434    /// - `Option<NodeId>` - Innermost interactive node eligible for hover tinting.
435    #[must_use]
436    fn resolve_active_hover_target(tree: &SceneTree) -> Option<NodeId> {
437        let mut cursor: Option<NodeId> = tree.get_focus().hovered_node();
438        while let Some(id) = cursor {
439            let Some(node) = tree.get_node(id) else {
440                break;
441            };
442            let style: Style = node.get_style();
443            let paint: PaintStyle = style.get_paint();
444            let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
445                || style.get_layout().get_position() == Position::Fixed;
446            let is_transparent_canvas: bool =
447                matches!(node.get_kind(), NodeKind::Canvas) && paint.background_color().is_none();
448            let is_interactive: bool = paint.get_cursor() == CursorIcon::Pointer
449                || node
450                    .get_handlers()
451                    .handler_for(&UiEventKind::Click(Point::default()))
452                    .is_some();
453            if !is_scrim && !is_transparent_canvas && is_interactive {
454                return Some(id);
455            }
456            cursor = node.parent_id();
457        }
458        None
459    }
460
461    /// Computes subtle shadcn-aligned hover/pressed color tinting for interactive controls.
462    ///
463    /// # Arguments
464    ///
465    /// - `Option<Color>` - Base background color, if any.
466    /// - `bool` - Whether the pointer hovers the control.
467    /// - `bool` - Whether the pointer actively presses the control.
468    ///
469    /// # Returns
470    ///
471    /// - `Option<Color>` - Tinted background color.
472    fn interactive_tint(base: Option<Color>, hovered: bool, pressed: bool) -> Option<Color> {
473        if !hovered && !pressed {
474            return base;
475        }
476        let delta: i32 = if pressed { 24 } else { 14 };
477        match base {
478            Some(c) if c.get_a() > 0 => {
479                let luma: u32 =
480                    (c.get_r() as u32) * 299 + (c.get_g() as u32) * 587 + (c.get_b() as u32) * 114;
481                if luma < 120_000 {
482                    let lift: i32 = if pressed { 30 } else { 20 };
483                    Some(Color::new(
484                        (c.get_r() as i32 + lift).clamp(0, 255) as u8,
485                        (c.get_g() as i32 + lift).clamp(0, 255) as u8,
486                        (c.get_b() as i32 + lift).clamp(0, 255) as u8,
487                        c.get_a(),
488                    ))
489                } else {
490                    Some(Color::new(
491                        (c.get_r() as i32 - delta).clamp(0, 255) as u8,
492                        (c.get_g() as i32 - delta).clamp(0, 255) as u8,
493                        (c.get_b() as i32 - delta).clamp(0, 255) as u8,
494                        c.get_a(),
495                    ))
496                }
497            }
498            _ => Some(Color::rgba(113, 113, 122, if pressed { 42 } else { 26 })),
499        }
500    }
501
502    /// Recursively emits commands for `node_id` and its z-sorted children.
503    ///
504    /// # Arguments
505    ///
506    /// - `&SceneTree` - Scene tree reference.
507    /// - `NodeId` - Node to paint.
508    /// - `(Point, f32)` - Accumulated ancestor scroll offset and opacity.
509    /// - `Rect` - Active cull clip rectangle.
510    /// - `Option<NodeId>` - Innermost hovered interactive node eligible for automatic hover tinting.
511    /// - `Option<&mut Vec<(i32, usize, NodeId)>>` - Optional deferred top-layer portal queue (`None` when painting top layer).
512    /// - `&mut DisplayList` - Output command list.
513    fn emit_node(
514        tree: &SceneTree,
515        node_id: NodeId,
516        scroll_and_opacity: (Point, f32),
517        cull_rect: Rect,
518        active_hover_target: Option<NodeId>,
519        mut portals: Option<&mut Vec<(i32, usize, NodeId)>>,
520        display_list: &mut DisplayList,
521    ) {
522        let (scroll_offset, parent_opacity): (Point, f32) = scroll_and_opacity;
523        let Some(node) = tree.get_node(node_id) else {
524            return;
525        };
526        let style: Style = node.get_style();
527        let layout: LayoutStyle = style.get_layout();
528        if layout.get_display() == Display::None {
529            return;
530        }
531        if let Some(portal_queue) = portals.as_deref_mut()
532            && (matches!(node.get_kind(), NodeKind::Portal)
533                || layout.get_position() == Position::Fixed)
534        {
535            portal_queue.push((layout.get_z_index(), portal_queue.len(), node_id));
536            return;
537        }
538        let hovered: bool = node.get_interaction().get_hovered();
539        let pressed: bool = node.get_interaction().get_pressed();
540        let mut paint: PaintStyle = if hovered {
541            node.hover_paint().unwrap_or(style.get_paint())
542        } else {
543            style.get_paint()
544        };
545        let is_scrim: bool =
546            matches!(node.get_kind(), NodeKind::Portal) || layout.get_position() == Position::Fixed;
547        let is_interactive: bool = paint.get_cursor() == CursorIcon::Pointer
548            || node
549                .get_handlers()
550                .handler_for(&UiEventKind::Click(Point::default()))
551                .is_some();
552        let is_transparent_canvas: bool =
553            matches!(node.get_kind(), NodeKind::Canvas) && paint.background_color().is_none();
554        let hover_visual: bool = hovered && active_hover_target == Some(node_id);
555        if is_interactive
556            && !is_scrim
557            && !is_transparent_canvas
558            && node.hover_paint().is_none()
559            && (hover_visual || pressed)
560        {
561            paint.set_background(Self::interactive_tint(
562                paint.background_color(),
563                hover_visual,
564                pressed,
565            ));
566        }
567        let opacity: f32 = (parent_opacity * paint.get_opacity()).clamp(0.0, 1.0);
568        if opacity <= 0.0 {
569            return;
570        }
571        let raw_bounds: Rect = node.get_layout_box().get_bounds();
572        let transform: Transform2D = paint.get_transform();
573        let bounds: Rect = Rect::new(
574            raw_bounds.get_x() - scroll_offset.get_x() + transform.get_translate_x(),
575            raw_bounds.get_y() - scroll_offset.get_y() + transform.get_translate_y(),
576            raw_bounds.get_width() * transform.get_scale_x(),
577            raw_bounds.get_height() * transform.get_scale_y(),
578        );
579        let clipped: bool = matches!(layout.get_overflow(), Overflow::Hidden | Overflow::Scroll);
580        let next_cull: Rect = if clipped {
581            match cull_rect.intersect(bounds) {
582                Some(r) => r,
583                None => return,
584            }
585        } else {
586            cull_rect
587        };
588        let halo: f32 = if paint.box_shadow().is_some() {
589            36.0
590        } else if paint.focus_ring_border().is_some() {
591            8.0
592        } else {
593            2.0
594        };
595        let self_vis_rect: Rect = Rect::new(
596            bounds.get_x() - halo,
597            bounds.get_y() - halo,
598            bounds.get_width() + halo * 2.0,
599            bounds.get_height() + halo * 2.0,
600        );
601        let self_visible: bool = bounds.get_width() > 0.0
602            && bounds.get_height() > 0.0
603            && self_vis_rect.intersect(cull_rect).is_some();
604        if self_visible {
605            if let Some(mut shadow) = paint.box_shadow() {
606                shadow.set_color(shadow.get_color().multiply_alpha(opacity));
607                display_list.push(DrawCommand::BoxShadow {
608                    rect: bounds,
609                    radius: paint.get_radius(),
610                    shadow,
611                });
612            }
613            if let Some(mut gradient) = paint.background_gradient() {
614                gradient.set_start_color(gradient.get_start_color().multiply_alpha(opacity));
615                gradient.set_end_color(gradient.get_end_color().multiply_alpha(opacity));
616                display_list.push(DrawCommand::LinearGradientRect {
617                    rect: bounds,
618                    gradient,
619                    radius: paint.get_radius(),
620                });
621            } else if let Some(bg) = paint.background_color() {
622                let mut border: Border = paint.get_border();
623                border.set_color(border.get_color().multiply_alpha(opacity));
624                display_list.push(DrawCommand::FillRoundedRect {
625                    rect: bounds,
626                    color: bg.multiply_alpha(opacity),
627                    radius: paint.get_radius(),
628                    border,
629                });
630            } else if paint.get_border().get_width() > 0.0 {
631                let mut border: Border = paint.get_border();
632                border.set_color(border.get_color().multiply_alpha(opacity));
633                display_list.push(DrawCommand::FillRoundedRect {
634                    rect: bounds,
635                    color: COLOR_TRANSPARENT,
636                    radius: paint.get_radius(),
637                    border,
638                });
639            }
640            if node.get_interaction().get_focused()
641                && let Some(mut ring) = paint.focus_ring_border()
642            {
643                ring.set_color(ring.get_color().multiply_alpha(opacity));
644                let ring_w: f32 = ring.get_width();
645                let ring_rect: Rect = Rect::new(
646                    bounds.get_x() - ring_w,
647                    bounds.get_y() - ring_w,
648                    bounds.get_width() + ring_w * 2.0,
649                    bounds.get_height() + ring_w * 2.0,
650                );
651                display_list.push(DrawCommand::FillRoundedRect {
652                    rect: ring_rect,
653                    color: COLOR_TRANSPARENT,
654                    radius: CornerRadius::all(paint.get_radius().max_radius() + ring_w),
655                    border: ring,
656                });
657            }
658            match node.get_kind() {
659                NodeKind::Text(text) => {
660                    let mut text_style: TextStyle = style.get_text();
661                    text_style.set_color(text_style.get_color().multiply_alpha(opacity));
662                    let content_b: Rect = node.get_layout_box().get_content_bounds();
663                    let shifted_content: Rect = Rect::new(
664                        content_b.get_x() - scroll_offset.get_x() + transform.get_translate_x(),
665                        content_b.get_y() - scroll_offset.get_y() + transform.get_translate_y(),
666                        content_b.get_width(),
667                        content_b.get_height(),
668                    );
669                    display_list.push(DrawCommand::TextRun {
670                        rect: shifted_content,
671                        text: text.clone(),
672                        style: text_style,
673                    });
674                }
675                NodeKind::Input(input_state) => {
676                    let mut text_style: TextStyle = style.get_text();
677                    let rendered_text: String = if input_state.get_value().is_empty() {
678                        text_style.set_color(text_style.get_color().multiply_alpha(opacity * 0.55));
679                        input_state.get_placeholder().clone()
680                    } else if input_state.get_password() {
681                        text_style.set_color(text_style.get_color().multiply_alpha(opacity));
682                        "*".repeat(input_state.get_value().chars().count())
683                    } else {
684                        text_style.set_color(text_style.get_color().multiply_alpha(opacity));
685                        input_state.get_value().clone()
686                    };
687                    let content_b: Rect = node.get_layout_box().get_content_bounds();
688                    let shifted_content: Rect = Rect::new(
689                        content_b.get_x() - scroll_offset.get_x() + transform.get_translate_x(),
690                        content_b.get_y() - scroll_offset.get_y() + transform.get_translate_y(),
691                        content_b.get_width(),
692                        content_b.get_height(),
693                    );
694                    let line_h: f32 =
695                        (text_style.get_font_size() * text_style.get_line_height()).max(1.0);
696                    let text_rect: Rect = if input_state.get_multiline() {
697                        shifted_content
698                    } else {
699                        text_style.set_overflow(TextOverflow::Clip);
700                        let text_y: f32 = shifted_content.get_y()
701                            + ((shifted_content.get_height() - line_h) * 0.5).max(0.0);
702                        Rect::new(
703                            shifted_content.get_x(),
704                            text_y,
705                            shifted_content.get_width(),
706                            line_h,
707                        )
708                    };
709                    display_list.push(DrawCommand::PushClip(shifted_content));
710                    display_list.push(DrawCommand::TextRun {
711                        rect: text_rect,
712                        text: rendered_text.clone(),
713                        style: text_style,
714                    });
715                    if node.get_interaction().get_focused() && tree.get_caret_visible() {
716                        let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
717                            if input_state.get_value().is_empty() {
718                                ""
719                            } else {
720                                rendered_text.as_str()
721                            },
722                            text_style,
723                            if input_state.get_multiline() {
724                                Some(shifted_content.get_width().max(1.0))
725                            } else {
726                                None
727                            },
728                        );
729                        let caret_h: f32 = (text_style.get_font_size() * 1.15)
730                            .min(shifted_content.get_height().max(12.0));
731                        let (caret_x, caret_y): (f32, f32) = if input_state.get_multiline() {
732                            let last_w: f32 = meas
733                                .get_lines()
734                                .last()
735                                .map(TextLine::get_width)
736                                .unwrap_or(0.0);
737                            let line_idx: usize = meas.get_lines().len().saturating_sub(1);
738                            let cy: f32 = shifted_content.get_y()
739                                + (line_idx as f32) * meas.get_line_height_px()
740                                + ((meas.get_line_height_px() - caret_h) * 0.5).max(0.0);
741                            (
742                                (shifted_content.get_x() + last_w + 1.0)
743                                    .min(shifted_content.right() - 2.0),
744                                cy.min(shifted_content.bottom() - caret_h)
745                                    .max(shifted_content.get_y()),
746                            )
747                        } else {
748                            (
749                                (shifted_content.get_x() + meas.get_size().get_width() + 1.0)
750                                    .min(shifted_content.right() - 2.0),
751                                shifted_content.get_y()
752                                    + ((shifted_content.get_height() - caret_h) * 0.5).max(0.0),
753                            )
754                        };
755                        display_list.push(DrawCommand::FillRoundedRect {
756                            rect: Rect::new(caret_x, caret_y, 1.5, caret_h),
757                            color: style.get_text().get_color().multiply_alpha(opacity),
758                            radius: CornerRadius::all(0.5),
759                            border: Border::default(),
760                        });
761                    }
762                    display_list.push(DrawCommand::PopClip);
763                }
764                NodeKind::Image(buffer) => {
765                    display_list.push(DrawCommand::Image {
766                        rect: bounds,
767                        buffer: buffer.clone(),
768                        radius: paint.get_radius(),
769                    });
770                }
771                NodeKind::Canvas => {
772                    if let Some(callback) = node.canvas_callback()
773                        && let Ok(mut func) = callback.try_borrow_mut()
774                    {
775                        display_list.push(DrawCommand::PushClip(bounds));
776                        func(bounds, display_list);
777                        display_list.push(DrawCommand::PopClip);
778                    }
779                }
780                NodeKind::View | NodeKind::ScrollView | NodeKind::Portal | NodeKind::Fragment => {}
781            }
782        }
783        if clipped {
784            display_list.push(DrawCommand::PushClip(bounds));
785        }
786        let scale: f32 = display_list.get_scale_factor().max(0.5);
787        let raw_node_scroll: Point = node.get_layout_box().get_scroll_offset();
788        let snap_scroll_x: f32 = (raw_node_scroll.get_x() * scale).round() / scale;
789        let snap_scroll_y: f32 = (raw_node_scroll.get_y() * scale).round() / scale;
790        let child_scroll: Point = Point::new(
791            scroll_offset.get_x() + snap_scroll_x,
792            scroll_offset.get_y() + snap_scroll_y,
793        );
794        let raw_children: &[NodeId] = node.get_children().as_slice();
795        let needs_z_sort: bool = raw_children.len() > 1
796            && raw_children.iter().copied().any(|cid: NodeId| {
797                tree.get_node(cid)
798                    .map(|c: &SceneNode| c.get_style().get_layout().get_z_index() != 0)
799                    .unwrap_or(false)
800            });
801        if !needs_z_sort {
802            for child_id in raw_children.iter().copied() {
803                Self::emit_node(
804                    tree,
805                    child_id,
806                    (child_scroll, opacity),
807                    next_cull,
808                    active_hover_target,
809                    portals.as_deref_mut(),
810                    display_list,
811                );
812            }
813        } else {
814            let mut sorted_children: Vec<(i32, usize, NodeId)> = raw_children
815                .iter()
816                .copied()
817                .enumerate()
818                .filter_map(|(idx, cid): (usize, NodeId)| {
819                    tree.get_node(cid)
820                        .map(|c: &SceneNode| (c.get_style().get_layout().get_z_index(), idx, cid))
821                })
822                .collect();
823            sorted_children.sort_by(|a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
824                a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
825            });
826            for (_, _, child_id) in sorted_children.into_iter() {
827                Self::emit_node(
828                    tree,
829                    child_id,
830                    (child_scroll, opacity),
831                    next_cull,
832                    active_hover_target,
833                    portals.as_deref_mut(),
834                    display_list,
835                );
836            }
837        }
838        let vp: Size = display_list.get_viewport();
839        let show_scrollbar: bool = vp.get_width().min(vp.get_height()) >= 540.0;
840        if show_scrollbar && layout.get_overflow() == Overflow::Scroll && bounds.get_height() > 24.0
841        {
842            let lbox: LayoutBox = node.get_layout_box();
843            let border_w: f32 = paint.get_border().get_width();
844            let inner_x: f32 = bounds.get_x() + border_w;
845            let inner_y: f32 = bounds.get_y() + border_w;
846            let inner_w: f32 = (bounds.get_width() - border_w * 2.0).max(1.0);
847            let inner_h: f32 = (bounds.get_height() - border_w * 2.0).max(1.0);
848            let view_h: f32 = lbox.get_content_bounds().get_height().max(1.0);
849            let (scroll_y, total_h): (f32, f32) = match node.virtual_scroll_metrics() {
850                Some((vy, vh)) => (vy, vh),
851                None => (
852                    lbox.get_scroll_offset().get_y(),
853                    lbox.get_content_size().get_height(),
854                ),
855            };
856            let max_scroll_y: f32 = (total_h - view_h).max(0.0);
857            if max_scroll_y > 1.0 {
858                let track_margin: f32 = 3.0;
859                let track_w: f32 = if hovered { 6.0 } else { 4.0 };
860                let track_x: f32 = (inner_x + inner_w - track_w - 2.0).max(inner_x);
861                let track_y: f32 = inner_y + track_margin;
862                let track_h: f32 = (inner_h - track_margin * 2.0).max(16.0);
863                let ratio: f32 = (view_h / total_h.max(view_h)).clamp(0.0, 1.0);
864                let min_thumb_h: f32 = 20.0_f32.min(track_h);
865                let thumb_h: f32 = (track_h * ratio).clamp(min_thumb_h, track_h);
866                let scroll_frac: f32 = (scroll_y / max_scroll_y).clamp(0.0, 1.0);
867                let thumb_y: f32 = track_y + (track_h - thumb_h) * scroll_frac;
868                if hovered {
869                    display_list.push(DrawCommand::FillRoundedRect {
870                        rect: Rect::new(track_x, track_y, track_w, track_h),
871                        color: Color::rgba(113, 113, 122, 24).multiply_alpha(opacity),
872                        radius: CornerRadius::all(3.0),
873                        border: Border::default(),
874                    });
875                }
876                let thumb_alpha: u8 = if hovered { 180 } else { 112 };
877                display_list.push(DrawCommand::FillRoundedRect {
878                    rect: Rect::new(track_x, thumb_y, track_w, thumb_h),
879                    color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
880                    radius: CornerRadius::all(track_w * 0.5),
881                    border: Border::default(),
882                });
883            }
884        }
885        if clipped {
886            display_list.push(DrawCommand::PopClip);
887        }
888    }
889}